code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import urllib as U
__all__ = ('sequence', )
def _seq_from_xml(xml):
start = xml.find(">", xml.find("<DNA")) + 1
end = xml.rfind("</DNA>")
return xml[start:end].replace(' ', '').replace('\n', '').strip()
def sequence(db, chrom, start, end):
"""
return the sequence for a region using the UCSC DAS
server. note the start is 1-based
each feature will have it's own .sequence method which sends
the correct start and end to this function.
>>> sequence('hg18', 'chr2', 2223, 2230)
'caacttag'
"""
url = "http://genome.ucsc.edu/cgi-bin/das/%s" % db
url += "/dna?segment=%s:%i,%i"
xml = U.urlopen(url % (chrom, start, end)).read()
return _seq_from_xml(xml)
if __name__ == "__main__":
import doctest
doctest.testmod()
| [
"doctest.testmod",
"urllib.urlopen"
] | [((764, 781), 'doctest.testmod', 'doctest.testmod', ([], {}), '()\n', (779, 781), False, 'import doctest\n'), ((639, 675), 'urllib.urlopen', 'U.urlopen', (['(url % (chrom, start, end))'], {}), '(url % (chrom, start, end))\n', (648, 675), True, 'import urllib as U\n')] |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import os
from tempfile import mkdtemp
from shutil import rmtree
from nipype.testing import (assert_equal, assert_true, assert_false,
assert_raises, skipif, parametric)
import nipype.interfaces.matlab as mlab
from nipype.interfaces.base import CommandLine, Bunch
try:
matlab_cmd = os.environ['MATLABCMD']
except:
matlab_cmd = 'matlab'
res = CommandLine(command='which', args=matlab_cmd).run()
matlab_path = res.runtime.stdout.strip()
no_matlab = True
if matlab_path != '':
no_matlab = False
mlab.MatlabCommand.set_default_matlab_cmd(matlab_cmd)
# If a test requires matlab, prefix it with the skipif decorator like
# below. Must import skipif from nipype.testing
#
#@skipif(no_matlab)
#def test_func():
# pass
@parametric
@skipif(no_matlab)
def test_cmdline():
basedir = mkdtemp()
mi = mlab.MatlabCommand(script='whos',
script_file='testscript')
yield assert_equal(mi.cmdline, \
matlab_cmd + ' -nodesktop -nosplash -singleCompThread -r "fprintf(1,\'Executing code at %s:\\n\',datestr(now));ver,try,whos,catch ME,ME,ME.stack,fprintf(\'%s\\n\',ME.message);fprintf(2,\'<MatlabScriptException>\');fprintf(2,\'%s\\n\',ME.message);fprintf(2,\'File:%s\\nName:%s\\nLine:%d\\n\',ME.stack.file,ME.stack.name,ME.stack.line);fprintf(2,\'</MatlabScriptException>\');end;;exit"')
yield assert_equal(mi.inputs.script, 'whos')
yield assert_equal(mi.inputs.script_file, 'testscript')
path_exists = os.path.exists(os.path.join(basedir,'testscript.m'))
yield assert_false(path_exists)
rmtree(basedir)
@parametric
@skipif(no_matlab)
def test_mlab_inputspec():
spec = mlab.MatlabInputSpec()
for k in ['paths', 'script', 'nosplash', 'mfile', 'logfile', 'script_file',
'nodesktop']:
yield assert_true(k in spec.copyable_trait_names())
yield assert_true(spec.nodesktop)
yield assert_true(spec.nosplash)
yield assert_false(spec.mfile)
yield assert_equal(spec.script_file, 'pyscript.m')
@parametric
@skipif(no_matlab)
def test_mlab_init():
yield assert_equal(mlab.MatlabCommand._cmd, 'matlab')
yield assert_equal(mlab.MatlabCommand.input_spec, mlab.MatlabInputSpec)
yield assert_equal(mlab.MatlabCommand().cmd, matlab_cmd)
mc = mlab.MatlabCommand(matlab_cmd='foo_m')
yield assert_equal(mc.cmd, 'foo_m')
@parametric
@skipif(no_matlab)
def test_run_interface():
mc = mlab.MatlabCommand(matlab_cmd='foo_m')
yield assert_raises(ValueError, mc.run) # script is mandatory
mc.inputs.script = 'a=1;'
yield assert_raises(IOError, mc.run) # foo_m is not an executable
cwd = os.getcwd()
basedir = mkdtemp()
os.chdir(basedir)
res = mlab.MatlabCommand(script='foo', paths=[basedir], mfile=True).run() # bypasses ubuntu dash issue
yield assert_equal(res.runtime.returncode, 1)
res = mlab.MatlabCommand(script='a=1;', paths=[basedir], mfile=True).run() # bypasses ubuntu dash issue
yield assert_equal(res.runtime.returncode, 0)
os.chdir(cwd)
rmtree(basedir)
@parametric
@skipif(no_matlab)
def test_set_matlabcmd():
mi = mlab.MatlabCommand()
mi.set_default_matlab_cmd('foo')
yield assert_equal(mi._default_matlab_cmd, 'foo')
mi.set_default_matlab_cmd(matlab_cmd)
| [
"nipype.testing.assert_true",
"nipype.interfaces.matlab.MatlabCommand",
"nipype.interfaces.base.CommandLine",
"nipype.testing.assert_equal",
"nipype.testing.assert_false",
"os.path.join",
"os.getcwd",
"os.chdir",
"nipype.testing.assert_raises",
"tempfile.mkdtemp",
"shutil.rmtree",
"nipype.inte... | [((896, 913), 'nipype.testing.skipif', 'skipif', (['no_matlab'], {}), '(no_matlab)\n', (902, 913), False, 'from nipype.testing import assert_equal, assert_true, assert_false, assert_raises, skipif, parametric\n'), ((1772, 1789), 'nipype.testing.skipif', 'skipif', (['no_matlab'], {}), '(no_matlab)\n', (1778, 1789), False, 'from nipype.testing import assert_equal, assert_true, assert_false, assert_raises, skipif, parametric\n'), ((2198, 2215), 'nipype.testing.skipif', 'skipif', (['no_matlab'], {}), '(no_matlab)\n', (2204, 2215), False, 'from nipype.testing import assert_equal, assert_true, assert_false, assert_raises, skipif, parametric\n'), ((2536, 2553), 'nipype.testing.skipif', 'skipif', (['no_matlab'], {}), '(no_matlab)\n', (2542, 2553), False, 'from nipype.testing import assert_equal, assert_true, assert_false, assert_raises, skipif, parametric\n'), ((3233, 3250), 'nipype.testing.skipif', 'skipif', (['no_matlab'], {}), '(no_matlab)\n', (3239, 3250), False, 'from nipype.testing import assert_equal, assert_true, assert_false, assert_raises, skipif, parametric\n'), ((654, 707), 'nipype.interfaces.matlab.MatlabCommand.set_default_matlab_cmd', 'mlab.MatlabCommand.set_default_matlab_cmd', (['matlab_cmd'], {}), '(matlab_cmd)\n', (695, 707), True, 'import nipype.interfaces.matlab as mlab\n'), ((948, 957), 'tempfile.mkdtemp', 'mkdtemp', ([], {}), '()\n', (955, 957), False, 'from tempfile import mkdtemp\n'), ((967, 1026), 'nipype.interfaces.matlab.MatlabCommand', 'mlab.MatlabCommand', ([], {'script': '"""whos"""', 'script_file': '"""testscript"""'}), "(script='whos', script_file='testscript')\n", (985, 1026), True, 'import nipype.interfaces.matlab as mlab\n'), ((1742, 1757), 'shutil.rmtree', 'rmtree', (['basedir'], {}), '(basedir)\n', (1748, 1757), False, 'from shutil import rmtree\n'), ((1828, 1850), 'nipype.interfaces.matlab.MatlabInputSpec', 'mlab.MatlabInputSpec', ([], {}), '()\n', (1848, 1850), True, 'import nipype.interfaces.matlab as mlab\n'), ((2443, 2481), 'nipype.interfaces.matlab.MatlabCommand', 'mlab.MatlabCommand', ([], {'matlab_cmd': '"""foo_m"""'}), "(matlab_cmd='foo_m')\n", (2461, 2481), True, 'import nipype.interfaces.matlab as mlab\n'), ((2589, 2627), 'nipype.interfaces.matlab.MatlabCommand', 'mlab.MatlabCommand', ([], {'matlab_cmd': '"""foo_m"""'}), "(matlab_cmd='foo_m')\n", (2607, 2627), True, 'import nipype.interfaces.matlab as mlab\n'), ((2804, 2815), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2813, 2815), False, 'import os\n'), ((2830, 2839), 'tempfile.mkdtemp', 'mkdtemp', ([], {}), '()\n', (2837, 2839), False, 'from tempfile import mkdtemp\n'), ((2844, 2861), 'os.chdir', 'os.chdir', (['basedir'], {}), '(basedir)\n', (2852, 2861), False, 'import os\n'), ((3181, 3194), 'os.chdir', 'os.chdir', (['cwd'], {}), '(cwd)\n', (3189, 3194), False, 'import os\n'), ((3199, 3214), 'shutil.rmtree', 'rmtree', (['basedir'], {}), '(basedir)\n', (3205, 3214), False, 'from shutil import rmtree\n'), ((3286, 3306), 'nipype.interfaces.matlab.MatlabCommand', 'mlab.MatlabCommand', ([], {}), '()\n', (3304, 3306), True, 'import nipype.interfaces.matlab as mlab\n'), ((495, 540), 'nipype.interfaces.base.CommandLine', 'CommandLine', ([], {'command': '"""which"""', 'args': 'matlab_cmd'}), "(command='which', args=matlab_cmd)\n", (506, 540), False, 'from nipype.interfaces.base import CommandLine, Bunch\n'), ((1098, 1518), 'nipype.testing.assert_equal', 'assert_equal', (['mi.cmdline', '(matlab_cmd +\n \' -nodesktop -nosplash -singleCompThread -r "fprintf(1,\\\'Executing code at %s:\\\\n\\\',datestr(now));ver,try,whos,catch ME,ME,ME.stack,fprintf(\\\'%s\\\\n\\\',ME.message);fprintf(2,\\\'<MatlabScriptException>\\\');fprintf(2,\\\'%s\\\\n\\\',ME.message);fprintf(2,\\\'File:%s\\\\nName:%s\\\\nLine:%d\\\\n\\\',ME.stack.file,ME.stack.name,ME.stack.line);fprintf(2,\\\'</MatlabScriptException>\\\');end;;exit"\'\n )'], {}), '(mi.cmdline, matlab_cmd +\n \' -nodesktop -nosplash -singleCompThread -r "fprintf(1,\\\'Executing code at %s:\\\\n\\\',datestr(now));ver,try,whos,catch ME,ME,ME.stack,fprintf(\\\'%s\\\\n\\\',ME.message);fprintf(2,\\\'<MatlabScriptException>\\\');fprintf(2,\\\'%s\\\\n\\\',ME.message);fprintf(2,\\\'File:%s\\\\nName:%s\\\\nLine:%d\\\\n\\\',ME.stack.file,ME.stack.name,ME.stack.line);fprintf(2,\\\'</MatlabScriptException>\\\');end;;exit"\'\n )\n', (1110, 1518), False, 'from nipype.testing import assert_equal, assert_true, assert_false, assert_raises, skipif, parametric\n'), ((1532, 1570), 'nipype.testing.assert_equal', 'assert_equal', (['mi.inputs.script', '"""whos"""'], {}), "(mi.inputs.script, 'whos')\n", (1544, 1570), False, 'from nipype.testing import assert_equal, assert_true, assert_false, assert_raises, skipif, parametric\n'), ((1581, 1630), 'nipype.testing.assert_equal', 'assert_equal', (['mi.inputs.script_file', '"""testscript"""'], {}), "(mi.inputs.script_file, 'testscript')\n", (1593, 1630), False, 'from nipype.testing import assert_equal, assert_true, assert_false, assert_raises, skipif, parametric\n'), ((1664, 1701), 'os.path.join', 'os.path.join', (['basedir', '"""testscript.m"""'], {}), "(basedir, 'testscript.m')\n", (1676, 1701), False, 'import os\n'), ((1712, 1737), 'nipype.testing.assert_false', 'assert_false', (['path_exists'], {}), '(path_exists)\n', (1724, 1737), False, 'from nipype.testing import assert_equal, assert_true, assert_false, assert_raises, skipif, parametric\n'), ((2029, 2056), 'nipype.testing.assert_true', 'assert_true', (['spec.nodesktop'], {}), '(spec.nodesktop)\n', (2040, 2056), False, 'from nipype.testing import assert_equal, assert_true, assert_false, assert_raises, skipif, parametric\n'), ((2067, 2093), 'nipype.testing.assert_true', 'assert_true', (['spec.nosplash'], {}), '(spec.nosplash)\n', (2078, 2093), False, 'from nipype.testing import assert_equal, assert_true, assert_false, assert_raises, skipif, parametric\n'), ((2104, 2128), 'nipype.testing.assert_false', 'assert_false', (['spec.mfile'], {}), '(spec.mfile)\n', (2116, 2128), False, 'from nipype.testing import assert_equal, assert_true, assert_false, assert_raises, skipif, parametric\n'), ((2139, 2183), 'nipype.testing.assert_equal', 'assert_equal', (['spec.script_file', '"""pyscript.m"""'], {}), "(spec.script_file, 'pyscript.m')\n", (2151, 2183), False, 'from nipype.testing import assert_equal, assert_true, assert_false, assert_raises, skipif, parametric\n'), ((2248, 2295), 'nipype.testing.assert_equal', 'assert_equal', (['mlab.MatlabCommand._cmd', '"""matlab"""'], {}), "(mlab.MatlabCommand._cmd, 'matlab')\n", (2260, 2295), False, 'from nipype.testing import assert_equal, assert_true, assert_false, assert_raises, skipif, parametric\n'), ((2306, 2371), 'nipype.testing.assert_equal', 'assert_equal', (['mlab.MatlabCommand.input_spec', 'mlab.MatlabInputSpec'], {}), '(mlab.MatlabCommand.input_spec, mlab.MatlabInputSpec)\n', (2318, 2371), False, 'from nipype.testing import assert_equal, assert_true, assert_false, assert_raises, skipif, parametric\n'), ((2492, 2521), 'nipype.testing.assert_equal', 'assert_equal', (['mc.cmd', '"""foo_m"""'], {}), "(mc.cmd, 'foo_m')\n", (2504, 2521), False, 'from nipype.testing import assert_equal, assert_true, assert_false, assert_raises, skipif, parametric\n'), ((2638, 2671), 'nipype.testing.assert_raises', 'assert_raises', (['ValueError', 'mc.run'], {}), '(ValueError, mc.run)\n', (2651, 2671), False, 'from nipype.testing import assert_equal, assert_true, assert_false, assert_raises, skipif, parametric\n'), ((2734, 2764), 'nipype.testing.assert_raises', 'assert_raises', (['IOError', 'mc.run'], {}), '(IOError, mc.run)\n', (2747, 2764), False, 'from nipype.testing import assert_equal, assert_true, assert_false, assert_raises, skipif, parametric\n'), ((2979, 3018), 'nipype.testing.assert_equal', 'assert_equal', (['res.runtime.returncode', '(1)'], {}), '(res.runtime.returncode, 1)\n', (2991, 3018), False, 'from nipype.testing import assert_equal, assert_true, assert_false, assert_raises, skipif, parametric\n'), ((3137, 3176), 'nipype.testing.assert_equal', 'assert_equal', (['res.runtime.returncode', '(0)'], {}), '(res.runtime.returncode, 0)\n', (3149, 3176), False, 'from nipype.testing import assert_equal, assert_true, assert_false, assert_raises, skipif, parametric\n'), ((3354, 3397), 'nipype.testing.assert_equal', 'assert_equal', (['mi._default_matlab_cmd', '"""foo"""'], {}), "(mi._default_matlab_cmd, 'foo')\n", (3366, 3397), False, 'from nipype.testing import assert_equal, assert_true, assert_false, assert_raises, skipif, parametric\n'), ((2872, 2933), 'nipype.interfaces.matlab.MatlabCommand', 'mlab.MatlabCommand', ([], {'script': '"""foo"""', 'paths': '[basedir]', 'mfile': '(True)'}), "(script='foo', paths=[basedir], mfile=True)\n", (2890, 2933), True, 'import nipype.interfaces.matlab as mlab\n'), ((3029, 3091), 'nipype.interfaces.matlab.MatlabCommand', 'mlab.MatlabCommand', ([], {'script': '"""a=1;"""', 'paths': '[basedir]', 'mfile': '(True)'}), "(script='a=1;', paths=[basedir], mfile=True)\n", (3047, 3091), True, 'import nipype.interfaces.matlab as mlab\n'), ((2396, 2416), 'nipype.interfaces.matlab.MatlabCommand', 'mlab.MatlabCommand', ([], {}), '()\n', (2414, 2416), True, 'import nipype.interfaces.matlab as mlab\n')] |
"""A filter block.
"""
import control
import numpy as np
import scipy
from .base import Block
class Filter(Block):
"""A Filter block class
This is simply a single-input-single-output LTI system defined by a
single TransferFunction object.
Parameters
----------
tf : control.TransferFunction
The transfer function of the filter (continuous).
fs : float
Sampling frequency in Hz.
method : str, optional
Method used to convert the continuous system to
discrete system.
Argument is passed to ``scipy.signal.cont2discrete``.
Defaults to "bilinear".
label : str, optional
Label for this filter.
Defaults to None.
Note
----
When ``inputs.setter`` the current input and output is saved into a register
for next cycle.
This means that calling ``inputs.setter`` indicates the end of a cycle.
"""
def __init__(self, tf, fs, method="bilinear", label=None):
"""Constructor
Parameters
----------
tf : control.TransferFunction
The transfer function of the filter (continuous).
fs : float
Sampling frequency in Hz.
method : str, optional
Method used to convert the continuous system to
discrete system.
Argument is passed to ``scipy.signal.cont2discrete``.
Defaults to "bilinear".
label : str, optional
Label for this filter.
Defaults to None.
"""
self._tf = None
self._fs = None
self._method = None
self._num_d = None
self._den_d = None
self._input_register = None
self._output_register = None
self.tf = tf
self.fs = fs
self.method = method
super().__init__(label=label)
def _i2o(self):
"""Pass input through filter and return the output"""
input_register = self.input_register
output_register = self.output_register
num_d = self.num_d
den_d = self.den_d
out = (np.dot(num_d, input_register)
- np.dot(den_d[1:], output_register[1:]))
return out
@property
def inputs(self):
"""Input of the block."""
return self._inputs
@inputs.setter
def inputs(self, _inputs):
"""input.setter"""
self._latch_output_register()
self._inputs = _inputs
self._latch_input_register()
@property
def tf(self):
"""The transfer function of the filter (continuous)."""
return self._tf
@tf.setter
def tf(self, _tf):
"""tf.setter"""
if not isinstance(_tf, control.TransferFunction):
raise TypeError("tf must be a TransferFunction object.")
if len(_tf.zero()) > len(_tf.pole()):
raise ValueError("tf must be a proper transfer function.")
if np.any(_tf.pole().real >= 0):
raise ValueError("tf must be a stable transfer function.")
self._tf = _tf
self._set_coefs()
self._reset_register()
@property
def fs(self):
"""Sampling frequency in Hz"""
return self._fs
@fs.setter
def fs(self, _fs):
"""fs.setter"""
self._fs = _fs
self._set_coefs()
self._reset_register()
@property
def method(self):
"""Method used to convert the continuous system discrete system."""
return self._method
@method.setter
def method(self, _method):
"""method.setter"""
self._method = _method
self._set_coefs()
self._reset_register()
@property
def num_d(self):
"""Discrete transfer function numerators"""
return self._num_d
@num_d.setter
def num_d(self, _num_d):
"""num_d.setter"""
self._num_d = _num_d
@property
def den_d(self):
"""Discrete transfer function denominator"""
return self._den_d
@den_d.setter
def den_d(self, _den_d):
"""den_d.setter"""
self._den_d = _den_d
@property
def input_register(self):
"""Input register (history of the input)"""
return self._input_register
@input_register.setter
def input_register(self, _input_register):
"""input_register.setter"""
self._input_register = _input_register
@property
def output_register(self):
"""output register (history of the output)"""
return self._output_register
@output_register.setter
def output_register(self, _output_register):
"""input_register.setter"""
self._output_register = _output_register
def _set_coefs(self):
"""Set discrete filter coefficients."""
if (self.tf is not None
and self.fs is not None
and self.method is not None):
# Set coefficients for discrete filters.
# Note: H(z) = (b0 + b1*z^1...)/(1 + a1*z^1...)
# print("set coefs")
num = self.tf.num[0][0]
den = self.tf.den[0][0]
dt = 1/self.fs
method = self.method
num_d, den_d, _ = scipy.signal.cont2discrete(
(num, den), dt=dt, method=method)
num_d = num_d.reshape(-1)
den_d = den_d.reshape(-1)
self.num_d = num_d
self.den_d = den_d
def _reset_register(self):
"""Reset the input/output register"""
if self.num_d is not None and self.den_d is not None:
self.input_register = np.zeros_like(self.num_d)
self.output_register = np.zeros_like(self.den_d)
def _latch_input_register(self):
"""Shift and then put input value into input register
"""
if self.input_register is not None:
self.input_register[1:] = self.input_register[:-1]
self.input_register[0] = self.inputs
def _latch_output_register(self):
"""Shift and then put input value into input register
"""
if self.output_register is not None:
self.output_register[0] = self.output
self.output_register[1:] = self.output_register[:-1]
| [
"numpy.dot",
"numpy.zeros_like",
"scipy.signal.cont2discrete"
] | [((2083, 2112), 'numpy.dot', 'np.dot', (['num_d', 'input_register'], {}), '(num_d, input_register)\n', (2089, 2112), True, 'import numpy as np\n'), ((2130, 2168), 'numpy.dot', 'np.dot', (['den_d[1:]', 'output_register[1:]'], {}), '(den_d[1:], output_register[1:])\n', (2136, 2168), True, 'import numpy as np\n'), ((5163, 5223), 'scipy.signal.cont2discrete', 'scipy.signal.cont2discrete', (['(num, den)'], {'dt': 'dt', 'method': 'method'}), '((num, den), dt=dt, method=method)\n', (5189, 5223), False, 'import scipy\n'), ((5553, 5578), 'numpy.zeros_like', 'np.zeros_like', (['self.num_d'], {}), '(self.num_d)\n', (5566, 5578), True, 'import numpy as np\n'), ((5614, 5639), 'numpy.zeros_like', 'np.zeros_like', (['self.den_d'], {}), '(self.den_d)\n', (5627, 5639), True, 'import numpy as np\n')] |
import pandas as pd
import numpy as np
import xml.etree.ElementTree as ElementTree
from traffic_analysis.d00_utils.bbox_helpers import bboxcv2_to_bboxcvlib
from traffic_analysis.d05_evaluation.parse_annotation import parse_annotation
from traffic_analysis.d05_evaluation.compute_mean_average_precision import get_avg_precision_at_iou
class FrameLevelEvaluator:
"""
Conduct frame level evaluation for one video.
"""
def __init__(self,
videos_to_eval: pd.DataFrame,
frame_level_df: pd.DataFrame,
selected_labels: list
):
# data frames to work with
self.videos_to_eval = videos_to_eval
self.frame_level_df = frame_level_df
self.frame_level_ground_truth = pd.DataFrame({})
self.frame_level_preds = pd.DataFrame({})
# parameters
self.selected_labels = selected_labels
def evaluate(self) -> pd.DataFrame:
"""Compute mean average precision for each vehicle type on multiple videos
"""
self.frame_level_ground_truth = self.get_ground_truth()
self.frame_level_preds = self.filter_frame_level_df()
frame_level_map_dfs = []
for (gt_camera_id, gt_video_upload_datetime), ground_truth_df in \
self.frame_level_ground_truth.groupby(["camera_id", "video_upload_datetime"]):
# get corresponding predictions for this video
pred_df = self.frame_level_preds[(self.frame_level_preds["camera_id"] == gt_camera_id) &
(self.frame_level_preds["video_upload_datetime"] ==
gt_video_upload_datetime)].copy()
ground_truth_dict = self.reparse_bboxes_df(ground_truth_df,
include_confidence=False)
predicted_dict = self.reparse_bboxes_df(pred_df,
include_confidence=True,
bbox_format="cv2")
map_dict = self.compute_map_video(ground_truth_dict, predicted_dict)
map_df = pd.DataFrame.from_dict(map_dict,
orient="index",
columns=["mean_avg_precision"])
map_df["camera_id"] = gt_camera_id
map_df["video_upload_datetime"] = gt_video_upload_datetime
frame_level_map_dfs.append(map_df)
frame_level_map_df = pd.concat(frame_level_map_dfs,
axis=0)
frame_level_map_df.index.name = "vehicle_type"
frame_level_map_df.reset_index(inplace=True)
return frame_level_map_df
def filter_frame_level_df(self) -> pd.DataFrame:
"""
Get preds for videos which are in videos_to_eval
"""
frame_level_df_filt = pd.merge(left=self.videos_to_eval[['camera_id', 'video_upload_datetime']],
right=self.frame_level_df,
on=['camera_id', 'video_upload_datetime'],
how='inner')
zeros_mask = frame_level_df_filt.bboxes.apply(
lambda x: all(True if bbox_entry == 0.0 else False for bbox_entry in x))
frame_level_df_filt = (frame_level_df_filt[~zeros_mask]
.sort_values(by=["camera_id", "video_upload_datetime"])
.reset_index(drop=True))
return frame_level_df_filt
def get_ground_truth(self) -> pd.DataFrame:
"""Read in annotation xmls from paths stored in self.videos_to_eval
"""
frame_level_ground_truth_dfs = []
for idx, video in self.videos_to_eval.iterrows():
# get frame level ground truth
xml_root = ElementTree.parse(video["xml_path"]).getroot()
frame_level_ground_truth = parse_annotation(xml_root)
frame_level_ground_truth["camera_id"] = video["camera_id"]
frame_level_ground_truth["video_upload_datetime"] = video["video_upload_datetime"]
frame_level_ground_truth_dfs.append(frame_level_ground_truth)
frame_level_ground_truth = pd.concat(frame_level_ground_truth_dfs,
axis=0)
return frame_level_ground_truth
def reparse_bboxes_df(self,
df: pd.DataFrame,
include_confidence: bool,
bbox_format: str = "cvlib") -> dict:
"""Restructures dfs containing bboxes for each frame (i.e. frame level df,
ground truth df) to a dictionary of dictionaries. This format is what
compute_mean_average_precision.py functions take as input.
Args:
df: frame_level_df which contains bboxes corresponding to each frame of
a video.
include_confidence: If this df contains the confidence corresponding to
the bbox predictions, this should be specified (the
reparser will construct a sub-dict for this case)
bbox_format: cvlib is cvlib (xmin,ymin, xmin+width, ymin+height),
cv2 is (xmin,ymin,width,height)
Returns:
df as a nested dictionary
"""
# dict of dict of dicts, with outermost layer being the vehicle type
n_frames = df["frame_id"].nunique()
bboxes_np = np.array(df["bboxes"].values.tolist())
assert bboxes_np.shape[1] == 4
if bbox_format == "cv2":
# convert to format cvlib
bboxes_cvlib = pd.Series(bboxcv2_to_bboxcvlib(bboxes_np, vectorized=True).tolist()).values
df.loc[:, "bboxes"] = bboxes_cvlib
# initialize dictionaries to correct shape
if include_confidence:
df_as_dict = {
vehicle_type: {
"frame" + str(i): {"bboxes": [], "scores": []}
for i in range(n_frames)
}
for vehicle_type in self.selected_labels
}
else:
df_as_dict = {
vehicle_type: {"frame" + str(i): [] for i in range(n_frames)}
for vehicle_type in self.selected_labels
}
for (vehicle_type, frame_id), vehicle_frame_df in df.groupby(
["vehicle_type", "frame_id"]):
if vehicle_type not in self.selected_labels:
continue
frame_id = int(frame_id)
if include_confidence:
df_as_dict[vehicle_type]["frame" + str(frame_id)]["bboxes"] = \
vehicle_frame_df["bboxes"].tolist()
df_as_dict[vehicle_type]["frame" + str(frame_id)]["scores"] = \
vehicle_frame_df["confidence"].tolist()
else:
df_as_dict[vehicle_type]["frame" + str(frame_id)] = \
vehicle_frame_df["bboxes"].tolist()
return df_as_dict
def compute_map_video(self, ground_truth_dict, predicted_dict) -> dict:
""" Function computes the mean average precision for each vehicle type for a video
Args:
ground_truth_dict: ground_truth_df reparsed by reparse_bboxes_df
predicted_dict: frame_level_df reparsed by reparse_bboxes_df
Returns:
map_dict: dictionary with vehicle_types as keys and maps as values
"""
map_dict = {vehicle_type: -1.0 for vehicle_type in self.selected_labels}
for vehicle_type in self.selected_labels:
vehicle_gt_dict = ground_truth_dict[vehicle_type]
vehicle_pred_dict = predicted_dict[vehicle_type]
avg_precs = []
iou_thrs = []
# compute avg precision for 10 IOU thresholds from .5 to .95 (COCO challenge standard)
for idx, iou_thr in enumerate(np.linspace(0.5, 0.95, 10)):
data_dict = get_avg_precision_at_iou(
gt_bboxes=vehicle_gt_dict,
pred_bboxes=vehicle_pred_dict,
iou_thr=iou_thr,
)
avg_precs.append(data_dict["avg_prec"])
iou_thrs.append(iou_thr)
# avg the avg precision for each IOU value
mean_avg_precision = 100 * np.mean(avg_precs)
map_dict[vehicle_type] = mean_avg_precision
return map_dict
| [
"traffic_analysis.d00_utils.bbox_helpers.bboxcv2_to_bboxcvlib",
"numpy.mean",
"traffic_analysis.d05_evaluation.parse_annotation.parse_annotation",
"xml.etree.ElementTree.parse",
"pandas.merge",
"pandas.DataFrame.from_dict",
"traffic_analysis.d05_evaluation.compute_mean_average_precision.get_avg_precisio... | [((781, 797), 'pandas.DataFrame', 'pd.DataFrame', (['{}'], {}), '({})\n', (793, 797), True, 'import pandas as pd\n'), ((831, 847), 'pandas.DataFrame', 'pd.DataFrame', (['{}'], {}), '({})\n', (843, 847), True, 'import pandas as pd\n'), ((2556, 2594), 'pandas.concat', 'pd.concat', (['frame_level_map_dfs'], {'axis': '(0)'}), '(frame_level_map_dfs, axis=0)\n', (2565, 2594), True, 'import pandas as pd\n'), ((2945, 3110), 'pandas.merge', 'pd.merge', ([], {'left': "self.videos_to_eval[['camera_id', 'video_upload_datetime']]", 'right': 'self.frame_level_df', 'on': "['camera_id', 'video_upload_datetime']", 'how': '"""inner"""'}), "(left=self.videos_to_eval[['camera_id', 'video_upload_datetime']],\n right=self.frame_level_df, on=['camera_id', 'video_upload_datetime'],\n how='inner')\n", (2953, 3110), True, 'import pandas as pd\n'), ((4297, 4344), 'pandas.concat', 'pd.concat', (['frame_level_ground_truth_dfs'], {'axis': '(0)'}), '(frame_level_ground_truth_dfs, axis=0)\n', (4306, 4344), True, 'import pandas as pd\n'), ((2188, 2273), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['map_dict'], {'orient': '"""index"""', 'columns': "['mean_avg_precision']"}), "(map_dict, orient='index', columns=['mean_avg_precision']\n )\n", (2210, 2273), True, 'import pandas as pd\n'), ((3993, 4019), 'traffic_analysis.d05_evaluation.parse_annotation.parse_annotation', 'parse_annotation', (['xml_root'], {}), '(xml_root)\n', (4009, 4019), False, 'from traffic_analysis.d05_evaluation.parse_annotation import parse_annotation\n'), ((8039, 8065), 'numpy.linspace', 'np.linspace', (['(0.5)', '(0.95)', '(10)'], {}), '(0.5, 0.95, 10)\n', (8050, 8065), True, 'import numpy as np\n'), ((8096, 8200), 'traffic_analysis.d05_evaluation.compute_mean_average_precision.get_avg_precision_at_iou', 'get_avg_precision_at_iou', ([], {'gt_bboxes': 'vehicle_gt_dict', 'pred_bboxes': 'vehicle_pred_dict', 'iou_thr': 'iou_thr'}), '(gt_bboxes=vehicle_gt_dict, pred_bboxes=\n vehicle_pred_dict, iou_thr=iou_thr)\n', (8120, 8200), False, 'from traffic_analysis.d05_evaluation.compute_mean_average_precision import get_avg_precision_at_iou\n'), ((8467, 8485), 'numpy.mean', 'np.mean', (['avg_precs'], {}), '(avg_precs)\n', (8474, 8485), True, 'import numpy as np\n'), ((3907, 3943), 'xml.etree.ElementTree.parse', 'ElementTree.parse', (["video['xml_path']"], {}), "(video['xml_path'])\n", (3924, 3943), True, 'import xml.etree.ElementTree as ElementTree\n'), ((5769, 5817), 'traffic_analysis.d00_utils.bbox_helpers.bboxcv2_to_bboxcvlib', 'bboxcv2_to_bboxcvlib', (['bboxes_np'], {'vectorized': '(True)'}), '(bboxes_np, vectorized=True)\n', (5789, 5817), False, 'from traffic_analysis.d00_utils.bbox_helpers import bboxcv2_to_bboxcvlib\n')] |
from load_to_s3 import export_to_s3_as_dataframe, export_to_s3_as_csv
from transform_form_specifications import get_custom_form_schema_df
from transform_form_results import get_form_results_df
from utils.clients import Clients
from utils.constants import PuenteTables
def run_transform_jobs(event, context):
"""
Orchestrate transformations
"""
# Initialize AWS S3 Client
s3_client = Clients.S3
# if event.get(PuenteTables.ALLERGIES):
if event.get(PuenteTables.FORM_RESULTS):
# raw_results == True does not aggregate the results, pass False to ensure aggregation
df = get_form_results_df(raw_results=True)
for org in df['form_result_surveying_organization'].unique():
org_df = df[df['form_result_surveying_organization']==org]
for custom_form in org_df['custom_form_id'].unique():
final_df = org_df[org_df['custom_form_id'] == custom_form]
export_to_s3_as_csv(s3_client, final_df, f"form-result-{custom_form}", org)
if event.get(PuenteTables.FORM_SPECIFICATIONS):
df = get_custom_form_schema_df()
export_to_s3_as_dataframe(s3_client, df, PuenteTables.FORM_SPECIFICATIONS)
# TODO: PUENTE FORMS
# if event.get(PuenteTables.FORM_ASSET_RESULTS):
# if event.get(PuenteTables.ASSETS):
# if event.get(PuenteTables.HISTORY_ENVIRONMENTAL_HEALTH):
# if event.get(PuenteTables.HISTORY_MEDICAL):
# if event.get(PuenteTables.SURVEY_DATA):
# if event.get(PuenteTables.VITALS):
# if event.get(PuenteTables.EVALUATION_MEDICAL):
# if event.get(PuenteTables.OFFLINE_FORM):
# if event.get(PuenteTables.OFFLINE_FORM_REQUEST):
# if event.get(PuenteTables.HOUSEHOLD):
# if event.get(PuenteTables.ROLE):
# if event.get(PuenteTables.SESSION):
# if event.get(PuenteTables.USER):
if __name__ == '__main__':
jobs = {
PuenteTables.ALLERGIES: False,
PuenteTables.ASSETS: False,
PuenteTables.EVALUATION_MEDICAL: False,
PuenteTables.FORM_ASSET_RESULTS: False,
PuenteTables.FORM_RESULTS: True,
PuenteTables.FORM_SPECIFICATIONS: False,
PuenteTables.HISTORY_ENVIRONMENTAL_HEALTH: False,
PuenteTables.HISTORY_MEDICAL: False,
#PuenteTables.OFFLINE_FORM: False,
#PuenteTables.OFFLINE_FORM_REQUEST: False,
PuenteTables.HOUSEHOLD: False,
PuenteTables.ROLE: False,
PuenteTables.SESSION: False,
PuenteTables.SURVEY_DATA: False,
PuenteTables.USER: False,
PuenteTables.VITALS: False
}
run_transform_jobs(jobs, {})
| [
"load_to_s3.export_to_s3_as_csv",
"transform_form_specifications.get_custom_form_schema_df",
"load_to_s3.export_to_s3_as_dataframe",
"transform_form_results.get_form_results_df"
] | [((615, 652), 'transform_form_results.get_form_results_df', 'get_form_results_df', ([], {'raw_results': '(True)'}), '(raw_results=True)\n', (634, 652), False, 'from transform_form_results import get_form_results_df\n'), ((1093, 1120), 'transform_form_specifications.get_custom_form_schema_df', 'get_custom_form_schema_df', ([], {}), '()\n', (1118, 1120), False, 'from transform_form_specifications import get_custom_form_schema_df\n'), ((1129, 1203), 'load_to_s3.export_to_s3_as_dataframe', 'export_to_s3_as_dataframe', (['s3_client', 'df', 'PuenteTables.FORM_SPECIFICATIONS'], {}), '(s3_client, df, PuenteTables.FORM_SPECIFICATIONS)\n', (1154, 1203), False, 'from load_to_s3 import export_to_s3_as_dataframe, export_to_s3_as_csv\n'), ((951, 1026), 'load_to_s3.export_to_s3_as_csv', 'export_to_s3_as_csv', (['s3_client', 'final_df', 'f"""form-result-{custom_form}"""', 'org'], {}), "(s3_client, final_df, f'form-result-{custom_form}', org)\n", (970, 1026), False, 'from load_to_s3 import export_to_s3_as_dataframe, export_to_s3_as_csv\n')] |
# Generated by Django 2.1.2 on 2019-06-21 15:16
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='ContactQuery',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=256)),
('email', models.EmailField(max_length=254)),
('phone_number', models.CharField(max_length=20)),
('message', models.TextField()),
],
),
]
| [
"django.db.models.EmailField",
"django.db.models.TextField",
"django.db.models.AutoField",
"django.db.models.CharField"
] | [((308, 401), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (324, 401), False, 'from django.db import migrations, models\n'), ((425, 457), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(256)'}), '(max_length=256)\n', (441, 457), False, 'from django.db import migrations, models\n'), ((486, 519), 'django.db.models.EmailField', 'models.EmailField', ([], {'max_length': '(254)'}), '(max_length=254)\n', (503, 519), False, 'from django.db import migrations, models\n'), ((555, 586), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(20)'}), '(max_length=20)\n', (571, 586), False, 'from django.db import migrations, models\n'), ((617, 635), 'django.db.models.TextField', 'models.TextField', ([], {}), '()\n', (633, 635), False, 'from django.db import migrations, models\n')] |
"""
Script to post grades back to EdX
"""
import requests
import json
import os
import time
from oauthlib.oauth1.rfc5849 import signature, parameters
from lxml import etree
from hashlib import sha1
import argparse
import base64
class GradePostException(Exception):
def __init__(self, response=None):
self.response = response
def post_grade(sourcedid, outcomes_url, consumer_key, consumer_secret, grade):
# Who is treating XML as Text? I am!
# WHY WOULD YOU MIX MULTIPART, XML (NOT EVEN JUST XML, BUT WSDL GENERATED POX WTF), AND PARTS OF OAUTH1 SIGNING
# IN THE SAME STANDARD AAAA!
# TODO: extract this into a real library with real XML parsing
# WARNING: You can use this only with data you trust! Beware, etc.
post_xml = r"""
<?xml version = "1.0" encoding = "UTF-8"?>
<imsx_POXEnvelopeRequest xmlns = "http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0">
<imsx_POXHeader>
<imsx_POXRequestHeaderInfo>
<imsx_version>V1.0</imsx_version>
<imsx_messageIdentifier>999999123</imsx_messageIdentifier>
</imsx_POXRequestHeaderInfo>
</imsx_POXHeader>
<imsx_POXBody>
<replaceResultRequest>
<resultRecord>
<sourcedGUID>
<sourcedId>{sourcedid}</sourcedId>
</sourcedGUID>
<result>
<resultScore>
<language>en</language>
<textString>{grade}</textString>
</resultScore>
</result>
</resultRecord>
</replaceResultRequest>
</imsx_POXBody>
</imsx_POXEnvelopeRequest>
"""
post_data = post_xml.format(grade=float(grade), sourcedid=sourcedid)
# Yes, we do have to use sha1 :(
body_hash_sha = sha1()
body_hash_sha.update(post_data.encode('utf-8'))
body_hash = base64.b64encode(body_hash_sha.digest()).decode('utf-8')
args = {
'oauth_body_hash': body_hash,
'oauth_consumer_key': consumer_key,
'oauth_timestamp': str(time.time()),
'oauth_nonce': str(time.time())
}
base_string = signature.construct_base_string(
'POST',
signature.normalize_base_string_uri(outcomes_url),
signature.normalize_parameters(
signature.collect_parameters(body=args, headers={})
)
)
oauth_signature = signature.sign_hmac_sha1(base_string, consumer_secret, None)
args['oauth_signature'] = oauth_signature
headers = parameters.prepare_headers(args, headers={
'Content-Type': 'application/xml'
})
resp = requests.post(outcomes_url, data=post_data, headers=headers)
if resp.status_code != 200:
raise GradePostException(resp)
response_tree = etree.fromstring(resp.text.encode('utf-8'))
# XML and its namespaces. UBOOF!
status_tree = response_tree.find('.//{http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0}imsx_statusInfo')
code_major = status_tree.find('{http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0}imsx_codeMajor').text
if code_major != 'success':
raise GradePostException(resp)
def main():
argparser = argparse.ArgumentParser()
argparser.add_argument(
'lti_launch_info',
help="Full LTI Launch info, in JSON format"
)
argparser.add_argument(
'grade',
help='Grade to post',
type=float
)
args = argparser.parse_args()
lti_launch_info = json.loads(args.lti_launch_info)
consumer_key = os.environ['LTI_CONSUMER_KEY']
consumer_secret = os.environ['LTI_CONSUMER_SECRET']
post_grade(
lti_launch_info['lis_result_sourcedid'],
lti_launch_info['lis_outcome_service_url'],
consumer_key,
consumer_secret,
args.grade
)
if __name__ == '__main__':
main() | [
"oauthlib.oauth1.rfc5849.signature.sign_hmac_sha1",
"json.loads",
"requests.post",
"oauthlib.oauth1.rfc5849.signature.collect_parameters",
"argparse.ArgumentParser",
"oauthlib.oauth1.rfc5849.parameters.prepare_headers",
"oauthlib.oauth1.rfc5849.signature.normalize_base_string_uri",
"hashlib.sha1",
"... | [((1786, 1792), 'hashlib.sha1', 'sha1', ([], {}), '()\n', (1790, 1792), False, 'from hashlib import sha1\n'), ((2374, 2434), 'oauthlib.oauth1.rfc5849.signature.sign_hmac_sha1', 'signature.sign_hmac_sha1', (['base_string', 'consumer_secret', 'None'], {}), '(base_string, consumer_secret, None)\n', (2398, 2434), False, 'from oauthlib.oauth1.rfc5849 import signature, parameters\n'), ((2496, 2573), 'oauthlib.oauth1.rfc5849.parameters.prepare_headers', 'parameters.prepare_headers', (['args'], {'headers': "{'Content-Type': 'application/xml'}"}), "(args, headers={'Content-Type': 'application/xml'})\n", (2522, 2573), False, 'from oauthlib.oauth1.rfc5849 import signature, parameters\n'), ((2604, 2664), 'requests.post', 'requests.post', (['outcomes_url'], {'data': 'post_data', 'headers': 'headers'}), '(outcomes_url, data=post_data, headers=headers)\n', (2617, 2664), False, 'import requests\n'), ((3175, 3200), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3198, 3200), False, 'import argparse\n'), ((3472, 3504), 'json.loads', 'json.loads', (['args.lti_launch_info'], {}), '(args.lti_launch_info)\n', (3482, 3504), False, 'import json\n'), ((2180, 2229), 'oauthlib.oauth1.rfc5849.signature.normalize_base_string_uri', 'signature.normalize_base_string_uri', (['outcomes_url'], {}), '(outcomes_url)\n', (2215, 2229), False, 'from oauthlib.oauth1.rfc5849 import signature, parameters\n'), ((2044, 2055), 'time.time', 'time.time', ([], {}), '()\n', (2053, 2055), False, 'import time\n'), ((2085, 2096), 'time.time', 'time.time', ([], {}), '()\n', (2094, 2096), False, 'import time\n'), ((2283, 2334), 'oauthlib.oauth1.rfc5849.signature.collect_parameters', 'signature.collect_parameters', ([], {'body': 'args', 'headers': '{}'}), '(body=args, headers={})\n', (2311, 2334), False, 'from oauthlib.oauth1.rfc5849 import signature, parameters\n')] |
import copy
import torch
import torch.nn as nn
from pytorch_metric_learning.losses import NTXentLoss
from transformers import BertForMaskedLM, BertForPreTraining, BertTokenizer
def mask_tokens(inputs, tokenizer, not_mask_pos=None):
""" Prepare masked tokens of inputs and labels for masked language modeling (80% MASK, 10% random, 10% original).
Args:
inputs: Inputs to mask. [batch_size, max_length]
tokenizer: Tokenizer.
not_mask_pos: Used to forbid masking entity mentions. 1 for not mask else 0.
Returns:
inputs: Masked input tokens.
labels: Masked language model label tokens.
"""
if tokenizer.mask_token is None:
raise ValueError(
"This tokenizer does not have a mask token which is necessary for masked language modeling. \
Remove the --mlm flag if you want to use this tokenizer."
)
labels = copy.deepcopy(inputs)
# sample a few tokens in each sequence for masked LM training (with probability args.mlm_probability defaults to 0.15 in Bert/RoBERTa)
probability_matrix = torch.full(labels.shape, 0.15)
special_tokens_mask = [tokenizer.get_special_tokens_mask(val, already_has_special_tokens=True) for val in labels.tolist()]
probability_matrix.masked_fill_(torch.tensor(special_tokens_mask, dtype=torch.bool), value=0.0)
if tokenizer.pad_token is not None:
padding_mask = labels.eq(tokenizer.pad_token_id)
probability_matrix.masked_fill_(padding_mask, value=0.0)
if not_mask_pos is None:
masked_indices = torch.bernoulli(probability_matrix).bool()
else:
masked_indices = torch.bernoulli(probability_matrix).bool() & (~(not_mask_pos.bool()))
labels[~masked_indices] = -100 # only compute loss on masked tokens
# replace masked input tokens with tokenizer.mask_token ([MASK]) - 80% probability
indices_replaced = torch.bernoulli(torch.full(labels.shape, 0.8)).bool() & masked_indices
inputs[indices_replaced] = tokenizer.convert_tokens_to_ids(tokenizer.mask_token)
# replace masked input tokens with random word - 10%
indices_random = torch.bernoulli(torch.full(labels.shape, 0.5)).bool() & masked_indices & ~indices_replaced
random_words = torch.randint(len(tokenizer), labels.shape, dtype=torch.long)
inputs[indices_random] = random_words[indices_random]
return inputs.cuda(), labels.cuda()
class CP(nn.Module):
""" Contrastive Pre-training model.
This class implements 'CP' model based on model 'BertForMaskedLM'.
Uses NTXentLoss as constrastive loss function.
Attributes:
model: Model to train.
tokenizer: Tokenizer.
ntxloss: Contrastive loss function.
args: args from command line.
"""
def __init__(self, args):
super().__init__()
self.model = BertForMaskedLM.from_pretrained('bert-base-uncased')
self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
self.ntxloss = NTXentLoss(temperature=args.temperature)
self.args = args
######################## revised ###########################
def forward(self, input, mask, label, h_pos, t_pos, h_end, t_end):
######################## revised ###########################
input = input.view(-1, self.args.max_length)
mask = mask.view(-1, self.args.max_length)
label = label.view(-1) # [batch_size * 2]
h_pos = h_pos.view(-1)
t_pos = t_pos.view(-1)
######################## revised ###########################
h_end = h_end.view(-1)
t_end = t_end.view(-1)
######################## revised ###########################
# mask_tokens function does not mask entity mention.
indice = torch.arange(0, input.size()[0])
not_mask_pos = torch.zeros((input.size()[0], input.size()[1]), dtype=int)
not_mask_pos[indice, h_pos] = 1
not_mask_pos[indice, t_pos] = 1
######################## revised ###########################
not_mask_pos[indice, h_end] = 1
not_mask_pos[indice, t_end] = 1
######################## revised ###########################
m_input, m_labels = mask_tokens(input.cpu(), self.tokenizer, not_mask_pos=not_mask_pos)
m_outputs = self.model(input_ids=m_input, labels=m_labels, attention_mask=mask, output_hidden_states=True)
m_loss = m_outputs.loss
m_logits = m_outputs.logits
m_last_hidden_state = m_outputs.hidden_states[-1]
##### revised
# # entity marker starter
# batch_size = input.size()[0]
# h_state = m_last_hidden_state[indice, h_pos] # [batch_size * 2, hidden_size]
# t_state = m_last_hidden_state[indice, t_pos]
# state = torch.cat((h_state, t_state), 1)
if self.args.output_representation == "entity_marker":
h_state = m_last_hidden_state[indice, h_pos]
t_state = m_last_hidden_state[indice, t_pos]
state = torch.cat((h_state, t_state), 1)
elif self.args.output_representation == "all_markers":
h_start_state = m_last_hidden_state[indice, h_pos]
h_end_state = m_last_hidden_state[indice, h_end]
t_start_state = m_last_hidden_state[indice, t_pos]
t_end_state = m_last_hidden_state[indice, t_end]
h_start_state = h_start_state.unsqueeze(2)
h_end_state = h_end_state.unsqueeze(2)
t_start_state = t_start_state.unsqueeze(2)
t_end_state = t_end_state.unsqueeze(2)
state = torch.cat([h_start_state, h_end_state, t_start_state, t_end_state], 2)
state = torch.max(state, dim=2)[0]
elif self.args.output_representation == "end_to_first":
h_end_state = m_last_hidden_state[indice, h_end]
t_start_state = m_last_hidden_state[indice, t_pos]
h_end_state = h_end_state.unsqueeze(2)
t_start_state = t_start_state.unsqueeze(2)
state = torch.cat([h_end_state, t_start_state], 2)
state = torch.max(state, dim=2)[0]
elif self.args.output_representation == "all_markers_concat":
h_start_state = m_last_hidden_state[indice, h_pos]
h_end_state = m_last_hidden_state[indice, h_end]
t_start_state = m_last_hidden_state[indice, t_pos]
t_end_state = m_last_hidden_state[indice, t_end]
state = torch.cat([h_start_state, h_end_state, t_start_state, t_end_state], 1)
elif self.args.output_representation == "end_to_first_concat":
h_end_state = m_last_hidden_state[indice, h_end]
t_start_state = m_last_hidden_state[indice, t_pos]
state = torch.cat([h_end_state, t_start_state], 1)
else: # CLS
state = m_last_hidden_state[:, 0, :]
##### revised
r_loss = self.ntxloss(state, label)
return m_loss, r_loss
class MTB(nn.Module):
""" Matching the Blanks.
This class implements 'MTB' model based on model 'BertForMaskedLM'.
Attributes:
model: Model to train.
tokenizer: Tokenizer.
bceloss: Binary Cross Entropy loss.
"""
def __init__(self, args):
super().__init__()
self.model = BertForMaskedLM.from_pretrained('bert-base-uncased')
self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
self.bceloss = nn.BCEWithLogitsLoss()
self.args = args
def forward(self, l_input, l_mask, l_ph, l_pt, r_input, r_mask, r_ph, r_pt, label):
# compute not mask entity marker
indice = torch.arange(0, l_input.size()[0])
l_not_mask_pos = torch.zeros((l_input.size()[0], l_input.size()[1]), dtype=int)
r_not_mask_pos = torch.zeros((l_input.size()[0], l_input.size()[1]), dtype=int)
# mask_tokens function does not mask entity mention.
l_not_mask_pos[indice, l_ph] = 1
l_not_mask_pos[indice, l_pt] = 1
r_not_mask_pos[indice, r_ph] = 1
r_not_mask_pos[indice, r_pt] = 1
m_l_input, m_l_labels = mask_tokens(l_input.cpu(), self.tokenizer, l_not_mask_pos)
m_r_input, m_r_labels = mask_tokens(r_input.cpu(), self.tokenizer, r_not_mask_pos)
m_l_outputs = self.model(input_ids=m_l_input, labels=m_l_labels, attention_mask=l_mask)
m_r_outputs = self.model(input_ids=m_r_input, labels=m_r_labels, attention_mask=r_mask)
m_loss = m_l_outputs.loss + m_r_outputs.loss
m_l_logits = m_l_outputs.logits
m_r_logits = m_r_outputs.logits
batch_size = l_input.size()[0]
# left output
l_h_state = m_l_logits[indice, l_ph] # [batch, hidden_size]
l_t_state = m_l_logits[indice, l_pt]
l_state = torch.cat((l_h_state, l_t_state), 1) # [batch, hidden_size * 2]
# right output
r_h_state = m_r_logits[indice, r_ph] # [batch, hidden_size]
r_t_state = m_r_logits[indice, r_pt]
r_state = torch.cat((r_h_state, r_t_state), 1) # [batch, hidden_size * 2]
# calculate similarity
similarity = torch.sum(l_state * r_state, 1)
# calculate loss
r_loss = self.bceloss(similarity, label.float())
return m_loss, r_loss | [
"torch.bernoulli",
"transformers.BertForMaskedLM.from_pretrained",
"torch.full",
"pytorch_metric_learning.losses.NTXentLoss",
"transformers.BertTokenizer.from_pretrained",
"torch.max",
"torch.tensor",
"torch.sum",
"copy.deepcopy",
"torch.nn.BCEWithLogitsLoss",
"torch.cat"
] | [((911, 932), 'copy.deepcopy', 'copy.deepcopy', (['inputs'], {}), '(inputs)\n', (924, 932), False, 'import copy\n'), ((1098, 1128), 'torch.full', 'torch.full', (['labels.shape', '(0.15)'], {}), '(labels.shape, 0.15)\n', (1108, 1128), False, 'import torch\n'), ((1292, 1343), 'torch.tensor', 'torch.tensor', (['special_tokens_mask'], {'dtype': 'torch.bool'}), '(special_tokens_mask, dtype=torch.bool)\n', (1304, 1343), False, 'import torch\n'), ((2852, 2904), 'transformers.BertForMaskedLM.from_pretrained', 'BertForMaskedLM.from_pretrained', (['"""bert-base-uncased"""'], {}), "('bert-base-uncased')\n", (2883, 2904), False, 'from transformers import BertForMaskedLM, BertForPreTraining, BertTokenizer\n'), ((2930, 2980), 'transformers.BertTokenizer.from_pretrained', 'BertTokenizer.from_pretrained', (['"""bert-base-uncased"""'], {}), "('bert-base-uncased')\n", (2959, 2980), False, 'from transformers import BertForMaskedLM, BertForPreTraining, BertTokenizer\n'), ((3004, 3044), 'pytorch_metric_learning.losses.NTXentLoss', 'NTXentLoss', ([], {'temperature': 'args.temperature'}), '(temperature=args.temperature)\n', (3014, 3044), False, 'from pytorch_metric_learning.losses import NTXentLoss\n'), ((7299, 7351), 'transformers.BertForMaskedLM.from_pretrained', 'BertForMaskedLM.from_pretrained', (['"""bert-base-uncased"""'], {}), "('bert-base-uncased')\n", (7330, 7351), False, 'from transformers import BertForMaskedLM, BertForPreTraining, BertTokenizer\n'), ((7377, 7427), 'transformers.BertTokenizer.from_pretrained', 'BertTokenizer.from_pretrained', (['"""bert-base-uncased"""'], {}), "('bert-base-uncased')\n", (7406, 7427), False, 'from transformers import BertForMaskedLM, BertForPreTraining, BertTokenizer\n'), ((7451, 7473), 'torch.nn.BCEWithLogitsLoss', 'nn.BCEWithLogitsLoss', ([], {}), '()\n', (7471, 7473), True, 'import torch.nn as nn\n'), ((8807, 8843), 'torch.cat', 'torch.cat', (['(l_h_state, l_t_state)', '(1)'], {}), '((l_h_state, l_t_state), 1)\n', (8816, 8843), False, 'import torch\n'), ((9036, 9072), 'torch.cat', 'torch.cat', (['(r_h_state, r_t_state)', '(1)'], {}), '((r_h_state, r_t_state), 1)\n', (9045, 9072), False, 'import torch\n'), ((9154, 9185), 'torch.sum', 'torch.sum', (['(l_state * r_state)', '(1)'], {}), '(l_state * r_state, 1)\n', (9163, 9185), False, 'import torch\n'), ((5023, 5055), 'torch.cat', 'torch.cat', (['(h_state, t_state)', '(1)'], {}), '((h_state, t_state), 1)\n', (5032, 5055), False, 'import torch\n'), ((1578, 1613), 'torch.bernoulli', 'torch.bernoulli', (['probability_matrix'], {}), '(probability_matrix)\n', (1593, 1613), False, 'import torch\n'), ((5599, 5669), 'torch.cat', 'torch.cat', (['[h_start_state, h_end_state, t_start_state, t_end_state]', '(2)'], {}), '([h_start_state, h_end_state, t_start_state, t_end_state], 2)\n', (5608, 5669), False, 'import torch\n'), ((1656, 1691), 'torch.bernoulli', 'torch.bernoulli', (['probability_matrix'], {}), '(probability_matrix)\n', (1671, 1691), False, 'import torch\n'), ((1931, 1960), 'torch.full', 'torch.full', (['labels.shape', '(0.8)'], {}), '(labels.shape, 0.8)\n', (1941, 1960), False, 'import torch\n'), ((5690, 5713), 'torch.max', 'torch.max', (['state'], {'dim': '(2)'}), '(state, dim=2)\n', (5699, 5713), False, 'import torch\n'), ((6031, 6073), 'torch.cat', 'torch.cat', (['[h_end_state, t_start_state]', '(2)'], {}), '([h_end_state, t_start_state], 2)\n', (6040, 6073), False, 'import torch\n'), ((2166, 2195), 'torch.full', 'torch.full', (['labels.shape', '(0.5)'], {}), '(labels.shape, 0.5)\n', (2176, 2195), False, 'import torch\n'), ((6094, 6117), 'torch.max', 'torch.max', (['state'], {'dim': '(2)'}), '(state, dim=2)\n', (6103, 6117), False, 'import torch\n'), ((6459, 6529), 'torch.cat', 'torch.cat', (['[h_start_state, h_end_state, t_start_state, t_end_state]', '(1)'], {}), '([h_start_state, h_end_state, t_start_state, t_end_state], 1)\n', (6468, 6529), False, 'import torch\n'), ((6745, 6787), 'torch.cat', 'torch.cat', (['[h_end_state, t_start_state]', '(1)'], {}), '([h_end_state, t_start_state], 1)\n', (6754, 6787), False, 'import torch\n')] |
import pandas as pd
import os
if __name__ == "__main__":
data_dir = os.environ.get("DATA_DIRECTORY")
data_file = os.environ.get("DATA_FILE")
print(data_dir)
data_df = pd.read_pickle(data_dir + data_file)
test_df = pd.DataFrame()
# Creating two non-overlapping datasets for training and validation
# by taking all pictures of 15 cards and putting them in the test data frame
for i in range(15):
temp = data_df.loc[
data_df["categories"].apply(
lambda x: set(x) == set(data_df["categories"][i])
),
:,
]
test_df = pd.concat([test_df, temp])
data_df = data_df.drop(test_df.index.values, axis=0).reset_index(drop=True)
test_df = test_df.reset_index(drop=True)
# Shuffling the data
data_df = data_df.sample(frac=1).reset_index(drop=True)
test_df = test_df.sample(frac=1).reset_index(drop=True)
print(data_df.shape)
print(test_df.shape)
data_df.to_pickle(data_dir + "/train.pkl")
test_df.to_pickle(data_dir + "/test.pkl")
| [
"pandas.read_pickle",
"os.environ.get",
"pandas.DataFrame",
"pandas.concat"
] | [((73, 105), 'os.environ.get', 'os.environ.get', (['"""DATA_DIRECTORY"""'], {}), "('DATA_DIRECTORY')\n", (87, 105), False, 'import os\n'), ((122, 149), 'os.environ.get', 'os.environ.get', (['"""DATA_FILE"""'], {}), "('DATA_FILE')\n", (136, 149), False, 'import os\n'), ((184, 220), 'pandas.read_pickle', 'pd.read_pickle', (['(data_dir + data_file)'], {}), '(data_dir + data_file)\n', (198, 220), True, 'import pandas as pd\n'), ((235, 249), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (247, 249), True, 'import pandas as pd\n'), ((621, 647), 'pandas.concat', 'pd.concat', (['[test_df, temp]'], {}), '([test_df, temp])\n', (630, 647), True, 'import pandas as pd\n')] |
## ACL Import Module
# ACL CSV Import
# Version 5
# 2015-10-30
# we only need the datetime class & the static function strptime from datetime module
from datetime import datetime
import re
import sys
import os
import logging
# best postgresql module so far, install it "yum install python-psycopg2"
import psycopg2
import csv
import shutil
from tempfile import mkstemp
module_logger = logging.getLogger('acl')
_sql={
'schd' : """
insert into acl_schd
(
source,
acl_id,
flight_id,
carrier_id,
leg_id,
airline_iata,
airline_icao,
flightnumber,
codeshare,
operating_flightnumber,
flight_date,
std,
"off",
"out",
down,
"on",
sta,
eta,
ata,
origin_iata,
origin_icao,
destination_iata,
destination_icao,
airport_iata,
airport_icao,
last_next_iata,
last_next_icao,
orig_dest_iata,
orig_dest_icao,
aircraft_iata,
aircraft_icao,
seats,
pax,
lastupdated,
flight_type,
pax_flight,
origin_status,
destination_status,
etd,
atd,
arr_dep,
oag_type,
flight_transid,
voyageid
)
select
source,
acl_id as acl_id,
null as flight_id,
null as carrier_id,
null as leg_id,
airline_iata,
airline_icao,
acl_flightnumber as flightnumber,
0 as codeshare,
null as operating_flightnumber,
acl_date as flight_date,
(case when acl_arrdep = 'D' then flight_datetime end) as std,
null as off,
null as out,
null as down,
null as on,
(case when acl_arrdep = 'A' then flight_datetime end) as sta,
null as eta,
null as ata,
acl_origin as origin_iata,
acl_origin_icao as origin_icao,
acl_dest as destination_iata,
acl_dest_icao as destination_icao,
acl_airport as airport_iata,
airport_icao as airport_icao,
acl_last_next_iata as last_next_iata,
acl_last_next_icao as last_next_icao,
acl_orig_dest_iata as orig_dest_iata,
acl_orig_dest_icao as orig_dest_icao,
acl_aircraft_iata as aircraft_iata,
acl_aircraft_icao as aircraft_icao,
null as seats,
null as pax,
lastupdated at time zone 'UTC' as lastupdated,
acl_service_type as flight_type,
servicetype_pax::int as pax_flight,
null as origin_status,
null as destination_status,
null as etd,
null as atd,
acl_arrdep as arr_dep,
null as oag_type,
null as flight_transid,
( acl_origin || acl_dest || to_char(acl_date,'YYYYMMDD') || btrim(coalesce(airline_iata,airline_icao)) || btrim(acl_flightnumber) || acl_arrdep) as voyageid
from (
select
A.acl_id,
A.acl_file_date,
A.acl_date,
A.acl_time,
A.acl_arrdep,
A.acl_airport,
A.acl_last_next_iata,
A.acl_orig_dest_iata,
A.acl_aircraft_iata,
A.acl_last_next_icao,
A.acl_orig_dest_icao,
A.acl_aircraft_icao,
A.acl_operator_airline_code,
A.acl_flightnumber,
A.acl_service_type,
A.acl_aircraft_reg,
A.acl_edit_date,
OFA.airline_iata,
OFA.airline_icao,
OF1.airport_icao,
-- calculated fields
A.acl_date + A.acl_time at time zone 'UTC' as flight_datetime,
--A.acl_date + A.acl_time as flight_datetime,
(case when A.acl_arrdep = 'D' then A.acl_airport else A.acl_last_next_iata end) as acl_origin,
(case when A.acl_arrdep = 'A' then A.acl_airport else A.acl_last_next_iata end) as acl_dest,
(case when A.acl_arrdep = 'D' then OF1.airport_icao else A.acl_last_next_icao end) as acl_origin_icao,
(case when A.acl_arrdep = 'A' then OF1.airport_icao else A.acl_last_next_icao end) as acl_dest_icao,
T.servicetype_pax,
source_type as source,
source_date as lastupdated
from acl_csv A
join history H
on H.source_type='A'
join of_airlines OFA
on ( OFA.airline_iata = A.acl_operator_airline_code and OFA.airline_active='Y' )
or OFA.airline_icao = A.acl_operator_airline_code
left join of_airports OF1
on OF1.airport_iata = A.acl_airport
left join servicetypes T
on acl_service_type = servicetype_code
where acl_file_type = 3
and acl_file_date > coalesce(
(
select
A.acl_file_date
from acl_csv A
join (
select
max(acl_id) as acl_id,
max(lastupdated) as lastupdated
from (
select
max(acl_id) as acl_id,
max(lastupdated) as lastupdated
from schd
where source='A'
group by lastupdated
UNION
select
max(acl_id) as acl_id,
max(lastupdated) as lastupdated
from acl_schd
where source='A'
group by lastupdated
) Z
) B
on B.acl_id = A.acl_id
), '2015-01-01'::date)
-- and acl_file_date >= '2015-09-14'::date
and acl_date > acl_file_date -- because acl data turns up nearly 24 hours late
) Z
""",
'copy' : """
copy acl_csv (
acl_aircraft_iata,
acl_aircraft_reg,
acl_airport,
acl_arrdep,
acl_created_date,
acl_date,
acl_doop,
acl_edit_date,
acl_aircraft_icao,
acl_last_next_icao,
acl_orig_dest_icao,
acl_last_next_iata,
acl_last_next_country,
acl_operator_airline_code,
acl_operator_group_name,
acl_operator_name,
acl_orig_dest_iata,
acl_orig_dest_country,
acl_terminal_name,
acl_season,
acl_seats,
acl_flightnumber,
acl_service_type,
acl_turnaround,
acl_terminal,
acl_time,
acl_turn_operator_airline_code,
acl_turn_flightnumber,
acl_flightdesignator,
acl_loadfactor
) from stdin
with csv header
""",
'history' : """
update history
set source_date = now()
where source_type='A'
""",
'update' : """
update acl_csv
set acl_filename = %s,
acl_file_date = %s,
acl_file_type = %s
where acl_filename is null
""",
'last' : """
select
extract(epoch from source_date) as lastupdated
from history
where source_type='A'
""",
'file_check' : """
select
acl_filename
from acl_csv
where acl_filename = %(filename)s
""",
'lock_acl_schd' : """
LOCK TABLE acl_schd IN ACCESS EXCLUSIVE MODE
"""
}
# import an ACL CSV file
# Args:
# dbh = database handle (psycopg2)
# filename = csv filename
def importfile(dbh, filename):
module_logger.info("Import %s", filename)
status=1
message='OK'
if os.path.isfile(filename):
# break the file name into useful parts
# optional airport & season prefix we actually ignore eg "LHRS15"
# mandatory "HOMEOFFICEROLL"
# mandatory integer filetype usually 1 or 3 or 180
# manatory file date in YYYYMMDD
# note case insensitive as we have been given files with both uppercase and lowercase filenames
match = re.search('^(.*?)homeofficeroll(\d+)_(\d{4}\d{2}\d{2})\.csv$', os.path.basename(filename), re.I)
if match is not None:
date = datetime.strptime(match.group(3), '%Y%m%d').date()
filetype= match.group(2)
module_logger.info("Importing %s", filename)
module_logger.debug("Processing File %s Date %s File Type %s Filename %s", filename, date, filetype, os.path.basename(filename))
# copy data use postgresql copy command, pyscopg2 allows use to do so from a python file handle via "stdin"
csr=dbh.cursor()
try:
f=open(filename)
csr.copy_expert(sql=_sql['copy'], file=f)
# add file info to the rows we just imported
csr.execute(_sql['update'], (os.path.basename(filename), date, filetype))
module_logger.debug("Q %s", csr.query)
module_logger.debug("R %s", csr.statusmessage)
csr.execute(_sql['history'])
module_logger.debug("Q %s", csr.query)
module_logger.debug("R %s", csr.statusmessage)
# gain an AccessExlusive lock on the acl_schd table to prevent race condition with schd.py
csr.execute(_sql['lock_acl_schd'])
module_logger.debug("Q %s", csr.query)
module_logger.debug("R %s", csr.statusmessage)
csr.execute(_sql['schd'])
module_logger.debug("Q %s", csr.query)
module_logger.debug("R %s", csr.statusmessage)
csr.close()
module_logger.debug("Commit")
dbh.commit()
status=1
except:
module_logger.exception("Rollback")
csr.close()
dbh.rollback()
status=-2
message="Error processing "+filename
module_logger.error("Error processing %s", filename)
finally:
f.close()
else:
status=-2
message="Invalid filename skipping "+filename
module_logger.warning("File name doesn't match %s", filename)
else:
status=-2
message="File not found"+filename
module_logger.error("File not found %s", filename)
return status,message
# end def importfile
def _sortkey(filename):
match = re.search('^(.*?)homeofficeroll(\d+)_(\d{4}\d{2}\d{2})(.*?)$', filename, re.I)
key=''
if match is not None:
key=match.group(3)
return key
#end def _sortkey
def validate_file(f , renamebad=True, baddir=None):
#logger=logging.getLogger()
if baddir is not None:
if not os.path.exists(baddir):
os.makedirs(baddir)
module_logger.info("Validating %s", f)
ok=True
header=False
rewritten=False
header_row=0
rowcount=0
tf=None
with open(f, 'rb') as file:
reader = csv.reader(file)
for row in reader:
if not header:
if len(row) == 30 and row[0] == 'A/C':
header=True
else:
header_row+=1
else:
if len(row) != 30:
ok=False
module_logger.info("Incorrect Row Size %s", rowcount)
rowcount+=1
# end for
if not header:
ok=False
module_logger.info("No Header found")
if header and header_row > 0:
module_logger.info("Extra Header Rows found")
fh, tf = mkstemp()
file.seek(0)
reader = csv.reader(file)
with open(tf, 'wb') as tmpfile:
writer = csv.writer(tmpfile)
r=0
for row in reader:
if r >= header_row:
writer.writerow(row)
r+=1
module_logger.info("Rewrite file")
rewritten=True
if ok and rewritten and tf is not None:
nf=None
if renamebad:
nf=f+'.bad'
os.rename(f,nf)
else:
nf=os.path.join(baddir, os.path.basename(f))
os.rename(f,nf)
os.rename(tf,f)
module_logger.info("Corrected %s Moved Bad File to %s", f, nf)
if not ok:
nf=None
if renamebad:
nf=f+'.bad'
os.rename(f,nf)
else:
nf=os.path.join(baddir, os.path.basename(f))
os.rename(f,nf)
module_logger.info("Moved Bad File %s to %s", f, nf)
return ok
#end def validate_file
def import_folder(dbh, sourcedir, archivedir=None, debug=False):
status=1
message='OK'
archivemode=False
if archivedir is not None and archivedir != sourcedir:
archivemode=True
if not os.path.exists(archivedir):
os.makedirs(archivedir)
#retrieve last imported file date/time
csr=dbh.cursor()
filecount=0
if os.path.isdir(sourcedir):
filelist=sorted(os.listdir(sourcedir), key = _sortkey)
if filelist is not None:
for filename in filelist:
f=os.path.join(sourcedir, filename)
if os.path.isfile(f):
# is it a .done file?
match = re.search('^((.*?)homeofficeroll(\d+)_(\d{4}\d{2}\d{2})\.csv)\.done$', filename, re.I)
if match is not None:
# extract corresponding csv name & check it
csvfilename=match.group(1)
cf=os.path.join(sourcedir, csvfilename)
if os.path.isfile(cf) and validate_file(cf, False, archivedir):
csr.execute(_sql['file_check'], { 'filename': csvfilename } )
# if the filename isn't found
if csr.rowcount == 0:
module_logger.debug("F %s",cf)
module_logger.info("Importing %s", cf)
status, message=importfile(dbh, cf)
if status != 1:
module_logger.debug("Status %s bailing", status)
break
filecount+=1
# only archive if status is good & archivedir
if archivemode:
nf=os.path.join(archivedir, csvfilename)
os.rename(cf,nf)
# remove the .done file
os.unlink(f)
#end for
if filecount == 0:
module_logger.error("No files imported")
message='No files imported'
else:
module_logger.info("%s files imported", filecount)
message="%s files imported" % filecount
else:
module_logger.error("No files found")
status=-2
message='No files found to import'
else:
status=-2
module_logger.error("%s not a folder", sourcedir)
message="Source Folder not found "+sourcedir
csr.close()
return status, message
# end def findfiles
| [
"logging.getLogger",
"os.path.exists",
"os.listdir",
"os.makedirs",
"os.rename",
"tempfile.mkstemp",
"csv.writer",
"os.path.join",
"os.path.isfile",
"os.path.isdir",
"os.path.basename",
"os.unlink",
"csv.reader",
"re.search"
] | [((390, 414), 'logging.getLogger', 'logging.getLogger', (['"""acl"""'], {}), "('acl')\n", (407, 414), False, 'import logging\n'), ((6289, 6313), 'os.path.isfile', 'os.path.isfile', (['filename'], {}), '(filename)\n', (6303, 6313), False, 'import os\n'), ((8608, 8694), 're.search', 're.search', (['"""^(.*?)homeofficeroll(\\\\d+)_(\\\\d{4}\\\\d{2}\\\\d{2})(.*?)$"""', 'filename', 're.I'], {}), "('^(.*?)homeofficeroll(\\\\d+)_(\\\\d{4}\\\\d{2}\\\\d{2})(.*?)$', filename,\n re.I)\n", (8617, 8694), False, 'import re\n'), ((10702, 10726), 'os.path.isdir', 'os.path.isdir', (['sourcedir'], {}), '(sourcedir)\n', (10715, 10726), False, 'import os\n'), ((9099, 9115), 'csv.reader', 'csv.reader', (['file'], {}), '(file)\n', (9109, 9115), False, 'import csv\n'), ((10032, 10048), 'os.rename', 'os.rename', (['tf', 'f'], {}), '(tf, f)\n', (10041, 10048), False, 'import os\n'), ((6718, 6744), 'os.path.basename', 'os.path.basename', (['filename'], {}), '(filename)\n', (6734, 6744), False, 'import os\n'), ((8891, 8913), 'os.path.exists', 'os.path.exists', (['baddir'], {}), '(baddir)\n', (8905, 8913), False, 'import os\n'), ((8919, 8938), 'os.makedirs', 'os.makedirs', (['baddir'], {}), '(baddir)\n', (8930, 8938), False, 'import os\n'), ((9556, 9565), 'tempfile.mkstemp', 'mkstemp', ([], {}), '()\n', (9563, 9565), False, 'from tempfile import mkstemp\n'), ((9601, 9617), 'csv.reader', 'csv.reader', (['file'], {}), '(file)\n', (9611, 9617), False, 'import csv\n'), ((9936, 9952), 'os.rename', 'os.rename', (['f', 'nf'], {}), '(f, nf)\n', (9945, 9952), False, 'import os\n'), ((10011, 10027), 'os.rename', 'os.rename', (['f', 'nf'], {}), '(f, nf)\n', (10020, 10027), False, 'import os\n'), ((10170, 10186), 'os.rename', 'os.rename', (['f', 'nf'], {}), '(f, nf)\n', (10179, 10186), False, 'import os\n'), ((10245, 10261), 'os.rename', 'os.rename', (['f', 'nf'], {}), '(f, nf)\n', (10254, 10261), False, 'import os\n'), ((10557, 10583), 'os.path.exists', 'os.path.exists', (['archivedir'], {}), '(archivedir)\n', (10571, 10583), False, 'import os\n'), ((10588, 10611), 'os.makedirs', 'os.makedirs', (['archivedir'], {}), '(archivedir)\n', (10599, 10611), False, 'import os\n'), ((10746, 10767), 'os.listdir', 'os.listdir', (['sourcedir'], {}), '(sourcedir)\n', (10756, 10767), False, 'import os\n'), ((7027, 7053), 'os.path.basename', 'os.path.basename', (['filename'], {}), '(filename)\n', (7043, 7053), False, 'import os\n'), ((9670, 9689), 'csv.writer', 'csv.writer', (['tmpfile'], {}), '(tmpfile)\n', (9680, 9689), False, 'import csv\n'), ((9987, 10006), 'os.path.basename', 'os.path.basename', (['f'], {}), '(f)\n', (10003, 10006), False, 'import os\n'), ((10221, 10240), 'os.path.basename', 'os.path.basename', (['f'], {}), '(f)\n', (10237, 10240), False, 'import os\n'), ((10850, 10883), 'os.path.join', 'os.path.join', (['sourcedir', 'filename'], {}), '(sourcedir, filename)\n', (10862, 10883), False, 'import os\n'), ((10892, 10909), 'os.path.isfile', 'os.path.isfile', (['f'], {}), '(f)\n', (10906, 10909), False, 'import os\n'), ((10957, 11053), 're.search', 're.search', (['"""^((.*?)homeofficeroll(\\\\d+)_(\\\\d{4}\\\\d{2}\\\\d{2})\\\\.csv)\\\\.done$"""', 'filename', 're.I'], {}), "('^((.*?)homeofficeroll(\\\\d+)_(\\\\d{4}\\\\d{2}\\\\d{2})\\\\.csv)\\\\.done$',\n filename, re.I)\n", (10966, 11053), False, 'import re\n'), ((7347, 7373), 'os.path.basename', 'os.path.basename', (['filename'], {}), '(filename)\n', (7363, 7373), False, 'import os\n'), ((11171, 11207), 'os.path.join', 'os.path.join', (['sourcedir', 'csvfilename'], {}), '(sourcedir, csvfilename)\n', (11183, 11207), False, 'import os\n'), ((11880, 11892), 'os.unlink', 'os.unlink', (['f'], {}), '(f)\n', (11889, 11892), False, 'import os\n'), ((11224, 11242), 'os.path.isfile', 'os.path.isfile', (['cf'], {}), '(cf)\n', (11238, 11242), False, 'import os\n'), ((11771, 11808), 'os.path.join', 'os.path.join', (['archivedir', 'csvfilename'], {}), '(archivedir, csvfilename)\n', (11783, 11808), False, 'import os\n'), ((11818, 11835), 'os.rename', 'os.rename', (['cf', 'nf'], {}), '(cf, nf)\n', (11827, 11835), False, 'import os\n')] |
import os, queue
from tablet import Tablet
f = open(os.path.join(os.path.dirname(__file__), '../input/18/part1.txt'), 'r')
def main():
instructionStrings = []
line = f.readline()
while line:
instructionStrings.append(line.rstrip())
line = f.readline()
q0 = queue.Queue()
q1 = queue.Queue()
t0 = Tablet(instructionStrings, 0, q0, q1)
t1 = Tablet(instructionStrings, 1, q1, q0)
isDeadlock = False
while not isDeadlock:
t0.run()
t1.run()
if t0.isWaiting() and t1.isWaiting():
isDeadlock = True
print(t1.getTimesSent())
if __name__ == '__main__':
main()
| [
"os.path.dirname",
"tablet.Tablet",
"queue.Queue"
] | [((292, 305), 'queue.Queue', 'queue.Queue', ([], {}), '()\n', (303, 305), False, 'import os, queue\n'), ((315, 328), 'queue.Queue', 'queue.Queue', ([], {}), '()\n', (326, 328), False, 'import os, queue\n'), ((339, 376), 'tablet.Tablet', 'Tablet', (['instructionStrings', '(0)', 'q0', 'q1'], {}), '(instructionStrings, 0, q0, q1)\n', (345, 376), False, 'from tablet import Tablet\n'), ((386, 423), 'tablet.Tablet', 'Tablet', (['instructionStrings', '(1)', 'q1', 'q0'], {}), '(instructionStrings, 1, q1, q0)\n', (392, 423), False, 'from tablet import Tablet\n'), ((66, 91), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (81, 91), False, 'import os, queue\n')] |
import datetime
import os
from zipfile import ZipFile
import requests
from icecream import ic
from wget import download
ic.enable()
date_from = (datetime.date.today() - datetime.timedelta(days=5)).isoformat()
date_to = (datetime.date.today()).isoformat()
ic(f'Date Range: {date_from} to {date_to}')
def getbhav_data(date_from: str, date_to: str):
date1 = datetime.date.fromisoformat(date_from)
date2 = datetime.date.fromisoformat(date_to)
months = {
1: 'JAN', 2: 'FEB', 3: 'MAR', 4: 'APR', 5: 'MAY', 6: 'JUN',
7: 'JUL', 8: 'AUG', 9: 'SEP', 10: 'OCT', 11: 'NOV', 12: 'DEC'
}
if not os.path.exists('./bhavcopy/'):
os.mkdir('./bhavcopy/')
os.chdir('./bhavcopy/')
def daterange(date_from, date_to):
for n in range(int((date_to - date_from).days + 1)):
yield date_from + datetime.timedelta(n)
for date in daterange(date1, date2):
url_NSE_archive_of_daily_monthly_reports = 'https://www1.nseindia.com/products/content/equities/equities/archieve_eq.htm'
url_bhavcopy_daily = f'https://www1.nseindia.com/content/historical/EQUITIES/{date.year}/{months[date.month]}/cm{date.day}{months[date.month]}{date.year}bhav.csv.zip'
req = requests.get(url_NSE_archive_of_daily_monthly_reports)
ic(req.status_code)
ZipFile = download(url_bhavcopy_daily)
# def extract_zip(zip_file, extract_path):
getbhav_data(date_from, date_to)
| [
"icecream.ic.enable",
"os.path.exists",
"icecream.ic",
"wget.download",
"requests.get",
"datetime.timedelta",
"os.chdir",
"os.mkdir",
"datetime.date.today",
"datetime.date.fromisoformat"
] | [((122, 133), 'icecream.ic.enable', 'ic.enable', ([], {}), '()\n', (131, 133), False, 'from icecream import ic\n'), ((259, 302), 'icecream.ic', 'ic', (['f"""Date Range: {date_from} to {date_to}"""'], {}), "(f'Date Range: {date_from} to {date_to}')\n", (261, 302), False, 'from icecream import ic\n'), ((365, 403), 'datetime.date.fromisoformat', 'datetime.date.fromisoformat', (['date_from'], {}), '(date_from)\n', (392, 403), False, 'import datetime\n'), ((416, 452), 'datetime.date.fromisoformat', 'datetime.date.fromisoformat', (['date_to'], {}), '(date_to)\n', (443, 452), False, 'import datetime\n'), ((224, 245), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (243, 245), False, 'import datetime\n'), ((625, 654), 'os.path.exists', 'os.path.exists', (['"""./bhavcopy/"""'], {}), "('./bhavcopy/')\n", (639, 654), False, 'import os\n'), ((664, 687), 'os.mkdir', 'os.mkdir', (['"""./bhavcopy/"""'], {}), "('./bhavcopy/')\n", (672, 687), False, 'import os\n'), ((696, 719), 'os.chdir', 'os.chdir', (['"""./bhavcopy/"""'], {}), "('./bhavcopy/')\n", (704, 719), False, 'import os\n'), ((1234, 1288), 'requests.get', 'requests.get', (['url_NSE_archive_of_daily_monthly_reports'], {}), '(url_NSE_archive_of_daily_monthly_reports)\n', (1246, 1288), False, 'import requests\n'), ((1297, 1316), 'icecream.ic', 'ic', (['req.status_code'], {}), '(req.status_code)\n', (1299, 1316), False, 'from icecream import ic\n'), ((1335, 1363), 'wget.download', 'download', (['url_bhavcopy_daily'], {}), '(url_bhavcopy_daily)\n', (1343, 1363), False, 'from wget import download\n'), ((149, 170), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (168, 170), False, 'import datetime\n'), ((173, 199), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(5)'}), '(days=5)\n', (191, 199), False, 'import datetime\n'), ((851, 872), 'datetime.timedelta', 'datetime.timedelta', (['n'], {}), '(n)\n', (869, 872), False, 'import datetime\n')] |
# coding=utf-8
# !/usr/bin/python3
# Name: ruuvitag calc - calculations
# Copyright: (c) 2019 TK
# Licence: MIT
# -------------------------------------------------------------------------------
import logging
logger = logging.getLogger('ruuvitag')
import math
# -------------------------------------------------------------------------------
class ruuvitag_calc():
# -------------------------------------------------------------------------------
@staticmethod
def set_value(*, out, field, value):
if value:
out[field] = value
# -------------------------------------------------------------------------------
@staticmethod
def calc(*, datas, out):
ruuvitag_calc.set_value(out=out, field='equilibriumVaporPressure', value=ruuvitag_calc.equilibriumVaporPressure(datas=datas))
ruuvitag_calc.set_value(out=out, field='absoluteHumidity', value=ruuvitag_calc.absoluteHumidity(datas=datas))
ruuvitag_calc.set_value(out=out, field='dewPoint', value=ruuvitag_calc.dewPoint(datas=datas))
ruuvitag_calc.set_value(out=out, field='airDensity', value=ruuvitag_calc.airDensity(datas=datas))
# -------------------------------------------------------------------------------
@staticmethod
def equilibriumVaporPressure(*, datas):
try:
l_temp = float(datas['temperature'])
return round((611.2 * math.exp(17.67 * l_temp / (243.5 + l_temp))), 3)
except:
return None
return None
# -------------------------------------------------------------------------------
@staticmethod
def absoluteHumidity(*, datas):
try:
l_temp = float(datas['temperature'])
l_humi = float(datas['humidity'])
return round((ruuvitag_calc.equilibriumVaporPressure(datas=datas) * l_humi * 0.021674 / (273.15 + l_temp)), 3)
except:
return None
return None
# -------------------------------------------------------------------------------
@staticmethod
def dewPoint(*, datas):
try:
l_humi = float(datas['humidity'])
l_v = math.log(l_humi / 100 * ruuvitag_calc.equilibriumVaporPressure(datas=datas) / 611.2)
return round(((-243.5 * l_v) / (l_v - 17.67)), 3)
except:
return None
return None
# -------------------------------------------------------------------------------
@staticmethod
def airDensity(*, datas):
"""
kg/m3
"""
try:
l_temp = float(datas['temperature'])
l_humi = float(datas['humidity'])
l_pres = float(datas['pressure'])
return round((1.2929 * 273.15 / (l_temp + 273.15) * (l_pres - 0.3783 * l_humi / 100 * ruuvitag_calc.equilibriumVaporPressure(datas=datas)) / 101300)*100, 3)
except:
return None
return None
| [
"logging.getLogger",
"math.exp"
] | [((234, 263), 'logging.getLogger', 'logging.getLogger', (['"""ruuvitag"""'], {}), "('ruuvitag')\n", (251, 263), False, 'import logging\n'), ((1403, 1446), 'math.exp', 'math.exp', (['(17.67 * l_temp / (243.5 + l_temp))'], {}), '(17.67 * l_temp / (243.5 + l_temp))\n', (1411, 1446), False, 'import math\n')] |
# -*- coding: utf-8 -*-
'''
Copyright (c) 2021, Trustworthy AI, Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
###############################################################################
# transforms.py
# Purpose: utilities for converting between carla and ROS coordinate systems
# Notes:
# to make sure my editor saves in utf-8 here is a nice character: é
###############################################################################
import math
import numpy
import tf
from geometry_msgs.msg import Vector3, Quaternion, Transform, Pose, Point, Twist, Accel
def carla_location_to_numpy_vector(carla_location):
"""
Convert a carla location to a ROS vector3
Considers the conversion from left-handed system (unreal) to right-handed
system (ROS)
:param carla_location: the carla location
:type carla_location: carla.Location
:return: a numpy.array with 3 elements
:rtype: numpy.array
"""
return numpy.array([
carla_location.x,
-carla_location.y,
carla_location.z
])
def carla_location_to_ros_vector3(carla_location):
"""
Convert a carla location to a ROS vector3
Considers the conversion from left-handed system (unreal) to right-handed
system (ROS)
:param carla_location: the carla location
:type carla_location: carla.Location
:return: a ROS vector3
:rtype: geometry_msgs.msg.Vector3
"""
ros_translation = Vector3()
ros_translation.x = carla_location.x
ros_translation.y = -carla_location.y
ros_translation.z = carla_location.z
return ros_translation
def carla_location_to_ros_point(carla_location):
"""
Convert a carla location to a ROS point
Considers the conversion from left-handed system (unreal) to right-handed
system (ROS)
:param carla_location: the carla location
:type carla_location: carla.Location
:return: a ROS point
:rtype: geometry_msgs.msg.Point
"""
ros_point = Point()
ros_point.x = carla_location.x
ros_point.y = -carla_location.y
ros_point.z = carla_location.z
return ros_point
def numpy_quaternion_to_ros_quaternion(numpy_quaternion):
"""
Convert a quaternion from transforms to a ROS msg quaternion
:param numpy_quaternion: a numpy quaternion
:type numpy_quaternion: numpy.array
:return: a ROS quaternion
:rtype: geometry_msgs.msg.Quaternion
"""
ros_quaternion = Quaternion()
ros_quaternion.x = numpy_quaternion[0]
ros_quaternion.y = numpy_quaternion[1]
ros_quaternion.z = numpy_quaternion[2]
ros_quaternion.w = numpy_quaternion[3]
return ros_quaternion
def carla_rotation_to_RPY(carla_rotation):
"""
Convert a carla rotation to a roll, pitch, yaw tuple
Considers the conversion from left-handed system (unreal) to right-handed
system (ROS).
Considers the conversion from degrees (carla) to radians (ROS).
:param carla_rotation: the carla rotation
:type carla_rotation: carla.Rotation
:return: a tuple with 3 elements (roll, pitch, yaw)
:rtype: tuple
"""
roll = math.radians(carla_rotation.roll)
pitch = -math.radians(carla_rotation.pitch)
yaw = -math.radians(carla_rotation.yaw)
return (roll, pitch, yaw)
def carla_rotation_to_numpy_quaternion(carla_rotation):
"""
Convert a carla rotation to a numpy quaternion
Considers the conversion from left-handed system (unreal) to right-handed
system (ROS).
Considers the conversion from degrees (carla) to radians (ROS).
:param carla_rotation: the carla rotation
:type carla_rotation: carla.Rotation
:return: a numpy.array with 4 elements (quaternion)
:rtype: numpy.array
"""
roll, pitch, yaw = carla_rotation_to_RPY(carla_rotation)
quat = tf.transformations.quaternion_from_euler(roll, pitch, yaw)
return quat
def carla_rotation_to_ros_quaternion(carla_rotation):
"""
Convert a carla rotation to a ROS quaternion
Considers the conversion from left-handed system (unreal) to right-handed
system (ROS).
Considers the conversion from degrees (carla) to radians (ROS).
:param carla_rotation: the carla rotation
:type carla_rotation: carla.Rotation
:return: a ROS quaternion
:rtype: geometry_msgs.msg.Quaternion
"""
quat = carla_rotation_to_numpy_quaternion(carla_rotation)
ros_quaternion = numpy_quaternion_to_ros_quaternion(quat)
return ros_quaternion
def carla_rotation_to_numpy_rotation_matrix(carla_rotation):
"""
Convert a carla rotation to a ROS quaternion
Considers the conversion from left-handed system (unreal) to right-handed
system (ROS).
Considers the conversion from degrees (carla) to radians (ROS).
:param carla_rotation: the carla rotation
:type carla_rotation: carla.Rotation
:return: a numpy.array with 3x3 elements
:rtype: numpy.array
"""
roll, pitch, yaw = carla_rotation_to_RPY(carla_rotation)
numpy_array = tf.transformations.euler_matrix(roll, pitch, yaw)
rotation_matrix = numpy_array[:3, :3]
return rotation_matrix
def carla_rotation_to_directional_numpy_vector(carla_rotation):
"""
Convert a carla rotation (as orientation) into a numpy directional vector
ros_quaternion = np_quaternion_to_ros_quaternion(quat)
:param carla_rotation: the carla rotation
:type carla_rotation: carla.Rotation
:return: a numpy.array with 3 elements as directional vector
representation of the orientation
:rtype: numpy.array
"""
rotation_matrix = carla_rotation_to_numpy_rotation_matrix(carla_rotation)
directional_vector = numpy.array([1, 0, 0])
rotated_directional_vector = rotation_matrix.dot(directional_vector)
return rotated_directional_vector
def carla_vector_to_ros_vector_rotated(carla_vector, carla_rotation):
"""
Rotate carla vector, return it as ros vector
:param carla_vector: the carla vector
:type carla_vector: carla.Vector3D
:param carla_rotation: the carla rotation
:type carla_rotation: carla.Rotation
:return: rotated ros vector
:rtype: Vector3
"""
rotation_matrix = carla_rotation_to_numpy_rotation_matrix(carla_rotation)
tmp_array = rotation_matrix.dot(numpy.array([carla_vector.x, carla_vector.y, carla_vector.z]))
ros_vector = Vector3()
ros_vector.x = tmp_array[0]
ros_vector.y = -tmp_array[1]
ros_vector.z = tmp_array[2]
return ros_vector
def carla_velocity_to_ros_twist(carla_linear_velocity, carla_angular_velocity, carla_rotation):
"""
Convert a carla velocity to a ROS twist
Considers the conversion from left-handed system (unreal) to right-handed
system (ROS).
:param carla_velocity: the carla velocity
:type carla_velocity: carla.Vector3D
:param carla_angular_velocity: the carla angular velocity
:type carla_angular_velocity: carla.Vector3D
:param carla_rotation: the carla rotation
:type carla_rotation: carla.Rotation
:return: a ROS twist (with rotation)
:rtype: geometry_msgs.msg.Twist
"""
ros_twist = Twist()
ros_twist.linear = carla_vector_to_ros_vector_rotated(carla_linear_velocity, carla_rotation)
ros_twist.angular.x = math.radians(carla_angular_velocity.x)
ros_twist.angular.y = -math.radians(carla_angular_velocity.y)
ros_twist.angular.z = -math.radians(carla_angular_velocity.z)
return ros_twist
def carla_velocity_to_numpy_vector(carla_velocity):
"""
Convert a carla velocity to a numpy array
Considers the conversion from left-handed system (unreal) to right-handed
system (ROS)
:param carla_velocity: the carla velocity
:type carla_velocity: carla.Vector3D
:return: a numpy.array with 3 elements
:rtype: numpy.array
"""
return numpy.array([
carla_velocity.x,
-carla_velocity.y,
carla_velocity.z
])
def carla_acceleration_to_ros_accel(carla_acceleration):
"""
Convert a carla acceleration to a ROS accel
Considers the conversion from left-handed system (unreal) to right-handed
system (ROS)
The angular accelerations remain zero.
:param carla_acceleration: the carla acceleration
:type carla_acceleration: carla.Vector3D
:return: a ROS accel
:rtype: geometry_msgs.msg.Accel
"""
ros_accel = Accel()
ros_accel.linear.x = carla_acceleration.x
ros_accel.linear.y = -carla_acceleration.y
ros_accel.linear.z = carla_acceleration.z
return ros_accel
def carla_transform_to_ros_transform(carla_transform):
"""
Convert a carla transform to a ROS transform
See carla_location_to_ros_vector3() and carla_rotation_to_ros_quaternion() for details
:param carla_transform: the carla transform
:type carla_transform: carla.Transform
:return: a ROS transform
:rtype: geometry_msgs.msg.Transform
"""
ros_transform = Transform()
ros_transform.translation = carla_location_to_ros_vector3(
carla_transform.location)
ros_transform.rotation = carla_rotation_to_ros_quaternion(
carla_transform.rotation)
return ros_transform
def carla_transform_to_ros_pose(carla_transform):
"""
Convert a carla transform to a ROS pose
See carla_location_to_ros_point() and carla_rotation_to_ros_quaternion() for details
:param carla_transform: the carla transform
:type carla_transform: carla.Transform
:return: a ROS pose
:rtype: geometry_msgs.msg.Pose
"""
ros_pose = Pose()
ros_pose.position = carla_location_to_ros_point(
carla_transform.location)
ros_pose.orientation = carla_rotation_to_ros_quaternion(
carla_transform.rotation)
return ros_pose
def carla_location_to_pose(carla_location):
"""
Convert a carla location to a ROS pose
See carla_location_to_ros_point() for details.
pose quaternion remains zero.
:param carla_location: the carla location
:type carla_location: carla.Location
:return: a ROS pose
:rtype: geometry_msgs.msg.Pose
"""
ros_pose = Pose()
ros_pose.position = carla_location_to_ros_point(carla_location)
return ros_pose
| [
"geometry_msgs.msg.Vector3",
"geometry_msgs.msg.Twist",
"math.radians",
"geometry_msgs.msg.Transform",
"numpy.array",
"geometry_msgs.msg.Point",
"geometry_msgs.msg.Quaternion",
"tf.transformations.quaternion_from_euler",
"tf.transformations.euler_matrix",
"geometry_msgs.msg.Accel",
"geometry_msg... | [((2477, 2545), 'numpy.array', 'numpy.array', (['[carla_location.x, -carla_location.y, carla_location.z]'], {}), '([carla_location.x, -carla_location.y, carla_location.z])\n', (2488, 2545), False, 'import numpy\n'), ((2962, 2971), 'geometry_msgs.msg.Vector3', 'Vector3', ([], {}), '()\n', (2969, 2971), False, 'from geometry_msgs.msg import Vector3, Quaternion, Transform, Pose, Point, Twist, Accel\n'), ((3496, 3503), 'geometry_msgs.msg.Point', 'Point', ([], {}), '()\n', (3501, 3503), False, 'from geometry_msgs.msg import Vector3, Quaternion, Transform, Pose, Point, Twist, Accel\n'), ((3954, 3966), 'geometry_msgs.msg.Quaternion', 'Quaternion', ([], {}), '()\n', (3964, 3966), False, 'from geometry_msgs.msg import Vector3, Quaternion, Transform, Pose, Point, Twist, Accel\n'), ((4621, 4654), 'math.radians', 'math.radians', (['carla_rotation.roll'], {}), '(carla_rotation.roll)\n', (4633, 4654), False, 'import math\n'), ((5308, 5366), 'tf.transformations.quaternion_from_euler', 'tf.transformations.quaternion_from_euler', (['roll', 'pitch', 'yaw'], {}), '(roll, pitch, yaw)\n', (5348, 5366), False, 'import tf\n'), ((6509, 6558), 'tf.transformations.euler_matrix', 'tf.transformations.euler_matrix', (['roll', 'pitch', 'yaw'], {}), '(roll, pitch, yaw)\n', (6540, 6558), False, 'import tf\n'), ((7169, 7191), 'numpy.array', 'numpy.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (7180, 7191), False, 'import numpy\n'), ((7855, 7864), 'geometry_msgs.msg.Vector3', 'Vector3', ([], {}), '()\n', (7862, 7864), False, 'from geometry_msgs.msg import Vector3, Quaternion, Transform, Pose, Point, Twist, Accel\n'), ((8618, 8625), 'geometry_msgs.msg.Twist', 'Twist', ([], {}), '()\n', (8623, 8625), False, 'from geometry_msgs.msg import Vector3, Quaternion, Transform, Pose, Point, Twist, Accel\n'), ((8749, 8787), 'math.radians', 'math.radians', (['carla_angular_velocity.x'], {}), '(carla_angular_velocity.x)\n', (8761, 8787), False, 'import math\n'), ((9319, 9387), 'numpy.array', 'numpy.array', (['[carla_velocity.x, -carla_velocity.y, carla_velocity.z]'], {}), '([carla_velocity.x, -carla_velocity.y, carla_velocity.z])\n', (9330, 9387), False, 'import numpy\n'), ((9857, 9864), 'geometry_msgs.msg.Accel', 'Accel', ([], {}), '()\n', (9862, 9864), False, 'from geometry_msgs.msg import Vector3, Quaternion, Transform, Pose, Point, Twist, Accel\n'), ((10421, 10432), 'geometry_msgs.msg.Transform', 'Transform', ([], {}), '()\n', (10430, 10432), False, 'from geometry_msgs.msg import Vector3, Quaternion, Transform, Pose, Point, Twist, Accel\n'), ((11022, 11028), 'geometry_msgs.msg.Pose', 'Pose', ([], {}), '()\n', (11026, 11028), False, 'from geometry_msgs.msg import Vector3, Quaternion, Transform, Pose, Point, Twist, Accel\n'), ((11586, 11592), 'geometry_msgs.msg.Pose', 'Pose', ([], {}), '()\n', (11590, 11592), False, 'from geometry_msgs.msg import Vector3, Quaternion, Transform, Pose, Point, Twist, Accel\n'), ((4668, 4702), 'math.radians', 'math.radians', (['carla_rotation.pitch'], {}), '(carla_rotation.pitch)\n', (4680, 4702), False, 'import math\n'), ((4714, 4746), 'math.radians', 'math.radians', (['carla_rotation.yaw'], {}), '(carla_rotation.yaw)\n', (4726, 4746), False, 'import math\n'), ((7775, 7836), 'numpy.array', 'numpy.array', (['[carla_vector.x, carla_vector.y, carla_vector.z]'], {}), '([carla_vector.x, carla_vector.y, carla_vector.z])\n', (7786, 7836), False, 'import numpy\n'), ((8815, 8853), 'math.radians', 'math.radians', (['carla_angular_velocity.y'], {}), '(carla_angular_velocity.y)\n', (8827, 8853), False, 'import math\n'), ((8881, 8919), 'math.radians', 'math.radians', (['carla_angular_velocity.z'], {}), '(carla_angular_velocity.z)\n', (8893, 8919), False, 'import math\n')] |
import numpy as np
class KNearestNeighbors:
def __init__(self, distances, labels, k=10):
self.distances = distances
self.labels = labels
self.k = k
def _kNN(self, instance, train, k):
nearest = np.argpartition(self.distances[instance][train], k)
nearest_labels = self.labels[train][nearest[:k]]
unique, counts = np.unique(nearest_labels, return_counts=True)
counts = dict(zip(unique, counts))
probabilities = np.zeros(10)
for i in range(10):
probabilities[i] = 0 if i not in counts else counts[i] / k
return probabilities
def score(self, train, test):
correct = 0
total = 0
confusion = np.zeros((10,10))
# choose k to be at most as large as supported by the training dataset
# or as configured, if enough training samples are available
k = min(len(train)//10, self.k)
for i in test:
probs = self._kNN(i, train, k)
pred = np.argmax(probs)
confusion[self.labels[i]][pred] += 1
if pred == self.labels[i]:
correct += 1
total += 1
accuracy = correct / total
return accuracy, confusion
class KNearestNeighborsTrainTest(KNearestNeighbors):
def __init__(self, distances, train_labels, test_labels, k=10):
self.test_labels = test_labels
super().__init__(distances, train_labels, k)
def score(self, train):
correct = 0
total = 0
confusion = np.zeros((10,10))
# choose k to be at most as large as supported by the training dataset
# or as configured, if enough training samples are available
k = min(len(train)//10, self.k)
for i, label in enumerate(self.test_labels):
probs = self._kNN(i, train, k)
pred = np.argmax(probs)
confusion[label][pred] += 1
if pred == label:
correct += 1
total += 1
accuracy = correct / total
return accuracy, confusion
| [
"numpy.argmax",
"numpy.zeros",
"numpy.unique",
"numpy.argpartition"
] | [((238, 289), 'numpy.argpartition', 'np.argpartition', (['self.distances[instance][train]', 'k'], {}), '(self.distances[instance][train], k)\n', (253, 289), True, 'import numpy as np\n'), ((372, 417), 'numpy.unique', 'np.unique', (['nearest_labels'], {'return_counts': '(True)'}), '(nearest_labels, return_counts=True)\n', (381, 417), True, 'import numpy as np\n'), ((494, 506), 'numpy.zeros', 'np.zeros', (['(10)'], {}), '(10)\n', (502, 506), True, 'import numpy as np\n'), ((741, 759), 'numpy.zeros', 'np.zeros', (['(10, 10)'], {}), '((10, 10))\n', (749, 759), True, 'import numpy as np\n'), ((1565, 1583), 'numpy.zeros', 'np.zeros', (['(10, 10)'], {}), '((10, 10))\n', (1573, 1583), True, 'import numpy as np\n'), ((1032, 1048), 'numpy.argmax', 'np.argmax', (['probs'], {}), '(probs)\n', (1041, 1048), True, 'import numpy as np\n'), ((1886, 1902), 'numpy.argmax', 'np.argmax', (['probs'], {}), '(probs)\n', (1895, 1902), True, 'import numpy as np\n')] |
# coding: utf-8
# In[1]:
from path import Path
from matplotlib import pyplot as plt
import numpy as np
import skimage.io as io
import os
from PIL import Image
import cv2
import random
import shutil
def crop_by_sequence(image_path,img_class_path,crop_size_w,crop_size_h,prefix,save_dir ,same_scale = False):
"""
image_path : the image you want to crop
img_class_path: the mask you want to crop
crop_size_h: the size of height you want
crop_size_w: the size of weight you want
save_dir: the dir you want to save
prefix: the special word you want to add
same_scale: big or small to same
"""
raw_img = io.imread(image_path,)[:,:,1:]
raw_img_class = io.imread(img_class_path,)
if same_scale == True:
crop_size_w = crop_size_w * 2
crop_size_h = crop_size_h * 2
print(raw_img.shape,raw_img_class.shape)
h,w,c = raw_img.shape[0],raw_img.shape[1],raw_img.shape[2]
index = 0
x2,y2 = 0,0
x0,y0 = 0,0
while(y2<h):
while(x2<w):
x1 = x0
x2 = x1 + crop_size_w
y1 = y0
y2 = y1 +crop_size_h
if(x2>w or y2>h):
x2 = min(x2,w)
y2 = min(y2,h)
if((x2-x1)>10 and (y2-y1)>10):
backgroud = np.zeros((crop_size_h,crop_size_w,c),dtype=np.uint8)
backgroud[:y2-y1,:x2-x1,:] = raw_img[y1:y2,x1:x2,:]
patch = backgroud
backgroud_label = np.zeros((crop_size_h,crop_size_w),dtype=np.uint8)
backgroud_label[:y2-y1,:x2-x1] = raw_img_class[y1:y2,x1:x2]
patch_label = backgroud_label
else:
break
else:
patch = raw_img[y1:y2,x1:x2,:]
patch_label = raw_img_class[y1:y2,x1:x2]
#stride_h = auto_stride(patch_label)
stride_h = crop_size_h
stride_w = crop_size_w
#print "current stride: ",stride_h
x0 = x1 + stride_w
if same_scale == True:
patch = cv2.resize(patch,(int(crop_size_w/2), int(crop_size_h/2)))
patch_label = cv2.resize(patch_label,(int(crop_size_w/2), int(crop_size_h/2)))
success = cv2.imwrite(save_dir + f'/images/{prefix}_sequence_{index}.png',patch)
success_1 = cv2.imwrite(save_dir + f'/labels/{prefix}_sequence_{index}.png',patch_label)
if success == 1 and success_1 ==1 :
pass
else:
print('seq_save err')
index = index + 1
x0,x1,x2 = 0,0,0
y0 = y1 + stride_h
def crop_by_random(num,image_path,img_class_path,crop_size_w,crop_size_h,prefix,save_dir, same_scale = False ):
"""
image_path : the image you want to crop
img_class_path: the mask you want to crop
crop_size_h: the size of height you want
crop_size_w: the size of weight you want
save_dir: the dir you want to save
prefix: the special word you want to add
same_scale: big or small to same
"""
if same_scale == True:
crop_size_w = crop_size_w * 2
crop_size_h = crop_size_h * 2
raw_img = io.imread(image_path,)[:,:,1:]
raw_img_class = io.imread(img_class_path)
print(raw_img.shape, raw_img_class.shape)
h,w,c = raw_img.shape[0],raw_img.shape[1],raw_img.shape[2]
index = 0
range_h = h - crop_size_h - 1
range_w = w - crop_size_w - 1
list_x = np.random.randint(low = 0, high = range_h, size = num)
list_y = np.random.randint(low = 0, high = range_w, size = num)
combine = list(zip(list_x,list_y))
for i in combine:
patch = raw_img[i[0]:i[0] + crop_size_h, i[1]:i[1] + crop_size_w,:]
patch_label = raw_img_class[i[0]:i[0] + crop_size_h, i[1]:i[1] + crop_size_w]
if same_scale == True:
patch = cv2.resize(patch,(int(crop_size_w/2), int(crop_size_h/2)))
patch_label = cv2.resize(patch_label,(int(crop_size_w/2), int(crop_size_h/2)))
success = cv2.imwrite(save_dir + f'/images/{prefix}_random_{index}.png',patch)
success_1 = cv2.imwrite(f'{save_dir}/labels/{prefix}_random_{index}.png',patch_label)
if success == 1 and success_1 ==1 :
pass
else:
print('random save err', success, success_1)
index = index + 1
def generate(ds_file:list, num = 1000,split = 5, crop_size_h = 512, crop_size_w = 512, save_dir = 'dataset',string = '', same_scale = False, ):
"""
num: the number of pictures split by random crop
split: trainset : validationset
crop_size_h: the size of height you want
crop_size_w: the size of weight you want
save_dir: the dir you want to save
string: the special word you want to add
same_scale: big or small to same
"""
print(crop_size_h, crop_size_w)
os.mkdir(f'./{save_dir}/')
os.mkdir(f'./{save_dir}/training')
os.mkdir(f'./{save_dir}/training/images')
os.mkdir(f'./{save_dir}/training/labels')
os.mkdir(f'./{save_dir}/validation')
os.mkdir(f'./{save_dir}/validation/images')
os.mkdir(f'./{save_dir}/validation/labels')
for f in ds_file:
images = [i for i in Path(f'{f}/').files() if len(str(i.name)) == 45]
if 'train' in f:
ge_save_dir = save_dir + '/training'
else:
ge_save_dir = save_dir +'/validation'
for i in range(len(images)):
image_path = images[i]
img_class_path = f'{f}/' + f'{images[i].stem[:-4]}'+ '_label_mask.png'
prefix = f"picture_{i}"
prefix = string + prefix
print(image_path)
print(img_class_path)
crop_by_random(num,image_path,img_class_path,crop_size_w,crop_size_h,prefix,ge_save_dir, same_scale = same_scale )
crop_by_sequence(image_path,img_class_path,crop_size_w,crop_size_h,prefix,ge_save_dir, same_scale = same_scale)
if split == True:
## split the train dataset and validation dataset
img_sample = random.sample(Path(f'./{save_dir}/training/images/').files(),len(Path(f'./{save_dir}/training/images/').files())//split )
train_img_dir = f'./{save_dir}/training/images/'
train_label_dir = f'./{save_dir}/training/labels/'
val_img_dir = f'./{save_dir}/validation/images/'
val_label_dir = f'./{save_dir}/validation/labels/'
for i in sample:
shutil.move(train_img_dir + i.name,f'{val_img_dir}{i.name}')
shutil.move(train_label_dir + i.name ,f'{val_label_dir}{i.name}')
generate(ds_file = ['train_set', 'val_set'])
| [
"cv2.imwrite",
"shutil.move",
"path.Path",
"skimage.io.imread",
"numpy.random.randint",
"numpy.zeros",
"os.mkdir"
] | [((703, 728), 'skimage.io.imread', 'io.imread', (['img_class_path'], {}), '(img_class_path)\n', (712, 728), True, 'import skimage.io as io\n'), ((3340, 3365), 'skimage.io.imread', 'io.imread', (['img_class_path'], {}), '(img_class_path)\n', (3349, 3365), True, 'import skimage.io as io\n'), ((3576, 3624), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(0)', 'high': 'range_h', 'size': 'num'}), '(low=0, high=range_h, size=num)\n', (3593, 3624), True, 'import numpy as np\n'), ((3644, 3692), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(0)', 'high': 'range_w', 'size': 'num'}), '(low=0, high=range_w, size=num)\n', (3661, 3692), True, 'import numpy as np\n'), ((4995, 5021), 'os.mkdir', 'os.mkdir', (['f"""./{save_dir}/"""'], {}), "(f'./{save_dir}/')\n", (5003, 5021), False, 'import os\n'), ((5026, 5060), 'os.mkdir', 'os.mkdir', (['f"""./{save_dir}/training"""'], {}), "(f'./{save_dir}/training')\n", (5034, 5060), False, 'import os\n'), ((5065, 5106), 'os.mkdir', 'os.mkdir', (['f"""./{save_dir}/training/images"""'], {}), "(f'./{save_dir}/training/images')\n", (5073, 5106), False, 'import os\n'), ((5111, 5152), 'os.mkdir', 'os.mkdir', (['f"""./{save_dir}/training/labels"""'], {}), "(f'./{save_dir}/training/labels')\n", (5119, 5152), False, 'import os\n'), ((5157, 5193), 'os.mkdir', 'os.mkdir', (['f"""./{save_dir}/validation"""'], {}), "(f'./{save_dir}/validation')\n", (5165, 5193), False, 'import os\n'), ((5198, 5241), 'os.mkdir', 'os.mkdir', (['f"""./{save_dir}/validation/images"""'], {}), "(f'./{save_dir}/validation/images')\n", (5206, 5241), False, 'import os\n'), ((5246, 5289), 'os.mkdir', 'os.mkdir', (['f"""./{save_dir}/validation/labels"""'], {}), "(f'./{save_dir}/validation/labels')\n", (5254, 5289), False, 'import os\n'), ((652, 673), 'skimage.io.imread', 'io.imread', (['image_path'], {}), '(image_path)\n', (661, 673), True, 'import skimage.io as io\n'), ((3289, 3310), 'skimage.io.imread', 'io.imread', (['image_path'], {}), '(image_path)\n', (3298, 3310), True, 'import skimage.io as io\n'), ((4160, 4229), 'cv2.imwrite', 'cv2.imwrite', (["(save_dir + f'/images/{prefix}_random_{index}.png')", 'patch'], {}), "(save_dir + f'/images/{prefix}_random_{index}.png', patch)\n", (4171, 4229), False, 'import cv2\n'), ((4249, 4323), 'cv2.imwrite', 'cv2.imwrite', (['f"""{save_dir}/labels/{prefix}_random_{index}.png"""', 'patch_label'], {}), "(f'{save_dir}/labels/{prefix}_random_{index}.png', patch_label)\n", (4260, 4323), False, 'import cv2\n'), ((2339, 2410), 'cv2.imwrite', 'cv2.imwrite', (["(save_dir + f'/images/{prefix}_sequence_{index}.png')", 'patch'], {}), "(save_dir + f'/images/{prefix}_sequence_{index}.png', patch)\n", (2350, 2410), False, 'import cv2\n'), ((2434, 2511), 'cv2.imwrite', 'cv2.imwrite', (["(save_dir + f'/labels/{prefix}_sequence_{index}.png')", 'patch_label'], {}), "(save_dir + f'/labels/{prefix}_sequence_{index}.png', patch_label)\n", (2445, 2511), False, 'import cv2\n'), ((6581, 6642), 'shutil.move', 'shutil.move', (['(train_img_dir + i.name)', 'f"""{val_img_dir}{i.name}"""'], {}), "(train_img_dir + i.name, f'{val_img_dir}{i.name}')\n", (6592, 6642), False, 'import shutil\n'), ((6654, 6719), 'shutil.move', 'shutil.move', (['(train_label_dir + i.name)', 'f"""{val_label_dir}{i.name}"""'], {}), "(train_label_dir + i.name, f'{val_label_dir}{i.name}')\n", (6665, 6719), False, 'import shutil\n'), ((1324, 1379), 'numpy.zeros', 'np.zeros', (['(crop_size_h, crop_size_w, c)'], {'dtype': 'np.uint8'}), '((crop_size_h, crop_size_w, c), dtype=np.uint8)\n', (1332, 1379), True, 'import numpy as np\n'), ((1526, 1578), 'numpy.zeros', 'np.zeros', (['(crop_size_h, crop_size_w)'], {'dtype': 'np.uint8'}), '((crop_size_h, crop_size_w), dtype=np.uint8)\n', (1534, 1578), True, 'import numpy as np\n'), ((6204, 6242), 'path.Path', 'Path', (['f"""./{save_dir}/training/images/"""'], {}), "(f'./{save_dir}/training/images/')\n", (6208, 6242), False, 'from path import Path\n'), ((5346, 5359), 'path.Path', 'Path', (['f"""{f}/"""'], {}), "(f'{f}/')\n", (5350, 5359), False, 'from path import Path\n'), ((6255, 6293), 'path.Path', 'Path', (['f"""./{save_dir}/training/images/"""'], {}), "(f'./{save_dir}/training/images/')\n", (6259, 6293), False, 'from path import Path\n')] |
import cProfile
import functools
import pstats
import resource
import signal
import time
from typing import Any, Callable
# This list is passed to @profile() which aggregates the cumulative runtime
# into these functions, which represent the primary stages of task solutioning.
PROFILE_BREAKOUT_STD: list[str] = [
"Task:decompose",
"Task:link",
"Task:solve",
"Task:test",
]
def profile(
threshold: float = 0.0, names: list[str] | None = None, dump_file: str | None = None
) -> Callable[[Any], Any]:
"""Measure where cumulative time is spent.
Args:
threshold: minimum total cumulative time to display a function
names: only display functions containing one of these substrings
"""
def inner(func: Callable[[Any], Any]) -> Callable[[Any], Any]:
@functools.wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> tuple[Any, list[tuple[str, float]]]:
# Begin profiling by enabling the profiler
pr = cProfile.Profile()
pr.enable()
# The call we are profiling
result = func(*args, **kwargs)
# Stop profiling and analyze the results
pr.disable()
ps = pstats.Stats(pr)
ps.strip_dirs()
if dump_file:
ps.dump_stats(dump_file)
# NOTE: PStats doesn't appear to use typing, thus the ignores
tot_time: float = max([row[3] for row in ps.stats.values()]) # type: ignore
stats: list[tuple[str, float]] = []
for func_triple, data in ps.stats.items(): # type: ignore
filename = f"{func_triple[0].replace('.py', '').capitalize()}" # type: ignore
func_name = f"{filename}:{func_triple[2]}"
cum_frac: float = round(data[3] / tot_time, 6) # type: ignore
if cum_frac > threshold and (
names is None or any([name in func_name for name in names])
):
stats.append((func_name, cum_frac))
return result, stats
return wrapper
return inner
def get_mem() -> int:
return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
class TimeoutException(Exception):
pass
def time_limit(seconds: int = 5) -> Callable[[Any], Any]:
"""Limit the runtime of the function to the specified number of seconds"""
def signal_handler(signum: int, frame: Any):
raise TimeoutException("Timed out!")
def inner(func: Callable[[Any], Any]) -> Callable[[Any], Any]:
"""Wraps a function and throws a Timeout exception if it runs too long"""
@functools.wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> tuple[Any, float]:
# Begin a signal alarm (
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(seconds)
start = time.time()
# The call we are limiting
try:
result = func(*args, **kwargs)
except TimeoutException as exc:
print(f"{exc}: Timed out after {seconds}s")
return None, seconds
return result, time.time() - start
return wrapper
return inner
| [
"signal.signal",
"resource.getrusage",
"functools.wraps",
"pstats.Stats",
"signal.alarm",
"cProfile.Profile",
"time.time"
] | [((809, 830), 'functools.wraps', 'functools.wraps', (['func'], {}), '(func)\n', (824, 830), False, 'import functools\n'), ((2152, 2192), 'resource.getrusage', 'resource.getrusage', (['resource.RUSAGE_SELF'], {}), '(resource.RUSAGE_SELF)\n', (2170, 2192), False, 'import resource\n'), ((2643, 2664), 'functools.wraps', 'functools.wraps', (['func'], {}), '(func)\n', (2658, 2664), False, 'import functools\n'), ((990, 1008), 'cProfile.Profile', 'cProfile.Profile', ([], {}), '()\n', (1006, 1008), False, 'import cProfile\n'), ((1213, 1229), 'pstats.Stats', 'pstats.Stats', (['pr'], {}), '(pr)\n', (1225, 1229), False, 'import pstats\n'), ((2783, 2828), 'signal.signal', 'signal.signal', (['signal.SIGALRM', 'signal_handler'], {}), '(signal.SIGALRM, signal_handler)\n', (2796, 2828), False, 'import signal\n'), ((2841, 2862), 'signal.alarm', 'signal.alarm', (['seconds'], {}), '(seconds)\n', (2853, 2862), False, 'import signal\n'), ((2883, 2894), 'time.time', 'time.time', ([], {}), '()\n', (2892, 2894), False, 'import time\n'), ((3168, 3179), 'time.time', 'time.time', ([], {}), '()\n', (3177, 3179), False, 'import time\n')] |
# -*- coding: utf-8 -*-
#Requires Win32 Python Extensions
import os
import servicemanager
import shutil
import subprocess
import sys
import win32api
import win32event
import win32service
import win32serviceutil
import tempfile
class VulnService(win32serviceutil.ServiceFramework):
_svc_name_ = "VulnService"
_svc_display_name_ = "Vulnerable Service"
_svc_description_ = ("Executes VBScripts and BAT files at regular intervals." +
"What could possibly go wrong?")
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
self.counter = 0
#Here we put the contents of the batch file to be run.
self.dos_script = """
@echo off
prompt $
echo -------------------------------------------------------------------------------
echo Running Processes:
tasklist
echo -------------------------------------------------------------------------------
netstat -oa
echo -------------------------------------------------------------------------------
echo Available Hosts:
net view
echo -------------------------------------------------------------------------------
echo Admin Users:
net localgroup administrators
exit
"""
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, 'Service is starting'))
# Fire every minute
self.timeout = 1000 * 60
while True:
# Wait for service stop signal, otherwise loop again
ret_code = win32event.WaitForSingleObject(self.hWaitStop, self.timeout)
# If stop signal encountered, quit
if ret_code == win32event.WAIT_OBJECT_0:
servicemanager.LogInfoMsg("Service is stopping")
break
# Otherwise, run our scripts and log the results to the event log
else:
self.counter += 1
log_output = "VulnService - %d loops and counting\n\n" % self.counter
log_output += self.vbs_task() + "\n\n"
log_output += self.dos_task()
servicemanager.LogInfoMsg(log_output)
def vbs_task(self):
# this function will make a copy of the vulnservice_task.vbs script that is in the same dirctory as the compiled
# Python program, copy it to %temp% of the user or service account the service is running under and execute it.
script_name = "vulnservice_task.vbs"
script_srcpath = "%s\\%s" % (os.path.dirname(sys.argv[0]), script_name)
script_dstpath = "%s\\%s" % (os.environ['TEMP'], script_name)
shutil.copyfile(script_srcpath, script_dstpath)
output = subprocess.check_output("wscript.exe %s" % script_dstpath, shell=False, stderr=subprocess.STDOUT)
os.unlink(script_dstpath)
return output
def dos_task(self):
# This function writes the contentes of the batch script to a file and executes it
# script_dstpath = "C:\\TEMP\\vulnservice_task.bat"
script_dstpath = os.path.join(tempfile.gettempdir(), "vulnservice_task.bat")
with open (script_dstpath, "w") as bat_file:
bat_file.write(self.dos_script)
output = subprocess.check_output("cmd.exe /k %s" % script_dstpath, shell=False, stderr=subprocess.STDOUT)
os.unlink(script_dstpath)
return output
def ctrlHandler(ctrlType):
return True
if __name__ == '__main__':
win32api.SetConsoleCtrlHandler(ctrlHandler, True)
win32serviceutil.HandleCommandLine(VulnService)
| [
"subprocess.check_output",
"servicemanager.LogInfoMsg",
"win32serviceutil.HandleCommandLine",
"servicemanager.LogMsg",
"win32event.WaitForSingleObject",
"win32serviceutil.ServiceFramework.__init__",
"shutil.copyfile",
"os.path.dirname",
"tempfile.gettempdir",
"win32api.SetConsoleCtrlHandler",
"o... | [((4090, 4139), 'win32api.SetConsoleCtrlHandler', 'win32api.SetConsoleCtrlHandler', (['ctrlHandler', '(True)'], {}), '(ctrlHandler, True)\n', (4120, 4139), False, 'import win32api\n'), ((4149, 4196), 'win32serviceutil.HandleCommandLine', 'win32serviceutil.HandleCommandLine', (['VulnService'], {}), '(VulnService)\n', (4183, 4196), False, 'import win32serviceutil\n'), ((576, 630), 'win32serviceutil.ServiceFramework.__init__', 'win32serviceutil.ServiceFramework.__init__', (['self', 'args'], {}), '(self, args)\n', (618, 630), False, 'import win32serviceutil\n'), ((657, 697), 'win32event.CreateEvent', 'win32event.CreateEvent', (['None', '(0)', '(0)', 'None'], {}), '(None, 0, 0, None)\n', (679, 697), False, 'import win32event\n'), ((1577, 1612), 'win32event.SetEvent', 'win32event.SetEvent', (['self.hWaitStop'], {}), '(self.hWaitStop)\n', (1596, 1612), False, 'import win32event\n'), ((1683, 1832), 'servicemanager.LogMsg', 'servicemanager.LogMsg', (['servicemanager.EVENTLOG_INFORMATION_TYPE', 'servicemanager.PYS_SERVICE_STARTED', "(self._svc_name_, 'Service is starting')"], {}), "(servicemanager.EVENTLOG_INFORMATION_TYPE,\n servicemanager.PYS_SERVICE_STARTED, (self._svc_name_,\n 'Service is starting'))\n", (1704, 1832), False, 'import servicemanager\n'), ((3185, 3232), 'shutil.copyfile', 'shutil.copyfile', (['script_srcpath', 'script_dstpath'], {}), '(script_srcpath, script_dstpath)\n', (3200, 3232), False, 'import shutil\n'), ((3251, 3352), 'subprocess.check_output', 'subprocess.check_output', (["('wscript.exe %s' % script_dstpath)"], {'shell': '(False)', 'stderr': 'subprocess.STDOUT'}), "('wscript.exe %s' % script_dstpath, shell=False,\n stderr=subprocess.STDOUT)\n", (3274, 3352), False, 'import subprocess\n'), ((3361, 3386), 'os.unlink', 'os.unlink', (['script_dstpath'], {}), '(script_dstpath)\n', (3370, 3386), False, 'import os\n'), ((3805, 3905), 'subprocess.check_output', 'subprocess.check_output', (["('cmd.exe /k %s' % script_dstpath)"], {'shell': '(False)', 'stderr': 'subprocess.STDOUT'}), "('cmd.exe /k %s' % script_dstpath, shell=False,\n stderr=subprocess.STDOUT)\n", (3828, 3905), False, 'import subprocess\n'), ((3921, 3946), 'os.unlink', 'os.unlink', (['script_dstpath'], {}), '(script_dstpath)\n', (3930, 3946), False, 'import os\n'), ((2043, 2103), 'win32event.WaitForSingleObject', 'win32event.WaitForSingleObject', (['self.hWaitStop', 'self.timeout'], {}), '(self.hWaitStop, self.timeout)\n', (2073, 2103), False, 'import win32event\n'), ((3629, 3650), 'tempfile.gettempdir', 'tempfile.gettempdir', ([], {}), '()\n', (3648, 3650), False, 'import tempfile\n'), ((2237, 2285), 'servicemanager.LogInfoMsg', 'servicemanager.LogInfoMsg', (['"""Service is stopping"""'], {}), "('Service is stopping')\n", (2262, 2285), False, 'import servicemanager\n'), ((2663, 2700), 'servicemanager.LogInfoMsg', 'servicemanager.LogInfoMsg', (['log_output'], {}), '(log_output)\n', (2688, 2700), False, 'import servicemanager\n'), ((3060, 3088), 'os.path.dirname', 'os.path.dirname', (['sys.argv[0]'], {}), '(sys.argv[0])\n', (3075, 3088), False, 'import os\n')] |
import copy
import logging
import torch
import numpy as np
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
log = logging.getLogger(__name__)
def balanced_batches(dataset, batch_size):
unlabled_idx = dataset.unlabeled_idx
labeled_idx = list(filter(lambda _: _ not in unlabled_idx,
np.arange(len(dataset.targets))))
labeled_idx = np.array(labeled_idx)
# construct batches - half of them should be from unlabled, half from labeled
n_batches = (len(unlabled_idx) // (batch_size//2)) + 1
for ulb in np.array_split(unlabled_idx, n_batches):
batch_idx = list(ulb)
lb = np.random.choice(labeled_idx, size=(
batch_size // 2), replace=True)
batch_idx.extend(lb)
x_batch = []
y_batch = []
for idx in batch_idx:
x, y = dataset[idx]
x_batch.append(x)
y_batch.append(y)
yield torch.stack(x_batch), torch.LongTensor(y_batch)
def balanced_batches_heirarchy(dataset, heirarchy, batch_size):
unlabled_idx = dataset.unlabeled_idx
labeled_idx = list(filter(lambda _: _ not in unlabled_idx,
np.arange(len(dataset.targets))))
labeled_idx = np.array(labeled_idx)
# construct batches - half of them should be from unlabled, half from labeled
n_batches = (len(unlabled_idx) // (batch_size//2)) + 1
for ulb in np.array_split(unlabled_idx, n_batches):
batch_idx = list(ulb)
lb = np.random.choice(labeled_idx, size=(
batch_size // 2), replace=True)
batch_idx.extend(lb)
x_batch = []
y_batch = []
for idx in batch_idx:
x, y = dataset[idx]
x_batch.append(x)
y_batch.append(y)
y_batch = heirarchy.to_vec(torch.LongTensor(y_batch))
yield torch.stack(x_batch), y_batch
class FashionMNIST(datasets.FashionMNIST):
UNLABLED = -1
def __init__(self, root, percent_unlabeled, train=True, transform=None, target_transform=None, download=False):
super().__init__(root, train=train, transform=transform,
target_transform=target_transform, download=download)
assert percent_unlabeled >= 0.0 and percent_unlabeled <= 1.0
if not train:
# no unlabled data in the test set
assert percent_unlabeled == 0.0
self.true_targets = copy.deepcopy(self.targets)
self.percent_unlabeled = percent_unlabeled
log.info("Setting {}% of the targets to UNLABELED".format(
self.percent_unlabeled * 100))
self.unlabeled_idx = np.random.permutation(
np.arange(0, len(self.targets)))[:int(self.percent_unlabeled * len(self.targets))]
self.targets[self.unlabeled_idx] = self.UNLABLED
self.n_classes = len(self.classes)
def sample_labels(self, n):
"""Sample n targets from the labeled data
Arguments:
n {int} -- Number of samples
"""
pass
@staticmethod
def separate_unlabeled(x_raw, y_raw):
if y_raw.ndimension() == 2:
unlabeled_idx = (y_raw == -1).sum(1) > 0
else:
unlabeled_idx = y_raw == FashionMNIST.UNLABLED
x, y = x_raw[~unlabeled_idx], y_raw[~unlabeled_idx]
x_unlab, y_unlab = x_raw[unlabeled_idx], y_raw[unlabeled_idx]
return x, y, x_unlab, y_unlab
class Hierarchy:
def __init__(self, fmnist):
self.org_class_to_idx = fmnist.class_to_idx
self.org_idx_to_class = {
v: k for (k, v) in self.org_class_to_idx.items()}
self.org_n_classes = len(self.org_class_to_idx)
Top = {"T-shirt/top", "Pullover", "Coat", "Shirt"}
Shoes = {"Sandal", "Sneaker", "Ankle boot"}
# simple one level heirarchy for now
self.heirarchy = {
"Top": Top,
"Shoes": Shoes,
"Bag": "Bag",
"Dress": "Dress",
"Trouser": "Trouser",
}
self.class_to_idx = copy.deepcopy(self.org_class_to_idx)
# add new top level classes
self.class_to_idx["Top"] = len(self.class_to_idx)
self.class_to_idx["Shoes"] = len(self.class_to_idx)
self.idx_to_class = {v: k for (k, v) in self.class_to_idx.items()}
self.n_classes = len(self.class_to_idx)
assoc_idx = {}
neg_assoc_idx = {}
all_idx = set(range(self.n_classes))
for clz in self.class_to_idx:
cls_idx = self.class_to_idx[clz]
assoc_idx[cls_idx] = [self.class_to_idx[c]
for c in self.find_classes(clz)]
neg_assoc_idx[cls_idx] = []
for idx in all_idx:
if idx not in assoc_idx[cls_idx]:
neg_assoc_idx[cls_idx].append(idx)
self.assoc_idx = assoc_idx
self.neg_assoc_idx = neg_assoc_idx
def find_classes(self, y, new_classes=None):
if new_classes is None:
new_classes = set()
for k, v in self.heirarchy.items():
if isinstance(v, set) and y in v:
new_classes.add(k)
new_classes.add(y)
elif k == y:
new_classes.add(k)
return new_classes
def to_vec(self, y):
new_y = torch.zeros(y.size(0), self.n_classes)
for idx, y_sub in enumerate(y.detach().numpy()):
if y_sub == -1:
new_y[idx, :] = -1.0
continue
classes = self.find_classes(self.org_idx_to_class[y_sub])
classes_idx = [self.class_to_idx[c] for c in classes]
new_y[idx, classes_idx] = 1.0
return new_y
def from_vector(self, v):
pass
if __name__ == '__main__':
fmnist_transforms = transforms.Compose([
transforms.ToTensor()
])
fmnist = FashionMNIST("./fashion-mnist", 0.5,
transform=fmnist_transforms, download=True)
for x_raw, y_raw in DataLoader(fmnist, batch_size=10):
x, y, x_unlab, y_unlab = FashionMNIST.separate_unlabeled(x_raw, y_raw)
print(x.size(), y.size())
print(x_unlab.size(), y_unlab.size())
break
fmnist = FashionMNIST("./fashion-mnist", 0.998, train=True,
transform=fmnist_transforms, download=True)
for x, y in balanced_batches(fmnist, 16):
print(x.size(), y)
# for x_raw, y_raw in DataLoader(fmnist, batch_size=10):
# x, y, x_unlab, y_unlab = FashionMNIST.separate_unlabeled(x_raw, y_raw)
# print(y, y_unlab)
# print(x.size(), y.size())
# print(x_unlab.size(), y_unlab.size())
| [
"logging.getLogger",
"copy.deepcopy",
"numpy.random.choice",
"torch.LongTensor",
"torch.stack",
"numpy.array_split",
"numpy.array",
"torch.utils.data.DataLoader",
"torchvision.transforms.ToTensor"
] | [((152, 179), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (169, 179), False, 'import logging\n'), ((411, 432), 'numpy.array', 'np.array', (['labeled_idx'], {}), '(labeled_idx)\n', (419, 432), True, 'import numpy as np\n'), ((590, 629), 'numpy.array_split', 'np.array_split', (['unlabled_idx', 'n_batches'], {}), '(unlabled_idx, n_batches)\n', (604, 629), True, 'import numpy as np\n'), ((1262, 1283), 'numpy.array', 'np.array', (['labeled_idx'], {}), '(labeled_idx)\n', (1270, 1283), True, 'import numpy as np\n'), ((1441, 1480), 'numpy.array_split', 'np.array_split', (['unlabled_idx', 'n_batches'], {}), '(unlabled_idx, n_batches)\n', (1455, 1480), True, 'import numpy as np\n'), ((6024, 6057), 'torch.utils.data.DataLoader', 'DataLoader', (['fmnist'], {'batch_size': '(10)'}), '(fmnist, batch_size=10)\n', (6034, 6057), False, 'from torch.utils.data import DataLoader\n'), ((674, 739), 'numpy.random.choice', 'np.random.choice', (['labeled_idx'], {'size': '(batch_size // 2)', 'replace': '(True)'}), '(labeled_idx, size=batch_size // 2, replace=True)\n', (690, 739), True, 'import numpy as np\n'), ((1525, 1590), 'numpy.random.choice', 'np.random.choice', (['labeled_idx'], {'size': '(batch_size // 2)', 'replace': '(True)'}), '(labeled_idx, size=batch_size // 2, replace=True)\n', (1541, 1590), True, 'import numpy as np\n'), ((2442, 2469), 'copy.deepcopy', 'copy.deepcopy', (['self.targets'], {}), '(self.targets)\n', (2455, 2469), False, 'import copy\n'), ((4063, 4099), 'copy.deepcopy', 'copy.deepcopy', (['self.org_class_to_idx'], {}), '(self.org_class_to_idx)\n', (4076, 4099), False, 'import copy\n'), ((1835, 1860), 'torch.LongTensor', 'torch.LongTensor', (['y_batch'], {}), '(y_batch)\n', (1851, 1860), False, 'import torch\n'), ((5850, 5871), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (5869, 5871), False, 'from torchvision import datasets, transforms\n'), ((962, 982), 'torch.stack', 'torch.stack', (['x_batch'], {}), '(x_batch)\n', (973, 982), False, 'import torch\n'), ((984, 1009), 'torch.LongTensor', 'torch.LongTensor', (['y_batch'], {}), '(y_batch)\n', (1000, 1009), False, 'import torch\n'), ((1876, 1896), 'torch.stack', 'torch.stack', (['x_batch'], {}), '(x_batch)\n', (1887, 1896), False, 'import torch\n')] |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the PyMVPA package for the
# copyright and license terms.
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
"""Unit tests for PyMVPA GNB classifier"""
import numpy as np
from mvpa2.testing import *
from mvpa2.testing.datasets import *
from mvpa2.clfs.gnb import GNB
from mvpa2.measures.base import TransferMeasure
from mvpa2.generators.splitters import Splitter
class GNBTests(unittest.TestCase):
def test_gnb(self):
gnb = GNB()
gnb_nc = GNB(common_variance=False)
gnb_n = GNB(normalize=True)
gnb_n_nc = GNB(normalize=True, common_variance=False)
ds = datasets['uni2medium']
# Generic silly coverage just to assure that it works in all
# possible scenarios:
bools = (True, False)
# There should be better way... heh
for cv in bools: # common_variance?
for prior in ('uniform', 'laplacian_smoothing', 'ratio'):
tp = None # predictions -- all above should
# result in the same predictions
for n in bools: # normalized?
for ls in bools: # logspace?
for es in ((), ('estimates')):
gnb_ = GNB(common_variance=cv,
prior=prior,
normalize=n,
logprob=ls,
enable_ca=es)
tm = TransferMeasure(gnb_, Splitter('train'))
predictions = tm(ds).samples[:,0]
if tp is None:
tp = predictions
assert_array_equal(predictions, tp)
# if normalized -- check if estimates are such
if n and 'estimates' in es:
v = gnb_.ca.estimates
if ls: # in log space -- take exp ;)
v = np.exp(v)
d1 = np.sum(v, axis=1) - 1.0
self.assertTrue(np.max(np.abs(d1)) < 1e-5)
def suite():
return unittest.makeSuite(GNBTests)
if __name__ == '__main__':
import runner
| [
"numpy.abs",
"mvpa2.clfs.gnb.GNB",
"numpy.exp",
"numpy.sum",
"mvpa2.generators.splitters.Splitter"
] | [((712, 717), 'mvpa2.clfs.gnb.GNB', 'GNB', ([], {}), '()\n', (715, 717), False, 'from mvpa2.clfs.gnb import GNB\n'), ((735, 761), 'mvpa2.clfs.gnb.GNB', 'GNB', ([], {'common_variance': '(False)'}), '(common_variance=False)\n', (738, 761), False, 'from mvpa2.clfs.gnb import GNB\n'), ((778, 797), 'mvpa2.clfs.gnb.GNB', 'GNB', ([], {'normalize': '(True)'}), '(normalize=True)\n', (781, 797), False, 'from mvpa2.clfs.gnb import GNB\n'), ((817, 859), 'mvpa2.clfs.gnb.GNB', 'GNB', ([], {'normalize': '(True)', 'common_variance': '(False)'}), '(normalize=True, common_variance=False)\n', (820, 859), False, 'from mvpa2.clfs.gnb import GNB\n'), ((1525, 1600), 'mvpa2.clfs.gnb.GNB', 'GNB', ([], {'common_variance': 'cv', 'prior': 'prior', 'normalize': 'n', 'logprob': 'ls', 'enable_ca': 'es'}), '(common_variance=cv, prior=prior, normalize=n, logprob=ls, enable_ca=es)\n', (1528, 1600), False, 'from mvpa2.clfs.gnb import GNB\n'), ((1772, 1789), 'mvpa2.generators.splitters.Splitter', 'Splitter', (['"""train"""'], {}), "('train')\n", (1780, 1789), False, 'from mvpa2.generators.splitters import Splitter\n'), ((2240, 2249), 'numpy.exp', 'np.exp', (['v'], {}), '(v)\n', (2246, 2249), True, 'import numpy as np\n'), ((2279, 2296), 'numpy.sum', 'np.sum', (['v'], {'axis': '(1)'}), '(v, axis=1)\n', (2285, 2296), True, 'import numpy as np\n'), ((2350, 2360), 'numpy.abs', 'np.abs', (['d1'], {}), '(d1)\n', (2356, 2360), True, 'import numpy as np\n')] |
# MIT License
#
# Copyright (c) 2020 <NAME>
#
# 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, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# 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.
# <pep8 compliant>
import pytest
import tempfile
import fakebpy
import bpy
from mathutils import Matrix
from unittest.mock import Mock
from io_mesh_amf.export_amf import ExportAMF
#
# Test model parent/child structure
# vis: visible in viewport
# vie: viewable in viewports
# ren: renderable
#
# empty_012 [vis | --- | ---]
# |
# o-- empty_0 [vis | --- | ren]
# | |
# | o-- cube_0 [vis | --- | ---]
# |
# o-- empty_12 [vis | --- | ren]
# |
# o-- empty_1 [--- | vie | ---]
# | |
# | o-- cube_1 [--- | vie | ---]
# |
# o-- empty_2 [--- | --- | ---]
# |
# o-- cube_2 [--- | --- | ren]
#
class vertex():
co = []
def __init__(self, x, y, z):
self.co = [x, y, z]
class triangle():
vertices = []
def __init__(self, v1, v2, v3):
self.vertices = [v1, v2, v3]
def cube_vertices(x=1):
return [
vertex(x+0, 0, 0),
vertex(x+1, 0, 0),
vertex(x+1, 1, 0),
vertex(x+0, 1, 0),
vertex(x+0, 1, 1),
vertex(x+1, 1, 1),
vertex(x+1, 0, 1),
vertex(x+0, 0, 1)
]
@pytest.fixture
def cube_mesh():
""" cube mesh """
mesh = Mock()
mesh.vertices = cube_vertices()
mesh.loop_triangles = [
triangle(0, 2, 1),
triangle(0, 3, 2),
triangle(2, 3, 4),
triangle(2, 4, 5),
triangle(1, 2, 5),
triangle(1, 5, 6),
triangle(0, 7, 4),
triangle(0, 4, 3),
triangle(5, 4, 7),
triangle(5, 7, 6),
triangle(0, 6, 7),
triangle(0, 1, 6),
]
return mesh
@pytest.fixture
def cube_0(cube_mesh):
""" Visible cube object """
obj = Mock()
obj.name = 'cube_0'
obj.mode = 'OBJECT'
obj.mesh_mock = cube_mesh
obj.to_mesh.return_value = cube_mesh
obj.matrix_world = Matrix.Identity(4)
obj.update_from_editmode = Mock()
obj.evaluated_get = lambda s: s
obj.visible_get.return_value = True
obj.hide_viewport = True
obj.hide_render = True
obj.children = None
return obj
@pytest.fixture
def cube_1(cube_mesh):
""" Viewable cube object shifted to 3 on x """
obj = Mock()
obj.name = 'cube_1'
obj.mode = 'OBJECT'
obj.mesh_mock = cube_mesh
obj.to_mesh.return_value = cube_mesh
obj.matrix_world = Matrix.Identity(4)
obj.mesh_mock.vertices = cube_vertices(3)
obj.update_from_editmode = Mock()
obj.evaluated_get = lambda s: s
obj.visible_get.return_value = False
obj.hide_viewport = False
obj.hide_render = True
obj.children = None
return obj
@pytest.fixture
def cube_2(cube_mesh):
""" Renderable cube object shifted to -3 on x """
obj = Mock()
obj.name = 'cube_2'
obj.mode = 'OBJECT'
obj.mesh_mock = cube_mesh
obj.to_mesh.return_value = cube_mesh
obj.matrix_world = Matrix.Identity(4)
obj.mesh_mock.vertices = cube_vertices(-3)
obj.update_from_editmode = Mock()
obj.evaluated_get = lambda s: s
obj.visible_get.return_value = False
obj.hide_viewport = True
obj.hide_render = False
obj.children = None
return obj
@pytest.fixture
def __empty_0():
""" Empty used as parent of cube_0 """
obj = Mock()
obj.name = 'empty_0'
obj.mode = 'OBJECT'
obj.to_mesh.return_value = None
obj.matrix_world = Matrix.Identity(4)
obj.visible_get.return_value = True
obj.hide_viewport = True
obj.hide_render = False
return obj
@pytest.fixture
def __empty_1():
""" Empty used as parent of cube_1 """
obj = Mock()
obj.name = 'empty_1'
obj.mode = 'OBJECT'
obj.to_mesh.return_value = None
obj.matrix_world = Matrix.Identity(4)
obj.visible_get.return_value = False
obj.hide_viewport = False
obj.hide_render = True
return obj
@pytest.fixture
def __empty_2():
""" Empty used as parent of cube_2 """
obj = Mock()
obj.name = 'empty_2'
obj.mode = 'OBJECT'
obj.to_mesh.return_value = None
obj.matrix_world = Matrix.Identity(4)
obj.visible_get.return_value = False
obj.hide_viewport = True
obj.hide_render = True
return obj
@pytest.fixture
def __empty_12():
""" Empty used as parent of __empty_1 and __empty_2 """
obj = Mock()
obj.name = 'empty_12'
obj.mode = 'OBJECT'
obj.to_mesh.return_value = None
obj.matrix_world = Matrix.Identity(4)
obj.visible_get.return_value = True
obj.hide_viewport = True
obj.hide_render = False
return obj
@pytest.fixture
def __empty_012():
""" Empty used as parent of __empty_0, __empty_1 and __empty_2 """
obj = Mock()
obj.name = 'empty_012'
obj.mode = 'OBJECT'
obj.to_mesh.return_value = None
obj.matrix_world = Matrix.Identity(4)
obj.visible_get.return_value = True
obj.hide_viewport = True
obj.hide_render = True
return obj
@pytest.fixture
def empty_0(cube_0, __empty_0):
__empty_0.children = (cube_0) # Blender children are tuples
cube_0.parent = __empty_0
return __empty_0
@pytest.fixture
def empty_1(cube_1, __empty_1):
__empty_1.children = (cube_1) # Blender children are tuples
cube_1.parent = __empty_1
return __empty_1
@pytest.fixture
def empty_2(cube_2, __empty_2):
__empty_2.children = (cube_2) # Blender children are tuples
cube_2.parent = __empty_2
return __empty_2
@pytest.fixture
def empty_12(__empty_12, empty_1, empty_2):
__empty_12.children = (empty_1, empty_2) # Blender children are tuples
empty_1.parent = __empty_12
empty_2.parent = __empty_12
return __empty_12
@pytest.fixture
def empty_012(__empty_012, empty_0, empty_12):
__empty_012.parent = None
__empty_012.children = (empty_0, empty_12) # Blender children are tuples
empty_0.parent = __empty_012
empty_12.parent = __empty_012
return __empty_012
@pytest.fixture
def context():
""" empty context """
context = Mock()
context.scene.name = "Nom de scene pour test"
return context
@pytest.fixture
def context_cube(context, cube_0):
""" context with cube object """
context.selected_objects = [cube_0]
return context
@pytest.fixture
def export():
""" Export object to test with all default properties """
tempName = f"{tempfile.gettempdir()}/test_export.amf"
exp = ExportAMF()
exp.filepath = tempName
exp.export_strategy = "selection"
exp.export_format = 'native'
exp.group_strategy = 'parents_selected'
exp.use_mesh_modifiers = False
exp.target_unit = 'meter'
return exp
| [
"io_mesh_amf.export_amf.ExportAMF",
"mathutils.Matrix.Identity",
"tempfile.gettempdir",
"unittest.mock.Mock"
] | [((2393, 2399), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (2397, 2399), False, 'from unittest.mock import Mock\n'), ((2893, 2899), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (2897, 2899), False, 'from unittest.mock import Mock\n'), ((3042, 3060), 'mathutils.Matrix.Identity', 'Matrix.Identity', (['(4)'], {}), '(4)\n', (3057, 3060), False, 'from mathutils import Matrix\n'), ((3092, 3098), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (3096, 3098), False, 'from unittest.mock import Mock\n'), ((3372, 3378), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (3376, 3378), False, 'from unittest.mock import Mock\n'), ((3521, 3539), 'mathutils.Matrix.Identity', 'Matrix.Identity', (['(4)'], {}), '(4)\n', (3536, 3539), False, 'from mathutils import Matrix\n'), ((3617, 3623), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (3621, 3623), False, 'from unittest.mock import Mock\n'), ((3902, 3908), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (3906, 3908), False, 'from unittest.mock import Mock\n'), ((4051, 4069), 'mathutils.Matrix.Identity', 'Matrix.Identity', (['(4)'], {}), '(4)\n', (4066, 4069), False, 'from mathutils import Matrix\n'), ((4148, 4154), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (4152, 4154), False, 'from unittest.mock import Mock\n'), ((4416, 4422), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (4420, 4422), False, 'from unittest.mock import Mock\n'), ((4531, 4549), 'mathutils.Matrix.Identity', 'Matrix.Identity', (['(4)'], {}), '(4)\n', (4546, 4549), False, 'from mathutils import Matrix\n'), ((4750, 4756), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (4754, 4756), False, 'from unittest.mock import Mock\n'), ((4865, 4883), 'mathutils.Matrix.Identity', 'Matrix.Identity', (['(4)'], {}), '(4)\n', (4880, 4883), False, 'from mathutils import Matrix\n'), ((5085, 5091), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (5089, 5091), False, 'from unittest.mock import Mock\n'), ((5200, 5218), 'mathutils.Matrix.Identity', 'Matrix.Identity', (['(4)'], {}), '(4)\n', (5215, 5218), False, 'from mathutils import Matrix\n'), ((5437, 5443), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (5441, 5443), False, 'from unittest.mock import Mock\n'), ((5553, 5571), 'mathutils.Matrix.Identity', 'Matrix.Identity', (['(4)'], {}), '(4)\n', (5568, 5571), False, 'from mathutils import Matrix\n'), ((5802, 5808), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (5806, 5808), False, 'from unittest.mock import Mock\n'), ((5919, 5937), 'mathutils.Matrix.Identity', 'Matrix.Identity', (['(4)'], {}), '(4)\n', (5934, 5937), False, 'from mathutils import Matrix\n'), ((7107, 7113), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (7111, 7113), False, 'from unittest.mock import Mock\n'), ((7494, 7505), 'io_mesh_amf.export_amf.ExportAMF', 'ExportAMF', ([], {}), '()\n', (7503, 7505), False, 'from io_mesh_amf.export_amf import ExportAMF\n'), ((7444, 7465), 'tempfile.gettempdir', 'tempfile.gettempdir', ([], {}), '()\n', (7463, 7465), False, 'import tempfile\n')] |
"""
amplitude.py
measure the maximum peak-to-peak amplitude
"""
import obspy
import types
import numpy as np
import pandas as pd
import madpy.noise as n
from typing import Tuple
import madpy.checks as ch
import madpy.config as config
import matplotlib.pyplot as plt
import madpy.plotting.amp as plot
def measure_amplitude(
st: obspy.Stream,
cfg: types.ModuleType = config,
) -> pd.DataFrame:
"""Measure noise level and amplitude
Args:
st: stream containing one or more time series
cfg: configuration file
Returns:
df: dataframe of time series amplitude information
"""
output = []
for tr in st:
preliminary_checks(tr, cfg)
noise = n.rms_noise(tr, 'amplitude', cfg)
amplitude = max_amplitude(tr, noise, cfg)
date_formatted = tr.stats.o.strftime('%Y-%m-%d')
time_formatted = tr.stats.o.strftime('%H:%M:%S.%f')
output.append([date_formatted, time_formatted[:11],
tr.stats.network, tr.stats.station, tr.stats.channel,
amplitude, noise])
df = format_output(output)
if cfg.Amplitude.save_output:
df.to_csv(f'{cfg.Amplitude.output_path}/amp-output.csv',
float_format='%0.5f', index=False)
return df
def preliminary_checks(
tr: obspy.Trace,
cfg: types.ModuleType = config
) -> None:
"""Make sure all necessary information is present
This function checks...
1. The configuration file is setup correctly
2. The trace has all relevant information
3. There is sufficient time series data
Args:
tr: time series
cfg: configuration file
Returns:
None
"""
ch.check_config(cfg.Amplitude())
ch.check_waveform(tr)
return None
def max_amplitude(
tr: obspy.Trace,
noise: float,
cfg: types.ModuleType = config
) -> float:
"""Measure maximum peak-to-peak amplitude
Args:
tr: time series
noise: noise level
cfg: configuration file
Returns:
amp: maximum peak-to-peak amplitude
Raises:
ValueError: if max amplitude is not real and positive
"""
acfg = cfg.Amplitude()
tr_signal = trim_waveform_signal(tr.copy())
peaks_nan = inflection_points(tr_signal.data)
peaks = remove_nan(peaks_nan)
p2p_amplitudes = np.diff(peaks)
amp = np.max(np.abs(p2p_amplitudes)) * acfg.amp_factor
ch.check_amplitude(amp)
if acfg.plot:
indices = p2p_indices(tr_signal, peaks, p2p_amplitudes)
plot.amplitude_plot(tr, tr_signal, amp, indices, noise, acfg)
return amp
def trim_waveform_signal(
tr: obspy.Trace,
cfg: types.ModuleType = config
) -> obspy.Trace:
"""Cut the time series to signal window
Args:
tr: time series
cfg: configuration file
Returns:
tr: trimmed time series
"""
starttime, endtime = signal_window(tr, cfg)
tr.trim(starttime=starttime, endtime=endtime)
return tr
def signal_window(
tr: obspy.Trace,
cfg: types.ModuleType = config
) -> Tuple[obspy.UTCDateTime, obspy.UTCDateTime]:
"""Get the starttimes and endtimes of signal window
Args:
tr: time series
cfg: configuration file
Returns:
starttime: signal window beginning date
endtime: signal window ending date
Raises:
AssertionError: Window begins before time series begins
AssertionError: Window ends after time series ends
"""
acfg = cfg.Amplitude()
arrival = n.arrival_time_utc(tr, acfg.signal_phase)
starttime = arrival + acfg.signal_window_begin
endtime = arrival + acfg.signal_window_end
ch.check_window(tr, starttime, endtime)
return starttime, endtime
def inflection_points(data: np.ndarray) -> np.ndarray:
"""Isolate the peaks of an array
Args:
data: time series
Returns:
inflection_points: peaks of the time series
"""
nan_points = np.concatenate([[0], np.diff(np.sign(np.diff(data))), [0]])
nan_points[nan_points == 0] = np.nan
nan_points[~np.isnan(nan_points)] = 0
inflection_points = nan_points + data
return inflection_points
def remove_nan(array: np.ndarray) -> np.ndarray:
"""Remove NaN values
Args:
array: time series
Returns:
the time series without NaN values
"""
return array[~np.isnan(array)]
def p2p_indices(
tr: obspy.Trace,
peaks: np.ndarray,
amplitudes: np.ndarray
) -> Tuple[float, float]:
"""Get peak indices of max peak-to-peak amplitude
Args:
tr: time series
peaks: the inflection points of the time series
amplitudes: values of each peak to peak
Return:
idx: indices of two peaks associated with maximum amplitude
"""
i_diff = np.where(np.abs(amplitudes) == np.max(np.abs(amplitudes)))
i_peak1 = i_diff[0][0]
i_peak2 = i_peak1 + 1
peak1 = peaks[i_peak1]
peak2 = peaks[i_peak2]
nan_points = inflection_points(tr.data)
i_p1_0 = np.where(nan_points == peak1)
i_p2_0 = np.where(nan_points == peak2)
idx = p2p_indices_check(i_p1_0, i_p2_0)
return idx
def p2p_indices_check(i_p1_0: float, i_p2_0: float) -> Tuple[float, float]:
"""Verify the indices are associated with the peaks
Args:
i_p1_0: preliminary peak 1
i_p2_0: preliminary peak 2
Returns:
idx: final peaks
"""
if len(i_p1_0[0]) > 1 or len(i_p2_0[0]) > 1:
x_p1 = np.repeat(i_p1_0[0], len(i_p2_0[0]))
x_p2 = np.tile(i_p2_0[0], len(i_p2_0[0]))
x_p2_p1 = np.subtract(x_p2, x_p1)
x_p2_p1 = np.divide(x_p2_p1, 1.0)
x_p2_p1[x_p2_p1 < 0] = np.nan
i_x = np.where(x_p2_p1 == np.nanmin(x_p2_p1))
i_p1 = x_p1[int(i_x[0])]
i_p2 = x_p2[int(i_x[0])]
idx = np.array([i_p1, i_p2])
else:
i_p1 = i_p1_0[0]
i_p2 = i_p2_0[0]
idx = np.array([i_p1, i_p2])
return idx
def format_output(data: list) -> pd.DataFrame:
"""Turn list into dataframe
Args:
data: list of amplitude information
Returns:
df: dataframe of amplitude information
Raises:
AssertionError: if data size does not match column size
"""
column_names = ['date', 'time', 'network', 'station', 'channel',
'amplitude', 'noise']
assert len(data[0]) == len(column_names), \
'(ValueError) Data length must match column length'
df = pd.DataFrame(data, columns=column_names)
return df | [
"numpy.abs",
"madpy.noise.arrival_time_utc",
"madpy.checks.check_amplitude",
"madpy.noise.rms_noise",
"numpy.divide",
"numpy.where",
"madpy.checks.check_window",
"numpy.diff",
"numpy.subtract",
"madpy.plotting.amp.amplitude_plot",
"numpy.array",
"numpy.isnan",
"pandas.DataFrame",
"numpy.na... | [((1808, 1829), 'madpy.checks.check_waveform', 'ch.check_waveform', (['tr'], {}), '(tr)\n', (1825, 1829), True, 'import madpy.checks as ch\n'), ((2460, 2474), 'numpy.diff', 'np.diff', (['peaks'], {}), '(peaks)\n', (2467, 2474), True, 'import numpy as np\n'), ((2538, 2561), 'madpy.checks.check_amplitude', 'ch.check_amplitude', (['amp'], {}), '(amp)\n', (2556, 2561), True, 'import madpy.checks as ch\n'), ((3733, 3774), 'madpy.noise.arrival_time_utc', 'n.arrival_time_utc', (['tr', 'acfg.signal_phase'], {}), '(tr, acfg.signal_phase)\n', (3751, 3774), True, 'import madpy.noise as n\n'), ((3877, 3916), 'madpy.checks.check_window', 'ch.check_window', (['tr', 'starttime', 'endtime'], {}), '(tr, starttime, endtime)\n', (3892, 3916), True, 'import madpy.checks as ch\n'), ((5324, 5353), 'numpy.where', 'np.where', (['(nan_points == peak1)'], {}), '(nan_points == peak1)\n', (5332, 5353), True, 'import numpy as np\n'), ((5367, 5396), 'numpy.where', 'np.where', (['(nan_points == peak2)'], {}), '(nan_points == peak2)\n', (5375, 5396), True, 'import numpy as np\n'), ((6841, 6881), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {'columns': 'column_names'}), '(data, columns=column_names)\n', (6853, 6881), True, 'import pandas as pd\n'), ((730, 763), 'madpy.noise.rms_noise', 'n.rms_noise', (['tr', '"""amplitude"""', 'cfg'], {}), "(tr, 'amplitude', cfg)\n", (741, 763), True, 'import madpy.noise as n\n'), ((2657, 2718), 'madpy.plotting.amp.amplitude_plot', 'plot.amplitude_plot', (['tr', 'tr_signal', 'amp', 'indices', 'noise', 'acfg'], {}), '(tr, tr_signal, amp, indices, noise, acfg)\n', (2676, 2718), True, 'import madpy.plotting.amp as plot\n'), ((5918, 5941), 'numpy.subtract', 'np.subtract', (['x_p2', 'x_p1'], {}), '(x_p2, x_p1)\n', (5929, 5941), True, 'import numpy as np\n'), ((5960, 5983), 'numpy.divide', 'np.divide', (['x_p2_p1', '(1.0)'], {}), '(x_p2_p1, 1.0)\n', (5969, 5983), True, 'import numpy as np\n'), ((6156, 6178), 'numpy.array', 'np.array', (['[i_p1, i_p2]'], {}), '([i_p1, i_p2])\n', (6164, 6178), True, 'import numpy as np\n'), ((6253, 6275), 'numpy.array', 'np.array', (['[i_p1, i_p2]'], {}), '([i_p1, i_p2])\n', (6261, 6275), True, 'import numpy as np\n'), ((2492, 2514), 'numpy.abs', 'np.abs', (['p2p_amplitudes'], {}), '(p2p_amplitudes)\n', (2498, 2514), True, 'import numpy as np\n'), ((4317, 4337), 'numpy.isnan', 'np.isnan', (['nan_points'], {}), '(nan_points)\n', (4325, 4337), True, 'import numpy as np\n'), ((4645, 4660), 'numpy.isnan', 'np.isnan', (['array'], {}), '(array)\n', (4653, 4660), True, 'import numpy as np\n'), ((5110, 5128), 'numpy.abs', 'np.abs', (['amplitudes'], {}), '(amplitudes)\n', (5116, 5128), True, 'import numpy as np\n'), ((5139, 5157), 'numpy.abs', 'np.abs', (['amplitudes'], {}), '(amplitudes)\n', (5145, 5157), True, 'import numpy as np\n'), ((6056, 6074), 'numpy.nanmin', 'np.nanmin', (['x_p2_p1'], {}), '(x_p2_p1)\n', (6065, 6074), True, 'import numpy as np\n'), ((4237, 4250), 'numpy.diff', 'np.diff', (['data'], {}), '(data)\n', (4244, 4250), True, 'import numpy as np\n')] |
# External Import
from django.contrib.auth import get_user_model
from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.core.exceptions import ValidationError
from django.contrib import messages
from django.urls import reverse
from django.contrib.sites.shortcuts import get_current_site
from django.template.loader import render_to_string
User = get_user_model()
class UserRegistrationForm(UserCreationForm):
email = forms.EmailField(max_length=250, widget=forms.EmailInput(
attrs={'placeholder': 'Email',
'class': 'myInput'}
))
username = forms.CharField(label='Username', widget=forms.TextInput(
attrs={'placeholder': 'Username', 'class': 'myInput'}))
password1 = forms.CharField(label='Password', widget=forms.PasswordInput(
attrs={'placeholder': 'Password', 'class': 'myInput'}))
password2 = forms.CharField(label='Confirmation Password', widget=forms.PasswordInput(
attrs={'placeholder': 'Confirm Password', 'class': 'myInput'}))
class Meta:
model = User
fields = ['username', 'email', 'password1', '<PASSWORD>']
def clean(self):
email = self.cleaned_data.get('email').lower()
username = self.cleaned_data.get('username').lower()
if User.objects.filter(email=email).exists():
raise forms.ValidationError(" Email exists")
elif User.objects.filter(username=username).exists():
raise forms.ValidationError(f"{username} Username Already Taken")
return self.cleaned_data
class LoginForm(AuthenticationForm):
username = forms.CharField(label='Username', widget=forms.TextInput(
attrs={'placeholder': 'Username or Email', 'class': 'myInput', 'id': 'username'}))
password = forms.CharField(label="Password", widget=forms.PasswordInput(
attrs={'placeholder': 'Password', 'class': 'myInput', 'id': 'password'})
)
def confirm_login_allowed(self, user):
if not user.is_active:
url = reverse("resend_verification")
URL = f"<a href='{url}'>Resend Verification URL</a>"
messages.error(
self.request, f'{URL}')
raise ValidationError(
("This account is inactive. Check your email"),
code='inactive',
)
class SendEmailVerificationForm(forms.Form):
email = forms.EmailField(required=True)
| [
"django.contrib.auth.get_user_model",
"django.urls.reverse",
"django.contrib.messages.error",
"django.forms.PasswordInput",
"django.core.exceptions.ValidationError",
"django.forms.ValidationError",
"django.forms.EmailInput",
"django.forms.TextInput",
"django.forms.EmailField"
] | [((404, 420), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (418, 420), False, 'from django.contrib.auth import get_user_model\n'), ((2419, 2450), 'django.forms.EmailField', 'forms.EmailField', ([], {'required': '(True)'}), '(required=True)\n', (2435, 2450), False, 'from django import forms\n'), ((521, 589), 'django.forms.EmailInput', 'forms.EmailInput', ([], {'attrs': "{'placeholder': 'Email', 'class': 'myInput'}"}), "(attrs={'placeholder': 'Email', 'class': 'myInput'})\n", (537, 589), False, 'from django import forms\n'), ((676, 746), 'django.forms.TextInput', 'forms.TextInput', ([], {'attrs': "{'placeholder': 'Username', 'class': 'myInput'}"}), "(attrs={'placeholder': 'Username', 'class': 'myInput'})\n", (691, 746), False, 'from django import forms\n'), ((815, 889), 'django.forms.PasswordInput', 'forms.PasswordInput', ([], {'attrs': "{'placeholder': 'Password', 'class': 'myInput'}"}), "(attrs={'placeholder': 'Password', 'class': 'myInput'})\n", (834, 889), False, 'from django import forms\n'), ((971, 1057), 'django.forms.PasswordInput', 'forms.PasswordInput', ([], {'attrs': "{'placeholder': 'Confirm Password', 'class': 'myInput'}"}), "(attrs={'placeholder': 'Confirm Password', 'class':\n 'myInput'})\n", (990, 1057), False, 'from django import forms\n'), ((1378, 1416), 'django.forms.ValidationError', 'forms.ValidationError', (['""" Email exists"""'], {}), "(' Email exists')\n", (1399, 1416), False, 'from django import forms\n'), ((1685, 1786), 'django.forms.TextInput', 'forms.TextInput', ([], {'attrs': "{'placeholder': 'Username or Email', 'class': 'myInput', 'id': 'username'}"}), "(attrs={'placeholder': 'Username or Email', 'class':\n 'myInput', 'id': 'username'})\n", (1700, 1786), False, 'from django import forms\n'), ((1849, 1945), 'django.forms.PasswordInput', 'forms.PasswordInput', ([], {'attrs': "{'placeholder': 'Password', 'class': 'myInput', 'id': 'password'}"}), "(attrs={'placeholder': 'Password', 'class': 'myInput',\n 'id': 'password'})\n", (1868, 1945), False, 'from django import forms\n'), ((2050, 2080), 'django.urls.reverse', 'reverse', (['"""resend_verification"""'], {}), "('resend_verification')\n", (2057, 2080), False, 'from django.urls import reverse\n'), ((2158, 2196), 'django.contrib.messages.error', 'messages.error', (['self.request', 'f"""{URL}"""'], {}), "(self.request, f'{URL}')\n", (2172, 2196), False, 'from django.contrib import messages\n'), ((2232, 2310), 'django.core.exceptions.ValidationError', 'ValidationError', (['"""This account is inactive. Check your email"""'], {'code': '"""inactive"""'}), "('This account is inactive. Check your email', code='inactive')\n", (2247, 2310), False, 'from django.core.exceptions import ValidationError\n'), ((1497, 1556), 'django.forms.ValidationError', 'forms.ValidationError', (['f"""{username} Username Already Taken"""'], {}), "(f'{username} Username Already Taken')\n", (1518, 1556), False, 'from django import forms\n')] |
import torch
import torch.nn as nn
import torch.nn.functional as F
from src.utils import get_seed
class DuelingQNetwork(nn.Module):
def __init__(self, state_size, action_size):
super().__init__()
self.seed = torch.manual_seed(get_seed())
self.V_fc1 = nn.Linear(state_size, 64)
self.V_fc2 = nn.Linear(64, 64)
self.V_fc3 = nn.Linear(64, 1)
self.A_fc1 = nn.Linear(state_size, 64)
self.A_fc2 = nn.Linear(64, 64)
self.A_fc3 = nn.Linear(64, action_size)
def forward(self, state):
x = F.relu(self.V_fc1(state))
x = F.relu(self.V_fc2(x))
state_value = self.V_fc3(x)
x = F.relu(self.A_fc1(state))
x = F.relu(self.A_fc2(x))
advantage_values = self.A_fc3(x)
return state_value + (advantage_values - advantage_values.mean()) | [
"src.utils.get_seed",
"torch.nn.Linear"
] | [((282, 307), 'torch.nn.Linear', 'nn.Linear', (['state_size', '(64)'], {}), '(state_size, 64)\n', (291, 307), True, 'import torch.nn as nn\n'), ((329, 346), 'torch.nn.Linear', 'nn.Linear', (['(64)', '(64)'], {}), '(64, 64)\n', (338, 346), True, 'import torch.nn as nn\n'), ((368, 384), 'torch.nn.Linear', 'nn.Linear', (['(64)', '(1)'], {}), '(64, 1)\n', (377, 384), True, 'import torch.nn as nn\n'), ((407, 432), 'torch.nn.Linear', 'nn.Linear', (['state_size', '(64)'], {}), '(state_size, 64)\n', (416, 432), True, 'import torch.nn as nn\n'), ((454, 471), 'torch.nn.Linear', 'nn.Linear', (['(64)', '(64)'], {}), '(64, 64)\n', (463, 471), True, 'import torch.nn as nn\n'), ((493, 519), 'torch.nn.Linear', 'nn.Linear', (['(64)', 'action_size'], {}), '(64, action_size)\n', (502, 519), True, 'import torch.nn as nn\n'), ((248, 258), 'src.utils.get_seed', 'get_seed', ([], {}), '()\n', (256, 258), False, 'from src.utils import get_seed\n')] |
"""Class for generation using the GAN."""
from pathlib import Path
import tensorflow as tf
from tensorflow.keras import Model
from tqdm import tqdm
from ..utils import Config
class GANEvaluator:
"""Class to generate images using a GAN.
Attributes:
generator: The generator model to be evaluated
config: The hyper-param config
"""
def __init__(self, generator: Model, config: Config):
"""Store the required objects and info.
Args:
generator: The generator model to be evaluated
config: The hyper-param config
"""
self.generator = generator
self.config = config
@tf.function
def _gen_img(self, digits: tf.Tensor) -> tf.Tensor:
"""Generate images of the requested digits."""
noise = tf.random.normal([digits.shape[0], self.config.noise_dims])
label = tf.convert_to_tensor(digits)
generated = self.generator([noise, label])
# Convert [-1, 1] float to uint8
outputs = generated / 2 + 0.5
outputs = tf.image.convert_image_dtype(outputs, tf.uint8)
# Convert images into strings having JPEG content
return tf.map_fn(
tf.io.encode_jpeg, outputs, fn_output_signature=tf.string
)
def generate(self, imgs_per_digit: int, output_dir: Path) -> None:
"""Generate the digits and save them to disk.
Args:
imgs_per_digit: The total number of images to generate per digit
output_dir: Where to save the generated images
"""
total_imgs = 10 * imgs_per_digit
if not output_dir.exists():
output_dir.mkdir(parents=True)
with tqdm(total=total_imgs, desc="Saving") as pbar:
for start in range(0, total_imgs, self.config.gan_batch_size):
end = min(total_imgs, start + self.config.gan_batch_size)
digits = tf.convert_to_tensor(
[i % 10 for i in range(start, end)]
)
imgs = self._gen_img(digits).numpy()
for i, img in enumerate(imgs):
idx = start + i
img_name = output_dir / f"{idx % 10}-{1 + idx // 10}.jpg"
with open(img_name, "wb") as img_file:
img_file.write(img)
pbar.update()
| [
"tensorflow.random.normal",
"tensorflow.image.convert_image_dtype",
"tqdm.tqdm",
"tensorflow.map_fn",
"tensorflow.convert_to_tensor"
] | [((808, 867), 'tensorflow.random.normal', 'tf.random.normal', (['[digits.shape[0], self.config.noise_dims]'], {}), '([digits.shape[0], self.config.noise_dims])\n', (824, 867), True, 'import tensorflow as tf\n'), ((884, 912), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['digits'], {}), '(digits)\n', (904, 912), True, 'import tensorflow as tf\n'), ((1062, 1109), 'tensorflow.image.convert_image_dtype', 'tf.image.convert_image_dtype', (['outputs', 'tf.uint8'], {}), '(outputs, tf.uint8)\n', (1090, 1109), True, 'import tensorflow as tf\n'), ((1184, 1252), 'tensorflow.map_fn', 'tf.map_fn', (['tf.io.encode_jpeg', 'outputs'], {'fn_output_signature': 'tf.string'}), '(tf.io.encode_jpeg, outputs, fn_output_signature=tf.string)\n', (1193, 1252), True, 'import tensorflow as tf\n'), ((1699, 1736), 'tqdm.tqdm', 'tqdm', ([], {'total': 'total_imgs', 'desc': '"""Saving"""'}), "(total=total_imgs, desc='Saving')\n", (1703, 1736), False, 'from tqdm import tqdm\n')] |
# Copyright (C) 2019 Intel Corporation
#
# SPDX-License-Identifier: MIT
import argparse
from . import project as project_module
def build_parser(parser=argparse.ArgumentParser()):
project_module.build_create_parser(parser) \
.set_defaults(command=project_module.create_command)
return parser
def main(args=None):
parser = build_parser()
args = parser.parse_args(args)
return args.command(args)
| [
"argparse.ArgumentParser"
] | [((157, 182), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (180, 182), False, 'import argparse\n')] |
#REQUESTS -> FAZER REQUISIÇÕES HTTP (URLLIB3)
#HTTP = Hypertext Transfer Protocol
#BEAUTIFULSOUP -> HTML ou XML -> Organiza-lo de maneira a ler no python
#PANDAS -> pegar esses objetos e tranformar em EXCEL
#USAR REQUESTS E ENTENDER COMO FUNCIONA.
import requests as req
url = 'https://g1.globo.com'
r = req.get(url)
conteudo_cru = r.content
from bs4 import BeautifulSoup
soup = BeautifulSoup(conteudo_cru, 'lxml')
noticias = soup.find_all('div','bastian-feed-item')
for noticia in noticias:
#imprime informação básica
titulo = noticia.find('a','feed-post-link').text
url = noticia.find('a','feed-post-link')['href']
data = noticia.find('span','feed-post-datetime').text
print('\n\n'+data+'\n'+titulo+'\nAcesse em: '+url)
#faz segunda requisição
r2 = req.get(url)
soup2 = BeautifulSoup(r2.content, 'lxml')
t = soup2.find('time').text
print('\n'+t+'\n')
article = soup2.find('div','mc-article-body').text
print(article+'\n')
| [
"bs4.BeautifulSoup",
"requests.get"
] | [((308, 320), 'requests.get', 'req.get', (['url'], {}), '(url)\n', (315, 320), True, 'import requests as req\n'), ((386, 421), 'bs4.BeautifulSoup', 'BeautifulSoup', (['conteudo_cru', '"""lxml"""'], {}), "(conteudo_cru, 'lxml')\n", (399, 421), False, 'from bs4 import BeautifulSoup\n'), ((788, 800), 'requests.get', 'req.get', (['url'], {}), '(url)\n', (795, 800), True, 'import requests as req\n'), ((813, 846), 'bs4.BeautifulSoup', 'BeautifulSoup', (['r2.content', '"""lxml"""'], {}), "(r2.content, 'lxml')\n", (826, 846), False, 'from bs4 import BeautifulSoup\n')] |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
import sys
import os
from collections import OrderedDict
from time import time
if sys.version_info >= (3, 0):
import configparser
else:
import ConfigParser as configparser
from subprocess import Popen
from tekamenu.const import *
def help():
print("usage : ")
print("tkmenu -c config_file")
print("If no config file is specified, ~/.tkmenu.conf is used and generated")
sys.exit()
def get_config(cf):
try:
config = configparser.ConfigParser()
config.read(cf)
return config
except:
print("Unable to read configuration file")
sys.exit(1)
def save_config(config, cf):
with open(cf, 'w') as configfile:
config.write(configfile)
def read_config(config):
"""Parse config (configparser) and return a dict of sections :
{'section_name' : [list of launchers] }
Each launcher is :
launcher = ['name','cmd','icon']
In the end :
config = {'section_name' [ [name, cmd, icon], [name, cmd, icon]] ... }
"""
cf = OrderedDict()
for s in config.sections():
cf[s] = [ [i.strip() for i in infos.split(',') ]
for option, infos in config.items(s)
if option != "closeafterrun" \
and option != "theme" \
and option != "titlebar" \
and option != "title" ]
return cf
def toggle_closeafter(config_file):
config = get_config(config_file)
if config.has_option("DEFAULT","closeafterrun"):
closeafterrun = config.getboolean("DEFAULT","closeafterrun")
config.set("DEFAULT","closeafterrun", str(not closeafterrun))
save_config(config, config_file)
def toggle(config_file,option):
"""return True if option is set"""
config = get_config(config_file)
if config.has_option("DEFAULT",option):
return config.getboolean("DEFAULT",option)
def add_recent(name, cmd, icon, cf):
# add new entry in recents
conf = get_config(cf)
if len(conf['Recent']) == max_recents:
# find oldest entry
oldest = str(min(float(entry) for entry in conf.options('Recent') if is_number(entry)))
# delete oldest entry
conf.remove_option('Recent', oldest)
# add recent entry
# this is all the launcher names :[ l[1].split(',')[0].strip() for l in conf.items('Recent') ]
# to avoid doubles
if name not in [ l[1].split(',')[0].strip() for l in conf.items('Recent') ]:
conf['Recent'][str(time())] = "{},{},{}".format(name, cmd, icon)
save_config(conf, cf)
def which(program):
#https://stackoverflow.com/questions/377017/test-if-executable-exists-in-python/377028#377028
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return False
def try_to_run(app_list):
"""
return the application in app_list if avaiable
return False if no app found
"""
for app in app_list:
APP = which(app)
if APP:
return APP
return False
def edit_config(cf):
EDITOR = try_to_run(["geany","gedit","scite","kate", "mousepad", "leafpad"])
if EDITOR:
Popen([EDITOR, cf])
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
| [
"collections.OrderedDict",
"subprocess.Popen",
"os.access",
"os.path.join",
"os.path.split",
"ConfigParser.ConfigParser",
"os.path.isfile",
"sys.exit",
"time.time"
] | [((441, 451), 'sys.exit', 'sys.exit', ([], {}), '()\n', (449, 451), False, 'import sys\n'), ((1069, 1082), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (1080, 1082), False, 'from collections import OrderedDict\n'), ((2885, 2907), 'os.path.split', 'os.path.split', (['program'], {}), '(program)\n', (2898, 2907), False, 'import os\n'), ((499, 526), 'ConfigParser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (524, 526), True, 'import ConfigParser as configparser\n'), ((3574, 3593), 'subprocess.Popen', 'Popen', (['[EDITOR, cf]'], {}), '([EDITOR, cf])\n', (3579, 3593), False, 'from subprocess import Popen\n'), ((644, 655), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (652, 655), False, 'import sys\n'), ((2813, 2834), 'os.path.isfile', 'os.path.isfile', (['fpath'], {}), '(fpath)\n', (2827, 2834), False, 'import os\n'), ((2839, 2864), 'os.access', 'os.access', (['fpath', 'os.X_OK'], {}), '(fpath, os.X_OK)\n', (2848, 2864), False, 'import os\n'), ((3103, 3130), 'os.path.join', 'os.path.join', (['path', 'program'], {}), '(path, program)\n', (3115, 3130), False, 'import os\n'), ((2583, 2589), 'time.time', 'time', ([], {}), '()\n', (2587, 2589), False, 'from time import time\n')] |
import ConfigParser
import logging
import os
import sys
import yaml
log = logging.getLogger()
def load_yaml(filename):
with open(filename, 'r') as stream:
return yaml.load(stream)
def set_env_aws_creds(account='default'):
"""
Parse ~/.aws/credentials for credentials
Allow OS environment variables to override (AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY)
Exit script of neither can be found
"""
# grab creds from env
aws_key_env_var = "AWS_ACCESS_KEY_ID"
aws_secret_env_var = "AWS_SECRET_ACCESS_KEY"
aws_key_val = os.getenv(aws_key_env_var)
aws_secret_val = os.getenv(aws_secret_env_var)
# if no env variables are set, source them from the config file
if not aws_key_val or not aws_secret_val:
creds_file_path = os.path.expanduser("~/.aws/credentials")
if os.path.exists(creds_file_path):
cfg_parser = ConfigParser.ConfigParser()
cfg_parser.read(creds_file_path)
if account in cfg_parser.sections():
try:
tmp_aws_key_val = cfg_parser.get(account, aws_key_env_var.lower())
tmp_aws_secret_val = cfg_parser.get(account, aws_secret_env_var.lower())
except ConfigParser.NoOptionError:
log.fatal("AWS credentials file misconfigured")
sys.exit(1)
else:
log.info("Sourcing AWS credentials [{}] from ~/.aws/credentials".format(account))
os.environ[aws_key_env_var] = tmp_aws_key_val
os.environ[aws_secret_env_var] = tmp_aws_secret_val
# validate that values are exported into environment
aws_key_val = os.getenv(aws_key_env_var)
aws_secret_val = os.getenv(aws_secret_env_var)
if not aws_key_val:
log.fatal("Environment variable: AWS_ACCESS_KEY_ID not set.")
if not aws_secret_val:
log.fatal("Environment variable: AWS_SECRET_ACCESS_KEY not set.")
if not aws_key_val or not aws_secret_val:
sys.exit(1)
| [
"logging.getLogger",
"os.path.exists",
"os.getenv",
"yaml.load",
"ConfigParser.ConfigParser",
"sys.exit",
"os.path.expanduser"
] | [((75, 94), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (92, 94), False, 'import logging\n'), ((569, 595), 'os.getenv', 'os.getenv', (['aws_key_env_var'], {}), '(aws_key_env_var)\n', (578, 595), False, 'import os\n'), ((617, 646), 'os.getenv', 'os.getenv', (['aws_secret_env_var'], {}), '(aws_secret_env_var)\n', (626, 646), False, 'import os\n'), ((1710, 1736), 'os.getenv', 'os.getenv', (['aws_key_env_var'], {}), '(aws_key_env_var)\n', (1719, 1736), False, 'import os\n'), ((1758, 1787), 'os.getenv', 'os.getenv', (['aws_secret_env_var'], {}), '(aws_secret_env_var)\n', (1767, 1787), False, 'import os\n'), ((177, 194), 'yaml.load', 'yaml.load', (['stream'], {}), '(stream)\n', (186, 194), False, 'import yaml\n'), ((788, 828), 'os.path.expanduser', 'os.path.expanduser', (['"""~/.aws/credentials"""'], {}), "('~/.aws/credentials')\n", (806, 828), False, 'import os\n'), ((840, 871), 'os.path.exists', 'os.path.exists', (['creds_file_path'], {}), '(creds_file_path)\n', (854, 871), False, 'import os\n'), ((2038, 2049), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2046, 2049), False, 'import sys\n'), ((898, 925), 'ConfigParser.ConfigParser', 'ConfigParser.ConfigParser', ([], {}), '()\n', (923, 925), False, 'import ConfigParser\n'), ((1360, 1371), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1368, 1371), False, 'import sys\n')] |
from setuptools import setup
import setuptools
readme = ''
with open('README.md') as f:
readme = f.read()
setup(
name="discsocket",
author="<NAME>",
url="https://github.com/murillotadeo/discsocket",
project_urls={
"Issue tracker": "https://github.com/murillotadeo/discsocket/issues",
"Source": "https://github.com/murillotadeo/discsocket"
},
version="1.1.6",
package_dir={'': 'src'},
packages=setuptools.find_packages('src'),
license="MIT",
description="Python framework for Discord interactions.",
long_description=readme,
long_description_content_type="text/markdown",
include_package_data=True,
install_requires=['aiohttp>=3.6.0,<3.8.0'],
python_requires=">=3.10.0",
classifiers=[
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3.10'
]
) | [
"setuptools.find_packages"
] | [((448, 479), 'setuptools.find_packages', 'setuptools.find_packages', (['"""src"""'], {}), "('src')\n", (472, 479), False, 'import setuptools\n')] |
# ==BEGIN LICENSE==
#
# MIT License
#
# Copyright (c) 2018 SRI Lab, ETH Zurich
#
# 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, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# 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.
#
# ==END LICENSE==
import importlib
from abc import ABC, abstractmethod
import os
import numpy as np
from typing import Tuple
import tensorflow as tf
import re
from dpfinder.utils.utils import arr_to_str
from dpfinder.algorithms.tf_implementations.implementation import TensorFlowImplementation
# precisions
precision_tf = tf.float64
precision_np = np.float64
regex = re.compile(r'^// ==BEGIN LICENSE==[\s\S]+// ==END LICENSE==[\s]+')
class Algorithm(ABC):
def __init__(self):
class_name = self.__class__.__name__
self.name = class_name[0].lower() + class_name[1:]
@abstractmethod
def get_random_input(self) -> Tuple[np.ndarray, np.ndarray]:
"""
Return a tuple of (a,d), where a is the original database,
and d characterizes the distance to the neighbouring database
"""
pass
@abstractmethod
def get_random_output(self, a, b):
"""
:param a:
:param b:
:return: a random output to check for (can also be multiple values that parametrize an output set)
"""
pass
def get_psi_filename(self):
"""Return the filename of the PSI code"""
return self.name + '.psi'
def get_psi_base_script(self):
"""Return an implementation in PSI, as a string"""
here = os.path.dirname(__file__)
psi_file_location = os.path.join(here, './psi_implementations/' + self.get_psi_filename())
with open(psi_file_location, 'r') as file:
psi_base_script = file.read()
psi_base_script = regex.sub('', psi_base_script)
return psi_base_script
def get_psi_script(self, a, o):
psi_script = self.get_psi_base_script()
psi_script = psi_script.replace("[$A]", arr_to_str(a))
psi_script = psi_script.replace("[$O]", arr_to_str(o))
return psi_script
def get_params(self):
return self
def get_tensorflow_implementation(self) -> TensorFlowImplementation:
i = importlib.import_module('.tf_implementations.imps.' + self.name, __package__)
class_name = self.name.capitalize()[0] + self.name[1:] + 'Impl'
class_ = getattr(i, class_name)
return class_(self.get_params())
def set_random_start(self, impl: TensorFlowImplementation):
"""随机初始化一组a, d, o 和参数(e.g. rho, nu)值(调用initialize,把placeholder替换为具体数据)"""
a_init, d_init = self.get_random_input()
o_init = self.get_random_output(a_init, a_init + d_init)
impl.initialize(a_init, d_init, o_init)
def get_algorithm(name, *args) -> Algorithm:
i = importlib.import_module('.algs.' + name, __package__)
class_name = name.capitalize()[0] + name[1:]
class_ = getattr(i, class_name)
return class_(*args)
def get_algorithm_larger_dict(name, d) -> Algorithm:
"""Requires d to contain at least all arguments require to construct
the algorithm referred to by name"""
# get constructor
i = importlib.import_module('.algs.' + name, __package__)
class_name = name.capitalize()[0] + name[1:]
class_ = getattr(i, class_name)
constructor = getattr(class_, '__init__')
# find arguments, extract them from d
code = constructor.__code__
n_arguments = code.co_argcount
args = {}
for v in code.co_varnames[1:n_arguments]:
args[v] = d[v]
return class_(**args)
| [
"dpfinder.utils.utils.arr_to_str",
"os.path.dirname",
"importlib.import_module",
"re.compile"
] | [((1516, 1584), 're.compile', 're.compile', (['"""^// ==BEGIN LICENSE==[\\\\s\\\\S]+// ==END LICENSE==[\\\\s]+"""'], {}), "('^// ==BEGIN LICENSE==[\\\\s\\\\S]+// ==END LICENSE==[\\\\s]+')\n", (1526, 1584), False, 'import re\n'), ((3484, 3537), 'importlib.import_module', 'importlib.import_module', (["('.algs.' + name)", '__package__'], {}), "('.algs.' + name, __package__)\n", (3507, 3537), False, 'import importlib\n'), ((3828, 3881), 'importlib.import_module', 'importlib.import_module', (["('.algs.' + name)", '__package__'], {}), "('.algs.' + name, __package__)\n", (3851, 3881), False, 'import importlib\n'), ((2339, 2364), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (2354, 2364), False, 'import os\n'), ((2937, 3014), 'importlib.import_module', 'importlib.import_module', (["('.tf_implementations.imps.' + self.name)", '__package__'], {}), "('.tf_implementations.imps.' + self.name, __package__)\n", (2960, 3014), False, 'import importlib\n'), ((2730, 2743), 'dpfinder.utils.utils.arr_to_str', 'arr_to_str', (['a'], {}), '(a)\n', (2740, 2743), False, 'from dpfinder.utils.utils import arr_to_str\n'), ((2787, 2800), 'dpfinder.utils.utils.arr_to_str', 'arr_to_str', (['o'], {}), '(o)\n', (2797, 2800), False, 'from dpfinder.utils.utils import arr_to_str\n')] |
####################################################
####################################################
# functions and classes used in conjunction with
# pipeline_metaomics.py
####################################################
####################################################
# import libraries
import sys
import re
import os
import itertools
import sqlite3
import CGAT.IOTools as IOTools
import CGATPipelines.Pipeline as P
from rpy2.robjects import r as R
import pandas
import numpy as np
####################################################
####################################################
####################################################
# SECTION 1
####################################################
####################################################
####################################################
def buildDiffStats(infile, outfile, db, connection):
'''
build differential abundance statistics
at different p-value and Fold change
thresholds for each comparison
'''
tablename = P.toTable(os.path.basename(infile))
statement = "ATTACH '%(db)s' as diff;" % locals()
connection.execute(statement)
# build table of results at different thresholds
ps = [0.01, 0.05, 0.1]
fcs = [0, 0.5, 1, 1.5, 2]
# build results for each pair
pairs = [("HhaIL10R", "WT"), ("WT", "aIL10R"), ("Hh", "WT")]
outf = open(outfile, "w")
outf.write("group1\tgroup2\tadj_P_Val\tlogFC\tnumber\n")
for pair in pairs:
p1, p2 = pair[0], pair[1]
for p, fc in itertools.product(ps, fcs):
statement = """SELECT COUNT(*)
FROM diff.%(tablename)s
WHERE group1 == "%(p1)s"
AND group2 == "%(p2)s"
AND adj_P_Val < %(p)f
AND abs(logFC) > %(fc)f""" % locals()
for data in connection.execute(statement).fetchall():
outf.write("\t".join([p1, p2, str(p), str(fc), str(data[0])]) + "\n")
outf.close()
####################################################
####################################################
####################################################
# SECTION 2
####################################################
####################################################
####################################################
def buildCommonList(rnadb, dnadb, outfile):
'''
build a list of NOGs/genera that were found in
common after filtering between RNA and
DNA data sets
'''
# select appropriate table depending on
# whether we want genera or NOGs
if "genera" in outfile:
tablename = "genus_diamond_aggregated_counts_diff"
else:
tablename = "gene_counts_diff"
# connect to respective
# databases for RNA and DNA
dbh_rna = sqlite3.connect(rnadb)
cc_rna = dbh_rna.cursor()
dbh_dna = sqlite3.connect(dnadb)
cc_dna = dbh_dna.cursor()
# collect NOGs/genera and write to
# file
outf = open(outfile, "w")
rna = set()
dna = set()
for gene in cc_rna.execute("""
SELECT taxa
FROM %s
WHERE group1 == "HhaIL10R"
AND group2 == "WT"
""" % tablename).fetchall():
rna.add(gene[0])
for gene in cc_dna.execute("""SELECT taxa
FROM %s
WHERE group1 == "HhaIL10R"
AND group2 == "WT"
""" % tablename).fetchall():
dna.add(gene[0])
for gene in rna.intersection(dna):
outf.write(gene + "\n")
####################################################
####################################################
####################################################
def buildDiffList(db,
commonset,
outfile,
fdr=0.05,
l2fold=1,
tablename=None):
'''
build a list of differentially expressed
NOGs between colitis and steady state
'''
# list of common NOGs for sql statement
common = set([x[:-1] for x in open(commonset).readlines()])
common = "(" + ",".join(['"'+x+'"' for x in common]) + ")"
# connect to database
dbh = sqlite3.connect(db)
cc = dbh.cursor()
# remove any genes that are different between Hh and steady state
# or between aIL10R and steady state
hh = set([x[0] for x in cc.execute("""SELECT taxa
FROM %s \
WHERE group1 == "Hh" \
AND group2 == "WT" \
AND adj_P_Val < %f""" % (tablename, fdr)).fetchall()])
# sql list
hh = "(" + ",".join(['"'+x+'"' for x in hh]) + ")"
ail10r = set([x[0] for x in cc.execute("""SELECT taxa
FROM %s
WHERE group1 == "WT"
AND group2 == "aIL10R"
AND adj_P_Val < %f""" % (tablename, fdr)).fetchall()])
# sql list
ail10r = "(" + ",".join(['"'+x+'"' for x in ail10r]) + ")"
outf = open(outfile, "w")
for gene in cc.execute("""SELECT taxa
FROM %s
WHERE group1 == "HhaIL10R"
AND group2 == "WT"
AND adj_P_Val < %f
AND (logFC > %i OR logFC < -%i)
AND taxa IN %s
AND taxa NOT IN %s
AND taxa NOT IN %s
ORDER BY logFC DESC""" % (tablename, fdr, l2fold, l2fold, common, hh, ail10r)).fetchall():
outf.write(gene[0] + "\n")
outf.close()
####################################################
####################################################
####################################################
def heatmapDiffFeatures(diff_list,
matrix,
outfile):
'''
draw heatmap of differentially abundant features
'''
R('''library(gplots)''')
R('''library(gtools)''')
R('''diff <- read.csv("%s", header=F, sep="\t", stringsAsFactors=F)''' % diff_list)
R('''dat <- read.csv("%s", header=T, stringsAsFactors=F, sep="\t")''' % matrix)
R('''rownames(dat) <- dat$taxa''')
R('''dat <- dat[, 1:ncol(dat)-1]''')
R('''dat <- dat[diff[,1],]''')
R('''dat <- na.omit(dat)''')
R('''dat <- dat[, mixedsort(colnames(dat))]''')
R('''samples <- colnames(dat)''')
R('''dat <- t(apply(dat, 1, scale))''')
R('''colnames(dat) <- samples''')
R('''cols <- colorRampPalette(c("blue", "white", "red"))''')
R('''pdf("%s")''' % outfile)
R('''heatmap.2(as.matrix(dat), col = cols, scale = "row", trace = "none", Rowv = F, Colv = F, margins = c(15,15),
distfun = function(x) dist(x, method = "manhattan"),
hclustfun = function(x) hclust(x, method = "ward.D2"))''')
R["dev.off"]()
####################################################
####################################################
####################################################
def buildDiffGeneOverlap(dnafile, rnafile, outfile):
'''
overlap differentially abundant NOGs between
RNA and DNA data sets
'''
dna = set([x[:-1] for x in open(dnafile).readlines()])
rna = set([x[:-1] for x in open(rnafile).readlines()])
ndna = len(dna)
nrna = len(rna)
overlap = len(dna.intersection(rna))
outf = open(outfile, "w")
outf.write("nDNA\tnRNA\tnoverlap\n%(ndna)i\t%(nrna)i\t%(overlap)i\n" % locals())
outf.close()
####################################################
####################################################
####################################################
def testSignificanceOfOverlap(common, overlap, outfile):
'''
Test significance of overlapping lists
bewteen RNA and DNA using hypergeometric test
'''
R('''pop <- read.csv("%s", header = F, sep = "\t", stringsAsFactors = F)''' % common)
R('''overlaps <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % overlap)
# total genes in population
R('''npop <- nrow(pop)''')
# x = number of white balls picked = overlap
R('''x <- overlaps$noverlap''')
# m = total number of white balls = total diff in RNA analysis
R('''m <- overlaps$nRNA''')
# n = total number of black balls = total - diff in RNA analysis
R('''n <- npop - m''')
# k = total balls sampled = number of genera different in DNA analysis
R('''k <- overlaps$nDNA''')
# hypergeometric test
R('''p <- 1-phyper(x,m,n,k)''')
# write result
R('''res <- matrix(ncol = 2, nrow = 5)''')
R('''res[1,1] <- "x"''')
R('''res[2,1] <- "m"''')
R('''res[3,1] <- "n"''')
R('''res[4,1] <- "k"''')
R('''res[5,1] <- "p-value"''')
R('''res[1,2] <- x''')
R('''res[2,2] <- m''')
R('''res[3,2] <- n''')
R('''res[4,2] <- k''')
R('''res[5,2] <- p''')
R('''print(res)''')
R('''write.table(as.data.frame(res), file = "%s", quote = F, sep = "\t", row.names = F)''' % outfile)
####################################################
####################################################
####################################################
def scatterplotAbundanceEstimates(dnamatrix,
rnamatrix,
outfile):
'''
scatterplot abundance estimates between DNA and RNA
data sets
'''
R('''rna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % rnamatrix)
R('''rownames(rna) <- rna$taxa''')
R('''rna <- rna[,1:ncol(rna)-1]''')
R('''dna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % dnamatrix)
R('''rownames(dna) <- dna$taxa''')
R('''dna <- dna[,1:ncol(dna)-1]''')
# intersection of taxa/NOGs present
R('''keep <- intersect(rownames(rna), rownames(dna))''')
# get data where there is rna and dna
R('''rna <- rna[keep,]''')
R('''dna <- dna[keep,]''')
# take averages
R('''rna.ave <- data.frame(apply(rna, 1, mean))''')
R('''dna.ave <- data.frame(apply(dna, 1, mean))''')
R('''print(cor(dna.ave,rna.ave)[[1]])''')
R('''png("%s")''' % outfile)
R('''plot(dna.ave[,1],
rna.ave[,1],
pch = 16,
col = "slateGrey",
xlab = "Mean DNA abundance",
ylab = "Mean RNA abundance",
main = paste("N = ", nrow(dna.ave), sep = ""))
abline(lm(rna[,1]~dna[,1], na.rm = T))''')
R["dev.off"]()
####################################################
####################################################
####################################################
def buildDetectionOverlap(rnacounts, dnacounts, outfile):
'''
build detection overlaps between RNA and DNA
data sets
'''
R('''rna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % rnacounts)
R('''rownames(rna) <- rna$taxa''')
R('''rna <- rna[,1:ncol(rna)]''')
R('''dna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % dnacounts)
R('''rownames(dna) <- dna$taxa''')
R('''dna <- dna[,1:ncol(dna)]''')
R('''taxa.rna <- rownames(rna)''')
R('''taxa.dna <- rownames(dna)''')
# union of taxa across samples
R('''nrna = length(taxa.rna)''')
R('''ndna = length(taxa.dna)''')
# get overlapping
R('''noverlap = length(intersect(taxa.rna, taxa.dna))''')
R('''result = data.frame(nrna = nrna, ndna = ndna, noverlap = noverlap)''')
R('''write.table(result, file = "%s", sep = "\t", quote = F, row.names = F)''' % outfile)
####################################################
####################################################
####################################################
def plotAbundanceLevelsOfOverlap(rnacounts,
dnacounts,
outfile,
of=None):
'''
plot abundance levels pf taxa/NOGs that do
and don't overlap between data sets
'''
R('''library(ggplot2)''')
# get rna reads per million
R('''rna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % rnacounts)
R('''rownames(rna) <- rna$taxa''')
R('''rna <- rna[,2:ncol(rna)]''')
R('''rna <- sweep(rna, 2, colSums(rna)/1000000, "/")''')
# get dna reads per million
R('''dna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % dnacounts)
R('''rownames(dna) <- dna$taxa''')
R('''dna <- dna[,2:ncol(dna)]''')
R('''dna <- sweep(dna, 2, colSums(dna)/1000000, "/")''')
# common and distinct sets
R('''common <- intersect(rownames(dna), rownames(rna))''')
R('''rna.only <- setdiff(rownames(rna), rownames(dna))''')
R('''dna.only <- setdiff(rownames(dna), rownames(rna))''')
# boxplot the abundance levels
R('''rna.common <- apply(rna[common,], 1, mean)''')
R('''dna.common <- apply(dna[common,], 1, mean)''')
R('''rna.distinct <- apply(rna[rna.only,], 1, mean)''')
R('''dna.distinct <- apply(dna[dna.only,], 1, mean)''')
if of == "genes":
# this is just so the thing will run
# genes do not have distinct genes
# in RNA analysis
R('''rna.distinct <- rep(0, 20)''')
else:
R('''rna.distinct <- rna.distinct''')
# test sig bewteen groups
R('''wtest1 <- wilcox.test(rna.common, rna.distinct)''')
R('''wtest2 <- wilcox.test(dna.common, dna.distinct)''')
R('''wtest3 <- wilcox.test(rna.common, dna.distinct)''')
R('''wtest4 <- wilcox.test(dna.common, rna.distinct)''')
R('''wtest5 <- wilcox.test(dna.common, rna.common)''')
R('''res <- data.frame("rna.common_vs_rna.distinct" = wtest1$p.value,
"dna.common_vs_dna.distinct" = wtest2$p.value,
"rna.common_vs_dna.distinct" = wtest3$p.value,
"dna.common_vs_rna.distinct" = wtest4$p.value,
"dna.common_vs_rna.common" = wtest5$p.value)''')
outname_sig = outfile[:-4] + ".sig"
R('''write.table(res, file = "%s", row.names = F, sep = "\t", quote = F)''' % outname_sig)
# create dataframe for plotting
R('''dat <- data.frame(values = c(dna.distinct, dna.common, rna.common, rna.distinct),
status = c(rep("unique.dna", length(dna.distinct)),
rep("common.dna", length(dna.common)),
rep("common.rna", length(rna.common)),
rep("unique.rna", length(rna.distinct))))''')
R('''plot1 <- ggplot(dat, aes(x = factor(status, levels = status), y = values, stat = "identity"))''')
R('''plot1 + geom_boxplot() + scale_y_log10()''')
R('''ggsave("%s")''' % outfile)
####################################################
####################################################
####################################################
# SECTION 3
####################################################
####################################################
####################################################
def runPCA(infile, outfile):
'''
run pca analysis - this outputs
a plot coloured by condition and
also the loadings
'''
if "RNA" in infile:
suffix = "rna"
else:
suffix = "dna"
if "gene" in infile:
xlim, ylim = 40,40
else:
xlim, ylim = 12,7
outname_plot = P.snip(outfile, ".loadings.tsv").replace("/", "/%s_" % suffix) + ".pca.pdf"
R('''dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % infile)
R('''rownames(dat) <- dat$taxa''')
R('''dat <- dat[, 1:ncol(dat)-1]''')
R('''pc <- prcomp(t(dat))''')
R('''conds <- unlist(strsplit(colnames(dat), ".R[0-9]"))[seq(1, ncol(dat)*2, 2)]''')
R('''conds <- unlist(strsplit(conds, ".", fixed = T))[seq(2, length(conds)*2, 2)]''')
# plot the principle components
R('''library(ggplot2)''')
R('''pcs <- data.frame(pc$x)''')
R('''pcs$cond <- conds''')
# get variance explained
R('''imps <- c(summary(pc)$importance[2], summary(pc)$importance[5])''')
R('''p <- ggplot(pcs, aes(x = PC1, y = PC2, colour = cond, size = 3)) + geom_point()''')
R('''p2 <- p + xlab(imps[1]) + ylab(imps[2])''')
R('''p3 <- p2 + scale_colour_manual(values = c("slateGrey", "green", "red", "blue"))''')
R('''p3 + xlim(c(-%i, %i)) + ylim(c(-%i, %i))''' % (xlim, xlim, ylim, ylim))
R('''ggsave("%s")''' % outname_plot)
# get the loadings
R('''loads <- data.frame(pc$rotation)''')
R('''loads$taxa <- rownames(loads)''')
# write out data
R('''write.table(loads, file = "%s", sep = "\t", row.names = F, quote = F)''' % outfile.replace("/", "/%s_" % suffix))
####################################################
####################################################
####################################################
def plotPCALoadings(infile, outfile):
'''
plot PCA loadings
'''
R('''library(ggplot2)''')
R('''library(grid)''')
R('''dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % infile)
R('''top5pc1 <- dat[order(-dat$PC1),][1:5,]''')
R('''bottom5pc1 <- dat[order(dat$PC1),][1:5,]''')
R('''top5pc2 <- dat[order(-dat$PC2),][1:5,]''')
R('''bottom5pc2 <- dat[order(dat$PC2),][1:5,]''')
R('''totext <- data.frame(rbind(top5pc1, bottom5pc1, top5pc2, bottom5pc2))''')
R('''dat$x <- 0''')
R('''dat$y <- 0''')
R('''p <- ggplot(dat, aes(x = x, y = y, xend = PC1, yend = PC2, colour = taxa))''')
R('''p2 <- p + geom_segment(arrow = arrow(length = unit(0.2, "cm")))''')
R('''p2 + geom_text(data = totext, aes(x = PC1, y = PC2, label = totext$taxa, size = 6)) + xlim(c(-0.5,0.5)) + ylim(c(-0.5,0.25))''')
R('''ggsave("%s")''' % outfile)
# rna = [x for x in infiles if "RNA" in x][0]
# dna = [x for x in infiles if "DNA" in x][0]
# R('''rna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % rna)
# R('''dna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % dna)
# R('''rna <- rna[rna$group1 == "HhaIL10R" & rna$group2 == "WT",]''')
# R('''dna <- dna[dna$group1 == "HhaIL10R" & dna$group2 == "WT",]''')
# R('''rownames(rna) <- rna$taxa''')
# R('''rownames(dna) <- dna$taxa''')
# R('''rna <- rna[,1:ncol(rna)-1]''')
# R('''dna <- dna[,1:ncol(dna)-1]''')
# # only look at those that are present in both
# R('''keep <- intersect(rownames(rna), rownames(dna))''')
# R('''rna <- rna[keep,]''')
# R('''dna <- dna[keep,]''')
# R('''rna.ratio <- rna$logFC''')
# R('''dna.ratio <- dna$logFC''')
# R('''rna.p <- rna$adj.P.Val''')
# R('''dna.p <- dna$adj.P.Val''')
# R('''ratio <- data.frame(gene = keep, dna = dna.ratio, rna = rna.ratio, pdna = dna.p, prna = rna.p, ratio = rna.ratio - dna.ratio)''')
# R('''write.table(ratio, file = "%s", sep = "\t", row.names = F, quote = F)''' % outfile)
####################################################
####################################################
####################################################
def barchartProportions(infile, outfile):
'''
stacked barchart description of percent reads
mapping to each taxon
'''
R('''library(ggplot2)''')
R('''library(gtools)''')
R('''library(reshape)''')
R('''dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % infile)
R('''rownames(dat) <- dat$taxa''')
# get rid of taxa colomn
R('''dat <- dat[,1:ncol(dat)-1]''')
R('''dat.percent <- data.frame(apply(dat, 2, function(x) x*100))''')
# candidate genera
R('''candidates <- c("Peptoniphilus",
"Deferribacter",
"Escherichia",
"Lactobacillus",
"Turicibacter",
"Akkermansia",
"Bifidobacterium",
"Methylacidiphilum")''')
R('''dat.percent <- dat.percent[candidates,]''')
R('''dat.percent <- dat.percent[,mixedsort(colnames(dat.percent))]''')
# add taxa column with "other" = < 5% in any sample
R('''dat.percent$taxa <- rownames(dat.percent)''')
# reshape and plot
outname = P.snip(outfile, ".pdf")
R('''dat.percent <- melt(dat.percent)''')
R('''conds <- unlist(strsplit(as.character(dat.percent$variable), ".R[0-9]"))[seq(1, nrow(dat.percent)*2, 2)]''')
R('''conds <- unlist(strsplit(conds, ".", fixed = T))[seq(2, length(conds)*2, 2)]''')
R('''dat.percent$cond <- conds''')
R('''for (taxon in candidates){
outname <- paste("%s", paste("_", taxon, sep=""), ".pdf", sep="")
dat.percent.restrict <- dat.percent[dat.percent$taxa==taxon,]
plot1 <- ggplot(dat.percent.restrict,
aes(x=factor(cond, levels=c("WT","aIL10R", "Hh", "HhaIL10R")),
y=value, group=cond, colour=cond, label=variable))
plot1 + geom_boxplot() + geom_jitter() + geom_text() + scale_colour_manual(values=c("darkGreen", "red", "grey", "blue"))
ggsave(outname)}''' % outname)
####################################################
####################################################
####################################################
# SECTION 4
####################################################
####################################################
####################################################
def buildRNADNARatio(dnadiff, rnadiff, outfile):
'''
build ratio of RNAfold/DNAfold
'''
R('''rna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % rnadiff)
R('''dna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % dnadiff)
R('''rna <- rna[rna$group1 == "HhaIL10R" & rna$group2 == "WT",]''')
R('''dna <- dna[dna$group1 == "HhaIL10R" & dna$group2 == "WT",]''')
R('''rownames(rna) <- rna$taxa''')
R('''rownames(dna) <- dna$taxa''')
R('''rna <- rna[,1:ncol(rna)-1]''')
R('''dna <- dna[,1:ncol(dna)-1]''')
# only look at those that are present in both
R('''keep <- intersect(rownames(rna), rownames(dna))''')
R('''rna <- rna[keep,]''')
R('''dna <- dna[keep,]''')
R('''rna.ratio <- rna$logFC''')
R('''dna.ratio <- dna$logFC''')
R('''rna.p <- rna$adj.P.Val''')
R('''dna.p <- dna$adj.P.Val''')
R('''ratio <- data.frame(gene = keep,
dna = dna.ratio,
rna = rna.ratio,
pdna = dna.p,
prna = rna.p,
ratio = rna.ratio - dna.ratio)''')
R('''write.table(ratio,
file = "%s",
sep = "\t",
row.names = F,
quote = F)''' % outfile)
####################################################
####################################################
####################################################
def annotateRNADNARatio(RNADNARatio,
dnalist,
rnalist,
outfile):
'''
annotate NOGs as to whether they were differentially
regulated in metagenomic, metatranscriptomic or both
data sets
'''
rna_diff = set([y[:-1] for y in open(rnalist).readlines()])
dna_diff = set([y[:-1] for y in open(dnalist).readlines()])
inf = IOTools.openFile(RNADNARatio)
inf.readline()
outf = IOTools.openFile(outfile, "w")
outf.write("gene\tdna\trna\tpdna\tprna\tratio\tstatus\n")
for line in inf.readlines():
gene, dna, rna, pdna, prna, ratio = line[:-1].split("\t")
gene = gene.strip('"')
dna, rna = float(dna), float(rna)
if gene in rna_diff and gene in dna_diff and dna > 0 and rna > 0:
status = "up.both"
elif gene in rna_diff and gene in dna_diff and dna < 0 and rna < 0:
status = "down.both"
elif gene in rna_diff and rna > 0:
status = "up.RNA"
elif gene in rna_diff and rna < 0:
status = "down.RNA"
elif gene in dna_diff and dna > 0:
status = "up.DNA"
elif gene in dna_diff and dna < 0:
status = "down.DNA"
else:
status = "NS"
outf.write("%(gene)s\t%(dna)s\t%(rna)s\t%(pdna)s\t%(prna)s\t%(ratio)s\t%(status)s\n" % locals())
outf.close()
####################################################
####################################################
####################################################
def plotSets(infile, outfile):
'''
plot the fold changes in RNA and DNA analyses
and label by how they are regulated in DNA and
RNA analyses
MUST HAVE GOI FILE IN WORKING DIR - not ideal
'''
R('''library(ggplot2)''')
# read in data
R('''dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % infile)
# get nog 2 gene map
R('''cog2gene <- read.csv("goi.tsv", header = F, stringsAsFactors = F, sep = "\t", row.names = 1)''')
# just get those signficant in either DNA or RNA or both
R('''dat$status[dat$status == "NS"] = "z"''')
R('''genes <- dat$gene''')
# regression model
R('''mod1 <- lm(dat$rna~dat$dna)''')
R('''intercept <- mod1[[1]][1]''')
R('''slope = mod1[[1]][2]''')
R('''print(summary(mod1))''')
# prediction intervals
R('''pred.ints <- predict(mod1, interval = "prediction", level = 0.95)''')
# add to data.frame
R('''dat$lwr <- pred.ints[,2]''')
R('''dat$upr <- pred.ints[,3]''')
# add labels
R('''dat$goi <- cog2gene[dat$gene,]''')
R('''dat$pointsize <- ifelse(!(is.na(dat$goi)), 10, 1)''')
# plot
R('''plot1 <- ggplot(dat, aes(x = dna, y = rna, alpha = 1, colour = status))''')
R('''plot2 <- plot1 + geom_point(shape = 18, aes(size = pointsize))''')
R('''plot3 <- plot2 + scale_size_area() + xlim(c(-5,5))''')
R('''plot4 <- plot3 + scale_colour_manual(values = c("blue",
"brown",
"darkGreen",
"orange",
"purple",
"red",
"grey"))''')
R('''plot5 <- plot4 + geom_abline(intercept = intercept, slope = slope)''')
# prediction intervals
R('''plot6 <- plot5 + geom_line(aes(x = dna, y = lwr), linetype = "dashed", colour = "black")''')
R('''plot7 <- plot6 + geom_line(aes(x = dna, y = upr), linetype = "dashed", colour = "black")''')
R('''plot7 + geom_text(aes(label = goi))''')
R('''ggsave("%s")''' % outfile)
####################################################
####################################################
####################################################
def buildGenesOutsidePredictionInterval(infile, outfile):
'''
annotate genes as being outside prediction
interval - these are the NOGs that we are
defining as colitis-responsive
'''
R('''dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % infile)
# just get those signficant in either DNA or RNA or both
R('''genes <- dat$gene''')
# regression model
R('''mod1 <- lm(dat$rna~dat$dna)''')
# prediction intervals
R('''pred.ints <- predict(mod1, interval = "prediction", level = 0.95)''')
# add to data.frame
R('''dat$lwr <- pred.ints[,2]''')
R('''dat$upr <- pred.ints[,3]''')
# annotate with whether or not they are above
# prediction intervals
R('''dat$pi_status[dat$rna > dat$upr & dat$status == "up.RNA"] <- "diff.up.rna"''')
R('''dat$pi_status[dat$rna > dat$upr & dat$status == "down.DNA"] <- "diff.down.dna"''')
R('''dat$pi_status[dat$rna > dat$upr & dat$status == "up.both"] <- "diff.up.rna"''')
R('''dat$pi_status[dat$rna < dat$lwr & dat$status == "down.RNA"] <- "diff.down.rna"''')
R('''dat$pi_status[dat$rna < dat$lwr & dat$status == "up.DNA"] <- "diff.up.dna"''')
R('''dat$pi_status[dat$rna < dat$lwr & dat$status == "down.both"] <- "diff.down.rna"''')
# write results
R('''write.table(dat, file = "%s", sep = "\t", quote = F, row.names = F)''' % outfile)
####################################################
####################################################
####################################################
# SECTION 6
####################################################
####################################################
####################################################
def buildGenusCogCountsMatrix(infile, outfile):
'''
build cog x genus proportion
matrix
'''
inf = IOTools.openFile(infile)
header = inf.readline()
result = {}
# create container for results
for line in inf.readlines():
data = line[:-1].split("\t")
cog, taxa = data[0], data[1]
if taxa == "unassigned": continue
result[cog] = {}
# get average % taxa per cog
inf = IOTools.openFile(infile)
header = inf.readline()
for line in inf.readlines():
data = line[:-1].split("\t")
if len(data) == 19:
cog, taxa = data[0], data[1]
values = map(float,data[3:])
elif len(data) == 20:
cog, taxa = data[0], data[1]
values = map(float,data[4:])
else:
cog, taxa = data[0], data[1]
values = map(float,data[2:])
if taxa == "unassigned": continue
ave = np.mean(values)
try:
result[cog][taxa] = ave
except KeyError: continue
df = pandas.DataFrame(result)
df.to_csv(outfile, sep = "\t", na_rep = 0)
####################################################
####################################################
####################################################
def mergePathwaysAndGenusCogCountsMatrix(annotations,
matrix,
outfile):
'''
merge cog annotations and per taxa cog counts
'''
# read annotations
R('''anno <- read.csv("%s", header=T, stringsAsFactors=F, sep="\t", row.names=1)''' % annotations)
R('''anno.no.pathways <- anno[,1:ncol(anno)-1]''')
R('''anno.p <- sweep(anno.no.pathways, 2, colSums(anno.no.pathways), "/")''')
R('''anno.p$average <- rowMeans(anno.p)''')
R('''anno.p$pathway <- anno$taxa''')
# read matrix
R('''mat <- read.csv("%s", header=T, stringsAsFactors=F, sep="\t", row.names=1)''' % matrix)
R('''mat <- data.frame(t(mat))''')
R('''mat$ref <- rownames(mat)''')
# split pathway annotations
R('''for (pathway in unique(anno.p$pathway)){
if (pathway == "Function unknown"){next}
# some weirness with some names
pw <- gsub("/", "_", pathway)
outname <- paste("candidate_pathways.dir", paste(pw, "tsv", sep = "."), sep="/")
outname <- gsub(" ", "_", outname)
print(outname)
anno.p2 <- anno.p[anno.p$pathway == pathway,]
anno.p2 <- anno.p2[order(anno.p2$average, decreasing=T),]
# top 10
# anno.p2 <- anno.p2[1:10,]
# merge with matrix
mat2 <- mat[rownames(anno.p2),]
mat2$pathway <- anno.p2$pathway
write.table(mat2, file=outname, sep="\t", row.names=F)}''')
####################################################
####################################################
####################################################
def plotNumberOfTaxaPerPathway(infiles, outfile):
'''
plot the average number of taxa expressing genes
in each pathway
'''
tmp = P.getTempFilename(".")
infs = " ".join(infiles)
statement = '''awk 'FNR==1 && NR!=1 { while (/ref/) getline; }1 {print}' %(infs)s > %(tmp)s'''
P.run()
R('''library(ggplot2)''')
R('''library(plyr)''')
R('''library(reshape)''')
R('''dat <-read.csv("%s", header=T, stringsAsFactors=F, sep="\t")''' % tmp)
R('''t <- ncol(dat)''')
R('''dat <- na.omit(dat)''')
R('''pathways <- dat$pathway''')
R('''dat2 <- dat[,1:ncol(dat)-1]''')
R('''dat2 <- dat2[,1:ncol(dat2)-1]''')
# colsums gives the total number of taxa expressing each NOG
R('''col.sums <- data.frame(t(sapply(split(dat2, pathways), colSums)))''')
R('''rownames(col.sums) <- unique(pathways)''')
# rowsums gives the total number of taxa expressing
# at least one NOG per pathway
R('''total.taxa <- data.frame(rowSums(col.sums > 0))''')
R('''total.taxa$pathway <- rownames(col.sums)''')
# sort by highest
R('''total.taxa <- total.taxa[order(total.taxa[,1], decreasing=T), ]''')
R('''colnames(total.taxa) <- c("value", "pathway")''')
R('''plot1 <- ggplot(total.taxa, aes(x=factor(pathway,levels=pathway), y=value/t, stat="identity"))''')
R('''plot1 + geom_bar(stat="identity") + theme(axis.text.x=element_text(angle=90))''')
R('''ggsave("%s")''' % outfile)
os.unlink(tmp)
####################################################
####################################################
####################################################
def plotTaxaContributionsToCandidatePathways(matrix,
outfile):
'''
plot the distribution of maximum genus
contribution per gene set
'''
R('''library(ggplot2)''')
R('''library(gplots)''')
R('''library(pheatmap)''')
R('''mat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % matrix)
R('''mat <- na.omit(mat)''')
R('''print(mat$ref)''')
# just plot top 10
R('''rownames(mat) <- mat$ref''')
R('''mat2 <- mat[,1:ncol(mat)-1]''')
R('''mat2 <- mat2[,1:ncol(mat2)-1]''')
# only keep those genera that contribute > 5% to
# a NOG
R('''mat2 <- mat2[,colSums(mat2) > 5]''')
R('''cols <- colorRampPalette(c("white", "blue"))(75)''')
R('''pdf("%s")''' % outfile)
R('''pheatmap(mat2,
color=cols,
cluster_cols=T,
cluster_rows=T,
cluster_method="ward.D2")''')
R["dev.off"]()
####################################################
####################################################
####################################################
def plotMaxTaxaContribution(matrix, annotations, outfile):
'''
plot the distribution of maximum genus
contribution per gene set
'''
R('''library(ggplot2)''')
R('''dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % matrix)
R('''annotations <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % annotations)
R('''maximums <- apply(dat, 2, max)''')
R('''dat2 <- data.frame("cog" = colnames(dat), "max" = maximums)''')
R('''dat3 <- merge(dat2, annotations, by.x = "cog", by.y = "gene")''')
R('''dat3$pi_status <- ifelse(dat3$status == "NS", "NS", dat3$pi_status)''')
R('''dat3$pi_status[is.na(dat3$pi_status)] <- "other_significant"''')
R('''plot1 <- ggplot(dat3, aes(x = as.numeric(as.character(max)), group = pi_status, colour = pi_status))''')
R('''plot2 <- plot1 + stat_ecdf(size = 1.1)''')
R('''plot2 + scale_colour_manual(values = c("cyan3",
"darkorchid",
"black",
"darkgoldenrod2",
"grey",
"darkBlue"))''')
R('''ggsave("%s")''' % outfile)
####################################################
####################################################
####################################################
def testSignificanceOfMaxTaxaContribution(matrix, annotations, outfile):
'''
Test significance of distribution differences. Compared to NS
group
'''
R('''library(ggplot2)''')
R('''dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % matrix)
R('''annotations <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % annotations)
R('''maximums <- apply(dat, 2, max)''')
R('''dat2 <- data.frame("cog" = colnames(dat), "max" = maximums)''')
R('''dat3 <- merge(dat2, annotations, by.x = "cog", by.y = "gene")''')
R('''dat3$pi_status <- ifelse(dat3$status == "NS", "NS", dat3$pi_status)''')
R('''diff.up.rna <- as.numeric(as.character(dat3$max[dat3$pi_status == "diff.up.rna"]))''')
R('''diff.down.rna <- as.numeric(as.character(dat3$max[dat3$pi_status == "diff.down.rna"]))''')
R('''diff.up.dna <- as.numeric(as.character(dat3$max[dat3$pi_status == "diff.up.dna"]))''')
R('''diff.down.dna <- as.numeric(as.character(dat3$max[dat3$pi_status == "diff.down.dna"]))''')
R('''ns <- as.numeric(as.character(dat3$max[dat3$pi_status == "NS"]))''')
# ks tests
R('''ks1 <- ks.test(diff.up.rna, ns)''')
R('''ks2 <- ks.test(diff.down.rna, ns)''')
R('''ks3 <- ks.test(diff.up.dna, ns)''')
R('''ks4 <- ks.test(diff.down.dna, ns)''')
R('''res <- data.frame("RNAGreaterThanDNA.up.pvalue" = ks1$p.value,
"RNAGreaterThanDNA.up.D" = ks1$statistic,
"RNAGreaterThanDNA.down.pvalue" = ks2$p.value,
"RNAGreaterThanDNA.down.D" = ks2$statistic,
"DNAGreaterThanRNA.up.pvalue" = ks3$p.value,
"DNAGreaterThanRNA.up.D" = ks3$statistic,
"DNAGreaterThanRNA.down.pvalue" = ks4$p.value,
"DNAGreaterThanRNA.down.D" = ks4$statistic)''')
R('''write.table(res, file = "%s", sep = "\t", quote = F, row.names = F)''' % outfile)
####################################################
####################################################
####################################################
def heatmapTaxaCogProportionMatrix(matrix, annotations, outfile):
'''
plot the taxa associated with each cog on
a heatmap
'''
R('''library(gplots)''')
R('''library(gtools)''')
R('''dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t", row.names = 1)''' % matrix)
R('''annotations <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % annotations)
R('''rownames(annotations) <- annotations$gene''')
# get genes present in both - not sure why these are different
# in the first place - need to check
R('''genes <- intersect(rownames(annotations), colnames(dat))''')
R('''dat <- dat[, genes]''')
R('''dat <- dat[grep("unassigned", rownames(dat), invert = T),]''')
R('''genera <- rownames(dat)''')
R('''rownames(dat) <- genera''')
R('''colnames(dat) <- genes''')
R('''annotations <- annotations[genes,]''')
R('''annotations <- annotations[order(annotations$pi_status),]''')
# only for the COGs that have RNA fold > DNA fold up-regulated
R('''annotations <- annotations[annotations$pi_status == "diff.up.rna",]''')
R('''annotations <- na.omit(annotations)''')
R('''dat <- dat[,rownames(annotations)]''')
R('''annotation <- data.frame(cluster = as.character(annotations$pi_status))''')
R('''rownames(annotation) <- rownames(annotations)''')
R('''colors1 <- c("grey")''')
R('''names(colors1) <- c("diff.up.rna")''')
R('''anno_colors <- list(cluster = colors1)''')
R('''cols <- colorRampPalette(c("white", "darkBlue"))(150)''')
R('''dat <- dat[,colSums(dat > 50) >= 1]''')
R('''dat <- dat[rowSums(dat > 10) >= 1,]''')
# not reading numeric in all instances
R('''dat2 <- data.frame(t(apply(dat, 1, as.numeric)))''')
R('''colnames(dat2) <- colnames(dat)''')
R('''pdf("%s", height = 10, width = 15)''' % outfile)
R('''library(pheatmap)''')
R('''pheatmap(dat2,
clustering_distance_cols = "manhattan",
clustering_method = "ward",
annotation = annotation,
annotation_colors = anno_colors,
cluster_rows = T,
cluster_cols = F,
color = cols,
fontsize = 8)''')
R["dev.off"]()
####################################################
####################################################
####################################################
def scatterplotPerCogTaxaDNAFoldRNAFold(taxa_cog_rnadiff,
taxa_cog_dnadiff,
cog_rnadiff,
cog_dnadiff):
'''
scatterplot fold changes for per genus cog
differences for NOGs of interestx
'''
R('''library(ggplot2)''')
# read in cogs + taxa
R('''dna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % taxa_cog_dnadiff)
R('''dna <- dna[dna$group2 == "WT" & dna$group1 == "HhaIL10R",]''')
R('''rna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % taxa_cog_rnadiff)
R('''rna <- rna[rna$group2 == "WT" & rna$group1 == "HhaIL10R",]''')
# read in cogs alone
R('''dna.cog <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % cog_dnadiff)
R('''dna.cog <- dna.cog[dna.cog$group2 == "WT" & dna.cog$group1 == "HhaIL10R",]''')
R('''rna.cog <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % cog_rnadiff)
R('''rna.cog <- rna.cog[rna.cog$group2 == "WT" & rna.cog$group1 == "HhaIL10R",]''')
# merge data for cogs + taxa
R('''dat <- merge(dna, rna,
by.x = "taxa",
by.y = "taxa",
all.x = T,
all.y = T,
suffixes = c(".dna.taxa.cog", ".rna.taxa.cog"))''')
# sub NA for 0
R('''dat[is.na(dat)] <- 0''')
# NOTE these are specified and hardcoded
# here - NOGs of interest
R('''cogs <- c("COG0783", "COG2837", "COG0435","COG5520", "COG0508", "COG0852")''')
# iterate over cogs and scatterplot
# fold changes in DNA and RNA analysis.
# if not present in one or other then fold change will
# be 0
R('''for (cog in cogs){
dat2 <- dat[grep(cog, dat$taxa),]
dna.cog2 <- dna.cog[grep(cog, dna.cog$taxa),]
rna.cog2 <- rna.cog[grep(cog, rna.cog$taxa),]
# add the data for COG fold changes and abundance
dat3 <- data.frame("genus" = append(dat2$taxa, cog),
"dna.fold" = append(dat2$logFC.dna.taxa.cog, dna.cog2$logFC),
"rna.fold" = append(dat2$logFC.rna.taxa.cog, rna.cog2$logFC),
"abundance" = append(dat2$AveExpr.rna.taxa.cog, rna.cog2$AveExpr))
suffix <- paste(cog, "scatters.pdf", sep = ".")
outname <- paste("scatterplot_genus_cog_fold.dir", suffix, sep = "/")
plot1 <- ggplot(dat3, aes(x = dna.fold, y = rna.fold, size = log10(abundance), label = genus))
plot2 <- plot1 + geom_point(shape = 18)
plot3 <- plot2 + geom_text(hjust = 0.5, vjust = 1) + scale_size(range = c(3,6))
plot4 <- plot3 + geom_abline(intercept = 0, slope = 1, colour = "blue")
plot5 <- plot4 + geom_hline(yintercept = c(-1,1), linetype = "dashed")
plot6 <- plot5 + geom_vline(xintercept = c(-1,1), linetype = "dashed")
plot7 <- plot6 + geom_hline(yintercept = 0) + geom_vline(xintercept = 0)
ggsave(outname)
}''')
| [
"numpy.mean",
"CGATPipelines.Pipeline.run",
"sqlite3.connect",
"CGATPipelines.Pipeline.snip",
"itertools.product",
"CGATPipelines.Pipeline.getTempFilename",
"os.unlink",
"os.path.basename",
"pandas.DataFrame",
"CGAT.IOTools.openFile",
"rpy2.robjects.r"
] | [((2859, 2881), 'sqlite3.connect', 'sqlite3.connect', (['rnadb'], {}), '(rnadb)\n', (2874, 2881), False, 'import sqlite3\n'), ((2926, 2948), 'sqlite3.connect', 'sqlite3.connect', (['dnadb'], {}), '(dnadb)\n', (2941, 2948), False, 'import sqlite3\n'), ((4401, 4420), 'sqlite3.connect', 'sqlite3.connect', (['db'], {}), '(db)\n', (4416, 4420), False, 'import sqlite3\n'), ((6211, 6231), 'rpy2.robjects.r', 'R', (['"""library(gplots)"""'], {}), "('library(gplots)')\n", (6212, 6231), True, 'from rpy2.robjects import r as R\n'), ((6240, 6260), 'rpy2.robjects.r', 'R', (['"""library(gtools)"""'], {}), "('library(gtools)')\n", (6241, 6260), True, 'from rpy2.robjects import r as R\n'), ((6270, 6349), 'rpy2.robjects.r', 'R', (['(\'diff <- read.csv("%s", header=F, sep="\\t", stringsAsFactors=F)\' % diff_list)'], {}), '(\'diff <- read.csv("%s", header=F, sep="\\t", stringsAsFactors=F)\' % diff_list)\n', (6271, 6349), True, 'from rpy2.robjects import r as R\n'), ((6359, 6434), 'rpy2.robjects.r', 'R', (['(\'dat <- read.csv("%s", header=T, stringsAsFactors=F, sep="\\t")\' % matrix)'], {}), '(\'dat <- read.csv("%s", header=T, stringsAsFactors=F, sep="\\t")\' % matrix)\n', (6360, 6434), True, 'from rpy2.robjects import r as R\n'), ((6443, 6473), 'rpy2.robjects.r', 'R', (['"""rownames(dat) <- dat$taxa"""'], {}), "('rownames(dat) <- dat$taxa')\n", (6444, 6473), True, 'from rpy2.robjects import r as R\n'), ((6482, 6514), 'rpy2.robjects.r', 'R', (['"""dat <- dat[, 1:ncol(dat)-1]"""'], {}), "('dat <- dat[, 1:ncol(dat)-1]')\n", (6483, 6514), True, 'from rpy2.robjects import r as R\n'), ((6523, 6549), 'rpy2.robjects.r', 'R', (['"""dat <- dat[diff[,1],]"""'], {}), "('dat <- dat[diff[,1],]')\n", (6524, 6549), True, 'from rpy2.robjects import r as R\n'), ((6558, 6582), 'rpy2.robjects.r', 'R', (['"""dat <- na.omit(dat)"""'], {}), "('dat <- na.omit(dat)')\n", (6559, 6582), True, 'from rpy2.robjects import r as R\n'), ((6591, 6634), 'rpy2.robjects.r', 'R', (['"""dat <- dat[, mixedsort(colnames(dat))]"""'], {}), "('dat <- dat[, mixedsort(colnames(dat))]')\n", (6592, 6634), True, 'from rpy2.robjects import r as R\n'), ((6643, 6672), 'rpy2.robjects.r', 'R', (['"""samples <- colnames(dat)"""'], {}), "('samples <- colnames(dat)')\n", (6644, 6672), True, 'from rpy2.robjects import r as R\n'), ((6681, 6716), 'rpy2.robjects.r', 'R', (['"""dat <- t(apply(dat, 1, scale))"""'], {}), "('dat <- t(apply(dat, 1, scale))')\n", (6682, 6716), True, 'from rpy2.robjects import r as R\n'), ((6725, 6754), 'rpy2.robjects.r', 'R', (['"""colnames(dat) <- samples"""'], {}), "('colnames(dat) <- samples')\n", (6726, 6754), True, 'from rpy2.robjects import r as R\n'), ((6763, 6819), 'rpy2.robjects.r', 'R', (['"""cols <- colorRampPalette(c("blue", "white", "red"))"""'], {}), '(\'cols <- colorRampPalette(c("blue", "white", "red"))\')\n', (6764, 6819), True, 'from rpy2.robjects import r as R\n'), ((6828, 6852), 'rpy2.robjects.r', 'R', (['(\'pdf("%s")\' % outfile)'], {}), '(\'pdf("%s")\' % outfile)\n', (6829, 6852), True, 'from rpy2.robjects import r as R\n'), ((6861, 7138), 'rpy2.robjects.r', 'R', (['"""heatmap.2(as.matrix(dat), col = cols, scale = "row", trace = "none", Rowv = F, Colv = F, margins = c(15,15), \n distfun = function(x) dist(x, method = "manhattan"),\n hclustfun = function(x) hclust(x, method = "ward.D2"))"""'], {}), '("""heatmap.2(as.matrix(dat), col = cols, scale = "row", trace = "none", Rowv = F, Colv = F, margins = c(15,15), \n distfun = function(x) dist(x, method = "manhattan"),\n hclustfun = function(x) hclust(x, method = "ward.D2"))"""\n )\n', (6862, 7138), True, 'from rpy2.robjects import r as R\n'), ((8121, 8206), 'rpy2.robjects.r', 'R', (['(\'pop <- read.csv("%s", header = F, sep = "\\t", stringsAsFactors = F)\' % common\n )'], {}), '(\'pop <- read.csv("%s", header = F, sep = "\\t", stringsAsFactors = F)\' %\n common)\n', (8122, 8206), True, 'from rpy2.robjects import r as R\n'), ((8211, 8308), 'rpy2.robjects.r', 'R', (['(\'overlaps <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n overlap)'], {}), '(\n \'overlaps <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\'\n % overlap)\n', (8212, 8308), True, 'from rpy2.robjects import r as R\n'), ((8340, 8362), 'rpy2.robjects.r', 'R', (['"""npop <- nrow(pop)"""'], {}), "('npop <- nrow(pop)')\n", (8341, 8362), True, 'from rpy2.robjects import r as R\n'), ((8421, 8448), 'rpy2.robjects.r', 'R', (['"""x <- overlaps$noverlap"""'], {}), "('x <- overlaps$noverlap')\n", (8422, 8448), True, 'from rpy2.robjects import r as R\n'), ((8525, 8548), 'rpy2.robjects.r', 'R', (['"""m <- overlaps$nRNA"""'], {}), "('m <- overlaps$nRNA')\n", (8526, 8548), True, 'from rpy2.robjects import r as R\n'), ((8627, 8645), 'rpy2.robjects.r', 'R', (['"""n <- npop - m"""'], {}), "('n <- npop - m')\n", (8628, 8645), True, 'from rpy2.robjects import r as R\n'), ((8730, 8753), 'rpy2.robjects.r', 'R', (['"""k <- overlaps$nDNA"""'], {}), "('k <- overlaps$nDNA')\n", (8731, 8753), True, 'from rpy2.robjects import r as R\n'), ((8789, 8816), 'rpy2.robjects.r', 'R', (['"""p <- 1-phyper(x,m,n,k)"""'], {}), "('p <- 1-phyper(x,m,n,k)')\n", (8790, 8816), True, 'from rpy2.robjects import r as R\n'), ((8845, 8883), 'rpy2.robjects.r', 'R', (['"""res <- matrix(ncol = 2, nrow = 5)"""'], {}), "('res <- matrix(ncol = 2, nrow = 5)')\n", (8846, 8883), True, 'from rpy2.robjects import r as R\n'), ((8892, 8912), 'rpy2.robjects.r', 'R', (['"""res[1,1] <- "x\\""""'], {}), '(\'res[1,1] <- "x"\')\n', (8893, 8912), True, 'from rpy2.robjects import r as R\n'), ((8921, 8941), 'rpy2.robjects.r', 'R', (['"""res[2,1] <- "m\\""""'], {}), '(\'res[2,1] <- "m"\')\n', (8922, 8941), True, 'from rpy2.robjects import r as R\n'), ((8950, 8970), 'rpy2.robjects.r', 'R', (['"""res[3,1] <- "n\\""""'], {}), '(\'res[3,1] <- "n"\')\n', (8951, 8970), True, 'from rpy2.robjects import r as R\n'), ((8979, 8999), 'rpy2.robjects.r', 'R', (['"""res[4,1] <- "k\\""""'], {}), '(\'res[4,1] <- "k"\')\n', (8980, 8999), True, 'from rpy2.robjects import r as R\n'), ((9008, 9034), 'rpy2.robjects.r', 'R', (['"""res[5,1] <- "p-value\\""""'], {}), '(\'res[5,1] <- "p-value"\')\n', (9009, 9034), True, 'from rpy2.robjects import r as R\n'), ((9043, 9061), 'rpy2.robjects.r', 'R', (['"""res[1,2] <- x"""'], {}), "('res[1,2] <- x')\n", (9044, 9061), True, 'from rpy2.robjects import r as R\n'), ((9070, 9088), 'rpy2.robjects.r', 'R', (['"""res[2,2] <- m"""'], {}), "('res[2,2] <- m')\n", (9071, 9088), True, 'from rpy2.robjects import r as R\n'), ((9097, 9115), 'rpy2.robjects.r', 'R', (['"""res[3,2] <- n"""'], {}), "('res[3,2] <- n')\n", (9098, 9115), True, 'from rpy2.robjects import r as R\n'), ((9124, 9142), 'rpy2.robjects.r', 'R', (['"""res[4,2] <- k"""'], {}), "('res[4,2] <- k')\n", (9125, 9142), True, 'from rpy2.robjects import r as R\n'), ((9151, 9169), 'rpy2.robjects.r', 'R', (['"""res[5,2] <- p"""'], {}), "('res[5,2] <- p')\n", (9152, 9169), True, 'from rpy2.robjects import r as R\n'), ((9178, 9193), 'rpy2.robjects.r', 'R', (['"""print(res)"""'], {}), "('print(res)')\n", (9179, 9193), True, 'from rpy2.robjects import r as R\n'), ((9202, 9309), 'rpy2.robjects.r', 'R', (['(\'write.table(as.data.frame(res), file = "%s", quote = F, sep = "\\t", row.names = F)\'\n % outfile)'], {}), '(\n \'write.table(as.data.frame(res), file = "%s", quote = F, sep = "\\t", row.names = F)\'\n % outfile)\n', (9203, 9309), True, 'from rpy2.robjects import r as R\n'), ((9690, 9778), 'rpy2.robjects.r', 'R', (['(\'rna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n rnamatrix)'], {}), '(\'rna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n rnamatrix)\n', (9691, 9778), True, 'from rpy2.robjects import r as R\n'), ((9783, 9813), 'rpy2.robjects.r', 'R', (['"""rownames(rna) <- rna$taxa"""'], {}), "('rownames(rna) <- rna$taxa')\n", (9784, 9813), True, 'from rpy2.robjects import r as R\n'), ((9822, 9853), 'rpy2.robjects.r', 'R', (['"""rna <- rna[,1:ncol(rna)-1]"""'], {}), "('rna <- rna[,1:ncol(rna)-1]')\n", (9823, 9853), True, 'from rpy2.robjects import r as R\n'), ((9862, 9950), 'rpy2.robjects.r', 'R', (['(\'dna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n dnamatrix)'], {}), '(\'dna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n dnamatrix)\n', (9863, 9950), True, 'from rpy2.robjects import r as R\n'), ((9955, 9985), 'rpy2.robjects.r', 'R', (['"""rownames(dna) <- dna$taxa"""'], {}), "('rownames(dna) <- dna$taxa')\n", (9956, 9985), True, 'from rpy2.robjects import r as R\n'), ((9994, 10025), 'rpy2.robjects.r', 'R', (['"""dna <- dna[,1:ncol(dna)-1]"""'], {}), "('dna <- dna[,1:ncol(dna)-1]')\n", (9995, 10025), True, 'from rpy2.robjects import r as R\n'), ((10075, 10127), 'rpy2.robjects.r', 'R', (['"""keep <- intersect(rownames(rna), rownames(dna))"""'], {}), "('keep <- intersect(rownames(rna), rownames(dna))')\n", (10076, 10127), True, 'from rpy2.robjects import r as R\n'), ((10179, 10201), 'rpy2.robjects.r', 'R', (['"""rna <- rna[keep,]"""'], {}), "('rna <- rna[keep,]')\n", (10180, 10201), True, 'from rpy2.robjects import r as R\n'), ((10210, 10232), 'rpy2.robjects.r', 'R', (['"""dna <- dna[keep,]"""'], {}), "('dna <- dna[keep,]')\n", (10211, 10232), True, 'from rpy2.robjects import r as R\n'), ((10270, 10317), 'rpy2.robjects.r', 'R', (['"""rna.ave <- data.frame(apply(rna, 1, mean))"""'], {}), "('rna.ave <- data.frame(apply(rna, 1, mean))')\n", (10271, 10317), True, 'from rpy2.robjects import r as R\n'), ((10326, 10373), 'rpy2.robjects.r', 'R', (['"""dna.ave <- data.frame(apply(dna, 1, mean))"""'], {}), "('dna.ave <- data.frame(apply(dna, 1, mean))')\n", (10327, 10373), True, 'from rpy2.robjects import r as R\n'), ((10383, 10420), 'rpy2.robjects.r', 'R', (['"""print(cor(dna.ave,rna.ave)[[1]])"""'], {}), "('print(cor(dna.ave,rna.ave)[[1]])')\n", (10384, 10420), True, 'from rpy2.robjects import r as R\n'), ((10429, 10453), 'rpy2.robjects.r', 'R', (['(\'png("%s")\' % outfile)'], {}), '(\'png("%s")\' % outfile)\n', (10430, 10453), True, 'from rpy2.robjects import r as R\n'), ((10462, 10780), 'rpy2.robjects.r', 'R', (['"""plot(dna.ave[,1], \n rna.ave[,1], \n pch = 16, \n col = "slateGrey",\n xlab = "Mean DNA abundance",\n ylab = "Mean RNA abundance",\n main = paste("N = ", nrow(dna.ave), sep = ""))\n abline(lm(rna[,1]~dna[,1], na.rm = T))"""'], {}), '("""plot(dna.ave[,1], \n rna.ave[,1], \n pch = 16, \n col = "slateGrey",\n xlab = "Mean DNA abundance",\n ylab = "Mean RNA abundance",\n main = paste("N = ", nrow(dna.ave), sep = ""))\n abline(lm(rna[,1]~dna[,1], na.rm = T))"""\n )\n', (10463, 10780), True, 'from rpy2.robjects import r as R\n'), ((11097, 11185), 'rpy2.robjects.r', 'R', (['(\'rna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n rnacounts)'], {}), '(\'rna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n rnacounts)\n', (11098, 11185), True, 'from rpy2.robjects import r as R\n'), ((11190, 11220), 'rpy2.robjects.r', 'R', (['"""rownames(rna) <- rna$taxa"""'], {}), "('rownames(rna) <- rna$taxa')\n", (11191, 11220), True, 'from rpy2.robjects import r as R\n'), ((11229, 11258), 'rpy2.robjects.r', 'R', (['"""rna <- rna[,1:ncol(rna)]"""'], {}), "('rna <- rna[,1:ncol(rna)]')\n", (11230, 11258), True, 'from rpy2.robjects import r as R\n'), ((11267, 11355), 'rpy2.robjects.r', 'R', (['(\'dna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n dnacounts)'], {}), '(\'dna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n dnacounts)\n', (11268, 11355), True, 'from rpy2.robjects import r as R\n'), ((11360, 11390), 'rpy2.robjects.r', 'R', (['"""rownames(dna) <- dna$taxa"""'], {}), "('rownames(dna) <- dna$taxa')\n", (11361, 11390), True, 'from rpy2.robjects import r as R\n'), ((11399, 11428), 'rpy2.robjects.r', 'R', (['"""dna <- dna[,1:ncol(dna)]"""'], {}), "('dna <- dna[,1:ncol(dna)]')\n", (11400, 11428), True, 'from rpy2.robjects import r as R\n'), ((11438, 11468), 'rpy2.robjects.r', 'R', (['"""taxa.rna <- rownames(rna)"""'], {}), "('taxa.rna <- rownames(rna)')\n", (11439, 11468), True, 'from rpy2.robjects import r as R\n'), ((11477, 11507), 'rpy2.robjects.r', 'R', (['"""taxa.dna <- rownames(dna)"""'], {}), "('taxa.dna <- rownames(dna)')\n", (11478, 11507), True, 'from rpy2.robjects import r as R\n'), ((11552, 11580), 'rpy2.robjects.r', 'R', (['"""nrna = length(taxa.rna)"""'], {}), "('nrna = length(taxa.rna)')\n", (11553, 11580), True, 'from rpy2.robjects import r as R\n'), ((11589, 11617), 'rpy2.robjects.r', 'R', (['"""ndna = length(taxa.dna)"""'], {}), "('ndna = length(taxa.dna)')\n", (11590, 11617), True, 'from rpy2.robjects import r as R\n'), ((11649, 11702), 'rpy2.robjects.r', 'R', (['"""noverlap = length(intersect(taxa.rna, taxa.dna))"""'], {}), "('noverlap = length(intersect(taxa.rna, taxa.dna))')\n", (11650, 11702), True, 'from rpy2.robjects import r as R\n'), ((11711, 11782), 'rpy2.robjects.r', 'R', (['"""result = data.frame(nrna = nrna, ndna = ndna, noverlap = noverlap)"""'], {}), "('result = data.frame(nrna = nrna, ndna = ndna, noverlap = noverlap)')\n", (11712, 11782), True, 'from rpy2.robjects import r as R\n'), ((11791, 11880), 'rpy2.robjects.r', 'R', (['(\'write.table(result, file = "%s", sep = "\\t", quote = F, row.names = F)\' %\n outfile)'], {}), '(\'write.table(result, file = "%s", sep = "\\t", quote = F, row.names = F)\' %\n outfile)\n', (11792, 11880), True, 'from rpy2.robjects import r as R\n'), ((12324, 12345), 'rpy2.robjects.r', 'R', (['"""library(ggplot2)"""'], {}), "('library(ggplot2)')\n", (12325, 12345), True, 'from rpy2.robjects import r as R\n'), ((12387, 12475), 'rpy2.robjects.r', 'R', (['(\'rna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n rnacounts)'], {}), '(\'rna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n rnacounts)\n', (12388, 12475), True, 'from rpy2.robjects import r as R\n'), ((12480, 12510), 'rpy2.robjects.r', 'R', (['"""rownames(rna) <- rna$taxa"""'], {}), "('rownames(rna) <- rna$taxa')\n", (12481, 12510), True, 'from rpy2.robjects import r as R\n'), ((12519, 12548), 'rpy2.robjects.r', 'R', (['"""rna <- rna[,2:ncol(rna)]"""'], {}), "('rna <- rna[,2:ncol(rna)]')\n", (12520, 12548), True, 'from rpy2.robjects import r as R\n'), ((12557, 12609), 'rpy2.robjects.r', 'R', (['"""rna <- sweep(rna, 2, colSums(rna)/1000000, "/")"""'], {}), '(\'rna <- sweep(rna, 2, colSums(rna)/1000000, "/")\')\n', (12558, 12609), True, 'from rpy2.robjects import r as R\n'), ((12651, 12739), 'rpy2.robjects.r', 'R', (['(\'dna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n dnacounts)'], {}), '(\'dna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n dnacounts)\n', (12652, 12739), True, 'from rpy2.robjects import r as R\n'), ((12744, 12774), 'rpy2.robjects.r', 'R', (['"""rownames(dna) <- dna$taxa"""'], {}), "('rownames(dna) <- dna$taxa')\n", (12745, 12774), True, 'from rpy2.robjects import r as R\n'), ((12783, 12812), 'rpy2.robjects.r', 'R', (['"""dna <- dna[,2:ncol(dna)]"""'], {}), "('dna <- dna[,2:ncol(dna)]')\n", (12784, 12812), True, 'from rpy2.robjects import r as R\n'), ((12821, 12873), 'rpy2.robjects.r', 'R', (['"""dna <- sweep(dna, 2, colSums(dna)/1000000, "/")"""'], {}), '(\'dna <- sweep(dna, 2, colSums(dna)/1000000, "/")\')\n', (12822, 12873), True, 'from rpy2.robjects import r as R\n'), ((12914, 12968), 'rpy2.robjects.r', 'R', (['"""common <- intersect(rownames(dna), rownames(rna))"""'], {}), "('common <- intersect(rownames(dna), rownames(rna))')\n", (12915, 12968), True, 'from rpy2.robjects import r as R\n'), ((12977, 13031), 'rpy2.robjects.r', 'R', (['"""rna.only <- setdiff(rownames(rna), rownames(dna))"""'], {}), "('rna.only <- setdiff(rownames(rna), rownames(dna))')\n", (12978, 13031), True, 'from rpy2.robjects import r as R\n'), ((13040, 13094), 'rpy2.robjects.r', 'R', (['"""dna.only <- setdiff(rownames(dna), rownames(rna))"""'], {}), "('dna.only <- setdiff(rownames(dna), rownames(rna))')\n", (13041, 13094), True, 'from rpy2.robjects import r as R\n'), ((13139, 13186), 'rpy2.robjects.r', 'R', (['"""rna.common <- apply(rna[common,], 1, mean)"""'], {}), "('rna.common <- apply(rna[common,], 1, mean)')\n", (13140, 13186), True, 'from rpy2.robjects import r as R\n'), ((13195, 13242), 'rpy2.robjects.r', 'R', (['"""dna.common <- apply(dna[common,], 1, mean)"""'], {}), "('dna.common <- apply(dna[common,], 1, mean)')\n", (13196, 13242), True, 'from rpy2.robjects import r as R\n'), ((13251, 13302), 'rpy2.robjects.r', 'R', (['"""rna.distinct <- apply(rna[rna.only,], 1, mean)"""'], {}), "('rna.distinct <- apply(rna[rna.only,], 1, mean)')\n", (13252, 13302), True, 'from rpy2.robjects import r as R\n'), ((13311, 13362), 'rpy2.robjects.r', 'R', (['"""dna.distinct <- apply(dna[dna.only,], 1, mean)"""'], {}), "('dna.distinct <- apply(dna[dna.only,], 1, mean)')\n", (13312, 13362), True, 'from rpy2.robjects import r as R\n'), ((13643, 13695), 'rpy2.robjects.r', 'R', (['"""wtest1 <- wilcox.test(rna.common, rna.distinct)"""'], {}), "('wtest1 <- wilcox.test(rna.common, rna.distinct)')\n", (13644, 13695), True, 'from rpy2.robjects import r as R\n'), ((13704, 13756), 'rpy2.robjects.r', 'R', (['"""wtest2 <- wilcox.test(dna.common, dna.distinct)"""'], {}), "('wtest2 <- wilcox.test(dna.common, dna.distinct)')\n", (13705, 13756), True, 'from rpy2.robjects import r as R\n'), ((13765, 13817), 'rpy2.robjects.r', 'R', (['"""wtest3 <- wilcox.test(rna.common, dna.distinct)"""'], {}), "('wtest3 <- wilcox.test(rna.common, dna.distinct)')\n", (13766, 13817), True, 'from rpy2.robjects import r as R\n'), ((13826, 13878), 'rpy2.robjects.r', 'R', (['"""wtest4 <- wilcox.test(dna.common, rna.distinct)"""'], {}), "('wtest4 <- wilcox.test(dna.common, rna.distinct)')\n", (13827, 13878), True, 'from rpy2.robjects import r as R\n'), ((13887, 13937), 'rpy2.robjects.r', 'R', (['"""wtest5 <- wilcox.test(dna.common, rna.common)"""'], {}), "('wtest5 <- wilcox.test(dna.common, rna.common)')\n", (13888, 13937), True, 'from rpy2.robjects import r as R\n'), ((13947, 14335), 'rpy2.robjects.r', 'R', (['"""res <- data.frame("rna.common_vs_rna.distinct" = wtest1$p.value,\n "dna.common_vs_dna.distinct" = wtest2$p.value,\n "rna.common_vs_dna.distinct" = wtest3$p.value,\n "dna.common_vs_rna.distinct" = wtest4$p.value,\n "dna.common_vs_rna.common" = wtest5$p.value)"""'], {}), '("""res <- data.frame("rna.common_vs_rna.distinct" = wtest1$p.value,\n "dna.common_vs_dna.distinct" = wtest2$p.value,\n "rna.common_vs_dna.distinct" = wtest3$p.value,\n "dna.common_vs_rna.distinct" = wtest4$p.value,\n "dna.common_vs_rna.common" = wtest5$p.value)"""\n )\n', (13948, 14335), True, 'from rpy2.robjects import r as R\n'), ((14381, 14471), 'rpy2.robjects.r', 'R', (['(\'write.table(res, file = "%s", row.names = F, sep = "\\t", quote = F)\' %\n outname_sig)'], {}), '(\'write.table(res, file = "%s", row.names = F, sep = "\\t", quote = F)\' %\n outname_sig)\n', (14382, 14471), True, 'from rpy2.robjects import r as R\n'), ((14513, 14921), 'rpy2.robjects.r', 'R', (['"""dat <- data.frame(values = c(dna.distinct, dna.common, rna.common, rna.distinct),\n status = c(rep("unique.dna", length(dna.distinct)),\n rep("common.dna", length(dna.common)),\n rep("common.rna", length(rna.common)),\n rep("unique.rna", length(rna.distinct))))"""'], {}), '("""dat <- data.frame(values = c(dna.distinct, dna.common, rna.common, rna.distinct),\n status = c(rep("unique.dna", length(dna.distinct)),\n rep("common.dna", length(dna.common)),\n rep("common.rna", length(rna.common)),\n rep("unique.rna", length(rna.distinct))))"""\n )\n', (14514, 14921), True, 'from rpy2.robjects import r as R\n'), ((14921, 15024), 'rpy2.robjects.r', 'R', (['"""plot1 <- ggplot(dat, aes(x = factor(status, levels = status), y = values, stat = "identity"))"""'], {}), '(\'plot1 <- ggplot(dat, aes(x = factor(status, levels = status), y = values, stat = "identity"))\'\n )\n', (14922, 15024), True, 'from rpy2.robjects import r as R\n'), ((15028, 15073), 'rpy2.robjects.r', 'R', (['"""plot1 + geom_boxplot() + scale_y_log10()"""'], {}), "('plot1 + geom_boxplot() + scale_y_log10()')\n", (15029, 15073), True, 'from rpy2.robjects import r as R\n'), ((15082, 15109), 'rpy2.robjects.r', 'R', (['(\'ggsave("%s")\' % outfile)'], {}), '(\'ggsave("%s")\' % outfile)\n', (15083, 15109), True, 'from rpy2.robjects import r as R\n'), ((15858, 15943), 'rpy2.robjects.r', 'R', (['(\'dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' % infile\n )'], {}), '(\'dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n infile)\n', (15859, 15943), True, 'from rpy2.robjects import r as R\n'), ((15948, 15978), 'rpy2.robjects.r', 'R', (['"""rownames(dat) <- dat$taxa"""'], {}), "('rownames(dat) <- dat$taxa')\n", (15949, 15978), True, 'from rpy2.robjects import r as R\n'), ((15987, 16019), 'rpy2.robjects.r', 'R', (['"""dat <- dat[, 1:ncol(dat)-1]"""'], {}), "('dat <- dat[, 1:ncol(dat)-1]')\n", (15988, 16019), True, 'from rpy2.robjects import r as R\n'), ((16028, 16053), 'rpy2.robjects.r', 'R', (['"""pc <- prcomp(t(dat))"""'], {}), "('pc <- prcomp(t(dat))')\n", (16029, 16053), True, 'from rpy2.robjects import r as R\n'), ((16062, 16147), 'rpy2.robjects.r', 'R', (['"""conds <- unlist(strsplit(colnames(dat), ".R[0-9]"))[seq(1, ncol(dat)*2, 2)]"""'], {}), '(\'conds <- unlist(strsplit(colnames(dat), ".R[0-9]"))[seq(1, ncol(dat)*2, 2)]\'\n )\n', (16063, 16147), True, 'from rpy2.robjects import r as R\n'), ((16151, 16237), 'rpy2.robjects.r', 'R', (['"""conds <- unlist(strsplit(conds, ".", fixed = T))[seq(2, length(conds)*2, 2)]"""'], {}), '(\'conds <- unlist(strsplit(conds, ".", fixed = T))[seq(2, length(conds)*2, 2)]\'\n )\n', (16152, 16237), True, 'from rpy2.robjects import r as R\n'), ((16288, 16309), 'rpy2.robjects.r', 'R', (['"""library(ggplot2)"""'], {}), "('library(ggplot2)')\n", (16289, 16309), True, 'from rpy2.robjects import r as R\n'), ((16318, 16346), 'rpy2.robjects.r', 'R', (['"""pcs <- data.frame(pc$x)"""'], {}), "('pcs <- data.frame(pc$x)')\n", (16319, 16346), True, 'from rpy2.robjects import r as R\n'), ((16355, 16377), 'rpy2.robjects.r', 'R', (['"""pcs$cond <- conds"""'], {}), "('pcs$cond <- conds')\n", (16356, 16377), True, 'from rpy2.robjects import r as R\n'), ((16415, 16483), 'rpy2.robjects.r', 'R', (['"""imps <- c(summary(pc)$importance[2], summary(pc)$importance[5])"""'], {}), "('imps <- c(summary(pc)$importance[2], summary(pc)$importance[5])')\n", (16416, 16483), True, 'from rpy2.robjects import r as R\n'), ((16492, 16581), 'rpy2.robjects.r', 'R', (['"""p <- ggplot(pcs, aes(x = PC1, y = PC2, colour = cond, size = 3)) + geom_point()"""'], {}), "('p <- ggplot(pcs, aes(x = PC1, y = PC2, colour = cond, size = 3)) + geom_point()'\n )\n", (16493, 16581), True, 'from rpy2.robjects import r as R\n'), ((16585, 16629), 'rpy2.robjects.r', 'R', (['"""p2 <- p + xlab(imps[1]) + ylab(imps[2])"""'], {}), "('p2 <- p + xlab(imps[1]) + ylab(imps[2])')\n", (16586, 16629), True, 'from rpy2.robjects import r as R\n'), ((16638, 16727), 'rpy2.robjects.r', 'R', (['"""p3 <- p2 + scale_colour_manual(values = c("slateGrey", "green", "red", "blue"))"""'], {}), '(\'p3 <- p2 + scale_colour_manual(values = c("slateGrey", "green", "red", "blue"))\'\n )\n', (16639, 16727), True, 'from rpy2.robjects import r as R\n'), ((16731, 16803), 'rpy2.robjects.r', 'R', (["('p3 + xlim(c(-%i, %i)) + ylim(c(-%i, %i))' % (xlim, xlim, ylim, ylim))"], {}), "('p3 + xlim(c(-%i, %i)) + ylim(c(-%i, %i))' % (xlim, xlim, ylim, ylim))\n", (16732, 16803), True, 'from rpy2.robjects import r as R\n'), ((16812, 16844), 'rpy2.robjects.r', 'R', (['(\'ggsave("%s")\' % outname_plot)'], {}), '(\'ggsave("%s")\' % outname_plot)\n', (16813, 16844), True, 'from rpy2.robjects import r as R\n'), ((16877, 16914), 'rpy2.robjects.r', 'R', (['"""loads <- data.frame(pc$rotation)"""'], {}), "('loads <- data.frame(pc$rotation)')\n", (16878, 16914), True, 'from rpy2.robjects import r as R\n'), ((16923, 16957), 'rpy2.robjects.r', 'R', (['"""loads$taxa <- rownames(loads)"""'], {}), "('loads$taxa <- rownames(loads)')\n", (16924, 16957), True, 'from rpy2.robjects import r as R\n'), ((17348, 17369), 'rpy2.robjects.r', 'R', (['"""library(ggplot2)"""'], {}), "('library(ggplot2)')\n", (17349, 17369), True, 'from rpy2.robjects import r as R\n'), ((17378, 17396), 'rpy2.robjects.r', 'R', (['"""library(grid)"""'], {}), "('library(grid)')\n", (17379, 17396), True, 'from rpy2.robjects import r as R\n'), ((17405, 17490), 'rpy2.robjects.r', 'R', (['(\'dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' % infile\n )'], {}), '(\'dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n infile)\n', (17406, 17490), True, 'from rpy2.robjects import r as R\n'), ((17500, 17543), 'rpy2.robjects.r', 'R', (['"""top5pc1 <- dat[order(-dat$PC1),][1:5,]"""'], {}), "('top5pc1 <- dat[order(-dat$PC1),][1:5,]')\n", (17501, 17543), True, 'from rpy2.robjects import r as R\n'), ((17552, 17597), 'rpy2.robjects.r', 'R', (['"""bottom5pc1 <- dat[order(dat$PC1),][1:5,]"""'], {}), "('bottom5pc1 <- dat[order(dat$PC1),][1:5,]')\n", (17553, 17597), True, 'from rpy2.robjects import r as R\n'), ((17606, 17649), 'rpy2.robjects.r', 'R', (['"""top5pc2 <- dat[order(-dat$PC2),][1:5,]"""'], {}), "('top5pc2 <- dat[order(-dat$PC2),][1:5,]')\n", (17607, 17649), True, 'from rpy2.robjects import r as R\n'), ((17658, 17703), 'rpy2.robjects.r', 'R', (['"""bottom5pc2 <- dat[order(dat$PC2),][1:5,]"""'], {}), "('bottom5pc2 <- dat[order(dat$PC2),][1:5,]')\n", (17659, 17703), True, 'from rpy2.robjects import r as R\n'), ((17712, 17786), 'rpy2.robjects.r', 'R', (['"""totext <- data.frame(rbind(top5pc1, bottom5pc1, top5pc2, bottom5pc2))"""'], {}), "('totext <- data.frame(rbind(top5pc1, bottom5pc1, top5pc2, bottom5pc2))')\n", (17713, 17786), True, 'from rpy2.robjects import r as R\n'), ((17797, 17812), 'rpy2.robjects.r', 'R', (['"""dat$x <- 0"""'], {}), "('dat$x <- 0')\n", (17798, 17812), True, 'from rpy2.robjects import r as R\n'), ((17821, 17836), 'rpy2.robjects.r', 'R', (['"""dat$y <- 0"""'], {}), "('dat$y <- 0')\n", (17822, 17836), True, 'from rpy2.robjects import r as R\n'), ((17845, 17924), 'rpy2.robjects.r', 'R', (['"""p <- ggplot(dat, aes(x = x, y = y, xend = PC1, yend = PC2, colour = taxa))"""'], {}), "('p <- ggplot(dat, aes(x = x, y = y, xend = PC1, yend = PC2, colour = taxa))')\n", (17846, 17924), True, 'from rpy2.robjects import r as R\n'), ((17933, 18001), 'rpy2.robjects.r', 'R', (['"""p2 <- p + geom_segment(arrow = arrow(length = unit(0.2, "cm")))"""'], {}), '(\'p2 <- p + geom_segment(arrow = arrow(length = unit(0.2, "cm")))\')\n', (17934, 18001), True, 'from rpy2.robjects import r as R\n'), ((18010, 18144), 'rpy2.robjects.r', 'R', (['"""p2 + geom_text(data = totext, aes(x = PC1, y = PC2, label = totext$taxa, size = 6)) + xlim(c(-0.5,0.5)) + ylim(c(-0.5,0.25))"""'], {}), "('p2 + geom_text(data = totext, aes(x = PC1, y = PC2, label = totext$taxa, size = 6)) + xlim(c(-0.5,0.5)) + ylim(c(-0.5,0.25))'\n )\n", (18011, 18144), True, 'from rpy2.robjects import r as R\n'), ((18148, 18175), 'rpy2.robjects.r', 'R', (['(\'ggsave("%s")\' % outfile)'], {}), '(\'ggsave("%s")\' % outfile)\n', (18149, 18175), True, 'from rpy2.robjects import r as R\n'), ((19656, 19677), 'rpy2.robjects.r', 'R', (['"""library(ggplot2)"""'], {}), "('library(ggplot2)')\n", (19657, 19677), True, 'from rpy2.robjects import r as R\n'), ((19686, 19706), 'rpy2.robjects.r', 'R', (['"""library(gtools)"""'], {}), "('library(gtools)')\n", (19687, 19706), True, 'from rpy2.robjects import r as R\n'), ((19715, 19736), 'rpy2.robjects.r', 'R', (['"""library(reshape)"""'], {}), "('library(reshape)')\n", (19716, 19736), True, 'from rpy2.robjects import r as R\n'), ((19746, 19831), 'rpy2.robjects.r', 'R', (['(\'dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' % infile\n )'], {}), '(\'dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n infile)\n', (19747, 19831), True, 'from rpy2.robjects import r as R\n'), ((19836, 19866), 'rpy2.robjects.r', 'R', (['"""rownames(dat) <- dat$taxa"""'], {}), "('rownames(dat) <- dat$taxa')\n", (19837, 19866), True, 'from rpy2.robjects import r as R\n'), ((19909, 19940), 'rpy2.robjects.r', 'R', (['"""dat <- dat[,1:ncol(dat)-1]"""'], {}), "('dat <- dat[,1:ncol(dat)-1]')\n", (19910, 19940), True, 'from rpy2.robjects import r as R\n'), ((19949, 20013), 'rpy2.robjects.r', 'R', (['"""dat.percent <- data.frame(apply(dat, 2, function(x) x*100))"""'], {}), "('dat.percent <- data.frame(apply(dat, 2, function(x) x*100))')\n", (19950, 20013), True, 'from rpy2.robjects import r as R\n'), ((20050, 20391), 'rpy2.robjects.r', 'R', (['"""candidates <- c("Peptoniphilus",\n "Deferribacter",\n "Escherichia",\n "Lactobacillus",\n "Turicibacter",\n "Akkermansia",\n "Bifidobacterium",\n "Methylacidiphilum")"""'], {}), '("""candidates <- c("Peptoniphilus",\n "Deferribacter",\n "Escherichia",\n "Lactobacillus",\n "Turicibacter",\n "Akkermansia",\n "Bifidobacterium",\n "Methylacidiphilum")"""\n )\n', (20051, 20391), True, 'from rpy2.robjects import r as R\n'), ((20396, 20440), 'rpy2.robjects.r', 'R', (['"""dat.percent <- dat.percent[candidates,]"""'], {}), "('dat.percent <- dat.percent[candidates,]')\n", (20397, 20440), True, 'from rpy2.robjects import r as R\n'), ((20449, 20515), 'rpy2.robjects.r', 'R', (['"""dat.percent <- dat.percent[,mixedsort(colnames(dat.percent))]"""'], {}), "('dat.percent <- dat.percent[,mixedsort(colnames(dat.percent))]')\n", (20450, 20515), True, 'from rpy2.robjects import r as R\n'), ((20581, 20627), 'rpy2.robjects.r', 'R', (['"""dat.percent$taxa <- rownames(dat.percent)"""'], {}), "('dat.percent$taxa <- rownames(dat.percent)')\n", (20582, 20627), True, 'from rpy2.robjects import r as R\n'), ((20670, 20693), 'CGATPipelines.Pipeline.snip', 'P.snip', (['outfile', '""".pdf"""'], {}), "(outfile, '.pdf')\n", (20676, 20693), True, 'import CGATPipelines.Pipeline as P\n'), ((20698, 20735), 'rpy2.robjects.r', 'R', (['"""dat.percent <- melt(dat.percent)"""'], {}), "('dat.percent <- melt(dat.percent)')\n", (20699, 20735), True, 'from rpy2.robjects import r as R\n'), ((20744, 20858), 'rpy2.robjects.r', 'R', (['"""conds <- unlist(strsplit(as.character(dat.percent$variable), ".R[0-9]"))[seq(1, nrow(dat.percent)*2, 2)]"""'], {}), '(\'conds <- unlist(strsplit(as.character(dat.percent$variable), ".R[0-9]"))[seq(1, nrow(dat.percent)*2, 2)]\'\n )\n', (20745, 20858), True, 'from rpy2.robjects import r as R\n'), ((20862, 20948), 'rpy2.robjects.r', 'R', (['"""conds <- unlist(strsplit(conds, ".", fixed = T))[seq(2, length(conds)*2, 2)]"""'], {}), '(\'conds <- unlist(strsplit(conds, ".", fixed = T))[seq(2, length(conds)*2, 2)]\'\n )\n', (20863, 20948), True, 'from rpy2.robjects import r as R\n'), ((20954, 20984), 'rpy2.robjects.r', 'R', (['"""dat.percent$cond <- conds"""'], {}), "('dat.percent$cond <- conds')\n", (20955, 20984), True, 'from rpy2.robjects import r as R\n'), ((20993, 21563), 'rpy2.robjects.r', 'R', (['("""for (taxon in candidates){\n outname <- paste("%s", paste("_", taxon, sep=""), ".pdf", sep="")\n dat.percent.restrict <- dat.percent[dat.percent$taxa==taxon,]\n plot1 <- ggplot(dat.percent.restrict, \n aes(x=factor(cond, levels=c("WT","aIL10R", "Hh", "HhaIL10R")), \n y=value, group=cond, colour=cond, label=variable))\n plot1 + geom_boxplot() + geom_jitter() + geom_text() + scale_colour_manual(values=c("darkGreen", "red", "grey", "blue"))\n ggsave(outname)}"""\n % outname)'], {}), '(\n """for (taxon in candidates){\n outname <- paste("%s", paste("_", taxon, sep=""), ".pdf", sep="")\n dat.percent.restrict <- dat.percent[dat.percent$taxa==taxon,]\n plot1 <- ggplot(dat.percent.restrict, \n aes(x=factor(cond, levels=c("WT","aIL10R", "Hh", "HhaIL10R")), \n y=value, group=cond, colour=cond, label=variable))\n plot1 + geom_boxplot() + geom_jitter() + geom_text() + scale_colour_manual(values=c("darkGreen", "red", "grey", "blue"))\n ggsave(outname)}"""\n % outname)\n', (20994, 21563), True, 'from rpy2.robjects import r as R\n'), ((21990, 22076), 'rpy2.robjects.r', 'R', (['(\'rna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n rnadiff)'], {}), '(\'rna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n rnadiff)\n', (21991, 22076), True, 'from rpy2.robjects import r as R\n'), ((22081, 22167), 'rpy2.robjects.r', 'R', (['(\'dna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n dnadiff)'], {}), '(\'dna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n dnadiff)\n', (22082, 22167), True, 'from rpy2.robjects import r as R\n'), ((22172, 22235), 'rpy2.robjects.r', 'R', (['"""rna <- rna[rna$group1 == "HhaIL10R" & rna$group2 == "WT",]"""'], {}), '(\'rna <- rna[rna$group1 == "HhaIL10R" & rna$group2 == "WT",]\')\n', (22173, 22235), True, 'from rpy2.robjects import r as R\n'), ((22244, 22307), 'rpy2.robjects.r', 'R', (['"""dna <- dna[dna$group1 == "HhaIL10R" & dna$group2 == "WT",]"""'], {}), '(\'dna <- dna[dna$group1 == "HhaIL10R" & dna$group2 == "WT",]\')\n', (22245, 22307), True, 'from rpy2.robjects import r as R\n'), ((22321, 22351), 'rpy2.robjects.r', 'R', (['"""rownames(rna) <- rna$taxa"""'], {}), "('rownames(rna) <- rna$taxa')\n", (22322, 22351), True, 'from rpy2.robjects import r as R\n'), ((22360, 22390), 'rpy2.robjects.r', 'R', (['"""rownames(dna) <- dna$taxa"""'], {}), "('rownames(dna) <- dna$taxa')\n", (22361, 22390), True, 'from rpy2.robjects import r as R\n'), ((22400, 22431), 'rpy2.robjects.r', 'R', (['"""rna <- rna[,1:ncol(rna)-1]"""'], {}), "('rna <- rna[,1:ncol(rna)-1]')\n", (22401, 22431), True, 'from rpy2.robjects import r as R\n'), ((22440, 22471), 'rpy2.robjects.r', 'R', (['"""dna <- dna[,1:ncol(dna)-1]"""'], {}), "('dna <- dna[,1:ncol(dna)-1]')\n", (22441, 22471), True, 'from rpy2.robjects import r as R\n'), ((22531, 22583), 'rpy2.robjects.r', 'R', (['"""keep <- intersect(rownames(rna), rownames(dna))"""'], {}), "('keep <- intersect(rownames(rna), rownames(dna))')\n", (22532, 22583), True, 'from rpy2.robjects import r as R\n'), ((22592, 22614), 'rpy2.robjects.r', 'R', (['"""rna <- rna[keep,]"""'], {}), "('rna <- rna[keep,]')\n", (22593, 22614), True, 'from rpy2.robjects import r as R\n'), ((22623, 22645), 'rpy2.robjects.r', 'R', (['"""dna <- dna[keep,]"""'], {}), "('dna <- dna[keep,]')\n", (22624, 22645), True, 'from rpy2.robjects import r as R\n'), ((22655, 22682), 'rpy2.robjects.r', 'R', (['"""rna.ratio <- rna$logFC"""'], {}), "('rna.ratio <- rna$logFC')\n", (22656, 22682), True, 'from rpy2.robjects import r as R\n'), ((22691, 22718), 'rpy2.robjects.r', 'R', (['"""dna.ratio <- dna$logFC"""'], {}), "('dna.ratio <- dna$logFC')\n", (22692, 22718), True, 'from rpy2.robjects import r as R\n'), ((22727, 22754), 'rpy2.robjects.r', 'R', (['"""rna.p <- rna$adj.P.Val"""'], {}), "('rna.p <- rna$adj.P.Val')\n", (22728, 22754), True, 'from rpy2.robjects import r as R\n'), ((22763, 22790), 'rpy2.robjects.r', 'R', (['"""dna.p <- dna$adj.P.Val"""'], {}), "('dna.p <- dna$adj.P.Val')\n", (22764, 22790), True, 'from rpy2.robjects import r as R\n'), ((22804, 23093), 'rpy2.robjects.r', 'R', (['"""ratio <- data.frame(gene = keep, \n dna = dna.ratio, \n rna = rna.ratio, \n pdna = dna.p, \n prna = rna.p, \n ratio = rna.ratio - dna.ratio)"""'], {}), '("""ratio <- data.frame(gene = keep, \n dna = dna.ratio, \n rna = rna.ratio, \n pdna = dna.p, \n prna = rna.p, \n ratio = rna.ratio - dna.ratio)"""\n )\n', (22805, 23093), True, 'from rpy2.robjects import r as R\n'), ((23093, 23279), 'rpy2.robjects.r', 'R', (['("""write.table(ratio, \n file = "%s", \n sep = "\t", \n row.names = F, \n quote = F)"""\n % outfile)'], {}), '(\n """write.table(ratio, \n file = "%s", \n sep = "\t", \n row.names = F, \n quote = F)"""\n % outfile)\n', (23094, 23279), True, 'from rpy2.robjects import r as R\n'), ((23855, 23884), 'CGAT.IOTools.openFile', 'IOTools.openFile', (['RNADNARatio'], {}), '(RNADNARatio)\n', (23871, 23884), True, 'import CGAT.IOTools as IOTools\n'), ((23915, 23945), 'CGAT.IOTools.openFile', 'IOTools.openFile', (['outfile', '"""w"""'], {}), "(outfile, 'w')\n", (23931, 23945), True, 'import CGAT.IOTools as IOTools\n'), ((25232, 25253), 'rpy2.robjects.r', 'R', (['"""library(ggplot2)"""'], {}), "('library(ggplot2)')\n", (25233, 25253), True, 'from rpy2.robjects import r as R\n'), ((25282, 25367), 'rpy2.robjects.r', 'R', (['(\'dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' % infile\n )'], {}), '(\'dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n infile)\n', (25283, 25367), True, 'from rpy2.robjects import r as R\n'), ((25398, 25500), 'rpy2.robjects.r', 'R', (['"""cog2gene <- read.csv("goi.tsv", header = F, stringsAsFactors = F, sep = "\t", row.names = 1)"""'], {}), '(\'cog2gene <- read.csv("goi.tsv", header = F, stringsAsFactors = F, sep = "\\t", row.names = 1)\'\n )\n', (25399, 25500), True, 'from rpy2.robjects import r as R\n'), ((25566, 25607), 'rpy2.robjects.r', 'R', (['"""dat$status[dat$status == "NS"] = "z\\""""'], {}), '(\'dat$status[dat$status == "NS"] = "z"\')\n', (25567, 25607), True, 'from rpy2.robjects import r as R\n'), ((25616, 25638), 'rpy2.robjects.r', 'R', (['"""genes <- dat$gene"""'], {}), "('genes <- dat$gene')\n", (25617, 25638), True, 'from rpy2.robjects import r as R\n'), ((25671, 25703), 'rpy2.robjects.r', 'R', (['"""mod1 <- lm(dat$rna~dat$dna)"""'], {}), "('mod1 <- lm(dat$rna~dat$dna)')\n", (25672, 25703), True, 'from rpy2.robjects import r as R\n'), ((25712, 25742), 'rpy2.robjects.r', 'R', (['"""intercept <- mod1[[1]][1]"""'], {}), "('intercept <- mod1[[1]][1]')\n", (25713, 25742), True, 'from rpy2.robjects import r as R\n'), ((25751, 25776), 'rpy2.robjects.r', 'R', (['"""slope = mod1[[1]][2]"""'], {}), "('slope = mod1[[1]][2]')\n", (25752, 25776), True, 'from rpy2.robjects import r as R\n'), ((25785, 25810), 'rpy2.robjects.r', 'R', (['"""print(summary(mod1))"""'], {}), "('print(summary(mod1))')\n", (25786, 25810), True, 'from rpy2.robjects import r as R\n'), ((25847, 25917), 'rpy2.robjects.r', 'R', (['"""pred.ints <- predict(mod1, interval = "prediction", level = 0.95)"""'], {}), '(\'pred.ints <- predict(mod1, interval = "prediction", level = 0.95)\')\n', (25848, 25917), True, 'from rpy2.robjects import r as R\n'), ((25951, 25980), 'rpy2.robjects.r', 'R', (['"""dat$lwr <- pred.ints[,2]"""'], {}), "('dat$lwr <- pred.ints[,2]')\n", (25952, 25980), True, 'from rpy2.robjects import r as R\n'), ((25989, 26018), 'rpy2.robjects.r', 'R', (['"""dat$upr <- pred.ints[,3]"""'], {}), "('dat$upr <- pred.ints[,3]')\n", (25990, 26018), True, 'from rpy2.robjects import r as R\n'), ((26049, 26084), 'rpy2.robjects.r', 'R', (['"""dat$goi <- cog2gene[dat$gene,]"""'], {}), "('dat$goi <- cog2gene[dat$gene,]')\n", (26050, 26084), True, 'from rpy2.robjects import r as R\n'), ((26093, 26147), 'rpy2.robjects.r', 'R', (['"""dat$pointsize <- ifelse(!(is.na(dat$goi)), 10, 1)"""'], {}), "('dat$pointsize <- ifelse(!(is.na(dat$goi)), 10, 1)')\n", (26094, 26147), True, 'from rpy2.robjects import r as R\n'), ((26168, 26244), 'rpy2.robjects.r', 'R', (['"""plot1 <- ggplot(dat, aes(x = dna, y = rna, alpha = 1, colour = status))"""'], {}), "('plot1 <- ggplot(dat, aes(x = dna, y = rna, alpha = 1, colour = status))')\n", (26169, 26244), True, 'from rpy2.robjects import r as R\n'), ((26254, 26321), 'rpy2.robjects.r', 'R', (['"""plot2 <- plot1 + geom_point(shape = 18, aes(size = pointsize))"""'], {}), "('plot2 <- plot1 + geom_point(shape = 18, aes(size = pointsize))')\n", (26255, 26321), True, 'from rpy2.robjects import r as R\n'), ((26330, 26385), 'rpy2.robjects.r', 'R', (['"""plot3 <- plot2 + scale_size_area() + xlim(c(-5,5))"""'], {}), "('plot3 <- plot2 + scale_size_area() + xlim(c(-5,5))')\n", (26331, 26385), True, 'from rpy2.robjects import r as R\n'), ((26395, 26869), 'rpy2.robjects.r', 'R', (['"""plot4 <- plot3 + scale_colour_manual(values = c("blue", \n "brown",\n "darkGreen", \n "orange", \n "purple", \n "red", \n "grey"))"""'], {}), '("""plot4 <- plot3 + scale_colour_manual(values = c("blue", \n "brown",\n "darkGreen", \n "orange", \n "purple", \n "red", \n "grey"))"""\n )\n', (26396, 26869), True, 'from rpy2.robjects import r as R\n'), ((26869, 26940), 'rpy2.robjects.r', 'R', (['"""plot5 <- plot4 + geom_abline(intercept = intercept, slope = slope)"""'], {}), "('plot5 <- plot4 + geom_abline(intercept = intercept, slope = slope)')\n", (26870, 26940), True, 'from rpy2.robjects import r as R\n'), ((26977, 27075), 'rpy2.robjects.r', 'R', (['"""plot6 <- plot5 + geom_line(aes(x = dna, y = lwr), linetype = "dashed", colour = "black")"""'], {}), '(\'plot6 <- plot5 + geom_line(aes(x = dna, y = lwr), linetype = "dashed", colour = "black")\'\n )\n', (26978, 27075), True, 'from rpy2.robjects import r as R\n'), ((27079, 27177), 'rpy2.robjects.r', 'R', (['"""plot7 <- plot6 + geom_line(aes(x = dna, y = upr), linetype = "dashed", colour = "black")"""'], {}), '(\'plot7 <- plot6 + geom_line(aes(x = dna, y = upr), linetype = "dashed", colour = "black")\'\n )\n', (27080, 27177), True, 'from rpy2.robjects import r as R\n'), ((27181, 27221), 'rpy2.robjects.r', 'R', (['"""plot7 + geom_text(aes(label = goi))"""'], {}), "('plot7 + geom_text(aes(label = goi))')\n", (27182, 27221), True, 'from rpy2.robjects import r as R\n'), ((27230, 27257), 'rpy2.robjects.r', 'R', (['(\'ggsave("%s")\' % outfile)'], {}), '(\'ggsave("%s")\' % outfile)\n', (27231, 27257), True, 'from rpy2.robjects import r as R\n'), ((27629, 27714), 'rpy2.robjects.r', 'R', (['(\'dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' % infile\n )'], {}), '(\'dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n infile)\n', (27630, 27714), True, 'from rpy2.robjects import r as R\n'), ((27781, 27803), 'rpy2.robjects.r', 'R', (['"""genes <- dat$gene"""'], {}), "('genes <- dat$gene')\n", (27782, 27803), True, 'from rpy2.robjects import r as R\n'), ((27836, 27868), 'rpy2.robjects.r', 'R', (['"""mod1 <- lm(dat$rna~dat$dna)"""'], {}), "('mod1 <- lm(dat$rna~dat$dna)')\n", (27837, 27868), True, 'from rpy2.robjects import r as R\n'), ((27905, 27975), 'rpy2.robjects.r', 'R', (['"""pred.ints <- predict(mod1, interval = "prediction", level = 0.95)"""'], {}), '(\'pred.ints <- predict(mod1, interval = "prediction", level = 0.95)\')\n', (27906, 27975), True, 'from rpy2.robjects import r as R\n'), ((28009, 28038), 'rpy2.robjects.r', 'R', (['"""dat$lwr <- pred.ints[,2]"""'], {}), "('dat$lwr <- pred.ints[,2]')\n", (28010, 28038), True, 'from rpy2.robjects import r as R\n'), ((28047, 28076), 'rpy2.robjects.r', 'R', (['"""dat$upr <- pred.ints[,3]"""'], {}), "('dat$upr <- pred.ints[,3]')\n", (28048, 28076), True, 'from rpy2.robjects import r as R\n'), ((28168, 28247), 'rpy2.robjects.r', 'R', (['"""dat$pi_status[dat$rna > dat$upr & dat$status == "up.RNA"] <- "diff.up.rna\\""""'], {}), '(\'dat$pi_status[dat$rna > dat$upr & dat$status == "up.RNA"] <- "diff.up.rna"\')\n', (28169, 28247), True, 'from rpy2.robjects import r as R\n'), ((28256, 28344), 'rpy2.robjects.r', 'R', (['"""dat$pi_status[dat$rna > dat$upr & dat$status == "down.DNA"] <- "diff.down.dna\\""""'], {}), '(\'dat$pi_status[dat$rna > dat$upr & dat$status == "down.DNA"] <- "diff.down.dna"\'\n )\n', (28257, 28344), True, 'from rpy2.robjects import r as R\n'), ((28348, 28433), 'rpy2.robjects.r', 'R', (['"""dat$pi_status[dat$rna > dat$upr & dat$status == "up.both"] <- "diff.up.rna\\""""'], {}), '(\'dat$pi_status[dat$rna > dat$upr & dat$status == "up.both"] <- "diff.up.rna"\'\n )\n', (28349, 28433), True, 'from rpy2.robjects import r as R\n'), ((28438, 28526), 'rpy2.robjects.r', 'R', (['"""dat$pi_status[dat$rna < dat$lwr & dat$status == "down.RNA"] <- "diff.down.rna\\""""'], {}), '(\'dat$pi_status[dat$rna < dat$lwr & dat$status == "down.RNA"] <- "diff.down.rna"\'\n )\n', (28439, 28526), True, 'from rpy2.robjects import r as R\n'), ((28530, 28609), 'rpy2.robjects.r', 'R', (['"""dat$pi_status[dat$rna < dat$lwr & dat$status == "up.DNA"] <- "diff.up.dna\\""""'], {}), '(\'dat$pi_status[dat$rna < dat$lwr & dat$status == "up.DNA"] <- "diff.up.dna"\')\n', (28531, 28609), True, 'from rpy2.robjects import r as R\n'), ((28618, 28707), 'rpy2.robjects.r', 'R', (['"""dat$pi_status[dat$rna < dat$lwr & dat$status == "down.both"] <- "diff.down.rna\\""""'], {}), '(\'dat$pi_status[dat$rna < dat$lwr & dat$status == "down.both"] <- "diff.down.rna"\'\n )\n', (28619, 28707), True, 'from rpy2.robjects import r as R\n'), ((28732, 28818), 'rpy2.robjects.r', 'R', (['(\'write.table(dat, file = "%s", sep = "\\t", quote = F, row.names = F)\' %\n outfile)'], {}), '(\'write.table(dat, file = "%s", sep = "\\t", quote = F, row.names = F)\' %\n outfile)\n', (28733, 28818), True, 'from rpy2.robjects import r as R\n'), ((29269, 29293), 'CGAT.IOTools.openFile', 'IOTools.openFile', (['infile'], {}), '(infile)\n', (29285, 29293), True, 'import CGAT.IOTools as IOTools\n'), ((29592, 29616), 'CGAT.IOTools.openFile', 'IOTools.openFile', (['infile'], {}), '(infile)\n', (29608, 29616), True, 'import CGAT.IOTools as IOTools\n'), ((30197, 30221), 'pandas.DataFrame', 'pandas.DataFrame', (['result'], {}), '(result)\n', (30213, 30221), False, 'import pandas\n'), ((30679, 30783), 'rpy2.robjects.r', 'R', (['(\'anno <- read.csv("%s", header=T, stringsAsFactors=F, sep="\\t", row.names=1)\'\n % annotations)'], {}), '(\n \'anno <- read.csv("%s", header=T, stringsAsFactors=F, sep="\\t", row.names=1)\'\n % annotations)\n', (30680, 30783), True, 'from rpy2.robjects import r as R\n'), ((30782, 30828), 'rpy2.robjects.r', 'R', (['"""anno.no.pathways <- anno[,1:ncol(anno)-1]"""'], {}), "('anno.no.pathways <- anno[,1:ncol(anno)-1]')\n", (30783, 30828), True, 'from rpy2.robjects import r as R\n'), ((30837, 30910), 'rpy2.robjects.r', 'R', (['"""anno.p <- sweep(anno.no.pathways, 2, colSums(anno.no.pathways), "/")"""'], {}), '(\'anno.p <- sweep(anno.no.pathways, 2, colSums(anno.no.pathways), "/")\')\n', (30838, 30910), True, 'from rpy2.robjects import r as R\n'), ((30919, 30958), 'rpy2.robjects.r', 'R', (['"""anno.p$average <- rowMeans(anno.p)"""'], {}), "('anno.p$average <- rowMeans(anno.p)')\n", (30920, 30958), True, 'from rpy2.robjects import r as R\n'), ((30967, 30999), 'rpy2.robjects.r', 'R', (['"""anno.p$pathway <- anno$taxa"""'], {}), "('anno.p$pathway <- anno$taxa')\n", (30968, 30999), True, 'from rpy2.robjects import r as R\n'), ((31027, 31125), 'rpy2.robjects.r', 'R', (['(\'mat <- read.csv("%s", header=T, stringsAsFactors=F, sep="\\t", row.names=1)\' %\n matrix)'], {}), '(\n \'mat <- read.csv("%s", header=T, stringsAsFactors=F, sep="\\t", row.names=1)\'\n % matrix)\n', (31028, 31125), True, 'from rpy2.robjects import r as R\n'), ((31124, 31154), 'rpy2.robjects.r', 'R', (['"""mat <- data.frame(t(mat))"""'], {}), "('mat <- data.frame(t(mat))')\n", (31125, 31154), True, 'from rpy2.robjects import r as R\n'), ((31163, 31192), 'rpy2.robjects.r', 'R', (['"""mat$ref <- rownames(mat)"""'], {}), "('mat$ref <- rownames(mat)')\n", (31164, 31192), True, 'from rpy2.robjects import r as R\n'), ((31234, 31983), 'rpy2.robjects.r', 'R', (['"""for (pathway in unique(anno.p$pathway)){\n if (pathway == "Function unknown"){next}\n # some weirness with some names\n pw <- gsub("/", "_", pathway)\n outname <- paste("candidate_pathways.dir", paste(pw, "tsv", sep = "."), sep="/")\n outname <- gsub(" ", "_", outname)\n print(outname)\n anno.p2 <- anno.p[anno.p$pathway == pathway,]\n anno.p2 <- anno.p2[order(anno.p2$average, decreasing=T),]\n # top 10\n# anno.p2 <- anno.p2[1:10,]\n # merge with matrix\n mat2 <- mat[rownames(anno.p2),]\n mat2$pathway <- anno.p2$pathway\n write.table(mat2, file=outname, sep="\t", row.names=F)}"""'], {}), '("""for (pathway in unique(anno.p$pathway)){\n if (pathway == "Function unknown"){next}\n # some weirness with some names\n pw <- gsub("/", "_", pathway)\n outname <- paste("candidate_pathways.dir", paste(pw, "tsv", sep = "."), sep="/")\n outname <- gsub(" ", "_", outname)\n print(outname)\n anno.p2 <- anno.p[anno.p$pathway == pathway,]\n anno.p2 <- anno.p2[order(anno.p2$average, decreasing=T),]\n # top 10\n# anno.p2 <- anno.p2[1:10,]\n # merge with matrix\n mat2 <- mat[rownames(anno.p2),]\n mat2$pathway <- anno.p2$pathway\n write.table(mat2, file=outname, sep="\t", row.names=F)}"""\n )\n', (31235, 31983), True, 'from rpy2.robjects import r as R\n'), ((32291, 32313), 'CGATPipelines.Pipeline.getTempFilename', 'P.getTempFilename', (['"""."""'], {}), "('.')\n", (32308, 32313), True, 'import CGATPipelines.Pipeline as P\n'), ((32446, 32453), 'CGATPipelines.Pipeline.run', 'P.run', ([], {}), '()\n', (32451, 32453), True, 'import CGATPipelines.Pipeline as P\n'), ((32458, 32479), 'rpy2.robjects.r', 'R', (['"""library(ggplot2)"""'], {}), "('library(ggplot2)')\n", (32459, 32479), True, 'from rpy2.robjects import r as R\n'), ((32488, 32506), 'rpy2.robjects.r', 'R', (['"""library(plyr)"""'], {}), "('library(plyr)')\n", (32489, 32506), True, 'from rpy2.robjects import r as R\n'), ((32515, 32536), 'rpy2.robjects.r', 'R', (['"""library(reshape)"""'], {}), "('library(reshape)')\n", (32516, 32536), True, 'from rpy2.robjects import r as R\n'), ((32545, 32616), 'rpy2.robjects.r', 'R', (['(\'dat <-read.csv("%s", header=T, stringsAsFactors=F, sep="\\t")\' % tmp)'], {}), '(\'dat <-read.csv("%s", header=T, stringsAsFactors=F, sep="\\t")\' % tmp)\n', (32546, 32616), True, 'from rpy2.robjects import r as R\n'), ((32625, 32644), 'rpy2.robjects.r', 'R', (['"""t <- ncol(dat)"""'], {}), "('t <- ncol(dat)')\n", (32626, 32644), True, 'from rpy2.robjects import r as R\n'), ((32653, 32677), 'rpy2.robjects.r', 'R', (['"""dat <- na.omit(dat)"""'], {}), "('dat <- na.omit(dat)')\n", (32654, 32677), True, 'from rpy2.robjects import r as R\n'), ((32686, 32714), 'rpy2.robjects.r', 'R', (['"""pathways <- dat$pathway"""'], {}), "('pathways <- dat$pathway')\n", (32687, 32714), True, 'from rpy2.robjects import r as R\n'), ((32723, 32755), 'rpy2.robjects.r', 'R', (['"""dat2 <- dat[,1:ncol(dat)-1]"""'], {}), "('dat2 <- dat[,1:ncol(dat)-1]')\n", (32724, 32755), True, 'from rpy2.robjects import r as R\n'), ((32764, 32798), 'rpy2.robjects.r', 'R', (['"""dat2 <- dat2[,1:ncol(dat2)-1]"""'], {}), "('dat2 <- dat2[,1:ncol(dat2)-1]')\n", (32765, 32798), True, 'from rpy2.robjects import r as R\n'), ((32873, 32943), 'rpy2.robjects.r', 'R', (['"""col.sums <- data.frame(t(sapply(split(dat2, pathways), colSums)))"""'], {}), "('col.sums <- data.frame(t(sapply(split(dat2, pathways), colSums)))')\n", (32874, 32943), True, 'from rpy2.robjects import r as R\n'), ((32952, 32995), 'rpy2.robjects.r', 'R', (['"""rownames(col.sums) <- unique(pathways)"""'], {}), "('rownames(col.sums) <- unique(pathways)')\n", (32953, 32995), True, 'from rpy2.robjects import r as R\n'), ((33096, 33148), 'rpy2.robjects.r', 'R', (['"""total.taxa <- data.frame(rowSums(col.sums > 0))"""'], {}), "('total.taxa <- data.frame(rowSums(col.sums > 0))')\n", (33097, 33148), True, 'from rpy2.robjects import r as R\n'), ((33157, 33202), 'rpy2.robjects.r', 'R', (['"""total.taxa$pathway <- rownames(col.sums)"""'], {}), "('total.taxa$pathway <- rownames(col.sums)')\n", (33158, 33202), True, 'from rpy2.robjects import r as R\n'), ((33234, 33302), 'rpy2.robjects.r', 'R', (['"""total.taxa <- total.taxa[order(total.taxa[,1], decreasing=T), ]"""'], {}), "('total.taxa <- total.taxa[order(total.taxa[,1], decreasing=T), ]')\n", (33235, 33302), True, 'from rpy2.robjects import r as R\n'), ((33315, 33365), 'rpy2.robjects.r', 'R', (['"""colnames(total.taxa) <- c("value", "pathway")"""'], {}), '(\'colnames(total.taxa) <- c("value", "pathway")\')\n', (33316, 33365), True, 'from rpy2.robjects import r as R\n'), ((33375, 33479), 'rpy2.robjects.r', 'R', (['"""plot1 <- ggplot(total.taxa, aes(x=factor(pathway,levels=pathway), y=value/t, stat="identity"))"""'], {}), '(\'plot1 <- ggplot(total.taxa, aes(x=factor(pathway,levels=pathway), y=value/t, stat="identity"))\'\n )\n', (33376, 33479), True, 'from rpy2.robjects import r as R\n'), ((33483, 33570), 'rpy2.robjects.r', 'R', (['"""plot1 + geom_bar(stat="identity") + theme(axis.text.x=element_text(angle=90))"""'], {}), '(\'plot1 + geom_bar(stat="identity") + theme(axis.text.x=element_text(angle=90))\'\n )\n', (33484, 33570), True, 'from rpy2.robjects import r as R\n'), ((33575, 33602), 'rpy2.robjects.r', 'R', (['(\'ggsave("%s")\' % outfile)'], {}), '(\'ggsave("%s")\' % outfile)\n', (33576, 33602), True, 'from rpy2.robjects import r as R\n'), ((33611, 33625), 'os.unlink', 'os.unlink', (['tmp'], {}), '(tmp)\n', (33620, 33625), False, 'import os\n'), ((33990, 34011), 'rpy2.robjects.r', 'R', (['"""library(ggplot2)"""'], {}), "('library(ggplot2)')\n", (33991, 34011), True, 'from rpy2.robjects import r as R\n'), ((34020, 34040), 'rpy2.robjects.r', 'R', (['"""library(gplots)"""'], {}), "('library(gplots)')\n", (34021, 34040), True, 'from rpy2.robjects import r as R\n'), ((34049, 34071), 'rpy2.robjects.r', 'R', (['"""library(pheatmap)"""'], {}), "('library(pheatmap)')\n", (34050, 34071), True, 'from rpy2.robjects import r as R\n'), ((34080, 34165), 'rpy2.robjects.r', 'R', (['(\'mat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' % matrix\n )'], {}), '(\'mat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n matrix)\n', (34081, 34165), True, 'from rpy2.robjects import r as R\n'), ((34170, 34194), 'rpy2.robjects.r', 'R', (['"""mat <- na.omit(mat)"""'], {}), "('mat <- na.omit(mat)')\n", (34171, 34194), True, 'from rpy2.robjects import r as R\n'), ((34203, 34222), 'rpy2.robjects.r', 'R', (['"""print(mat$ref)"""'], {}), "('print(mat$ref)')\n", (34204, 34222), True, 'from rpy2.robjects import r as R\n'), ((34255, 34284), 'rpy2.robjects.r', 'R', (['"""rownames(mat) <- mat$ref"""'], {}), "('rownames(mat) <- mat$ref')\n", (34256, 34284), True, 'from rpy2.robjects import r as R\n'), ((34293, 34325), 'rpy2.robjects.r', 'R', (['"""mat2 <- mat[,1:ncol(mat)-1]"""'], {}), "('mat2 <- mat[,1:ncol(mat)-1]')\n", (34294, 34325), True, 'from rpy2.robjects import r as R\n'), ((34334, 34368), 'rpy2.robjects.r', 'R', (['"""mat2 <- mat2[,1:ncol(mat2)-1]"""'], {}), "('mat2 <- mat2[,1:ncol(mat2)-1]')\n", (34335, 34368), True, 'from rpy2.robjects import r as R\n'), ((34443, 34480), 'rpy2.robjects.r', 'R', (['"""mat2 <- mat2[,colSums(mat2) > 5]"""'], {}), "('mat2 <- mat2[,colSums(mat2) > 5]')\n", (34444, 34480), True, 'from rpy2.robjects import r as R\n'), ((34489, 34542), 'rpy2.robjects.r', 'R', (['"""cols <- colorRampPalette(c("white", "blue"))(75)"""'], {}), '(\'cols <- colorRampPalette(c("white", "blue"))(75)\')\n', (34490, 34542), True, 'from rpy2.robjects import r as R\n'), ((34551, 34575), 'rpy2.robjects.r', 'R', (['(\'pdf("%s")\' % outfile)'], {}), '(\'pdf("%s")\' % outfile)\n', (34552, 34575), True, 'from rpy2.robjects import r as R\n'), ((34584, 34758), 'rpy2.robjects.r', 'R', (['"""pheatmap(mat2, \n color=cols, \n cluster_cols=T, \n cluster_rows=T, \n cluster_method="ward.D2")"""'], {}), '("""pheatmap(mat2, \n color=cols, \n cluster_cols=T, \n cluster_rows=T, \n cluster_method="ward.D2")"""\n )\n', (34585, 34758), True, 'from rpy2.robjects import r as R\n'), ((35087, 35108), 'rpy2.robjects.r', 'R', (['"""library(ggplot2)"""'], {}), "('library(ggplot2)')\n", (35088, 35108), True, 'from rpy2.robjects import r as R\n'), ((35117, 35202), 'rpy2.robjects.r', 'R', (['(\'dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' % matrix\n )'], {}), '(\'dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n matrix)\n', (35118, 35202), True, 'from rpy2.robjects import r as R\n'), ((35207, 35311), 'rpy2.robjects.r', 'R', (['(\'annotations <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\'\n % annotations)'], {}), '(\n \'annotations <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\'\n % annotations)\n', (35208, 35311), True, 'from rpy2.robjects import r as R\n'), ((35311, 35346), 'rpy2.robjects.r', 'R', (['"""maximums <- apply(dat, 2, max)"""'], {}), "('maximums <- apply(dat, 2, max)')\n", (35312, 35346), True, 'from rpy2.robjects import r as R\n'), ((35355, 35419), 'rpy2.robjects.r', 'R', (['"""dat2 <- data.frame("cog" = colnames(dat), "max" = maximums)"""'], {}), '(\'dat2 <- data.frame("cog" = colnames(dat), "max" = maximums)\')\n', (35356, 35419), True, 'from rpy2.robjects import r as R\n'), ((35428, 35494), 'rpy2.robjects.r', 'R', (['"""dat3 <- merge(dat2, annotations, by.x = "cog", by.y = "gene")"""'], {}), '(\'dat3 <- merge(dat2, annotations, by.x = "cog", by.y = "gene")\')\n', (35429, 35494), True, 'from rpy2.robjects import r as R\n'), ((35503, 35575), 'rpy2.robjects.r', 'R', (['"""dat3$pi_status <- ifelse(dat3$status == "NS", "NS", dat3$pi_status)"""'], {}), '(\'dat3$pi_status <- ifelse(dat3$status == "NS", "NS", dat3$pi_status)\')\n', (35504, 35575), True, 'from rpy2.robjects import r as R\n'), ((35584, 35649), 'rpy2.robjects.r', 'R', (['"""dat3$pi_status[is.na(dat3$pi_status)] <- "other_significant\\""""'], {}), '(\'dat3$pi_status[is.na(dat3$pi_status)] <- "other_significant"\')\n', (35585, 35649), True, 'from rpy2.robjects import r as R\n'), ((35659, 35769), 'rpy2.robjects.r', 'R', (['"""plot1 <- ggplot(dat3, aes(x = as.numeric(as.character(max)), group = pi_status, colour = pi_status))"""'], {}), "('plot1 <- ggplot(dat3, aes(x = as.numeric(as.character(max)), group = pi_status, colour = pi_status))'\n )\n", (35660, 35769), True, 'from rpy2.robjects import r as R\n'), ((35773, 35816), 'rpy2.robjects.r', 'R', (['"""plot2 <- plot1 + stat_ecdf(size = 1.1)"""'], {}), "('plot2 <- plot1 + stat_ecdf(size = 1.1)')\n", (35774, 35816), True, 'from rpy2.robjects import r as R\n'), ((35825, 36193), 'rpy2.robjects.r', 'R', (['"""plot2 + scale_colour_manual(values = c("cyan3", \n "darkorchid", \n "black", \n "darkgoldenrod2", \n "grey", \n "darkBlue"))"""'], {}), '("""plot2 + scale_colour_manual(values = c("cyan3", \n "darkorchid", \n "black", \n "darkgoldenrod2", \n "grey", \n "darkBlue"))"""\n )\n', (35826, 36193), True, 'from rpy2.robjects import r as R\n'), ((36193, 36220), 'rpy2.robjects.r', 'R', (['(\'ggsave("%s")\' % outfile)'], {}), '(\'ggsave("%s")\' % outfile)\n', (36194, 36220), True, 'from rpy2.robjects import r as R\n'), ((36555, 36576), 'rpy2.robjects.r', 'R', (['"""library(ggplot2)"""'], {}), "('library(ggplot2)')\n", (36556, 36576), True, 'from rpy2.robjects import r as R\n'), ((36585, 36670), 'rpy2.robjects.r', 'R', (['(\'dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' % matrix\n )'], {}), '(\'dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n matrix)\n', (36586, 36670), True, 'from rpy2.robjects import r as R\n'), ((36675, 36779), 'rpy2.robjects.r', 'R', (['(\'annotations <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\'\n % annotations)'], {}), '(\n \'annotations <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\'\n % annotations)\n', (36676, 36779), True, 'from rpy2.robjects import r as R\n'), ((36779, 36814), 'rpy2.robjects.r', 'R', (['"""maximums <- apply(dat, 2, max)"""'], {}), "('maximums <- apply(dat, 2, max)')\n", (36780, 36814), True, 'from rpy2.robjects import r as R\n'), ((36823, 36887), 'rpy2.robjects.r', 'R', (['"""dat2 <- data.frame("cog" = colnames(dat), "max" = maximums)"""'], {}), '(\'dat2 <- data.frame("cog" = colnames(dat), "max" = maximums)\')\n', (36824, 36887), True, 'from rpy2.robjects import r as R\n'), ((36896, 36962), 'rpy2.robjects.r', 'R', (['"""dat3 <- merge(dat2, annotations, by.x = "cog", by.y = "gene")"""'], {}), '(\'dat3 <- merge(dat2, annotations, by.x = "cog", by.y = "gene")\')\n', (36897, 36962), True, 'from rpy2.robjects import r as R\n'), ((36971, 37043), 'rpy2.robjects.r', 'R', (['"""dat3$pi_status <- ifelse(dat3$status == "NS", "NS", dat3$pi_status)"""'], {}), '(\'dat3$pi_status <- ifelse(dat3$status == "NS", "NS", dat3$pi_status)\')\n', (36972, 37043), True, 'from rpy2.robjects import r as R\n'), ((37052, 37144), 'rpy2.robjects.r', 'R', (['"""diff.up.rna <- as.numeric(as.character(dat3$max[dat3$pi_status == "diff.up.rna"]))"""'], {}), '(\'diff.up.rna <- as.numeric(as.character(dat3$max[dat3$pi_status == "diff.up.rna"]))\'\n )\n', (37053, 37144), True, 'from rpy2.robjects import r as R\n'), ((37148, 37244), 'rpy2.robjects.r', 'R', (['"""diff.down.rna <- as.numeric(as.character(dat3$max[dat3$pi_status == "diff.down.rna"]))"""'], {}), '(\'diff.down.rna <- as.numeric(as.character(dat3$max[dat3$pi_status == "diff.down.rna"]))\'\n )\n', (37149, 37244), True, 'from rpy2.robjects import r as R\n'), ((37248, 37340), 'rpy2.robjects.r', 'R', (['"""diff.up.dna <- as.numeric(as.character(dat3$max[dat3$pi_status == "diff.up.dna"]))"""'], {}), '(\'diff.up.dna <- as.numeric(as.character(dat3$max[dat3$pi_status == "diff.up.dna"]))\'\n )\n', (37249, 37340), True, 'from rpy2.robjects import r as R\n'), ((37344, 37440), 'rpy2.robjects.r', 'R', (['"""diff.down.dna <- as.numeric(as.character(dat3$max[dat3$pi_status == "diff.down.dna"]))"""'], {}), '(\'diff.down.dna <- as.numeric(as.character(dat3$max[dat3$pi_status == "diff.down.dna"]))\'\n )\n', (37345, 37440), True, 'from rpy2.robjects import r as R\n'), ((37444, 37513), 'rpy2.robjects.r', 'R', (['"""ns <- as.numeric(as.character(dat3$max[dat3$pi_status == "NS"]))"""'], {}), '(\'ns <- as.numeric(as.character(dat3$max[dat3$pi_status == "NS"]))\')\n', (37445, 37513), True, 'from rpy2.robjects import r as R\n'), ((37542, 37578), 'rpy2.robjects.r', 'R', (['"""ks1 <- ks.test(diff.up.rna, ns)"""'], {}), "('ks1 <- ks.test(diff.up.rna, ns)')\n", (37543, 37578), True, 'from rpy2.robjects import r as R\n'), ((37587, 37625), 'rpy2.robjects.r', 'R', (['"""ks2 <- ks.test(diff.down.rna, ns)"""'], {}), "('ks2 <- ks.test(diff.down.rna, ns)')\n", (37588, 37625), True, 'from rpy2.robjects import r as R\n'), ((37635, 37671), 'rpy2.robjects.r', 'R', (['"""ks3 <- ks.test(diff.up.dna, ns)"""'], {}), "('ks3 <- ks.test(diff.up.dna, ns)')\n", (37636, 37671), True, 'from rpy2.robjects import r as R\n'), ((37680, 37718), 'rpy2.robjects.r', 'R', (['"""ks4 <- ks.test(diff.down.dna, ns)"""'], {}), "('ks4 <- ks.test(diff.down.dna, ns)')\n", (37681, 37718), True, 'from rpy2.robjects import r as R\n'), ((37728, 38304), 'rpy2.robjects.r', 'R', (['"""res <- data.frame("RNAGreaterThanDNA.up.pvalue" = ks1$p.value,\n "RNAGreaterThanDNA.up.D" = ks1$statistic,\n "RNAGreaterThanDNA.down.pvalue" = ks2$p.value,\n "RNAGreaterThanDNA.down.D" = ks2$statistic,\n "DNAGreaterThanRNA.up.pvalue" = ks3$p.value,\n "DNAGreaterThanRNA.up.D" = ks3$statistic,\n "DNAGreaterThanRNA.down.pvalue" = ks4$p.value,\n "DNAGreaterThanRNA.down.D" = ks4$statistic)"""'], {}), '("""res <- data.frame("RNAGreaterThanDNA.up.pvalue" = ks1$p.value,\n "RNAGreaterThanDNA.up.D" = ks1$statistic,\n "RNAGreaterThanDNA.down.pvalue" = ks2$p.value,\n "RNAGreaterThanDNA.down.D" = ks2$statistic,\n "DNAGreaterThanRNA.up.pvalue" = ks3$p.value,\n "DNAGreaterThanRNA.up.D" = ks3$statistic,\n "DNAGreaterThanRNA.down.pvalue" = ks4$p.value,\n "DNAGreaterThanRNA.down.D" = ks4$statistic)"""\n )\n', (37729, 38304), True, 'from rpy2.robjects import r as R\n'), ((38304, 38390), 'rpy2.robjects.r', 'R', (['(\'write.table(res, file = "%s", sep = "\\t", quote = F, row.names = F)\' %\n outfile)'], {}), '(\'write.table(res, file = "%s", sep = "\\t", quote = F, row.names = F)\' %\n outfile)\n', (38305, 38390), True, 'from rpy2.robjects import r as R\n'), ((38698, 38718), 'rpy2.robjects.r', 'R', (['"""library(gplots)"""'], {}), "('library(gplots)')\n", (38699, 38718), True, 'from rpy2.robjects import r as R\n'), ((38727, 38747), 'rpy2.robjects.r', 'R', (['"""library(gtools)"""'], {}), "('library(gtools)')\n", (38728, 38747), True, 'from rpy2.robjects import r as R\n'), ((38756, 38862), 'rpy2.robjects.r', 'R', (['(\'dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t", row.names = 1)\'\n % matrix)'], {}), '(\n \'dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t", row.names = 1)\'\n % matrix)\n', (38757, 38862), True, 'from rpy2.robjects import r as R\n'), ((38862, 38966), 'rpy2.robjects.r', 'R', (['(\'annotations <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\'\n % annotations)'], {}), '(\n \'annotations <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\'\n % annotations)\n', (38863, 38966), True, 'from rpy2.robjects import r as R\n'), ((38965, 39011), 'rpy2.robjects.r', 'R', (['"""rownames(annotations) <- annotations$gene"""'], {}), "('rownames(annotations) <- annotations$gene')\n", (38966, 39011), True, 'from rpy2.robjects import r as R\n'), ((39129, 39190), 'rpy2.robjects.r', 'R', (['"""genes <- intersect(rownames(annotations), colnames(dat))"""'], {}), "('genes <- intersect(rownames(annotations), colnames(dat))')\n", (39130, 39190), True, 'from rpy2.robjects import r as R\n'), ((39199, 39223), 'rpy2.robjects.r', 'R', (['"""dat <- dat[, genes]"""'], {}), "('dat <- dat[, genes]')\n", (39200, 39223), True, 'from rpy2.robjects import r as R\n'), ((39232, 39295), 'rpy2.robjects.r', 'R', (['"""dat <- dat[grep("unassigned", rownames(dat), invert = T),]"""'], {}), '(\'dat <- dat[grep("unassigned", rownames(dat), invert = T),]\')\n', (39233, 39295), True, 'from rpy2.robjects import r as R\n'), ((39305, 39333), 'rpy2.robjects.r', 'R', (['"""genera <- rownames(dat)"""'], {}), "('genera <- rownames(dat)')\n", (39306, 39333), True, 'from rpy2.robjects import r as R\n'), ((39342, 39370), 'rpy2.robjects.r', 'R', (['"""rownames(dat) <- genera"""'], {}), "('rownames(dat) <- genera')\n", (39343, 39370), True, 'from rpy2.robjects import r as R\n'), ((39379, 39406), 'rpy2.robjects.r', 'R', (['"""colnames(dat) <- genes"""'], {}), "('colnames(dat) <- genes')\n", (39380, 39406), True, 'from rpy2.robjects import r as R\n'), ((39415, 39454), 'rpy2.robjects.r', 'R', (['"""annotations <- annotations[genes,]"""'], {}), "('annotations <- annotations[genes,]')\n", (39416, 39454), True, 'from rpy2.robjects import r as R\n'), ((39464, 39526), 'rpy2.robjects.r', 'R', (['"""annotations <- annotations[order(annotations$pi_status),]"""'], {}), "('annotations <- annotations[order(annotations$pi_status),]')\n", (39465, 39526), True, 'from rpy2.robjects import r as R\n'), ((39607, 39679), 'rpy2.robjects.r', 'R', (['"""annotations <- annotations[annotations$pi_status == "diff.up.rna",]"""'], {}), '(\'annotations <- annotations[annotations$pi_status == "diff.up.rna",]\')\n', (39608, 39679), True, 'from rpy2.robjects import r as R\n'), ((39689, 39729), 'rpy2.robjects.r', 'R', (['"""annotations <- na.omit(annotations)"""'], {}), "('annotations <- na.omit(annotations)')\n", (39690, 39729), True, 'from rpy2.robjects import r as R\n'), ((39738, 39777), 'rpy2.robjects.r', 'R', (['"""dat <- dat[,rownames(annotations)]"""'], {}), "('dat <- dat[,rownames(annotations)]')\n", (39739, 39777), True, 'from rpy2.robjects import r as R\n'), ((39787, 39863), 'rpy2.robjects.r', 'R', (['"""annotation <- data.frame(cluster = as.character(annotations$pi_status))"""'], {}), "('annotation <- data.frame(cluster = as.character(annotations$pi_status))')\n", (39788, 39863), True, 'from rpy2.robjects import r as R\n'), ((39872, 39922), 'rpy2.robjects.r', 'R', (['"""rownames(annotation) <- rownames(annotations)"""'], {}), "('rownames(annotation) <- rownames(annotations)')\n", (39873, 39922), True, 'from rpy2.robjects import r as R\n'), ((39933, 39958), 'rpy2.robjects.r', 'R', (['"""colors1 <- c("grey")"""'], {}), '(\'colors1 <- c("grey")\')\n', (39934, 39958), True, 'from rpy2.robjects import r as R\n'), ((39967, 40006), 'rpy2.robjects.r', 'R', (['"""names(colors1) <- c("diff.up.rna")"""'], {}), '(\'names(colors1) <- c("diff.up.rna")\')\n', (39968, 40006), True, 'from rpy2.robjects import r as R\n'), ((40016, 40059), 'rpy2.robjects.r', 'R', (['"""anno_colors <- list(cluster = colors1)"""'], {}), "('anno_colors <- list(cluster = colors1)')\n", (40017, 40059), True, 'from rpy2.robjects import r as R\n'), ((40069, 40127), 'rpy2.robjects.r', 'R', (['"""cols <- colorRampPalette(c("white", "darkBlue"))(150)"""'], {}), '(\'cols <- colorRampPalette(c("white", "darkBlue"))(150)\')\n', (40070, 40127), True, 'from rpy2.robjects import r as R\n'), ((40137, 40177), 'rpy2.robjects.r', 'R', (['"""dat <- dat[,colSums(dat > 50) >= 1]"""'], {}), "('dat <- dat[,colSums(dat > 50) >= 1]')\n", (40138, 40177), True, 'from rpy2.robjects import r as R\n'), ((40186, 40226), 'rpy2.robjects.r', 'R', (['"""dat <- dat[rowSums(dat > 10) >= 1,]"""'], {}), "('dat <- dat[rowSums(dat > 10) >= 1,]')\n", (40187, 40226), True, 'from rpy2.robjects import r as R\n'), ((40279, 40332), 'rpy2.robjects.r', 'R', (['"""dat2 <- data.frame(t(apply(dat, 1, as.numeric)))"""'], {}), "('dat2 <- data.frame(t(apply(dat, 1, as.numeric)))')\n", (40280, 40332), True, 'from rpy2.robjects import r as R\n'), ((40341, 40377), 'rpy2.robjects.r', 'R', (['"""colnames(dat2) <- colnames(dat)"""'], {}), "('colnames(dat2) <- colnames(dat)')\n", (40342, 40377), True, 'from rpy2.robjects import r as R\n'), ((40387, 40436), 'rpy2.robjects.r', 'R', (['(\'pdf("%s", height = 10, width = 15)\' % outfile)'], {}), '(\'pdf("%s", height = 10, width = 15)\' % outfile)\n', (40388, 40436), True, 'from rpy2.robjects import r as R\n'), ((40445, 40467), 'rpy2.robjects.r', 'R', (['"""library(pheatmap)"""'], {}), "('library(pheatmap)')\n", (40446, 40467), True, 'from rpy2.robjects import r as R\n'), ((40476, 40839), 'rpy2.robjects.r', 'R', (['"""pheatmap(dat2, \n clustering_distance_cols = "manhattan",\n clustering_method = "ward",\n annotation = annotation,\n annotation_colors = anno_colors,\n cluster_rows = T,\n cluster_cols = F,\n color = cols,\n fontsize = 8)"""'], {}), '("""pheatmap(dat2, \n clustering_distance_cols = "manhattan",\n clustering_method = "ward",\n annotation = annotation,\n annotation_colors = anno_colors,\n cluster_rows = T,\n cluster_cols = F,\n color = cols,\n fontsize = 8)"""\n )\n', (40477, 40839), True, 'from rpy2.robjects import r as R\n'), ((41348, 41369), 'rpy2.robjects.r', 'R', (['"""library(ggplot2)"""'], {}), "('library(ggplot2)')\n", (41349, 41369), True, 'from rpy2.robjects import r as R\n'), ((41405, 41500), 'rpy2.robjects.r', 'R', (['(\'dna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n taxa_cog_dnadiff)'], {}), '(\'dna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n taxa_cog_dnadiff)\n', (41406, 41500), True, 'from rpy2.robjects import r as R\n'), ((41505, 41568), 'rpy2.robjects.r', 'R', (['"""dna <- dna[dna$group2 == "WT" & dna$group1 == "HhaIL10R",]"""'], {}), '(\'dna <- dna[dna$group2 == "WT" & dna$group1 == "HhaIL10R",]\')\n', (41506, 41568), True, 'from rpy2.robjects import r as R\n'), ((41577, 41672), 'rpy2.robjects.r', 'R', (['(\'rna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n taxa_cog_rnadiff)'], {}), '(\'rna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n taxa_cog_rnadiff)\n', (41578, 41672), True, 'from rpy2.robjects import r as R\n'), ((41677, 41740), 'rpy2.robjects.r', 'R', (['"""rna <- rna[rna$group2 == "WT" & rna$group1 == "HhaIL10R",]"""'], {}), '(\'rna <- rna[rna$group2 == "WT" & rna$group1 == "HhaIL10R",]\')\n', (41678, 41740), True, 'from rpy2.robjects import r as R\n'), ((41775, 41869), 'rpy2.robjects.r', 'R', (['(\'dna.cog <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n cog_dnadiff)'], {}), '(\'dna.cog <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n cog_dnadiff)\n', (41776, 41869), True, 'from rpy2.robjects import r as R\n'), ((41874, 41953), 'rpy2.robjects.r', 'R', (['"""dna.cog <- dna.cog[dna.cog$group2 == "WT" & dna.cog$group1 == "HhaIL10R",]"""'], {}), '(\'dna.cog <- dna.cog[dna.cog$group2 == "WT" & dna.cog$group1 == "HhaIL10R",]\')\n', (41875, 41953), True, 'from rpy2.robjects import r as R\n'), ((41962, 42056), 'rpy2.robjects.r', 'R', (['(\'rna.cog <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n cog_rnadiff)'], {}), '(\'rna.cog <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\\t")\' %\n cog_rnadiff)\n', (41963, 42056), True, 'from rpy2.robjects import r as R\n'), ((42061, 42140), 'rpy2.robjects.r', 'R', (['"""rna.cog <- rna.cog[rna.cog$group2 == "WT" & rna.cog$group1 == "HhaIL10R",]"""'], {}), '(\'rna.cog <- rna.cog[rna.cog$group2 == "WT" & rna.cog$group1 == "HhaIL10R",]\')\n', (42062, 42140), True, 'from rpy2.robjects import r as R\n'), ((42183, 42434), 'rpy2.robjects.r', 'R', (['"""dat <- merge(dna, rna, \n by.x = "taxa", \n by.y = "taxa", \n all.x = T, \n all.y = T, \n suffixes = c(".dna.taxa.cog", ".rna.taxa.cog"))"""'], {}), '("""dat <- merge(dna, rna, \n by.x = "taxa", \n by.y = "taxa", \n all.x = T, \n all.y = T, \n suffixes = c(".dna.taxa.cog", ".rna.taxa.cog"))"""\n )\n', (42184, 42434), True, 'from rpy2.robjects import r as R\n'), ((42454, 42479), 'rpy2.robjects.r', 'R', (['"""dat[is.na(dat)] <- 0"""'], {}), "('dat[is.na(dat)] <- 0')\n", (42455, 42479), True, 'from rpy2.robjects import r as R\n'), ((42565, 42644), 'rpy2.robjects.r', 'R', (['"""cogs <- c("COG0783", "COG2837", "COG0435","COG5520", "COG0508", "COG0852")"""'], {}), '(\'cogs <- c("COG0783", "COG2837", "COG0435","COG5520", "COG0508", "COG0852")\')\n', (42566, 42644), True, 'from rpy2.robjects import r as R\n'), ((42808, 44219), 'rpy2.robjects.r', 'R', (['"""for (cog in cogs){\n dat2 <- dat[grep(cog, dat$taxa),]\n dna.cog2 <- dna.cog[grep(cog, dna.cog$taxa),]\n rna.cog2 <- rna.cog[grep(cog, rna.cog$taxa),]\n\n # add the data for COG fold changes and abundance\n dat3 <- data.frame("genus" = append(dat2$taxa, cog),\n "dna.fold" = append(dat2$logFC.dna.taxa.cog, dna.cog2$logFC),\n "rna.fold" = append(dat2$logFC.rna.taxa.cog, rna.cog2$logFC),\n "abundance" = append(dat2$AveExpr.rna.taxa.cog, rna.cog2$AveExpr))\n \n suffix <- paste(cog, "scatters.pdf", sep = ".")\n outname <- paste("scatterplot_genus_cog_fold.dir", suffix, sep = "/")\n\n plot1 <- ggplot(dat3, aes(x = dna.fold, y = rna.fold, size = log10(abundance), label = genus))\n plot2 <- plot1 + geom_point(shape = 18) \n plot3 <- plot2 + geom_text(hjust = 0.5, vjust = 1) + scale_size(range = c(3,6))\n plot4 <- plot3 + geom_abline(intercept = 0, slope = 1, colour = "blue") \n plot5 <- plot4 + geom_hline(yintercept = c(-1,1), linetype = "dashed")\n plot6 <- plot5 + geom_vline(xintercept = c(-1,1), linetype = "dashed")\n plot7 <- plot6 + geom_hline(yintercept = 0) + geom_vline(xintercept = 0)\n ggsave(outname)\n }"""'], {}), '("""for (cog in cogs){\n dat2 <- dat[grep(cog, dat$taxa),]\n dna.cog2 <- dna.cog[grep(cog, dna.cog$taxa),]\n rna.cog2 <- rna.cog[grep(cog, rna.cog$taxa),]\n\n # add the data for COG fold changes and abundance\n dat3 <- data.frame("genus" = append(dat2$taxa, cog),\n "dna.fold" = append(dat2$logFC.dna.taxa.cog, dna.cog2$logFC),\n "rna.fold" = append(dat2$logFC.rna.taxa.cog, rna.cog2$logFC),\n "abundance" = append(dat2$AveExpr.rna.taxa.cog, rna.cog2$AveExpr))\n \n suffix <- paste(cog, "scatters.pdf", sep = ".")\n outname <- paste("scatterplot_genus_cog_fold.dir", suffix, sep = "/")\n\n plot1 <- ggplot(dat3, aes(x = dna.fold, y = rna.fold, size = log10(abundance), label = genus))\n plot2 <- plot1 + geom_point(shape = 18) \n plot3 <- plot2 + geom_text(hjust = 0.5, vjust = 1) + scale_size(range = c(3,6))\n plot4 <- plot3 + geom_abline(intercept = 0, slope = 1, colour = "blue") \n plot5 <- plot4 + geom_hline(yintercept = c(-1,1), linetype = "dashed")\n plot6 <- plot5 + geom_vline(xintercept = c(-1,1), linetype = "dashed")\n plot7 <- plot6 + geom_hline(yintercept = 0) + geom_vline(xintercept = 0)\n ggsave(outname)\n }"""\n )\n', (42809, 44219), True, 'from rpy2.robjects import r as R\n'), ((1048, 1072), 'os.path.basename', 'os.path.basename', (['infile'], {}), '(infile)\n', (1064, 1072), False, 'import os\n'), ((1549, 1575), 'itertools.product', 'itertools.product', (['ps', 'fcs'], {}), '(ps, fcs)\n', (1566, 1575), False, 'import itertools\n'), ((13516, 13547), 'rpy2.robjects.r', 'R', (['"""rna.distinct <- rep(0, 20)"""'], {}), "('rna.distinct <- rep(0, 20)')\n", (13517, 13547), True, 'from rpy2.robjects import r as R\n'), ((13570, 13603), 'rpy2.robjects.r', 'R', (['"""rna.distinct <- rna.distinct"""'], {}), "('rna.distinct <- rna.distinct')\n", (13571, 13603), True, 'from rpy2.robjects import r as R\n'), ((30089, 30104), 'numpy.mean', 'np.mean', (['values'], {}), '(values)\n', (30096, 30104), True, 'import numpy as np\n'), ((15778, 15810), 'CGATPipelines.Pipeline.snip', 'P.snip', (['outfile', '""".loadings.tsv"""'], {}), "(outfile, '.loadings.tsv')\n", (15784, 15810), True, 'import CGATPipelines.Pipeline as P\n')] |
# ------------------------------------------------------------------------------
# Test Formatting weeks
# ------------------------------------------------------------------------------
import sys
import datetime as dt
from django.test import TestCase, override_settings
import ls.joyous.utils.weeks
from ls.joyous.utils.weeks import (
_iso_year_start, _iso_info, _iso_num_weeks,
_gregorian_to_iso, _iso_to_gregorian, _iso_week_of_month)
from ls.joyous.utils.weeks import (
_ssweek_year_start, _ssweek_info, _ssweek_num_weeks,
_gregorian_to_ssweek, _ssweek_to_gregorian, _ssweek_of_month)
from django.utils.translation import override
from django.utils.formats import get_format
import importlib
# ------------------------------------------------------------------------------
class TestMondayStartingWeek(TestCase):
def testYearStart(self):
self.assertEqual(_iso_year_start(1991), dt.date(1990,12,31))
self.assertEqual(_iso_year_start(2006), dt.date(2006,1,2))
self.assertEqual(_iso_year_start(2020), dt.date(2019,12,30))
self.assertEqual(_iso_year_start(2036), dt.date(2035,12,31))
def testNumWeeksInYear(self):
self.assertEqual(_iso_num_weeks(1991), 52)
self.assertEqual(_iso_num_weeks(2006), 52)
self.assertEqual(_iso_num_weeks(2020), 53)
self.assertEqual(_iso_num_weeks(2036), 52)
def testWeekOfMonth(self):
self.assertEqual(_iso_week_of_month(dt.date(1990,5,31)), 4)
self.assertEqual(_iso_week_of_month(dt.date(2005,1,2)), 0)
self.assertEqual(_iso_week_of_month(dt.date(2021,12,13)), 2)
self.assertEqual(_iso_week_of_month(dt.date(2030,10,8)), 1)
def testGregorianToWeekDate(self):
self.assertEqual(_gregorian_to_iso(dt.date(1991,5,25)), (1991,21,6))
self.assertEqual(_gregorian_to_iso(dt.date(2007,1,2)), (2007,1,2))
self.assertEqual(_gregorian_to_iso(dt.date(2022,12,13)), (2022,50,2))
self.assertEqual(_gregorian_to_iso(dt.date(2035,12,31)), (2036,1,1))
self.assertEqual(_gregorian_to_iso(dt.date(2021,1,1)), (2020,53,5))
def testWeekToGregorianDate(self):
self.assertEqual(_iso_to_gregorian(1990,2,6), dt.date(1990,1,13))
self.assertEqual(_iso_to_gregorian(2005,20,1), dt.date(2005,5,16))
self.assertEqual(_iso_to_gregorian(2020,53,5), dt.date(2021,1,1))
self.assertEqual(_iso_to_gregorian(2035,6,7), dt.date(2035,2,11))
def testWeekInfo(self):
# (first_day, last_day, prev_year_num_weeks, year_num_weeks)
self.assertEqual(_iso_info(1991,2),
(dt.date(1991,1,7), dt.date(1991,1,13), 52, 52))
self.assertEqual(_iso_info(2006,20),
(dt.date(2006,5,15), dt.date(2006,5,21), 52, 52))
self.assertEqual(_iso_info(2020,40),
(dt.date(2020,9,28), dt.date(2020,10,4), 52, 53))
self.assertEqual(_iso_info(2036,21),
(dt.date(2036,5,19), dt.date(2036,5,25), 52, 52))
# ------------------------------------------------------------------------------
class TestSundayStartingWeek(TestCase):
def testYearStart(self):
self.assertEqual(_ssweek_year_start(1991), dt.date(1990,12,30))
self.assertEqual(_ssweek_year_start(2006), dt.date(2006,1,1))
self.assertEqual(_ssweek_year_start(2020), dt.date(2019,12,29))
self.assertEqual(_ssweek_year_start(2036), dt.date(2035,12,30))
def testNumWeeksInYear(self):
self.assertEqual(_ssweek_num_weeks(1991), 52)
self.assertEqual(_ssweek_num_weeks(2006), 52)
self.assertEqual(_ssweek_num_weeks(2020), 53)
self.assertEqual(_ssweek_num_weeks(2036), 53)
def testWeekOfMonth(self):
self.assertEqual(_ssweek_of_month(dt.date(1990,5,31)), 4)
self.assertEqual(_ssweek_of_month(dt.date(2005,1,2)), 1)
self.assertEqual(_ssweek_of_month(dt.date(2021,12,13)), 2)
self.assertEqual(_ssweek_of_month(dt.date(2030,10,8)), 1)
def testGregorianToWeekDate(self):
self.assertEqual(_gregorian_to_ssweek(dt.date(1991,5,25)), (1991,21,6))
self.assertEqual(_gregorian_to_ssweek(dt.date(2007,1,2)), (2007,1,2))
self.assertEqual(_gregorian_to_ssweek(dt.date(2022,12,13)), (2022,50,2))
self.assertEqual(_gregorian_to_ssweek(dt.date(2035,12,31)), (2036,1,1))
self.assertEqual(_gregorian_to_ssweek(dt.date(2019,12,1)), (2019,49,7))
self.assertEqual(_gregorian_to_ssweek(dt.date(2019,12,29)), (2020,1,7))
self.assertEqual(_gregorian_to_ssweek(dt.date(2021,1,1)), (2020,53,5))
def testWeekToGregorianDate(self):
self.assertEqual(_ssweek_to_gregorian(1990,2,6), dt.date(1990,1,12))
self.assertEqual(_ssweek_to_gregorian(2005,20,1), dt.date(2005,5,15))
self.assertEqual(_ssweek_to_gregorian(2020,53,5), dt.date(2020,12,31))
self.assertEqual(_ssweek_to_gregorian(2035,6,7), dt.date(2035,2,10))
def testWeekInfo(self):
# (first_day, last_day, prev_year_num_weeks, year_num_weeks)
self.assertEqual(_ssweek_info(1991,2),
(dt.date(1991,1,6), dt.date(1991,1,12), 52, 52))
self.assertEqual(_ssweek_info(2006,20),
(dt.date(2006,5,14), dt.date(2006,5,20), 52, 52))
self.assertEqual(_ssweek_info(2020,40),
(dt.date(2020,9,27), dt.date(2020,10,3), 52, 53))
self.assertEqual(_ssweek_info(2036,21),
(dt.date(2036,5,18), dt.date(2036,5,24), 52, 53))
# ------------------------------------------------------------------------------
class TestSetting(TestCase):
@override('en-gb')
def testMondayStartingWeek(self):
# FIRST_DAY_OF_WEEK is Monday for Great Britain
self.assertEqual(get_format('FIRST_DAY_OF_WEEK'), 1)
importlib.reload(ls.joyous.utils.weeks)
from ls.joyous.utils.weeks import (week_info, num_weeks_in_year,
gregorian_to_week_date, week_of_month, weekday_abbr, weekday_name,
_iso_info, _iso_num_weeks, _gregorian_to_iso, _iso_week_of_month)
self.assertIs(week_info, _iso_info)
self.assertIs(num_weeks_in_year, _iso_num_weeks)
self.assertIs(gregorian_to_week_date, _gregorian_to_iso)
self.assertIs(week_of_month, _iso_week_of_month)
self.assertEqual(weekday_abbr, ("Mon","Tue","Wed","Thu","Fri","Sat","Sun"))
self.assertEqual(weekday_name, ("Monday","Tuesday","Wednesday","Thursday",
"Friday","Saturday","Sunday"))
@override('en-au')
def testSundayStartingWeek(self):
# FIRST_DAY_OF_WEEK is Sunday for Australia
self.assertEqual(get_format('FIRST_DAY_OF_WEEK'), 0)
importlib.reload(ls.joyous.utils.weeks)
from ls.joyous.utils.weeks import (week_info, num_weeks_in_year,
gregorian_to_week_date, week_of_month, weekday_abbr, weekday_name,
_ssweek_info, _ssweek_num_weeks, _gregorian_to_ssweek, _ssweek_of_month)
self.assertIs(week_info, _ssweek_info)
self.assertIs(num_weeks_in_year, _ssweek_num_weeks)
self.assertIs(gregorian_to_week_date, _gregorian_to_ssweek)
self.assertIs(week_of_month, _ssweek_of_month)
self.assertEqual(weekday_abbr, ("Sun","Mon","Tue","Wed","Thu","Fri","Sat"))
self.assertEqual(weekday_name, ("Sunday","Monday","Tuesday","Wednesday","Thursday",
"Friday","Saturday"))
def testFirstDayOfWeek(self):
with override_settings(JOYOUS_FIRST_DAY_OF_WEEK = 0):
importlib.reload(ls.joyous.utils.weeks)
from ls.joyous.utils.weeks import weekday_abbr
self.assertEqual(weekday_abbr, ("Sun","Mon","Tue","Wed","Thu","Fri","Sat"))
with override_settings(JOYOUS_FIRST_DAY_OF_WEEK = 1):
importlib.reload(ls.joyous.utils.weeks)
from ls.joyous.utils.weeks import weekday_abbr
self.assertEqual(weekday_abbr, ("Mon","Tue","Wed","Thu","Fri","Sat","Sun"))
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
| [
"ls.joyous.utils.weeks._iso_year_start",
"ls.joyous.utils.weeks._iso_to_gregorian",
"ls.joyous.utils.weeks._ssweek_to_gregorian",
"ls.joyous.utils.weeks._ssweek_info",
"ls.joyous.utils.weeks._iso_num_weeks",
"ls.joyous.utils.weeks._ssweek_year_start",
"django.utils.translation.override",
"django.test.... | [((5694, 5711), 'django.utils.translation.override', 'override', (['"""en-gb"""'], {}), "('en-gb')\n", (5702, 5711), False, 'from django.utils.translation import override\n'), ((6620, 6637), 'django.utils.translation.override', 'override', (['"""en-au"""'], {}), "('en-au')\n", (6628, 6637), False, 'from django.utils.translation import override\n'), ((5875, 5914), 'importlib.reload', 'importlib.reload', (['ls.joyous.utils.weeks'], {}), '(ls.joyous.utils.weeks)\n', (5891, 5914), False, 'import importlib\n'), ((6797, 6836), 'importlib.reload', 'importlib.reload', (['ls.joyous.utils.weeks'], {}), '(ls.joyous.utils.weeks)\n', (6813, 6836), False, 'import importlib\n'), ((904, 925), 'ls.joyous.utils.weeks._iso_year_start', '_iso_year_start', (['(1991)'], {}), '(1991)\n', (919, 925), False, 'from ls.joyous.utils.weeks import _iso_year_start, _iso_info, _iso_num_weeks, _gregorian_to_iso, _iso_to_gregorian, _iso_week_of_month\n'), ((927, 948), 'datetime.date', 'dt.date', (['(1990)', '(12)', '(31)'], {}), '(1990, 12, 31)\n', (934, 948), True, 'import datetime as dt\n'), ((973, 994), 'ls.joyous.utils.weeks._iso_year_start', '_iso_year_start', (['(2006)'], {}), '(2006)\n', (988, 994), False, 'from ls.joyous.utils.weeks import _iso_year_start, _iso_info, _iso_num_weeks, _gregorian_to_iso, _iso_to_gregorian, _iso_week_of_month\n'), ((996, 1015), 'datetime.date', 'dt.date', (['(2006)', '(1)', '(2)'], {}), '(2006, 1, 2)\n', (1003, 1015), True, 'import datetime as dt\n'), ((1040, 1061), 'ls.joyous.utils.weeks._iso_year_start', '_iso_year_start', (['(2020)'], {}), '(2020)\n', (1055, 1061), False, 'from ls.joyous.utils.weeks import _iso_year_start, _iso_info, _iso_num_weeks, _gregorian_to_iso, _iso_to_gregorian, _iso_week_of_month\n'), ((1063, 1084), 'datetime.date', 'dt.date', (['(2019)', '(12)', '(30)'], {}), '(2019, 12, 30)\n', (1070, 1084), True, 'import datetime as dt\n'), ((1109, 1130), 'ls.joyous.utils.weeks._iso_year_start', '_iso_year_start', (['(2036)'], {}), '(2036)\n', (1124, 1130), False, 'from ls.joyous.utils.weeks import _iso_year_start, _iso_info, _iso_num_weeks, _gregorian_to_iso, _iso_to_gregorian, _iso_week_of_month\n'), ((1132, 1153), 'datetime.date', 'dt.date', (['(2035)', '(12)', '(31)'], {}), '(2035, 12, 31)\n', (1139, 1153), True, 'import datetime as dt\n'), ((1213, 1233), 'ls.joyous.utils.weeks._iso_num_weeks', '_iso_num_weeks', (['(1991)'], {}), '(1991)\n', (1227, 1233), False, 'from ls.joyous.utils.weeks import week_info, num_weeks_in_year, gregorian_to_week_date, week_of_month, weekday_abbr, weekday_name, _iso_info, _iso_num_weeks, _gregorian_to_iso, _iso_week_of_month\n'), ((1264, 1284), 'ls.joyous.utils.weeks._iso_num_weeks', '_iso_num_weeks', (['(2006)'], {}), '(2006)\n', (1278, 1284), False, 'from ls.joyous.utils.weeks import week_info, num_weeks_in_year, gregorian_to_week_date, week_of_month, weekday_abbr, weekday_name, _iso_info, _iso_num_weeks, _gregorian_to_iso, _iso_week_of_month\n'), ((1315, 1335), 'ls.joyous.utils.weeks._iso_num_weeks', '_iso_num_weeks', (['(2020)'], {}), '(2020)\n', (1329, 1335), False, 'from ls.joyous.utils.weeks import week_info, num_weeks_in_year, gregorian_to_week_date, week_of_month, weekday_abbr, weekday_name, _iso_info, _iso_num_weeks, _gregorian_to_iso, _iso_week_of_month\n'), ((1366, 1386), 'ls.joyous.utils.weeks._iso_num_weeks', '_iso_num_weeks', (['(2036)'], {}), '(2036)\n', (1380, 1386), False, 'from ls.joyous.utils.weeks import week_info, num_weeks_in_year, gregorian_to_week_date, week_of_month, weekday_abbr, weekday_name, _iso_info, _iso_num_weeks, _gregorian_to_iso, _iso_week_of_month\n'), ((2193, 2222), 'ls.joyous.utils.weeks._iso_to_gregorian', '_iso_to_gregorian', (['(1990)', '(2)', '(6)'], {}), '(1990, 2, 6)\n', (2210, 2222), False, 'from ls.joyous.utils.weeks import _iso_year_start, _iso_info, _iso_num_weeks, _gregorian_to_iso, _iso_to_gregorian, _iso_week_of_month\n'), ((2223, 2243), 'datetime.date', 'dt.date', (['(1990)', '(1)', '(13)'], {}), '(1990, 1, 13)\n', (2230, 2243), True, 'import datetime as dt\n'), ((2268, 2298), 'ls.joyous.utils.weeks._iso_to_gregorian', '_iso_to_gregorian', (['(2005)', '(20)', '(1)'], {}), '(2005, 20, 1)\n', (2285, 2298), False, 'from ls.joyous.utils.weeks import _iso_year_start, _iso_info, _iso_num_weeks, _gregorian_to_iso, _iso_to_gregorian, _iso_week_of_month\n'), ((2298, 2318), 'datetime.date', 'dt.date', (['(2005)', '(5)', '(16)'], {}), '(2005, 5, 16)\n', (2305, 2318), True, 'import datetime as dt\n'), ((2343, 2373), 'ls.joyous.utils.weeks._iso_to_gregorian', '_iso_to_gregorian', (['(2020)', '(53)', '(5)'], {}), '(2020, 53, 5)\n', (2360, 2373), False, 'from ls.joyous.utils.weeks import _iso_year_start, _iso_info, _iso_num_weeks, _gregorian_to_iso, _iso_to_gregorian, _iso_week_of_month\n'), ((2373, 2392), 'datetime.date', 'dt.date', (['(2021)', '(1)', '(1)'], {}), '(2021, 1, 1)\n', (2380, 2392), True, 'import datetime as dt\n'), ((2417, 2446), 'ls.joyous.utils.weeks._iso_to_gregorian', '_iso_to_gregorian', (['(2035)', '(6)', '(7)'], {}), '(2035, 6, 7)\n', (2434, 2446), False, 'from ls.joyous.utils.weeks import _iso_year_start, _iso_info, _iso_num_weeks, _gregorian_to_iso, _iso_to_gregorian, _iso_week_of_month\n'), ((2447, 2467), 'datetime.date', 'dt.date', (['(2035)', '(2)', '(11)'], {}), '(2035, 2, 11)\n', (2454, 2467), True, 'import datetime as dt\n'), ((2590, 2608), 'ls.joyous.utils.weeks._iso_info', '_iso_info', (['(1991)', '(2)'], {}), '(1991, 2)\n', (2599, 2608), False, 'from ls.joyous.utils.weeks import week_info, num_weeks_in_year, gregorian_to_week_date, week_of_month, weekday_abbr, weekday_name, _iso_info, _iso_num_weeks, _gregorian_to_iso, _iso_week_of_month\n'), ((2709, 2728), 'ls.joyous.utils.weeks._iso_info', '_iso_info', (['(2006)', '(20)'], {}), '(2006, 20)\n', (2718, 2728), False, 'from ls.joyous.utils.weeks import week_info, num_weeks_in_year, gregorian_to_week_date, week_of_month, weekday_abbr, weekday_name, _iso_info, _iso_num_weeks, _gregorian_to_iso, _iso_week_of_month\n'), ((2829, 2848), 'ls.joyous.utils.weeks._iso_info', '_iso_info', (['(2020)', '(40)'], {}), '(2020, 40)\n', (2838, 2848), False, 'from ls.joyous.utils.weeks import week_info, num_weeks_in_year, gregorian_to_week_date, week_of_month, weekday_abbr, weekday_name, _iso_info, _iso_num_weeks, _gregorian_to_iso, _iso_week_of_month\n'), ((2949, 2968), 'ls.joyous.utils.weeks._iso_info', '_iso_info', (['(2036)', '(21)'], {}), '(2036, 21)\n', (2958, 2968), False, 'from ls.joyous.utils.weeks import week_info, num_weeks_in_year, gregorian_to_week_date, week_of_month, weekday_abbr, weekday_name, _iso_info, _iso_num_weeks, _gregorian_to_iso, _iso_week_of_month\n'), ((3220, 3244), 'ls.joyous.utils.weeks._ssweek_year_start', '_ssweek_year_start', (['(1991)'], {}), '(1991)\n', (3238, 3244), False, 'from ls.joyous.utils.weeks import _ssweek_year_start, _ssweek_info, _ssweek_num_weeks, _gregorian_to_ssweek, _ssweek_to_gregorian, _ssweek_of_month\n'), ((3246, 3267), 'datetime.date', 'dt.date', (['(1990)', '(12)', '(30)'], {}), '(1990, 12, 30)\n', (3253, 3267), True, 'import datetime as dt\n'), ((3292, 3316), 'ls.joyous.utils.weeks._ssweek_year_start', '_ssweek_year_start', (['(2006)'], {}), '(2006)\n', (3310, 3316), False, 'from ls.joyous.utils.weeks import _ssweek_year_start, _ssweek_info, _ssweek_num_weeks, _gregorian_to_ssweek, _ssweek_to_gregorian, _ssweek_of_month\n'), ((3318, 3337), 'datetime.date', 'dt.date', (['(2006)', '(1)', '(1)'], {}), '(2006, 1, 1)\n', (3325, 3337), True, 'import datetime as dt\n'), ((3362, 3386), 'ls.joyous.utils.weeks._ssweek_year_start', '_ssweek_year_start', (['(2020)'], {}), '(2020)\n', (3380, 3386), False, 'from ls.joyous.utils.weeks import _ssweek_year_start, _ssweek_info, _ssweek_num_weeks, _gregorian_to_ssweek, _ssweek_to_gregorian, _ssweek_of_month\n'), ((3388, 3409), 'datetime.date', 'dt.date', (['(2019)', '(12)', '(29)'], {}), '(2019, 12, 29)\n', (3395, 3409), True, 'import datetime as dt\n'), ((3434, 3458), 'ls.joyous.utils.weeks._ssweek_year_start', '_ssweek_year_start', (['(2036)'], {}), '(2036)\n', (3452, 3458), False, 'from ls.joyous.utils.weeks import _ssweek_year_start, _ssweek_info, _ssweek_num_weeks, _gregorian_to_ssweek, _ssweek_to_gregorian, _ssweek_of_month\n'), ((3460, 3481), 'datetime.date', 'dt.date', (['(2035)', '(12)', '(30)'], {}), '(2035, 12, 30)\n', (3467, 3481), True, 'import datetime as dt\n'), ((3541, 3564), 'ls.joyous.utils.weeks._ssweek_num_weeks', '_ssweek_num_weeks', (['(1991)'], {}), '(1991)\n', (3558, 3564), False, 'from ls.joyous.utils.weeks import week_info, num_weeks_in_year, gregorian_to_week_date, week_of_month, weekday_abbr, weekday_name, _ssweek_info, _ssweek_num_weeks, _gregorian_to_ssweek, _ssweek_of_month\n'), ((3595, 3618), 'ls.joyous.utils.weeks._ssweek_num_weeks', '_ssweek_num_weeks', (['(2006)'], {}), '(2006)\n', (3612, 3618), False, 'from ls.joyous.utils.weeks import week_info, num_weeks_in_year, gregorian_to_week_date, week_of_month, weekday_abbr, weekday_name, _ssweek_info, _ssweek_num_weeks, _gregorian_to_ssweek, _ssweek_of_month\n'), ((3649, 3672), 'ls.joyous.utils.weeks._ssweek_num_weeks', '_ssweek_num_weeks', (['(2020)'], {}), '(2020)\n', (3666, 3672), False, 'from ls.joyous.utils.weeks import week_info, num_weeks_in_year, gregorian_to_week_date, week_of_month, weekday_abbr, weekday_name, _ssweek_info, _ssweek_num_weeks, _gregorian_to_ssweek, _ssweek_of_month\n'), ((3703, 3726), 'ls.joyous.utils.weeks._ssweek_num_weeks', '_ssweek_num_weeks', (['(2036)'], {}), '(2036)\n', (3720, 3726), False, 'from ls.joyous.utils.weeks import week_info, num_weeks_in_year, gregorian_to_week_date, week_of_month, weekday_abbr, weekday_name, _ssweek_info, _ssweek_num_weeks, _gregorian_to_ssweek, _ssweek_of_month\n'), ((4701, 4733), 'ls.joyous.utils.weeks._ssweek_to_gregorian', '_ssweek_to_gregorian', (['(1990)', '(2)', '(6)'], {}), '(1990, 2, 6)\n', (4721, 4733), False, 'from ls.joyous.utils.weeks import _ssweek_year_start, _ssweek_info, _ssweek_num_weeks, _gregorian_to_ssweek, _ssweek_to_gregorian, _ssweek_of_month\n'), ((4734, 4754), 'datetime.date', 'dt.date', (['(1990)', '(1)', '(12)'], {}), '(1990, 1, 12)\n', (4741, 4754), True, 'import datetime as dt\n'), ((4779, 4812), 'ls.joyous.utils.weeks._ssweek_to_gregorian', '_ssweek_to_gregorian', (['(2005)', '(20)', '(1)'], {}), '(2005, 20, 1)\n', (4799, 4812), False, 'from ls.joyous.utils.weeks import _ssweek_year_start, _ssweek_info, _ssweek_num_weeks, _gregorian_to_ssweek, _ssweek_to_gregorian, _ssweek_of_month\n'), ((4812, 4832), 'datetime.date', 'dt.date', (['(2005)', '(5)', '(15)'], {}), '(2005, 5, 15)\n', (4819, 4832), True, 'import datetime as dt\n'), ((4857, 4890), 'ls.joyous.utils.weeks._ssweek_to_gregorian', '_ssweek_to_gregorian', (['(2020)', '(53)', '(5)'], {}), '(2020, 53, 5)\n', (4877, 4890), False, 'from ls.joyous.utils.weeks import _ssweek_year_start, _ssweek_info, _ssweek_num_weeks, _gregorian_to_ssweek, _ssweek_to_gregorian, _ssweek_of_month\n'), ((4890, 4911), 'datetime.date', 'dt.date', (['(2020)', '(12)', '(31)'], {}), '(2020, 12, 31)\n', (4897, 4911), True, 'import datetime as dt\n'), ((4936, 4968), 'ls.joyous.utils.weeks._ssweek_to_gregorian', '_ssweek_to_gregorian', (['(2035)', '(6)', '(7)'], {}), '(2035, 6, 7)\n', (4956, 4968), False, 'from ls.joyous.utils.weeks import _ssweek_year_start, _ssweek_info, _ssweek_num_weeks, _gregorian_to_ssweek, _ssweek_to_gregorian, _ssweek_of_month\n'), ((4969, 4989), 'datetime.date', 'dt.date', (['(2035)', '(2)', '(10)'], {}), '(2035, 2, 10)\n', (4976, 4989), True, 'import datetime as dt\n'), ((5112, 5133), 'ls.joyous.utils.weeks._ssweek_info', '_ssweek_info', (['(1991)', '(2)'], {}), '(1991, 2)\n', (5124, 5133), False, 'from ls.joyous.utils.weeks import week_info, num_weeks_in_year, gregorian_to_week_date, week_of_month, weekday_abbr, weekday_name, _ssweek_info, _ssweek_num_weeks, _gregorian_to_ssweek, _ssweek_of_month\n'), ((5234, 5256), 'ls.joyous.utils.weeks._ssweek_info', '_ssweek_info', (['(2006)', '(20)'], {}), '(2006, 20)\n', (5246, 5256), False, 'from ls.joyous.utils.weeks import week_info, num_weeks_in_year, gregorian_to_week_date, week_of_month, weekday_abbr, weekday_name, _ssweek_info, _ssweek_num_weeks, _gregorian_to_ssweek, _ssweek_of_month\n'), ((5357, 5379), 'ls.joyous.utils.weeks._ssweek_info', '_ssweek_info', (['(2020)', '(40)'], {}), '(2020, 40)\n', (5369, 5379), False, 'from ls.joyous.utils.weeks import week_info, num_weeks_in_year, gregorian_to_week_date, week_of_month, weekday_abbr, weekday_name, _ssweek_info, _ssweek_num_weeks, _gregorian_to_ssweek, _ssweek_of_month\n'), ((5480, 5502), 'ls.joyous.utils.weeks._ssweek_info', '_ssweek_info', (['(2036)', '(21)'], {}), '(2036, 21)\n', (5492, 5502), False, 'from ls.joyous.utils.weeks import week_info, num_weeks_in_year, gregorian_to_week_date, week_of_month, weekday_abbr, weekday_name, _ssweek_info, _ssweek_num_weeks, _gregorian_to_ssweek, _ssweek_of_month\n'), ((5831, 5862), 'django.utils.formats.get_format', 'get_format', (['"""FIRST_DAY_OF_WEEK"""'], {}), "('FIRST_DAY_OF_WEEK')\n", (5841, 5862), False, 'from django.utils.formats import get_format\n'), ((6753, 6784), 'django.utils.formats.get_format', 'get_format', (['"""FIRST_DAY_OF_WEEK"""'], {}), "('FIRST_DAY_OF_WEEK')\n", (6763, 6784), False, 'from django.utils.formats import get_format\n'), ((7598, 7643), 'django.test.override_settings', 'override_settings', ([], {'JOYOUS_FIRST_DAY_OF_WEEK': '(0)'}), '(JOYOUS_FIRST_DAY_OF_WEEK=0)\n', (7615, 7643), False, 'from django.test import TestCase, override_settings\n'), ((7659, 7698), 'importlib.reload', 'importlib.reload', (['ls.joyous.utils.weeks'], {}), '(ls.joyous.utils.weeks)\n', (7675, 7698), False, 'import importlib\n'), ((7860, 7905), 'django.test.override_settings', 'override_settings', ([], {'JOYOUS_FIRST_DAY_OF_WEEK': '(1)'}), '(JOYOUS_FIRST_DAY_OF_WEEK=1)\n', (7877, 7905), False, 'from django.test import TestCase, override_settings\n'), ((7921, 7960), 'importlib.reload', 'importlib.reload', (['ls.joyous.utils.weeks'], {}), '(ls.joyous.utils.weeks)\n', (7937, 7960), False, 'import importlib\n'), ((1468, 1488), 'datetime.date', 'dt.date', (['(1990)', '(5)', '(31)'], {}), '(1990, 5, 31)\n', (1475, 1488), True, 'import datetime as dt\n'), ((1537, 1556), 'datetime.date', 'dt.date', (['(2005)', '(1)', '(2)'], {}), '(2005, 1, 2)\n', (1544, 1556), True, 'import datetime as dt\n'), ((1606, 1627), 'datetime.date', 'dt.date', (['(2021)', '(12)', '(13)'], {}), '(2021, 12, 13)\n', (1613, 1627), True, 'import datetime as dt\n'), ((1675, 1695), 'datetime.date', 'dt.date', (['(2030)', '(10)', '(8)'], {}), '(2030, 10, 8)\n', (1682, 1695), True, 'import datetime as dt\n'), ((1783, 1803), 'datetime.date', 'dt.date', (['(1991)', '(5)', '(25)'], {}), '(1991, 5, 25)\n', (1790, 1803), True, 'import datetime as dt\n'), ((1861, 1880), 'datetime.date', 'dt.date', (['(2007)', '(1)', '(2)'], {}), '(2007, 1, 2)\n', (1868, 1880), True, 'import datetime as dt\n'), ((1938, 1959), 'datetime.date', 'dt.date', (['(2022)', '(12)', '(13)'], {}), '(2022, 12, 13)\n', (1945, 1959), True, 'import datetime as dt\n'), ((2016, 2037), 'datetime.date', 'dt.date', (['(2035)', '(12)', '(31)'], {}), '(2035, 12, 31)\n', (2023, 2037), True, 'import datetime as dt\n'), ((2093, 2112), 'datetime.date', 'dt.date', (['(2021)', '(1)', '(1)'], {}), '(2021, 1, 1)\n', (2100, 2112), True, 'import datetime as dt\n'), ((2635, 2654), 'datetime.date', 'dt.date', (['(1991)', '(1)', '(7)'], {}), '(1991, 1, 7)\n', (2642, 2654), True, 'import datetime as dt\n'), ((2655, 2675), 'datetime.date', 'dt.date', (['(1991)', '(1)', '(13)'], {}), '(1991, 1, 13)\n', (2662, 2675), True, 'import datetime as dt\n'), ((2755, 2775), 'datetime.date', 'dt.date', (['(2006)', '(5)', '(15)'], {}), '(2006, 5, 15)\n', (2762, 2775), True, 'import datetime as dt\n'), ((2775, 2795), 'datetime.date', 'dt.date', (['(2006)', '(5)', '(21)'], {}), '(2006, 5, 21)\n', (2782, 2795), True, 'import datetime as dt\n'), ((2875, 2895), 'datetime.date', 'dt.date', (['(2020)', '(9)', '(28)'], {}), '(2020, 9, 28)\n', (2882, 2895), True, 'import datetime as dt\n'), ((2895, 2915), 'datetime.date', 'dt.date', (['(2020)', '(10)', '(4)'], {}), '(2020, 10, 4)\n', (2902, 2915), True, 'import datetime as dt\n'), ((2995, 3015), 'datetime.date', 'dt.date', (['(2036)', '(5)', '(19)'], {}), '(2036, 5, 19)\n', (3002, 3015), True, 'import datetime as dt\n'), ((3015, 3035), 'datetime.date', 'dt.date', (['(2036)', '(5)', '(25)'], {}), '(2036, 5, 25)\n', (3022, 3035), True, 'import datetime as dt\n'), ((3806, 3826), 'datetime.date', 'dt.date', (['(1990)', '(5)', '(31)'], {}), '(1990, 5, 31)\n', (3813, 3826), True, 'import datetime as dt\n'), ((3873, 3892), 'datetime.date', 'dt.date', (['(2005)', '(1)', '(2)'], {}), '(2005, 1, 2)\n', (3880, 3892), True, 'import datetime as dt\n'), ((3940, 3961), 'datetime.date', 'dt.date', (['(2021)', '(12)', '(13)'], {}), '(2021, 12, 13)\n', (3947, 3961), True, 'import datetime as dt\n'), ((4007, 4027), 'datetime.date', 'dt.date', (['(2030)', '(10)', '(8)'], {}), '(2030, 10, 8)\n', (4014, 4027), True, 'import datetime as dt\n'), ((4118, 4138), 'datetime.date', 'dt.date', (['(1991)', '(5)', '(25)'], {}), '(1991, 5, 25)\n', (4125, 4138), True, 'import datetime as dt\n'), ((4199, 4218), 'datetime.date', 'dt.date', (['(2007)', '(1)', '(2)'], {}), '(2007, 1, 2)\n', (4206, 4218), True, 'import datetime as dt\n'), ((4279, 4300), 'datetime.date', 'dt.date', (['(2022)', '(12)', '(13)'], {}), '(2022, 12, 13)\n', (4286, 4300), True, 'import datetime as dt\n'), ((4360, 4381), 'datetime.date', 'dt.date', (['(2035)', '(12)', '(31)'], {}), '(2035, 12, 31)\n', (4367, 4381), True, 'import datetime as dt\n'), ((4440, 4460), 'datetime.date', 'dt.date', (['(2019)', '(12)', '(1)'], {}), '(2019, 12, 1)\n', (4447, 4460), True, 'import datetime as dt\n'), ((4521, 4542), 'datetime.date', 'dt.date', (['(2019)', '(12)', '(29)'], {}), '(2019, 12, 29)\n', (4528, 4542), True, 'import datetime as dt\n'), ((4601, 4620), 'datetime.date', 'dt.date', (['(2021)', '(1)', '(1)'], {}), '(2021, 1, 1)\n', (4608, 4620), True, 'import datetime as dt\n'), ((5160, 5179), 'datetime.date', 'dt.date', (['(1991)', '(1)', '(6)'], {}), '(1991, 1, 6)\n', (5167, 5179), True, 'import datetime as dt\n'), ((5180, 5200), 'datetime.date', 'dt.date', (['(1991)', '(1)', '(12)'], {}), '(1991, 1, 12)\n', (5187, 5200), True, 'import datetime as dt\n'), ((5283, 5303), 'datetime.date', 'dt.date', (['(2006)', '(5)', '(14)'], {}), '(2006, 5, 14)\n', (5290, 5303), True, 'import datetime as dt\n'), ((5303, 5323), 'datetime.date', 'dt.date', (['(2006)', '(5)', '(20)'], {}), '(2006, 5, 20)\n', (5310, 5323), True, 'import datetime as dt\n'), ((5406, 5426), 'datetime.date', 'dt.date', (['(2020)', '(9)', '(27)'], {}), '(2020, 9, 27)\n', (5413, 5426), True, 'import datetime as dt\n'), ((5426, 5446), 'datetime.date', 'dt.date', (['(2020)', '(10)', '(3)'], {}), '(2020, 10, 3)\n', (5433, 5446), True, 'import datetime as dt\n'), ((5529, 5549), 'datetime.date', 'dt.date', (['(2036)', '(5)', '(18)'], {}), '(2036, 5, 18)\n', (5536, 5549), True, 'import datetime as dt\n'), ((5549, 5569), 'datetime.date', 'dt.date', (['(2036)', '(5)', '(24)'], {}), '(2036, 5, 24)\n', (5556, 5569), True, 'import datetime as dt\n')] |
#!/usr/bin/env python3
#
# MIT License
#
# Copyright (c) 2020-2021 EntySec
#
# 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, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# 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.
#
import socket
import requests.exceptions
from core.cli.badges import badges
from core.base.jobs import jobs
from core.base.exceptions import exceptions
class pseudo_shell:
def __init__(self):
self.badges = badges()
self.jobs = jobs()
self.exceptions = exceptions()
self.prompt = 'pseudo % '
def pseudo_shell_header(self):
self.badges.output_empty("")
self.badges.output_information("--=( Welcome to Pseudo shell )=--")
self.badges.output_information("Interface for executing commands on the target.")
self.badges.output_information("Commands are sent to the target via provided execute method.")
self.badges.output_empty("")
def execute_command(self, execute_method, command, arguments=()):
try:
if command == "exit":
return True
if isinstance(arguments, tuple):
output = execute_method(*arguments, command)
else:
output = execute_method(arguments, command)
if isinstance(output, tuple) and len(output) == 2:
if output[0]:
if output[1]:
self.badges.output_empty(output[1].strip())
else:
self.badges.output_warning("No output provided by command.")
else:
self.badges.output_error("Failed to execute command!")
else:
self.badges.output_error("Invalid execute method!")
except (requests.exceptions.Timeout, socket.timeout):
self.badges.output_warning("Timeout waiting for response.")
except Exception as e:
self.badges.output_error("An error occurred: " + str(e) + "!")
return False
def spawn_pseudo_shell(self, module_name, execute_method, arguments=()):
self.badges.output_process("Spawning Pseudo shell...")
if self.jobs.check_module_job(module_name):
self.badges.output_error("Failed to spawn Pseudo shell!")
self.badges.output_warning("Pseudo shell can not be background job.")
else:
self.badges.output_success("Congratulations, you won Pseudo shell!")
self.pseudo_shell_header()
self.launch_pseudo_shell(execute_method, arguments)
def launch_pseudo_shell(self, execute_method, arguments):
while True:
try:
command = self.badges.input_empty(self.prompt)
except (KeyboardInterrupt, EOFError, self.exceptions.GlobalException):
pass
if self.execute_command(execute_method, command, arguments):
return
| [
"core.cli.badges.badges",
"core.base.exceptions.exceptions",
"core.base.jobs.jobs"
] | [((1356, 1364), 'core.cli.badges.badges', 'badges', ([], {}), '()\n', (1362, 1364), False, 'from core.cli.badges import badges\n'), ((1385, 1391), 'core.base.jobs.jobs', 'jobs', ([], {}), '()\n', (1389, 1391), False, 'from core.base.jobs import jobs\n'), ((1418, 1430), 'core.base.exceptions.exceptions', 'exceptions', ([], {}), '()\n', (1428, 1430), False, 'from core.base.exceptions import exceptions\n')] |
from collections import namedtuple
Genotype = namedtuple('Genotype', 'backbone rpn')
OP_NAMES = [
'sep_conv_3x3',
'sep_conv_3x3_dil3',
'sep_conv_5x5_dil6',
'skip_connect',
'def_conv_3x3',
]
AGG_NAMES = [
'psum',
'cat'
]
HEAD_OP_NAMES = [
'conv1x1',
'conv3x3',
'sep_conv_3x3',
'sep_conv_3x3_dil3',
'skip_connect',
'def_conv_3x3',
]
HEAD_AGG_NAMES = [
'psum',
'cat'
]
| [
"collections.namedtuple"
] | [((47, 85), 'collections.namedtuple', 'namedtuple', (['"""Genotype"""', '"""backbone rpn"""'], {}), "('Genotype', 'backbone rpn')\n", (57, 85), False, 'from collections import namedtuple\n')] |
# Copyright (c) 2014 Red Hat, Inc.
#
# 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 rally.plugins.openstack import scenario
from rally.task import atomic
class ZaqarScenario(scenario.OpenStackScenario):
"""Base class for Zaqar scenarios with basic atomic actions."""
@atomic.action_timer("zaqar.create_queue")
def _queue_create(self, **kwargs):
"""Create a Zaqar queue with random name.
:param kwargs: other optional parameters to create queues like
"metadata"
:returns: Zaqar queue instance
"""
name = self.generate_random_name()
return self.clients("zaqar").queue(name, **kwargs)
@atomic.action_timer("zaqar.delete_queue")
def _queue_delete(self, queue):
"""Removes a Zaqar queue.
:param queue: queue to remove
"""
queue.delete()
def _messages_post(self, queue, messages, min_msg_count, max_msg_count):
"""Post a list of messages to a given Zaqar queue.
:param queue: post the messages to queue
:param messages: messages to post
:param min_msg_count: minimum number of messages
:param max_msg_count: maximum number of messages
"""
with atomic.ActionTimer(self, "zaqar.post_between_%s_and_%s_messages" %
(min_msg_count, max_msg_count)):
queue.post(messages)
@atomic.action_timer("zaqar.list_messages")
def _messages_list(self, queue):
"""Gets messages from a given Zaqar queue.
:param queue: get messages from queue
:returns: messages iterator
"""
return queue.messages()
| [
"rally.task.atomic.action_timer",
"rally.task.atomic.ActionTimer"
] | [((781, 822), 'rally.task.atomic.action_timer', 'atomic.action_timer', (['"""zaqar.create_queue"""'], {}), "('zaqar.create_queue')\n", (800, 822), False, 'from rally.task import atomic\n'), ((1177, 1218), 'rally.task.atomic.action_timer', 'atomic.action_timer', (['"""zaqar.delete_queue"""'], {}), "('zaqar.delete_queue')\n", (1196, 1218), False, 'from rally.task import atomic\n'), ((1903, 1945), 'rally.task.atomic.action_timer', 'atomic.action_timer', (['"""zaqar.list_messages"""'], {}), "('zaqar.list_messages')\n", (1922, 1945), False, 'from rally.task import atomic\n'), ((1732, 1835), 'rally.task.atomic.ActionTimer', 'atomic.ActionTimer', (['self', "('zaqar.post_between_%s_and_%s_messages' % (min_msg_count, max_msg_count))"], {}), "(self, 'zaqar.post_between_%s_and_%s_messages' % (\n min_msg_count, max_msg_count))\n", (1750, 1835), False, 'from rally.task import atomic\n')] |
# -*- coding: utf-8 -*-
'''
Script Name: ping_Utility.py
Path: \IPS_DecisionFabric\Exception Handling\
Description: This script is considered as a module for the Application level Exception handling in DF framework.
Author: <NAME>
Version: 1.0
Revision History:
----------------------------------------------------------------------------------------------------------------------
S.No. Date(MM/DD/YY) Changed By Change Description
----------------------------------------------------------------------------------------------------------------------
1. 05/16/2019 Y Suryawanshi Initial Version (Exception Handling v1.1.1)
2. 06/21/2019 Y Suryawanshi Fixed the bug for ISODate object
3. 23/09/2019 Y Suryawanshi Added Process ID and Dynamic behaivior and minor enhancements.
----------------------------------------------------------------------------------------------------------------------
'''
try:
from datetime import datetime
from time import sleep
import logging
import sys, os
import pandas as pd
from subprocess import call
import ping_services
sys.path.insert(0,'/IPS_DecisionFabric/Control Framework')
from mongo_operations import Mongo
except Exception as Error:
sys.exit(1)
def ping_utility(time_min, config_file, csv_file):
df, error_dict = ping_services.check_for_status(config_file, csv_file)
df_error = df[df['count'] >= 3]
PID = os.getpid()
connection = Mongo()
connection.Mongodb['PROCESS_MASTER'].update_one({"Application_Code": 'PING_UTILITY'},
{"$set": {"Process_ID": str(PID)}})
error_master = pd.DataFrame(list(connection.Mongodb['EXCEPTION_ERROR_MASTER'].find({"Error_Code": 'CONNECTION_ERROR'},
{'_id': 0}).limit(1)))
pro_master = pd.DataFrame(list(connection.Mongodb['PROCESS_MASTER'].find({"Application_Code": 'PING_UTILITY'},
{'_id': 0}).limit(1)))
application_master = pd.DataFrame(list(connection.Mongodb['APPLICATION_MASTER'].find({'Application_Code': 'PING_UTILITY'},
{'_id': 0}).limit(1)))
if (len(df_error.index) > 0):
for ind in df_error.index:
App_Name = df_error.loc[ind, 'Application_name']
IP = (df_error.loc[ind, 'IP'])
Port = (df_error.loc[ind, 'Port'])
error_message = "{0}:{1} Application {2} is not reachable".format(IP, Port, App_Name)
error_log = pd.DataFrame(columns=['Exception_Log_Dtm',
'Application_Code',
'Application_Name',
'Process_ID',
'Process_Name',
'Error_Category',
'Error_Code',
'Error_Desc',
'Error_Severity',
'Script_Name',
'Active_Flag',
'Rec_Inserted_By',
'Rec_Inserted_Dtm',
'Rec_Updated_By',
'Rec_Updated_Dtm']
)
error_log = error_log.append(pd.Series(), ignore_index=True)
error_log[['Application_Code', 'Application_Name']] = application_master[['Application_Code', 'Application_Name']]
error_log[['Process_ID', 'Process_Name']] = pro_master[['Process_ID', 'Process_Name']]
error_log[['Error_Category', 'Error_Code',
'Error_Severity', 'Active_Flag']] = error_master[['Error_Category', 'Error_Code',
'Error_Severity', 'Active_Flag']]
error_log['Rec_Inserted_By'] = "ping_utility"
error_log['Error_Desc'] = error_message
error_log['Exception_Log_Dtm'] = df_error.loc[ind, 'Timestamp']
error_log['Rec_Inserted_Dtm'] = datetime.now()
error_log['Rec_Updated_By'] = 'ping_utility'
error_log['Rec_Updated_Dtm'] = datetime.now()
error_log['Script_Name'] = __file__
try:
Collection = "IPS_EXCEPTION_LOG"
connection.insert_record_in_table(error_log, Collection)
except Exception as Inserterror:
logging.error("Unable to insert data into {}".format(Collection))
df.loc[ind, 'count'] = 0
df.to_csv(csv_file, index=False)
logging.info("\n")
sleep(time_min * 60)
def create_config(filename):
try:
connection = Mongo()
App_master = pd.DataFrame(list(connection.Mongodb['APPLICATION_MASTER'].find({})))
with open(filename, "w+") as configuration_:
df = App_master[['Application_IP_Address', 'Application_Port_No',
'Application_Name']]
df = df.dropna()
for index, row in df.iterrows():
data = [row.Application_IP_Address, row.Application_Port_No,
row.Application_Name]
sent = ("IP={0}\tport={1}\tapp={2}\n".format(data[0], int(data[1]),
data[2]))
configuration_.write(sent)
logging.debug("{} has been created".format(filename))
except Exception as Error:
logging.debug("Connection is not created with MONGO DB while creating"
" configfile:", Error)
if __name__=="__main__":
# Initiallising logging
dtstr = datetime.now().strftime("%Y%m%d%H")
log_file = "APPLICATION_STATUS_LOG_{0}.log".format(dtstr)
FORMAT = ('%(asctime)s %(levelname)s \t %(message)s')
logging.basicConfig(filename=log_file, level=logging.DEBUG, format=FORMAT)
# Check if the configuration file is existing
config_file = "ping_config.txt"
create_config(config_file)
# Check if external timer is provided, default 5 minutes
if len(sys.argv) > 1:
times = float(sys.argv[1])
logging.debug("Externally time is set to {0:.2f} seconds".format(times*60))
else:
times = 5
logging.debug("Default timer is set to 5 min")
csv_file = ('ip_port_app.csv')
while True:
ping_utility(times, config_file, csv_file) | [
"logging.basicConfig",
"pandas.Series",
"sys.path.insert",
"logging.debug",
"mongo_operations.Mongo",
"time.sleep",
"datetime.datetime.now",
"os.getpid",
"sys.exit",
"pandas.DataFrame",
"logging.info",
"ping_services.check_for_status"
] | [((1119, 1178), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""/IPS_DecisionFabric/Control Framework"""'], {}), "(0, '/IPS_DecisionFabric/Control Framework')\n", (1134, 1178), False, 'import sys, os\n'), ((1331, 1384), 'ping_services.check_for_status', 'ping_services.check_for_status', (['config_file', 'csv_file'], {}), '(config_file, csv_file)\n', (1361, 1384), False, 'import ping_services\n'), ((1429, 1440), 'os.getpid', 'os.getpid', ([], {}), '()\n', (1438, 1440), False, 'import sys, os\n'), ((1458, 1465), 'mongo_operations.Mongo', 'Mongo', ([], {}), '()\n', (1463, 1465), False, 'from mongo_operations import Mongo\n'), ((3990, 4008), 'logging.info', 'logging.info', (['"""\n"""'], {}), "('\\n')\n", (4002, 4008), False, 'import logging\n'), ((4011, 4031), 'time.sleep', 'sleep', (['(time_min * 60)'], {}), '(time_min * 60)\n', (4016, 4031), False, 'from time import sleep\n'), ((5039, 5113), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': 'log_file', 'level': 'logging.DEBUG', 'format': 'FORMAT'}), '(filename=log_file, level=logging.DEBUG, format=FORMAT)\n', (5058, 5113), False, 'import logging\n'), ((1245, 1256), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1253, 1256), False, 'import sys, os\n'), ((4093, 4100), 'mongo_operations.Mongo', 'Mongo', ([], {}), '()\n', (4098, 4100), False, 'from mongo_operations import Mongo\n'), ((5445, 5491), 'logging.debug', 'logging.debug', (['"""Default timer is set to 5 min"""'], {}), "('Default timer is set to 5 min')\n", (5458, 5491), False, 'import logging\n'), ((2397, 2696), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['Exception_Log_Dtm', 'Application_Code', 'Application_Name', 'Process_ID',\n 'Process_Name', 'Error_Category', 'Error_Code', 'Error_Desc',\n 'Error_Severity', 'Script_Name', 'Active_Flag', 'Rec_Inserted_By',\n 'Rec_Inserted_Dtm', 'Rec_Updated_By', 'Rec_Updated_Dtm']"}), "(columns=['Exception_Log_Dtm', 'Application_Code',\n 'Application_Name', 'Process_ID', 'Process_Name', 'Error_Category',\n 'Error_Code', 'Error_Desc', 'Error_Severity', 'Script_Name',\n 'Active_Flag', 'Rec_Inserted_By', 'Rec_Inserted_Dtm', 'Rec_Updated_By',\n 'Rec_Updated_Dtm'])\n", (2409, 2696), True, 'import pandas as pd\n'), ((3553, 3567), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (3565, 3567), False, 'from datetime import datetime\n'), ((3652, 3666), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (3664, 3666), False, 'from datetime import datetime\n'), ((4711, 4811), 'logging.debug', 'logging.debug', (['"""Connection is not created with MONGO DB while creating configfile:"""', 'Error'], {}), "(\n 'Connection is not created with MONGO DB while creating configfile:', Error\n )\n", (4724, 4811), False, 'import logging\n'), ((4879, 4893), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4891, 4893), False, 'from datetime import datetime\n'), ((2921, 2932), 'pandas.Series', 'pd.Series', ([], {}), '()\n', (2930, 2932), True, 'import pandas as pd\n')] |
from setuptools import setup
setup(
name='NotebookScripter',
version='6.0.0',
packages=('NotebookScripter',),
url='https://github.com/breathe/NotebookScripter',
license='MIT',
author='<NAME>',
author_email='<EMAIL>',
install_requires=(
"ipython",
"nbformat"
),
tests_require=(
"nose",
"coverage",
"snapshottest",
"matplotlib"
),
description='Expose ipython jupyter notebooks as callable functions. More info here https://github.com/breathe/NotebookScripter',
long_description='Expose ipython jupyter notebooks as callable functions. More info here https://github.com/breathe/NotebookScripter',
classifiers=(
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython')
)
| [
"setuptools.setup"
] | [((30, 839), 'setuptools.setup', 'setup', ([], {'name': '"""NotebookScripter"""', 'version': '"""6.0.0"""', 'packages': "('NotebookScripter',)", 'url': '"""https://github.com/breathe/NotebookScripter"""', 'license': '"""MIT"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'install_requires': "('ipython', 'nbformat')", 'tests_require': "('nose', 'coverage', 'snapshottest', 'matplotlib')", 'description': '"""Expose ipython jupyter notebooks as callable functions. More info here https://github.com/breathe/NotebookScripter"""', 'long_description': '"""Expose ipython jupyter notebooks as callable functions. More info here https://github.com/breathe/NotebookScripter"""', 'classifiers': "('License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: Implementation :: CPython')"}), "(name='NotebookScripter', version='6.0.0', packages=(\n 'NotebookScripter',), url='https://github.com/breathe/NotebookScripter',\n license='MIT', author='<NAME>', author_email='<EMAIL>',\n install_requires=('ipython', 'nbformat'), tests_require=('nose',\n 'coverage', 'snapshottest', 'matplotlib'), description=\n 'Expose ipython jupyter notebooks as callable functions. More info here https://github.com/breathe/NotebookScripter'\n , long_description=\n 'Expose ipython jupyter notebooks as callable functions. More info here https://github.com/breathe/NotebookScripter'\n , classifiers=('License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: Implementation :: CPython'))\n", (35, 839), False, 'from setuptools import setup\n')] |
# Third-party
import astropy.units as u
import numpy as np
import pymc3 as pm
from pymc3.distributions import generate_samples
import aesara_theano_fallback.tensor as tt
import exoplanet.units as xu
__all__ = ['UniformLog', 'FixedCompanionMass']
class UniformLog(pm.Continuous):
def __init__(self, a, b, **kwargs):
"""A distribution over a value, x, that is uniform in log(x) over the
domain :math:`(a, b)`.
"""
self.a = float(a)
self.b = float(b)
assert (self.a > 0) and (self.b > 0)
self._fac = np.log(self.b) - np.log(self.a)
shape = kwargs.get("shape", None)
if shape is None:
testval = 0.5 * (self.a + self.b)
else:
testval = 0.5 * (self.a + self.b) + np.zeros(shape)
kwargs["testval"] = kwargs.pop("testval", testval)
super(UniformLog, self).__init__(**kwargs)
def _random(self, size=None):
uu = np.random.uniform(size=size)
return np.exp(uu * self._fac + np.log(self.a))
def random(self, point=None, size=None):
return generate_samples(
self._random,
dist_shape=self.shape,
broadcast_shape=self.shape,
size=size,
)
def logp(self, value):
return -tt.as_tensor_variable(value) - np.log(self._fac)
class FixedCompanionMass(pm.Normal):
r"""
A distribution over velocity semi-amplitude, :math:`K`, that, at
fixed primary mass, is a fixed Normal distribution in companion mass. This
has the form:
.. math::
p(K) \propto \mathcal{N}(K \,|\, \mu_K, \sigma_K)
\sigma_K = \sigma_{K, 0} \, \left(\frac{P}{P_0}\right)^{-1/3} \,
\left(1 - e^2\right)^{-1}
where :math:`P` and :math:`e` are period and eccentricity, and
``sigma_K0`` and ``P0`` are parameters of this distribution that must
be specified.
"""
@u.quantity_input(sigma_K0=u.km/u.s, P0=u.day, max_K=u.km/u.s)
def __init__(self, P, e, sigma_K0, P0, mu=0., max_K=500*u.km/u.s,
K_unit=None, **kwargs):
self._sigma_K0 = sigma_K0
self._P0 = P0
self._max_K = max_K
if K_unit is not None:
self._sigma_K0 = self.sigma_K0.to(K_unit)
self._max_K = self._max_K.to(self._sigma_K0.unit)
if hasattr(P, xu.UNIT_ATTR_NAME):
self._P0 = self._P0.to(getattr(P, xu.UNIT_ATTR_NAME))
sigma_K0 = self._sigma_K0.value
P0 = self._P0.value
sigma = tt.min([self._max_K.value,
sigma_K0 * (P/P0)**(-1/3) / np.sqrt(1-e**2)])
super().__init__(mu=mu, sigma=sigma)
class Kipping13Long(pm.Beta):
def __init__(self):
r"""
The inferred long-period eccentricity distribution from Kipping (2013).
"""
super().__init__(1.12, 3.09)
class Kipping13Short(pm.Beta):
def __init__(self):
r"""
The inferred short-period eccentricity distribution from Kipping (2013).
"""
super().__init__(0.697, 3.27)
class Kipping13Global(pm.Beta):
def __init__(self):
r"""
The inferred global eccentricity distribution from Kipping (2013).
"""
super().__init__(0.867, 3.03)
| [
"numpy.sqrt",
"numpy.log",
"aesara_theano_fallback.tensor.as_tensor_variable",
"numpy.zeros",
"numpy.random.uniform",
"pymc3.distributions.generate_samples",
"astropy.units.quantity_input"
] | [((1908, 1973), 'astropy.units.quantity_input', 'u.quantity_input', ([], {'sigma_K0': '(u.km / u.s)', 'P0': 'u.day', 'max_K': '(u.km / u.s)'}), '(sigma_K0=u.km / u.s, P0=u.day, max_K=u.km / u.s)\n', (1924, 1973), True, 'import astropy.units as u\n'), ((945, 973), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': 'size'}), '(size=size)\n', (962, 973), True, 'import numpy as np\n'), ((1090, 1187), 'pymc3.distributions.generate_samples', 'generate_samples', (['self._random'], {'dist_shape': 'self.shape', 'broadcast_shape': 'self.shape', 'size': 'size'}), '(self._random, dist_shape=self.shape, broadcast_shape=self.\n shape, size=size)\n', (1106, 1187), False, 'from pymc3.distributions import generate_samples\n'), ((562, 576), 'numpy.log', 'np.log', (['self.b'], {}), '(self.b)\n', (568, 576), True, 'import numpy as np\n'), ((579, 593), 'numpy.log', 'np.log', (['self.a'], {}), '(self.a)\n', (585, 593), True, 'import numpy as np\n'), ((1317, 1334), 'numpy.log', 'np.log', (['self._fac'], {}), '(self._fac)\n', (1323, 1334), True, 'import numpy as np\n'), ((771, 786), 'numpy.zeros', 'np.zeros', (['shape'], {}), '(shape)\n', (779, 786), True, 'import numpy as np\n'), ((1013, 1027), 'numpy.log', 'np.log', (['self.a'], {}), '(self.a)\n', (1019, 1027), True, 'import numpy as np\n'), ((1286, 1314), 'aesara_theano_fallback.tensor.as_tensor_variable', 'tt.as_tensor_variable', (['value'], {}), '(value)\n', (1307, 1314), True, 'import aesara_theano_fallback.tensor as tt\n'), ((2583, 2602), 'numpy.sqrt', 'np.sqrt', (['(1 - e ** 2)'], {}), '(1 - e ** 2)\n', (2590, 2602), True, 'import numpy as np\n')] |
import json
import os
import unittest
import price_checker
from product import Product
def load_json(filename):
with open(filename) as json_file:
imported_file = json.load(json_file)
return imported_file
cwd = os.path.dirname(os.path.realpath(__file__))
products_data = load_json(r"" + cwd + "/test-products.json")
products_list = []
class PricehuntTest(unittest.TestCase):
def setUp(self):
for i in range(len(products_data)):
products_list.append(Product(products_data[i]))
def test_correct_product0(self):
self.assertEqual("Logitech MX Master 3", products_list[0].name)
def test_correct_product1(self):
self.assertEqual("Logitech MX Keys", products_list[1].name)
def test_correct_product2(self):
self.assertEqual("Apple Watch Series 5 Cellular 44mm", products_list[2].name)
def test_lowest_price_product0(self):
self.assertEqual("1149", products_list[0].price)
def test_compare_price_product0(self):
diff = price_checker.compare_prices(products_list[0].price, products_list[0].purchased_price)
self.assertEqual("50", diff)
def test_open_policyFalse(self):
self.assertFalse(price_checker.open_policy(61, "Komplett.no"))
def test_open_policyTrue0(self):
self.assertTrue(price_checker.open_policy(60, "Komplett.no"))
def test_open_policyTrue1(self):
self.assertTrue(price_checker.open_policy(10, "Komplett.no"))
# def test_add_product(self):
# self.fail()
#
# def test_remove_product(self):
# self.fail()
#
# def test_get_list(self):
# self.fail()
if __name__ == '__main__':
unittest.main()
| [
"price_checker.compare_prices",
"price_checker.open_policy",
"product.Product",
"unittest.main",
"os.path.realpath",
"json.load"
] | [((251, 277), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (267, 277), False, 'import os\n'), ((1689, 1704), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1702, 1704), False, 'import unittest\n'), ((177, 197), 'json.load', 'json.load', (['json_file'], {}), '(json_file)\n', (186, 197), False, 'import json\n'), ((1026, 1117), 'price_checker.compare_prices', 'price_checker.compare_prices', (['products_list[0].price', 'products_list[0].purchased_price'], {}), '(products_list[0].price, products_list[0].\n purchased_price)\n', (1054, 1117), False, 'import price_checker\n'), ((1213, 1257), 'price_checker.open_policy', 'price_checker.open_policy', (['(61)', '"""Komplett.no"""'], {}), "(61, 'Komplett.no')\n", (1238, 1257), False, 'import price_checker\n'), ((1321, 1365), 'price_checker.open_policy', 'price_checker.open_policy', (['(60)', '"""Komplett.no"""'], {}), "(60, 'Komplett.no')\n", (1346, 1365), False, 'import price_checker\n'), ((1429, 1473), 'price_checker.open_policy', 'price_checker.open_policy', (['(10)', '"""Komplett.no"""'], {}), "(10, 'Komplett.no')\n", (1454, 1473), False, 'import price_checker\n'), ((500, 525), 'product.Product', 'Product', (['products_data[i]'], {}), '(products_data[i])\n', (507, 525), False, 'from product import Product\n')] |
from collections import (
OrderedDict,
)
from unittest.mock import Mock
import pandas as pd
from datetime import (
datetime,
)
from fireant import *
from fireant.slicer.references import ReferenceType
from fireant.slicer.totals import get_totals_marker_for_dtype
from fireant.utils import (
format_dimension_key as fd,
format_metric_key as fm,
)
from pypika import (
JoinType,
Table,
functions as fn,
)
class TestDatabase(VerticaDatabase):
# Vertica client that uses the vertica_python driver.
connect = Mock()
def __eq__(self, other):
return isinstance(other, TestDatabase)
test_database = TestDatabase()
politicians_table = Table('politician', schema='politics')
voters_table = Table('voter', schema='politics')
state_table = Table('state', schema='locations')
district_table = Table('district', schema='locations')
deep_join_table = Table('deep', schema='test')
slicer = Slicer(
table=politicians_table,
database=test_database,
joins=(
Join(table=district_table,
criterion=politicians_table.district_id == district_table.id,
join_type=JoinType.outer),
Join(table=district_table,
criterion=politicians_table.district_id == district_table.id,
join_type=JoinType.outer),
Join(table=state_table,
criterion=district_table.state_id == state_table.id),
Join(table=voters_table,
criterion=politicians_table.id == voters_table.politician_id),
Join(table=deep_join_table,
criterion=deep_join_table.id == state_table.ref_id),
),
dimensions=(
DatetimeDimension('timestamp',
label='Timestamp',
definition=politicians_table.timestamp),
DatetimeDimension('timestamp2',
label='Timestamp 2',
definition=politicians_table.timestamp2),
DatetimeDimension('join_timestamp',
label='Join Timestamp',
definition=voters_table.timestamp),
CategoricalDimension('political_party',
label='Party',
definition=politicians_table.political_party,
display_values=(
('d', 'Democrat'),
('r', 'Republican'),
('i', 'Independent'),
('l', 'Libertarian'),
('g', 'Green'),
('c', 'Constitution'))),
UniqueDimension('candidate',
label='Candidate',
definition=politicians_table.candidate_id,
display_definition=politicians_table.candidate_name),
UniqueDimension('election',
label='Election',
definition=politicians_table.election_id,
display_definition=politicians_table.election_year),
UniqueDimension('district',
label='District',
definition=politicians_table.district_id,
display_definition=district_table.district_name),
UniqueDimension('state',
label='State',
definition=district_table.state_id,
display_definition=state_table.state_name),
BooleanDimension('winner',
label='Winner',
definition=politicians_table.is_winner),
UniqueDimension('deepjoin',
definition=deep_join_table.id),
),
metrics=(
Metric('votes',
label='Votes',
definition=fn.Sum(politicians_table.votes)),
Metric('wins',
label='Wins',
definition=fn.Sum(politicians_table.is_winner)),
Metric('voters',
label='Voters',
definition=fn.Count(voters_table.id)),
Metric('turnout',
label='Turnout',
definition=fn.Sum(politicians_table.votes) / fn.Count(voters_table.id),
suffix='%',
precision=2),
Metric('wins_with_suffix_and_prefix',
label='Wins',
definition=fn.Sum(politicians_table.is_winner),
prefix='$',
suffix='€'),
),
)
political_parties = OrderedDict((('d', 'Democrat'),
('r', 'Republican'),
('i', 'Independent'),
('l', 'Libertarian'),
('g', 'Green'),
('c', 'Constitution')))
candidates = OrderedDict(((1, '<NAME>'),
(2, '<NAME>'),
(3, '<NAME>'),
(4, '<NAME>'),
(5, '<NAME>'),
(6, '<NAME>'),
(7, '<NAME>'),
(8, '<NAME>'),
(9, '<NAME>'),
(10, '<NAME>'),
(11, '<NAME>')))
states = OrderedDict(((1, 'Texas'),
(2, 'California')))
elections = OrderedDict(((1, '1996'),
(2, '2000'),
(3, '2004'),
(4, '2008'),
(5, '2012'),
(6, '2016')))
election_candidates = {
1: {'candidates': [1, 2, 3], 'winner': 1},
2: {'candidates': [4, 5], 'winner': 4},
3: {'candidates': [4, 6], 'winner': 4},
4: {'candidates': [7, 8], 'winner': 7},
5: {'candidates': [7, 9], 'winner': 7},
6: {'candidates': [10, 11], 'winner': 10},
}
candidate_parties = {
1: 'd',
2: 'r',
3: 'i',
4: 'r',
5: 'd',
6: 'd',
7: 'd',
8: 'r',
9: 'r',
10: 'r',
11: 'd',
}
election_candidate_state_votes = {
# Texas
(1, 1, 1): 2459683,
(1, 2, 1): 2736167,
(1, 3, 1): 378537,
(2, 4, 1): 3799639,
(2, 5, 1): 2433746,
(3, 4, 1): 4526917,
(3, 6, 1): 2832704,
(4, 7, 1): 3528633,
(4, 8, 1): 4479328,
(5, 7, 1): 4569843,
(5, 9, 1): 3308124,
(6, 10, 1): 4685047,
(6, 11, 1): 387868,
# California
(1, 1, 2): 5119835,
(1, 2, 2): 3828380,
(1, 3, 2): 697847,
(2, 4, 2): 4567429,
(2, 5, 2): 5861203,
(3, 4, 2): 5509826,
(3, 6, 2): 6745485,
(4, 7, 2): 8274473,
(4, 8, 2): 5011781,
(5, 7, 2): 7854285,
(5, 9, 2): 4839958,
(6, 10, 2): 8753788,
(6, 11, 2): 4483810,
}
election_candidate_wins = {
(1, 1): True,
(1, 2): False,
(1, 3): False,
(2, 4): True,
(2, 5): False,
(3, 4): True,
(3, 6): False,
(4, 7): True,
(4, 8): False,
(5, 7): True,
(5, 9): False,
(6, 10): True,
(6, 11): False,
}
df_columns = [fd('timestamp'),
fd('candidate'), fd('candidate_display'),
fd('political_party'),
fd('election'), fd('election_display'),
fd('state'), fd('state_display'),
fd('winner'),
fm('votes'),
fm('wins')]
def PoliticsRow(timestamp, candidate, candidate_display, political_party, election, election_display, state,
state_display, winner, votes, wins):
return (
timestamp, candidate, candidate_display, political_party, election, election_display, state, state_display,
winner, votes, wins
)
records = []
for (election_id, candidate_id, state_id), votes in election_candidate_state_votes.items():
election_year = elections[election_id]
winner = election_candidate_wins[(election_id, candidate_id)]
records.append(PoliticsRow(
timestamp=datetime(int(election_year), 1, 1),
candidate=candidate_id, candidate_display=candidates[candidate_id],
political_party=candidate_parties[candidate_id],
election=election_id, election_display=elections[election_id],
state=state_id, state_display=states[state_id],
winner=winner,
votes=votes,
wins=(1 if winner else 0),
))
mock_politics_database = pd.DataFrame.from_records(records, columns=df_columns)
single_metric_df = pd.DataFrame(mock_politics_database[[fm('votes')]]
.sum()).T
multi_metric_df = pd.DataFrame(mock_politics_database[[fm('votes'), fm('wins')]]
.sum()).T
cont_dim_df = mock_politics_database[[fd('timestamp'), fm('votes'), fm('wins')]] \
.groupby(fd('timestamp')) \
.sum()
no_index_df = pd.DataFrame(cont_dim_df.sum()).T
cat_dim_df = mock_politics_database[[fd('political_party'), fm('votes'), fm('wins')]] \
.groupby(fd('political_party')) \
.sum()
cat_uni_dim_df = mock_politics_database[[fd('political_party'), fd('candidate'), fd('candidate_display'),
fm('votes'), fm('wins')]] \
.groupby([fd('political_party'), fd('candidate'), fd('candidate_display')]) \
.sum() \
.reset_index(fd('candidate_display'))
uni_dim_df = mock_politics_database[[fd('candidate'), fd('candidate_display'), fm('votes'), fm('wins')]] \
.groupby([fd('candidate'), fd('candidate_display')]) \
.sum() \
.reset_index(fd('candidate_display'))
cont_cat_dim_df = mock_politics_database[[fd('timestamp'), fd('political_party'), fm('votes'), fm('wins')]] \
.groupby([fd('timestamp'), fd('political_party')]) \
.sum()
cont_uni_dim_df = mock_politics_database[[fd('timestamp'), fd('state'), fd('state_display'), fm('votes'), fm('wins')]] \
.groupby([fd('timestamp'), fd('state'), fd('state_display')]) \
.sum() \
.reset_index(fd('state_display'))
cont_cat_uni_dim_df = mock_politics_database[[fd('timestamp'), fd('political_party'),
fd('state'), fd('state_display'),
fm('votes'), fm('wins')]] \
.groupby([fd('timestamp'), fd('political_party'), fd('state'), fd('state_display')]) \
.sum() \
.reset_index(fd('state_display'))
cont_dim_operation_df = cont_dim_df.copy()
operation_key = fm('cumsum(votes)')
cont_dim_operation_df[operation_key] = cont_dim_df[fm('votes')].cumsum()
def split(list, i):
return list[:i], list[i:]
def ref(data_frame, columns):
ref_cols = {column: '%s_eoe' % column
for column in columns}
ref_df = data_frame \
.shift(2) \
.rename(columns=ref_cols)[list(ref_cols.values())]
return (cont_uni_dim_df
.copy()
.join(ref_df)
.iloc[2:])
def ref_delta(ref_data_frame, columns):
ref_columns = ['%s_eoe' % column for column in columns]
delta_data_frame = pd.DataFrame(
data=ref_data_frame[ref_columns].values - ref_data_frame[columns].values,
columns=['%s_eoe_delta' % column for column in columns],
index=ref_data_frame.index
)
return ref_data_frame.join(delta_data_frame)
_columns = [fm('votes'), fm('wins')]
cont_uni_dim_ref_df = ref(cont_uni_dim_df, _columns)
cont_uni_dim_ref_delta_df = ref_delta(cont_uni_dim_ref_df, _columns)
def totals(data_frame, dimensions, columns):
"""
Computes the totals across a dimension and adds the total as an extra row.
"""
if not isinstance(data_frame.index, pd.MultiIndex):
totals_marker = get_totals_marker_for_dtype(data_frame.index.dtype)
totals_df = pd.DataFrame([data_frame.sum()],
index=pd.Index([totals_marker],
name=data_frame.index.name))
return data_frame.append(totals_df)
def _totals(df):
if isinstance(df, pd.Series):
return df.sum()
totals_index_value = get_totals_marker_for_dtype(df.index.levels[-1].dtype)
return pd.DataFrame(
[df.sum()],
columns=columns,
index=pd.Index([totals_index_value],
name=df.index.names[-1]))
totals_df = None
for i in range(-1, -1 - len(dimensions), -1):
groupby_levels = data_frame.index.names[:i]
if groupby_levels:
level_totals_df = data_frame[columns].groupby(level=groupby_levels).apply(_totals)
missing_dims = set(data_frame.index.names) - set(level_totals_df.index.names)
if missing_dims:
for dim in missing_dims:
dtype = data_frame.index.levels[data_frame.index.names.index(dim)].dtype
level_totals_df[dim] = get_totals_marker_for_dtype(dtype)
level_totals_df.set_index(dim, append=True, inplace=True)
level_totals_df = level_totals_df.reorder_levels(data_frame.index.names)
else:
totals_index_values = [get_totals_marker_for_dtype(level.dtype)
for level in data_frame.index.levels]
level_totals_df = pd.DataFrame([data_frame[columns].apply(_totals)],
columns=columns,
index=pd.MultiIndex.from_tuples([totals_index_values],
names=data_frame.index.names))
totals_df = totals_df.append(level_totals_df) \
if totals_df is not None \
else level_totals_df
return data_frame.append(totals_df).sort_index()
# Convert all index values to string
for l in list(locals().values()):
if not isinstance(l, pd.DataFrame):
continue
if hasattr(l.index, 'levels'):
l.index = pd.MultiIndex(levels=[level.astype('str')
if not isinstance(level, (pd.DatetimeIndex, pd.RangeIndex))
else level
for level in l.index.levels],
labels=l.index.labels)
elif not isinstance(l.index, (pd.DatetimeIndex, pd.RangeIndex)):
l.index = l.index.astype('str')
cat_dim_totals_df = totals(cat_dim_df, [fd('political_party')], _columns)
cont_cat_dim_totals_df = totals(cont_cat_dim_df, [fd('political_party')], _columns)
cont_cat_dim_all_totals_df = totals(cont_cat_dim_df, [fd('timestamp'), fd('political_party')], _columns)
cont_uni_dim_totals_df = totals(cont_uni_dim_df, [fd('state')], _columns)
cont_uni_dim_all_totals_df = totals(cont_uni_dim_df, [fd('timestamp'), fd('state')], _columns)
cont_cat_uni_dim_all_totals_df = totals(cont_cat_uni_dim_df, [fd('timestamp'), fd('political_party'), fd('state')],
_columns)
ElectionOverElection = ReferenceType('eoe', 'EoE', 'year', 4)
| [
"pandas.DataFrame.from_records",
"collections.OrderedDict",
"unittest.mock.Mock",
"fireant.utils.format_dimension_key",
"fireant.utils.format_metric_key",
"fireant.slicer.totals.get_totals_marker_for_dtype",
"pypika.functions.Count",
"pypika.functions.Sum",
"pandas.Index",
"pypika.Table",
"firea... | [((682, 720), 'pypika.Table', 'Table', (['"""politician"""'], {'schema': '"""politics"""'}), "('politician', schema='politics')\n", (687, 720), False, 'from pypika import JoinType, Table, functions as fn\n'), ((736, 769), 'pypika.Table', 'Table', (['"""voter"""'], {'schema': '"""politics"""'}), "('voter', schema='politics')\n", (741, 769), False, 'from pypika import JoinType, Table, functions as fn\n'), ((784, 818), 'pypika.Table', 'Table', (['"""state"""'], {'schema': '"""locations"""'}), "('state', schema='locations')\n", (789, 818), False, 'from pypika import JoinType, Table, functions as fn\n'), ((836, 873), 'pypika.Table', 'Table', (['"""district"""'], {'schema': '"""locations"""'}), "('district', schema='locations')\n", (841, 873), False, 'from pypika import JoinType, Table, functions as fn\n'), ((892, 920), 'pypika.Table', 'Table', (['"""deep"""'], {'schema': '"""test"""'}), "('deep', schema='test')\n", (897, 920), False, 'from pypika import JoinType, Table, functions as fn\n'), ((4526, 4666), 'collections.OrderedDict', 'OrderedDict', (["(('d', 'Democrat'), ('r', 'Republican'), ('i', 'Independent'), ('l',\n 'Libertarian'), ('g', 'Green'), ('c', 'Constitution'))"], {}), "((('d', 'Democrat'), ('r', 'Republican'), ('i', 'Independent'),\n ('l', 'Libertarian'), ('g', 'Green'), ('c', 'Constitution')))\n", (4537, 4666), False, 'from collections import OrderedDict\n'), ((4842, 5030), 'collections.OrderedDict', 'OrderedDict', (["((1, '<NAME>'), (2, '<NAME>'), (3, '<NAME>'), (4, '<NAME>'), (5, '<NAME>'),\n (6, '<NAME>'), (7, '<NAME>'), (8, '<NAME>'), (9, '<NAME>'), (10,\n '<NAME>'), (11, '<NAME>'))"], {}), "(((1, '<NAME>'), (2, '<NAME>'), (3, '<NAME>'), (4, '<NAME>'), (5,\n '<NAME>'), (6, '<NAME>'), (7, '<NAME>'), (8, '<NAME>'), (9, '<NAME>'),\n (10, '<NAME>'), (11, '<NAME>')))\n", (4853, 5030), False, 'from collections import OrderedDict\n'), ((5293, 5339), 'collections.OrderedDict', 'OrderedDict', (["((1, 'Texas'), (2, 'California'))"], {}), "(((1, 'Texas'), (2, 'California')))\n", (5304, 5339), False, 'from collections import OrderedDict\n'), ((5375, 5471), 'collections.OrderedDict', 'OrderedDict', (["((1, '1996'), (2, '2000'), (3, '2004'), (4, '2008'), (5, '2012'), (6, '2016'))"], {}), "(((1, '1996'), (2, '2000'), (3, '2004'), (4, '2008'), (5, '2012'\n ), (6, '2016')))\n", (5386, 5471), False, 'from collections import OrderedDict\n'), ((8341, 8395), 'pandas.DataFrame.from_records', 'pd.DataFrame.from_records', (['records'], {'columns': 'df_columns'}), '(records, columns=df_columns)\n', (8366, 8395), True, 'import pandas as pd\n'), ((10346, 10365), 'fireant.utils.format_metric_key', 'fm', (['"""cumsum(votes)"""'], {}), "('cumsum(votes)')\n", (10348, 10365), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((14917, 14955), 'fireant.slicer.references.ReferenceType', 'ReferenceType', (['"""eoe"""', '"""EoE"""', '"""year"""', '(4)'], {}), "('eoe', 'EoE', 'year', 4)\n", (14930, 14955), False, 'from fireant.slicer.references import ReferenceType\n'), ((545, 551), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (549, 551), False, 'from unittest.mock import Mock\n'), ((7030, 7045), 'fireant.utils.format_dimension_key', 'fd', (['"""timestamp"""'], {}), "('timestamp')\n", (7032, 7045), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((7061, 7076), 'fireant.utils.format_dimension_key', 'fd', (['"""candidate"""'], {}), "('candidate')\n", (7063, 7076), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((7078, 7101), 'fireant.utils.format_dimension_key', 'fd', (['"""candidate_display"""'], {}), "('candidate_display')\n", (7080, 7101), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((7117, 7138), 'fireant.utils.format_dimension_key', 'fd', (['"""political_party"""'], {}), "('political_party')\n", (7119, 7138), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((7154, 7168), 'fireant.utils.format_dimension_key', 'fd', (['"""election"""'], {}), "('election')\n", (7156, 7168), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((7170, 7192), 'fireant.utils.format_dimension_key', 'fd', (['"""election_display"""'], {}), "('election_display')\n", (7172, 7192), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((7208, 7219), 'fireant.utils.format_dimension_key', 'fd', (['"""state"""'], {}), "('state')\n", (7210, 7219), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((7221, 7240), 'fireant.utils.format_dimension_key', 'fd', (['"""state_display"""'], {}), "('state_display')\n", (7223, 7240), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((7256, 7268), 'fireant.utils.format_dimension_key', 'fd', (['"""winner"""'], {}), "('winner')\n", (7258, 7268), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((7284, 7295), 'fireant.utils.format_metric_key', 'fm', (['"""votes"""'], {}), "('votes')\n", (7286, 7295), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((7311, 7321), 'fireant.utils.format_metric_key', 'fm', (['"""wins"""'], {}), "('wins')\n", (7313, 7321), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9234, 9257), 'fireant.utils.format_dimension_key', 'fd', (['"""candidate_display"""'], {}), "('candidate_display')\n", (9236, 9257), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9456, 9479), 'fireant.utils.format_dimension_key', 'fd', (['"""candidate_display"""'], {}), "('candidate_display')\n", (9458, 9479), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9880, 9899), 'fireant.utils.format_dimension_key', 'fd', (['"""state_display"""'], {}), "('state_display')\n", (9882, 9899), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((10263, 10282), 'fireant.utils.format_dimension_key', 'fd', (['"""state_display"""'], {}), "('state_display')\n", (10265, 10282), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((10946, 11128), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': '(ref_data_frame[ref_columns].values - ref_data_frame[columns].values)', 'columns': "[('%s_eoe_delta' % column) for column in columns]", 'index': 'ref_data_frame.index'}), "(data=ref_data_frame[ref_columns].values - ref_data_frame[\n columns].values, columns=[('%s_eoe_delta' % column) for column in\n columns], index=ref_data_frame.index)\n", (10958, 11128), True, 'import pandas as pd\n'), ((11217, 11228), 'fireant.utils.format_metric_key', 'fm', (['"""votes"""'], {}), "('votes')\n", (11219, 11228), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((11230, 11240), 'fireant.utils.format_metric_key', 'fm', (['"""wins"""'], {}), "('wins')\n", (11232, 11240), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((11586, 11637), 'fireant.slicer.totals.get_totals_marker_for_dtype', 'get_totals_marker_for_dtype', (['data_frame.index.dtype'], {}), '(data_frame.index.dtype)\n', (11613, 11637), False, 'from fireant.slicer.totals import get_totals_marker_for_dtype\n'), ((11996, 12050), 'fireant.slicer.totals.get_totals_marker_for_dtype', 'get_totals_marker_for_dtype', (['df.index.levels[-1].dtype'], {}), '(df.index.levels[-1].dtype)\n', (12023, 12050), False, 'from fireant.slicer.totals import get_totals_marker_for_dtype\n'), ((14335, 14356), 'fireant.utils.format_dimension_key', 'fd', (['"""political_party"""'], {}), "('political_party')\n", (14337, 14356), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((14419, 14440), 'fireant.utils.format_dimension_key', 'fd', (['"""political_party"""'], {}), "('political_party')\n", (14421, 14440), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((14507, 14522), 'fireant.utils.format_dimension_key', 'fd', (['"""timestamp"""'], {}), "('timestamp')\n", (14509, 14522), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((14524, 14545), 'fireant.utils.format_dimension_key', 'fd', (['"""political_party"""'], {}), "('political_party')\n", (14526, 14545), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((14608, 14619), 'fireant.utils.format_dimension_key', 'fd', (['"""state"""'], {}), "('state')\n", (14610, 14619), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((14686, 14701), 'fireant.utils.format_dimension_key', 'fd', (['"""timestamp"""'], {}), "('timestamp')\n", (14688, 14701), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((14703, 14714), 'fireant.utils.format_dimension_key', 'fd', (['"""state"""'], {}), "('state')\n", (14705, 14714), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((14789, 14804), 'fireant.utils.format_dimension_key', 'fd', (['"""timestamp"""'], {}), "('timestamp')\n", (14791, 14804), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((14806, 14827), 'fireant.utils.format_dimension_key', 'fd', (['"""political_party"""'], {}), "('political_party')\n", (14808, 14827), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((14829, 14840), 'fireant.utils.format_dimension_key', 'fd', (['"""state"""'], {}), "('state')\n", (14831, 14840), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((8729, 8744), 'fireant.utils.format_dimension_key', 'fd', (['"""timestamp"""'], {}), "('timestamp')\n", (8731, 8744), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((8910, 8931), 'fireant.utils.format_dimension_key', 'fd', (['"""political_party"""'], {}), "('political_party')\n", (8912, 8931), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((10417, 10428), 'fireant.utils.format_metric_key', 'fm', (['"""votes"""'], {}), "('votes')\n", (10419, 10428), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9606, 9621), 'fireant.utils.format_dimension_key', 'fd', (['"""timestamp"""'], {}), "('timestamp')\n", (9608, 9621), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9623, 9644), 'fireant.utils.format_dimension_key', 'fd', (['"""political_party"""'], {}), "('political_party')\n", (9625, 9644), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((11730, 11783), 'pandas.Index', 'pd.Index', (['[totals_marker]'], {'name': 'data_frame.index.name'}), '([totals_marker], name=data_frame.index.name)\n', (11738, 11783), True, 'import pandas as pd\n'), ((12158, 12213), 'pandas.Index', 'pd.Index', (['[totals_index_value]'], {'name': 'df.index.names[-1]'}), '([totals_index_value], name=df.index.names[-1])\n', (12166, 12213), True, 'import pandas as pd\n'), ((13041, 13081), 'fireant.slicer.totals.get_totals_marker_for_dtype', 'get_totals_marker_for_dtype', (['level.dtype'], {}), '(level.dtype)\n', (13068, 13081), False, 'from fireant.slicer.totals import get_totals_marker_for_dtype\n'), ((3842, 3873), 'pypika.functions.Sum', 'fn.Sum', (['politicians_table.votes'], {}), '(politicians_table.votes)\n', (3848, 3873), True, 'from pypika import JoinType, Table, functions as fn\n'), ((3954, 3989), 'pypika.functions.Sum', 'fn.Sum', (['politicians_table.is_winner'], {}), '(politicians_table.is_winner)\n', (3960, 3989), True, 'from pypika import JoinType, Table, functions as fn\n'), ((4074, 4099), 'pypika.functions.Count', 'fn.Count', (['voters_table.id'], {}), '(voters_table.id)\n', (4082, 4099), True, 'from pypika import JoinType, Table, functions as fn\n'), ((4404, 4439), 'pypika.functions.Sum', 'fn.Sum', (['politicians_table.is_winner'], {}), '(politicians_table.is_winner)\n', (4410, 4439), True, 'from pypika import JoinType, Table, functions as fn\n'), ((12788, 12822), 'fireant.slicer.totals.get_totals_marker_for_dtype', 'get_totals_marker_for_dtype', (['dtype'], {}), '(dtype)\n', (12815, 12822), False, 'from fireant.slicer.totals import get_totals_marker_for_dtype\n'), ((13345, 13423), 'pandas.MultiIndex.from_tuples', 'pd.MultiIndex.from_tuples', (['[totals_index_values]'], {'names': 'data_frame.index.names'}), '([totals_index_values], names=data_frame.index.names)\n', (13370, 13423), True, 'import pandas as pd\n'), ((4186, 4217), 'pypika.functions.Sum', 'fn.Sum', (['politicians_table.votes'], {}), '(politicians_table.votes)\n', (4192, 4217), True, 'from pypika import JoinType, Table, functions as fn\n'), ((4220, 4245), 'pypika.functions.Count', 'fn.Count', (['voters_table.id'], {}), '(voters_table.id)\n', (4228, 4245), True, 'from pypika import JoinType, Table, functions as fn\n'), ((8453, 8464), 'fireant.utils.format_metric_key', 'fm', (['"""votes"""'], {}), "('votes')\n", (8455, 8464), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((8565, 8576), 'fireant.utils.format_metric_key', 'fm', (['"""votes"""'], {}), "('votes')\n", (8567, 8576), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((8578, 8588), 'fireant.utils.format_metric_key', 'fm', (['"""wins"""'], {}), "('wins')\n", (8580, 8588), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((8671, 8686), 'fireant.utils.format_dimension_key', 'fd', (['"""timestamp"""'], {}), "('timestamp')\n", (8673, 8686), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((8688, 8699), 'fireant.utils.format_metric_key', 'fm', (['"""votes"""'], {}), "('votes')\n", (8690, 8699), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((8701, 8711), 'fireant.utils.format_metric_key', 'fm', (['"""wins"""'], {}), "('wins')\n", (8703, 8711), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((8846, 8867), 'fireant.utils.format_dimension_key', 'fd', (['"""political_party"""'], {}), "('political_party')\n", (8848, 8867), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((8869, 8880), 'fireant.utils.format_metric_key', 'fm', (['"""votes"""'], {}), "('votes')\n", (8871, 8880), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((8882, 8892), 'fireant.utils.format_metric_key', 'fm', (['"""wins"""'], {}), "('wins')\n", (8884, 8892), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9136, 9157), 'fireant.utils.format_dimension_key', 'fd', (['"""political_party"""'], {}), "('political_party')\n", (9138, 9157), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9159, 9174), 'fireant.utils.format_dimension_key', 'fd', (['"""candidate"""'], {}), "('candidate')\n", (9161, 9174), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9176, 9199), 'fireant.utils.format_dimension_key', 'fd', (['"""candidate_display"""'], {}), "('candidate_display')\n", (9178, 9199), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9381, 9396), 'fireant.utils.format_dimension_key', 'fd', (['"""candidate"""'], {}), "('candidate')\n", (9383, 9396), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9398, 9421), 'fireant.utils.format_dimension_key', 'fd', (['"""candidate_display"""'], {}), "('candidate_display')\n", (9400, 9421), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9524, 9539), 'fireant.utils.format_dimension_key', 'fd', (['"""timestamp"""'], {}), "('timestamp')\n", (9526, 9539), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9541, 9562), 'fireant.utils.format_dimension_key', 'fd', (['"""political_party"""'], {}), "('political_party')\n", (9543, 9562), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9564, 9575), 'fireant.utils.format_metric_key', 'fm', (['"""votes"""'], {}), "('votes')\n", (9566, 9575), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9577, 9587), 'fireant.utils.format_metric_key', 'fm', (['"""wins"""'], {}), "('wins')\n", (9579, 9587), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9796, 9811), 'fireant.utils.format_dimension_key', 'fd', (['"""timestamp"""'], {}), "('timestamp')\n", (9798, 9811), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9813, 9824), 'fireant.utils.format_dimension_key', 'fd', (['"""state"""'], {}), "('state')\n", (9815, 9824), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9826, 9845), 'fireant.utils.format_dimension_key', 'fd', (['"""state_display"""'], {}), "('state_display')\n", (9828, 9845), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((10156, 10171), 'fireant.utils.format_dimension_key', 'fd', (['"""timestamp"""'], {}), "('timestamp')\n", (10158, 10171), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((10173, 10194), 'fireant.utils.format_dimension_key', 'fd', (['"""political_party"""'], {}), "('political_party')\n", (10175, 10194), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((10196, 10207), 'fireant.utils.format_dimension_key', 'fd', (['"""state"""'], {}), "('state')\n", (10198, 10207), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((10209, 10228), 'fireant.utils.format_dimension_key', 'fd', (['"""state_display"""'], {}), "('state_display')\n", (10211, 10228), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((8988, 9009), 'fireant.utils.format_dimension_key', 'fd', (['"""political_party"""'], {}), "('political_party')\n", (8990, 9009), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9011, 9026), 'fireant.utils.format_dimension_key', 'fd', (['"""candidate"""'], {}), "('candidate')\n", (9013, 9026), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9028, 9051), 'fireant.utils.format_dimension_key', 'fd', (['"""candidate_display"""'], {}), "('candidate_display')\n", (9030, 9051), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9094, 9105), 'fireant.utils.format_metric_key', 'fm', (['"""votes"""'], {}), "('votes')\n", (9096, 9105), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9107, 9117), 'fireant.utils.format_metric_key', 'fm', (['"""wins"""'], {}), "('wins')\n", (9109, 9117), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9297, 9312), 'fireant.utils.format_dimension_key', 'fd', (['"""candidate"""'], {}), "('candidate')\n", (9299, 9312), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9314, 9337), 'fireant.utils.format_dimension_key', 'fd', (['"""candidate_display"""'], {}), "('candidate_display')\n", (9316, 9337), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9339, 9350), 'fireant.utils.format_metric_key', 'fm', (['"""votes"""'], {}), "('votes')\n", (9341, 9350), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9352, 9362), 'fireant.utils.format_metric_key', 'fm', (['"""wins"""'], {}), "('wins')\n", (9354, 9362), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9703, 9718), 'fireant.utils.format_dimension_key', 'fd', (['"""timestamp"""'], {}), "('timestamp')\n", (9705, 9718), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9720, 9731), 'fireant.utils.format_dimension_key', 'fd', (['"""state"""'], {}), "('state')\n", (9722, 9731), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9733, 9752), 'fireant.utils.format_dimension_key', 'fd', (['"""state_display"""'], {}), "('state_display')\n", (9735, 9752), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9754, 9765), 'fireant.utils.format_metric_key', 'fm', (['"""votes"""'], {}), "('votes')\n", (9756, 9765), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9767, 9777), 'fireant.utils.format_metric_key', 'fm', (['"""wins"""'], {}), "('wins')\n", (9769, 9777), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9948, 9963), 'fireant.utils.format_dimension_key', 'fd', (['"""timestamp"""'], {}), "('timestamp')\n", (9950, 9963), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((9965, 9986), 'fireant.utils.format_dimension_key', 'fd', (['"""political_party"""'], {}), "('political_party')\n", (9967, 9986), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((10034, 10045), 'fireant.utils.format_dimension_key', 'fd', (['"""state"""'], {}), "('state')\n", (10036, 10045), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((10047, 10066), 'fireant.utils.format_dimension_key', 'fd', (['"""state_display"""'], {}), "('state_display')\n", (10049, 10066), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((10114, 10125), 'fireant.utils.format_metric_key', 'fm', (['"""votes"""'], {}), "('votes')\n", (10116, 10125), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n'), ((10127, 10137), 'fireant.utils.format_metric_key', 'fm', (['"""wins"""'], {}), "('wins')\n", (10129, 10137), True, 'from fireant.utils import format_dimension_key as fd, format_metric_key as fm\n')] |
import requests
from datetime import timedelta
from app.spotify_api import get_auth_header
def get_albums(data):
result = []
for item in data:
skip = False
header = get_auth_header()
songs_r = requests.get(f'https://api.spotify.com/v1/albums/{item["id"]}/tracks', headers=header)
if songs_r.status_code == 200:
if not songs_r.json()['items'][0]['preview_url']:
continue
else:
songs = []
counter = 1
for song in songs_r.json()['items']:
sound_url = song['preview_url']
if not sound_url:
skip = True
break;
song_name = song['name']
spt_song_id = song['id']
order_number = counter
counter += 1
duration = str(timedelta(milliseconds=song['duration_ms']))[2:7]
songs.append({
'spt_song_id': spt_song_id,
'song_name': song_name,
'order_number': order_number,
'duration': duration,
'sound_url': sound_url
})
if skip:
continue
spt_album_id = item['id']
cover_image_url = item['images'][0]['url']
album_name = item['name']
artists = []
for artist in item['artists']:
r_artist = requests.get(artist['href'], headers=header)
if r_artist.status_code == 200:
artist_cover_img_url = r_artist.json()['images'][0]['url']
spt_artist_id = artist['id']
artist_name = artist['name']
else:
print(f'There was an error fetching {artist["name"]}\'s image.')
continue
artists.append({
'spt_artist_id': spt_artist_id,
'artist_name': artist_name,
'cover_image_url': artist_cover_img_url
})
result.append({
'spt_album_id': spt_album_id,
'cover_image_url': cover_image_url,
'album_name': album_name,
'artists': artists,
'songs': songs
})
return result
| [
"app.spotify_api.get_auth_header",
"datetime.timedelta",
"requests.get"
] | [((192, 209), 'app.spotify_api.get_auth_header', 'get_auth_header', ([], {}), '()\n', (207, 209), False, 'from app.spotify_api import get_auth_header\n'), ((228, 318), 'requests.get', 'requests.get', (['f"""https://api.spotify.com/v1/albums/{item[\'id\']}/tracks"""'], {'headers': 'header'}), '(f"https://api.spotify.com/v1/albums/{item[\'id\']}/tracks",\n headers=header)\n', (240, 318), False, 'import requests\n'), ((1525, 1569), 'requests.get', 'requests.get', (["artist['href']"], {'headers': 'header'}), "(artist['href'], headers=header)\n", (1537, 1569), False, 'import requests\n'), ((925, 968), 'datetime.timedelta', 'timedelta', ([], {'milliseconds': "song['duration_ms']"}), "(milliseconds=song['duration_ms'])\n", (934, 968), False, 'from datetime import timedelta\n')] |
import cv2
import numpy as np
from PyQt5.QtGui import QIntValidator
from PyQt5.QtWidgets import QDialog
from PyQt5.uic import loadUi
from utils import processing_utils as utils
IMAGE_DESCRIPT_DIALOG_UI = 'coreUI/image_description_dialog.ui'
class ImageDescriptionDialog(QDialog):
"""Image Description Dialog Window"""
def __init__(self, image):
super(ImageDescriptionDialog, self).__init__()
loadUi(IMAGE_DESCRIPT_DIALOG_UI, self)
self.kernel = None
self.kernel_matrix_edits = [
self.m_r1c1,
self.m_r2c1,
self.m_r3c1,
self.m_r1c2,
self.m_r2c2,
self.m_r3c2,
self.m_r1c3,
self.m_r2c3,
self.m_r3c3,
]
self.set_validation()
description_labels = [
self.shapeDataLabel,
self.channelsDataLabel,
self.sizeDataLabel,
self.datatypeDataLabel
]
# Set up initial display labels
utils.display_img(image, self.imageViewLabel)
(h, w, c) = image.shape
self.shapeDataLabel.setText(f"{w} x {h} pixels")
self.channelsDataLabel.setText(f"{c}")
self.sizeDataLabel.setText(f"{image.size} pixels")
self.datatypeDataLabel.setText(f"{image.dtype}")
# Resize all labels to match the max width
max_label_width = 0
for label in description_labels:
if label.width() > max_label_width:
max_label_width = label.width()
for label in description_labels:
# Add padding to the width for size dimensions
label.setFixedWidth(max_label_width + 50)
# CV image that is passed to the dialog menu
# Note: We do not want a dialog without an image to accompany it
self._image = image
# Cache both the original and processed image
self._processed_image = image.copy()
# Connect UI buttons
self.applyButton.clicked.connect(self.on_apply_clicked)
self.resetButton.clicked.connect(self.on_reset_clicked)
self.normalizeButton.clicked.connect(self.on_normalize_clicked)
def on_apply_clicked(self):
"""
Handle when apply button is clicked
Only apply the matrix when it meets all validation criteria
:return: None if verification fails
"""
if self.verify_not_empty():
utils.display_img(self.apply_kernel_transformation(), self.imageViewLabel)
def on_reset_clicked(self):
"""
Handle when the reset button is clicked
:return:
"""
# Display the original image and reset the processed image
utils.display_img(self._image, self.imageViewLabel)
self._processed_image = self._image.copy()
def verify_not_empty(self):
"""
Verify that all text fields are not empty
:return: True only if all fields are not empty
"""
for text_edit in self.kernel_matrix_edits:
if not text_edit.hasAcceptableInput():
return False
return True
def on_normalize_clicked(self):
"""
Normalize the current kernel matrix and display the result
:return: None if the kernel has not been applied
"""
if self.kernel is None:
return
# Get the sum of the matrix and create the new normalized matrix
sum = np.sum(self.kernel, dtype=np.int32)
normalized_kernel = self.kernel / sum
self._processed_image = self._image.copy()
image = cv2.filter2D(self._processed_image, -1, normalized_kernel)
utils.display_img(image, self.imageViewLabel)
def set_validation(self):
"""
Set validators on all matrix text edits (ensure integer input)
:return:
"""
validator = QIntValidator(-9999999999, 9999999999)
for text_exit in self.kernel_matrix_edits:
text_exit.setValidator(validator)
def apply_kernel_transformation(self):
def val(text_edit): return int(text_edit.text())
self.kernel = np.array([
[val(self.m_r1c1), val(self.m_r1c2), val(self.m_r1c3)],
[val(self.m_r2c1), val(self.m_r2c2), val(self.m_r2c3)],
[val(self.m_r3c1), val(self.m_r3c2), val(self.m_r3c3)]
])
return cv2.filter2D(self._processed_image, -1, self.kernel)
| [
"PyQt5.QtGui.QIntValidator",
"PyQt5.uic.loadUi",
"utils.processing_utils.display_img",
"cv2.filter2D",
"numpy.sum"
] | [((420, 458), 'PyQt5.uic.loadUi', 'loadUi', (['IMAGE_DESCRIPT_DIALOG_UI', 'self'], {}), '(IMAGE_DESCRIPT_DIALOG_UI, self)\n', (426, 458), False, 'from PyQt5.uic import loadUi\n'), ((1016, 1061), 'utils.processing_utils.display_img', 'utils.display_img', (['image', 'self.imageViewLabel'], {}), '(image, self.imageViewLabel)\n', (1033, 1061), True, 'from utils import processing_utils as utils\n'), ((2703, 2754), 'utils.processing_utils.display_img', 'utils.display_img', (['self._image', 'self.imageViewLabel'], {}), '(self._image, self.imageViewLabel)\n', (2720, 2754), True, 'from utils import processing_utils as utils\n'), ((3444, 3479), 'numpy.sum', 'np.sum', (['self.kernel'], {'dtype': 'np.int32'}), '(self.kernel, dtype=np.int32)\n', (3450, 3479), True, 'import numpy as np\n'), ((3594, 3652), 'cv2.filter2D', 'cv2.filter2D', (['self._processed_image', '(-1)', 'normalized_kernel'], {}), '(self._processed_image, -1, normalized_kernel)\n', (3606, 3652), False, 'import cv2\n'), ((3661, 3706), 'utils.processing_utils.display_img', 'utils.display_img', (['image', 'self.imageViewLabel'], {}), '(image, self.imageViewLabel)\n', (3678, 3706), True, 'from utils import processing_utils as utils\n'), ((3870, 3908), 'PyQt5.QtGui.QIntValidator', 'QIntValidator', (['(-9999999999)', '(9999999999)'], {}), '(-9999999999, 9999999999)\n', (3883, 3908), False, 'from PyQt5.QtGui import QIntValidator\n'), ((4372, 4424), 'cv2.filter2D', 'cv2.filter2D', (['self._processed_image', '(-1)', 'self.kernel'], {}), '(self._processed_image, -1, self.kernel)\n', (4384, 4424), False, 'import cv2\n')] |
import tensorflow as tf
from tensorflow import keras
import numpy as np
imdb = keras.datasets.imdb
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)
# A dictionary mapping words to an integer index
word_index = imdb.get_word_index()
# The first indices are reserved
word_index = {k:(v+3) for k,v in word_index.items()}
word_index["<PAD>"] = 0
word_index["<START>"] = 1
word_index["<UNK>"] = 2 # unknown
word_index["<UNUSED>"] = 3
# save indices for later use from java
with open('word_index.txt', 'w') as f:
for k, v in word_index.items():
f.write(str(k.encode('utf-8'))[2:-1] + ',' + str(v) + '\n')
reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
def decode_review(text):
return ' '.join([reverse_word_index.get(i, '?') for i in text])
# save some text for testing from java
save_text = ''
for i in range(10):
save_text += decode_review(test_data[i]) + '\n'
save_text = save_text[:-1]
with open('reviews.txt', 'w') as f:
f.write(save_text)
# prepare the data
train_data = keras.preprocessing.sequence.pad_sequences(train_data,
value=word_index["<PAD>"],
padding='post',
maxlen=256)
test_data = keras.preprocessing.sequence.pad_sequences(test_data,
value=word_index["<PAD>"],
padding='post',
maxlen=256)
vocab_size = 10000
with tf.Session() as sess:
keras.backend.set_session(sess)
model = keras.Sequential()
model.add(keras.layers.Embedding(vocab_size, 16))
model.add(keras.layers.GlobalAveragePooling1D())
model.add(keras.layers.Dense(16, activation=tf.nn.relu))
model.add(keras.layers.Dense(1, activation=tf.nn.sigmoid))
model.summary()
model.compile(optimizer=tf.train.AdamOptimizer(),
loss='binary_crossentropy',
metrics=['accuracy'])
history = model.fit(train_data,
train_labels,
epochs=40,
batch_size=512,
validation_data=(test_data, test_labels),
verbose=1)
sess.run(tf.global_variables_initializer())
output_node_name = model.output.name.split(':')[0]
output_graph_def = tf.graph_util.convert_variables_to_constants(sess, sess.graph.as_graph_def(), [output_node_name])
with tf.gfile.GFile("imdb.pb", "wb") as f:
f.write(output_graph_def.SerializeToString())
| [
"tensorflow.keras.preprocessing.sequence.pad_sequences",
"tensorflow.keras.Sequential",
"tensorflow.Session",
"tensorflow.keras.layers.Embedding",
"tensorflow.global_variables_initializer",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.layers.GlobalAveragePooling1D",
"tensorflow.keras.backend.set... | [((1083, 1197), 'tensorflow.keras.preprocessing.sequence.pad_sequences', 'keras.preprocessing.sequence.pad_sequences', (['train_data'], {'value': "word_index['<PAD>']", 'padding': '"""post"""', 'maxlen': '(256)'}), "(train_data, value=word_index[\n '<PAD>'], padding='post', maxlen=256)\n", (1125, 1197), False, 'from tensorflow import keras\n'), ((1374, 1487), 'tensorflow.keras.preprocessing.sequence.pad_sequences', 'keras.preprocessing.sequence.pad_sequences', (['test_data'], {'value': "word_index['<PAD>']", 'padding': '"""post"""', 'maxlen': '(256)'}), "(test_data, value=word_index[\n '<PAD>'], padding='post', maxlen=256)\n", (1416, 1487), False, 'from tensorflow import keras\n'), ((1674, 1686), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1684, 1686), True, 'import tensorflow as tf\n'), ((1700, 1731), 'tensorflow.keras.backend.set_session', 'keras.backend.set_session', (['sess'], {}), '(sess)\n', (1725, 1731), False, 'from tensorflow import keras\n'), ((1744, 1762), 'tensorflow.keras.Sequential', 'keras.Sequential', ([], {}), '()\n', (1760, 1762), False, 'from tensorflow import keras\n'), ((1777, 1815), 'tensorflow.keras.layers.Embedding', 'keras.layers.Embedding', (['vocab_size', '(16)'], {}), '(vocab_size, 16)\n', (1799, 1815), False, 'from tensorflow import keras\n'), ((1831, 1868), 'tensorflow.keras.layers.GlobalAveragePooling1D', 'keras.layers.GlobalAveragePooling1D', ([], {}), '()\n', (1866, 1868), False, 'from tensorflow import keras\n'), ((1884, 1929), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(16)'], {'activation': 'tf.nn.relu'}), '(16, activation=tf.nn.relu)\n', (1902, 1929), False, 'from tensorflow import keras\n'), ((1945, 1992), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(1)'], {'activation': 'tf.nn.sigmoid'}), '(1, activation=tf.nn.sigmoid)\n', (1963, 1992), False, 'from tensorflow import keras\n'), ((2406, 2439), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (2437, 2439), True, 'import tensorflow as tf\n'), ((2626, 2657), 'tensorflow.gfile.GFile', 'tf.gfile.GFile', (['"""imdb.pb"""', '"""wb"""'], {}), "('imdb.pb', 'wb')\n", (2640, 2657), True, 'import tensorflow as tf\n'), ((2045, 2069), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {}), '()\n', (2067, 2069), True, 'import tensorflow as tf\n')] |
import vcr
from fast_arrow import Client
def gen_vcr():
return vcr.VCR(
cassette_library_dir='tests/fixtures_vcr',
record_mode='none',
match_on=['method', 'scheme', 'host', 'port', 'path', 'query'],
)
def gen_client():
auth_data = gen_auth_data()
client = Client(auth_data)
return client
def gen_auth_data():
auth_data = {
"account_id": 123,
"access_token": "<PASSWORD>",
"refresh_token": "<PASSWORD>",
"device_token": "<PASSWORD>",
}
return auth_data
| [
"fast_arrow.Client",
"vcr.VCR"
] | [((70, 208), 'vcr.VCR', 'vcr.VCR', ([], {'cassette_library_dir': '"""tests/fixtures_vcr"""', 'record_mode': '"""none"""', 'match_on': "['method', 'scheme', 'host', 'port', 'path', 'query']"}), "(cassette_library_dir='tests/fixtures_vcr', record_mode='none',\n match_on=['method', 'scheme', 'host', 'port', 'path', 'query'])\n", (77, 208), False, 'import vcr\n'), ((301, 318), 'fast_arrow.Client', 'Client', (['auth_data'], {}), '(auth_data)\n', (307, 318), False, 'from fast_arrow import Client\n')] |
import datetime
class Person(object):
def __init__(self, name):
self.name = name
try:
lastBlank = name.rindex(' ')
self.lastName = name[lastBlank+1:]
except:
self.lastName = name
self.birthday = None
def getName(self):
return self.name
def getLastName(self):
return self.lastName
def setBirthday(self, birthday):
self.birthday = birthday
def getAge(self):
if self.birthday == None:
raise ValueError
return (datetime.date.today() - self.birthday).days
def __lt__(self, other):
if self.lastName == other.lastName:
return self.name < other.name
return self.lastName < other.lastName
def __str__(self):
return self.name
class MITPerson(Person):
nextIdNum = 0
def __init__(self,name):
Person.__init__(self, name)
self.idNum = MITPerson.nextIdNum
MITPerson.nextIdNum += 1
def getIdNum(self):
return self.idNum
def __lt__(self, other):
return self.idNum < other.idNum
class Student(MITPerson):
pass
class UG(Student):
def __init__(self, name, classYear):
Student.__init__(self, name)
self.year = classYear
def getClass(self):
return self.year
class Grad(Student):
pass
class TransferStudent(Student):
def __init__(self, name, fromSchool):
Student.__init__(self, name)
self.fromSchool = fromSchool
def getOldSchool(self):
return self.fromSchool
class Grades(object):
def __init__(self):
self.students = []
p5 = Grad('<NAME>')
p6 = UG('<NAME>', 1984)
print(p5)
print(type(p5)==Grad)
print(p6, type(p6) == UG)
print(UG)
me = Person('<NAME>')
him = Person('<NAME>')
her = Person('Madonna')
print(him.getLastName())
him.setBirthday(datetime.date(1961,8,4))
her.setBirthday(datetime.date(1958, 8, 16))
p1 = MITPerson('<NAME>')
print(str(p1) + '\'s id number is ' + str(p1.getIdNum())) | [
"datetime.date.today",
"datetime.date"
] | [((1905, 1930), 'datetime.date', 'datetime.date', (['(1961)', '(8)', '(4)'], {}), '(1961, 8, 4)\n', (1918, 1930), False, 'import datetime\n'), ((1946, 1972), 'datetime.date', 'datetime.date', (['(1958)', '(8)', '(16)'], {}), '(1958, 8, 16)\n', (1959, 1972), False, 'import datetime\n'), ((557, 578), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (576, 578), False, 'import datetime\n')] |
#
# Copyright 2022 DMetaSoul
#
# 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 metaspore as ms
import subprocess
import yaml
import argparse
import sys
import pyspark
import pyspark.sql.functions as F
from pyspark.mllib.evaluation import RankingMetrics
sys.path.append("../../../../")
from python.algos.tuner.base_tuner import BaseTuner
class SwingTuner(BaseTuner):
def __init__(self, config):
super().__init__(config)
self._experiments_order_by = 'recall_at_20'
self._experiments_order_reverse = True
def get_estimator(self, config):
param_dict = {**config['common_param'], **config['hyper_param'], **self._dataset}
estimator = ms.SwingEstimator(user_id_column_name=param_dict['user_id_column_name'],
item_id_column_name=param_dict['item_id_column_name'],
behavior_column_name=param_dict['behavior_column_name'],
behavior_filter_value=param_dict['behavior_filter_value'],
key_column_name=param_dict['key_column_name'],
value_column_name=param_dict['value_column_name'],
use_plain_weight=param_dict['use_plain_weight'],
smoothing_coefficient=param_dict['smoothing_coefficient'],
max_recommendation_count=param_dict['max_recommendation_count'])
## we need transform test dataframe
self._test_df = self._dataset['test']
self._test_df = self._test_df.select(param_dict['user_id_column_name'], param_dict['last_item_col_name'], param_dict['item_id_column_name'])\
.groupBy(param_dict['user_id_column_name'], param_dict['last_item_col_name'])\
.agg(F.collect_set(param_dict['item_id_column_name']).alias('label_items'))
self._test_df = self._test_df.withColumnRenamed(param_dict['last_item_col_name'], param_dict['item_id_column_name'])
return estimator
def evaluate(self, model):
prediction_df = model.transform(self._test_df)
prediction_df = prediction_df.withColumnRenamed('value', 'rec_info')
prediction_label_rdd = prediction_df.rdd.map(lambda x:(\
[xx._1 for xx in x.rec_info] if x.rec_info is not None else [], \
x.label_items))
metrics = RankingMetrics(prediction_label_rdd)
precisionAt20 = metrics.precisionAt(20)
recallAt20 = metrics.recallAt(20)
meanAveragePrecisionAt20 = metrics.meanAveragePrecisionAt(20)
print('=========================================')
print('Precision@20: ', precisionAt20)
print('Recall@20: ', recallAt20)
print('MAP@20: ', meanAveragePrecisionAt20)
print('=========================================')
return {'precision_at_20': precisionAt20, \
'recall_at_20': recallAt20, \
'map_at_20': meanAveragePrecisionAt20}
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Tuner information')
parser.add_argument('-conf', dest='config', type=str, help='Path of config file')
args = parser.parse_args()
print(args.config)
config_path = args.config
config = dict()
with open(config_path, 'r') as stream:
config = yaml.load(stream, Loader=yaml.FullLoader)
subprocess.run(['zip', '-r', 'demo/movielens/offline/tuner/offline/python.zip', 'python'], cwd='../../../../')
tuner = SwingTuner(config)
tuner.run()
| [
"argparse.ArgumentParser",
"pyspark.mllib.evaluation.RankingMetrics",
"subprocess.run",
"yaml.load",
"metaspore.SwingEstimator",
"sys.path.append",
"pyspark.sql.functions.collect_set"
] | [((760, 791), 'sys.path.append', 'sys.path.append', (['"""../../../../"""'], {}), "('../../../../')\n", (775, 791), False, 'import sys\n'), ((3667, 3723), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Tuner information"""'}), "(description='Tuner information')\n", (3690, 3723), False, 'import argparse\n'), ((4026, 4145), 'subprocess.run', 'subprocess.run', (["['zip', '-r', 'demo/movielens/offline/tuner/offline/python.zip', 'python']"], {'cwd': '"""../../../../"""'}), "(['zip', '-r',\n 'demo/movielens/offline/tuner/offline/python.zip', 'python'], cwd=\n '../../../../')\n", (4040, 4145), False, 'import subprocess\n'), ((1194, 1744), 'metaspore.SwingEstimator', 'ms.SwingEstimator', ([], {'user_id_column_name': "param_dict['user_id_column_name']", 'item_id_column_name': "param_dict['item_id_column_name']", 'behavior_column_name': "param_dict['behavior_column_name']", 'behavior_filter_value': "param_dict['behavior_filter_value']", 'key_column_name': "param_dict['key_column_name']", 'value_column_name': "param_dict['value_column_name']", 'use_plain_weight': "param_dict['use_plain_weight']", 'smoothing_coefficient': "param_dict['smoothing_coefficient']", 'max_recommendation_count': "param_dict['max_recommendation_count']"}), "(user_id_column_name=param_dict['user_id_column_name'],\n item_id_column_name=param_dict['item_id_column_name'],\n behavior_column_name=param_dict['behavior_column_name'],\n behavior_filter_value=param_dict['behavior_filter_value'],\n key_column_name=param_dict['key_column_name'], value_column_name=\n param_dict['value_column_name'], use_plain_weight=param_dict[\n 'use_plain_weight'], smoothing_coefficient=param_dict[\n 'smoothing_coefficient'], max_recommendation_count=param_dict[\n 'max_recommendation_count'])\n", (1211, 1744), True, 'import metaspore as ms\n'), ((3014, 3050), 'pyspark.mllib.evaluation.RankingMetrics', 'RankingMetrics', (['prediction_label_rdd'], {}), '(prediction_label_rdd)\n', (3028, 3050), False, 'from pyspark.mllib.evaluation import RankingMetrics\n'), ((3975, 4016), 'yaml.load', 'yaml.load', (['stream'], {'Loader': 'yaml.FullLoader'}), '(stream, Loader=yaml.FullLoader)\n', (3984, 4016), False, 'import yaml\n'), ((2363, 2411), 'pyspark.sql.functions.collect_set', 'F.collect_set', (["param_dict['item_id_column_name']"], {}), "(param_dict['item_id_column_name'])\n", (2376, 2411), True, 'import pyspark.sql.functions as F\n')] |
import shared_module
from shared_module import module_function as my_function, ModuleClass
class NewParent(object):
def do_useful_stuff(self):
i = shared_module.MODULE_CONTANT
my_function()
ModuleClass() | [
"shared_module.ModuleClass",
"shared_module.module_function"
] | [((198, 211), 'shared_module.module_function', 'my_function', ([], {}), '()\n', (209, 211), True, 'from shared_module import module_function as my_function, ModuleClass\n'), ((220, 233), 'shared_module.ModuleClass', 'ModuleClass', ([], {}), '()\n', (231, 233), False, 'from shared_module import module_function as my_function, ModuleClass\n')] |
# -*- coding: utf-8 -*-
import os
os.environ['DJANGO_SETTINGS_MODULE']='settings'
from logistic import logisticdb
import webapp2 as webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
import numpy as np
import cgi
import cgitb
cgitb.enable()
def lesliegrow(n_o, T, l_m,S):
n_f=np.zeros(shape=(S,T))
for i in range(0, T):
n=np.dot(l_m, n_o)
n_o=n
n_f[:,i]=n.squeeze()
return n_f.tolist()
class leslieOutputPage(webapp.RequestHandler):
def post(self):
form = cgi.FieldStorage()
#text_file = open('.txt','r')
#x1 = text_file.read()
T = form.getvalue('T')
T = int(T)
S = form.getvalue('S')
S = int(S)
l_m = np.zeros(shape=(S,S))
n_o = np.zeros(shape=(S,1))
for i in range(S):
n_o_temp = form.getvalue('no'+str(i))
n_o[i,] = n_o_temp
for j in range(S):
l_m_temp = form.getvalue('a'+str(i)+str(j))
l_m[i,j] = l_m_temp
x=lesliegrow(n_o, T, l_m,S)
templatepath = os.path.dirname(__file__) + '/../templates/'
html = template.render(templatepath + '01pop_uberheader.html', {'title':'Ubertool'})
html = html + template.render(templatepath + '02pop_uberintroblock_wmodellinks.html', {'model':'leslie','page':'output'})
html = html + template.render(templatepath + '03pop_ubertext_links_left.html', {})
html = html + template.render(templatepath + '04uberoutput_start.html', {
'model':'leslie',
'model_attributes':'Leslie Matrix Outputs'})
html = html + """<table class="out-in out_" width="550" border="1">
<tr>
<th scope="col" width="250"><div align="center">Inputs</div></th>
<th scope="col" width="150"><div align="center">Unit</div></th>
<th scope="col" width="150"><div align="center">Value</div></th>
</tr>
<tr>
<td><div align="center">Simulation duration</div></td>
<td><div align="center">time unit</div></td>
<td><div align="center">%s</div></td>
</tr>
<tr>
<td><div align="center">Modeled stages</div></td>
<td><div align="center"> </div></td>
<td id="MS"><div align="center">%s</div></td>
</tr>
<tr style="display:none">
<td><div align="center">Leslie Matrix</div></td>
<td><div align="center"> </div></td>
<td id="LM"><div align="center">%s</div></td>
</tr>
<tr style="display:none">
<td><div align="center">Initial numbers</div></td>
<td><div align="center"> </div></td>
<td id="IN"><div align="center">%s</div></td>
</tr>
</table>
<p> </p>"""%(T, S, l_m.tolist(), n_o.tolist())
html = html + """<table class="lm out_" border="1">"""
html = html + """<table class="ii out_" border="1">"""
html = html + """<table width="400" border="1" style="display: none">
<tr>
<td>X</td>
<td id="final">%s</td>
</tr>
</table>"""%(x)
html = html + template.render(templatepath + 'leslie-output-jqplot.html', {})
html = html + template.render(templatepath + '04uberoutput_end.html', {})
html = html + template.render(templatepath + 'export.html', {})
html = html + template.render(templatepath + '06pop_uberfooter.html', {'links': ''})
self.response.out.write(html)
app = webapp.WSGIApplication([('/.*', leslieOutputPage)], debug=True)
def main():
run_wsgi_app(app)
if __name__ == '__main__':
main()
| [
"cgi.FieldStorage",
"os.path.dirname",
"numpy.dot",
"numpy.zeros",
"google.appengine.ext.webapp.util.run_wsgi_app",
"webapp2.WSGIApplication",
"cgitb.enable",
"google.appengine.ext.webapp.template.render"
] | [((291, 305), 'cgitb.enable', 'cgitb.enable', ([], {}), '()\n', (303, 305), False, 'import cgitb\n'), ((4709, 4772), 'webapp2.WSGIApplication', 'webapp.WSGIApplication', (["[('/.*', leslieOutputPage)]"], {'debug': '(True)'}), "([('/.*', leslieOutputPage)], debug=True)\n", (4731, 4772), True, 'import webapp2 as webapp\n'), ((351, 373), 'numpy.zeros', 'np.zeros', ([], {'shape': '(S, T)'}), '(shape=(S, T))\n', (359, 373), True, 'import numpy as np\n'), ((4799, 4816), 'google.appengine.ext.webapp.util.run_wsgi_app', 'run_wsgi_app', (['app'], {}), '(app)\n', (4811, 4816), False, 'from google.appengine.ext.webapp.util import run_wsgi_app\n'), ((409, 425), 'numpy.dot', 'np.dot', (['l_m', 'n_o'], {}), '(l_m, n_o)\n', (415, 425), True, 'import numpy as np\n'), ((584, 602), 'cgi.FieldStorage', 'cgi.FieldStorage', ([], {}), '()\n', (600, 602), False, 'import cgi\n'), ((788, 810), 'numpy.zeros', 'np.zeros', ([], {'shape': '(S, S)'}), '(shape=(S, S))\n', (796, 810), True, 'import numpy as np\n'), ((824, 846), 'numpy.zeros', 'np.zeros', ([], {'shape': '(S, 1)'}), '(shape=(S, 1))\n', (832, 846), True, 'import numpy as np\n'), ((1239, 1317), 'google.appengine.ext.webapp.template.render', 'template.render', (["(templatepath + '01pop_uberheader.html')", "{'title': 'Ubertool'}"], {}), "(templatepath + '01pop_uberheader.html', {'title': 'Ubertool'})\n", (1254, 1317), False, 'from google.appengine.ext.webapp import template\n'), ((1179, 1204), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1194, 1204), False, 'import os\n'), ((1339, 1454), 'google.appengine.ext.webapp.template.render', 'template.render', (["(templatepath + '02pop_uberintroblock_wmodellinks.html')", "{'model': 'leslie', 'page': 'output'}"], {}), "(templatepath + '02pop_uberintroblock_wmodellinks.html', {\n 'model': 'leslie', 'page': 'output'})\n", (1354, 1454), False, 'from google.appengine.ext.webapp import template\n'), ((1469, 1537), 'google.appengine.ext.webapp.template.render', 'template.render', (["(templatepath + '03pop_ubertext_links_left.html')", '{}'], {}), "(templatepath + '03pop_ubertext_links_left.html', {})\n", (1484, 1537), False, 'from google.appengine.ext.webapp import template\n'), ((1560, 1687), 'google.appengine.ext.webapp.template.render', 'template.render', (["(templatepath + '04uberoutput_start.html')", "{'model': 'leslie', 'model_attributes': 'Leslie Matrix Outputs'}"], {}), "(templatepath + '04uberoutput_start.html', {'model':\n 'leslie', 'model_attributes': 'Leslie Matrix Outputs'})\n", (1575, 1687), False, 'from google.appengine.ext.webapp import template\n'), ((4323, 4386), 'google.appengine.ext.webapp.template.render', 'template.render', (["(templatepath + 'leslie-output-jqplot.html')", '{}'], {}), "(templatepath + 'leslie-output-jqplot.html', {})\n", (4338, 4386), False, 'from google.appengine.ext.webapp import template\n'), ((4434, 4493), 'google.appengine.ext.webapp.template.render', 'template.render', (["(templatepath + '04uberoutput_end.html')", '{}'], {}), "(templatepath + '04uberoutput_end.html', {})\n", (4449, 4493), False, 'from google.appengine.ext.webapp import template\n'), ((4516, 4565), 'google.appengine.ext.webapp.template.render', 'template.render', (["(templatepath + 'export.html')", '{}'], {}), "(templatepath + 'export.html', {})\n", (4531, 4565), False, 'from google.appengine.ext.webapp import template\n'), ((4588, 4658), 'google.appengine.ext.webapp.template.render', 'template.render', (["(templatepath + '06pop_uberfooter.html')", "{'links': ''}"], {}), "(templatepath + '06pop_uberfooter.html', {'links': ''})\n", (4603, 4658), False, 'from google.appengine.ext.webapp import template\n')] |
from cement import Controller, ex
from ..utils import databaseUtils, controllerUtils
class CollectionController(Controller):
class Meta:
label = 'collection controls'
@ex(
help='set currently active collection by id or name',
arguments=[
(
['-i', '--id'],
{
'help': 'collection id',
'action': 'store',
'dest': 'id'
}
)
]
)
def collection_active(self):
if self.app.pargs.id is not None:
col_id = self.app.pargs.id
databaseUtils.set_active_collection(self, col_id)
self.collection_list()
else:
col_id = databaseUtils.get_active_collection_id(self)
collection = self.app.db.table('collections').get(doc_id=col_id)
data = {'collection': collection}
self.app.render(data, 'select_collection.help.jinja2')
@ex(help='create a new collection')
def collection_new(self):
databaseUtils.create_poem_collection(self)
@ex(help='list all collections')
def collection_list(self):
data = {
'collections': controllerUtils.get_all_collections(self),
'active_collection': databaseUtils.get_active_collection_id(self)
}
self.app.render(data, 'list_collections.jinja2')
@ex(
help='permanently delete collection',
arguments=[
(
['-i', '--id'],
{
'help': 'collection id',
'action': 'store',
'dest': 'id'
}
)
]
)
def collection_delete(self):
if self.app.pargs.id is not None:
delete_id = self.app.pargs.id
databaseUtils.delete_collection(self, delete_id)
self.collection_list()
else:
self.app.render({}, 'delete_collection.help.jinja2')
| [
"cement.ex"
] | [((187, 337), 'cement.ex', 'ex', ([], {'help': '"""set currently active collection by id or name"""', 'arguments': "[(['-i', '--id'], {'help': 'collection id', 'action': 'store', 'dest': 'id'})]"}), "(help='set currently active collection by id or name', arguments=[(['-i',\n '--id'], {'help': 'collection id', 'action': 'store', 'dest': 'id'})])\n", (189, 337), False, 'from cement import Controller, ex\n'), ((989, 1023), 'cement.ex', 'ex', ([], {'help': '"""create a new collection"""'}), "(help='create a new collection')\n", (991, 1023), False, 'from cement import Controller, ex\n'), ((1111, 1142), 'cement.ex', 'ex', ([], {'help': '"""list all collections"""'}), "(help='list all collections')\n", (1113, 1142), False, 'from cement import Controller, ex\n'), ((1412, 1547), 'cement.ex', 'ex', ([], {'help': '"""permanently delete collection"""', 'arguments': "[(['-i', '--id'], {'help': 'collection id', 'action': 'store', 'dest': 'id'})]"}), "(help='permanently delete collection', arguments=[(['-i', '--id'], {\n 'help': 'collection id', 'action': 'store', 'dest': 'id'})])\n", (1414, 1547), False, 'from cement import Controller, ex\n')] |
import copy
import typing
import splendor_sim.interfaces.coin.i_coin_reserve as i_coin_reserve
import splendor_sim.interfaces.coin.i_coin_type as i_coin_type
import splendor_sim.interfaces.coin.i_coin_type_manager as i_coin_type_manager
class CoinReserve(i_coin_reserve.ICoinReserve):
def __init__(
self,
coin_type_manager: i_coin_type_manager.ICoinTypeManager,
coin_stocks: typing.Dict[i_coin_type.ICoinType, int] = None,
):
self._coin_type_manager = coin_type_manager
self._coin_set = self._coin_type_manager.get_coin_set()
self._max_coin_size: typing.Dict[i_coin_type.ICoinType, int] = {
coin: coin.get_total_number() for coin in self._coin_set
}
self._current_coins: typing.Dict[i_coin_type.ICoinType, int] = {
coin: coin.get_total_number() for coin in self._coin_set
}
if coin_stocks:
self._validate_coin_stocks(coin_stocks)
for coin, count in coin_stocks.items():
self._current_coins[coin] = count
def get_manager(self) -> i_coin_type_manager.ICoinTypeManager:
return self._coin_type_manager
def get_coins_remaining(self) -> typing.Dict[i_coin_type.ICoinType, int]:
return copy.copy(self._current_coins)
def get_coins_maximum(self) -> typing.Dict[i_coin_type.ICoinType, int]:
return copy.copy(self._max_coin_size)
def has_minimum(self, minimum: typing.Dict[i_coin_type.ICoinType, int]) -> bool:
self._validate_input_dictionary(minimum)
for coin, value in minimum.items():
if self._current_coins[coin] < value:
return False
return True
def add_coins(self, added_coins: typing.Dict[i_coin_type.ICoinType, int]) -> None:
self._validate_input_dictionary(added_coins)
for coin, value in added_coins.items():
if self._current_coins[coin] + value > self._max_coin_size[coin]:
raise ValueError("add would set " + str(coin) + " above its max")
self._current_coins[coin] += value
def remove_coins(
self, removed_coins: typing.Dict[i_coin_type.ICoinType, int]
) -> None:
self._validate_input_dictionary(removed_coins)
for coin, value in removed_coins.items():
if self._current_coins[coin] - value < 0:
raise ValueError("removed would set " + str(coin) + " bellow zero")
self._current_coins[coin] -= value
def _validate_input_dictionary(
self, dictionary: typing.Dict[i_coin_type.ICoinType, int]
) -> None:
for key in dictionary:
if key not in self._coin_set:
raise ValueError(str(key) + "is not a coin type in this Reserve")
def _validate_coin_stocks(
self, dictionary: typing.Dict[i_coin_type.ICoinType, int]
) -> None:
self._validate_input_dictionary(dictionary)
for key, value in dictionary.items():
if key.get_total_number() < value:
raise ValueError(
str(key) + "coin type cant have more stock then max number of coins"
)
def to_json(self) -> typing.Dict:
coin_stocks = []
for coin, value in self._current_coins.items():
if not value == coin.get_total_number():
coin_stocks.append({"coin_name": coin.get_name(), "count": value})
return {
"coin_type_manager": self._coin_type_manager.to_json(),
"coin_stocks": coin_stocks,
}
| [
"copy.copy"
] | [((1260, 1290), 'copy.copy', 'copy.copy', (['self._current_coins'], {}), '(self._current_coins)\n', (1269, 1290), False, 'import copy\n'), ((1383, 1413), 'copy.copy', 'copy.copy', (['self._max_coin_size'], {}), '(self._max_coin_size)\n', (1392, 1413), False, 'import copy\n')] |
import pytest
from dagger.serializer.as_pickle import AsPickle
from dagger.serializer.errors import DeserializationError, SerializationError
from dagger.serializer.protocol import Serializer
def test__conforms_to_protocol():
assert isinstance(AsPickle(), Serializer)
def test_extension():
assert AsPickle().extension == "pickle"
def test_serialization_and_deserialization__with_valid_values():
serializer = AsPickle()
valid_values = [
None,
1,
1.1,
True,
"string",
["list", "of", 3],
{"object": {"with": ["nested", "values"]}},
{"python", "set"},
float("inf"),
float("-inf"),
serializer,
]
for value in valid_values:
serialized_value = serializer.serialize(value)
assert (type(serialized_value)) == bytes
deserialized_value = serializer.deserialize(serialized_value)
assert value == deserialized_value
def test_serialization__with_invalid_values():
class ClassOutOfScope:
pass
def func_out_of_scope():
pass
serializer = AsPickle()
invalid_values = [
lambda: 1,
ClassOutOfScope,
ClassOutOfScope(),
func_out_of_scope,
]
for value in invalid_values:
with pytest.raises(SerializationError):
serializer.serialize(value)
def test_deserialization__with_invalid_values():
serializer = AsPickle()
invalid_values = [
b"arbitrary byte string",
{"python": ["data", "structure"]},
serializer,
]
for value in invalid_values:
with pytest.raises(DeserializationError):
serializer.deserialize(value)
| [
"dagger.serializer.as_pickle.AsPickle",
"pytest.raises"
] | [((426, 436), 'dagger.serializer.as_pickle.AsPickle', 'AsPickle', ([], {}), '()\n', (434, 436), False, 'from dagger.serializer.as_pickle import AsPickle\n'), ((1105, 1115), 'dagger.serializer.as_pickle.AsPickle', 'AsPickle', ([], {}), '()\n', (1113, 1115), False, 'from dagger.serializer.as_pickle import AsPickle\n'), ((1433, 1443), 'dagger.serializer.as_pickle.AsPickle', 'AsPickle', ([], {}), '()\n', (1441, 1443), False, 'from dagger.serializer.as_pickle import AsPickle\n'), ((250, 260), 'dagger.serializer.as_pickle.AsPickle', 'AsPickle', ([], {}), '()\n', (258, 260), False, 'from dagger.serializer.as_pickle import AsPickle\n'), ((309, 319), 'dagger.serializer.as_pickle.AsPickle', 'AsPickle', ([], {}), '()\n', (317, 319), False, 'from dagger.serializer.as_pickle import AsPickle\n'), ((1290, 1323), 'pytest.raises', 'pytest.raises', (['SerializationError'], {}), '(SerializationError)\n', (1303, 1323), False, 'import pytest\n'), ((1617, 1652), 'pytest.raises', 'pytest.raises', (['DeserializationError'], {}), '(DeserializationError)\n', (1630, 1652), False, 'import pytest\n')] |
from torch.utils.data import Dataset
from PIL import Image
from pathlib import Path
import pandas
import torch
# from utils import data_utils
class InferenceDataset(Dataset):
def __init__(self, root, opts, split, transform=None, preprocess=None):
self.root = root
attributes_path = Path(root) / "list_attr_celeba.txt"
attr = pandas.read_csv(attributes_path, delim_whitespace=True, header=1)
split_map = {
"train": 0,
"valid": 1,
"test": 2,
"all": None,
}
split_ = split_map[split.lower()]
attributes_path = Path(root) / "list_eval_partition.txt"
splits = pandas.read_csv(
attributes_path, delim_whitespace=True, header=None, index_col=0
)
mask = slice(None) if split_ is None else (splits[1] == split_)
self.attr = torch.as_tensor(attr[mask].values)
self.paths = attr[mask].index.tolist()
self.attribute_names = attr.columns.tolist()
self.transform = transform
self.preprocess = preprocess
self.opts = opts
def __len__(self):
return len(self.paths)
def __getitem__(self, index):
img_name = self.paths[index]
from_path = self.root + "img_align_celeba/" + img_name
attr = self.attr[index]
if self.preprocess is not None:
from_im = self.preprocess(from_path)
else:
from_im = Image.open(from_path).convert('RGB')
if self.transform:
from_im = self.transform(from_im)
return from_im, attr, img_name
if __name__ == '__main__':
dataset = InferenceDataset("/home/davidetalon/Dev/learning-self/data/raw/celeba", split='train', opts=None ) | [
"torch.as_tensor",
"PIL.Image.open",
"pandas.read_csv",
"pathlib.Path"
] | [((335, 400), 'pandas.read_csv', 'pandas.read_csv', (['attributes_path'], {'delim_whitespace': '(True)', 'header': '(1)'}), '(attributes_path, delim_whitespace=True, header=1)\n', (350, 400), False, 'import pandas\n'), ((588, 673), 'pandas.read_csv', 'pandas.read_csv', (['attributes_path'], {'delim_whitespace': '(True)', 'header': 'None', 'index_col': '(0)'}), '(attributes_path, delim_whitespace=True, header=None,\n index_col=0)\n', (603, 673), False, 'import pandas\n'), ((763, 797), 'torch.as_tensor', 'torch.as_tensor', (['attr[mask].values'], {}), '(attr[mask].values)\n', (778, 797), False, 'import torch\n'), ((290, 300), 'pathlib.Path', 'Path', (['root'], {}), '(root)\n', (294, 300), False, 'from pathlib import Path\n'), ((538, 548), 'pathlib.Path', 'Path', (['root'], {}), '(root)\n', (542, 548), False, 'from pathlib import Path\n'), ((1253, 1274), 'PIL.Image.open', 'Image.open', (['from_path'], {}), '(from_path)\n', (1263, 1274), False, 'from PIL import Image\n')] |
#!/usr/bin/python2.4
#
# Copyright 2009 Google Inc. All Rights Reserved.
"""Defines the generic robot classes.
This module provides the Robot class and RobotListener interface,
as well as some helper functions for web requests and responses.
"""
__author__ = '<EMAIL> (<NAME>)'
import events
import model
import ops
import simplejson
import util
def ParseJSONBody(json_body):
"""Parse a JSON string and return a context and an event list."""
json = simplejson.loads(json_body)
# TODO(davidbyttow): Remove this once no longer needed.
data = util.CollapseJavaCollections(json)
context = ops.CreateContext(data)
event_list = [model.CreateEvent(event_data) for event_data in data['events']]
return context, event_list
def SerializeContext(context, version):
"""Return a JSON string representing the given context."""
context_dict = util.Serialize(context)
context_dict['version'] = version
return simplejson.dumps(context_dict)
class Robot(object):
"""Robot metadata class.
This class holds on to basic robot information like the name and profile.
It also maintains the list of event handlers and cron jobs and
dispatches events to the appropriate handlers.
"""
def __init__(self, name, version, image_url='', profile_url=''):
"""Initializes self with robot information."""
self._handlers = {}
self.name = name
self.version = version
self.image_url = image_url
self.profile_url = profile_url
self.cron_jobs = []
def RegisterListener(self, listener):
"""Registers all event handlers exported by the given object.
Args:
listener: an object with methods corresponding to wave events.
Methods should be named either in camel case, e.g. 'OnBlipSubmitted',
or in lowercase, e.g. 'on_blip_submitted', with names corresponding
to the event names in the events module.
"""
for event in dir(events):
if event.startswith('_'):
continue
lowercase_method_name = 'on_' + event.lower()
camelcase_method_name = 'On' + util.ToUpperCamelCase(event)
if hasattr(listener, lowercase_method_name):
handler = getattr(listener, lowercase_method_name)
elif hasattr(listener, camelcase_method_name):
handler = getattr(listener, camelcase_method_name)
else:
continue
if callable(handler):
self.RegisterHandler(event, handler)
def RegisterHandler(self, event_type, handler):
"""Registers a handler on a specific event type.
Multiple handlers may be registered on a single event type and are
guaranteed to be called in order.
The handler takes two arguments, the event properties and the Context of
this session. For example:
def OnParticipantsChanged(properties, context):
pass
Args:
event_type: An event type to listen for.
handler: A function handler which takes two arguments, event properties
and the Context of this session.
"""
self._handlers.setdefault(event_type, []).append(handler)
def RegisterCronJob(self, path, seconds):
"""Registers a cron job to surface in capabilities.xml."""
self.cron_jobs.append((path, seconds))
def HandleEvent(self, event, context):
"""Calls all of the handlers associated with an event."""
for handler in self._handlers.get(event.type, []):
# TODO(jacobly): pass the event in to the handlers directly
# instead of passing the properties dictionary.
handler(event.properties, context)
def GetCapabilitiesXml(self):
"""Return this robot's capabilities as an XML string."""
lines = ['<w:version>%s</w:version>' % self.version]
lines.append('<w:capabilities>')
for capability in self._handlers:
lines.append(' <w:capability name="%s"/>' % capability)
lines.append('</w:capabilities>')
if self.cron_jobs:
lines.append('<w:crons>')
for job in self.cron_jobs:
lines.append(' <w:cron path="%s" timerinseconds="%s"/>' % job)
lines.append('</w:crons>')
robot_attrs = ' name="%s"' % self.name
if self.image_url:
robot_attrs += ' imageurl="%s"' % self.image_url
if self.profile_url:
robot_attrs += ' profileurl="%s"' % self.profile_url
lines.append('<w:profile%s/>' % robot_attrs)
return ('<?xml version="1.0"?>\n'
'<w:robot xmlns:w="http://wave.google.com/extensions/robots/1.0">\n'
'%s\n</w:robot>\n') % ('\n'.join(lines))
def GetProfileJson(self):
"""Returns JSON body for any profile handler.
Returns:
String of JSON to be sent as a response.
"""
data = {}
data['name'] = self.name
data['imageUrl'] = self.image_url
data['profileUrl'] = self.profile_url
# TODO(davidbyttow): Remove this java nonsense.
data['javaClass'] = 'com.google.wave.api.ParticipantProfile'
return simplejson.dumps(data)
| [
"util.CollapseJavaCollections",
"simplejson.dumps",
"util.ToUpperCamelCase",
"ops.CreateContext",
"util.Serialize",
"simplejson.loads",
"model.CreateEvent"
] | [((459, 486), 'simplejson.loads', 'simplejson.loads', (['json_body'], {}), '(json_body)\n', (475, 486), False, 'import simplejson\n'), ((554, 588), 'util.CollapseJavaCollections', 'util.CollapseJavaCollections', (['json'], {}), '(json)\n', (582, 588), False, 'import util\n'), ((601, 624), 'ops.CreateContext', 'ops.CreateContext', (['data'], {}), '(data)\n', (618, 624), False, 'import ops\n'), ((854, 877), 'util.Serialize', 'util.Serialize', (['context'], {}), '(context)\n', (868, 877), False, 'import util\n'), ((923, 953), 'simplejson.dumps', 'simplejson.dumps', (['context_dict'], {}), '(context_dict)\n', (939, 953), False, 'import simplejson\n'), ((641, 670), 'model.CreateEvent', 'model.CreateEvent', (['event_data'], {}), '(event_data)\n', (658, 670), False, 'import model\n'), ((4856, 4878), 'simplejson.dumps', 'simplejson.dumps', (['data'], {}), '(data)\n', (4872, 4878), False, 'import simplejson\n'), ((2048, 2076), 'util.ToUpperCamelCase', 'util.ToUpperCamelCase', (['event'], {}), '(event)\n', (2069, 2076), False, 'import util\n')] |
import pathlib
from setuptools import setup, find_packages
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
setup(
description='Data extraction and processing for genre prediction using ML',
long_description=README,
long_description_content_type="text/markdown",
url="https://github.com/adaros92/CS467-Project",
version='0.3.4',
install_requires=[
'requests', 'pandas', 'numpy', 'tabulate', 'pydub', 'librosa', 'matplotlib', 'youtube_dl',
'tensorflow', 'scikit-learn==0.22.2.post1'],
tests_require=['pytest', 'pytest-cov'],
license="MIT",
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7",
],
packages=find_packages(exclude=("test",)),
name='genreml',
python_requires='>=3.5',
package_data={
'genreml': ['fma_data/*.mp3', 'model_resources/*', 'model/cnn/data/*']
},
entry_points={
'console_scripts': [
'genreml = genreml.model.__main__:main'
]
}
)
| [
"setuptools.find_packages",
"pathlib.Path"
] | [((105, 127), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (117, 127), False, 'import pathlib\n'), ((872, 904), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "('test',)"}), "(exclude=('test',))\n", (885, 904), False, 'from setuptools import setup, find_packages\n')] |
# Copyright (c) 2015-2019 The Switch Authors. All rights reserved.
# Licensed under the Apache License, Version 2.0, which is in the LICENSE file.
"""
Defines generation projects build-outs.
INPUT FILE FORMAT
Import data describing project builds. The following files are
expected in the input directory.
generation_projects_info.csv has mandatory and optional columns. The
operations.gen_dispatch module will also look for additional columns in
this file. You may drop optional columns entirely or mark blank
values with a dot '.' for select rows for which the column does not
apply. Mandatory columns are:
GENERATION_PROJECT, gen_tech, gen_energy_source, gen_load_zone,
gen_max_age, gen_is_variable, gen_is_baseload,
gen_full_load_heat_rate, gen_variable_om, gen_connect_cost_per_mw
Optional columns are:
gen_dbid, gen_scheduled_outage_rate, gen_forced_outage_rate,
gen_capacity_limit_mw, gen_unit_size, gen_ccs_energy_load,
gen_ccs_capture_efficiency, gen_min_build_capacity, gen_is_cogen,
gen_is_distributed
The following file lists existing builds of projects, and is
optional for simulations where there is no existing capacity:
gen_build_predetermined.csv
GENERATION_PROJECT, build_year, gen_predetermined_cap
The following file is mandatory, because it sets cost parameters for
both existing and new project buildouts:
gen_build_costs.csv
GENERATION_PROJECT, build_year, gen_overnight_cost, gen_fixed_om
"""
import os
from pyomo.environ import *
from switch_model.financials import capital_recovery_factor as crf
from switch_model.reporting import write_table
from switch_model.tools.graph import graph
from switch_model.utilities.scaling import get_assign_default_value_rule
dependencies = 'switch_model.timescales', 'switch_model.balancing.load_zones',\
'switch_model.financials', 'switch_model.energy_sources.properties.properties'
def define_components(mod):
"""
Adds components to a Pyomo abstract model object to describe
generation and storage projects. Unless otherwise stated, all power
capacity is specified in units of MW and all sets and parameters
are mandatory.
GENERATION_PROJECTS is the set of generation and storage projects that
have been built or could potentially be built. A project is a combination
of generation technology, load zone and location. A particular build-out
of a project should also include the year in which construction was
complete and additional capacity came online. Members of this set are
abbreviated as gen in parameter names and g in indexes. Use of p instead
of g is discouraged because p is reserved for period.
gen_dbid[g] is an external database id for each generation project. This is
an optional parameter than defaults to the project index.
gen_tech[g] describes what kind of technology a generation project is
using.
gen_load_zone[g] is the load zone this generation project is built in.
VARIABLE_GENS is a subset of GENERATION_PROJECTS that only includes
variable generators such as wind or solar that have exogenous
constraints on their energy production.
BASELOAD_GENS is a subset of GENERATION_PROJECTS that only includes
baseload generators such as coal or geothermal.
GENS_IN_ZONE[z in LOAD_ZONES] is an indexed set that lists all
generation projects within each load zone.
CAPACITY_LIMITED_GENS is the subset of GENERATION_PROJECTS that are
capacity limited. Most of these will be generator types that are resource
limited like wind, solar or geothermal, but this can be specified for any
generation project. Some existing or proposed generation projects may have
upper bounds on increasing capacity or replacing capacity as it is retired
based on permits or local air quality regulations.
gen_capacity_limit_mw[g] is defined for generation technologies that are
resource limited and do not compete for land area. This describes the
maximum possible capacity of a generation project in units of megawatts.
-- CONSTRUCTION --
GEN_BLD_YRS is a two-dimensional set of generation projects and the
years in which construction or expansion occured or can occur. You
can think of a project as a physical site that can be built out over
time. BuildYear is the year in which construction is completed and
new capacity comes online, not the year when constrution begins.
BuildYear will be in the past for existing projects and will be the
first year of an investment period for new projects. Investment
decisions are made for each project/invest period combination. This
set is derived from other parameters for all new construction. This
set also includes entries for existing projects that have already
been built and planned projects whose capacity buildouts have already been
decided; information for legacy projects come from other files
and their build years will usually not correspond to the set of
investment periods. There are two recommended options for
abbreviating this set for denoting indexes: typically this should be
written out as (g, build_year) for clarity, but when brevity is
more important (g, b) is acceptable.
NEW_GEN_BLD_YRS is a subset of GEN_BLD_YRS that only
includes projects that have not yet been constructed. This is
derived by joining the set of GENERATION_PROJECTS with the set of
NEW_GENERATION_BUILDYEARS using generation technology.
PREDETERMINED_GEN_BLD_YRS is a subset of GEN_BLD_YRS that
only includes existing or planned projects that are not subject to
optimization.
gen_predetermined_cap[(g, build_year) in PREDETERMINED_GEN_BLD_YRS] is
a parameter that describes how much capacity was built in the past
for existing projects, or is planned to be built for future projects.
BuildGen[g, build_year] is a decision variable that describes
how much capacity of a project to install in a given period. This also
stores the amount of capacity that was installed in existing projects
that are still online.
GenCapacity[g, period] is an expression that returns the total
capacity online in a given period. This is the sum of installed capacity
minus all retirements.
Max_Build_Potential[g] is a constraint defined for each project
that enforces maximum capacity limits for resource-limited projects.
GenCapacity <= gen_capacity_limit_mw
NEW_GEN_WITH_MIN_BUILD_YEARS is the subset of NEW_GEN_BLD_YRS for
which minimum capacity build-out constraints will be enforced.
BuildMinGenCap[g, build_year] is a binary variable that indicates
whether a project will build capacity in a period or not. If the model is
committing to building capacity, then the minimum must be enforced.
Enforce_Min_Build_Lower[g, build_year] and
Enforce_Min_Build_Upper[g, build_year] are a pair of constraints that
force project build-outs to meet the minimum build requirements for
generation technologies that have those requirements. They force BuildGen
to be 0 when BuildMinGenCap is 0, and to be greater than
g_min_build_capacity when BuildMinGenCap is 1. In the latter case,
the upper constraint should be non-binding; the upper limit is set to 10
times the peak non-conincident demand of the entire system.
--- OPERATIONS ---
PERIODS_FOR_GEN_BLD_YR[g, build_year] is an indexed
set that describes which periods a given project build will be
operational.
BLD_YRS_FOR_GEN_PERIOD[g, period] is a complementary
indexed set that identify which build years will still be online
for the given project in the given period. For some project-period
combinations, this will be an empty set.
GEN_PERIODS describes periods in which generation projects
could be operational. Unlike the related sets above, it is not
indexed. Instead it is specified as a set of (g, period)
combinations useful for indexing other model components.
--- COSTS ---
gen_connect_cost_per_mw[g] is the cost of grid upgrades to support a
new project, in dollars per peak MW. These costs include new
transmission lines to a substation, substation upgrades and any
other grid upgrades that are needed to deliver power from the
interconnect point to the load center or from the load center to the
broader transmission network.
The following cost components are defined for each project and build
year. These parameters will always be available, but will typically
be populated by the generic costs specified in generator costs
inputs file and the load zone cost adjustment multipliers from
load_zones inputs file.
gen_overnight_cost[g, build_year] is the overnight capital cost per
MW of capacity for building a project in the given period. By
"installed in the given period", I mean that it comes online at the
beginning of the given period and construction starts before that.
gen_fixed_om[g, build_year] is the annual fixed Operations and
Maintenance costs (O&M) per MW of capacity for given project that
was installed in the given period.
-- Derived cost parameters --
gen_capital_cost_annual[g, build_year] is the annualized loan
payments for a project's capital and connection costs in units of
$/MW per year. This is specified in non-discounted real dollars in a
future period, not real dollars in net present value.
Proj_Fixed_Costs_Annual[g, period] is the total annual fixed
costs (capital as well as fixed operations & maintenance) incurred
by a project in a period. This reflects all of the builds are
operational in the given period. This is an expression that reflect
decision variables.
ProjFixedCosts[period] is the sum of
Proj_Fixed_Costs_Annual[g, period] for all projects that could be
online in the target period. This aggregation is performed for the
benefit of the objective function.
TODO:
- Allow early capacity retirements with savings on fixed O&M
"""
# This set is defined by generation_projects_info.csv
mod.GENERATION_PROJECTS = Set(dimen=1, input_file="generation_projects_info.csv")
mod.gen_dbid = Param(
mod.GENERATION_PROJECTS,
input_file="generation_projects_info.csv",
default=lambda m, g: g,
within=Any)
mod.gen_tech = Param(mod.GENERATION_PROJECTS,
input_file="generation_projects_info.csv",
within=Any)
mod.GENERATION_TECHNOLOGIES = Set(ordered=False, initialize=lambda m:
{m.gen_tech[g] for g in m.GENERATION_PROJECTS}
)
mod.gen_energy_source = Param(mod.GENERATION_PROJECTS, within=Any,
input_file="generation_projects_info.csv",
validate=lambda m, val, g: val in m.ENERGY_SOURCES or val == "multiple")
mod.gen_load_zone = Param(mod.GENERATION_PROJECTS, input_file="generation_projects_info.csv",
within=mod.LOAD_ZONES)
mod.gen_max_age = Param(mod.GENERATION_PROJECTS, input_file="generation_projects_info.csv",
within=PositiveIntegers)
mod.gen_is_variable = Param(mod.GENERATION_PROJECTS, input_file="generation_projects_info.csv",
within=Boolean)
mod.gen_is_baseload = Param(mod.GENERATION_PROJECTS, input_file="generation_projects_info.csv",
within=Boolean, default=False)
mod.gen_is_cogen = Param(mod.GENERATION_PROJECTS, within=Boolean, default=False,
input_file="generation_projects_info.csv")
mod.gen_is_distributed = Param(mod.GENERATION_PROJECTS, within=Boolean, default=False,
input_file="generation_projects_info.csv")
mod.gen_scheduled_outage_rate = Param(mod.GENERATION_PROJECTS, input_file="generation_projects_info.csv",
within=PercentFraction, default=0)
mod.gen_forced_outage_rate = Param(mod.GENERATION_PROJECTS, input_file="generation_projects_info.csv",
within=PercentFraction, default=0)
mod.min_data_check('GENERATION_PROJECTS', 'gen_tech', 'gen_energy_source',
'gen_load_zone', 'gen_max_age', 'gen_is_variable')
"""Construct GENS_* indexed sets efficiently with a
'construction dictionary' pattern: on the first call, make a single
traversal through all generation projects to generate a complete index,
use that for subsequent lookups, and clean up at the last call."""
def GENS_IN_ZONE_init(m, z):
if not hasattr(m, 'GENS_IN_ZONE_dict'):
m.GENS_IN_ZONE_dict = {_z: [] for _z in m.LOAD_ZONES}
for g in m.GENERATION_PROJECTS:
m.GENS_IN_ZONE_dict[m.gen_load_zone[g]].append(g)
result = m.GENS_IN_ZONE_dict.pop(z)
if not m.GENS_IN_ZONE_dict:
del m.GENS_IN_ZONE_dict
return result
mod.GENS_IN_ZONE = Set(
mod.LOAD_ZONES,
initialize=GENS_IN_ZONE_init
)
mod.VARIABLE_GENS = Set(
initialize=mod.GENERATION_PROJECTS,
filter=lambda m, g: m.gen_is_variable[g])
mod.VARIABLE_GENS_IN_ZONE = Set(
mod.LOAD_ZONES,
initialize=lambda m, z: [g for g in m.GENS_IN_ZONE[z] if m.gen_is_variable[g]])
mod.BASELOAD_GENS = Set(
initialize=mod.GENERATION_PROJECTS,
filter=lambda m, g: m.gen_is_baseload[g])
def GENS_BY_TECHNOLOGY_init(m, t):
if not hasattr(m, 'GENS_BY_TECH_dict'):
m.GENS_BY_TECH_dict = {_t: [] for _t in m.GENERATION_TECHNOLOGIES}
for g in m.GENERATION_PROJECTS:
m.GENS_BY_TECH_dict[m.gen_tech[g]].append(g)
result = m.GENS_BY_TECH_dict.pop(t)
if not m.GENS_BY_TECH_dict:
del m.GENS_BY_TECH_dict
return result
mod.GENS_BY_TECHNOLOGY = Set(
mod.GENERATION_TECHNOLOGIES,
initialize=GENS_BY_TECHNOLOGY_init
)
mod.CAPACITY_LIMITED_GENS = Set(within=mod.GENERATION_PROJECTS)
mod.gen_capacity_limit_mw = Param(
mod.CAPACITY_LIMITED_GENS, input_file="generation_projects_info.csv",
input_optional=True, within=NonNegativeReals)
mod.DISCRETELY_SIZED_GENS = Set(within=mod.GENERATION_PROJECTS)
mod.gen_unit_size = Param(
mod.DISCRETELY_SIZED_GENS, input_file="generation_projects_info.csv",
input_optional=True, within=PositiveReals)
mod.CCS_EQUIPPED_GENS = Set(within=mod.GENERATION_PROJECTS)
mod.gen_ccs_capture_efficiency = Param(
mod.CCS_EQUIPPED_GENS, input_file="generation_projects_info.csv",
input_optional=True, within=PercentFraction)
mod.gen_ccs_energy_load = Param(
mod.CCS_EQUIPPED_GENS, input_file="generation_projects_info.csv",
input_optional=True, within=PercentFraction)
mod.gen_uses_fuel = Param(
mod.GENERATION_PROJECTS,
initialize=lambda m, g: (
m.gen_energy_source[g] in m.FUELS
or m.gen_energy_source[g] == "multiple"))
mod.NON_FUEL_BASED_GENS = Set(
initialize=mod.GENERATION_PROJECTS,
filter=lambda m, g: not m.gen_uses_fuel[g])
mod.FUEL_BASED_GENS = Set(
initialize=mod.GENERATION_PROJECTS,
filter=lambda m, g: m.gen_uses_fuel[g])
mod.gen_full_load_heat_rate = Param(
mod.FUEL_BASED_GENS, input_file="generation_projects_info.csv",
within=NonNegativeReals)
mod.MULTIFUEL_GENS = Set(
initialize=mod.GENERATION_PROJECTS,
filter=lambda m, g: m.gen_energy_source[g] == "multiple")
mod.FUELS_FOR_MULTIFUEL_GEN = Set(mod.MULTIFUEL_GENS, within=mod.FUELS)
mod.FUELS_FOR_GEN = Set(mod.FUEL_BASED_GENS,
initialize=lambda m, g: (
m.FUELS_FOR_MULTIFUEL_GEN[g]
if g in m.MULTIFUEL_GENS
else [m.gen_energy_source[g]]))
def GENS_BY_ENERGY_SOURCE_init(m, e):
if not hasattr(m, 'GENS_BY_ENERGY_dict'):
m.GENS_BY_ENERGY_dict = {_e: [] for _e in m.ENERGY_SOURCES}
for g in m.GENERATION_PROJECTS:
if g in m.FUEL_BASED_GENS:
for f in m.FUELS_FOR_GEN[g]:
m.GENS_BY_ENERGY_dict[f].append(g)
else:
m.GENS_BY_ENERGY_dict[m.gen_energy_source[g]].append(g)
result = m.GENS_BY_ENERGY_dict.pop(e)
if not m.GENS_BY_ENERGY_dict:
del m.GENS_BY_ENERGY_dict
return result
mod.GENS_BY_ENERGY_SOURCE = Set(
mod.ENERGY_SOURCES,
initialize=GENS_BY_ENERGY_SOURCE_init
)
mod.GENS_BY_NON_FUEL_ENERGY_SOURCE = Set(
mod.NON_FUEL_ENERGY_SOURCES,
initialize=lambda m, s: m.GENS_BY_ENERGY_SOURCE[s]
)
mod.GENS_BY_FUEL = Set(
mod.FUELS,
initialize=lambda m, f: m.GENS_BY_ENERGY_SOURCE[f]
)
# This set is defined by gen_build_predetermined.csv
mod.PREDETERMINED_GEN_BLD_YRS = Set(
input_file="gen_build_predetermined.csv",
input_optional=True,
dimen=2)
mod.PREDETERMINED_BLD_YRS = Set(
dimen=1,
ordered=False,
initialize=lambda m: set(bld_yr for (g, bld_yr) in m.PREDETERMINED_GEN_BLD_YRS),
doc="Set of all the years where pre-determined builds occurs."
)
# This set is defined by gen_build_costs.csv
mod.GEN_BLD_YRS = Set(
dimen=2,
input_file="gen_build_costs.csv",
validate=lambda m, g, bld_yr: (
(g, bld_yr) in m.PREDETERMINED_GEN_BLD_YRS or
(g, bld_yr) in m.GENERATION_PROJECTS * m.PERIODS))
mod.NEW_GEN_BLD_YRS = Set(
dimen=2,
initialize=lambda m: m.GEN_BLD_YRS - m.PREDETERMINED_GEN_BLD_YRS)
mod.gen_predetermined_cap = Param(
mod.PREDETERMINED_GEN_BLD_YRS,
input_file="gen_build_predetermined.csv",
within=NonNegativeReals)
mod.min_data_check('gen_predetermined_cap')
def gen_build_can_operate_in_period(m, g, build_year, period):
# If a period has the same name as a predetermined build year then we have a problem.
# For example, consider what happens if we have both a period named 2020
# and a predetermined build in 2020. In this case, "build_year in m.PERIODS"
# will be True even if the project is a 2020 predetermined build.
# This will result in the "online" variable being the start of the period rather
# than the prebuild year which can cause issues such as the project retiring too soon.
# To prevent this we've added the no_predetermined_bld_yr_vs_period_conflict BuildCheck below.
if build_year in m.PERIODS:
online = m.period_start[build_year]
else:
online = build_year
retirement = online + m.gen_max_age[g]
# Previously the code read return online <= m.period_start[period] < retirement
# However using the midpoint of the period as the "cutoff" seems more correct so
# we've made the switch.
return online <= m.period_start[period] + 0.5 * m.period_length_years[period] < retirement
# This verifies that a predetermined build year doesn't conflict with a period since if that's the case
# gen_build_can_operate_in_period will mistaken the prebuild for an investment build
# (see note in gen_build_can_operate_in_period)
mod.no_predetermined_bld_yr_vs_period_conflict = BuildCheck(
mod.PREDETERMINED_BLD_YRS, mod.PERIODS,
rule=lambda m, bld_yr, p: bld_yr != p
)
# The set of periods when a project built in a certain year will be online
mod.PERIODS_FOR_GEN_BLD_YR = Set(
mod.GEN_BLD_YRS,
within=mod.PERIODS,
ordered=True,
initialize=lambda m, g, bld_yr: [
period for period in m.PERIODS
if gen_build_can_operate_in_period(m, g, bld_yr, period)])
mod.BLD_YRS_FOR_GEN = Set(
mod.GENERATION_PROJECTS,
ordered=False,
initialize=lambda m, g: set(
bld_yr for (gen, bld_yr) in m.GEN_BLD_YRS if gen == g
)
)
# The set of build years that could be online in the given period
# for the given project.
mod.BLD_YRS_FOR_GEN_PERIOD = Set(
mod.GENERATION_PROJECTS, mod.PERIODS,
ordered=False,
initialize=lambda m, g, period: set(
bld_yr for bld_yr in m.BLD_YRS_FOR_GEN[g]
if gen_build_can_operate_in_period(m, g, bld_yr, period)))
# The set of periods when a generator is available to run
mod.PERIODS_FOR_GEN = Set(
mod.GENERATION_PROJECTS,
initialize=lambda m, g: [p for p in m.PERIODS if len(m.BLD_YRS_FOR_GEN_PERIOD[g, p]) > 0]
)
def bounds_BuildGen(model, g, bld_yr):
if((g, bld_yr) in model.PREDETERMINED_GEN_BLD_YRS):
return (model.gen_predetermined_cap[g, bld_yr],
model.gen_predetermined_cap[g, bld_yr])
elif(g in model.CAPACITY_LIMITED_GENS):
# This does not replace Max_Build_Potential because
# Max_Build_Potential applies across all build years.
return (0, model.gen_capacity_limit_mw[g])
else:
return (0, None)
mod.BuildGen = Var(
mod.GEN_BLD_YRS,
within=NonNegativeReals,
bounds=bounds_BuildGen)
# Some projects are retired before the first study period, so they
# don't appear in the objective function or any constraints.
# In this case, pyomo may leave the variable value undefined even
# after a solve, instead of assigning a value within the allowed
# range. This causes errors in the Progressive Hedging code, which
# expects every variable to have a value after the solve. So as a
# starting point we assign an appropriate value to all the existing
# projects here.
mod.BuildGen_assign_default_value = BuildAction(
mod.PREDETERMINED_GEN_BLD_YRS,
rule=get_assign_default_value_rule("BuildGen", "gen_predetermined_cap"))
# note: in pull request 78, commit e7f870d..., GEN_PERIODS
# was mistakenly redefined as GENERATION_PROJECTS * PERIODS.
# That didn't directly affect the objective function in the tests
# because most code uses GEN_TPS, which was defined correctly.
# But it did have some subtle effects on the main Hawaii model.
# It would be good to have a test that this set is correct,
# e.g., assertions that in the 3zone_toy model,
# ('C-Coal_ST', 2020) in m.GEN_PERIODS and ('C-Coal_ST', 2030) not in m.GEN_PERIODS
# and 'C-Coal_ST' in m.GENS_IN_PERIOD[2020] and 'C-Coal_ST' not in m.GENS_IN_PERIOD[2030]
mod.GEN_PERIODS = Set(
dimen=2,
initialize=lambda m:
[(g, p) for g in m.GENERATION_PROJECTS for p in m.PERIODS_FOR_GEN[g]])
mod.GenCapacity = Expression(
mod.GENERATION_PROJECTS, mod.PERIODS,
rule=lambda m, g, period: sum(
m.BuildGen[g, bld_yr]
for bld_yr in m.BLD_YRS_FOR_GEN_PERIOD[g, period]))
# We use a scaling factor to improve the numerical properties
# of the model. The scaling factor was determined using trial
# and error and this tool https://github.com/staadecker/lp-analyzer.
# Learn more by reading the documentation on Numerical Issues.
max_build_potential_scaling_factor = 1e-1
mod.Max_Build_Potential = Constraint(
mod.CAPACITY_LIMITED_GENS, mod.PERIODS,
rule=lambda m, g, p: (
m.gen_capacity_limit_mw[g] * max_build_potential_scaling_factor >= m.GenCapacity[
g, p] * max_build_potential_scaling_factor))
# The following components enforce minimum capacity build-outs.
# Note that this adds binary variables to the model.
mod.gen_min_build_capacity = Param(mod.GENERATION_PROJECTS, input_file="generation_projects_info.csv",
within=NonNegativeReals, default=0)
mod.NEW_GEN_WITH_MIN_BUILD_YEARS = Set(
dimen=2,
initialize=mod.NEW_GEN_BLD_YRS,
filter=lambda m, g, p: (
m.gen_min_build_capacity[g] > 0))
mod.BuildMinGenCap = Var(
mod.NEW_GEN_WITH_MIN_BUILD_YEARS,
within=Binary)
mod.Enforce_Min_Build_Lower = Constraint(
mod.NEW_GEN_WITH_MIN_BUILD_YEARS,
rule=lambda m, g, p: (
m.BuildMinGenCap[g, p] * m.gen_min_build_capacity[g]
<= m.BuildGen[g, p]))
# Define a constant for enforcing binary constraints on project capacity
# The value of 100 GW should be larger than any expected build size. For
# perspective, the world's largest electric power plant (Three Gorges Dam)
# is 22.5 GW. I tried using 1 TW, but CBC had numerical stability problems
# with that value and chose a suboptimal solution for the
# discrete_and_min_build example which is installing capacity of 3-5 MW.
mod._gen_max_cap_for_binary_constraints = 10 ** 5
mod.Enforce_Min_Build_Upper = Constraint(
mod.NEW_GEN_WITH_MIN_BUILD_YEARS,
rule=lambda m, g, p: (
m.BuildGen[g, p] <= m.BuildMinGenCap[g, p] *
mod._gen_max_cap_for_binary_constraints))
# Costs
mod.gen_variable_om = Param(mod.GENERATION_PROJECTS, input_file="generation_projects_info.csv",
within=NonNegativeReals)
mod.gen_connect_cost_per_mw = Param(mod.GENERATION_PROJECTS, within=NonNegativeReals,
input_file="generation_projects_info.csv",
)
mod.min_data_check('gen_variable_om', 'gen_connect_cost_per_mw')
mod.gen_overnight_cost = Param(
mod.GEN_BLD_YRS,
input_file="gen_build_costs.csv",
within=NonNegativeReals)
mod.gen_fixed_om = Param(
mod.GEN_BLD_YRS,
input_file="gen_build_costs.csv",
within=NonNegativeReals)
mod.min_data_check('gen_overnight_cost', 'gen_fixed_om')
# Derived annual costs
mod.gen_capital_cost_annual = Param(
mod.GEN_BLD_YRS,
initialize=lambda m, g, bld_yr: (
(m.gen_overnight_cost[g, bld_yr] +
m.gen_connect_cost_per_mw[g]) *
crf(m.interest_rate, m.gen_max_age[g])))
mod.GenCapitalCosts = Expression(
mod.GENERATION_PROJECTS, mod.PERIODS,
rule=lambda m, g, p: sum(
m.BuildGen[g, bld_yr] * m.gen_capital_cost_annual[g, bld_yr]
for bld_yr in m.BLD_YRS_FOR_GEN_PERIOD[g, p]))
mod.GenFixedOMCosts = Expression(
mod.GENERATION_PROJECTS, mod.PERIODS,
rule=lambda m, g, p: sum(
m.BuildGen[g, bld_yr] * m.gen_fixed_om[g, bld_yr]
for bld_yr in m.BLD_YRS_FOR_GEN_PERIOD[g, p]))
# Summarize costs for the objective function. Units should be total
# annual future costs in $base_year real dollars. The objective
# function will convert these to base_year Net Present Value in
# $base_year real dollars.
mod.TotalGenFixedCosts = Expression(
mod.PERIODS,
rule=lambda m, p: sum(
m.GenCapitalCosts[g, p] + m.GenFixedOMCosts[g, p]
for g in m.GENERATION_PROJECTS))
mod.Cost_Components_Per_Period.append('TotalGenFixedCosts')
def load_inputs(mod, switch_data, inputs_dir):
# Construct sets of capacity-limited, ccs-capable and unit-size-specified
# projects. These sets include projects for which these parameters have
# a value
if 'gen_capacity_limit_mw' in switch_data.data():
switch_data.data()['CAPACITY_LIMITED_GENS'] = {
None: list(switch_data.data(name='gen_capacity_limit_mw').keys())}
if 'gen_unit_size' in switch_data.data():
switch_data.data()['DISCRETELY_SIZED_GENS'] = {
None: list(switch_data.data(name='gen_unit_size').keys())}
if 'gen_ccs_capture_efficiency' in switch_data.data():
switch_data.data()['CCS_EQUIPPED_GENS'] = {
None: list(switch_data.data(name='gen_ccs_capture_efficiency').keys())}
# read FUELS_FOR_MULTIFUEL_GEN from gen_multiple_fuels.dat if available
if os.path.isfile(os.path.join(inputs_dir, 'gen_multiple_fuels.dat')):
if 'switch_model.generators.core.commit.fuel_use' in mod.module_list:
raise NotImplementedError(
"Multi-fuel generation is being used with generators.core.commit.fuel_use despite not being fully "
"supported.\n"
"Specifically, DispatchGenByFuel has not been constrained to match the true fuel use (GenFuelUseRate)."
"Therefore, DispatchGenByFuel may result in incorrect values. DispatchGenByFuel is used when calculating"
"non-CO2 emissions resulting in incorrect non-CO2 emission values. If there exists carbon_policies for"
"non-CO2 emissions, the model may return an incorrect solution.")
# TODO handle multi fuel input file
raise NotImplementedError(
"This code has not been updated to the latest version. We no longer handle .dat files.")
def post_solve(m, outdir):
write_table(
m,
m.GEN_PERIODS,
output_file=os.path.join(outdir, "gen_cap.csv"),
headings=(
"GENERATION_PROJECT", "PERIOD",
"gen_tech", "gen_load_zone", "gen_energy_source",
"GenCapacity", "GenCapitalCosts", "GenFixedOMCosts"),
# Indexes are provided as a tuple, so put (g,p) in parentheses to
# access the two components of the index individually.
values=lambda m, g, p: (
g, p,
m.gen_tech[g], m.gen_load_zone[g], m.gen_energy_source[g],
m.GenCapacity[g, p], m.GenCapitalCosts[g, p], m.GenFixedOMCosts[g, p]))
@graph(
"generation_capacity_per_period",
title="Online Generation Capacity Per Period"
)
def graph_capacity(tools):
# Load gen_cap.csv
gen_cap = tools.get_dataframe("gen_cap.csv")
# Map energy sources to technology type
gen_cap = tools.transform.gen_type(gen_cap)
# Aggregate by gen_tech_type and PERIOD by summing the generation capacity
capacity_df = gen_cap.pivot_table(index='PERIOD', columns='gen_type', values='GenCapacity', aggfunc=tools.np.sum,
fill_value=0)
capacity_df = capacity_df * 1e-3 # Convert values to GW
# For generation types that make less than 2% in every period, group them under "Other"
# ---------
# sum the generation across the energy_sources for each period, 2% of that is the cutoff for that period
cutoff_value = 0.01
cutoff_per_period = capacity_df.sum(axis=1) * cutoff_value
# Check for each technology if it's below the cutoff for every period
is_below_cutoff = capacity_df.lt(cutoff_per_period, axis=0).all()
# groupby if the technology is below the cutoff
capacity_df = capacity_df.groupby(axis=1, by=lambda c: "Other" if is_below_cutoff[c] else c).sum()
# Sort columns by the last period
capacity_df = capacity_df.sort_values(by=capacity_df.index[-1], axis=1)
# Plot
# Get a new set of axis to create a breakdown of the generation capacity
capacity_df.plot(
kind='bar',
ax=tools.get_axes(),
stacked=True,
ylabel="Capacity Online (GW)",
xlabel="Period",
color=tools.get_colors(len(capacity_df.index)),
)
tools.bar_label()
@graph(
"buildout_gen_per_period",
title="Built Capacity per Period",
supports_multi_scenario=True
)
def graph_buildout(tools):
build_gen = tools.get_dataframe("BuildGen.csv", dtype={"GEN_BLD_YRS_1": str})
build_gen = build_gen.rename(
{"GEN_BLD_YRS_1": "GENERATION_PROJECT", "GEN_BLD_YRS_2": "build_year", "BuildGen": "Amount"},
axis=1
)
build_gen = tools.transform.build_year(build_gen)
gen = tools.get_dataframe("generation_projects_info", from_inputs=True)
gen = tools.transform.gen_type(gen)
gen = gen[["GENERATION_PROJECT", "gen_type", "scenario_name"]]
build_gen = build_gen.merge(
gen,
on=["GENERATION_PROJECT", "scenario_name"],
how="left",
validate="many_to_one"
)
groupby = "build_year" if tools.num_scenarios == 1 else ["build_year", "scenario_name"]
build_gen = build_gen.pivot_table(index=groupby, columns="gen_type", values="Amount", aggfunc=tools.np.sum)
build_gen = build_gen * 1e-3 # Convert values to GW
build_gen = build_gen.sort_index(ascending=False, key=tools.sort_build_years)
# For generation types that make less than 2% in every period, group them under "Other"
# ---------
# sum the generation across the energy_sources for each period, 2% of that is the cutoff for that period
cutoff_value = 0.01
cutoff_per_period = build_gen.sum(axis=1) * cutoff_value
# Check for each technology if it's below the cutoff for every period
is_below_cutoff = build_gen.lt(cutoff_per_period, axis=0).all()
# groupby if the technology is below the cutoff
build_gen = build_gen.groupby(axis=1, by=lambda c: "Other" if is_below_cutoff[c] else c).sum()
# Sort columns by the last period
build_gen = build_gen.sort_values(by=build_gen.index[-1], axis=1)
# Plot
# Get a new set of axis to create a breakdown of the generation capacity
build_gen.plot(
kind='bar',
ax=tools.get_axes(),
stacked=True,
ylabel="Capacity Online (GW)",
xlabel="Period",
color=tools.get_colors(len(build_gen.index)),
)
@graph(
"gen_buildout_per_tech_period",
title="Buildout relative to max allowed for period",
note="\nNote 1: This graph excludes predetermined buildout and projects that have no capacity limit."
"\nTechnologies that contain projects with no capacity limit are marked by a * and their graphs may"
"be misleading."
)
def graph_buildout_per_tech(tools):
# Load gen_cap.csv
gen_cap = tools.get_dataframe("gen_cap.csv")
# Map energy sources to technology type
gen_cap = tools.transform.gen_type(gen_cap)
# Load generation_projects_info.csv
gen_info = tools.get_dataframe('generation_projects_info.csv', from_inputs=True)
# Filter out projects with unlimited capacity since we can't consider those (coerce converts '.' to NaN)
gen_info['gen_capacity_limit_mw'] = tools.pd.to_numeric(gen_info["gen_capacity_limit_mw"], errors='coerce')
# Set the type to be the same to ensure merge works
gen_cap["GENERATION_PROJECT"] = gen_cap["GENERATION_PROJECT"].astype(object)
gen_info["GENERATION_PROJECT"] = gen_info["GENERATION_PROJECT"].astype(object)
# Add the capacity_limit to the gen_cap dataframe which has the total capacity at each period
df = gen_cap.merge(
gen_info[["GENERATION_PROJECT", "gen_capacity_limit_mw"]],
on='GENERATION_PROJECT',
validate='many_to_one'
)
# Get the predetermined generation
predetermined = tools.get_dataframe("gen_build_predetermined.csv", from_inputs=True)
# Filter out projects that are predetermined
df = df[~df["GENERATION_PROJECT"].isin(predetermined["GENERATION_PROJECT"])]
# Make PERIOD a category to ensure x-axis labels don't fill in years between period
# TODO we should order this by period here to ensure they're in increasing order
df["PERIOD"] = df["PERIOD"].astype("category")
# Get gen_types that have projects with unlimited buildout
unlimited_gen_types = df[df['gen_capacity_limit_mw'].isna()]['gen_type'].drop_duplicates()
# Filter out unlimited generation
df = df[~df['gen_capacity_limit_mw'].isna()]
if df.size == 0: # in this case there are no projects that have a limit on build capacity
return
# Sum the GenCapacity and gen_capacity_limit_mw for all projects in the same period and type
df = df.groupby(['PERIOD', 'gen_type']).sum()
# Create a dataframe that's the division of the Capacity and the capacity limit
df = (df['GenCapacity'] / df['gen_capacity_limit_mw']).unstack()
# Filter out generation types that don't make up a large percent of the energy mix to decultter graph
# df = df.loc[:, ~is_below_cutoff]
# Set the name of the legend.
df = df.rename_axis("Type", axis='columns')
# Add a * to tech
df = df.rename(lambda c: f"{c}*" if c in unlimited_gen_types.values else c, axis='columns')
# Plot
colors = tools.get_colors()
if colors is not None:
# Add the same colors but with a * to support our legend.
colors.update({f"{k}*": v for k, v in colors.items()})
ax = tools.get_axes()
df.plot(ax=ax, kind='line', color=colors, xlabel='Period', marker="x")
# Set the y-axis to use percent
ax.yaxis.set_major_formatter(tools.plt.ticker.PercentFormatter(1.0))
# Horizontal line at 100%
ax.axhline(y=1, linestyle="--", color='b')
@graph(
"buildout_map",
title="Map of online capacity per load zone."
)
def buildout_map(tools):
buildout = tools.get_dataframe("gen_cap.csv").rename({"GenCapacity": "value"}, axis=1)
buildout = tools.transform.gen_type(buildout)
buildout = buildout.groupby(["gen_type", "gen_load_zone"], as_index=False)["value"].sum()
ax = tools.maps.graph_pie_chart(buildout)
transmission = tools.get_dataframe("transmission.csv", convert_dot_to_na=True).fillna(0)
transmission = transmission.rename({"trans_lz1": "from", "trans_lz2": "to", "BuildTx": "value"}, axis=1)
transmission = transmission[["from", "to", "value", "PERIOD"]]
transmission = transmission.groupby(["from", "to", "PERIOD"], as_index=False).sum().drop("PERIOD", axis=1)
# Rename the columns appropriately
transmission.value *= 1e-3
tools.maps.graph_transmission(transmission, cutoff=0.1, ax=ax, legend=True)
| [
"switch_model.financials.capital_recovery_factor",
"os.path.join",
"switch_model.tools.graph.graph",
"switch_model.utilities.scaling.get_assign_default_value_rule"
] | [((29938, 30029), 'switch_model.tools.graph.graph', 'graph', (['"""generation_capacity_per_period"""'], {'title': '"""Online Generation Capacity Per Period"""'}), "('generation_capacity_per_period', title=\n 'Online Generation Capacity Per Period')\n", (29943, 30029), False, 'from switch_model.tools.graph import graph\n'), ((31588, 31689), 'switch_model.tools.graph.graph', 'graph', (['"""buildout_gen_per_period"""'], {'title': '"""Built Capacity per Period"""', 'supports_multi_scenario': '(True)'}), "('buildout_gen_per_period', title='Built Capacity per Period',\n supports_multi_scenario=True)\n", (31593, 31689), False, 'from switch_model.tools.graph import graph\n'), ((33713, 34035), 'switch_model.tools.graph.graph', 'graph', (['"""gen_buildout_per_tech_period"""'], {'title': '"""Buildout relative to max allowed for period"""', 'note': '"""\nNote 1: This graph excludes predetermined buildout and projects that have no capacity limit.\nTechnologies that contain projects with no capacity limit are marked by a * and their graphs maybe misleading."""'}), '(\'gen_buildout_per_tech_period\', title=\n \'Buildout relative to max allowed for period\', note=\n """\nNote 1: This graph excludes predetermined buildout and projects that have no capacity limit.\nTechnologies that contain projects with no capacity limit are marked by a * and their graphs maybe misleading."""\n )\n', (33718, 34035), False, 'from switch_model.tools.graph import graph\n'), ((37057, 37125), 'switch_model.tools.graph.graph', 'graph', (['"""buildout_map"""'], {'title': '"""Map of online capacity per load zone."""'}), "('buildout_map', title='Map of online capacity per load zone.')\n", (37062, 37125), False, 'from switch_model.tools.graph import graph\n'), ((28323, 28373), 'os.path.join', 'os.path.join', (['inputs_dir', '"""gen_multiple_fuels.dat"""'], {}), "(inputs_dir, 'gen_multiple_fuels.dat')\n", (28335, 28373), False, 'import os\n'), ((22174, 22240), 'switch_model.utilities.scaling.get_assign_default_value_rule', 'get_assign_default_value_rule', (['"""BuildGen"""', '"""gen_predetermined_cap"""'], {}), "('BuildGen', 'gen_predetermined_cap')\n", (22203, 22240), False, 'from switch_model.utilities.scaling import get_assign_default_value_rule\n'), ((29364, 29399), 'os.path.join', 'os.path.join', (['outdir', '"""gen_cap.csv"""'], {}), "(outdir, 'gen_cap.csv')\n", (29376, 29399), False, 'import os\n'), ((26417, 26455), 'switch_model.financials.capital_recovery_factor', 'crf', (['m.interest_rate', 'm.gen_max_age[g]'], {}), '(m.interest_rate, m.gen_max_age[g])\n', (26420, 26455), True, 'from switch_model.financials import capital_recovery_factor as crf\n')] |
# https://www.codewars.com/kata/directions-reduction/train/python
# My solution
import re
def dirReduc(arr):
card = {"NORTH": "N", "SOUTH": "S", "EAST": "E", "WEST": "W"}
arr = "".join(map(lambda elem: card[elem], arr))
while "NS" in arr or "SN" in arr or "EW" in arr or "WE" in arr:
arr = re.sub("NS|SN|EW|WE", "", arr)
cardr = {v: k for k,v in card.items()}
return list(map(lambda elem: cardr[elem], list(arr)))
# ...
def dirReduc(arr):
ix = 0
while ix < len(arr)-1:
if arr[ix][0] + arr[ix+1][0] in ["NS", "SN", "EW", "WE"]:
arr[ix:ix+2] = []
if ix: ix -= 1
else:
ix += 1
return arr
# ...
opposite = {'NORTH': 'SOUTH', 'EAST': 'WEST', 'SOUTH': 'NORTH', 'WEST': 'EAST'}
def dirReduc(plan):
new_plan = []
for d in plan:
if new_plan and new_plan[-1] == opposite[d]:
new_plan.pop()
else:
new_plan.append(d)
return new_plan
# ...
def dirReduc(arr):
dir = " ".join(arr)
dir2 = dir.replace("NORTH SOUTH",'').replace("SOUTH NORTH",'').replace("EAST WEST",'').replace("WEST EAST",'')
dir3 = dir2.split()
return dirReduc(dir3) if len(dir3) < len(arr) else dir3
# ...
def dirReduc(arr):
opposites = [{'NORTH', 'SOUTH'}, {'EAST', 'WEST'}]
for i in range(len(arr)-1):
if set(arr[i:i+2]) in opposites:
del arr[i:i+2]
return dirReduc(arr)
return arr
# ...
def dirReduc(arr):
s = ''.join([d[0] for d in arr])
while True:
o = s
s = s.replace('NS', '')
s = s.replace('SN', '')
s = s.replace('EW', '')
s = s.replace('WE', '')
if o == s:
break
lookup = {'N': 'NORTH', 'S': 'SOUTH', 'E': 'EAST', 'W': 'WEST'}
return [lookup[c] for c in s] | [
"re.sub"
] | [((319, 349), 're.sub', 're.sub', (['"""NS|SN|EW|WE"""', '""""""', 'arr'], {}), "('NS|SN|EW|WE', '', arr)\n", (325, 349), False, 'import re\n')] |
# Copyright 2020 Red Hat Inc.
#
# 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.
"""General Provider interface."""
import asyncio
import logging
from datetime import datetime
from mrack.errors import ProvisioningError, ValidationError
from mrack.host import STATUS_OTHER, Host
logger = logging.getLogger(__name__)
class Provider:
"""General Provider interface."""
def __init__(self, provisioning_config, job_config):
"""Initialize provider."""
self._name = "dummy"
self.STATUS_MAP = {"OTHER": STATUS_OTHER}
return
@property
def name(self):
"""Get provider name."""
return self._name
async def validate_hosts(self, hosts):
"""Validate that host requirements are well specified."""
raise NotImplementedError()
async def can_provision(self, hosts):
"""Check that provider has enough resources to provison hosts."""
raise NotImplementedError()
async def create_server(self, req):
"""Request and create resource on selected provider."""
raise NotImplementedError()
async def wait_till_provisioned(self, resource):
"""Wait till resource is provisioned."""
raise NotImplementedError()
async def provision_hosts(self, hosts):
"""Provision hosts based on list of host requirements.
Main provider method for provisioning.
First it validates that host requirements are valid and that
provider has enough resources(quota).
Then issues provisioning and waits for it succeed. Raises exception if any of
the servers was not successfully provisioned. If that happens it issues deletion
of all already provisioned resources.
Return list of information about provisioned servers.
"""
logger.info("Validating hosts definitions")
await self.validate_hosts(hosts)
logger.info("Host definitions valid")
logger.info("Checking available resources")
can = await self.can_provision(hosts)
if not can:
raise ValidationError("Not enough resources to provision")
logger.info("Resource availability: OK")
started = datetime.now()
count = len(hosts)
logger.info(f"Issuing provisioning of {count} hosts")
create_servers = []
for req in hosts:
awaitable = self.create_server(req)
create_servers.append(awaitable)
create_resps = await asyncio.gather(*create_servers)
logger.info("Provisioning issued")
logger.info("Waiting for all hosts to be available")
wait_servers = []
for create_resp in create_resps:
awaitable = self.wait_till_provisioned(create_resp)
wait_servers.append(awaitable)
server_results = await asyncio.gather(*wait_servers)
provisioned = datetime.now()
provi_duration = provisioned - started
logger.info("All hosts reached provisioning final state (ACTIVE or ERROR)")
logger.info(f"Provisioning duration: {provi_duration}")
errors = self.parse_errors(server_results)
if errors:
logger.info("Some host did not start properly")
for err in errors:
self.print_basic_info(err)
logger.info("Given the error, will delete all hosts")
await self.delete_hosts(server_results)
raise ProvisioningError(errors)
hosts = [self.to_host(srv) for srv in server_results]
for host in hosts:
logger.info(host)
return hosts
def parse_errors(self, server_results):
"""Parse provisioning errors from provider result."""
raise NotImplementedError()
async def delete_host(self, host):
"""Delete provisioned host."""
raise NotImplementedError()
async def delete_hosts(self, hosts):
"""Issue deletion of all servers based on previous results from provisioning."""
logger.info("Issuing deletion")
delete_servers = []
for host in hosts:
awaitable = self.delete_host(host)
delete_servers.append(awaitable)
results = await asyncio.gather(*delete_servers)
logger.info("All servers issued to be deleted")
return results
def prov_result_to_host_data(self, prov_result):
"""Transform provisioning result to needed host data."""
raise NotImplementedError()
def to_host(self, provisioning_result, username=None):
"""Transform provisioning result into Host object."""
host_info = self.prov_result_to_host_data(provisioning_result)
host = Host(
self,
host_info.get("id"),
host_info.get("name"),
host_info.get("addresses"),
self.STATUS_MAP.get(host_info.get("status"), STATUS_OTHER),
provisioning_result,
username=username,
error_obj=host_info.get("fault"),
)
return host
| [
"logging.getLogger",
"mrack.errors.ValidationError",
"datetime.datetime.now",
"mrack.errors.ProvisioningError",
"asyncio.gather"
] | [((784, 811), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (801, 811), False, 'import logging\n'), ((2694, 2708), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (2706, 2708), False, 'from datetime import datetime\n'), ((3370, 3384), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (3382, 3384), False, 'from datetime import datetime\n'), ((2573, 2625), 'mrack.errors.ValidationError', 'ValidationError', (['"""Not enough resources to provision"""'], {}), "('Not enough resources to provision')\n", (2588, 2625), False, 'from mrack.errors import ProvisioningError, ValidationError\n'), ((2975, 3006), 'asyncio.gather', 'asyncio.gather', (['*create_servers'], {}), '(*create_servers)\n', (2989, 3006), False, 'import asyncio\n'), ((3318, 3347), 'asyncio.gather', 'asyncio.gather', (['*wait_servers'], {}), '(*wait_servers)\n', (3332, 3347), False, 'import asyncio\n'), ((3922, 3947), 'mrack.errors.ProvisioningError', 'ProvisioningError', (['errors'], {}), '(errors)\n', (3939, 3947), False, 'from mrack.errors import ProvisioningError, ValidationError\n'), ((4690, 4721), 'asyncio.gather', 'asyncio.gather', (['*delete_servers'], {}), '(*delete_servers)\n', (4704, 4721), False, 'import asyncio\n')] |
"""
Capstone Project. Code to run on a LAPTOP (NOT the robot).
Displays the Graphical User Interface (GUI) and communicates with the robot.
Authors: Your professors (for the framework)
and <NAME>.
Winter term, 2018-2019.
"""
import mqtt_remote_method_calls as com
import tkinter
from tkinter import ttk
import shared_gui
import time
import random
def main():
"""
This code, which must run on a LAPTOP:
1. Constructs a GUI for my part of the Capstone Project.
2. Communicates via MQTT with the code that runs on the EV3 robot.
"""
# -------------------------------------------------------------------------
# Construct and connect the MQTT Client:
# -------------------------------------------------------------------------
delegate = laptopDelegate()
client = com.MqttClient(delegate)
client.connect_to_ev3()
time.sleep(1)
# -------------------------------------------------------------------------
# The root TK object for the GUI:
# -------------------------------------------------------------------------
root = tkinter.Tk()
root.title("EV3 Remote")
# -------------------------------------------------------------------------
# The main frame, upon which the other frames are placed.
# -------------------------------------------------------------------------
mainFrame = ttk.Frame(root, padding=10, borderwidth=5, relief='groove')
mainFrame.grid()
# -------------------------------------------------------------------------
# Frames that are particular to my individual contributions to the project.
# -------------------------------------------------------------------------
simonFrame, textBox = getSimonFrame(mainFrame,client)
# -------------------------------------------------------------------------
# Grid the frames.
# -------------------------------------------------------------------------
simonFrame.grid(row=0,column=0)
# -------------------------------------------------------------------------
# The event loop:
# -------------------------------------------------------------------------
delegate.gui = textBox
root.mainloop()
#Creates the frame with all the simon says functionality
def getSimonFrame(window,client):
Frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge")
Frame.grid()
frameLabel = ttk.Label(Frame,text='Simon Says')
simonButton = ttk.Button(Frame,text='Simon Says...')
moveButton = ttk.Button(Frame,text='Move')
danceButton = ttk.Button(Frame,text='Dance!')
stretchButton = ttk.Button(Frame,text='Stretch')
clapButton = ttk.Button(Frame,text='Clap')
colorButton = ttk.Button(Frame,text='Read Color')
findButton = ttk.Button(Frame,text='Find Cube')
beepButton = ttk.Button(Frame,text='Beep')
singButton = ttk.Button(Frame,text='Sing')
blankLabel= ttk.Label(Frame,text='')
blankLabel2 = ttk.Label(Frame,text='')
diffLabel = ttk.Label(Frame,text='Difficulty Bar')
difficultBar = ttk.Progressbar(Frame,maximum=1000)
difficultBar.start(200)
difficultBar.step(1)
textBox = ttk.Entry(Frame)
textBox.insert(0,'Ready to play!')
winBox = ttk.Entry(Frame)
frameLabel.grid(row=0,column=1)
blankLabel.grid(row=1,column=1)
simonButton.grid(row=2,column=1)
blankLabel2.grid(row=3,column=1)
moveButton.grid(row=4,column=0)
danceButton.grid(row=5,column=0)
stretchButton.grid(row=6,column=0)
clapButton.grid(row=7,column=0)
colorButton.grid(row=4,column=2)
findButton.grid(row=5,column=2)
beepButton.grid(row=6,column=2)
singButton.grid(row=7,column=2)
diffLabel.grid(row=11,column=1)
difficultBar.grid(row=12,column=1)
textBox.grid(row=13,column=1)
winBox.grid(row=14,column=1)
simonButton['command'] = lambda: handleSimon(client, difficultBar, textBox, winBox)
moveButton['command'] = lambda: handleMove(client, difficultBar, textBox, winBox)
danceButton['command'] = lambda: handleDance(client, difficultBar, textBox, winBox)
stretchButton['command'] = lambda: handleStretch(client, difficultBar, textBox, winBox)
clapButton['command'] = lambda: handleClap(client, difficultBar, textBox, winBox)
colorButton['command'] = lambda: handleColor(client, difficultBar, textBox, winBox)
findButton['command'] = lambda: handleFind(client, difficultBar, textBox, winBox)
beepButton['command'] = lambda: handleBeep(client, difficultBar, textBox, winBox)
singButton['command'] = lambda: handleSing(client, difficultBar, textBox, winBox)
return Frame, textBox
#Creates a function to handle each button press event and communicate the desired action to the robot's Delegate
def handleSimon(client, difficultBar, textBox, winBox):
textBox.delete(0,100)
textBox.insert(0,'Simon Says...')
def handleMove(client, difficultBar, textBox, winBox):
difficultBar.step(10)
if textBox.get() == 'Simon Says...':
textBox.delete(0, 100)
textBox.insert(0, 'Moving')
client.send_message('Move')
elif doesFail(difficultBar):
textBox.delete(0,100)
textBox.insert(0, 'Whoops!')
client.send_message('Move')
winBox.delete(0, 100)
winBox.insert(0,'You Win!')
difficultBar.stop()
else:
textBox.delete(0, 100)
textBox.insert(0, 'Waiting...')
def handleDance(client, difficultBar, textBox, winBox):
difficultBar.step(10)
if textBox.get() == 'Simon Says...':
textBox.delete(0, 100)
textBox.insert(0, 'Dancing')
client.send_message('Dance')
elif doesFail(difficultBar):
textBox.delete(0, 100)
textBox.insert(0, 'Whoops!')
client.send_message('Dance')
winBox.delete(0, 100)
winBox.insert(0, 'You Win!')
difficultBar.stop()
else:
textBox.delete(0, 100)
textBox.insert(0, 'Waiting...')
def handleStretch(client, difficultBar, textBox, winBox):
difficultBar.step(10)
if textBox.get() == 'Simon Says...':
textBox.delete(0, 100)
textBox.insert(0, 'Stretching')
client.send_message('Stretch')
elif doesFail(difficultBar):
textBox.delete(0, 100)
textBox.insert(0, 'Whoops!')
client.send_message('Stretch')
winBox.delete(0, 100)
winBox.insert(0, 'You Win!')
difficultBar.stop()
else:
textBox.delete(0, 100)
textBox.insert(0, 'Waiting...')
def handleClap(client, difficultBar, textBox, winBox):
difficultBar.step(10)
if textBox.get() == 'Simon Says...':
textBox.delete(0, 100)
textBox.insert(0, 'Clapping')
client.send_message('Clap')
elif doesFail(difficultBar):
textBox.delete(0, 100)
textBox.insert(0, 'Whoops!')
client.send_message('Clap')
winBox.delete(0, 100)
winBox.insert(0, 'You Win!')
difficultBar.stop()
else:
textBox.delete(0, 100)
textBox.insert(0, 'Waiting...')
def handleColor(client, difficultBar, textBox, winBox):
difficultBar.step(10)
if textBox.get() == 'Simon Says...':
textBox.delete(0, 100)
textBox.insert(0, 'Looking for Color')
client.send_message('Color')
elif doesFail(difficultBar):
textBox.delete(0, 100)
textBox.insert(0, 'Whoops!')
client.send_message('Color')
winBox.delete(0, 100)
winBox.insert(0, 'You Win!')
difficultBar.stop()
else:
textBox.delete(0, 100)
textBox.insert(0, 'Waiting...')
def handleFind(client, difficultBar, textBox, winBox):
difficultBar.step(10)
if textBox.get() == 'Simon Says...':
textBox.delete(0, 100)
textBox.insert(0, 'Finding')
client.send_message('Find')
elif doesFail(difficultBar):
textBox.delete(0, 100)
textBox.insert(0, 'Whoops!')
client.send_message('Find')
winBox.delete(0, 100)
winBox.insert(0, 'You Win!')
difficultBar.stop()
else:
textBox.delete(0, 100)
textBox.insert(0, 'Waiting...')
def handleBeep(client, difficultBar, textBox, winBox):
difficultBar.step(10)
if textBox.get() == 'Simon Says...':
textBox.delete(0, 100)
textBox.insert(0, 'Beeping')
client.send_message('Beep')
elif doesFail(difficultBar):
textBox.delete(0, 100)
textBox.insert(0, 'Whoops!')
client.send_message('Beep')
winBox.delete(0, 100)
winBox.insert(0, 'You Win!')
difficultBar.stop()
else:
textBox.delete(0, 100)
textBox.insert(0, 'Waiting...')
def handleSing(client, difficultBar, textBox, winBox):
difficultBar.step(10)
if textBox.get() == 'Simon Says...':
textBox.delete(0, 100)
textBox.insert(0, 'Singing')
client.send_message('Sing')
elif doesFail(difficultBar):
textBox.delete(0, 100)
textBox.insert(0, 'Whoops!')
client.send_message('Sing')
winBox.delete(0, 100)
winBox.insert(0, 'You Win!')
difficultBar.stop()
else:
textBox.delete(0, 100)
textBox.insert(0, 'Waiting...')
def doesFail(difficultBar):
difficultBar.step(5)
num = random.randrange(0,100)
diffCo = difficultBar['value']/1000 + 1
return num*diffCo>95
#Create the delegate to recieve robot data on the laptop. Basically just posts robot data to the GUI text box
class laptopDelegate(object):
def __init__(self):
self.gui = None
def writeText(self,text):
self.gui.delete(0,100)
self.gui.insert(0,text)
# -----------------------------------------------------------------------------
# Calls main to start the ball rolling.
# -----------------------------------------------------------------------------
main()
| [
"tkinter.ttk.Button",
"tkinter.ttk.Entry",
"random.randrange",
"tkinter.ttk.Frame",
"tkinter.ttk.Label",
"time.sleep",
"tkinter.Tk",
"tkinter.ttk.Progressbar",
"mqtt_remote_method_calls.MqttClient"
] | [((822, 846), 'mqtt_remote_method_calls.MqttClient', 'com.MqttClient', (['delegate'], {}), '(delegate)\n', (836, 846), True, 'import mqtt_remote_method_calls as com\n'), ((879, 892), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (889, 892), False, 'import time\n'), ((1104, 1116), 'tkinter.Tk', 'tkinter.Tk', ([], {}), '()\n', (1114, 1116), False, 'import tkinter\n'), ((1386, 1445), 'tkinter.ttk.Frame', 'ttk.Frame', (['root'], {'padding': '(10)', 'borderwidth': '(5)', 'relief': '"""groove"""'}), "(root, padding=10, borderwidth=5, relief='groove')\n", (1395, 1445), False, 'from tkinter import ttk\n'), ((2328, 2388), 'tkinter.ttk.Frame', 'ttk.Frame', (['window'], {'padding': '(10)', 'borderwidth': '(5)', 'relief': '"""ridge"""'}), "(window, padding=10, borderwidth=5, relief='ridge')\n", (2337, 2388), False, 'from tkinter import ttk\n'), ((2424, 2459), 'tkinter.ttk.Label', 'ttk.Label', (['Frame'], {'text': '"""Simon Says"""'}), "(Frame, text='Simon Says')\n", (2433, 2459), False, 'from tkinter import ttk\n'), ((2477, 2516), 'tkinter.ttk.Button', 'ttk.Button', (['Frame'], {'text': '"""Simon Says..."""'}), "(Frame, text='Simon Says...')\n", (2487, 2516), False, 'from tkinter import ttk\n'), ((2533, 2563), 'tkinter.ttk.Button', 'ttk.Button', (['Frame'], {'text': '"""Move"""'}), "(Frame, text='Move')\n", (2543, 2563), False, 'from tkinter import ttk\n'), ((2581, 2613), 'tkinter.ttk.Button', 'ttk.Button', (['Frame'], {'text': '"""Dance!"""'}), "(Frame, text='Dance!')\n", (2591, 2613), False, 'from tkinter import ttk\n'), ((2633, 2666), 'tkinter.ttk.Button', 'ttk.Button', (['Frame'], {'text': '"""Stretch"""'}), "(Frame, text='Stretch')\n", (2643, 2666), False, 'from tkinter import ttk\n'), ((2683, 2713), 'tkinter.ttk.Button', 'ttk.Button', (['Frame'], {'text': '"""Clap"""'}), "(Frame, text='Clap')\n", (2693, 2713), False, 'from tkinter import ttk\n'), ((2731, 2767), 'tkinter.ttk.Button', 'ttk.Button', (['Frame'], {'text': '"""Read Color"""'}), "(Frame, text='Read Color')\n", (2741, 2767), False, 'from tkinter import ttk\n'), ((2784, 2819), 'tkinter.ttk.Button', 'ttk.Button', (['Frame'], {'text': '"""Find Cube"""'}), "(Frame, text='Find Cube')\n", (2794, 2819), False, 'from tkinter import ttk\n'), ((2836, 2866), 'tkinter.ttk.Button', 'ttk.Button', (['Frame'], {'text': '"""Beep"""'}), "(Frame, text='Beep')\n", (2846, 2866), False, 'from tkinter import ttk\n'), ((2883, 2913), 'tkinter.ttk.Button', 'ttk.Button', (['Frame'], {'text': '"""Sing"""'}), "(Frame, text='Sing')\n", (2893, 2913), False, 'from tkinter import ttk\n'), ((2929, 2954), 'tkinter.ttk.Label', 'ttk.Label', (['Frame'], {'text': '""""""'}), "(Frame, text='')\n", (2938, 2954), False, 'from tkinter import ttk\n'), ((2972, 2997), 'tkinter.ttk.Label', 'ttk.Label', (['Frame'], {'text': '""""""'}), "(Frame, text='')\n", (2981, 2997), False, 'from tkinter import ttk\n'), ((3013, 3052), 'tkinter.ttk.Label', 'ttk.Label', (['Frame'], {'text': '"""Difficulty Bar"""'}), "(Frame, text='Difficulty Bar')\n", (3022, 3052), False, 'from tkinter import ttk\n'), ((3071, 3107), 'tkinter.ttk.Progressbar', 'ttk.Progressbar', (['Frame'], {'maximum': '(1000)'}), '(Frame, maximum=1000)\n', (3086, 3107), False, 'from tkinter import ttk\n'), ((3174, 3190), 'tkinter.ttk.Entry', 'ttk.Entry', (['Frame'], {}), '(Frame)\n', (3183, 3190), False, 'from tkinter import ttk\n'), ((3243, 3259), 'tkinter.ttk.Entry', 'ttk.Entry', (['Frame'], {}), '(Frame)\n', (3252, 3259), False, 'from tkinter import ttk\n'), ((9315, 9339), 'random.randrange', 'random.randrange', (['(0)', '(100)'], {}), '(0, 100)\n', (9331, 9339), False, 'import random\n')] |
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters import Command
from aiogram.types import Message, CallbackQuery
from sqlalchemy.exc import NoResultFound
from loader import dp, logger_guru
from utils.database_manage.sql.sql_commands import DB_USERS
from utils.keyboards.admins_tools_kb import tools_choice_kb
from utils.misc.notify_users import send_a_message_to_all_users
@dp.message_handler(Command('admin_tools'))
async def go_to_admin_panel(message: Message, state: FSMContext) -> None:
lang: str = await DB_USERS.select_bot_language(telegram_id=message.from_user.id)
await message.answer(
'Чего изволите?' if lang == 'ru' else 'What would you like?', reply_markup=tools_choice_kb
)
await state.set_state('admin_in_action')
async with state.proxy() as data:
data['lang']: str = lang
@dp.callback_query_handler(text={'reset_user_codeword', 'make_newsletter'}, state='admin_in_action')
async def choose_an_action(call: CallbackQuery, state: FSMContext) -> None:
async with state.proxy() as data:
lang: str = data.get('lang')
if call.data == 'reset_user_codeword':
await call.message.answer('id пользователя?' if lang == 'ru' else 'user id?')
await state.set_state('accept_user_id')
elif call.data == 'make_newsletter':
await call.message.answer('текст рассылки?' if lang == 'ru' else 'mailing text?')
await state.set_state('receiving_mailing_text')
await call.message.delete_reply_markup()
@dp.message_handler(state='accept_user_id')
async def take_user_id(message: Message, state: FSMContext) -> None:
async with state.proxy() as data:
lang: str = data.get('lang')
try:
if await DB_USERS.check_personal_pass(telegram_id=message.text):
await DB_USERS.update_personal_pass(telegram_id=message.text, personal_pass=None)
await message.answer('СДЕЛАНО!' if lang == 'ru' else 'MADE!')
except NoResultFound:
logger_guru.exception('Failed attempt to reset the code word!')
await message.reply(
'Что-то пошло не так...смотри логи' if lang == 'ru' else 'Something went wrong...look at the logs'
)
finally:
await state.finish()
@dp.message_handler(state='receiving_mailing_text')
async def make_newsletter_to_all_users(message: Message, state: FSMContext) -> None:
async with state.proxy() as data:
lang: str = data.get('lang')
if not (result := await send_a_message_to_all_users(msg=message.text)):
await message.answer('Готово!' if lang == 'ru' else 'YAHOO!')
else:
await message.answer(
f'Что-то пошло не так: {result}' if lang == 'ru' else
f'Something went wrong: {result}'
)
await state.finish()
| [
"loader.logger_guru.exception",
"aiogram.dispatcher.filters.Command",
"loader.dp.callback_query_handler",
"utils.database_manage.sql.sql_commands.DB_USERS.update_personal_pass",
"utils.database_manage.sql.sql_commands.DB_USERS.check_personal_pass",
"loader.dp.message_handler",
"utils.misc.notify_users.s... | [((855, 958), 'loader.dp.callback_query_handler', 'dp.callback_query_handler', ([], {'text': "{'reset_user_codeword', 'make_newsletter'}", 'state': '"""admin_in_action"""'}), "(text={'reset_user_codeword', 'make_newsletter'},\n state='admin_in_action')\n", (880, 958), False, 'from loader import dp, logger_guru\n'), ((1520, 1562), 'loader.dp.message_handler', 'dp.message_handler', ([], {'state': '"""accept_user_id"""'}), "(state='accept_user_id')\n", (1538, 1562), False, 'from loader import dp, logger_guru\n'), ((2250, 2300), 'loader.dp.message_handler', 'dp.message_handler', ([], {'state': '"""receiving_mailing_text"""'}), "(state='receiving_mailing_text')\n", (2268, 2300), False, 'from loader import dp, logger_guru\n'), ((421, 443), 'aiogram.dispatcher.filters.Command', 'Command', (['"""admin_tools"""'], {}), "('admin_tools')\n", (428, 443), False, 'from aiogram.dispatcher.filters import Command\n'), ((541, 603), 'utils.database_manage.sql.sql_commands.DB_USERS.select_bot_language', 'DB_USERS.select_bot_language', ([], {'telegram_id': 'message.from_user.id'}), '(telegram_id=message.from_user.id)\n', (569, 603), False, 'from utils.database_manage.sql.sql_commands import DB_USERS\n'), ((1733, 1787), 'utils.database_manage.sql.sql_commands.DB_USERS.check_personal_pass', 'DB_USERS.check_personal_pass', ([], {'telegram_id': 'message.text'}), '(telegram_id=message.text)\n', (1761, 1787), False, 'from utils.database_manage.sql.sql_commands import DB_USERS\n'), ((1991, 2054), 'loader.logger_guru.exception', 'logger_guru.exception', (['"""Failed attempt to reset the code word!"""'], {}), "('Failed attempt to reset the code word!')\n", (2012, 2054), False, 'from loader import dp, logger_guru\n'), ((1807, 1882), 'utils.database_manage.sql.sql_commands.DB_USERS.update_personal_pass', 'DB_USERS.update_personal_pass', ([], {'telegram_id': 'message.text', 'personal_pass': 'None'}), '(telegram_id=message.text, personal_pass=None)\n', (1836, 1882), False, 'from utils.database_manage.sql.sql_commands import DB_USERS\n'), ((2490, 2535), 'utils.misc.notify_users.send_a_message_to_all_users', 'send_a_message_to_all_users', ([], {'msg': 'message.text'}), '(msg=message.text)\n', (2517, 2535), False, 'from utils.misc.notify_users import send_a_message_to_all_users\n')] |
import math
#matplotlib keyboard
noteKeys = "<KEY>'"
class keyboard:
def __init__(self,keystring="<KEY>"):
self.keys = keystring
self._keepinscope = None
self.keysDown = set()
def plot(self,ival=50):
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots()
fig.canvas.mpl_disconnect(
fig.canvas.manager.key_press_handler_id)
def press(event):
if event.key in self.keys:
self.keysDown.add(event.key)
return True
def release(event):
if event.key in self.keysDown:
self.keysDown.remove(event.key)
return True
ax.set_title("keyboard")
fig.canvas.mpl_connect("key_release_event",release)
fig.canvas.mpl_connect('key_press_event', press)
def no(i):
pass
ani = animation.FuncAnimation(fig,no,interval=50)
self._keepinscope = [press,release,no]
return plt
eone = math.exp(2*math.pi)
def sinKeyboard(kb,fbase=440,offs=7,nk=noteKeys,sr=48000):
factors = [eone**(1j*fbase*2**((i-offs)/12)/sr) for i in range(len(nk))]
oscilators = [1]*len(factors)
while 1:
t = 0
for k in kb.keysDown:
i = nk.index(k)
oscilators[i] *= factors[i]
t += oscilators[i]
yield t
def sindKeyboard(kb,fbase=440,start=.01,attak=1.01,decay=.99,offs=7,nk=noteKeys,sr=48000):
factors = [eone**(1j*fbase*2**((i-offs)/12)/sr) for i in range(len(nk))]
oscilators = [start]*len(factors)
alive = set()
while 1:
t = 0
for i in range(len(factors)):
if nk[i] in kb.keysDown:
s = abs(oscilators[i])
alive.add(i)
if s*attak>1:
oscilators[i] *= factors[i]/s
else:
oscilators[i] *= factors[i]*attak
elif i in alive:
oscilators[i] *= factors[i]*decay
if abs(oscilators[i]) < start:
alive.remove(i)
else:
continue
t += oscilators[i]
yield t
def delaylineKeyboard(kb,f=lambda x:x*.75,fbase=440,offs=7,nk=noteKeys,sr=48000):
delays = [sr/(fbase*2**((i-offs)/12)) for i in range(len(nk))]
#nearest interp for now
delays = [round(d) for d in delays]
lines = [[0]*d for d in delays]
def do(v,i=[0],l=lines):
t = 0
n = 0
for o in range(len(l)):
p = l[o][i[0]%len(l[o])]
l[o][i[0]%len(l[o])] = v
if nk[o] in kb.keysDown:
l[o][i[0]%len(l[o])] += f(p)
t += l[o][i[0]%len(l[o])]
n += 1
i[0] += 1
return t/max(1,n)
return do
from filters import biquadPeak
l2 = math.log(2)
def filtkeyb(kb,fbase=440,offs=7,fg = lambda f:biquadPeak(f,f*l2/12,10),nk=noteKeys,sr=48000):
filts = [fg((2*fbase*2**((i-offs)/12))/sr) for i in range(len(nk))]
def do(v):
for o in range(len(filts)):
if nk[o] in kb.keysDown:
v = filts[o](v)
return v
return do
| [
"filters.biquadPeak",
"matplotlib.animation.FuncAnimation",
"math.log",
"math.exp",
"matplotlib.pyplot.subplots"
] | [((1047, 1068), 'math.exp', 'math.exp', (['(2 * math.pi)'], {}), '(2 * math.pi)\n', (1055, 1068), False, 'import math\n'), ((2865, 2876), 'math.log', 'math.log', (['(2)'], {}), '(2)\n', (2873, 2876), False, 'import math\n'), ((341, 355), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (353, 355), True, 'import matplotlib.pyplot as plt\n'), ((929, 974), 'matplotlib.animation.FuncAnimation', 'animation.FuncAnimation', (['fig', 'no'], {'interval': '(50)'}), '(fig, no, interval=50)\n', (952, 974), True, 'import matplotlib.animation as animation\n'), ((2925, 2955), 'filters.biquadPeak', 'biquadPeak', (['f', '(f * l2 / 12)', '(10)'], {}), '(f, f * l2 / 12, 10)\n', (2935, 2955), False, 'from filters import biquadPeak\n')] |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Calculation.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from Calculation.CalculatingLast5Days import CalculatingLast5Days
from PyQt5 import QtCore, QtGui, QtWidgets
class CalculationUi_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(933, 444)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.lblHeading = QtWidgets.QLabel(self.centralwidget)
self.lblHeading.setGeometry(QtCore.QRect(10, 10, 909, 109))
font = QtGui.QFont()
font.setPointSize(22)
font.setBold(True)
font.setWeight(75)
self.lblHeading.setFont(font)
self.lblHeading.setStyleSheet("background-color: rgb(140, 244, 255)")
self.lblHeading.setFrameShape(QtWidgets.QFrame.NoFrame)
self.lblHeading.setAlignment(QtCore.Qt.AlignCenter)
self.lblHeading.setObjectName("lblHeading")
self.horizontalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.horizontalLayoutWidget.setGeometry(QtCore.QRect(10, 130, 911, 301))
self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget)
self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.horizontalLayout_6 = QtWidgets.QHBoxLayout()
self.horizontalLayout_6.setObjectName("horizontalLayout_6")
self.verticalLayout_6 = QtWidgets.QVBoxLayout()
self.verticalLayout_6.setObjectName("verticalLayout_6")
self.btnlast5days = QtWidgets.QPushButton(self.horizontalLayoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.btnlast5days.sizePolicy().hasHeightForWidth())
self.btnlast5days.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily("Times New Roman")
font.setPointSize(14)
font.setBold(True)
font.setWeight(75)
self.btnlast5days.setFont(font)
self.btnlast5days.setStyleSheet("")
self.btnlast5days.setObjectName("btnlast5days")
self.verticalLayout_6.addWidget(self.btnlast5days)
self.btnlast2 = QtWidgets.QPushButton(self.horizontalLayoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.btnlast2.sizePolicy().hasHeightForWidth())
self.btnlast2.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily("Times New Roman")
font.setPointSize(14)
font.setBold(True)
font.setItalic(False)
font.setWeight(75)
self.btnlast2.setFont(font)
self.btnlast2.setStyleSheet("")
self.btnlast2.setObjectName("btnlast2")
self.verticalLayout_6.addWidget(self.btnlast2)
self.btnNifty50FromNiftyAll_3 = QtWidgets.QPushButton(self.horizontalLayoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.btnNifty50FromNiftyAll_3.sizePolicy().hasHeightForWidth())
self.btnNifty50FromNiftyAll_3.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily("Times New Roman")
font.setPointSize(14)
font.setBold(True)
font.setItalic(False)
font.setWeight(75)
self.btnNifty50FromNiftyAll_3.setFont(font)
self.btnNifty50FromNiftyAll_3.setStyleSheet("")
self.btnNifty50FromNiftyAll_3.setObjectName("btnNifty50FromNiftyAll_3")
self.verticalLayout_6.addWidget(self.btnNifty50FromNiftyAll_3)
self.horizontalLayout_6.addLayout(self.verticalLayout_6)
self.horizontalLayout_2.addLayout(self.horizontalLayout_6)
self.horizontalLayout_7 = QtWidgets.QHBoxLayout()
self.horizontalLayout_7.setObjectName("horizontalLayout_7")
self.verticalLayout_7 = QtWidgets.QVBoxLayout()
self.verticalLayout_7.setObjectName("verticalLayout_7")
self.btnlast1 = QtWidgets.QPushButton(self.horizontalLayoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.btnlast1.sizePolicy().hasHeightForWidth())
self.btnlast1.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily("Times New Roman")
font.setPointSize(14)
font.setBold(True)
font.setItalic(False)
font.setWeight(75)
self.btnlast1.setFont(font)
self.btnlast1.setStyleSheet("")
self.btnlast1.setObjectName("btnlast1")
self.verticalLayout_7.addWidget(self.btnlast1)
self.btnlast4 = QtWidgets.QPushButton(self.horizontalLayoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.btnlast4.sizePolicy().hasHeightForWidth())
self.btnlast4.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily("Times New Roman")
font.setPointSize(14)
font.setBold(True)
font.setItalic(False)
font.setWeight(75)
self.btnlast4.setFont(font)
self.btnlast4.setStyleSheet("")
self.btnlast4.setObjectName("btnlast4")
self.verticalLayout_7.addWidget(self.btnlast4)
self.btnlast5 = QtWidgets.QPushButton(self.horizontalLayoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.btnlast5.sizePolicy().hasHeightForWidth())
self.btnlast5.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily("Times New Roman")
font.setPointSize(14)
font.setBold(True)
font.setItalic(False)
font.setWeight(75)
self.btnlast5.setFont(font)
self.btnlast5.setStyleSheet("")
self.btnlast5.setObjectName("btnlast5")
self.verticalLayout_7.addWidget(self.btnlast5)
self.horizontalLayout_7.addLayout(self.verticalLayout_7)
self.horizontalLayout_2.addLayout(self.horizontalLayout_7)
MainWindow.setCentralWidget(self.centralwidget)
# Calling Function
self.objCalculation = CalculatingLast5Days()
self.btnlast5days.clicked.connect(self.objCalculation.calculatingData)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.lblHeading.setText(_translate("MainWindow", "Calulation of NSE Data"))
self.btnlast5days.setText(_translate("MainWindow", "Last 5 Days"))
self.btnlast2.setText(_translate("MainWindow", "Last "))
self.btnNifty50FromNiftyAll_3.setText(_translate("MainWindow", "Last "))
self.btnlast1.setText(_translate("MainWindow", "Last"))
self.btnlast4.setText(_translate("MainWindow", "Last "))
self.btnlast5.setText(_translate("MainWindow", "Last "))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = CalculationUi_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
| [
"PyQt5.QtWidgets.QWidget",
"PyQt5.QtWidgets.QMainWindow",
"PyQt5.QtGui.QFont",
"PyQt5.QtWidgets.QSizePolicy",
"PyQt5.QtCore.QMetaObject.connectSlotsByName",
"Calculation.CalculatingLast5Days.CalculatingLast5Days",
"PyQt5.QtWidgets.QHBoxLayout",
"PyQt5.QtCore.QRect",
"PyQt5.QtWidgets.QLabel",
"PyQt... | [((8245, 8277), 'PyQt5.QtWidgets.QApplication', 'QtWidgets.QApplication', (['sys.argv'], {}), '(sys.argv)\n', (8267, 8277), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((8296, 8319), 'PyQt5.QtWidgets.QMainWindow', 'QtWidgets.QMainWindow', ([], {}), '()\n', (8317, 8319), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((511, 540), 'PyQt5.QtWidgets.QWidget', 'QtWidgets.QWidget', (['MainWindow'], {}), '(MainWindow)\n', (528, 540), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((627, 663), 'PyQt5.QtWidgets.QLabel', 'QtWidgets.QLabel', (['self.centralwidget'], {}), '(self.centralwidget)\n', (643, 663), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((749, 762), 'PyQt5.QtGui.QFont', 'QtGui.QFont', ([], {}), '()\n', (760, 762), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((1186, 1223), 'PyQt5.QtWidgets.QWidget', 'QtWidgets.QWidget', (['self.centralwidget'], {}), '(self.centralwidget)\n', (1203, 1223), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((1418, 1468), 'PyQt5.QtWidgets.QHBoxLayout', 'QtWidgets.QHBoxLayout', (['self.horizontalLayoutWidget'], {}), '(self.horizontalLayoutWidget)\n', (1439, 1468), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((1637, 1660), 'PyQt5.QtWidgets.QHBoxLayout', 'QtWidgets.QHBoxLayout', ([], {}), '()\n', (1658, 1660), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((1763, 1786), 'PyQt5.QtWidgets.QVBoxLayout', 'QtWidgets.QVBoxLayout', ([], {}), '()\n', (1784, 1786), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((1881, 1931), 'PyQt5.QtWidgets.QPushButton', 'QtWidgets.QPushButton', (['self.horizontalLayoutWidget'], {}), '(self.horizontalLayoutWidget)\n', (1902, 1931), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((1954, 2044), 'PyQt5.QtWidgets.QSizePolicy', 'QtWidgets.QSizePolicy', (['QtWidgets.QSizePolicy.Minimum', 'QtWidgets.QSizePolicy.Expanding'], {}), '(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.\n Expanding)\n', (1975, 2044), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((2285, 2298), 'PyQt5.QtGui.QFont', 'QtGui.QFont', ([], {}), '()\n', (2296, 2298), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((2657, 2707), 'PyQt5.QtWidgets.QPushButton', 'QtWidgets.QPushButton', (['self.horizontalLayoutWidget'], {}), '(self.horizontalLayoutWidget)\n', (2678, 2707), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((2730, 2822), 'PyQt5.QtWidgets.QSizePolicy', 'QtWidgets.QSizePolicy', (['QtWidgets.QSizePolicy.Expanding', 'QtWidgets.QSizePolicy.Expanding'], {}), '(QtWidgets.QSizePolicy.Expanding, QtWidgets.\n QSizePolicy.Expanding)\n', (2751, 2822), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((3055, 3068), 'PyQt5.QtGui.QFont', 'QtGui.QFont', ([], {}), '()\n', (3066, 3068), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((3454, 3504), 'PyQt5.QtWidgets.QPushButton', 'QtWidgets.QPushButton', (['self.horizontalLayoutWidget'], {}), '(self.horizontalLayoutWidget)\n', (3475, 3504), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((3527, 3619), 'PyQt5.QtWidgets.QSizePolicy', 'QtWidgets.QSizePolicy', (['QtWidgets.QSizePolicy.Expanding', 'QtWidgets.QSizePolicy.Expanding'], {}), '(QtWidgets.QSizePolicy.Expanding, QtWidgets.\n QSizePolicy.Expanding)\n', (3548, 3619), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((3884, 3897), 'PyQt5.QtGui.QFont', 'QtGui.QFont', ([], {}), '()\n', (3895, 3897), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((4491, 4514), 'PyQt5.QtWidgets.QHBoxLayout', 'QtWidgets.QHBoxLayout', ([], {}), '()\n', (4512, 4514), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((4617, 4640), 'PyQt5.QtWidgets.QVBoxLayout', 'QtWidgets.QVBoxLayout', ([], {}), '()\n', (4638, 4640), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((4731, 4781), 'PyQt5.QtWidgets.QPushButton', 'QtWidgets.QPushButton', (['self.horizontalLayoutWidget'], {}), '(self.horizontalLayoutWidget)\n', (4752, 4781), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((4804, 4896), 'PyQt5.QtWidgets.QSizePolicy', 'QtWidgets.QSizePolicy', (['QtWidgets.QSizePolicy.Expanding', 'QtWidgets.QSizePolicy.Expanding'], {}), '(QtWidgets.QSizePolicy.Expanding, QtWidgets.\n QSizePolicy.Expanding)\n', (4825, 4896), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((5129, 5142), 'PyQt5.QtGui.QFont', 'QtGui.QFont', ([], {}), '()\n', (5140, 5142), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((5512, 5562), 'PyQt5.QtWidgets.QPushButton', 'QtWidgets.QPushButton', (['self.horizontalLayoutWidget'], {}), '(self.horizontalLayoutWidget)\n', (5533, 5562), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((5585, 5677), 'PyQt5.QtWidgets.QSizePolicy', 'QtWidgets.QSizePolicy', (['QtWidgets.QSizePolicy.Expanding', 'QtWidgets.QSizePolicy.Expanding'], {}), '(QtWidgets.QSizePolicy.Expanding, QtWidgets.\n QSizePolicy.Expanding)\n', (5606, 5677), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((5910, 5923), 'PyQt5.QtGui.QFont', 'QtGui.QFont', ([], {}), '()\n', (5921, 5923), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((6293, 6343), 'PyQt5.QtWidgets.QPushButton', 'QtWidgets.QPushButton', (['self.horizontalLayoutWidget'], {}), '(self.horizontalLayoutWidget)\n', (6314, 6343), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((6366, 6458), 'PyQt5.QtWidgets.QSizePolicy', 'QtWidgets.QSizePolicy', (['QtWidgets.QSizePolicy.Expanding', 'QtWidgets.QSizePolicy.Expanding'], {}), '(QtWidgets.QSizePolicy.Expanding, QtWidgets.\n QSizePolicy.Expanding)\n', (6387, 6458), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((6691, 6704), 'PyQt5.QtGui.QFont', 'QtGui.QFont', ([], {}), '()\n', (6702, 6704), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((7301, 7323), 'Calculation.CalculatingLast5Days.CalculatingLast5Days', 'CalculatingLast5Days', ([], {}), '()\n', (7321, 7323), False, 'from Calculation.CalculatingLast5Days import CalculatingLast5Days\n'), ((7457, 7506), 'PyQt5.QtCore.QMetaObject.connectSlotsByName', 'QtCore.QMetaObject.connectSlotsByName', (['MainWindow'], {}), '(MainWindow)\n', (7494, 7506), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((701, 731), 'PyQt5.QtCore.QRect', 'QtCore.QRect', (['(10)', '(10)', '(909)', '(109)'], {}), '(10, 10, 909, 109)\n', (713, 731), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((1273, 1304), 'PyQt5.QtCore.QRect', 'QtCore.QRect', (['(10)', '(130)', '(911)', '(301)'], {}), '(10, 130, 911, 301)\n', (1285, 1304), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n')] |
import os
import sys
import inspect
from ruamel import yaml
def get_script_dir(follow_symlinks=True):
if getattr(sys, 'frozen', False): # py2exe, PyInstaller, cx_Freeze
path = os.path.abspath(sys.executable)
else:
path = inspect.getabsfile(get_script_dir)
if follow_symlinks:
path = os.path.realpath(path)
return os.path.dirname(path)
def create_dir_if_not_exists(d):
basedir = os.path.dirname(d)
if not os.path.exists(basedir):
os.makedirs(basedir)
def get_config(path):
return yaml.safe_load(open(path, "r"))
def list_files(directory, *args):
result = []
for f in os.listdir(directory):
for ext in args:
if f.endswith('.{}'.format(ext)):
result.append(f)
break
return result
def get_min_max(arr):
amin = arr[0]
amax = arr[0]
for a in arr:
if a < amin:
amin = a
elif a > amax:
amax = a
return (amin, amax)
| [
"os.path.exists",
"os.listdir",
"os.makedirs",
"os.path.realpath",
"os.path.dirname",
"inspect.getabsfile",
"os.path.abspath"
] | [((370, 391), 'os.path.dirname', 'os.path.dirname', (['path'], {}), '(path)\n', (385, 391), False, 'import os\n'), ((453, 471), 'os.path.dirname', 'os.path.dirname', (['d'], {}), '(d)\n', (468, 471), False, 'import os\n'), ((696, 717), 'os.listdir', 'os.listdir', (['directory'], {}), '(directory)\n', (706, 717), False, 'import os\n'), ((200, 231), 'os.path.abspath', 'os.path.abspath', (['sys.executable'], {}), '(sys.executable)\n', (215, 231), False, 'import os\n'), ((259, 293), 'inspect.getabsfile', 'inspect.getabsfile', (['get_script_dir'], {}), '(get_script_dir)\n', (277, 293), False, 'import inspect\n'), ((335, 357), 'os.path.realpath', 'os.path.realpath', (['path'], {}), '(path)\n', (351, 357), False, 'import os\n'), ((484, 507), 'os.path.exists', 'os.path.exists', (['basedir'], {}), '(basedir)\n', (498, 507), False, 'import os\n'), ((518, 538), 'os.makedirs', 'os.makedirs', (['basedir'], {}), '(basedir)\n', (529, 538), False, 'import os\n')] |
import random
from typing import Any
import factory
import pytz
from django.utils.text import slugify
from ap.apps.events.models import EVENT_TYPE_CHOICES, Event, Organization, Route
from ap.apps.users.constants import COUNTRY_CHOICES
from ap.apps.users.models import User
from ap.apps.events.factory_data import RANDOM_EVENT_LIST, RANDOM_COORDS_LIST
class RouteFactory(factory.django.DjangoModelFactory):
"""Fabricate a route with realistic data. MUST have an event passed in when called."""
class Meta:
model = Route
title = factory.Faker('text', max_nb_chars=60)
url = factory.Faker('url')
class EventFactory(factory.django.DjangoModelFactory):
"""Fabricate an event with realistic data"""
class Meta:
model = Event
name = factory.LazyAttribute(lambda o: random.choice(RANDOM_EVENT_LIST))
event_type = factory.LazyAttribute(lambda o: random.choice(EVENT_TYPE_CHOICES)[0])
slug = factory.LazyAttribute(lambda o: slugify(o.name))
about = factory.Faker('paragraph', nb_sentences=9)
start = factory.Faker('date_time_this_century', tzinfo=pytz.UTC)
address = factory.Faker('street_address')
place_name = factory.Faker('company')
city = factory.Faker('city')
state_province = factory.Faker('state')
country = factory.LazyAttribute(lambda o: random.choice(COUNTRY_CHOICES)[0])
official_event_site_url = factory.Faker('url')
official_event_site_title = factory.Faker('text', max_nb_chars=30)
fee = factory.Faker('pydecimal', left_digits=4, right_digits=2, positive=True)
fee_paid = factory.Faker('pybool')
notes = factory.Faker('paragraph')
published = True
@factory.post_generation
def maybe_add_orgs(obj, build: bool, extracted: Any, **kwargs: dict) -> None:
# Maybe assign a random org to event.
dice = random.choice(range(1, 5))
for _ in range(dice):
org = Organization.objects.all().order_by('?').first()
obj.organizations.add(org)
@factory.post_generation
def maybe_add_humans(obj, build: bool, extracted: Any, **kwargs: dict) -> None:
# Maybe assign a random contact to event.
dice = random.choice(range(1, 5))
for _ in range(dice):
user = User.objects.all().order_by('?').first()
obj.humans.add(user)
@factory.post_generation
def add_routes(obj, build: bool, extracted: Any, **kwargs: dict) -> None:
numroutes = random.choice(range(0, 5))
RouteFactory.create_batch(numroutes, event=obj)
@factory.post_generation
def add_coords(obj, build: bool, extracted: Any, **kwargs: dict) -> None:
# Select from actual city coordinates guaranteed to be on land
coords = random.choice(RANDOM_COORDS_LIST)
obj.latitude = coords[0]
obj.longitude = coords[1]
class OrgFactory(factory.django.DjangoModelFactory):
"""Fabricate an organization with realistic data"""
class Meta:
model = Organization
name = factory.Faker('company')
slug = factory.LazyAttribute(lambda o: slugify(o.name))
address = factory.Faker('address')
phone = factory.Faker('phone_number')
email = factory.Faker('email')
human = factory.LazyAttribute(lambda o: User.objects.all().order_by('?').first())
| [
"django.utils.text.slugify",
"ap.apps.events.models.Organization.objects.all",
"random.choice",
"factory.Faker",
"ap.apps.users.models.User.objects.all"
] | [((552, 590), 'factory.Faker', 'factory.Faker', (['"""text"""'], {'max_nb_chars': '(60)'}), "('text', max_nb_chars=60)\n", (565, 590), False, 'import factory\n'), ((601, 621), 'factory.Faker', 'factory.Faker', (['"""url"""'], {}), "('url')\n", (614, 621), False, 'import factory\n'), ((1003, 1045), 'factory.Faker', 'factory.Faker', (['"""paragraph"""'], {'nb_sentences': '(9)'}), "('paragraph', nb_sentences=9)\n", (1016, 1045), False, 'import factory\n'), ((1058, 1114), 'factory.Faker', 'factory.Faker', (['"""date_time_this_century"""'], {'tzinfo': 'pytz.UTC'}), "('date_time_this_century', tzinfo=pytz.UTC)\n", (1071, 1114), False, 'import factory\n'), ((1129, 1160), 'factory.Faker', 'factory.Faker', (['"""street_address"""'], {}), "('street_address')\n", (1142, 1160), False, 'import factory\n'), ((1178, 1202), 'factory.Faker', 'factory.Faker', (['"""company"""'], {}), "('company')\n", (1191, 1202), False, 'import factory\n'), ((1214, 1235), 'factory.Faker', 'factory.Faker', (['"""city"""'], {}), "('city')\n", (1227, 1235), False, 'import factory\n'), ((1257, 1279), 'factory.Faker', 'factory.Faker', (['"""state"""'], {}), "('state')\n", (1270, 1279), False, 'import factory\n'), ((1391, 1411), 'factory.Faker', 'factory.Faker', (['"""url"""'], {}), "('url')\n", (1404, 1411), False, 'import factory\n'), ((1444, 1482), 'factory.Faker', 'factory.Faker', (['"""text"""'], {'max_nb_chars': '(30)'}), "('text', max_nb_chars=30)\n", (1457, 1482), False, 'import factory\n'), ((1493, 1565), 'factory.Faker', 'factory.Faker', (['"""pydecimal"""'], {'left_digits': '(4)', 'right_digits': '(2)', 'positive': '(True)'}), "('pydecimal', left_digits=4, right_digits=2, positive=True)\n", (1506, 1565), False, 'import factory\n'), ((1581, 1604), 'factory.Faker', 'factory.Faker', (['"""pybool"""'], {}), "('pybool')\n", (1594, 1604), False, 'import factory\n'), ((1617, 1643), 'factory.Faker', 'factory.Faker', (['"""paragraph"""'], {}), "('paragraph')\n", (1630, 1643), False, 'import factory\n'), ((3007, 3031), 'factory.Faker', 'factory.Faker', (['"""company"""'], {}), "('company')\n", (3020, 3031), False, 'import factory\n'), ((3106, 3130), 'factory.Faker', 'factory.Faker', (['"""address"""'], {}), "('address')\n", (3119, 3130), False, 'import factory\n'), ((3143, 3172), 'factory.Faker', 'factory.Faker', (['"""phone_number"""'], {}), "('phone_number')\n", (3156, 3172), False, 'import factory\n'), ((3185, 3207), 'factory.Faker', 'factory.Faker', (['"""email"""'], {}), "('email')\n", (3198, 3207), False, 'import factory\n'), ((2738, 2771), 'random.choice', 'random.choice', (['RANDOM_COORDS_LIST'], {}), '(RANDOM_COORDS_LIST)\n', (2751, 2771), False, 'import random\n'), ((810, 842), 'random.choice', 'random.choice', (['RANDOM_EVENT_LIST'], {}), '(RANDOM_EVENT_LIST)\n', (823, 842), False, 'import random\n'), ((974, 989), 'django.utils.text.slugify', 'slugify', (['o.name'], {}), '(o.name)\n', (981, 989), False, 'from django.utils.text import slugify\n'), ((3075, 3090), 'django.utils.text.slugify', 'slugify', (['o.name'], {}), '(o.name)\n', (3082, 3090), False, 'from django.utils.text import slugify\n'), ((893, 926), 'random.choice', 'random.choice', (['EVENT_TYPE_CHOICES'], {}), '(EVENT_TYPE_CHOICES)\n', (906, 926), False, 'import random\n'), ((1326, 1356), 'random.choice', 'random.choice', (['COUNTRY_CHOICES'], {}), '(COUNTRY_CHOICES)\n', (1339, 1356), False, 'import random\n'), ((1913, 1939), 'ap.apps.events.models.Organization.objects.all', 'Organization.objects.all', ([], {}), '()\n', (1937, 1939), False, 'from ap.apps.events.models import EVENT_TYPE_CHOICES, Event, Organization, Route\n'), ((2256, 2274), 'ap.apps.users.models.User.objects.all', 'User.objects.all', ([], {}), '()\n', (2272, 2274), False, 'from ap.apps.users.models import User\n'), ((3252, 3270), 'ap.apps.users.models.User.objects.all', 'User.objects.all', ([], {}), '()\n', (3268, 3270), False, 'from ap.apps.users.models import User\n')] |
#!/usr/bin/env python
from __future__ import division
import math
import random
import time
import genpy
import rospy
import roslib
from qt_gui.plugin import Plugin
from python_qt_binding.QtCore import Slot, QSignalMapper, QTimer
from python_qt_binding.QtWidgets import QHeaderView, QTableWidgetItem
from rqt_command_publisher.command_publisher_widget import CommandPublisherWidget
class CommandPublisher(Plugin):
def __init__(self, context):
super(CommandPublisher, self).__init__(context)
# Give QObjects reasonable names
self.setObjectName('Command Publisher')
# Create widget
self._widget = CommandPublisherWidget()
self._widget.start_publisher.connect(self.start_publisher)
self._widget.stop_publisher.connect(self.clean_up_publishers)
self._widget.update_command_table.connect(self.update_command_table)
# Show _widget.windowTitle on left-top of each plugin (when
# it's set in _widget). This is useful when you open multiple
# plugins at once. Also if you open multiple instances of your
# plugin at once, these lines add number to make it easy to
# tell from pane to pane.
if context.serial_number() > 1:
self._widget.setWindowTitle(self._widget.windowTitle() + (' (%d)' % context.serial_number()))
# Create context for the expression eval statement
self._eval_locals = {'i': 0}
for module in (math, random, time):
self._eval_locals.update(module.__dict__)
self._eval_locals['genpy'] = genpy
del self._eval_locals['__name__']
del self._eval_locals['__doc__']
self._publishers = {}
self._id_counter = 0
self._timeout_mapper = QSignalMapper(self)
self._timeout_mapper.mapped[int].connect(self.publish_once)
# Add widget to the user interface
context.add_widget(self._widget)
@Slot(str, str, float, object)
def start_publisher(self, topic_name, command_name, rate, data):
publisher_info = {
'topic_name': str(topic_name),
'type_name': str('std_msgs/UInt16MultiArray'),
'command_name': str(command_name),
'rate': float(rate),
'data': data
}
self._start_publisher(publisher_info)
def _start_publisher(self, publisher_info):
publisher_info['publisher_id'] = self._id_counter
self._id_counter += 1
publisher_info['counter'] = 0
publisher_info['message_instance'] = roslib.message.get_message_class(publisher_info['type_name'])()
if publisher_info['message_instance'] is None:
return
# create publisher and timer
try:
publisher_info['publisher'] = rospy.Publisher(publisher_info['topic_name'],
type(publisher_info['message_instance']),
queue_size=10)
except TypeError:
publisher_info['publisher'] = rospy.Publisher(publisher_info['topic_name'],
type(publisher_info['message_instance']))
publisher_info['timer'] = QTimer(self)
# add publisher info to _publishers dict and create signal mapping
self._publishers[publisher_info['publisher_id']] = publisher_info
self._timeout_mapper.setMapping(publisher_info['timer'], publisher_info['publisher_id'])
publisher_info['timer'].timeout.connect(self._timeout_mapper.map)
if publisher_info['rate'] > 0:
publisher_info['timer'].start(int(1000.0 / publisher_info['rate']))
@Slot(int)
def publish_once(self, publisher_id):
rospy.loginfo('publish_once: {}'.format(publisher_id))
publisher_info = self._publishers.get(publisher_id, None)
rospy.loginfo(publisher_info)
if publisher_info is not None:
publisher_info['counter'] += 1
publisher_info['publisher'].publish(data=publisher_info['data'])
def clean_up_publishers(self):
# self._widget.publisher_tree_widget.model().clear()
for publisher_info in self._publishers.values():
publisher_info['timer'].stop()
publisher_info['publisher'].unregister()
self._publishers = {}
def shutdown_plugin(self):
self._widget.shutdown_plugin()
self.clean_up_publishers()
def update_command_table(self, commands):
table = self._widget.command_table_widget
table.setRowCount(len(commands))
for index, command in enumerate(sorted(commands.keys())):
table.setItem(index, 0, QTableWidgetItem(str(command)))
data = commands[command]
for i in range(len(data)):
table.setItem(index, i + 1, QTableWidgetItem(str(data[i])))
header = table.horizontalHeader()
header.setSectionResizeMode(0, QHeaderView.Stretch)
for i in range(1, len(header)):
header.setSectionResizeMode(i, QHeaderView.ResizeToContents)
| [
"python_qt_binding.QtCore.Slot",
"rqt_command_publisher.command_publisher_widget.CommandPublisherWidget",
"python_qt_binding.QtCore.QTimer",
"roslib.message.get_message_class",
"rospy.loginfo",
"python_qt_binding.QtCore.QSignalMapper"
] | [((1935, 1964), 'python_qt_binding.QtCore.Slot', 'Slot', (['str', 'str', 'float', 'object'], {}), '(str, str, float, object)\n', (1939, 1964), False, 'from python_qt_binding.QtCore import Slot, QSignalMapper, QTimer\n'), ((3702, 3711), 'python_qt_binding.QtCore.Slot', 'Slot', (['int'], {}), '(int)\n', (3706, 3711), False, 'from python_qt_binding.QtCore import Slot, QSignalMapper, QTimer\n'), ((646, 670), 'rqt_command_publisher.command_publisher_widget.CommandPublisherWidget', 'CommandPublisherWidget', ([], {}), '()\n', (668, 670), False, 'from rqt_command_publisher.command_publisher_widget import CommandPublisherWidget\n'), ((1756, 1775), 'python_qt_binding.QtCore.QSignalMapper', 'QSignalMapper', (['self'], {}), '(self)\n', (1769, 1775), False, 'from python_qt_binding.QtCore import Slot, QSignalMapper, QTimer\n'), ((3243, 3255), 'python_qt_binding.QtCore.QTimer', 'QTimer', (['self'], {}), '(self)\n', (3249, 3255), False, 'from python_qt_binding.QtCore import Slot, QSignalMapper, QTimer\n'), ((3891, 3920), 'rospy.loginfo', 'rospy.loginfo', (['publisher_info'], {}), '(publisher_info)\n', (3904, 3920), False, 'import rospy\n'), ((2545, 2606), 'roslib.message.get_message_class', 'roslib.message.get_message_class', (["publisher_info['type_name']"], {}), "(publisher_info['type_name'])\n", (2577, 2606), False, 'import roslib\n')] |
import time
import os
import arcade
import argparse
import gym
from gym import spaces
import swarm_env
import numpy as np
import random
import sys
sys.path.insert(0, '..')
from objects import SwarmSimulator
# Running experiment 22 in standalone file.
def experiment_runner(SWARM_SIZE = 15, ARENA_WIDTH = 600, ARENA_HEIGHT = 600, name_of_experiment = time.time(), INPUT_TIME = 300, GRID_X = 40, GRID_Y = 40,
disaster_size = 1, disaster_location = 'random', operator_size = 1, operator_location = 'random', reliability = (100, 101), unreliability_percentage = 0,
moving_disaster = False, communication_noise = 0, alpha = 10, normal_command = None, command_period = 0, constant_repulsion = False,
operator_vision_radius = 150, communication_range = 8, vision_range = 2, velocity_weight_coef = 0.01, boundary_repulsion = 1, aging_factor = 0.9999,
gp = False, gp_step = 50, maze = None, through_walls = True, rl_sim = None):
########### q-learning parameter setup #############
max_steps_per_episode = 10 # Steps allowed in a single episode.
learning_rate = 0.1 # alpha in bellman.
discount_rate = 0.99 # gamma in bellman for discount.
# Epsilon greedy policy vars.
exploration_rate = 1 # To set exploration (1 means 100% exploration)
max_exploration_rate = 1 # How large can exploration be.
min_exploration_rate = 0.01 # How small can exploration be.
exploration_decay_rate = 0.001 # decay rate for exploration.
rewards_all_episodes = [] # Saving all scores in rewards.
gym_swarm_env = gym.make('humanswarm-v0', maze_size=GRID_X) # Creating the environment for swarm learning.
gym_swarm_env.action_space = np.zeros((GRID_X, GRID_Y))
q_table = np.zeros((gym_swarm_env.observation_space.n , gym_swarm_env.action_space.size)) # Creating q-table for measuring score.
action = np.zeros((gym_swarm_env.action_space.size))
print('\n')
print("===== Reinforcement Parameters =====")
print("# Discount rate: " + str(discount_rate))
print("# Learning rate: " + str(learning_rate))
print("# Max steps per iteration: " + str(max_steps_per_episode))
print("# Max exploration rate: " + str(max_exploration_rate))
print("# Min exploration rate: " + str(min_exploration_rate))
print("# Exploration decay rate: " + str(exploration_decay_rate))
print("# Algorithm: " + str(rl_sim))
print("# State space size: " + str(gym_swarm_env.observation_space.n))
print("# Action space size: " + str(gym_swarm_env.action_space.size))
print("# Q-table size: " + str(q_table.shape))
print("====================================")
print('\n')
# Implemeting Q-learning algorithm.
done = False
state = gym_swarm_env.reset()
s_list = []
for step in range(max_steps_per_episode):
print('\n' + "============ start of step " + str(step) + " =============")
"""
In this loop we will set up exploration-exploitation trade-off,
Taking new action,
Updating Q-table,
Setting new state,
Adding new reward.
"""
# Simulation functions
sim = SwarmSimulator(ARENA_WIDTH, ARENA_HEIGHT, name_of_experiment, SWARM_SIZE, INPUT_TIME, GRID_X, GRID_Y, rl_sim)
sim.setup(disaster_size, disaster_location, operator_size, operator_location, reliability[0], reliability[1], unreliability_percentage, moving_disaster, communication_noise,
alpha, normal_command, command_period, constant_repulsion, operator_vision_radius,
communication_range, vision_range, velocity_weight_coef, boundary_repulsion, aging_factor, gp, gp_step, maze, through_walls)
if (not os.path.isdir('../outputs/' + name_of_experiment)):
os.mkdir('../outputs/' + name_of_experiment)
if (not os.path.isdir('../outputs/' + name_of_experiment + '/step_' + str(step))):
os.mkdir('../outputs/' + name_of_experiment + '/step_' + str(step))
if (not os.path.isdir('../outputs/' + name_of_experiment + '/step_' + str(step) + '/data')):
os.mkdir('../outputs/' + name_of_experiment + '/step_' + str(step) + '/data')
if (not os.path.isdir('../outputs/' + name_of_experiment + '/step_' + str(step) + '/data' + '/results')):
os.mkdir('../outputs/' + name_of_experiment + '/step_' + str(step) + '/data' + '/results')
sim.directory = str('../outputs/' + name_of_experiment + '/data/results/'+ str(time.time()))
while os.path.isdir(sim.directory):
sim.directory = str('../outputs/' + name_of_experiment + '/step_'+ str(step) + '/data/results/' + str(time.time()))
sim.directory = str('../outputs/' + name_of_experiment + '/step_'+ str(step) + '/data/results/'+ str(time.time()))
while os.path.isdir(sim.directory):
sim.directory = str('../outputs/' + name_of_experiment + '/step_'+ str(step) + '/data/results/' + str(time.time()))
directory = sim.directory
os.mkdir(directory)
sim.log_setup(directory)
# Adding new RL parameters to log #
with open(directory + "/log_setup.txt", "a") as file:
file.write('\n')
file.write('REINFORCEMENT LEARNING INFO:' + '\n')
file.write(' -- DISCOUNT RATE: ' + str(discount_rate) + '\n')
file.write(' -- LEARNING RATE: ' + str(learning_rate) + '\n')
file.write(' -- MAX STEPS PER ITERATION: ' + str(max_steps_per_episode) + '\n')
file.write(' -- MAX EXPLORATION RATE: ' + str(max_exploration_rate) + '\n')
file.write(' -- MIN EXPLORATION RATE: ' + str(min_exploration_rate) + '\n')
file.write(' -- EXPLORATION DECAY RATE: ' + str(exploration_decay_rate) + '\n')
file.write(' -- ALGORITHM: ' + str(rl_sim) + '\n')
file.write(' -- STATE SPACE SIZE: ' + str(gym_swarm_env.observation_space.n) + '\n')
file.write(' -- ACTION SPACE SIZE: ' + str(gym_swarm_env.action_space.size) + '\n')
file.write(' -- Q-TABLE SIZE: ' + str(q_table.shape) + '\n')
arcade.run()
########################
##### Exploration and explotation block. ####
exploration_rate_threshold = random.uniform(0, 1) # Setting a random number that will be compared to exploration_rate.
if exploration_rate_threshold > exploration_rate:
i, j = np.unravel_index(np.argmax(q_table[state, :]), q_table.shape)
print ("i ", i, " , j ", j)
#action = (i, j) # Choosing the action that had the highest q-value in q-table.
action = i*GRID_X + j # Choosing the action that had the highest q-value in q-table.
#print (action)
#exit(0)
else:
i = random.randint(0, GRID_X - 1)
j = random.randint(0, GRID_Y - 1)
action = i*GRID_X + j # Sample an action randomly to explore.
##### Exploration and explotation block. ####
##### Taking appropriate action after choosing the action. ####
new_state, reward, done, info, operator_cm = gym_swarm_env.step(action, sim.operator_list[0], GRID_X, GRID_Y) # Returns a tuple contaning the new state, the reward for this action, the end status of action, some additional info.
sim.operator_list[0].confidence_map = operator_cm
# Updating q-table values
q_table[state, action]=q_table[state, action] * (1 - learning_rate) + \
learning_rate * (reward + discount_rate * np.max(q_table[new_state, :]))
print('*** State-Action pair in Q-table ***')
print('Q[' + str(state) + ', ' + str(action) + '] = '+ str(q_table[state, action]))
state = new_state
if done == True:
break
##### Taking appropriate action after choosing the action. ####
print("============= End of step " + str(step) + " =============")
"""
# logging q-table
if self.directory == None:
self.q_table.tofile(self.directory + "/q_table" + "_step" + str(step) + "_timer" + str(self.timer) + ".txt", sep=" ", format="%s")
else:
self.q_table.tofile(self.directory + "/q_table" + "_step" + str(step) + "_timer" + str(self.timer) + ".txt", sep=" ", format="%s")
"""
# Decay exploration rate using a formula.
exploration_rate = min_exploration_rate + (max_exploration_rate - min_exploration_rate) * np.exp(-exploration_decay_rate * step)
######## END of q-learning parameter setup #########
if __name__ == '__main__':
experiment_runner(operator_vision_radius=40, INPUT_TIME=0, command_period=200, alpha=10, moving_disaster=False, disaster_location=[(500, 500)], operator_location=[(450, 300)], name_of_experiment='RL model experiment_r40_t200') | [
"random.uniform",
"sys.path.insert",
"random.randint",
"numpy.argmax",
"numpy.max",
"numpy.exp",
"numpy.zeros",
"os.path.isdir",
"os.mkdir",
"arcade.run",
"objects.SwarmSimulator",
"time.time",
"gym.make"
] | [((147, 171), 'sys.path.insert', 'sys.path.insert', (['(0)', '""".."""'], {}), "(0, '..')\n", (162, 171), False, 'import sys\n'), ((352, 363), 'time.time', 'time.time', ([], {}), '()\n', (361, 363), False, 'import time\n'), ((1595, 1638), 'gym.make', 'gym.make', (['"""humanswarm-v0"""'], {'maze_size': 'GRID_X'}), "('humanswarm-v0', maze_size=GRID_X)\n", (1603, 1638), False, 'import gym\n'), ((1719, 1745), 'numpy.zeros', 'np.zeros', (['(GRID_X, GRID_Y)'], {}), '((GRID_X, GRID_Y))\n', (1727, 1745), True, 'import numpy as np\n'), ((1760, 1838), 'numpy.zeros', 'np.zeros', (['(gym_swarm_env.observation_space.n, gym_swarm_env.action_space.size)'], {}), '((gym_swarm_env.observation_space.n, gym_swarm_env.action_space.size))\n', (1768, 1838), True, 'import numpy as np\n'), ((1893, 1934), 'numpy.zeros', 'np.zeros', (['gym_swarm_env.action_space.size'], {}), '(gym_swarm_env.action_space.size)\n', (1901, 1934), True, 'import numpy as np\n'), ((3172, 3285), 'objects.SwarmSimulator', 'SwarmSimulator', (['ARENA_WIDTH', 'ARENA_HEIGHT', 'name_of_experiment', 'SWARM_SIZE', 'INPUT_TIME', 'GRID_X', 'GRID_Y', 'rl_sim'], {}), '(ARENA_WIDTH, ARENA_HEIGHT, name_of_experiment, SWARM_SIZE,\n INPUT_TIME, GRID_X, GRID_Y, rl_sim)\n', (3186, 3285), False, 'from objects import SwarmSimulator\n'), ((4535, 4563), 'os.path.isdir', 'os.path.isdir', (['sim.directory'], {}), '(sim.directory)\n', (4548, 4563), False, 'import os\n'), ((4840, 4868), 'os.path.isdir', 'os.path.isdir', (['sim.directory'], {}), '(sim.directory)\n', (4853, 4868), False, 'import os\n'), ((5054, 5073), 'os.mkdir', 'os.mkdir', (['directory'], {}), '(directory)\n', (5062, 5073), False, 'import os\n'), ((6167, 6179), 'arcade.run', 'arcade.run', ([], {}), '()\n', (6177, 6179), False, 'import arcade\n'), ((6307, 6327), 'random.uniform', 'random.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (6321, 6327), False, 'import random\n'), ((3722, 3771), 'os.path.isdir', 'os.path.isdir', (["('../outputs/' + name_of_experiment)"], {}), "('../outputs/' + name_of_experiment)\n", (3735, 3771), False, 'import os\n'), ((3786, 3830), 'os.mkdir', 'os.mkdir', (["('../outputs/' + name_of_experiment)"], {}), "('../outputs/' + name_of_experiment)\n", (3794, 3830), False, 'import os\n'), ((6845, 6874), 'random.randint', 'random.randint', (['(0)', '(GRID_X - 1)'], {}), '(0, GRID_X - 1)\n', (6859, 6874), False, 'import random\n'), ((6891, 6920), 'random.randint', 'random.randint', (['(0)', '(GRID_Y - 1)'], {}), '(0, GRID_Y - 1)\n', (6905, 6920), False, 'import random\n'), ((6491, 6519), 'numpy.argmax', 'np.argmax', (['q_table[state, :]'], {}), '(q_table[state, :])\n', (6500, 6519), True, 'import numpy as np\n'), ((8585, 8623), 'numpy.exp', 'np.exp', (['(-exploration_decay_rate * step)'], {}), '(-exploration_decay_rate * step)\n', (8591, 8623), True, 'import numpy as np\n'), ((4498, 4509), 'time.time', 'time.time', ([], {}), '()\n', (4507, 4509), False, 'import time\n'), ((4803, 4814), 'time.time', 'time.time', ([], {}), '()\n', (4812, 4814), False, 'import time\n'), ((4679, 4690), 'time.time', 'time.time', ([], {}), '()\n', (4688, 4690), False, 'import time\n'), ((4984, 4995), 'time.time', 'time.time', ([], {}), '()\n', (4993, 4995), False, 'import time\n'), ((7623, 7652), 'numpy.max', 'np.max', (['q_table[new_state, :]'], {}), '(q_table[new_state, :])\n', (7629, 7652), True, 'import numpy as np\n')] |
from helpers import *
from discord.ext import commands
from discord.ext.commands import Cog, Bot, command, Context
import database as db
import discord
import asyncio
def setup(bot):
bot.add_cog(Commands(bot))
class Commands(Cog):
def __init__(self, bot: Bot):
self.bot = bot
# List spread across pages
async def spread_list(self, res, title, no_res_desc, ctx):
page = 1
total = total_pages(len(res))
if total == 0:
await ctx.send(embed=gen_embed(title, "\U0000274C " + no_res_desc))
else:
# Send message and add reactions
msg: discord.Message = await ctx.send(embed=page_embed(page, res, bullet_list, title))
await add_nav_reactions(msg, page, total)
def check(rct, usr):
return rct.message.id == msg.id and usr != self.bot.user
while True:
try:
reaction, user = await self.bot.wait_for("reaction_add", check=check, timeout=timeout)
emoji = str(reaction.emoji)
if user == ctx.author and (emoji == left or emoji == right):
# Change page
if emoji == left:
# If left reacted on first page, don't decrease page
if page != 1:
page -= 1
else:
# If right reacted on last page, don't increase page
if page != total:
page += 1
# Send/Edit message
msg = await msg_embed_nav(ctx, msg, page_embed(page, res, bullet_list, title), page, total)
# Remove reaction
elif not from_dm(ctx):
await reaction.remove(user)
except asyncio.TimeoutError:
await msg_timeout(ctx, msg, title)
break
# List all TV shows
@command(
aliases=["shows"],
name="tvshows",
help="Lists available TV Shows.")
async def tv_shows(self, ctx: Context):
tv_shows = db.get_all_tv_shows()
title = "TV Shows"
no_res_desc = "No TV Shows available"
await self.spread_list(tv_shows, title, no_res_desc, ctx)
# List subscriptions
@command(
aliases=["subs"],
help="Lists subscriptions.")
async def subscriptions(self, ctx: Context):
subs = db.get_subscriptions(ctx.author.id)
title = "Subscriptions"
no_res_desc = "You have no subscriptions"
await self.spread_list(subs, title, no_res_desc, ctx)
# Change notification setting for TV Show
@command(
aliases=["sub"],
help="Search for a TV show to which you want to subscribe / unsubscribe. When subscribed to a TV show, you will"
" receive a notification when a new episode of that TV show has been added to the server.")
async def subscribe(self, ctx, *, search_term):
res = db.search_tv_show(search_term)
length = len(res)
title = "Subscribe"
def approve_embed(desc):
return gen_embed(title, desc)
async def approve(show):
tv_show_id = show[0]
tv_show = show[1]
discord_id = ctx.author.id
# Define choice emojis
yes = "\U00002705"
no = "\U0000274C"
is_subscribed = db.is_subscribed(discord_id, tv_show_id)
# Check if already subscribed to TV show
if is_subscribed:
embed = approve_embed(f"\U00002757 You are currently subscribed to {tv_show}. Do you want to "
f"unsubscribe?")
embed_yes = approve_embed(f"{yes} Unsubscribed from {tv_show}")
embed_no = approve_embed(f"{no} Cancelled subscription cancellation of {tv_show}")
else:
embed = approve_embed(f"\U00002753 Do you want to subscribe to {tv_show}?")
embed_yes = approve_embed(f"{yes} Subscribed to {tv_show}")
embed_no = approve_embed(f"{no} Cancelled subscription for {tv_show}")
# Send message and add reactions
msg: discord.Message = await ctx.send(embed=embed)
await msg.add_reaction(yes)
await msg.add_reaction(no)
def check(rct, usr):
return rct.message.id == msg.id and usr != self.bot.user
while True:
try:
reaction, user = await self.bot.wait_for("reaction_add", check=check, timeout=timeout)
emoji = str(reaction.emoji)
# If reaction on correct message equals yes or no AND if reacted by correct user
if user == ctx.author and (emoji == yes or emoji == no):
# Set correct embed
if emoji == yes:
if is_subscribed:
db.unsubscribe(discord_id, tv_show_id)
else:
db.subscribe(discord_id, tv_show_id)
await msg_embed(ctx, msg, embed_yes)
else:
await msg_embed(ctx, msg, embed_no)
break
# Remove reaction
if not from_dm(ctx):
await reaction.remove(user)
except asyncio.TimeoutError:
await msg_timeout(ctx, msg, title)
break
# If no results
if length == 0:
await ctx.send(embed=approve_embed("\U0000274C No results"))
# If one result
elif length == 1:
await approve(res[0])
# If many results
else:
page = 1
total = total_pages(length)
add_msg = "Send the number, corresponding to the show to which you want to subscribe, in a new message."
# Send message and add reactions
msg: discord.Message = await ctx.send(embed=page_embed(page, res, number_list, title, add_msg=add_msg))
await add_nav_reactions(msg, page, total)
def reaction_check(rct, usr):
return rct.message.id == msg.id and usr != self.bot.user
def message_check(message):
try:
num = int(message.content)
return (1 <= num <= length) and message.author == ctx.author
except ValueError:
return False
while True:
reaction_task = asyncio.create_task(self.bot.wait_for("reaction_add", check=reaction_check))
message_task = asyncio.create_task(self.bot.wait_for("message", check=message_check))
done, pending = await asyncio.wait([reaction_task, message_task], timeout=timeout,
return_when=asyncio.FIRST_COMPLETED)
# Reaction on message
if reaction_task in done:
for task in done:
reaction, user = await task
emoji = str(reaction.emoji)
if user == ctx.author and (emoji == left or emoji == right):
# Change page
if emoji == left:
# If left reacted on first page, don't decrease page
if page != 1:
page -= 1
else:
# If right reacted on last page, don't increase page
if page != total:
page += 1
# Send/Edit message
msg = await msg_embed_nav(ctx, msg, page_embed(page, res, number_list, title, add_msg=add_msg),
page, total)
# Remove reaction
elif not from_dm(ctx):
await reaction.remove(user)
# Message containing number
elif message_task in done:
for task in done:
message = await task
num = int(message.content)
await msg.delete()
if not from_dm(ctx):
await message.delete()
await approve(res[num - 1])
# Timeout
else:
await msg_timeout(ctx, msg, title)
break
# If no search term provided
@subscribe.error
async def subscribe_error(self, ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send(embed=gen_embed("Error", f"Please enter (parts of) the TV show's name to which you want to "
f"subscribe.\n Command usage: "
f"`.sub | .subscribe {ctx.command.signature}`")
)
@command(help="Shows this message.")
async def help(self, ctx):
embed = gen_embed('Available Commands', 'Below commands can be executed:')
for command in self.bot.commands:
names = command.aliases
names.append(command.name)
title = '.' + ' | .'.join(names)
if command.signature:
title += f' {command.signature}'
embed.add_field(name=title, value=command.help, inline=False)
await ctx.send(embed=embed)
| [
"database.subscribe",
"database.is_subscribed",
"database.get_subscriptions",
"database.get_all_tv_shows",
"asyncio.wait",
"database.unsubscribe",
"database.search_tv_show",
"discord.ext.commands.command"
] | [((2097, 2173), 'discord.ext.commands.command', 'command', ([], {'aliases': "['shows']", 'name': '"""tvshows"""', 'help': '"""Lists available TV Shows."""'}), "(aliases=['shows'], name='tvshows', help='Lists available TV Shows.')\n", (2104, 2173), False, 'from discord.ext.commands import Cog, Bot, command, Context\n'), ((2464, 2518), 'discord.ext.commands.command', 'command', ([], {'aliases': "['subs']", 'help': '"""Lists subscriptions."""'}), "(aliases=['subs'], help='Lists subscriptions.')\n", (2471, 2518), False, 'from discord.ext.commands import Cog, Bot, command, Context\n'), ((2833, 3069), 'discord.ext.commands.command', 'command', ([], {'aliases': "['sub']", 'help': '"""Search for a TV show to which you want to subscribe / unsubscribe. When subscribed to a TV show, you will receive a notification when a new episode of that TV show has been added to the server."""'}), "(aliases=['sub'], help=\n 'Search for a TV show to which you want to subscribe / unsubscribe. When subscribed to a TV show, you will receive a notification when a new episode of that TV show has been added to the server.'\n )\n", (2840, 3069), False, 'from discord.ext.commands import Cog, Bot, command, Context\n'), ((9527, 9562), 'discord.ext.commands.command', 'command', ([], {'help': '"""Shows this message."""'}), "(help='Shows this message.')\n", (9534, 9562), False, 'from discord.ext.commands import Cog, Bot, command, Context\n'), ((2263, 2284), 'database.get_all_tv_shows', 'db.get_all_tv_shows', ([], {}), '()\n', (2282, 2284), True, 'import database as db\n'), ((2600, 2635), 'database.get_subscriptions', 'db.get_subscriptions', (['ctx.author.id'], {}), '(ctx.author.id)\n', (2620, 2635), True, 'import database as db\n'), ((3160, 3190), 'database.search_tv_show', 'db.search_tv_show', (['search_term'], {}), '(search_term)\n', (3177, 3190), True, 'import database as db\n'), ((3583, 3623), 'database.is_subscribed', 'db.is_subscribed', (['discord_id', 'tv_show_id'], {}), '(discord_id, tv_show_id)\n', (3599, 3623), True, 'import database as db\n'), ((7168, 7270), 'asyncio.wait', 'asyncio.wait', (['[reaction_task, message_task]'], {'timeout': 'timeout', 'return_when': 'asyncio.FIRST_COMPLETED'}), '([reaction_task, message_task], timeout=timeout, return_when=\n asyncio.FIRST_COMPLETED)\n', (7180, 7270), False, 'import asyncio\n'), ((5204, 5242), 'database.unsubscribe', 'db.unsubscribe', (['discord_id', 'tv_show_id'], {}), '(discord_id, tv_show_id)\n', (5218, 5242), True, 'import database as db\n'), ((5311, 5347), 'database.subscribe', 'db.subscribe', (['discord_id', 'tv_show_id'], {}), '(discord_id, tv_show_id)\n', (5323, 5347), True, 'import database as db\n')] |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import numpy as np
class DMatrix:
def __init__(self, data_arr, missing={np.nan, 0}):
"""
:param data_arr: 样本特征 (不含标签)
:param missing: 缺失值的集合, 若特征值在此集合中, 则认为其为缺失值
"""
# N 样本总个数( 包含缺出现缺失值的样本 )
# m 特征的总数
self.N, self.m = np.shape(data_arr)
# row_index 样本行的索引
self.row_index = list(range(self.N))
# 样本行
self.row_data = data_arr
# 所有特征对应的块集合
self.sorted_pages = []
# 不同特征中出现过特征缺失值的行的集合
# self.missing_value_pages = []
for i in range(self.m): # 遍历所有的特征
feature = data_arr[:, i] # 特征 i 拎出来 shape:(N,)
feature_index = []
for rid in range(self.N):
if feature[rid] not in missing: # 特征值 不在 缺失值集合中
feature_index.append((feature[rid], rid)) # (特征值, 样本标号)
# 按照特征值的大小排序
sorted_feature_index = sorted(feature_index, key=lambda t: t[0])
self.sorted_pages.append(sorted_feature_index)
| [
"numpy.shape"
] | [((326, 344), 'numpy.shape', 'np.shape', (['data_arr'], {}), '(data_arr)\n', (334, 344), True, 'import numpy as np\n')] |
from bs4 import BeautifulSoup
import requests
import pandas as pd
url = 'https://mexico.as.com/resultados/futbol/mexico_clausura/clasificacion/'
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
#Equipos
eq = soup.find_all('span', class_='nombre-equipo')
equipos = list()
count = 0
for i in eq:
if count < 18:
equipos.append(i.text)
else:
break
count += 1
#Puntos
pt = soup.find_all('td', class_='destacado')
#print(eq)
puntos = list()
count = 0
for i in pt:
if count < 18:
puntos.append(i.text)
else:
break
count += 1
df = pd.DataFrame({'Nombre': equipos, 'Puntos': puntos}, index=list(range(1,19)))
df.to_csv('ClasificacionLigaMX.csv', index=True) | [
"bs4.BeautifulSoup",
"requests.get"
] | [((153, 170), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (165, 170), False, 'import requests\n'), ((178, 220), 'bs4.BeautifulSoup', 'BeautifulSoup', (['page.content', '"""html.parser"""'], {}), "(page.content, 'html.parser')\n", (191, 220), False, 'from bs4 import BeautifulSoup\n')] |
import inspect
from flask import render_template, request, jsonify
from ..configurables import app
from .. import metrics
from ..metrics import metric_classes
def get_metrics(add_class=False):
records = []
for name, metric in metric_classes.iteritems():
if metric.show_in_ui:
new_record = {
'name' : name,
'id' : metric.id,
'label': metric.label,
'description' : metric.description,
}
if add_class:
new_record['metricClass'] = metric
records.append(new_record)
return sorted(records, key=lambda r: r['label'])
@app.route('/metrics/')
def metrics_index():
"""
Renders a page which will fetch a list of all metrics.
"""
return render_template('metrics.html', metrics=get_metrics(add_class=True))
@app.route('/metrics/list/')
def metrics_list():
"""
Returns a JSON response of the format:
{'metrics' : [
{
'id' : 1,
'name' : MetricClassName
'label' : 'Label',
'description' : 'This is a long description of what the metric does'
}
]
}
"""
records = get_metrics()
return jsonify(metrics=records)
@app.route('/metrics/configure/<string:name>', methods=['GET', 'POST'])
def metrics_configure(name):
"""
Generic endpoint that renders an html form for a specific metric
Parameters:
name : the name of the wikimetrics.metrics.Metric subclass desired
Returns:
if validation passes or is a get, the form to edit the metric
if validation fails, the form with the relevant errors
"""
if request.method == 'POST':
metric_form = metric_classes[name](request.form)
metric_form.validate()
elif request.method == 'GET':
metric_form = metric_classes[name]()
return render_template(
'forms/metric_configuration.html',
form=metric_form,
action=request.path,
)
| [
"flask.render_template",
"flask.jsonify"
] | [((1298, 1322), 'flask.jsonify', 'jsonify', ([], {'metrics': 'records'}), '(metrics=records)\n', (1305, 1322), False, 'from flask import render_template, request, jsonify\n'), ((1977, 2071), 'flask.render_template', 'render_template', (['"""forms/metric_configuration.html"""'], {'form': 'metric_form', 'action': 'request.path'}), "('forms/metric_configuration.html', form=metric_form, action\n =request.path)\n", (1992, 2071), False, 'from flask import render_template, request, jsonify\n')] |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name='pyramid_zipkin-example',
version='0.1',
author='OpenZipkin',
author_email='<EMAIL>',
license='Apache 2.0',
url='https://github.com/openzipkin/pyramid_zipkin-example',
description='See how much time python services spend on an http request',
install_requires=[
'pyramid',
'requests',
'pyramid_zipkin',
]
)
| [
"setuptools.setup"
] | [((72, 402), 'setuptools.setup', 'setup', ([], {'name': '"""pyramid_zipkin-example"""', 'version': '"""0.1"""', 'author': '"""OpenZipkin"""', 'author_email': '"""<EMAIL>"""', 'license': '"""Apache 2.0"""', 'url': '"""https://github.com/openzipkin/pyramid_zipkin-example"""', 'description': '"""See how much time python services spend on an http request"""', 'install_requires': "['pyramid', 'requests', 'pyramid_zipkin']"}), "(name='pyramid_zipkin-example', version='0.1', author='OpenZipkin',\n author_email='<EMAIL>', license='Apache 2.0', url=\n 'https://github.com/openzipkin/pyramid_zipkin-example', description=\n 'See how much time python services spend on an http request',\n install_requires=['pyramid', 'requests', 'pyramid_zipkin'])\n", (77, 402), False, 'from setuptools import setup\n')] |
import os
from glob import glob
import tensorflow as tf
from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2, preprocess_input
from tensorflow.keras.preprocessing.image import img_to_array, load_img
from tensorflow.keras.models import Model, load_model
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Activation, Flatten, Dense, Input, BatchNormalization
from model.baseline import MyModel
import numpy as np
import cv2
from tensorflow.keras.optimizers import SGD
TRAIN_DIR = './dataset/PKLot/custom_dataset/train/'
VALID_DIR = './dataset/PKLot/custom_dataset/valid/'
ROOT_DIR = '../../dataset/Pklot/PKLotSegmented/'
WIDTH, HEIGHT = 39,72
NB_EPOCHS = 5
LR = 1e-4
BATCH_SIZE = 32
# print("Setup model")
#base_model = load_model('./output')
base_model = MobileNetV2(weights='imagenet', include_top=True)
print(base_model.summary())
model = Model(inputs=base_model.input, outputs=base_model.layers[-2].output)
#opt = SGD(lr = LR, momentum=0.9, decay = LR/NB_EPOCHS)
#model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])
def extract_features(list_img_path, features_path = './features',label_path_to_save = './'):
ground_truths = []
for img in list_img_path:
img = img.replace("\\","/")
label = img.split("/")[-2]
img_name = img.split("/")[-1]
img_name = img_name.replace(".jpg", ".npy")
if label == "Empty":
ground_truths.append(0)
else:
ground_truths.append(1)
image = cv2.imread(img)
image = cv2.resize(image, (224, 224))
image_x = np.expand_dims(image, axis=0)
image_x = preprocess_input(image_x)
feature = model.predict(image_x)
os.makedirs(os.path.dirname(features_path), exist_ok=True)
np.save(features_path + img_name, feature)
np.save(label_path_to_save,ground_truths)
if __name__ == "__main__":
# occupied_val = VALID_DIR + 'Occupied/*.jpg'
# empty_val = VALID_DIR + 'Empty/*.jpg'
# valid_images = list(glob(occupied_val) + glob(empty_val))
occupied_train = TRAIN_DIR + 'Occupied/*.jpg'
empty_train = TRAIN_DIR + 'Empty/*.jpg'
train_images = list(glob(occupied_train) + glob(empty_train))
extract_features(train_images, './features/PKLot/Train/', './features/PKLot/train_label.npy')
occupied_valid = VALID_DIR + 'Occupied/*.jpg'
empty_valid = VALID_DIR + 'Empty/*.jpg'
valid_images = list(glob(occupied_valid) + glob(empty_valid))
extract_features(valid_images, './features/PKLot/Valid/', './features/PKLot/valid_label.npy') | [
"tensorflow.keras.applications.mobilenet_v2.MobileNetV2",
"os.path.dirname",
"glob.glob",
"tensorflow.keras.applications.mobilenet_v2.preprocess_input",
"numpy.expand_dims",
"tensorflow.keras.models.Model",
"cv2.resize",
"cv2.imread",
"numpy.save"
] | [((816, 865), 'tensorflow.keras.applications.mobilenet_v2.MobileNetV2', 'MobileNetV2', ([], {'weights': '"""imagenet"""', 'include_top': '(True)'}), "(weights='imagenet', include_top=True)\n", (827, 865), False, 'from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2, preprocess_input\n'), ((906, 974), 'tensorflow.keras.models.Model', 'Model', ([], {'inputs': 'base_model.input', 'outputs': 'base_model.layers[-2].output'}), '(inputs=base_model.input, outputs=base_model.layers[-2].output)\n', (911, 974), False, 'from tensorflow.keras.models import Model, load_model\n'), ((1967, 2009), 'numpy.save', 'np.save', (['label_path_to_save', 'ground_truths'], {}), '(label_path_to_save, ground_truths)\n', (1974, 2009), True, 'import numpy as np\n'), ((1615, 1630), 'cv2.imread', 'cv2.imread', (['img'], {}), '(img)\n', (1625, 1630), False, 'import cv2\n'), ((1652, 1681), 'cv2.resize', 'cv2.resize', (['image', '(224, 224)'], {}), '(image, (224, 224))\n', (1662, 1681), False, 'import cv2\n'), ((1705, 1734), 'numpy.expand_dims', 'np.expand_dims', (['image'], {'axis': '(0)'}), '(image, axis=0)\n', (1719, 1734), True, 'import numpy as np\n'), ((1758, 1783), 'tensorflow.keras.applications.mobilenet_v2.preprocess_input', 'preprocess_input', (['image_x'], {}), '(image_x)\n', (1774, 1783), False, 'from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2, preprocess_input\n'), ((1915, 1957), 'numpy.save', 'np.save', (['(features_path + img_name)', 'feature'], {}), '(features_path + img_name, feature)\n', (1922, 1957), True, 'import numpy as np\n'), ((1855, 1885), 'os.path.dirname', 'os.path.dirname', (['features_path'], {}), '(features_path)\n', (1870, 1885), False, 'import os\n'), ((2335, 2355), 'glob.glob', 'glob', (['occupied_train'], {}), '(occupied_train)\n', (2339, 2355), False, 'from glob import glob\n'), ((2358, 2375), 'glob.glob', 'glob', (['empty_train'], {}), '(empty_train)\n', (2362, 2375), False, 'from glob import glob\n'), ((2615, 2635), 'glob.glob', 'glob', (['occupied_valid'], {}), '(occupied_valid)\n', (2619, 2635), False, 'from glob import glob\n'), ((2638, 2655), 'glob.glob', 'glob', (['empty_valid'], {}), '(empty_valid)\n', (2642, 2655), False, 'from glob import glob\n')] |
import argparse
import matplotlib.pyplot as plt
import meshcut
import numpy as np
import pandas
import seaborn as sns
import pandas as pd
import sys, os
import math
#from scipy.stats import norm
SAVE_PATH = os.path.join(os.path.expanduser("~"),'PycharmProjects/Gibson_Exercise/examples/plot_result/')
WAY_PATH = os.path.join(os.path.expanduser("~"),'PycharmProjects/Gibson_Exercise/examples/plot_result/')
def load_obj(fn):
verts = []
faces = []
with open(fn) as f:
for line in f:
if line[:2] == 'v ':
verts.append(list(map(float, line.strip().split()[1:4])))
if line[:2] == 'f ':
face = [int(item.split('/')[0]) for item in line.strip().split()[-3:]]
faces.append(face)
verts = np.array(verts)
faces = np.array(faces) - 1
return verts, faces
def add_arrow(line, position=None, direction='right', size=15, color='dodgerblue'):
xdata = line.get_xdata()
ydata = line.get_ydata()
if position is None:
position = xdata.mean()
start_ind = np.argmin(np.absolute(xdata - position))
if direction == 'right':
end_ind = start_ind + 1
else:
end_ind = start_ind - 1
line.axes.annotate('',
xytext=(xdata[start_ind], ydata[start_ind]),
xy=(xdata[end_ind], ydata[end_ind]),
arrowprops=dict(arrowstyle="->", color=color),
size=size
)
def mesh(model_id="", waypoint=False):
C1 = '\033[91m'
C1END = '\033[0m'
print(C1 + "PLOTTING EPISODE:" + C1END)
plt.style.use('default') # switches back to matplotlib style
fn = os.path.join(os.path.expanduser("~"),
"PycharmProjects/Gibson_Exercise/gibson/assets/dataset/") + str(model_id) + "/mesh_z_up.obj"
verts, faces = load_obj(fn)
z = np.min(verts[:, -1]) + 0.5 # your robot height
cross_section = meshcut.cross_section(verts, faces, plane_orig=(0, 0, z), plane_normal=(0, 0, 1))
plt.figure(figsize=(8,8))
for item in cross_section:
for i in range(len(item) - 1):
plt.plot(item[i:i + 2, 0], item[i:i + 2, 1], 'k')
plt.title('Map of Navigation')
plt.xlabel('X Position'); plt.ylabel('Y Position')
plt.grid(True)
if waypoint:
#df = pandas.read_csv(WAY_PATH + str('aloha_waypoints_sort_test.csv'))
#df = pandas.read_csv(WAY_PATH + str('aloha_waypoints_clipped_sort.csv'))
df = pandas.read_csv(WAY_PATH + str('euharlee_waypoints_sort_test.csv'))
#df = pandas.read_csv(WAY_PATH + str('euharlee_waypoints_clipped_sort.csv'))
points = df.values
length = len(points)
sp = np.zeros((length, 3)); ang = np.zeros((length, 1)); gp = np.zeros((length, 3))
complexity = np.zeros((length, 1))
for r in range(length):
sp[r] = np.array([points[r][2], points[r][3], points[r][4]])
ang[r] = np.array([points[r][5]])
gp[r] = np.array([points[r][6], points[r][7], points[r][8]])
complexity[r] = np.array([points[r][10]/points[r][9]])
for k in range(length):
plt.plot(sp[k][0], sp[k][1], 'r*')
plt.plot(gp[k][0], gp[k][1], 'g*')
line=plt.plot([sp[k][0], gp[k][0]], [sp[k][1], gp[k][1]], color='dodgerblue', linewidth=1)
m1 = (sp[k][0] + gp[k][0]) / 2
m2 = (sp[k][1] + gp[k][1]) / 2
plt.annotate(s='', xy=(gp[k][0],gp[k][1]), xytext=(sp[k][0],sp[k][1]), arrowprops=dict(arrowstyle='->',color='grey'))
#plt.arrow([sp[k][0], gp[k][0]], [sp[k][1], gp[k][1]], [dx],[dy], shape='full', lw=0, length_includes_head=True, head_width=.05)
print("%i Waypoint Navigation Complexity ---> %.3f" % (k+1,complexity[k]))
debug=1
if debug:
plt.savefig(os.path.join(SAVE_PATH + 'waypoints_map_test.png'))
#plt.savefig(os.path.join(SAVE_PATH + 'waypoints_map.png'))
plt.show()
def main(raw_args=None):
"This function shows that analysis of training process"
deb = bool(0)
mesh(model_id=raw_args.model, waypoint=True)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--model', type=str, default="Euharlee")
args = parser.parse_args()
main(args)
| [
"matplotlib.pyplot.grid",
"argparse.ArgumentParser",
"matplotlib.pyplot.ylabel",
"meshcut.cross_section",
"matplotlib.pyplot.xlabel",
"numpy.absolute",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.style.use",
"os.path.join",
"numpy.array",
"matplotlib.pyplot.figure",
"numpy.zeros",
"numpy.mi... | [((221, 244), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (239, 244), False, 'import sys, os\n'), ((326, 349), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (344, 349), False, 'import sys, os\n'), ((705, 720), 'numpy.array', 'np.array', (['verts'], {}), '(verts)\n', (713, 720), True, 'import numpy as np\n'), ((1418, 1442), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""default"""'], {}), "('default')\n", (1431, 1442), True, 'import matplotlib.pyplot as plt\n'), ((1723, 1809), 'meshcut.cross_section', 'meshcut.cross_section', (['verts', 'faces'], {'plane_orig': '(0, 0, z)', 'plane_normal': '(0, 0, 1)'}), '(verts, faces, plane_orig=(0, 0, z), plane_normal=(0, \n 0, 1))\n', (1744, 1809), False, 'import meshcut\n'), ((1807, 1833), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 8)'}), '(figsize=(8, 8))\n', (1817, 1833), True, 'import matplotlib.pyplot as plt\n'), ((1949, 1979), 'matplotlib.pyplot.title', 'plt.title', (['"""Map of Navigation"""'], {}), "('Map of Navigation')\n", (1958, 1979), True, 'import matplotlib.pyplot as plt\n'), ((1981, 2005), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""X Position"""'], {}), "('X Position')\n", (1991, 2005), True, 'import matplotlib.pyplot as plt\n'), ((2007, 2031), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Y Position"""'], {}), "('Y Position')\n", (2017, 2031), True, 'import matplotlib.pyplot as plt\n'), ((2033, 2047), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (2041, 2047), True, 'import matplotlib.pyplot as plt\n'), ((3740, 3819), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), '(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n', (3763, 3819), False, 'import argparse\n'), ((730, 745), 'numpy.array', 'np.array', (['faces'], {}), '(faces)\n', (738, 745), True, 'import numpy as np\n'), ((982, 1011), 'numpy.absolute', 'np.absolute', (['(xdata - position)'], {}), '(xdata - position)\n', (993, 1011), True, 'import numpy as np\n'), ((1658, 1678), 'numpy.min', 'np.min', (['verts[:, -1]'], {}), '(verts[:, -1])\n', (1664, 1678), True, 'import numpy as np\n'), ((2417, 2438), 'numpy.zeros', 'np.zeros', (['(length, 3)'], {}), '((length, 3))\n', (2425, 2438), True, 'import numpy as np\n'), ((2446, 2467), 'numpy.zeros', 'np.zeros', (['(length, 1)'], {}), '((length, 1))\n', (2454, 2467), True, 'import numpy as np\n'), ((2474, 2495), 'numpy.zeros', 'np.zeros', (['(length, 3)'], {}), '((length, 3))\n', (2482, 2495), True, 'import numpy as np\n'), ((2511, 2532), 'numpy.zeros', 'np.zeros', (['(length, 1)'], {}), '((length, 1))\n', (2519, 2532), True, 'import numpy as np\n'), ((3529, 3539), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3537, 3539), True, 'import matplotlib.pyplot as plt\n'), ((1897, 1946), 'matplotlib.pyplot.plot', 'plt.plot', (['item[i:i + 2, 0]', 'item[i:i + 2, 1]', '"""k"""'], {}), "(item[i:i + 2, 0], item[i:i + 2, 1], 'k')\n", (1905, 1946), True, 'import matplotlib.pyplot as plt\n'), ((2570, 2622), 'numpy.array', 'np.array', (['[points[r][2], points[r][3], points[r][4]]'], {}), '([points[r][2], points[r][3], points[r][4]])\n', (2578, 2622), True, 'import numpy as np\n'), ((2635, 2659), 'numpy.array', 'np.array', (['[points[r][5]]'], {}), '([points[r][5]])\n', (2643, 2659), True, 'import numpy as np\n'), ((2671, 2723), 'numpy.array', 'np.array', (['[points[r][6], points[r][7], points[r][8]]'], {}), '([points[r][6], points[r][7], points[r][8]])\n', (2679, 2723), True, 'import numpy as np\n'), ((2743, 2783), 'numpy.array', 'np.array', (['[points[r][10] / points[r][9]]'], {}), '([points[r][10] / points[r][9]])\n', (2751, 2783), True, 'import numpy as np\n'), ((2812, 2846), 'matplotlib.pyplot.plot', 'plt.plot', (['sp[k][0]', 'sp[k][1]', '"""r*"""'], {}), "(sp[k][0], sp[k][1], 'r*')\n", (2820, 2846), True, 'import matplotlib.pyplot as plt\n'), ((2850, 2884), 'matplotlib.pyplot.plot', 'plt.plot', (['gp[k][0]', 'gp[k][1]', '"""g*"""'], {}), "(gp[k][0], gp[k][1], 'g*')\n", (2858, 2884), True, 'import matplotlib.pyplot as plt\n'), ((2893, 2982), 'matplotlib.pyplot.plot', 'plt.plot', (['[sp[k][0], gp[k][0]]', '[sp[k][1], gp[k][1]]'], {'color': '"""dodgerblue"""', 'linewidth': '(1)'}), "([sp[k][0], gp[k][0]], [sp[k][1], gp[k][1]], color='dodgerblue',\n linewidth=1)\n", (2901, 2982), True, 'import matplotlib.pyplot as plt\n'), ((3413, 3463), 'os.path.join', 'os.path.join', (["(SAVE_PATH + 'waypoints_map_test.png')"], {}), "(SAVE_PATH + 'waypoints_map_test.png')\n", (3425, 3463), False, 'import sys, os\n'), ((1499, 1522), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (1517, 1522), False, 'import sys, os\n')] |
"""A module for the uFJC single-chain model in the isometric ensemble.
This module consist of the class ``uFJCIsometric`` which contains
methods for computing single-chain quantities
in the isometric (constant end-to-end vector) thermodynamic ensemble.
Example:
Import and instantiate the class:
>>> from ufjc.isometric import uFJCIsometric
>>> class_instance = uFJCIsometric()
"""
# Import internal modules
from .monte_carlo import MHMCMC
from .isotensional import uFJCIsotensional
# Import external modules
import numpy as np
import numpy.linalg as la
class uFJCIsometric(uFJCIsotensional):
"""The uFJC single-chain model class for the isometric ensemble.
This class contains methods for computing single-chain quantities
in the isometric (constant end-to-end vector) thermodynamic ensemble.
It inherits all attributes and methods from the ``uFJCIsotensional``
class, which inherits all attributes and methods from the
``BasicUtility`` class.
"""
def __init__(self):
"""Initializes the ``uFJCIsometric`` class.
Initialize and inherit all attributes and methods
from a ``uFJCIsotensional`` class instance.
"""
uFJCIsotensional.__init__(self)
def eta_isometric(self, gamma, **kwargs):
r"""Main function for the isometric :math:`\eta(\gamma)`.
This is the main function utilized to compute the isometric
nondimensional single-chain mechanical response.
Keyword arguments specify and are passed onto the method.
Args:
gamma (array_like): The nondimensional end-to-end length(s).
**kwargs: Arbitrary keyword arguments.
Passed to the chosen method.
Returns:
numpy.ndarray: The nondimensional force(s).
Example:
Compute the nondimensional force for an eight-link Morse-FJC at a
nondimensional end-to-end length of 0.8 in the isometric ensemble,
using the Legendre transformation method from the isotensional
ensemble, and using the reduced asymptotic approach to compute
quantities in the isotensional ensemble:
>>> from ufjc import uFJC
>>> model = uFJC(N_b=8, potential='morse')
>>> model.eta_isometric([0, 0.8], \
... method='legendre', approach='reduced')
array([0. , 4.41715473])
Warning:
Only the Legendre transformation method is currently unavailable:
>>> from ufjc import uFJC
>>> uFJC().eta_isometric(0.8, method='exact')
array([nan])
"""
gamma = self.np_array(gamma)
method = kwargs.get('method', 'legendre')
if method == 'legendre':
return self.eta_isometric_legendre(gamma, **kwargs)
else:
return np.nan*gamma
def eta_isometric_legendre(self, gamma, **kwargs):
r"""The Legendre transformation method of approximating
the isometric :math:`\eta(\gamma)`.
This function uses the Legendre transformation method to obtain an
approximate isometric nondimensional single-chain mechanical response.
The result is to simply use the isotensional :math:`\eta(\gamma)`,
and this approximation is asymptotically valid for :math:`N_b\gg 1`
and appreciable loads :cite:`buche2020statistical`.
Args:
gamma (array_like): The nondimensional end-to-end length(s).
**kwargs: Arbitrary keyword arguments.
Passed to ``_eta_isotensional``.
Returns:
numpy.ndarray: The nondimensional force(s).
Example:
Compute the nondimensional force at a large nondimensional
end-to-end length using the Legendre transformation method:
>>> from ufjc import uFJC
>>> model = uFJC()
>>> model.eta_isometric_legendre(1.3)
array([28.71102552])
"""
return self.eta_isotensional(gamma, **kwargs)
def gamma_isometric(self, eta, **kwargs):
r"""Main function for the isometric :math:`\gamma(\eta)`.
This function obtains the isometric nondimensional
single-chain mechanical response :math:`\gamma(\eta)`
by inverting the isometric :math:`\eta(\gamma)`.
Args:
eta (array_like): the nondimensional force(s).
**kwargs: Arbitrary keyword arguments.
Passed to ``_eta_isometric``.
Returns:
numpy.ndarray: The nondimensional end-to-end length(s).
Example:
Check that :math:`\gamma[\eta(\gamma)] = \gamma\,`:
>>> import numpy as np
>>> from ufjc import uFJC
>>> model = uFJC()
>>> def check_eta(gamma):
... eta_fun = lambda gamma: model.eta_isometric(gamma)
... gamma_fun = lambda eta: model.gamma_isometric(eta)
... return np.isclose(gamma_fun(eta_fun(gamma))[0], gamma)
>>> check_eta(np.random.rand())
True
"""
def eta_fun(gamma):
return self.eta_isometric(gamma, **kwargs)
return self.inv_fun_1D(eta, eta_fun)
def vartheta_isometric(self, gamma, **kwargs):
r"""Main function for the isometric :math:`\vartheta(\gamma)`.
This is the main function utilized to compute the nondimensional
Helmholtz free energy per link, an isometric quantity.
Keyword arguments specify and are passed onto the method.
Args:
gamma (array_like): The nondimensional end-to-end length(s).
**kwargs: Arbitrary keyword arguments.
Passed to the chosen method.
Returns:
numpy.ndarray: The nondimensional Helmholtz free energy per link.
Example:
Compute the nondimensional Helmholtz free energy per link
for an eight-link Morse-FJC at a
nondimensional end-to-end length of 0.8 in the isometric ensemble,
using the Legendre transformation method from the isotensional
ensemble, and using the reduced asymptotic approach to compute
quantities in the isotensional ensemble:
>>> from ufjc import uFJC
>>> model = uFJC(N_b=8, potential='morse')
>>> model.vartheta_isometric(0.8, \
... method='legendre', approach='reduced')
array([1.23847534])
Warning:
The exact method is currently unavailable:
>>> from ufjc import uFJC
>>> uFJC().vartheta_isometric(0.8, method='exact')
nan
"""
method = kwargs.get('method', 'legendre')
if method == 'exact':
return np.nan*gamma
elif method == 'legendre':
return self.vartheta_isometric_legendre(gamma, **kwargs)
def vartheta_isometric_legendre(self, gamma, **kwargs):
r"""The Legendre transformation method of approximating
the isometric :math:`\vartheta(\gamma)`.
This function uses the Legendre transformation method to obtain an
approximate isometric Helmholtz free energy per link.
The result is independent of the number of links :math:`N_b`, and
this approximation is asymptotically valid for :math:`N_b\gg 1`
and appreciable loads :cite:`buche2021chain`.
For example, using the reduced asymptotic approach, this is
.. math::
\vartheta(\gamma) \sim
\ln\left\{\frac{
\eta\exp[\eta\mathcal{L}(\eta)]}{\sinh(\eta)}\right\}
+ \beta u[\lambda(\eta)]
,
valid when :math:`\varepsilon\gg 1` and :math:`N_b\gg 1` are
simultaneously true.
Note that :math:`\eta=\eta(\gamma)` is implied, and obtained
through inverting the isotensional :math:`\gamma(\eta)`.
Args:
gamma (array_like): The nondimensional end-to-end length(s).
**kwargs: Arbitrary keyword arguments.
Passed to the chosen method.
Returns:
numpy.ndarray: The nondimensional Helmholtz free energy per link.
Example:
Approximate the nondimensional Helmholtz free energy per link
using the Legendre method and both asymptotic approaches:
>>> from ufjc import uFJC
>>> model = uFJC(potential='log-squared', varepsilon=23)
>>> model.vartheta_isometric_legendre(1.1)
array([1.90431381])
>>> model.vartheta_isometric_legendre(1.1, approach='reduced')
array([2.09238198])
Warning:
Only the asymptotic approaches are currently unavailable:
>>> from ufjc import uFJC
>>> model = uFJC(potential='log-squared', varepsilon=23)
>>> model.vartheta_isometric_legendre(1.1, approach='exact')
nan
"""
# Invert gamma=gamma(eta) for the corresponding eta
eta = self.eta_isotensional(gamma, **kwargs)
# Avoid overflow, important for integrating P_eq
eta[eta > self.maximum_exponent] = self.maximum_exponent
# Find the corresponding bond stretch under direct eta
lambda_ = 1 + self.delta_lambda(eta)
# Need to finish this portion
approach = kwargs.get('approach', 'asymptotic')
if approach == 'asymptotic':
Ln = self.langevin(eta)
coth = self.coth(eta)
return eta*Ln + self.log_over_sinh(eta) + \
self.varepsilon*(self.phi(lambda_) - self.phi(1)) + \
eta**2/self.kappa*(
(1 - Ln*coth)/(self.c + eta/self.kappa*coth)
) - np.log(1 + eta*coth/self.kappa)
elif approach == 'reduced':
return eta*self.langevin(eta) + self.log_over_sinh(eta) + \
self.varepsilon*(self.phi(lambda_) - self.phi(1))
else:
return np.nan*gamma
def beta_U_config(self, config):
r"""The nondimensional potential energy of a configuration.
This function provides the nondimensional potential energy
:math:`\beta U` given the configuration of the chain, i.e. the
vector position of each atom/hinge relative to the first one.
Args:
config (numpy.ndarray): The configuration of the chain,
a :math:`(N_b+1)`-by-3 numpy array.
Returns:
float: The nondimensional potential energy :math:`\beta U`.
Example:
Compute the potential energy of the uniformly-stretched
default initial configuration:
>>> from ufjc import uFJC
>>> model = uFJC(N_b=8, potential='lennard-jones')
>>> model.beta_U_config(1.1*model.init_config)
133.5368021523727
"""
beta_U = 0
for j in range(1, len(config)):
lambda_ = la.norm(config[j, :] - config[j - 1, :])
beta_U += self.beta_u(lambda_)
return beta_U
| [
"numpy.log",
"numpy.linalg.norm"
] | [((11454, 11494), 'numpy.linalg.norm', 'la.norm', (['(config[j, :] - config[j - 1, :])'], {}), '(config[j, :] - config[j - 1, :])\n', (11461, 11494), True, 'import numpy.linalg as la\n'), ((10199, 10234), 'numpy.log', 'np.log', (['(1 + eta * coth / self.kappa)'], {}), '(1 + eta * coth / self.kappa)\n', (10205, 10234), True, 'import numpy as np\n')] |
import inspect
import re
def debug_str(arg):
'''Return string of arg varible name and str(arg) value.'''
frame = inspect.currentframe().f_back
s = inspect.getframeinfo(frame).code_context[0]
r = re.search(r"\((.*)\)", s).group(1)
return str("{} = {}".format(r, arg))
def debug_print(arg):
'''Print arg varible name and str(arg) value.'''
frame = inspect.currentframe().f_back
s = inspect.getframeinfo(frame).code_context[0]
r = re.search(r"\((.*)\)", s).group(1)
print("{} = {}".format(r, arg))
DBGP = debug_print # shortened alias
DBGS = debug_str # shortened alias
| [
"re.search",
"inspect.currentframe",
"inspect.getframeinfo"
] | [((123, 145), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (143, 145), False, 'import inspect\n'), ((378, 400), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (398, 400), False, 'import inspect\n'), ((161, 188), 'inspect.getframeinfo', 'inspect.getframeinfo', (['frame'], {}), '(frame)\n', (181, 188), False, 'import inspect\n'), ((213, 239), 're.search', 're.search', (['"""\\\\((.*)\\\\)"""', 's'], {}), "('\\\\((.*)\\\\)', s)\n", (222, 239), False, 'import re\n'), ((416, 443), 'inspect.getframeinfo', 'inspect.getframeinfo', (['frame'], {}), '(frame)\n', (436, 443), False, 'import inspect\n'), ((468, 494), 're.search', 're.search', (['"""\\\\((.*)\\\\)"""', 's'], {}), "('\\\\((.*)\\\\)', s)\n", (477, 494), False, 'import re\n')] |
"""
Author: <NAME>
Date: 10 April 2021
"""
import logging
import os
from typing import List
from dataclasses import dataclass, asdict
import click
from click import Context
from sla_cli.src.cli.context import COMMAND_CONTEXT_SETTINGS
from sla_cli.src.cli.utils import kwargs_to_dataclass, default_from_context
from sla_cli.src.db.accessors import AccessorFactory
from sla_cli.src.download import Downloader, DownloaderOptions, DummyDownloader
from sla_cli.src.download.isic import IsicMetadataDownloader, IsicImageDownloader
from sla_cli.src.download.ph2 import Ph2Downloader
from sla_cli.src.download.pad_ufes_20 import PadUfes20Downloader
from sla_cli.src.download.mednode import MednodeDownloader
logger = logging.getLogger(__name__)
@dataclass
class DownloadParameters:
datasets: List[str]
directory: str
force: bool
clean: bool
skip: bool
metadata_as_name: bool
isic_meta: bool
@click.command(**COMMAND_CONTEXT_SETTINGS, short_help="Downloads available datasets.")
@click.argument("datasets", type=click.STRING, nargs=-1)
@click.option("-d", "--directory", type=click.STRING, cls=default_from_context("data_directory"), help="The destination directory for the downloaded content. Default is the current work directory.")
@click.option("-f", "--force", type=click.BOOL, is_flag=True, help="Force download a dataset, even if it already exists on the filesystem.")
@click.option("-c", "--clean", type=click.BOOL, is_flag=True, help="Remove archive files directly after extraction.")
@click.option("-s", "--skip", type=click.BOOL, is_flag=True, help="Skip the download phase, useful for running builds on previously downloaded archives.")
@click.option("--isic-meta", type=click.BOOL, is_flag=True, help="Download the ISIC Archive metadata instead of a dataset.")
@click.option("--metadata-as-name", type=click.BOOL, is_flag=True, help="Saves the dataset metadata as the dataset name. Helpful for viewing in excel, not optimal for ML pipelines.")
@kwargs_to_dataclass(DownloadParameters)
@click.pass_context
def download(ctx: Context, params: DownloadParameters):
datasets = AccessorFactory.create_datasets()
# Remove datasets that dont exist in the tool before continuing.
keep = []
for dataset in params.datasets:
if dataset in datasets.datasets.names:
keep.append(dataset)
else:
logger.warning(f"'{dataset}' does not exist for download, removing...")
params.datasets = keep
options = DownloaderOptions(
destination_directory=params.directory,
config=ctx.obj,
force=params.force,
metadata_as_name=params.metadata_as_name,
clean=params.clean,
skip=params.skip
)
# Download only the ISIC metadata.
if params.isic_meta:
options.url = datasets.datasets["ham10000"].info.download[0]
IsicMetadataDownloader(options=options)
else:
size = sum([datasets.datasets[dataset].info.size for dataset in params.datasets])
logger.info(f"Total size of requested download: {size} MB.")
for dataset in params.datasets:
# Get the downloader object for the given dataset.
downloader = downloader_factory(dataset)
# Add dataset to options.
options.dataset = dataset
options.url = datasets.datasets[dataset].info.download[0]
options.size = datasets.datasets[dataset].info.size
# Download the dataset.
downloader = downloader(options=options)
downloader.download()
def downloader_factory(dataset) -> Downloader:
"""
Creates a downloader depending on the dataset name based.
:param dataset: The dataset name to create a downloader for.
:return: A Downloader object suited for the specified dataset.
"""
return {
"bcn_20000": IsicImageDownloader,
"bcn_2020_challenge": IsicImageDownloader,
"brisbane_isic_challnge_2020": IsicImageDownloader,
"dermoscopedia_cc_by": IsicImageDownloader,
"ham10000": IsicImageDownloader,
"isic_2020_challenge_mskcc_contribution": IsicImageDownloader,
"isic_2020_vienna_part_1": IsicImageDownloader,
"isic_2020_vienna_part_2": IsicImageDownloader,
"jid_editorial_images_2018": IsicImageDownloader,
"mednode": MednodeDownloader,
"msk_1": IsicImageDownloader,
"msk_2": IsicImageDownloader,
"msk_3": IsicImageDownloader,
"msk_4": IsicImageDownloader,
"msk_5": IsicImageDownloader,
"pad_ufes_20": PadUfes20Downloader,
"ph2": Ph2Downloader,
"sonic": IsicImageDownloader,
"sydney_mia_smdc_2020_isic_challenge_contribution": IsicImageDownloader,
"uda_1": IsicImageDownloader,
"uda_2": IsicImageDownloader,
}.get(
dataset,
DummyDownloader
)
| [
"logging.getLogger",
"click.argument",
"sla_cli.src.download.isic.IsicMetadataDownloader",
"click.option",
"sla_cli.src.cli.utils.default_from_context",
"sla_cli.src.db.accessors.AccessorFactory.create_datasets",
"sla_cli.src.cli.utils.kwargs_to_dataclass",
"click.command",
"sla_cli.src.download.Dow... | [((724, 751), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (741, 751), False, 'import logging\n'), ((931, 1021), 'click.command', 'click.command', ([], {'short_help': '"""Downloads available datasets."""'}), "(**COMMAND_CONTEXT_SETTINGS, short_help=\n 'Downloads available datasets.')\n", (944, 1021), False, 'import click\n'), ((1018, 1073), 'click.argument', 'click.argument', (['"""datasets"""'], {'type': 'click.STRING', 'nargs': '(-1)'}), "('datasets', type=click.STRING, nargs=-1)\n", (1032, 1073), False, 'import click\n'), ((1274, 1418), 'click.option', 'click.option', (['"""-f"""', '"""--force"""'], {'type': 'click.BOOL', 'is_flag': '(True)', 'help': '"""Force download a dataset, even if it already exists on the filesystem."""'}), "('-f', '--force', type=click.BOOL, is_flag=True, help=\n 'Force download a dataset, even if it already exists on the filesystem.')\n", (1286, 1418), False, 'import click\n'), ((1415, 1536), 'click.option', 'click.option', (['"""-c"""', '"""--clean"""'], {'type': 'click.BOOL', 'is_flag': '(True)', 'help': '"""Remove archive files directly after extraction."""'}), "('-c', '--clean', type=click.BOOL, is_flag=True, help=\n 'Remove archive files directly after extraction.')\n", (1427, 1536), False, 'import click\n'), ((1533, 1696), 'click.option', 'click.option', (['"""-s"""', '"""--skip"""'], {'type': 'click.BOOL', 'is_flag': '(True)', 'help': '"""Skip the download phase, useful for running builds on previously downloaded archives."""'}), "('-s', '--skip', type=click.BOOL, is_flag=True, help=\n 'Skip the download phase, useful for running builds on previously downloaded archives.'\n )\n", (1545, 1696), False, 'import click\n'), ((1688, 1816), 'click.option', 'click.option', (['"""--isic-meta"""'], {'type': 'click.BOOL', 'is_flag': '(True)', 'help': '"""Download the ISIC Archive metadata instead of a dataset."""'}), "('--isic-meta', type=click.BOOL, is_flag=True, help=\n 'Download the ISIC Archive metadata instead of a dataset.')\n", (1700, 1816), False, 'import click\n'), ((1813, 2004), 'click.option', 'click.option', (['"""--metadata-as-name"""'], {'type': 'click.BOOL', 'is_flag': '(True)', 'help': '"""Saves the dataset metadata as the dataset name. Helpful for viewing in excel, not optimal for ML pipelines."""'}), "('--metadata-as-name', type=click.BOOL, is_flag=True, help=\n 'Saves the dataset metadata as the dataset name. Helpful for viewing in excel, not optimal for ML pipelines.'\n )\n", (1825, 2004), False, 'import click\n'), ((1996, 2035), 'sla_cli.src.cli.utils.kwargs_to_dataclass', 'kwargs_to_dataclass', (['DownloadParameters'], {}), '(DownloadParameters)\n', (2015, 2035), False, 'from sla_cli.src.cli.utils import kwargs_to_dataclass, default_from_context\n'), ((2127, 2160), 'sla_cli.src.db.accessors.AccessorFactory.create_datasets', 'AccessorFactory.create_datasets', ([], {}), '()\n', (2158, 2160), False, 'from sla_cli.src.db.accessors import AccessorFactory\n'), ((2502, 2684), 'sla_cli.src.download.DownloaderOptions', 'DownloaderOptions', ([], {'destination_directory': 'params.directory', 'config': 'ctx.obj', 'force': 'params.force', 'metadata_as_name': 'params.metadata_as_name', 'clean': 'params.clean', 'skip': 'params.skip'}), '(destination_directory=params.directory, config=ctx.obj,\n force=params.force, metadata_as_name=params.metadata_as_name, clean=\n params.clean, skip=params.skip)\n', (2519, 2684), False, 'from sla_cli.src.download import Downloader, DownloaderOptions, DummyDownloader\n'), ((2872, 2911), 'sla_cli.src.download.isic.IsicMetadataDownloader', 'IsicMetadataDownloader', ([], {'options': 'options'}), '(options=options)\n', (2894, 2911), False, 'from sla_cli.src.download.isic import IsicMetadataDownloader, IsicImageDownloader\n'), ((1132, 1170), 'sla_cli.src.cli.utils.default_from_context', 'default_from_context', (['"""data_directory"""'], {}), "('data_directory')\n", (1152, 1170), False, 'from sla_cli.src.cli.utils import kwargs_to_dataclass, default_from_context\n')] |
import json
print("Generating stamp files")
stamps = [
"armor_plate",
"armor_trim",
"arrow_head",
"arrow_shaft",
"axe_head",
"binding",
"boots_core",
"bow_limb",
"bow_string",
"broad_axe_head",
"chest_core",
"cross_guard",
"emerald",
"excavator_head",
"fletching",
"hammer_head",
"hand_guard",
"helmet_core",
"kama_head",
"knife_blade",
"large_plate",
"large_sword_blade",
"leggings_core",
"pan_head",
"pick_head",
"polishing_kit",
"scythe_head",
"shard",
"sharpening_kit",
"shovel_head",
"sign_head",
"sword_blade",
"tool_rod",
"tough_binding",
"tough_tool_rod",
"wide_guard"
]
for stamp in stamps:
with open('src/main/resources/assets/emberstic/models/item/stamp_%s.json' % stamp, 'w') as outfile:
data = {
"parent": "item/generated",
"textures": {
"layer0": "emberstic:items/stamp_%s" % stamp
}
}
json.dump(data, outfile, indent=2)
print("Done!") | [
"json.dump"
] | [((929, 963), 'json.dump', 'json.dump', (['data', 'outfile'], {'indent': '(2)'}), '(data, outfile, indent=2)\n', (938, 963), False, 'import json\n')] |
import torch
from uninas.modules.mixed.mixedop import AbstractDependentMixedOp
from uninas.methods.strategies.manager import StrategyManager
from uninas.register import Register
@Register.network_mixed_op()
class SplitWeightsMixedOp(AbstractDependentMixedOp):
"""
all op choices on one path in parallel,
the weight strategy decides which results to compute and combine
in addition, load different sets of weights for the operations,
depending on architecture choices in previous layers
due to the used saving/loading approach, this operation will most likely malfunction in distributed settings
"""
max_depth = 2
def __init__(self, submodules: list, name: str, strategy_name: str, depth=0):
"""
:param submodules: list or nn.ModuleList of choices
:param name: name of the architecture weight
:param strategy_name: name of the architecture strategy to use
:param depth: depth, how many previous architecture decisions to consider
"""
super().__init__(submodules, name, strategy_name)
# store previous names in case this mixed op will be deepened, no need to store the own name
self._add_to_kwargs(depth=depth)
self._all_prev_names = StrategyManager().ordered_names(unique=False)[-self.max_depth - 1:-1]
self._state_dicts = {}
self._last_state = 'w'
self.change_depth(new_depth=self.depth)
def change_depth(self, new_depth=1):
"""
called by a SplitWeightsMixedOpCallback,
increases the recursive depth of the op, copying the weights, using a copy depending on a previous layer choice
"""
if new_depth > 0:
assert new_depth >= self.depth, "Can not reduce the depth"
assert new_depth <= self.max_depth, "Can not increase the depth beyond %d" % self.max_depth
assert StrategyManager().is_only_single_path()
while self.depth < min([new_depth, len(self._all_prev_names)]):
if len(self._state_dicts) == 0:
self._state_dicts[self._last_state] = self.submodules.state_dict()
# enlarge dict of stored state dicts by one layer
new_state_dicts = {'0.%s' % k: v for k, v in self._state_dicts.items()}
self._state_dicts = new_state_dicts
self._last_state = '0.%s' % self._last_state
self.depth += 1
def _get_current_state_name(self) -> str:
""" get a name for the current setting (e.g. "0.1.w") that depends on the previously chosen indices """
names = self._all_prev_names[-self.depth:]
return '.'.join([str(self.sm.get_finalized_indices(n, flat=True)) for n in names] + ['w'])
def _set_weight(self):
if self.depth > 0:
# get name of currently used local architecture
cur_state = self._get_current_state_name()
if self._last_state != cur_state:
# store current weights
self._state_dicts[self._last_state] = {k: v.detach().clone()
for k, v in self.submodules.state_dict().items()}
# load data of current weight into the parameter
self.submodules.load_state_dict(self._state_dicts.get(cur_state, self._state_dicts[self._last_state]))
self._last_state = cur_state
def _save_add_dict(self) -> dict:
""" additional info stored in the save_dict """
return dict(depth=self.depth, _last_state=self._last_state, _state_dicts=self._state_dicts)
def _load_add_dict(self, dct: dict):
""" additional info restored from the save_dict """
self.depth = dct.get('depth', self.depth)
self._last_state = dct.get('_last_state', self._last_state)
self._state_dicts = dct.get('_state_dicts', self._state_dicts)
def forward(self, x: torch.Tensor) -> torch.Tensor:
self._set_weight()
return self.ws.combine(self.name, x, self.submodules)
| [
"uninas.register.Register.network_mixed_op",
"uninas.methods.strategies.manager.StrategyManager"
] | [((181, 208), 'uninas.register.Register.network_mixed_op', 'Register.network_mixed_op', ([], {}), '()\n', (206, 208), False, 'from uninas.register import Register\n'), ((1253, 1270), 'uninas.methods.strategies.manager.StrategyManager', 'StrategyManager', ([], {}), '()\n', (1268, 1270), False, 'from uninas.methods.strategies.manager import StrategyManager\n'), ((1888, 1905), 'uninas.methods.strategies.manager.StrategyManager', 'StrategyManager', ([], {}), '()\n', (1903, 1905), False, 'from uninas.methods.strategies.manager import StrategyManager\n')] |
"""
Plot various visualizations
"""
import sys
import json
from collections import Counter
import numpy as np
import scipy.stats as scstats
import matplotlib
matplotlib.use("agg")
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.patches as mp
from zipteedo.util import GzipFileType, load_jsonl, first
from zipteedo.stats import get_correlations, get_data_efficiencies, make_bias_table
from zipteedo.viz import draw_matrix, violinplot
import zipteedo.estimators as zpe
LABELS = {
"rouge-l": "ROUGE-L",
"rouge-1": "ROUGE-1",
"rouge-2": "ROUGE-2",
"ter": "TER",
"sim": "VecSim",
"meteor": "METEOR",
"bleu": "BLEU-2",
"bleu-2": "BLEU-2",
"bleu-4": "BLEU-4",
"gold": "Upper bound",
"hter": "Edit",
"lqual": "CNN/DailyMail",
"msmarco": "MSMARCO",
"fastqa": "fastqa",
"fastqa_ext": "fastqa_ext",
"snet.single": "snet",
"snet.ensemble": "snet.ens",
"*": "Combined"
}
SYSTEMS = {
"lqual": ["seq2seq", "pointer", "ml", "ml+rl"],
"msmarco": ["fastqa", "fastqa_ext", "snet.single", "snet.ensemble"],
}
PROMPTS = {
"lqual": ["hter", "overall", "redundancy", "grammar"],
"msmarco": ["AnyCorrect", "AvgCorrect"],
}
def do_correlation_table(args):
with open(args.input) as f:
data = load_jsonl(f)
data = get_correlations(data)
data = data[args.data_prompt]
prompt = args.data_prompt
metrics = sorted(data.keys())
task = first(key for key, values in PROMPTS.items() if prompt in values)
systems = SYSTEMS[task] + ["*"]
X = np.array([[data[metric][system] for system in systems] for metric in metrics])
plt.rc("font", size=16)
plt.rc("text", usetex=False)
#plt.rc("figure", figsize=(10,10))
draw_matrix(X, with_values=True,
x_labels=[LABELS.get(s, s) for s in systems],
y_labels=[LABELS.get(m, m) for m in metrics],)
plt.colorbar(label=r"Pearson ρ")
plt.xlabel("Systems")
plt.ylabel("Metrics")
if args.with_title:
task = first(key for key, values in PROMPTS.items() if prompt in values)
plt.title(r"Correlations on {} using the {} prompt".format(
LABELS.get(task, task),
LABELS.get(prompt, prompt),
), fontsize=14)
plt.tight_layout()
plt.savefig(args.output)
def do_trajectory(args):
data = [json.loads(line) for line in open(args.input, "rt")]
data = {(obj["system"], obj["metric"], obj["prompt"], obj["estimator"]): obj for obj in data}
if args.input_gold:
data_gold = [json.loads(line) for line in open(args.input_gold, "rt")]
data_gold = {(obj["system"], obj["metric"], obj["prompt"], obj["estimator"]): obj for obj in data_gold}
else:
data_gold = None
colors = cm.tab10.colors
system = args.data_system
metric = args.data_metric
prompt = args.data_prompt
baseline = np.array(data[system, metric, prompt, "simple"]["summary"])
model = np.array(data[system, metric, prompt, "model_variate"]["summary"])
if data_gold:
model_gold = np.array(data_gold[system, metric, prompt, "model_variate"]["summary"])
gold = np.array(data[system, "gold", prompt, "model_variate"]["summary"])
plt.rc("font", size=16)
plt.rc("text", usetex=False)
#plt.rc("figure", figsize=(10,10))
plt.xlabel("Number of samples")
plt.ylabel(r"80% confidence interval")
plt.plot(baseline.T[2] - baseline.T[1], color=colors[0], label="Humans")
plt.plot(model.T[2] - model.T[1], color=colors[1], label="Humans + {}".format(LABELS.get(metric,metric)))
if data_gold:
plt.plot(model_gold.T[2] - model_gold.T[1], ':', color=colors[2], label="Noiseless humans + {}".format(LABELS.get(metric,metric)))
plt.plot(gold.T[2] - gold.T[1], ':', color=colors[4], label="Humans + perfect metric")
plt.xlim([0, 500])
plt.ylim([0.05, 0.2])
plt.legend()
if args.with_title:
task = first(key for key, values in PROMPTS.items() if prompt in values)
plt.title(r"{} on {} using the {} prompt".format(
LABELS.get(system, system),
LABELS.get(task, task),
LABELS.get(prompt, prompt),
), fontsize=14)
plt.tight_layout()
plt.savefig(args.output)
def do_data_efficiency_table(args):
data = [json.loads(line) for line in open(args.input, "rt")]
data = get_data_efficiencies(data)
prompt = args.data_prompt
metrics = sorted(data.keys())
task = first(key for key, values in PROMPTS.items() if prompt in values)
systems = SYSTEMS[task]
X = np.array([[data[metric][prompt][system]**2 for system in systems] for metric in metrics])
plt.rc("font", size=16)
plt.rc("text", usetex=False)
draw_matrix(X, with_values=True,
x_labels=[LABELS.get(s, s) for s in systems],
y_labels=[LABELS.get(m, m) for m in metrics],
vmin=0.9, vmax=1.3)
plt.colorbar(label="Data efficiency")
plt.xlabel("Systems")
plt.ylabel("Metrics")
if args.with_title:
plt.title(r"Data efficiencies on {} using the {} prompt".format(
LABELS.get(task, task),
LABELS.get(prompt, prompt),
), fontsize=14)
plt.tight_layout()
plt.savefig(args.output)
def do_system_correlation(args):
data = [json.loads(line) for line in open(args.input)]
prompt, metric = args.data_prompt, args.data_metric
task = first(key for key, values in PROMPTS.items() if prompt in values)
systems = SYSTEMS[task]
# Group by data by system.
data = make_bias_table(data, prompt, metric, ["lr", "ur"])
plt.rc("font", size=16)
plt.rc("text", usetex=False)
plt.rc("figure", figsize=(8,6))
colors = cm.Dark2.colors[:len(systems)]
def _thresh(y):
return max(min(y, 1), -1)
# 0. Plot the xy correlation curve.
xy = np.array([[x, _thresh(y)] for system in systems for (x, *_), (y, *_) in [data[system]["default"]]])
xlim = np.array([xy.T[0].min(), xy.T[0].max()])
coeffs = np.polyfit(xy.T[0], xy.T[1], 1)
plt.plot(xlim, xlim * coeffs[0] + coeffs[1], linestyle='--', linewidth=2, zorder=-1)
# 1. Plot actual data points with error bars.
xy = np.array([[x, y] for system in systems for (x, *_), (y, *_) in data[system].values()])
xy_l = np.array([[x, y] for system in systems for (_, x, _), (_, y, _) in data[system].values()])
xy_u = np.array([[x, y] for system in systems for (_, _, x), (_, _, y) in data[system].values()])
plt.errorbar(xy.T[0], xy.T[1],
xerr=[(xy - xy_l).T[0], (xy_u - xy).T[0]],
yerr=[(xy - xy_l).T[1], (xy_u - xy).T[1]],
capsize=2, alpha=0.5, linestyle='', marker="", zorder=-1)
# 2. Plot markers.
xy = np.array([[x, y] for system in systems for (x, *_), (y, *_) in [data[system]["default"]]])
xy_lr = np.array([[x, y] for system in systems for (x, *_), (y, *_) in [data[system]["lr"]]])
xy_ur = np.array([[x, y] for system in systems for (x, *_), (y, *_) in [data[system]["ur"]]])
plt.scatter(xy_lr.T[0], xy_lr.T[1], color=colors, marker=">")
plt.scatter(xy_ur.T[0], xy_ur.T[1], color=colors, marker="^")
plt.scatter(xy.T[0], xy.T[1], 100, c=colors, marker="o")
plt.xlabel(r"Human judgement ({})".format(LABELS.get(prompt, prompt)))
plt.ylabel(LABELS.get(metric, metric))
if args.with_title:
task = first(key for key, values in PROMPTS.items() if prompt in values)
plt.title(r"System-level correlation on {}".format(
LABELS.get(task, task),
), fontsize=14)
plt.tight_layout()
plt.legend(handles=[mp.Patch(color=colors[i], label=LABELS.get(system, system)) for i, system in enumerate(systems)])
plt.savefig(args.output)
def _snap(vs, points):
ret = []
for x, y in vs:
ret.append((first(x_ for x_ in points if x_ >= x), y))
return np.array(ret)
def do_instance_correlation(args):
data = [json.loads(line) for line in open(args.input)]
prompt, metric = args.data_prompt, args.data_metric
task = first(key for key, values in PROMPTS.items() if prompt in values)
systems = SYSTEMS[task]
# Group by data by system.
plt.rc("font", size=16)
plt.rc("text", usetex=False)
plt.rc("figure", figsize=(6,8))
colors = cm.Dark2.colors[:len(systems)]
# 1. How many distinct Y values exist?
fig, axs = plt.subplots(4, 1, sharex=True, sharey=True)
def _thresh(y):
return max(min(y, 1), -1)
xy = {system: np.array([[_thresh(datum["prompts"][prompt]["gold"]), datum["prompts"][prompt][metric]] for datum in data if system in datum["system"].split(";")])
for system in systems}
if args.bins:
y = np.array([_thresh(datum["prompts"][prompt]["gold"]) for datum in data])
distinct_values = np.linspace(y.min(), y.max(), args.bins)
plt.xticks(distinct_values)
for system in systems:
xy[system] = _snap(xy[system], distinct_values)
# 2. Make violin plots.
for i, system in enumerate(systems):
violinplot(axs[i], xy[system], distinct_values, colors[i])
for i, system in enumerate(systems):
x, y = xy[system].T[0], xy[system].T[1]
axs[i].scatter(x, y, alpha=0.3, marker='.', color=colors[i])
for i, system in enumerate(systems):
x, y = xy[system].T[0], xy[system].T[1]
coeffs = np.polyfit(x, y, 1)
xlim = np.array([x.min(), x.max()])
axs[i].plot(xlim, xlim * coeffs[0] + coeffs[1], linestyle='--', linewidth=1, zorder=-1, color=colors[i])
for i, system in enumerate(systems):
axs[i].text(1.2, 0.5, LABELS.get(system, system), va='center', rotation='vertical')
plt.xlabel(r"Human judgement ({})".format(LABELS.get(prompt, prompt)))
#plt.text(-1, 0, LABELS.get(metric, metric), va="center")
fig.text(0.01, 0.5, LABELS.get(metric, metric), va='center', rotation='vertical')
if args.with_title:
task = first(key for key, values in PROMPTS.items() if prompt in values)
axs[0].set_title(r"Instance-level correlation on {}".format(
LABELS.get(task, task),
), fontsize=14)
plt.subplots_adjust(wspace=0, hspace=0.05)
#plt.tight_layout()
#plt.legend(handles=[mp.Patch(color=colors[i], label=LABELS.get(system, system)) for i, system in enumerate(systems)])
plt.savefig(args.output)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='')
parser.set_defaults(func=None)
subparsers = parser.add_subparsers()
command_parser = subparsers.add_parser('correlation-table', help='Plot the system-wide correlation of a models output with truth')
command_parser.add_argument('-i', '--input', type=str, default="lqual_correlation.jsonl", help="Bias data")
command_parser.add_argument('-Dp', '--data-prompt', type=str, default="hter", help="An example trajectory for a task")
command_parser.add_argument('-o', '--output', type=str, default="correlations.pdf", help="Where to save plot")
command_parser.add_argument('-wt', '--with-title', action="store_true", help="An example trajectory for a task")
command_parser.set_defaults(func=do_correlation_table)
command_parser = subparsers.add_parser('data-efficiency-table', help='Plot data efficiencies for different systems and automatic metrics')
command_parser.add_argument('-i', '--input', type=str, default="lqual_trajectories.jsonl", help="Trajecotry data")
command_parser.add_argument('-Dp', '--data-prompt', type=str, default="hter", help="An example trajectory for a task")
command_parser.add_argument('-o', '--output', type=str, default="data_efficiencies.pdf", help="Where to save plot")
command_parser.add_argument('-wt', '--with-title', action="store_true", help="An example trajectory for a task")
command_parser.set_defaults(func=do_data_efficiency_table)
command_parser = subparsers.add_parser('trajectory', help='Plot a trajectory for an estimator')
command_parser.add_argument('-i', '--input', type=str, default="lqual/lqual_trajectories.json", help="")
command_parser.add_argument('-ig', '--input-gold', type=str, help="")
command_parser.add_argument('-o', '--output', type=str, default="trajectory.pdf", help="An example trajectory for a task")
command_parser.add_argument('-Dp', '--data-prompt', type=str, default="hter", help="An example trajectory for a task")
command_parser.add_argument('-Dm', '--data-metric', type=str, default="sim", help="An example trajectory for a task")
command_parser.add_argument('-Ds', '--data-system', type=str, default="seq2seq", help="An example trajectory for a task")
command_parser.add_argument('-wt', '--with-title', action="store_true", help="An example trajectory for a task")
command_parser.set_defaults(func=do_trajectory)
command_parser = subparsers.add_parser('system-correlation', help='Plot the system-wide correlation of a models output with truth')
command_parser.add_argument('-i', '--input', type=str, default="lqual.json", help="Bias data")
command_parser.add_argument('-Dp', '--data-prompt', type=str, default="overall", help="An example trajectory for a task")
command_parser.add_argument('-Dm', '--data-metric', type=str, default="sim", help="An example trajectory for a task")
command_parser.add_argument('-o', '--output', type=str, default="system_correlation.pdf", help="Where to save plot")
command_parser.add_argument('-wt', '--with-title', action="store_true", help="An example trajectory for a task")
command_parser.set_defaults(func=do_system_correlation)
command_parser = subparsers.add_parser('instance-correlation', help='Plot the system-wide correlation of a models output with truth')
command_parser.add_argument('-i', '--input', type=str, default="lqual.json", help="Bias data")
command_parser.add_argument('-Dp', '--data-prompt', type=str, default="overall", help="An example trajectory for a task")
command_parser.add_argument('-Dm', '--data-metric', type=str, default="sim", help="An example trajectory for a task")
command_parser.add_argument('-o', '--output', type=str, default="instance_correlation.pdf", help="Where to save plot")
command_parser.add_argument('-wt', '--with-title', action="store_true", help="An example trajectory for a task")
command_parser.add_argument('-b', '--bins', type=int, help="An example trajectory for a task")
command_parser.set_defaults(func=do_instance_correlation)
ARGS = parser.parse_args()
if ARGS.func is None:
parser.print_help()
sys.exit(1)
else:
ARGS.func(ARGS)
| [
"zipteedo.stats.make_bias_table",
"matplotlib.pyplot.ylabel",
"numpy.polyfit",
"zipteedo.util.first",
"numpy.array",
"zipteedo.stats.get_correlations",
"matplotlib.pyplot.errorbar",
"sys.exit",
"argparse.ArgumentParser",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"zipteedo.viz.violi... | [((160, 181), 'matplotlib.use', 'matplotlib.use', (['"""agg"""'], {}), "('agg')\n", (174, 181), False, 'import matplotlib\n'), ((1343, 1365), 'zipteedo.stats.get_correlations', 'get_correlations', (['data'], {}), '(data)\n', (1359, 1365), False, 'from zipteedo.stats import get_correlations, get_data_efficiencies, make_bias_table\n'), ((1587, 1665), 'numpy.array', 'np.array', (['[[data[metric][system] for system in systems] for metric in metrics]'], {}), '([[data[metric][system] for system in systems] for metric in metrics])\n', (1595, 1665), True, 'import numpy as np\n'), ((1671, 1694), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'size': '(16)'}), "('font', size=16)\n", (1677, 1694), True, 'import matplotlib.pyplot as plt\n'), ((1699, 1727), 'matplotlib.pyplot.rc', 'plt.rc', (['"""text"""'], {'usetex': '(False)'}), "('text', usetex=False)\n", (1705, 1727), True, 'import matplotlib.pyplot as plt\n'), ((1935, 1966), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {'label': '"""Pearson ρ"""'}), "(label='Pearson ρ')\n", (1947, 1966), True, 'import matplotlib.pyplot as plt\n'), ((1972, 1993), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Systems"""'], {}), "('Systems')\n", (1982, 1993), True, 'import matplotlib.pyplot as plt\n'), ((1998, 2019), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Metrics"""'], {}), "('Metrics')\n", (2008, 2019), True, 'import matplotlib.pyplot as plt\n'), ((2303, 2321), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2319, 2321), True, 'import matplotlib.pyplot as plt\n'), ((2326, 2350), 'matplotlib.pyplot.savefig', 'plt.savefig', (['args.output'], {}), '(args.output)\n', (2337, 2350), True, 'import matplotlib.pyplot as plt\n'), ((2929, 2988), 'numpy.array', 'np.array', (["data[system, metric, prompt, 'simple']['summary']"], {}), "(data[system, metric, prompt, 'simple']['summary'])\n", (2937, 2988), True, 'import numpy as np\n'), ((3004, 3070), 'numpy.array', 'np.array', (["data[system, metric, prompt, 'model_variate']['summary']"], {}), "(data[system, metric, prompt, 'model_variate']['summary'])\n", (3012, 3070), True, 'import numpy as np\n'), ((3197, 3263), 'numpy.array', 'np.array', (["data[system, 'gold', prompt, 'model_variate']['summary']"], {}), "(data[system, 'gold', prompt, 'model_variate']['summary'])\n", (3205, 3263), True, 'import numpy as np\n'), ((3269, 3292), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'size': '(16)'}), "('font', size=16)\n", (3275, 3292), True, 'import matplotlib.pyplot as plt\n'), ((3297, 3325), 'matplotlib.pyplot.rc', 'plt.rc', (['"""text"""'], {'usetex': '(False)'}), "('text', usetex=False)\n", (3303, 3325), True, 'import matplotlib.pyplot as plt\n'), ((3370, 3401), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Number of samples"""'], {}), "('Number of samples')\n", (3380, 3401), True, 'import matplotlib.pyplot as plt\n'), ((3406, 3443), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""80% confidence interval"""'], {}), "('80% confidence interval')\n", (3416, 3443), True, 'import matplotlib.pyplot as plt\n'), ((3449, 3521), 'matplotlib.pyplot.plot', 'plt.plot', (['(baseline.T[2] - baseline.T[1])'], {'color': 'colors[0]', 'label': '"""Humans"""'}), "(baseline.T[2] - baseline.T[1], color=colors[0], label='Humans')\n", (3457, 3521), True, 'import matplotlib.pyplot as plt\n'), ((3793, 3884), 'matplotlib.pyplot.plot', 'plt.plot', (['(gold.T[2] - gold.T[1])', '""":"""'], {'color': 'colors[4]', 'label': '"""Humans + perfect metric"""'}), "(gold.T[2] - gold.T[1], ':', color=colors[4], label=\n 'Humans + perfect metric')\n", (3801, 3884), True, 'import matplotlib.pyplot as plt\n'), ((3885, 3903), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[0, 500]'], {}), '([0, 500])\n', (3893, 3903), True, 'import matplotlib.pyplot as plt\n'), ((3908, 3929), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0.05, 0.2]'], {}), '([0.05, 0.2])\n', (3916, 3929), True, 'import matplotlib.pyplot as plt\n'), ((3935, 3947), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (3945, 3947), True, 'import matplotlib.pyplot as plt\n'), ((4261, 4279), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (4277, 4279), True, 'import matplotlib.pyplot as plt\n'), ((4284, 4308), 'matplotlib.pyplot.savefig', 'plt.savefig', (['args.output'], {}), '(args.output)\n', (4295, 4308), True, 'import matplotlib.pyplot as plt\n'), ((4423, 4450), 'zipteedo.stats.get_data_efficiencies', 'get_data_efficiencies', (['data'], {}), '(data)\n', (4444, 4450), False, 'from zipteedo.stats import get_correlations, get_data_efficiencies, make_bias_table\n'), ((4630, 4727), 'numpy.array', 'np.array', (['[[(data[metric][prompt][system] ** 2) for system in systems] for metric in\n metrics]'], {}), '([[(data[metric][prompt][system] ** 2) for system in systems] for\n metric in metrics])\n', (4638, 4727), True, 'import numpy as np\n'), ((4725, 4748), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'size': '(16)'}), "('font', size=16)\n", (4731, 4748), True, 'import matplotlib.pyplot as plt\n'), ((4753, 4781), 'matplotlib.pyplot.rc', 'plt.rc', (['"""text"""'], {'usetex': '(False)'}), "('text', usetex=False)\n", (4759, 4781), True, 'import matplotlib.pyplot as plt\n'), ((4985, 5022), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {'label': '"""Data efficiency"""'}), "(label='Data efficiency')\n", (4997, 5022), True, 'import matplotlib.pyplot as plt\n'), ((5027, 5048), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Systems"""'], {}), "('Systems')\n", (5037, 5048), True, 'import matplotlib.pyplot as plt\n'), ((5053, 5074), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Metrics"""'], {}), "('Metrics')\n", (5063, 5074), True, 'import matplotlib.pyplot as plt\n'), ((5283, 5301), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (5299, 5301), True, 'import matplotlib.pyplot as plt\n'), ((5306, 5330), 'matplotlib.pyplot.savefig', 'plt.savefig', (['args.output'], {}), '(args.output)\n', (5317, 5330), True, 'import matplotlib.pyplot as plt\n'), ((5628, 5679), 'zipteedo.stats.make_bias_table', 'make_bias_table', (['data', 'prompt', 'metric', "['lr', 'ur']"], {}), "(data, prompt, metric, ['lr', 'ur'])\n", (5643, 5679), False, 'from zipteedo.stats import get_correlations, get_data_efficiencies, make_bias_table\n'), ((5685, 5708), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'size': '(16)'}), "('font', size=16)\n", (5691, 5708), True, 'import matplotlib.pyplot as plt\n'), ((5713, 5741), 'matplotlib.pyplot.rc', 'plt.rc', (['"""text"""'], {'usetex': '(False)'}), "('text', usetex=False)\n", (5719, 5741), True, 'import matplotlib.pyplot as plt\n'), ((5746, 5778), 'matplotlib.pyplot.rc', 'plt.rc', (['"""figure"""'], {'figsize': '(8, 6)'}), "('figure', figsize=(8, 6))\n", (5752, 5778), True, 'import matplotlib.pyplot as plt\n'), ((6092, 6123), 'numpy.polyfit', 'np.polyfit', (['xy.T[0]', 'xy.T[1]', '(1)'], {}), '(xy.T[0], xy.T[1], 1)\n', (6102, 6123), True, 'import numpy as np\n'), ((6128, 6216), 'matplotlib.pyplot.plot', 'plt.plot', (['xlim', '(xlim * coeffs[0] + coeffs[1])'], {'linestyle': '"""--"""', 'linewidth': '(2)', 'zorder': '(-1)'}), "(xlim, xlim * coeffs[0] + coeffs[1], linestyle='--', linewidth=2,\n zorder=-1)\n", (6136, 6216), True, 'import matplotlib.pyplot as plt\n'), ((6568, 6750), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['xy.T[0]', 'xy.T[1]'], {'xerr': '[(xy - xy_l).T[0], (xy_u - xy).T[0]]', 'yerr': '[(xy - xy_l).T[1], (xy_u - xy).T[1]]', 'capsize': '(2)', 'alpha': '(0.5)', 'linestyle': '""""""', 'marker': '""""""', 'zorder': '(-1)'}), "(xy.T[0], xy.T[1], xerr=[(xy - xy_l).T[0], (xy_u - xy).T[0]],\n yerr=[(xy - xy_l).T[1], (xy_u - xy).T[1]], capsize=2, alpha=0.5,\n linestyle='', marker='', zorder=-1)\n", (6580, 6750), True, 'import matplotlib.pyplot as plt\n'), ((6827, 6922), 'numpy.array', 'np.array', (["[[x, y] for system in systems for (x, *_), (y, *_) in [data[system]['default']]\n ]"], {}), "([[x, y] for system in systems for (x, *_), (y, *_) in [data[system\n ]['default']]])\n", (6835, 6922), True, 'import numpy as np\n'), ((6930, 7020), 'numpy.array', 'np.array', (["[[x, y] for system in systems for (x, *_), (y, *_) in [data[system]['lr']]]"], {}), "([[x, y] for system in systems for (x, *_), (y, *_) in [data[system\n ]['lr']]])\n", (6938, 7020), True, 'import numpy as np\n'), ((7028, 7118), 'numpy.array', 'np.array', (["[[x, y] for system in systems for (x, *_), (y, *_) in [data[system]['ur']]]"], {}), "([[x, y] for system in systems for (x, *_), (y, *_) in [data[system\n ]['ur']]])\n", (7036, 7118), True, 'import numpy as np\n'), ((7119, 7180), 'matplotlib.pyplot.scatter', 'plt.scatter', (['xy_lr.T[0]', 'xy_lr.T[1]'], {'color': 'colors', 'marker': '""">"""'}), "(xy_lr.T[0], xy_lr.T[1], color=colors, marker='>')\n", (7130, 7180), True, 'import matplotlib.pyplot as plt\n'), ((7185, 7246), 'matplotlib.pyplot.scatter', 'plt.scatter', (['xy_ur.T[0]', 'xy_ur.T[1]'], {'color': 'colors', 'marker': '"""^"""'}), "(xy_ur.T[0], xy_ur.T[1], color=colors, marker='^')\n", (7196, 7246), True, 'import matplotlib.pyplot as plt\n'), ((7251, 7307), 'matplotlib.pyplot.scatter', 'plt.scatter', (['xy.T[0]', 'xy.T[1]', '(100)'], {'c': 'colors', 'marker': '"""o"""'}), "(xy.T[0], xy.T[1], 100, c=colors, marker='o')\n", (7262, 7307), True, 'import matplotlib.pyplot as plt\n'), ((7661, 7679), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (7677, 7679), True, 'import matplotlib.pyplot as plt\n'), ((7808, 7832), 'matplotlib.pyplot.savefig', 'plt.savefig', (['args.output'], {}), '(args.output)\n', (7819, 7832), True, 'import matplotlib.pyplot as plt\n'), ((7965, 7978), 'numpy.array', 'np.array', (['ret'], {}), '(ret)\n', (7973, 7978), True, 'import numpy as np\n'), ((8272, 8295), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'size': '(16)'}), "('font', size=16)\n", (8278, 8295), True, 'import matplotlib.pyplot as plt\n'), ((8300, 8328), 'matplotlib.pyplot.rc', 'plt.rc', (['"""text"""'], {'usetex': '(False)'}), "('text', usetex=False)\n", (8306, 8328), True, 'import matplotlib.pyplot as plt\n'), ((8333, 8365), 'matplotlib.pyplot.rc', 'plt.rc', (['"""figure"""'], {'figsize': '(6, 8)'}), "('figure', figsize=(6, 8))\n", (8339, 8365), True, 'import matplotlib.pyplot as plt\n'), ((8468, 8512), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(4)', '(1)'], {'sharex': '(True)', 'sharey': '(True)'}), '(4, 1, sharex=True, sharey=True)\n', (8480, 8512), True, 'import matplotlib.pyplot as plt\n'), ((10262, 10304), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0)', 'hspace': '(0.05)'}), '(wspace=0, hspace=0.05)\n', (10281, 10304), True, 'import matplotlib.pyplot as plt\n'), ((10458, 10482), 'matplotlib.pyplot.savefig', 'plt.savefig', (['args.output'], {}), '(args.output)\n', (10469, 10482), True, 'import matplotlib.pyplot as plt\n'), ((10545, 10584), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '""""""'}), "(description='')\n", (10568, 10584), False, 'import argparse\n'), ((1318, 1331), 'zipteedo.util.load_jsonl', 'load_jsonl', (['f'], {}), '(f)\n', (1328, 1331), False, 'from zipteedo.util import GzipFileType, load_jsonl, first\n'), ((2390, 2406), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (2400, 2406), False, 'import json\n'), ((3110, 3181), 'numpy.array', 'np.array', (["data_gold[system, metric, prompt, 'model_variate']['summary']"], {}), "(data_gold[system, metric, prompt, 'model_variate']['summary'])\n", (3118, 3181), True, 'import numpy as np\n'), ((4359, 4375), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (4369, 4375), False, 'import json\n'), ((5377, 5393), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (5387, 5393), False, 'import json\n'), ((8028, 8044), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (8038, 8044), False, 'import json\n'), ((8948, 8975), 'matplotlib.pyplot.xticks', 'plt.xticks', (['distinct_values'], {}), '(distinct_values)\n', (8958, 8975), True, 'import matplotlib.pyplot as plt\n'), ((9483, 9502), 'numpy.polyfit', 'np.polyfit', (['x', 'y', '(1)'], {}), '(x, y, 1)\n', (9493, 9502), True, 'import numpy as np\n'), ((14745, 14756), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (14753, 14756), False, 'import sys\n'), ((2587, 2603), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (2597, 2603), False, 'import json\n'), ((9158, 9216), 'zipteedo.viz.violinplot', 'violinplot', (['axs[i]', 'xy[system]', 'distinct_values', 'colors[i]'], {}), '(axs[i], xy[system], distinct_values, colors[i])\n', (9168, 9216), False, 'from zipteedo.viz import draw_matrix, violinplot\n'), ((7911, 7948), 'zipteedo.util.first', 'first', (['(x_ for x_ in points if x_ >= x)'], {}), '(x_ for x_ in points if x_ >= x)\n', (7916, 7948), False, 'from zipteedo.util import GzipFileType, load_jsonl, first\n')] |
import plotly.plotly as py
import plotly.graph_objs as go
import plotly.offline as offline
import sys, os
from .CreateTableFromDatabase import getRankingsFromDatabase
# Using the plotly API creates a few plots
def createAndUploadPlots(table, plotName):
# Read plotly username and API key from file (to avoid accidentally publishing it)
inputFile = open(os.path.join(os.path.dirname(__file__), "PlotlyAPIAccess.txt"))
lines = []
for line in inputFile:
lines.append(line)
username = lines[0]
APIkey = lines[1]
# Sign in plotly
py.sign_in(username.replace('\n', ''), APIkey.replace('\n', ''))
#print(table)
# Create the three place bars
place1 = go.Bar(
x=[row[0] for row in table],
y=[row[1] for row in table],
name='First Place Count',
marker=dict(color='rgb(252,223,7)')
)
place2 = go.Bar(
x=[row[0] for row in table],
y=[row[2] for row in table],
name='Second Place Count',
marker=dict(color='rgb(204,204,204)')
)
place3 = go.Bar(
x=[row[0] for row in table],
y=[row[3] for row in table],
name='Third Place Count',
marker=dict(color='rgb(142,75,17)')
)
data = [place1, place2, place3]
layout = go.Layout(
title='%s' % (plotName),
barmode='group'
)
fig = go.Figure(data=data, layout=layout)
#py.image.save_as(fig, filename='plot.png')
offline.plot(fig, image = 'png', filename = 'plot.html')
return py.plot(fig, filename = plotName + '.png', auto_open=False)
if __name__ == '__main__':
print(createAndUploadPlots(getRankingsFromDatabase("statelands"), "statelands"))
| [
"plotly.offline.plot",
"plotly.plotly.plot",
"os.path.dirname",
"plotly.graph_objs.Layout",
"plotly.graph_objs.Figure"
] | [((1285, 1334), 'plotly.graph_objs.Layout', 'go.Layout', ([], {'title': "('%s' % plotName)", 'barmode': '"""group"""'}), "(title='%s' % plotName, barmode='group')\n", (1294, 1334), True, 'import plotly.graph_objs as go\n'), ((1371, 1406), 'plotly.graph_objs.Figure', 'go.Figure', ([], {'data': 'data', 'layout': 'layout'}), '(data=data, layout=layout)\n', (1380, 1406), True, 'import plotly.graph_objs as go\n'), ((1459, 1511), 'plotly.offline.plot', 'offline.plot', (['fig'], {'image': '"""png"""', 'filename': '"""plot.html"""'}), "(fig, image='png', filename='plot.html')\n", (1471, 1511), True, 'import plotly.offline as offline\n'), ((1527, 1584), 'plotly.plotly.plot', 'py.plot', (['fig'], {'filename': "(plotName + '.png')", 'auto_open': '(False)'}), "(fig, filename=plotName + '.png', auto_open=False)\n", (1534, 1584), True, 'import plotly.plotly as py\n'), ((378, 403), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (393, 403), False, 'import sys, os\n')] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('proposals', '0003_auto_20150113_1401'),
('conferences', '0004_conference_logo'),
]
operations = [
migrations.CreateModel(
name='EmailReviewerNotificationSetting',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Created At')),
('modified_at', models.DateTimeField(auto_now=True, verbose_name='Last Modified At')),
('action', models.CharField(max_length=15)),
('status', models.BooleanField(default=True)),
('conference_reviewer', models.ForeignKey(to='conferences.ConferenceProposalReviewer')),
('created_by', models.ForeignKey(related_name='created_emailreviewernotificationsetting_set', verbose_name='Created By', blank=True, to=settings.AUTH_USER_MODEL, null=True)),
('modified_by', models.ForeignKey(related_name='updated_emailreviewernotificationsetting_set', verbose_name='Modified By', blank=True, to=settings.AUTH_USER_MODEL, null=True)),
('proposal_section', models.ForeignKey(to='proposals.ProposalSection')),
('proposal_type', models.ForeignKey(to='proposals.ProposalType')),
],
options={
'verbose_name': 'email notification',
'verbose_name_plural': 'email notifications',
},
bases=(models.Model,),
),
]
| [
"django.db.models.ForeignKey",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.DateTimeField",
"django.db.migrations.swappable_dependency",
"django.db.models.CharField"
] | [((210, 267), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (241, 267), False, 'from django.db import models, migrations\n'), ((523, 616), 'django.db.models.AutoField', 'models.AutoField', ([], {'verbose_name': '"""ID"""', 'serialize': '(False)', 'auto_created': '(True)', 'primary_key': '(True)'}), "(verbose_name='ID', serialize=False, auto_created=True,\n primary_key=True)\n", (539, 616), False, 'from django.db import models, migrations\n'), ((646, 712), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', 'verbose_name': '"""Created At"""'}), "(auto_now_add=True, verbose_name='Created At')\n", (666, 712), False, 'from django.db import models, migrations\n'), ((747, 815), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)', 'verbose_name': '"""Last Modified At"""'}), "(auto_now=True, verbose_name='Last Modified At')\n", (767, 815), False, 'from django.db import models, migrations\n'), ((845, 876), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(15)'}), '(max_length=15)\n', (861, 876), False, 'from django.db import models, migrations\n'), ((906, 939), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)'}), '(default=True)\n', (925, 939), False, 'from django.db import models, migrations\n'), ((982, 1044), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'to': '"""conferences.ConferenceProposalReviewer"""'}), "(to='conferences.ConferenceProposalReviewer')\n", (999, 1044), False, 'from django.db import models, migrations\n'), ((1078, 1245), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'related_name': '"""created_emailreviewernotificationsetting_set"""', 'verbose_name': '"""Created By"""', 'blank': '(True)', 'to': 'settings.AUTH_USER_MODEL', 'null': '(True)'}), "(related_name=\n 'created_emailreviewernotificationsetting_set', verbose_name=\n 'Created By', blank=True, to=settings.AUTH_USER_MODEL, null=True)\n", (1095, 1245), False, 'from django.db import models, migrations\n'), ((1270, 1438), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'related_name': '"""updated_emailreviewernotificationsetting_set"""', 'verbose_name': '"""Modified By"""', 'blank': '(True)', 'to': 'settings.AUTH_USER_MODEL', 'null': '(True)'}), "(related_name=\n 'updated_emailreviewernotificationsetting_set', verbose_name=\n 'Modified By', blank=True, to=settings.AUTH_USER_MODEL, null=True)\n", (1287, 1438), False, 'from django.db import models, migrations\n'), ((1468, 1517), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'to': '"""proposals.ProposalSection"""'}), "(to='proposals.ProposalSection')\n", (1485, 1517), False, 'from django.db import models, migrations\n'), ((1554, 1600), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'to': '"""proposals.ProposalType"""'}), "(to='proposals.ProposalType')\n", (1571, 1600), False, 'from django.db import models, migrations\n')] |
#!/usr/bin/env python3
import statistics
import os
import glob
from tkinter import filedialog
from tkinter import * # noqa
import pandas as pd
from eventcodes import eventcodes_dictionary
from natsort import natsorted, ns
import matplotlib.pyplot as plt
import numpy as np
import datetime
__all__ = ["loop_over_days", "load_file", "concat_lickometer_files",
"extract_info_from_file", "DNAMIC_extract_info_from_file",
"DNAMIC_loop_over_days", "get_events_indices", "reward_retrieval", "cue_iti_responding",
"cue_iti_responding_PavCA", "binned_responding",
"cue_responding_duration", "lever_pressing", "lever_press_latency", "lever_press_latency_PavCA",
"total_head_pokes",
"num_successful_go_nogo_trials", "count_go_nogo_trials", "num_switch_trials", "bin_by_time",
"lever_press_lat_gng", "RVI_gng_weird", "RVI_nogo_latency", "lever_press_latency_Switch",
"response_rate_across_cue_iti", "duration_across_cue_iti"]
def date_sort_key(date_as_string, date_fmt = '%b_%d_%y', date_grep_fmt = '\w{3}_\d{1,2}_\d{2}'):
'''
:param date_as_string: a string containing a date, typically from a file or directory name
:param date_fmt: The formatting to use with datetime to extract the raw date information.
A default is provided for ease of use.
:param date_grep_fmt: A pattern used to pull the date itself out of date_as_string.
Default matches that of date_fmt.
:return: A tuple containing date information in Month, Day, Year order to be used by
a sort function, such as sorted, as a key for sorting a list of dates.
'''
# Ensure separator between year, month, and day is underscore.
date_as_string = date_as_string.replace('-', '_')
try:
sanitized_string_date = re.search(date_grep_fmt, date_as_string).group(0)
date_info = datetime.datetime.strptime(sanitized_string_date, date_fmt)
except (AttributeError, ValueError) as e:
print(e)
# If the desired string is not matched, re.search will return NoneType and
# group(0) will yield an AttributeError.
print(f'The date is {date_as_string}\n\
The regex pattern is {date_grep_fmt}\n\
The datetime format is {date_fmt}.)')
date_grep_fmt = input('Enter desired regex pattern to match date string: ')
date_fmt = input('Enter desired date format string for strptime: ')
# and then try it again.
sanitized_string_date = re.search(date_grep_fmt, date_as_string).group(0)
date_info = datetime.datetime.strptime(sanitized_string_date, date_fmt)
return date_info.month, date_info.day, date_info.year
def loop_over_days(column_list, behavioral_test_function, master_data_folder=''):
"""
:param column_list: list of strings/column titles for analysis that will be output in a table
:param behavioral_test_function: function that contains all the analysis functions to run on each file
:param master_data_folder: A directory which contains all single-day directories of interest. Used instead
of GUI selection with Tk. Path provided by sys.argv in executing script.
:return: one concatenated data table of analysis for each animal for each day specified
"""
# If a data folder is passed, skip user input.
if master_data_folder == '':
days = int(input("How many days would you like to analyze?"))
gui=True
else:
data_folders = glob.glob(os.path.join(master_data_folder, '*'))
data_folders = natsorted(data_folders, key=date_sort_key)
print('I found {}'.format(data_folders))
continue_script = input('Are these in the right order (y/n)? ')
if continue_script =='y':
pass
elif continue_script=='n':
date_fmt = input('Enter desired date format string for strptime: ')
regex_fmt = input('Enter desired regex pattern to match date string: ')
data_folders = natsorted(data_folders, key=date_sort_key(date_fmt=date_fmt, date_grep_fmt=regex_fmt))
days = len(data_folders)
gui=False
df = pd.DataFrame(columns=column_list)
for i in range(days):
# Ask user to specify data folder if necessary.
if gui:
root = Tk() # noqa
root.withdraw()
folder_selected = filedialog.askdirectory()
else:
folder_selected = data_folders[i]
# Iterate over single animal datafiles in current folder.
file_pattern = os.path.join(folder_selected, '*')
for file in sorted(glob.glob(file_pattern)):
loaded_file = load_file(file)
df2 = behavioral_test_function(loaded_file, i)
df = df.append(df2, ignore_index=True)
return days, df
def loop_over_days_lickometer(column_list, behavioral_test_function):
"""
:param column_list: list of strings/column titles for analysis that will be output in a table
:param behavioral_test_function: function that contains all the analysis functions to run on each file
:return: one concatenated data table of analysis for each animal for each day specified
"""
days = int(input("How many days would you like to analyze?"))
df = pd.DataFrame(columns=column_list)
for i in range(days):
root = Tk() # noqa
root.withdraw()
folder_selected = filedialog.askdirectory()
file_pattern = os.path.join(folder_selected, '*')
for file in sorted(glob.glob(file_pattern)):
loaded_file = load_file(file)
df2 = behavioral_test_function(loaded_file, i)
df = df.append(df2, ignore_index=True)
return days, df
def load_file(filename):
"""
:param filename: string that refers to single operant file location, file is txt
:return: dictionary of all the fields and their values contained in the file (like subject, group, or w array)
"""
with open(filename, "r") as fileref:
filelines = fileref.readlines()
fields_dictionary = {}
for line in filelines:
if line[0] != ' ' and line[0] != '\n':
name = line.split(':')[0]
fields_dictionary[name] = line.replace(name + ':', '')
fields_dictionary[name] = fields_dictionary[name].replace('\n', '')
fields_dictionary[name] = fields_dictionary[name].replace(' ', '')
elif line[0] == ' ':
fields_dictionary[name] += line
fields_dictionary[name] = fields_dictionary[name].replace('\n', '')
group_identities = fields_dictionary['Group'].split('/')
fields_dictionary['Group'] = group_identities.pop(0)
for remaining in group_identities:
if ':' in remaining:
next_group = remaining.split(':')
fields_dictionary[next_group[0]] = next_group[1]
return fields_dictionary
def concat_lickometer_files():
"""
:return: data frame for lickometer analysis
"""
files_list = []
root = Tk();
root.withdraw()
home = os.path.expanduser('~') # returns the home directory on any OS --> ex) /Users/jhl
selected_folder = filedialog.askdirectory(initialdir=home)
file_pattern = os.path.join(selected_folder, '*.txt')
data_dict = {}
for fname in natsorted(glob.glob(file_pattern), alg=ns.IGNORECASE): # loop through all the txt files
with open(fname, "r") as file:
filelines = file.readlines() # read the lines in each file
subject_line = filelines[5] # Animal ID will always be at the 6th index (5+1)
subject = subject_line.split(",")[-1].strip() # subject will be the last element, strip any whitespaces!
values = filelines[-1].strip().split(",") # Need to split by delimiter in order to make the list!
data_dict[subject] = values
lick_df = pd.DataFrame.from_dict(data_dict, orient='index')
lick_final = lick_df.T
# Delete row at index position 0 & 1
lick_final = lick_final.drop([lick_final.index[0]]) # to get rid of row of ones at top
lick_final.reset_index(inplace=True)
for c in lick_final.columns:
lick_final[c] = pd.to_numeric(lick_final[c], errors='coerce')
lick_final = lick_final.drop(lick_final.columns[[0]], axis=1)
lick_final.fillna(value=pd.np.nan, inplace=True)
lick_final.rename(columns=lick_final.iloc[0]).drop(lick_final.index[0])
lick_final.to_excel("output.xlsx")
return lick_final
def extract_info_from_file(dictionary_from_file, time_conversion):
"""
:param dictionary_from_file: dictionary of all the fields and their values contained in the file (like subject, group, or w array)
:param time_conversion: conversion number the timecode needs to be divided by to get seconds
:return: timecode and eventcode lists derived from the w array
"""
time_event_codes = dictionary_from_file["W"].split()
for num in time_event_codes:
if ':' in num:
time_event_codes.remove(num)
for num in time_event_codes:
time_event_codes[time_event_codes.index(num)] = str(int(float(num)))
timecode = []
eventcode = []
first_timecode = (float(time_event_codes[0][:-4]) / time_conversion)
for num in time_event_codes:
if num == time_event_codes[0]:
timecode += [0.0]
else:
timecode += [round((float(num[:-4]) / time_conversion) - first_timecode, 2)]
eventcode += [eventcodes_dictionary[int(num[-4:])]]
return timecode, eventcode
def DNAMIC_loop_over_days(column_list, behavioral_test_function):
"""
:param column_list: list of strings/column titles for analysis that will be output in a table
:param behavioral_test_function: function that contains all the analysis functions to run on each file
:return: one concatenated data table of analysis for each animal for each day specified
"""
days = int(input("How many days would you like to analyze?"))
df = pd.DataFrame(columns=column_list)
for i in range(days):
root = Tk() # noqa
root.withdraw()
folder_selected = filedialog.askdirectory()
file_pattern = os.path.join(folder_selected, '*')
for file in sorted(glob.glob(file_pattern)):
(eventcode, timecode, fields_dictionary) = DNAMIC_extract_info_from_file(file)
df2 = behavioral_test_function(eventcode, timecode, fields_dictionary, i)
df = df.append(df2, ignore_index=True)
return days, df
def DNAMIC_extract_info_from_file(filename):
df = pd.read_csv(filename, sep=':', names=['event', 'timestamp'])
df['timestamp'] = df['timestamp'].str.strip()
# 0, 0, 0 appears after successful initialization --> serves as a cutoff mark
end_of_init_idx = df.loc[df['timestamp'] == '0'].index[-1]
body_start_idx = end_of_init_idx + 1
keys = df[:body_start_idx]['event'].tolist()
values = df[:body_start_idx]['timestamp'].tolist()
fields_dictionary = dict(zip(keys, values))
df_body = df[body_start_idx:-2]
eventcode = df_body['event'].tolist()
eventcode = [eventcodes_dictionary[int(i)] for i in eventcode]
timecode = df_body['timestamp'].tolist()
timecode = [int(i) / 1000 for i in timecode]
return eventcode, timecode, fields_dictionary
def get_events_indices(eventcode, eventtypes):
"""
:param eventcode: list of event codes from operant conditioning file
:param eventtypes: list of event types to index
:return: list of indices of target events
"""
return [i for i, event in enumerate(eventcode) if event in eventtypes]
def reward_retrieval(timecode, eventcode):
"""
:param timecode: list of time codes from operant conditioning file
:param eventcode: list of event codes from operant conditioning file
:return: number of reinforcers (dippers) presented, number retrieved, and latency to retrieve as floats
"""
dip_on = get_events_indices(eventcode, ['DipOn'])
dip_off = get_events_indices(eventcode, ['DipOff', 'EndSession'])
poke_on = get_events_indices(eventcode, ['PokeOn1'])
poke_off = get_events_indices(eventcode, ['PokeOff1'])
dips_retrieved = 0
latency_dip_retrieval = []
for i in range(len(dip_on)):
for x in range(len(poke_off)):
dip_on_idx = dip_on[i]
dip_off_idx = dip_off[i]
if poke_on[x] < dip_on_idx < poke_off[x]:
dips_retrieved += 1
latency_dip_retrieval += [0]
break
elif 'PokeOn1' in eventcode[dip_on_idx:dip_off_idx]:
dips_retrieved += 1
poke_during_dip_idx = eventcode[dip_on_idx:dip_off_idx].index('PokeOn1')
latency_dip_retrieval += [round(timecode[poke_during_dip_idx + dip_on_idx] - timecode[dip_on_idx], 2)]
break
if dips_retrieved == 0:
return len(dip_on), dips_retrieved, 0
else:
return len(dip_on), dips_retrieved, round(statistics.mean(latency_dip_retrieval), 3)
def cue_iti_responding(timecode, eventcode, code_on, code_off, counted_behavior):
"""
:param timecode: list of time codes from operant conditioning file
:param eventcode: list of event codes from operant conditioning file
:param code_on: event code for the beginning of a cue
:param code_off: event code for the end of a cue
:param counted_behavior: event code for counted behavior
:return: mean rpm of head pokes during cue and mean rpm of head pokes during equivalent ITI preceding cue
"""
cue_on = get_events_indices(eventcode, [code_on])
cue_off = get_events_indices(eventcode, [code_off])
if len(cue_on) != len(cue_off):
cue_off += get_events_indices(eventcode, ['EndSession'])
iti_on = get_events_indices(eventcode, [code_off, 'StartSession'])
all_poke_rpm = []
all_poke_iti_rpm = []
for i in range(len(cue_on)):
cue_on_idx = cue_on[i]
cue_off_idx = cue_off[i]
iti_on_idx = iti_on[i]
cue_length_sec = (timecode[cue_off_idx] - timecode[cue_on_idx])
if cue_length_sec > 0:
poke_rpm = ((eventcode[cue_on_idx:cue_off_idx].count(counted_behavior)) / (cue_length_sec / 60))
else:
poke_rpm = 0
all_poke_rpm += [poke_rpm]
iti_poke = 0
for x in range(iti_on_idx, cue_on_idx):
if eventcode[x] == counted_behavior and timecode[x] >= (timecode[cue_on_idx] - cue_length_sec):
iti_poke += 1
if cue_length_sec > 0:
iti_poke_rpm = iti_poke / (cue_length_sec / 60)
else:
iti_poke_rpm = 0
all_poke_iti_rpm += [iti_poke_rpm]
return round(statistics.mean(all_poke_rpm), 3), round(statistics.mean(all_poke_iti_rpm), 3)
def cue_iti_responding_PavCA(timecode, eventcode, code_on, code_off, counted_behavior):
"""
:param timecode: list of time codes from operant conditioning file
:param eventcode: list of event codes from operant conditioning file
:param code_on: event code for the beginning of a cue
:param code_off: event code for the end of a cue
:param counted_behavior: event code for counted behavior
:return: mean rpm of head pokes during cue and mean rpm of head pokes during equivalent ITI preceding cue
"""
cue_on = get_events_indices(eventcode, [code_on])
cue_off = get_events_indices(eventcode, [code_off])
if len(cue_on) != len(cue_off):
cue_off += get_events_indices(eventcode, ['EndSession'])
iti_on = get_events_indices(eventcode, [code_off, 'StartSession'])
all_poke_rpm = []
all_poke_iti_rpm = []
for i in range(len(cue_on)):
cue_on_idx = cue_on[i]
cue_off_idx = cue_off[i]
iti_on_idx = iti_on[i]
cue_length_sec = (timecode[cue_off_idx] - timecode[cue_on_idx])
if cue_length_sec > 0:
poke_rpm = ((eventcode[cue_on_idx:cue_off_idx].count(counted_behavior)) / (cue_length_sec / 60))
else:
poke_rpm = 0
all_poke_rpm += [poke_rpm]
iti_poke = 0
for x in range(iti_on_idx, cue_on_idx):
if eventcode[x] == counted_behavior and timecode[x] >= (timecode[cue_on_idx] - cue_length_sec):
iti_poke += 1
if cue_length_sec > 0:
iti_poke_rpm = iti_poke / (cue_length_sec / 60)
else:
iti_poke_rpm = 0
all_poke_iti_rpm += [iti_poke_rpm]
return round(statistics.mean(all_poke_rpm), 3), round(statistics.mean(all_poke_iti_rpm), 3), len(
[j for j in all_poke_rpm if j > 0])
def binned_responding(timecode, eventcode, code_on, code_off, counted_behavior, trial_count):
"""
:param timecode: list of time codes from operant conditioning file
:param eventcode: list of event codes from operant conditioning file
:param code_on: event code for the beginning of a cue
:param code_off: event code for the end of a cue
:param counted_behavior: event code for behavior you want counted
:param trial_count: number of bins
:return: mean rpm of head pokes during cue and mean rpm of head pokes during equivalent ITI preceding cue
"""
cue_on = get_events_indices(eventcode, [code_on])
cue_off = get_events_indices(eventcode, [code_off])
iti_on = get_events_indices(eventcode, [code_off, 'StartSession'])
all_poke_rpm = []
all_poke_iti_rpm = []
for i in range(trial_count):
cue_on_idx = cue_on[i]
cue_off_idx = cue_off[i]
iti_on_idx = iti_on[i]
cue_length_sec = (timecode[cue_off_idx] - timecode[cue_on_idx])
poke_rpm = ((eventcode[cue_on_idx:cue_off_idx].count(counted_behavior)) / (cue_length_sec / 60))
all_poke_rpm += [poke_rpm]
iti_poke = 0
for x in range(iti_on_idx, cue_on_idx):
if eventcode[x] == counted_behavior and timecode[x] >= (timecode[cue_on_idx] - cue_length_sec):
iti_poke += 1
iti_poke_rpm = iti_poke / (cue_length_sec / 60)
all_poke_iti_rpm += [iti_poke_rpm]
return round(statistics.mean(all_poke_rpm), 3), round(statistics.mean(all_poke_iti_rpm), 3)
def cue_responding_duration(timecode, eventcode, code_on, code_off, counted_behavior_on, counted_behavior_off):
"""
:param timecode: list of time codes from operant conditioning file
:param eventcode: list of event codes from operant conditioning file
:param code_on: event code for the beginning of a cue
:param code_off: event code for the end of a cue
:param counted_behavior_off: event code for the beginning of target behavior
:param counted_behavior_on: event code for the end of target behavior
:return: mean duration of individual head pokes during cue, mean total duration of head poking during cue, also these for ITI preceeding cue
"""
cue_on = get_events_indices(eventcode, [code_on])
cue_off = get_events_indices(eventcode, [code_off])
if len(cue_on) != len(cue_off):
cue_off += get_events_indices(eventcode, ['EndSession'])
iti_on = get_events_indices(eventcode, [code_off, 'StartSession'])
all_poke_dur = []
all_iti_poke_dur = []
all_cue_duration = []
all_iti_duration = []
for i in range(len(cue_on)):
cue_on_idx = cue_on[i]
cue_off_idx = cue_off[i]
iti_on_idx = iti_on[i]
cue_length_sec = (timecode[cue_off_idx] - timecode[cue_on_idx])
in_cue_duration = 0
iti_cue_duration = 0
for x in range(cue_on_idx, cue_off_idx):
if eventcode[x - 1] == code_on and eventcode[x] == counted_behavior_off:
poke_dur = timecode[x] - timecode[x - 1]
all_poke_dur += [poke_dur]
in_cue_duration += poke_dur
elif eventcode[x] == code_off and eventcode[x - 1] == code_on and eventcode[x + 1] == counted_behavior_off:
poke_dur = timecode[x] - timecode[x - 1]
all_poke_dur += [poke_dur]
in_cue_duration += poke_dur
elif eventcode[x] == counted_behavior_on and (
eventcode[x + 1] == counted_behavior_off or eventcode[x + 1] == code_off):
poke_dur = timecode[x + 1] - timecode[x]
all_poke_dur += [poke_dur]
in_cue_duration += poke_dur
all_cue_duration += [in_cue_duration]
for x in range(iti_on_idx, cue_on_idx):
if eventcode[x] == counted_behavior_on and timecode[x] >= (timecode[cue_on_idx] - cue_length_sec):
if eventcode[x - 1] == code_on and eventcode[x] == counted_behavior_off:
poke_dur = timecode[x] - timecode[x - 1]
all_iti_poke_dur += [poke_dur]
iti_cue_duration += poke_dur
elif eventcode[x] == code_off and eventcode[x - 1] == code_on and eventcode[
x + 1] == counted_behavior_off:
poke_dur = timecode[x] - timecode[x - 1]
all_iti_poke_dur += [poke_dur]
iti_cue_duration += poke_dur
elif eventcode[x] == counted_behavior_on and (
eventcode[x + 1] == counted_behavior_off or eventcode[x + 1] == code_off):
poke_dur = timecode[x + 1] - timecode[x]
all_iti_poke_dur += [poke_dur]
iti_cue_duration += poke_dur
all_iti_duration += [iti_cue_duration]
if not all_cue_duration:
all_cue_duration += [0]
if not all_poke_dur:
all_poke_dur += [0]
if not all_iti_duration:
all_iti_duration += [0]
if not all_iti_poke_dur:
all_iti_poke_dur += [0]
return round(statistics.mean(all_poke_dur), 3), round(statistics.mean(all_cue_duration), 3), \
round(statistics.mean(all_iti_poke_dur), 3), round(statistics.mean(all_iti_duration), 3)
def lever_pressing(eventcode, lever1, lever2=False):
"""
:param eventcode: list of event codes from operant conditioning file
:param lever1: eventcode for lever pressing or
:param lever2: optional parameter for second lever eventcode if two levers are used
:return: count of first lever presses, second lever presses, and total lever presses, as int
"""
lever1_presses = eventcode.count(lever1)
if lever2:
lever2_presses = eventcode.count(lever2)
else:
lever2_presses = 0
total_lever_presses = lever1_presses + lever2_presses
return lever1_presses, lever2_presses, total_lever_presses
def lever_press_latency(timecode, eventcode, lever_on, lever_press):
"""
:param timecode: list of times (in seconds) when events occurred
:param eventcode: list of events that happened in a session
:param lever_on: event name for lever presentation
:param lever_press: event name for lever press
:return: the mean latency to press the lever in seconds
"""
lever_on = get_events_indices(eventcode, [lever_on, 'EndSession'])
press_latency = []
for i in range(len(lever_on) - 1):
lever_on_idx = lever_on[i]
if lever_press in eventcode[lever_on_idx:lever_on[i + 1]]:
lever_press_idx = eventcode[lever_on_idx:lever_on[i + 1]].index(lever_press)
press_latency += [round(timecode[lever_on_idx + lever_press_idx] - timecode[lever_on_idx], 2)]
else:
pass
if len(press_latency) > 0:
return round(statistics.mean(press_latency), 3)
else:
return 0
def lever_press_latency_PavCA(timecode, eventcode, lever_on, lever_press, pres_len):
"""
:param timecode: list of times (in seconds) when events occurred
:param eventcode: list of events that happened in a session
:param lever_on: event name for lever presentation
:param lever_press: event name for lever press
:return: the mean latency to press the lever in seconds
"""
lever_on = get_events_indices(eventcode, [lever_on, 'EndSession'])
press_latency = []
for i in range(len(lever_on) - 1):
lever_on_idx = lever_on[i]
if lever_press in eventcode[lever_on_idx:lever_on[i + 1]]:
lever_press_idx = eventcode[lever_on_idx:lever_on[i + 1]].index(lever_press)
if round(timecode[lever_on_idx + lever_press_idx] - timecode[lever_on_idx], 2) <= pres_len:
press_latency += [round(timecode[lever_on_idx + lever_press_idx] - timecode[lever_on_idx], 2)]
else:
press_latency += [10]
else:
press_latency += [10]
if len(press_latency) > 0:
return round(statistics.mean(press_latency), 3)
else:
return 0
def total_head_pokes(eventcode):
"""
:param eventcode: list of event codes from operant conditioning file
:return: total number of times animal poked head into reward receptacle
"""
return eventcode.count('PokeOn1')
def num_successful_go_nogo_trials(eventcode):
"""
:param eventcode: list of event codes from operant conditioning file
:return: number of successful go and no go trials in the go/no go tasks
"""
return eventcode.count('SuccessfulGoTrial'), eventcode.count('SuccessfulNoGoTrial')
def count_go_nogo_trials(eventcode):
"""
:param eventcode: list of event codes from operant conditioning file
:return: number of go and no go trials in the go/no go tasks
"""
lever_on = get_events_indices(eventcode, ['RLeverOn', 'LLeverOn'])
(go_trials, nogo_trials) = (0, 0)
for lever in lever_on:
if eventcode[lever + 1] in ('LightOn1', 'LightOn2'):
nogo_trials += 1
else:
go_trials += 1
return go_trials, nogo_trials
def num_switch_trials(eventcode):
"""
:param eventcode: list of event codes from operant conditioning file
:return: number of large and small rewards in the switch task
"""
return eventcode.count('LargeReward'), eventcode.count('SmallReward')
def bin_by_time(timecode, eventcode, bin_length, counted_event):
"""
:param timecode: list of time codes from operant conditioning file
:param eventcode: list of event codes from operant conditioning file
:param bin_length: length of time in seconds to split the session into
:param counted_event: event that is counted in each bin, in list format
:return: a list of counts of specified event for each bin
"""
event_on_list = get_events_indices(eventcode, counted_event)
if timecode[-1] % bin_length != 0:
num_bins = int(timecode[-1] // bin_length) + 1
elif timecode[-1] % bin_length == 0:
num_bins = int(timecode[-1] // bin_length)
counts_for_each_bin = [0] * num_bins
for i in range(num_bins):
for event_on in event_on_list:
if (i + 1) != num_bins and (i + 1) * bin_length > timecode[event_on] >= i * bin_length:
counts_for_each_bin[i] += 1
elif (i + 1) == num_bins and timecode[event_on] >= i * bin_length:
counts_for_each_bin[i] += 1
return counts_for_each_bin
def lever_press_lat_gng(timecode, eventcode, lever_on, lever_press):
"""
:param timecode: list of times (in seconds) when events occurred
:param eventcode: list of events that happened in a session
:param lever_on: event name for lever presentation
:param lever_press: event name for lever press
:return: the mean latency to press the lever in seconds
"""
lever_on = get_events_indices(eventcode, [lever_on, 'EndSession'])
press_latency = []
for i in range(len(lever_on) - 1):
lever_on_idx = lever_on[i]
if lever_press in eventcode[lever_on_idx:lever_on[i + 1]]:
lever_press_idx = eventcode[lever_on_idx:lever_on[i + 1]].index(lever_press)
press_latency += [round(timecode[lever_on_idx + lever_press_idx] - timecode[lever_on_idx], 2)]
else:
pass
if len(press_latency) > 0:
return round(statistics.mean(press_latency), 3)
else:
return 0
def RVI_gng_weird(timecode, eventcode, lever_on, lever_press, cue_length):
"""
:param timecode: list of times (in seconds) when events occurred
:param eventcode: list of events that happened in a session
:param lever_on: event name for lever presentation
:param lever_press: event name for lever press
:return: the mean latency to press the lever in seconds
"""
lever_on = get_events_indices(eventcode, [lever_on, 'EndSession'])
press_latency = []
incorrect_trials = 0
for i in range(len(lever_on) - 1):
lever_on_idx = lever_on[i]
if lever_press in eventcode[lever_on_idx:lever_on[i + 1]]:
lever_press_idx = eventcode[lever_on_idx:lever_on[i + 1]].index(lever_press)
press_latency += [round(timecode[lever_on_idx + lever_press_idx] - timecode[lever_on_idx], 2)]
else:
press_latency += [cue_length]
final_press_latency = []
for x in press_latency:
if x > cue_length:
incorrect_trials += 1
else:
final_press_latency += [x]
if len(final_press_latency) > 0:
return round(statistics.mean(final_press_latency), 3), incorrect_trials
else:
return 0, incorrect_trials
def RVI_nogo_latency(timecode, eventcode, lever_on, cue_length):
"""
:param timecode: list of times (in seconds) when events occurred
:param eventcode: list of events that happened in a session
:param lever_on: event name or list for lever presentation
:param lever_press: event name or list for lever press
:return: the mean latency to press the lever in seconds
"""
lever_on = get_events_indices(eventcode, [lever_on, 'EndSession'])
press_latency = []
for i in range(len(lever_on) - 1):
lever_on_idx = lever_on[i]
if 'LPressOn' in eventcode[lever_on_idx:lever_on[i + 1]]:
lever_press_idx = eventcode[lever_on_idx:lever_on[i + 1]].index('LPressOn')
if timecode[lever_on_idx + lever_press_idx] - timecode[lever_on_idx] < cue_length:
press_latency += [round(timecode[lever_on_idx + lever_press_idx] - timecode[lever_on_idx], 2)]
elif 'RPressOn' in eventcode[lever_on_idx:lever_on[i + 1]]:
lever_press_idx = eventcode[lever_on_idx:lever_on[i + 1]].index('RPressOn')
if timecode[lever_on_idx + lever_press_idx] - timecode[lever_on_idx] < cue_length:
press_latency += [round(timecode[lever_on_idx + lever_press_idx] - timecode[lever_on_idx], 2)]
else:
press_latency += [cue_length]
if len(press_latency) > 0:
return round(statistics.mean(press_latency), 3)
else:
return 0
def lever_press_latency_Switch(timecode, eventcode):
"""
:param timecode: list of times (in seconds) when events occurred
:param eventcode: list of events that happened in a session
:param lever_on: event name for lever presentation
:param lever_press: event name for lever press
:return: the mean latency to press the lever in seconds
"""
lever_on = get_events_indices(eventcode, ['LLeverOn', 'RLeverOn', 'EndSession'])
press_latency = []
for i in range(len(lever_on) - 1):
lever_on_idx = lever_on[i]
if len(press_latency) < 10:
if 'LPressOn' in eventcode[lever_on_idx:lever_on[i + 1]]:
lever_press_idx = eventcode[lever_on_idx:lever_on[i + 1]].index('LPressOn')
press_latency += [round(timecode[lever_on_idx + lever_press_idx] - timecode[lever_on_idx], 2)]
elif 'RPressOn' in eventcode[lever_on_idx:lever_on[i + 1]]:
lever_press_idx = eventcode[lever_on_idx:lever_on[i + 1]].index('RPressOn')
press_latency += [round(timecode[lever_on_idx + lever_press_idx] - timecode[lever_on_idx], 2)]
else:
pass
if len(press_latency) > 0:
return round(statistics.mean(press_latency), 3)
else:
return 0
def response_rate_across_cue_iti(timecode, eventcode, code_on, code_off, counted_behavior):
"""
:param timecode: list of times (in seconds) when events occurred
:param eventcode: list of events that happened in a session
:param code_on: event name for lever presentation
:param code_off: event name for lever press
:param code_off: event name for lever press
:return: 3 lists of cue, iti, and the subtracted responding across seconds
"""
cue_on = get_events_indices(eventcode, [code_on])
cue_off = get_events_indices(eventcode, [code_off])
if len(cue_on) != len(cue_off):
cue_off += get_events_indices(eventcode, ['EndSession'])
iti_on = get_events_indices(eventcode, [code_off, 'StartSession'])
cue_length_sec = int(timecode[cue_off[6]] - timecode[cue_on[6]])
all_cue_length_poke_rates = [0] * cue_length_sec
all_iti_length_poke_rates = [0] * cue_length_sec
for i in range(len(cue_on)):
cue_on_idx = cue_on[i]
cue_off_idx = cue_off[i]
iti_on_idx = iti_on[i]
cue_length_poke_rates = []
iti_length_poke_rates = []
for y in range(int(cue_length_sec)):
pokes = 0
iti_pokes = 0
for x in range(cue_on_idx, cue_off_idx):
if eventcode[x] == counted_behavior and (timecode[cue_on_idx] + y) <= timecode[x] < (
timecode[cue_on_idx] + y + 1):
pokes += 1
else:
pokes += 0
cue_length_poke_rates += [pokes]
for t in range(iti_on_idx, cue_on_idx):
if eventcode[t] == counted_behavior and (timecode[cue_on_idx] - (cue_length_sec - y)) \
<= timecode[t] < (timecode[cue_on_idx] - (cue_length_sec - (y + 1))):
iti_pokes += 1
else:
iti_pokes += 0
iti_length_poke_rates += [iti_pokes]
all_cue_length_poke_rates = [cue_length_poke_rates[i] + all_cue_length_poke_rates[i] for i in
range(len(all_cue_length_poke_rates))]
all_iti_length_poke_rates = [iti_length_poke_rates[i] + all_iti_length_poke_rates[i] for i in
range(len(all_iti_length_poke_rates))]
all_cue_length_poke_rates = [all_cue_length_poke_rates[i] / len(cue_on) for i in
range(len(all_cue_length_poke_rates))]
all_iti_length_poke_rates = [all_iti_length_poke_rates[i] / len(cue_on) for i in
range(len(all_iti_length_poke_rates))]
subtracted_poke_rates = [all_cue_length_poke_rates[i] - all_iti_length_poke_rates[i] for i in
range(len(all_cue_length_poke_rates))]
return all_cue_length_poke_rates, all_iti_length_poke_rates, subtracted_poke_rates
def duration_across_cue_iti(timecode, eventcode, code_on, code_off, counted_behavior_on, counted_behavior_off):
"""
:param timecode: list of times (in seconds) when events occurred
:param eventcode: list of events that happened in a session
:param code_on: event name for lever presentation
:param code_off: event name for lever press
:param code_off: event name for lever press
:return: 3 lists of cue, iti, and the subtracted responding across seconds
"""
cue_on = get_events_indices(eventcode, [code_on])
cue_off = get_events_indices(eventcode, [code_off])
poke_on = get_events_indices(eventcode, [counted_behavior_on])
poke_off = get_events_indices(eventcode, [counted_behavior_off])
if len(cue_on) != len(cue_off):
cue_off += get_events_indices(eventcode, ['EndSession'])
cue_length_sec = int(timecode[cue_off[6]] - timecode[cue_on[6]])
all_cue_length_poke_dur = [0] * int(cue_length_sec)
all_iti_length_poke_dur = [0] * int(cue_length_sec)
for i in range(len(cue_on)):
cue_on_idx = cue_on[i]
cue_off_idx = cue_off[i]
cue_length_poke_dur = []
iti_length_poke_dur = []
for y in range(int(cue_length_sec)):
poke_dur = 0
iti_poke_dur = 0
for c in range(len(poke_off)):
# pokes that span whole seconds
if timecode[poke_on[c]] < (timecode[cue_on_idx] + y) and timecode[poke_off[c]] > \
(timecode[cue_on_idx] + y + 1):
poke_dur += 1
break
# pokes contained within a second
elif (timecode[cue_on_idx] + y) <= timecode[poke_on[c]] < timecode[poke_off[c]] \
< (timecode[cue_on_idx] + y + 1):
poke_dur += timecode[poke_off[c]] - timecode[poke_on[c]]
# pokes that start in a second of a cue
elif (timecode[cue_on_idx] + y) <= timecode[poke_on[c]] < (timecode[cue_on_idx] + y + 1) \
< timecode[poke_off[c]]:
poke_dur += ((timecode[cue_on_idx] + y + 1) - timecode[poke_on[c]])
# pokes that end in a second of a cue
elif timecode[poke_on[c]] < (timecode[cue_on_idx] + y) <= timecode[poke_off[c]] \
< (timecode[cue_on_idx] + y + 1):
poke_dur += (timecode[poke_off[c]] - (timecode[cue_on_idx] + y))
# pokes not occurring in the cue
else:
poke_dur += 0
cue_length_poke_dur += [round(poke_dur, 3)]
for d in range(len(poke_off)):
# pokes that span whole seconds
if timecode[poke_on[d]] < (timecode[cue_on_idx] - (cue_length_sec - y)) and timecode[poke_off[d]] \
> (timecode[cue_on_idx] - (cue_length_sec - (y + 1))):
iti_poke_dur += 1
break
# pokes contained within a second
elif (timecode[cue_on_idx] - (cue_length_sec - y)) <= timecode[poke_on[d]] < timecode[poke_off[d]] \
< (timecode[cue_on_idx] - (cue_length_sec - (y + 1))):
iti_poke_dur += (timecode[poke_off[d]] - timecode[poke_on[d]])
# pokes that start in a second of an ITI
elif (timecode[cue_on_idx] - (cue_length_sec - y)) <= timecode[poke_on[d]] \
< (timecode[cue_on_idx] - (cue_length_sec - (y + 1))) < timecode[poke_off[d]]:
iti_poke_dur += ((timecode[cue_on_idx] - (cue_length_sec - (y + 1))) - timecode[poke_on[d]])
# pokes that end in a second of an ITI
elif timecode[poke_on[d]] < (timecode[cue_on_idx] - (cue_length_sec - y)) <= timecode[poke_off[d]] \
< (timecode[cue_on_idx] - (cue_length_sec - (y + 1))):
iti_poke_dur += (timecode[poke_off[d]] - (timecode[cue_on_idx] - (cue_length_sec - y)))
# pokes not occurring in the ITI
else:
iti_poke_dur += 0
iti_length_poke_dur += [round(iti_poke_dur, 3)]
all_cue_length_poke_dur = [cue_length_poke_dur[i] + all_cue_length_poke_dur[i] for i in
range(len(all_cue_length_poke_dur))]
all_iti_length_poke_dur = [iti_length_poke_dur[i] + all_iti_length_poke_dur[i] for i in
range(len(all_iti_length_poke_dur))]
all_cue_length_poke_dur = [all_cue_length_poke_dur[i] / len(cue_on) for i in
range(len(all_iti_length_poke_dur))]
all_iti_length_poke_dur = [all_iti_length_poke_dur[i] / len(cue_on) for i in
range(len(all_iti_length_poke_dur))]
subtracted_poke_dur = [all_cue_length_poke_dur[i] - all_iti_length_poke_dur[i] for i in
range(len(all_cue_length_poke_dur))]
return all_cue_length_poke_dur, all_iti_length_poke_dur, subtracted_poke_dur
def display_line_graph(data_frame, event_name):
"""
:param data_frame: a long-form DataFrame containing data of interest.
:param event_name: Column from data_frame to be graphed.
:return: Creates a plot object that can be displayed with plt.show()
"""
# Begin by compiling and sorting a list of subject IDs.
try:
subject_ids = set(data_frame.loc[:, 'Subject'])
subject_column_name='Subject'
except:
# If subject IDs aren't where expected, ask the user
subject_column_name = input('Unable to find column "Subject". What is the column name? ')
subject_ids = set(data_frame.loc[:, subject_column_name])
subject_ids = sorted(subject_ids)
# Next, do the EXACT same for days. (Copied for ease of variable naming.)
try:
run_days = set(data_frame.loc[:, 'Day'])
day_column_name='Day'
except:
day_column_name = input('Unable to find column "Day". What is the column name? ')
run_days = set(data_frame.loc[:, day_column_name])
run_days = sorted(run_days)
# Use the verified column names to ensure that data_frame is sorted by Day in ascending order.
data_frame.sort_values(by=[day_column_name], ascending=True, inplace=True)
# Then create and populate the short-form DataFrame
short_form_DF = pd.DataFrame(index=subject_ids, columns=run_days)
plt.figure(event_name)
for mouse in subject_ids:
mouse_idx = data_frame[data_frame[subject_column_name]==mouse].index
raw_mouse_data = data_frame.loc[mouse_idx, event_name].values
try:
short_form_DF.loc[mouse, run_days] = raw_mouse_data
# In the rare case that an animal is run twice in a day (e.g. during trough training)
# There will be a value error. Just drop a data point for ease of graphing here.
except ValueError:
print(f'{mouse} has {len(raw_mouse_data)} datapoints, but there are only {len(run_days)} run days.')
print(data_frame.loc[mouse_idx])
day_to_drop = int(input('Which datapoint would you like to drop (enter 0-ordered index)? '))
raw_mouse_data = np.delete(raw_mouse_data, day_to_drop)
plt.plot(range(1, len(raw_mouse_data)+1), raw_mouse_data, marker='o')
plt.title(event_name)
plt.xlabel('Days')
# The below is taken from https://stackoverflow.com/a/47166787
# Someday, it would be nice to try to adapt this to display the
# subject ID upon mousing over each line.
# x = np.sort(np.random.rand(15))
# y = np.sort(np.random.rand(15))
# names = np.array(list("ABCDEFGHIJKLMNO"))
# norm = plt.Normalize(1,4)
# cmap = plt.cm.RdYlGn
# fig,ax = plt.subplots()
# line, = plt.plot(x,y, marker="o")
# annot = ax.annotate("", xy=(0,0), xytext=(-20,20),textcoords="offset points",
# bbox=dict(boxstyle="round", fc="w"),
# arrowprops=dict(arrowstyle="->"))
# annot.set_visible(False)
# def update_annot(ind):
# x,y = line.get_data()
# annot.xy = (x[ind["ind"][0]], y[ind["ind"][0]])
# text = "{}, {}".format(" ".join(list(map(str,ind["ind"]))),
# " ".join([names[n] for n in ind["ind"]]))
# annot.set_text(text)
# annot.get_bbox_patch().set_alpha(0.4)
# def hover(event):
# vis = annot.get_visible()
# if event.inaxes == ax:
# cont, ind = line.contains(event)
# if cont:
# update_annot(ind)
# annot.set_visible(True)
# fig.canvas.draw_idle()
# else:
# if vis:
# annot.set_visible(False)
# fig.canvas.draw_idle()
# fig.canvas.mpl_connect("motion_notify_event", hover)
# plt.show()
| [
"statistics.mean",
"tkinter.filedialog.askdirectory",
"pandas.read_csv",
"datetime.datetime.strptime",
"numpy.delete",
"matplotlib.pyplot.xlabel",
"os.path.join",
"pandas.DataFrame.from_dict",
"matplotlib.pyplot.figure",
"glob.glob",
"natsort.natsorted",
"pandas.to_numeric",
"pandas.DataFram... | [((4274, 4307), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'column_list'}), '(columns=column_list)\n', (4286, 4307), True, 'import pandas as pd\n'), ((5395, 5428), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'column_list'}), '(columns=column_list)\n', (5407, 5428), True, 'import pandas as pd\n'), ((7180, 7203), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (7198, 7203), False, 'import os\n'), ((7285, 7325), 'tkinter.filedialog.askdirectory', 'filedialog.askdirectory', ([], {'initialdir': 'home'}), '(initialdir=home)\n', (7308, 7325), False, 'from tkinter import filedialog\n'), ((7345, 7383), 'os.path.join', 'os.path.join', (['selected_folder', '"""*.txt"""'], {}), "(selected_folder, '*.txt')\n", (7357, 7383), False, 'import os\n'), ((7994, 8043), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['data_dict'], {'orient': '"""index"""'}), "(data_dict, orient='index')\n", (8016, 8043), True, 'import pandas as pd\n'), ((10123, 10156), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'column_list'}), '(columns=column_list)\n', (10135, 10156), True, 'import pandas as pd\n'), ((10704, 10764), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'sep': '""":"""', 'names': "['event', 'timestamp']"}), "(filename, sep=':', names=['event', 'timestamp'])\n", (10715, 10764), True, 'import pandas as pd\n'), ((41480, 41529), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'subject_ids', 'columns': 'run_days'}), '(index=subject_ids, columns=run_days)\n', (41492, 41529), True, 'import pandas as pd\n'), ((41535, 41557), 'matplotlib.pyplot.figure', 'plt.figure', (['event_name'], {}), '(event_name)\n', (41545, 41557), True, 'import matplotlib.pyplot as plt\n'), ((42442, 42463), 'matplotlib.pyplot.title', 'plt.title', (['event_name'], {}), '(event_name)\n', (42451, 42463), True, 'import matplotlib.pyplot as plt\n'), ((42468, 42486), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Days"""'], {}), "('Days')\n", (42478, 42486), True, 'import matplotlib.pyplot as plt\n'), ((1942, 2001), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['sanitized_string_date', 'date_fmt'], {}), '(sanitized_string_date, date_fmt)\n', (1968, 2001), False, 'import datetime\n'), ((3676, 3718), 'natsort.natsorted', 'natsorted', (['data_folders'], {'key': 'date_sort_key'}), '(data_folders, key=date_sort_key)\n', (3685, 3718), False, 'from natsort import natsorted, ns\n'), ((4674, 4708), 'os.path.join', 'os.path.join', (['folder_selected', '"""*"""'], {}), "(folder_selected, '*')\n", (4686, 4708), False, 'import os\n'), ((5534, 5559), 'tkinter.filedialog.askdirectory', 'filedialog.askdirectory', ([], {}), '()\n', (5557, 5559), False, 'from tkinter import filedialog\n'), ((5583, 5617), 'os.path.join', 'os.path.join', (['folder_selected', '"""*"""'], {}), "(folder_selected, '*')\n", (5595, 5617), False, 'import os\n'), ((7430, 7453), 'glob.glob', 'glob.glob', (['file_pattern'], {}), '(file_pattern)\n', (7439, 7453), False, 'import glob\n'), ((8304, 8349), 'pandas.to_numeric', 'pd.to_numeric', (['lick_final[c]'], {'errors': '"""coerce"""'}), "(lick_final[c], errors='coerce')\n", (8317, 8349), True, 'import pandas as pd\n'), ((10262, 10287), 'tkinter.filedialog.askdirectory', 'filedialog.askdirectory', ([], {}), '()\n', (10285, 10287), False, 'from tkinter import filedialog\n'), ((10311, 10345), 'os.path.join', 'os.path.join', (['folder_selected', '"""*"""'], {}), "(folder_selected, '*')\n", (10323, 10345), False, 'import os\n'), ((2659, 2718), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['sanitized_string_date', 'date_fmt'], {}), '(sanitized_string_date, date_fmt)\n', (2685, 2718), False, 'import datetime\n'), ((3614, 3651), 'os.path.join', 'os.path.join', (['master_data_folder', '"""*"""'], {}), "(master_data_folder, '*')\n", (3626, 3651), False, 'import os\n'), ((4498, 4523), 'tkinter.filedialog.askdirectory', 'filedialog.askdirectory', ([], {}), '()\n', (4521, 4523), False, 'from tkinter import filedialog\n'), ((4736, 4759), 'glob.glob', 'glob.glob', (['file_pattern'], {}), '(file_pattern)\n', (4745, 4759), False, 'import glob\n'), ((5645, 5668), 'glob.glob', 'glob.glob', (['file_pattern'], {}), '(file_pattern)\n', (5654, 5668), False, 'import glob\n'), ((10373, 10396), 'glob.glob', 'glob.glob', (['file_pattern'], {}), '(file_pattern)\n', (10382, 10396), False, 'import glob\n'), ((14850, 14879), 'statistics.mean', 'statistics.mean', (['all_poke_rpm'], {}), '(all_poke_rpm)\n', (14865, 14879), False, 'import statistics\n'), ((14891, 14924), 'statistics.mean', 'statistics.mean', (['all_poke_iti_rpm'], {}), '(all_poke_iti_rpm)\n', (14906, 14924), False, 'import statistics\n'), ((16608, 16637), 'statistics.mean', 'statistics.mean', (['all_poke_rpm'], {}), '(all_poke_rpm)\n', (16623, 16637), False, 'import statistics\n'), ((16649, 16682), 'statistics.mean', 'statistics.mean', (['all_poke_iti_rpm'], {}), '(all_poke_iti_rpm)\n', (16664, 16682), False, 'import statistics\n'), ((18241, 18270), 'statistics.mean', 'statistics.mean', (['all_poke_rpm'], {}), '(all_poke_rpm)\n', (18256, 18270), False, 'import statistics\n'), ((18282, 18315), 'statistics.mean', 'statistics.mean', (['all_poke_iti_rpm'], {}), '(all_poke_iti_rpm)\n', (18297, 18315), False, 'import statistics\n'), ((21873, 21902), 'statistics.mean', 'statistics.mean', (['all_poke_dur'], {}), '(all_poke_dur)\n', (21888, 21902), False, 'import statistics\n'), ((21914, 21947), 'statistics.mean', 'statistics.mean', (['all_cue_duration'], {}), '(all_cue_duration)\n', (21929, 21947), False, 'import statistics\n'), ((21972, 22005), 'statistics.mean', 'statistics.mean', (['all_iti_poke_dur'], {}), '(all_iti_poke_dur)\n', (21987, 22005), False, 'import statistics\n'), ((22017, 22050), 'statistics.mean', 'statistics.mean', (['all_iti_duration'], {}), '(all_iti_duration)\n', (22032, 22050), False, 'import statistics\n'), ((23607, 23637), 'statistics.mean', 'statistics.mean', (['press_latency'], {}), '(press_latency)\n', (23622, 23637), False, 'import statistics\n'), ((24768, 24798), 'statistics.mean', 'statistics.mean', (['press_latency'], {}), '(press_latency)\n', (24783, 24798), False, 'import statistics\n'), ((28135, 28165), 'statistics.mean', 'statistics.mean', (['press_latency'], {}), '(press_latency)\n', (28150, 28165), False, 'import statistics\n'), ((30837, 30867), 'statistics.mean', 'statistics.mean', (['press_latency'], {}), '(press_latency)\n', (30852, 30867), False, 'import statistics\n'), ((32128, 32158), 'statistics.mean', 'statistics.mean', (['press_latency'], {}), '(press_latency)\n', (32143, 32158), False, 'import statistics\n'), ((13134, 13172), 'statistics.mean', 'statistics.mean', (['latency_dip_retrieval'], {}), '(latency_dip_retrieval)\n', (13149, 13172), False, 'import statistics\n'), ((29334, 29370), 'statistics.mean', 'statistics.mean', (['final_press_latency'], {}), '(final_press_latency)\n', (29349, 29370), False, 'import statistics\n'), ((42319, 42357), 'numpy.delete', 'np.delete', (['raw_mouse_data', 'day_to_drop'], {}), '(raw_mouse_data, day_to_drop)\n', (42328, 42357), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
boot script, do initial stuff here, similar to the setup() function on Arduino
"""
import esp
import gc
import network
import time
# custom packages
from be_helpers.led_helper import Led
# set clock speed to 240MHz instead of default 160MHz
# machine.freq(240000000)
# disable ESP os debug output
esp.osdebug(None)
led = Led()
led.flash(amount=3, delay_ms=50)
led.turn_on()
station = network.WLAN(network.STA_IF)
if station.active() and station.isconnected():
station.disconnect()
time.sleep(1)
station.active(False)
time.sleep(1)
station.active(True)
led.turn_off()
# run garbage collector at the end to clean up
gc.collect()
print('Finished booting')
| [
"be_helpers.led_helper.Led",
"time.sleep",
"network.WLAN",
"gc.collect",
"esp.osdebug"
] | [((354, 371), 'esp.osdebug', 'esp.osdebug', (['None'], {}), '(None)\n', (365, 371), False, 'import esp\n'), ((379, 384), 'be_helpers.led_helper.Led', 'Led', ([], {}), '()\n', (382, 384), False, 'from be_helpers.led_helper import Led\n'), ((443, 471), 'network.WLAN', 'network.WLAN', (['network.STA_IF'], {}), '(network.STA_IF)\n', (455, 471), False, 'import network\n'), ((584, 597), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (594, 597), False, 'import time\n'), ((683, 695), 'gc.collect', 'gc.collect', ([], {}), '()\n', (693, 695), False, 'import gc\n'), ((548, 561), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (558, 561), False, 'import time\n')] |
#!/usr/bin/env python
# -*- coding: utf8 -*-
import os
from functools import reduce
from Log import log
__title__ = 'Structure runner'
__all__ = ['Structure']
__author__ = '<NAME> <<EMAIL>>'
class Structure(object):
@staticmethod
def get_directory_structure(confdir: str) -> dict:
"""
Creates a nested dictionary representing folder structure of confdir
"""
from functools import reduce
out = {}
confdir = confdir.rstrip(os.sep)
start = confdir.rfind(os.sep) + 1
for path, dirs, files in os.walk(confdir):
folders = path[start:].split(os.sep)
subdir = dict.fromkeys(files)
parent = reduce(dict.get, folders[:-1], out)
parent[folders[-1]] = subdir
return out
@staticmethod
def get_file_list(confdir: str) -> list:
"""
Creates list of all files in the given directory structure
"""
paths = []
for root, dirs, files in os.walk(confdir):
for filename in files:
filepath = os.path.join(root, filename)
paths.append(filepath)
return paths
@staticmethod
def get_ini_files(confdir: str) -> list:
"""
Creates list of all files with .ini extension in the given
directory structure
"""
return [f for f in Structure.get_file_list(confdir) if f.endswith('.ini')]
@staticmethod
def get_xml_files(confdir: str) -> list:
"""
Creates list of all files with .xml extension in the given
directory structure
"""
return [f for f in Structure.get_file_list(confdir) if f.endswith('.xml')]
@staticmethod
def get_yaml_files(confdir: str) -> list:
"""
Creates list of all files with .yaml extension in the given
directory structure
"""
return [f for f in Structure.get_file_list(confdir) if f.endswith('.yaml')]
@staticmethod
def get_json_files(confdir: str) -> list:
"""
Creates list of all files with .yml extension in the given
directory structure
"""
return [f for f in Structure.get_file_list(confdir) if f.endswith('.json')]
class Parser(object):
@staticmethod
def get_all_config(confdir: str) -> list:
"""
Walks over confdir and returns parsed configs
"""
out = []
for each in Structure.get_json_files(confdir):
out.append(Parser.read_json(each))
for each in Structure.get_ini_files(confdir):
out.append(Parser.read_ini(each))
for each in Structure.get_yaml_files(confdir):
out.append(Parser.read_yaml(each))
for each in Structure.get_xml_files(confdir):
out.append(Parser.read_xml(each))
return out
@staticmethod
def read_json(cfile: str) -> list:
"""
Opens JSON conf file and returns its contents.
"""
import json
try:
with open(cfile, 'r') as json_file:
return json.load(json_file)
except Exception as e:
log.error(e)
@staticmethod
def read_yaml(cfile: str) -> list:
"""
Opens YAML conf file and returns its contents.
"""
import yaml
try:
with open(cfile, 'r') as yaml_file:
conf = yaml.load(yaml_file)
return [each for each in conf.items()]
except Exception as e:
log.error(e)
@staticmethod
def read_ini(cfile: str) -> list:
"""
Opens INI conf file and returns its contents.
"""
from configparser import ConfigParser
config = ConfigParser()
out = []
try:
config.read(cfile)
sections = config.sections()
for section in sections:
items = config.items(section)
out.append({section: {item[0]: item[1] for item in items}})
return out
except Exception as e:
log.error(e)
@staticmethod
def read_xml(cfile: str) -> list:
"""
Opens XML conf file and returns its contents.
"""
import xml.etree.ElementTree as xmlparser
out = []
try:
tree = xmlparser.parse(cfile)
root = tree.getroot()
for device in root.findall('device'):
out.append(
{device.attrib['name']:
{'ip': device.find('ip').text,
'user': device.find('user').text,
'password': device.find('password').text}})
return out
except Exception as e:
log.error(e)
| [
"Log.log.error",
"xml.etree.ElementTree.parse",
"configparser.ConfigParser",
"functools.reduce",
"os.path.join",
"yaml.load",
"json.load",
"os.walk"
] | [((565, 581), 'os.walk', 'os.walk', (['confdir'], {}), '(confdir)\n', (572, 581), False, 'import os\n'), ((998, 1014), 'os.walk', 'os.walk', (['confdir'], {}), '(confdir)\n', (1005, 1014), False, 'import os\n'), ((3732, 3746), 'configparser.ConfigParser', 'ConfigParser', ([], {}), '()\n', (3744, 3746), False, 'from configparser import ConfigParser\n'), ((695, 730), 'functools.reduce', 'reduce', (['dict.get', 'folders[:-1]', 'out'], {}), '(dict.get, folders[:-1], out)\n', (701, 730), False, 'from functools import reduce\n'), ((4321, 4343), 'xml.etree.ElementTree.parse', 'xmlparser.parse', (['cfile'], {}), '(cfile)\n', (4336, 4343), True, 'import xml.etree.ElementTree as xmlparser\n'), ((1078, 1106), 'os.path.join', 'os.path.join', (['root', 'filename'], {}), '(root, filename)\n', (1090, 1106), False, 'import os\n'), ((3084, 3104), 'json.load', 'json.load', (['json_file'], {}), '(json_file)\n', (3093, 3104), False, 'import json\n'), ((3148, 3160), 'Log.log.error', 'log.error', (['e'], {}), '(e)\n', (3157, 3160), False, 'from Log import log\n'), ((3402, 3422), 'yaml.load', 'yaml.load', (['yaml_file'], {}), '(yaml_file)\n', (3411, 3422), False, 'import yaml\n'), ((3521, 3533), 'Log.log.error', 'log.error', (['e'], {}), '(e)\n', (3530, 3533), False, 'from Log import log\n'), ((4074, 4086), 'Log.log.error', 'log.error', (['e'], {}), '(e)\n', (4083, 4086), False, 'from Log import log\n'), ((4749, 4761), 'Log.log.error', 'log.error', (['e'], {}), '(e)\n', (4758, 4761), False, 'from Log import log\n')] |
import ray
from ray.experimental.workflow import storage
from ray.experimental.workflow import workflow_storage
def some_func(x):
return x + 1
def some_func2(x):
return x - 1
def test_raw_storage():
ray.init()
workflow_id = test_workflow_storage.__name__
raw_storage = storage.get_global_storage()
step_id = "some_step"
input_metadata = {"2": "c"}
output_metadata = {"a": 1}
args = ([1, "2"], {"k": b"543"})
output = ["the_answer"]
object_resolved = 42
obj_ref = ray.put(object_resolved)
# test creating normal objects
raw_storage.save_step_input_metadata(workflow_id, step_id, input_metadata)
raw_storage.save_step_func_body(workflow_id, step_id, some_func)
raw_storage.save_step_args(workflow_id, step_id, args)
raw_storage.save_object_ref(workflow_id, obj_ref)
raw_storage.save_step_output_metadata(workflow_id, step_id,
output_metadata)
raw_storage.save_step_output(workflow_id, step_id, output)
step_status = raw_storage.get_step_status(workflow_id, step_id)
assert step_status.args_exists
assert step_status.output_object_exists
assert step_status.output_metadata_exists
assert step_status.input_metadata_exists
assert step_status.func_body_exists
assert raw_storage.load_step_input_metadata(workflow_id,
step_id) == input_metadata
assert raw_storage.load_step_func_body(workflow_id, step_id)(33) == 34
assert raw_storage.load_step_args(workflow_id, step_id) == args
assert ray.get(raw_storage.load_object_ref(
workflow_id, obj_ref.hex())) == object_resolved
assert raw_storage.load_step_output_metadata(workflow_id,
step_id) == output_metadata
assert raw_storage.load_step_output(workflow_id, step_id) == output
# test overwrite
input_metadata = [input_metadata, "overwrite"]
output_metadata = [output_metadata, "overwrite"]
args = (args, "overwrite")
output = (output, "overwrite")
object_resolved = (object_resolved, "overwrite")
obj_ref = ray.put(object_resolved)
raw_storage.save_step_input_metadata(workflow_id, step_id, input_metadata)
raw_storage.save_step_func_body(workflow_id, step_id, some_func2)
raw_storage.save_step_args(workflow_id, step_id, args)
raw_storage.save_object_ref(workflow_id, obj_ref)
raw_storage.save_step_output_metadata(workflow_id, step_id,
output_metadata)
raw_storage.save_step_output(workflow_id, step_id, output)
assert raw_storage.load_step_input_metadata(workflow_id,
step_id) == input_metadata
assert raw_storage.load_step_func_body(workflow_id, step_id)(33) == 32
assert raw_storage.load_step_args(workflow_id, step_id) == args
assert ray.get(raw_storage.load_object_ref(
workflow_id, obj_ref.hex())) == object_resolved
assert raw_storage.load_step_output_metadata(workflow_id,
step_id) == output_metadata
assert raw_storage.load_step_output(workflow_id, step_id) == output
ray.shutdown()
def test_workflow_storage():
ray.init()
workflow_id = test_workflow_storage.__name__
raw_storage = storage.get_global_storage()
step_id = "some_step"
input_metadata = {
"name": "test_basic_workflows.append1",
"object_refs": ["abc"],
"workflows": ["def"]
}
output_metadata = {
"output_step_id": "a12423",
"dynamic_output_step_id": "b1234"
}
args = ([1, "2"], {"k": b"543"})
output = ["the_answer"]
object_resolved = 42
obj_ref = ray.put(object_resolved)
# test basics
raw_storage.save_step_input_metadata(workflow_id, step_id, input_metadata)
raw_storage.save_step_func_body(workflow_id, step_id, some_func)
raw_storage.save_step_args(workflow_id, step_id, args)
raw_storage.save_object_ref(workflow_id, obj_ref)
raw_storage.save_step_output_metadata(workflow_id, step_id,
output_metadata)
raw_storage.save_step_output(workflow_id, step_id, output)
wf_storage = workflow_storage.WorkflowStorage(workflow_id)
assert wf_storage.load_step_output(step_id) == output
assert wf_storage.load_step_args(step_id, [], []) == args
assert wf_storage.load_step_func_body(step_id)(33) == 34
assert ray.get(wf_storage.load_object_ref(
obj_ref.hex())) == object_resolved
# test "inspect_step"
inspect_result = wf_storage.inspect_step(step_id)
assert inspect_result == workflow_storage.StepInspectResult(
output_object_valid=True)
assert inspect_result.is_recoverable()
step_id = "some_step2"
raw_storage.save_step_input_metadata(workflow_id, step_id, input_metadata)
raw_storage.save_step_func_body(workflow_id, step_id, some_func)
raw_storage.save_step_args(workflow_id, step_id, args)
raw_storage.save_step_output_metadata(workflow_id, step_id,
output_metadata)
inspect_result = wf_storage.inspect_step(step_id)
assert inspect_result == workflow_storage.StepInspectResult(
output_step_id=output_metadata["dynamic_output_step_id"])
assert inspect_result.is_recoverable()
step_id = "some_step3"
raw_storage.save_step_input_metadata(workflow_id, step_id, input_metadata)
raw_storage.save_step_func_body(workflow_id, step_id, some_func)
raw_storage.save_step_args(workflow_id, step_id, args)
inspect_result = wf_storage.inspect_step(step_id)
assert inspect_result == workflow_storage.StepInspectResult(
args_valid=True,
func_body_valid=True,
object_refs=input_metadata["object_refs"],
workflows=input_metadata["workflows"])
assert inspect_result.is_recoverable()
step_id = "some_step4"
raw_storage.save_step_input_metadata(workflow_id, step_id, input_metadata)
raw_storage.save_step_func_body(workflow_id, step_id, some_func)
inspect_result = wf_storage.inspect_step(step_id)
assert inspect_result == workflow_storage.StepInspectResult(
func_body_valid=True,
object_refs=input_metadata["object_refs"],
workflows=input_metadata["workflows"])
assert not inspect_result.is_recoverable()
step_id = "some_step5"
raw_storage.save_step_input_metadata(workflow_id, step_id, input_metadata)
inspect_result = wf_storage.inspect_step(step_id)
assert inspect_result == workflow_storage.StepInspectResult(
object_refs=input_metadata["object_refs"],
workflows=input_metadata["workflows"])
assert not inspect_result.is_recoverable()
step_id = "some_step6"
inspect_result = wf_storage.inspect_step(step_id)
assert inspect_result == workflow_storage.StepInspectResult()
assert not inspect_result.is_recoverable()
ray.shutdown()
| [
"ray.shutdown",
"ray.experimental.workflow.workflow_storage.WorkflowStorage",
"ray.experimental.workflow.storage.get_global_storage",
"ray.put",
"ray.init",
"ray.experimental.workflow.workflow_storage.StepInspectResult"
] | [((217, 227), 'ray.init', 'ray.init', ([], {}), '()\n', (225, 227), False, 'import ray\n'), ((295, 323), 'ray.experimental.workflow.storage.get_global_storage', 'storage.get_global_storage', ([], {}), '()\n', (321, 323), False, 'from ray.experimental.workflow import storage\n'), ((517, 541), 'ray.put', 'ray.put', (['object_resolved'], {}), '(object_resolved)\n', (524, 541), False, 'import ray\n'), ((2158, 2182), 'ray.put', 'ray.put', (['object_resolved'], {}), '(object_resolved)\n', (2165, 2182), False, 'import ray\n'), ((3231, 3245), 'ray.shutdown', 'ray.shutdown', ([], {}), '()\n', (3243, 3245), False, 'import ray\n'), ((3281, 3291), 'ray.init', 'ray.init', ([], {}), '()\n', (3289, 3291), False, 'import ray\n'), ((3359, 3387), 'ray.experimental.workflow.storage.get_global_storage', 'storage.get_global_storage', ([], {}), '()\n', (3385, 3387), False, 'from ray.experimental.workflow import storage\n'), ((3764, 3788), 'ray.put', 'ray.put', (['object_resolved'], {}), '(object_resolved)\n', (3771, 3788), False, 'import ray\n'), ((4273, 4318), 'ray.experimental.workflow.workflow_storage.WorkflowStorage', 'workflow_storage.WorkflowStorage', (['workflow_id'], {}), '(workflow_id)\n', (4305, 4318), False, 'from ray.experimental.workflow import workflow_storage\n'), ((6990, 7004), 'ray.shutdown', 'ray.shutdown', ([], {}), '()\n', (7002, 7004), False, 'import ray\n'), ((4700, 4760), 'ray.experimental.workflow.workflow_storage.StepInspectResult', 'workflow_storage.StepInspectResult', ([], {'output_object_valid': '(True)'}), '(output_object_valid=True)\n', (4734, 4760), False, 'from ray.experimental.workflow import workflow_storage\n'), ((5254, 5351), 'ray.experimental.workflow.workflow_storage.StepInspectResult', 'workflow_storage.StepInspectResult', ([], {'output_step_id': "output_metadata['dynamic_output_step_id']"}), "(output_step_id=output_metadata[\n 'dynamic_output_step_id'])\n", (5288, 5351), False, 'from ray.experimental.workflow import workflow_storage\n'), ((5717, 5881), 'ray.experimental.workflow.workflow_storage.StepInspectResult', 'workflow_storage.StepInspectResult', ([], {'args_valid': '(True)', 'func_body_valid': '(True)', 'object_refs': "input_metadata['object_refs']", 'workflows': "input_metadata['workflows']"}), "(args_valid=True, func_body_valid=True,\n object_refs=input_metadata['object_refs'], workflows=input_metadata[\n 'workflows'])\n", (5751, 5881), False, 'from ray.experimental.workflow import workflow_storage\n'), ((6208, 6351), 'ray.experimental.workflow.workflow_storage.StepInspectResult', 'workflow_storage.StepInspectResult', ([], {'func_body_valid': '(True)', 'object_refs': "input_metadata['object_refs']", 'workflows': "input_metadata['workflows']"}), "(func_body_valid=True, object_refs=\n input_metadata['object_refs'], workflows=input_metadata['workflows'])\n", (6242, 6351), False, 'from ray.experimental.workflow import workflow_storage\n'), ((6609, 6730), 'ray.experimental.workflow.workflow_storage.StepInspectResult', 'workflow_storage.StepInspectResult', ([], {'object_refs': "input_metadata['object_refs']", 'workflows': "input_metadata['workflows']"}), "(object_refs=input_metadata['object_refs'\n ], workflows=input_metadata['workflows'])\n", (6643, 6730), False, 'from ray.experimental.workflow import workflow_storage\n'), ((6901, 6937), 'ray.experimental.workflow.workflow_storage.StepInspectResult', 'workflow_storage.StepInspectResult', ([], {}), '()\n', (6935, 6937), False, 'from ray.experimental.workflow import workflow_storage\n')] |
from django.db import models
from django.utils import timezone
class BaseCoin(models.Model):
date = models.DateField(default=timezone.now)
exchange = models.CharField(max_length=100, blank=True, default='')
price = models.DecimalField(max_digits=12, decimal_places=4, default=0)
high = models.DecimalField(max_digits=12, decimal_places=4, default=0)
low = models.DecimalField(max_digits=12, decimal_places=4, default=0)
close = models.DecimalField(max_digits=12, decimal_places=4, default=0)
volume = models.DecimalField(max_digits=12, decimal_places=4, default=0)
class Meta:
abstract = True
ordering = ('date',)
class BTC(BaseCoin):
market_cap = models.DecimalField(max_digits=18, decimal_places=8, default=0)
class ETH(BaseCoin):
market_cap = models.DecimalField(max_digits=18, decimal_places=8, default=0)
class LTC(BaseCoin):
market_cap = models.DecimalField(max_digits=18, decimal_places=8, default=0)
| [
"django.db.models.DecimalField",
"django.db.models.DateField",
"django.db.models.CharField"
] | [((106, 144), 'django.db.models.DateField', 'models.DateField', ([], {'default': 'timezone.now'}), '(default=timezone.now)\n', (122, 144), False, 'from django.db import models\n'), ((160, 216), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)', 'blank': '(True)', 'default': '""""""'}), "(max_length=100, blank=True, default='')\n", (176, 216), False, 'from django.db import models\n'), ((229, 292), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(12)', 'decimal_places': '(4)', 'default': '(0)'}), '(max_digits=12, decimal_places=4, default=0)\n', (248, 292), False, 'from django.db import models\n'), ((304, 367), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(12)', 'decimal_places': '(4)', 'default': '(0)'}), '(max_digits=12, decimal_places=4, default=0)\n', (323, 367), False, 'from django.db import models\n'), ((378, 441), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(12)', 'decimal_places': '(4)', 'default': '(0)'}), '(max_digits=12, decimal_places=4, default=0)\n', (397, 441), False, 'from django.db import models\n'), ((454, 517), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(12)', 'decimal_places': '(4)', 'default': '(0)'}), '(max_digits=12, decimal_places=4, default=0)\n', (473, 517), False, 'from django.db import models\n'), ((531, 594), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(12)', 'decimal_places': '(4)', 'default': '(0)'}), '(max_digits=12, decimal_places=4, default=0)\n', (550, 594), False, 'from django.db import models\n'), ((705, 768), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(8)', 'default': '(0)'}), '(max_digits=18, decimal_places=8, default=0)\n', (724, 768), False, 'from django.db import models\n'), ((809, 872), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(8)', 'default': '(0)'}), '(max_digits=18, decimal_places=8, default=0)\n', (828, 872), False, 'from django.db import models\n'), ((913, 976), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(8)', 'default': '(0)'}), '(max_digits=18, decimal_places=8, default=0)\n', (932, 976), False, 'from django.db import models\n')] |
from __future__ import print_function
from ghidra.program.model.address import Address
import platform
import ghidra
if (platform.system() != "Java"):
from ghidra_builtins import *
monitor = ghidra.util.task.TaskMonitor.DUMMY
def getFuncInstructions(function):
instructions = []
instruction = getFirstInstruction(function)
while function.getBody().contains(instruction.address):
instructions += [instruction]
instruction = instruction.getNext()
if instruction is None:
break
return instructions
def getNamespace(hierarchy):
symbolTable = currentProgram.getSymbolTable()
namespace = None
for name in hierarchy:
next = symbolTable.getNamespace(name, namespace)
if next is None:
next = symbolTable.createNameSpace(namespace, name, ghidra.program.model.symbol.SourceType.USER_DEFINED)
namespace = next
return namespace
def maskedSearch(values, mask, addr_set = None, max_count = 99):
# type: (...) -> List[Address]
search_data = ghidra.app.plugin.core.searchmem.SearchData.createSearchData(
"search", values, mask)
search_info = ghidra.util.search.memory.SearchInfo(search_data, max_count, True, True, 1, False, None)
select = ghidra.program.util.ProgramSelection(currentProgram.getMinAddress(), currentProgram.getMaxAddress())
if addr_set is not None:
select = ghidra.program.util.ProgramSelection(addr_set)
alg = search_info.createSearchAlgorithm(currentProgram, currentProgram.getMinAddress(), select)
acc = ghidra.util.datastruct.ListAccumulator()
alg.search(acc, monitor)
return [i.getAddress() for i in acc]
def findResourcePtr(name, vtableStartOffset):
namespace = getNamespace(['MH', 'Quest', name])
search = 'r' + name
addr = maskedSearch([ord(i) for i in search],
[-1 for _ in search], max_count=1)[0] # type: Address
data = createData(addr.add(vtableStartOffset), ghidra.program.model.data.PointerDataType())
createLabel(data.getAddress(), "ResourceVtable", False).setNamespace(namespace)
print(addr.add(vtableStartOffset))
addr = toAddr(getLong(addr.add(vtableStartOffset)))
ghidra.app.cmd.disassemble.DisassembleCommand(addr, None, True).applyTo(currentProgram, monitor)
func = createFunction(addr, "ResourceFunc")
instructions = getFuncInstructions(func)
instruction = instructions[3]
addr = instruction.getOpObjects(1)[0]
symbol = createLabel(toAddr(addr.getValue()), "ResourcePtr", False)
symbol.setNamespace(namespace)
func.setParentNamespace(namespace)
findResourcePtr('QuestData', -0x58)
findResourcePtr('QuestNoList', -0x18)
| [
"ghidra.app.cmd.disassemble.DisassembleCommand",
"ghidra.program.util.ProgramSelection",
"ghidra.util.datastruct.ListAccumulator",
"ghidra.program.model.data.PointerDataType",
"ghidra.util.search.memory.SearchInfo",
"platform.system",
"ghidra.app.plugin.core.searchmem.SearchData.createSearchData"
] | [((123, 140), 'platform.system', 'platform.system', ([], {}), '()\n', (138, 140), False, 'import platform\n'), ((1047, 1135), 'ghidra.app.plugin.core.searchmem.SearchData.createSearchData', 'ghidra.app.plugin.core.searchmem.SearchData.createSearchData', (['"""search"""', 'values', 'mask'], {}), "('search',\n values, mask)\n", (1107, 1135), False, 'import ghidra\n'), ((1159, 1251), 'ghidra.util.search.memory.SearchInfo', 'ghidra.util.search.memory.SearchInfo', (['search_data', 'max_count', '(True)', '(True)', '(1)', '(False)', 'None'], {}), '(search_data, max_count, True, True, 1,\n False, None)\n', (1195, 1251), False, 'import ghidra\n'), ((1565, 1605), 'ghidra.util.datastruct.ListAccumulator', 'ghidra.util.datastruct.ListAccumulator', ([], {}), '()\n', (1603, 1605), False, 'import ghidra\n'), ((1408, 1454), 'ghidra.program.util.ProgramSelection', 'ghidra.program.util.ProgramSelection', (['addr_set'], {}), '(addr_set)\n', (1444, 1454), False, 'import ghidra\n'), ((1979, 2022), 'ghidra.program.model.data.PointerDataType', 'ghidra.program.model.data.PointerDataType', ([], {}), '()\n', (2020, 2022), False, 'import ghidra\n'), ((2207, 2270), 'ghidra.app.cmd.disassemble.DisassembleCommand', 'ghidra.app.cmd.disassemble.DisassembleCommand', (['addr', 'None', '(True)'], {}), '(addr, None, True)\n', (2252, 2270), False, 'import ghidra\n')] |
import unittest
import numpy as np
import sklearn_supp.random_coordinates as random_coordinates
class TestRandomCoordinateForestClassifier(unittest.TestCase):
"""These are just some simple sanity checks to make sure we don't get
exceptions.
"""
def test_simple(self):
X = [[0], [1]]
y = [0, 1]
classifier = random_coordinates.RandomCoordinateForestClassifier(
n_estimators=50)
classifier.fit(X, y)
y_pred = classifier.predict(X)
print(y_pred)
eq = np.all(y_pred == y)
self.assertTrue(eq)
def test_transform_dimension(self):
X = [[0, 0], [1, 1]]
X = np.array(X)
y = [0, 1]
classifier = random_coordinates.RandomCoordinateForestClassifier(
n_estimators=50, transform_dimension=2)
classifier.fit(X, y)
y_pred = classifier.predict(X)
print(y_pred)
eq = np.all(y_pred == y)
self.assertTrue(eq)
| [
"numpy.array",
"numpy.all",
"sklearn_supp.random_coordinates.RandomCoordinateForestClassifier"
] | [((352, 420), 'sklearn_supp.random_coordinates.RandomCoordinateForestClassifier', 'random_coordinates.RandomCoordinateForestClassifier', ([], {'n_estimators': '(50)'}), '(n_estimators=50)\n', (403, 420), True, 'import sklearn_supp.random_coordinates as random_coordinates\n'), ((537, 556), 'numpy.all', 'np.all', (['(y_pred == y)'], {}), '(y_pred == y)\n', (543, 556), True, 'import numpy as np\n'), ((667, 678), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (675, 678), True, 'import numpy as np\n'), ((719, 814), 'sklearn_supp.random_coordinates.RandomCoordinateForestClassifier', 'random_coordinates.RandomCoordinateForestClassifier', ([], {'n_estimators': '(50)', 'transform_dimension': '(2)'}), '(n_estimators=50,\n transform_dimension=2)\n', (770, 814), True, 'import sklearn_supp.random_coordinates as random_coordinates\n'), ((927, 946), 'numpy.all', 'np.all', (['(y_pred == y)'], {}), '(y_pred == y)\n', (933, 946), True, 'import numpy as np\n')] |
# Author : <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.
"""
Sequence Ordering of Alignments
"""
import os
import numpy as np
import pandas as pd
from constants import (
folder,
alignment_file,
recipe_folder_name,
)
from utils import (
fetch_parsed_recipe,
fetch_action_ids,
)
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
class SequenceModel:
def test_sequence_model(self):
dish_list = os.listdir(folder)
dish_list = [dish for dish in dish_list if not dish.startswith(".")]
dish_list.sort()
correct_predictions = 0
num_actions = 0
for dish in dish_list:
data_folder = os.path.join(folder, dish) # dish folder
recipe_folder = os.path.join(data_folder, recipe_folder_name) # recipe folder
alignment_file_path = os.path.join(
data_folder, alignment_file
) # alignment file
# Gold Standard Alignments between all recipes for dish
alignments = pd.read_csv(
alignment_file_path, sep="\t", header=0, skiprows=0, encoding="utf-8"
)
# Group by Recipe pairs
group_alignments = alignments.groupby(["file1", "file2"])
dish_correct_predictions = 0
dish_num_actions = 0
for key in group_alignments.groups.keys():
#print('Recipe Pair: ')
#print(key)
recipe1_filename = os.path.join(recipe_folder, key[0] + ".conllu")
recipe2_filename = os.path.join(recipe_folder, key[1] + ".conllu")
parsed_recipe1 = fetch_parsed_recipe(recipe1_filename)
parsed_recipe2 = fetch_parsed_recipe(recipe2_filename)
action_ids1 = fetch_action_ids(parsed_recipe1)
#print('Actions in Recipe 1: ')
#print(action_ids1)
action_ids2 = fetch_action_ids(parsed_recipe2)
#print('Actions in Recipe 2: ')
#print(action_ids2)
if len(action_ids1) < len(action_ids2):
predictions = action_ids2[:len(action_ids1)]
else:
predictions = action_ids2
predictions.extend([0] * (len(action_ids1) - len(action_ids2)))
predictions = np.array(predictions)
#print('Predictions: ')
#print(predictions)
recipe_pair_alignment = group_alignments.get_group(key)
true_labels = list()
for i in action_ids1:
# True Action Id
action_line = recipe_pair_alignment.loc[
recipe_pair_alignment["token1"] == i
]
if not action_line.empty:
label = action_line["token2"].item()
true_labels.append(label)
else:
true_labels.append(0)
true_labels = np.array(true_labels)
#print('True Labels:')
#print(true_labels)
score = [predictions == true_labels]
dish_correct_predictions += np.sum(score)
dish_num_actions += len(action_ids1)
dish_accuracy = dish_correct_predictions * 100 / dish_num_actions
correct_predictions += dish_correct_predictions
num_actions += dish_num_actions
print("Accuracy of Dish {} : {:.2f}".format(dish, dish_accuracy))
model_accuracy = correct_predictions * 100 / num_actions
print("Model Accuracy: {:.2f}".format(model_accuracy))
| [
"os.listdir",
"utils.fetch_action_ids",
"pandas.read_csv",
"os.path.join",
"numpy.array",
"numpy.sum",
"warnings.simplefilter",
"utils.fetch_parsed_recipe"
] | [((824, 886), 'warnings.simplefilter', 'warnings.simplefilter', ([], {'action': '"""ignore"""', 'category': 'FutureWarning'}), "(action='ignore', category=FutureWarning)\n", (845, 886), False, 'import warnings\n'), ((974, 992), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (984, 992), False, 'import os\n'), ((1241, 1267), 'os.path.join', 'os.path.join', (['folder', 'dish'], {}), '(folder, dish)\n', (1253, 1267), False, 'import os\n'), ((1311, 1356), 'os.path.join', 'os.path.join', (['data_folder', 'recipe_folder_name'], {}), '(data_folder, recipe_folder_name)\n', (1323, 1356), False, 'import os\n'), ((1434, 1475), 'os.path.join', 'os.path.join', (['data_folder', 'alignment_file'], {}), '(data_folder, alignment_file)\n', (1446, 1475), False, 'import os\n'), ((1634, 1721), 'pandas.read_csv', 'pd.read_csv', (['alignment_file_path'], {'sep': '"""\t"""', 'header': '(0)', 'skiprows': '(0)', 'encoding': '"""utf-8"""'}), "(alignment_file_path, sep='\\t', header=0, skiprows=0, encoding=\n 'utf-8')\n", (1645, 1721), True, 'import pandas as pd\n'), ((2166, 2213), 'os.path.join', 'os.path.join', (['recipe_folder', "(key[0] + '.conllu')"], {}), "(recipe_folder, key[0] + '.conllu')\n", (2178, 2213), False, 'import os\n'), ((2249, 2296), 'os.path.join', 'os.path.join', (['recipe_folder', "(key[1] + '.conllu')"], {}), "(recipe_folder, key[1] + '.conllu')\n", (2261, 2296), False, 'import os\n'), ((2347, 2384), 'utils.fetch_parsed_recipe', 'fetch_parsed_recipe', (['recipe1_filename'], {}), '(recipe1_filename)\n', (2366, 2384), False, 'from utils import fetch_parsed_recipe, fetch_action_ids\n'), ((2418, 2455), 'utils.fetch_parsed_recipe', 'fetch_parsed_recipe', (['recipe2_filename'], {}), '(recipe2_filename)\n', (2437, 2455), False, 'from utils import fetch_parsed_recipe, fetch_action_ids\n'), ((2503, 2535), 'utils.fetch_action_ids', 'fetch_action_ids', (['parsed_recipe1'], {}), '(parsed_recipe1)\n', (2519, 2535), False, 'from utils import fetch_parsed_recipe, fetch_action_ids\n'), ((2667, 2699), 'utils.fetch_action_ids', 'fetch_action_ids', (['parsed_recipe2'], {}), '(parsed_recipe2)\n', (2683, 2699), False, 'from utils import fetch_parsed_recipe, fetch_action_ids\n'), ((3189, 3210), 'numpy.array', 'np.array', (['predictions'], {}), '(predictions)\n', (3197, 3210), True, 'import numpy as np\n'), ((4039, 4060), 'numpy.array', 'np.array', (['true_labels'], {}), '(true_labels)\n', (4047, 4060), True, 'import numpy as np\n'), ((4268, 4281), 'numpy.sum', 'np.sum', (['score'], {}), '(score)\n', (4274, 4281), True, 'import numpy as np\n')] |
from flask import Flask, current_app, request
from flask_babelex import get_locale
from flask_sqlalchemy import SQLAlchemy
from flask_transalchemy.model import TranslationMixin
class TransAlchemy(object):
"""Flask-TransAlchemy extension class.
:param app: Flask application instance
:param db: Flask-SQLAlchemy instance
"""
def __init__(self, app: Flask, db: SQLAlchemy, label_route: str = None):
self.app = app
self.db = db
self.model = None
self.route = label_route
if app is not None:
self.init_app(app)
def init_app(self, app: Flask):
"""Initialize extension and create `Translation` model class.
:param app: Flask application instance
"""
app.extensions["babel_alchemy"] = self
class Translation(self.db.Model, TranslationMixin):
pass
self.model = Translation
if self.route:
@self.app.route(
'/{}/<label>'.format(self.route),
endpoint='label_translations'
)
def translate(label):
return self.get_label(label, **request.args)
def set_label(self, label: str, value: str, language: str = None):
"""Save label translation in database.
:param label: Label name ('attribute' field in table)
:param value: Translated label text.
:param language: Language of translation
"""
if language is None:
language = str(get_locale())
translation = self.model(
attribute=label,
language=language,
value=value
)
self.db.session.add(translation)
self.db.session.commit()
def get_label(self, label: str, language: str = None):
"""Get translated label from database.
Labels are stored in the table without table name and record_id.
:param label: Label name ('attribute' field in table)
:param language: Language of translation
:return: Translated label text.
"""
if language is None:
language = str(get_locale())
qry = self.model.query.filter_by(
table=None,
record_id=None,
attribute=label,
language=language
)
translation = qry.first()
if translation is None:
return label
return translation.value
def set_label(label: str, value: str, language: str = None):
"""Shortcut for `BabelAlchemy.set_label()`.
:param label: Label name ('attribute' field in table)
:param value: Translated label text.
:param language: Language of translation
"""
babel_alchemy = current_app.extensions.get("babel_alchemy")
return babel_alchemy.set_label(label, value, language)
def get_label(label: str, language: str = None):
"""Shortcut for `BabelAlchemy.get_label()`.
Labels are stored in the table without table name and record_id.
:param label: Label name ('attribute' field in table)
:param language: Language of translation
:return: Translated label text.
"""
babel_alchemy = current_app.extensions.get("babel_alchemy")
return babel_alchemy.get_label(label, language)
| [
"flask_babelex.get_locale",
"flask.current_app.extensions.get"
] | [((2719, 2762), 'flask.current_app.extensions.get', 'current_app.extensions.get', (['"""babel_alchemy"""'], {}), "('babel_alchemy')\n", (2745, 2762), False, 'from flask import Flask, current_app, request\n'), ((3159, 3202), 'flask.current_app.extensions.get', 'current_app.extensions.get', (['"""babel_alchemy"""'], {}), "('babel_alchemy')\n", (3185, 3202), False, 'from flask import Flask, current_app, request\n'), ((1512, 1524), 'flask_babelex.get_locale', 'get_locale', ([], {}), '()\n', (1522, 1524), False, 'from flask_babelex import get_locale\n'), ((2131, 2143), 'flask_babelex.get_locale', 'get_locale', ([], {}), '()\n', (2141, 2143), False, 'from flask_babelex import get_locale\n')] |
# Copyright 2016, The NIG Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
from __future__ import absolute_import, division, print_function
import re
import six
from contextlib import contextmanager
from timeit import default_timer
__author__ = ['eaplatanios', 'alshedivat']
__all__ = ['dummy', 'elapsed_timer', 'unique_list', 'escape_glob',
'get_from_module']
@contextmanager
def dummy():
yield None
@contextmanager
def elapsed_timer():
start = default_timer()
elapsed = lambda: default_timer() - start
yield lambda: elapsed()
end = default_timer()
elapsed = lambda: end - start
def unique_list(l):
seen = set()
return [x for x in l if x not in seen and not seen.add(x)]
def escape_glob(path):
characters = ['[', ']', '?', '!']
replacements = {re.escape(char): '[' + char + ']' for char in characters}
pattern = re.compile('|'.join(replacements.keys()))
return pattern.sub(lambda m: replacements[re.escape(m.group(0))], path)
def get_from_module(identifier, module_params, module_name,
instantiate=False, kwargs=None):
"""The function is stolen from keras.utils.generic_utils.
"""
if isinstance(identifier, six.string_types):
res = module_params.get(identifier)
if not res:
raise Exception('Invalid ' + str(module_name) + ': ' +
str(identifier))
if instantiate and not kwargs:
return res()
elif instantiate and kwargs:
return res(**kwargs)
else:
return res
elif type(identifier) is dict:
name = identifier.pop('name')
res = module_params.get(name)
if res:
return res(**identifier)
else:
raise Exception('Invalid ' + str(module_name) + ': ' +
str(identifier))
return identifier
| [
"timeit.default_timer",
"re.escape"
] | [((1001, 1016), 'timeit.default_timer', 'default_timer', ([], {}), '()\n', (1014, 1016), False, 'from timeit import default_timer\n'), ((1101, 1116), 'timeit.default_timer', 'default_timer', ([], {}), '()\n', (1114, 1116), False, 'from timeit import default_timer\n'), ((1336, 1351), 're.escape', 're.escape', (['char'], {}), '(char)\n', (1345, 1351), False, 'import re\n'), ((1039, 1054), 'timeit.default_timer', 'default_timer', ([], {}), '()\n', (1052, 1054), False, 'from timeit import default_timer\n')] |
from __future__ import print_function, absolute_import
from random import random
from time import sleep
import threading
import pygame
import sys
try:
from olympe.messages.ardrone3.GPSSettingsState import GPSFixStateChanged
from olympe.messages.ardrone3.Piloting import TakeOff, Landing
from olympe.messages.ardrone3.PilotingState import FlyingStateChanged
import olympe
except ImportError:
print("Olympe has not been loaded yet! Cannot run the app", file=sys.__stderr__)
sys.exit(0)
class JoystickTeleop:
PHYSICAL_IP = "192.168.42.1"
SIMULATED_IP = "10.202.0.1"
LAND_TAKEOFF_TIME = 4.0
def __init__(self, drone=None, speed=65, refresh_move=0.1):
""""""
try:
self._quit_pressed = None
self.drone_speed = min([speed, 100])
self.drone_mtime = min([refresh_move, 1]) # move time
pygame.init()
self.joy = pygame.joystick.Joystick(0)
self.drone = drone
self.drone.connection()
self.drone.start_piloting()
except pygame.error as e:
print(e)
print("\n(There is no joystick connected to the system)")
sys.exit(0)
def start(self):
self.joy.init()
print("Initialized Joystick: {}".format(self.joy.get_name()))
self._mainloop()
def stop(self):
self._quit_pressed = True
def _close_conn(self):
self.drone.stop_piloting()
self.drone.disconnection()
def _get_joy_values(self):
pygame.event.pump()
#Read input from the two joysticks and take only the ones we need
out_joys = [self.joy.get_axis(i) for i in [0,1,3,4]]
return out_joys
def _is_takeoff_pressed(self):
return self.joy.get_button(3) == 1
def _is_landed_pressed(self):
return self.joy.get_button(0) == 1
def _check_quit_pressed(self):
self._quit_pressed = self.joy.get_button(8) == 1
def _mainloop(self):
""""""
while not self._quit_pressed:
sleep(0.2)
joy_values = self._get_joy_values()
if self._is_takeoff_pressed():
print("Pressed takeoff button!")
self._takeoff()
elif self._is_landed_pressed():
print("Pressed landing button!")
self._land()
else:
# print(joy_values)
self.move(joy_values)
self._check_quit_pressed()
print("\n============")
print("Pressed QUIT button (X)")
print("============\n")
self._land()
self._close_conn() # closes the connection
def _takeoff(self):
""""""
print("Takeoff if necessary...")
self.drone(
FlyingStateChanged(state="hovering", _policy="check")
| FlyingStateChanged(state="flying", _policy="check")
| (
GPSFixStateChanged(fixed=1, _timeout=5, _policy="check_wait")
>> (
TakeOff(_no_expect=True)
& FlyingStateChanged(
state="hovering", _timeout=5, _policy="check_wait")
)
)
).wait()
def _land(self):
"""Lands the drone"""
print("Landing...")
self.drone(
Landing()
>> FlyingStateChanged(state="landed", _timeout=5)
).wait()
def move(self, joy_values):
"""
Move in the desired direction given the (normalized) Joystick values:
[LeftThumbXAxis, LeftThumbYAxis, RightThumbXAxis, RightThumbYAxis, Select/Quit]
"""
# movements must be in [-100:100]
left_right, front_back, turning, up_down = [
int(j * self.drone_speed) for j in joy_values
]
self.drone.piloting_pcmd(
left_right, -front_back, turning, -up_down,
self.drone_mtime
)
if __name__ == "__main__":
drone = olympe.Drone(JoystickTeleop.SIMULATED_IP, loglevel=0)
try:
x = JoystickTeleop(drone)
x.start()
except KeyboardInterrupt:
x.stop()
print("Teleoperating stopped\n")
sys.exit(0) | [
"olympe.Drone",
"pygame.init",
"olympe.messages.ardrone3.Piloting.Landing",
"olympe.messages.ardrone3.PilotingState.FlyingStateChanged",
"pygame.joystick.Joystick",
"time.sleep",
"olympe.messages.ardrone3.Piloting.TakeOff",
"sys.exit",
"pygame.event.pump",
"olympe.messages.ardrone3.GPSSettingsStat... | [((4034, 4087), 'olympe.Drone', 'olympe.Drone', (['JoystickTeleop.SIMULATED_IP'], {'loglevel': '(0)'}), '(JoystickTeleop.SIMULATED_IP, loglevel=0)\n', (4046, 4087), False, 'import olympe\n'), ((4239, 4250), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (4247, 4250), False, 'import sys\n'), ((499, 510), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (507, 510), False, 'import sys\n'), ((1553, 1572), 'pygame.event.pump', 'pygame.event.pump', ([], {}), '()\n', (1570, 1572), False, 'import pygame\n'), ((887, 900), 'pygame.init', 'pygame.init', ([], {}), '()\n', (898, 900), False, 'import pygame\n'), ((924, 951), 'pygame.joystick.Joystick', 'pygame.joystick.Joystick', (['(0)'], {}), '(0)\n', (948, 951), False, 'import pygame\n'), ((2075, 2085), 'time.sleep', 'sleep', (['(0.2)'], {}), '(0.2)\n', (2080, 2085), False, 'from time import sleep\n'), ((1199, 1210), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (1207, 1210), False, 'import sys\n'), ((3388, 3397), 'olympe.messages.ardrone3.Piloting.Landing', 'Landing', ([], {}), '()\n', (3395, 3397), False, 'from olympe.messages.ardrone3.Piloting import TakeOff, Landing\n'), ((3413, 3459), 'olympe.messages.ardrone3.PilotingState.FlyingStateChanged', 'FlyingStateChanged', ([], {'state': '"""landed"""', '_timeout': '(5)'}), "(state='landed', _timeout=5)\n", (3431, 3459), False, 'from olympe.messages.ardrone3.PilotingState import FlyingStateChanged\n'), ((2829, 2882), 'olympe.messages.ardrone3.PilotingState.FlyingStateChanged', 'FlyingStateChanged', ([], {'state': '"""hovering"""', '_policy': '"""check"""'}), "(state='hovering', _policy='check')\n", (2847, 2882), False, 'from olympe.messages.ardrone3.PilotingState import FlyingStateChanged\n'), ((2897, 2948), 'olympe.messages.ardrone3.PilotingState.FlyingStateChanged', 'FlyingStateChanged', ([], {'state': '"""flying"""', '_policy': '"""check"""'}), "(state='flying', _policy='check')\n", (2915, 2948), False, 'from olympe.messages.ardrone3.PilotingState import FlyingStateChanged\n'), ((2981, 3042), 'olympe.messages.ardrone3.GPSSettingsState.GPSFixStateChanged', 'GPSFixStateChanged', ([], {'fixed': '(1)', '_timeout': '(5)', '_policy': '"""check_wait"""'}), "(fixed=1, _timeout=5, _policy='check_wait')\n", (2999, 3042), False, 'from olympe.messages.ardrone3.GPSSettingsState import GPSFixStateChanged\n'), ((3084, 3108), 'olympe.messages.ardrone3.Piloting.TakeOff', 'TakeOff', ([], {'_no_expect': '(True)'}), '(_no_expect=True)\n', (3091, 3108), False, 'from olympe.messages.ardrone3.Piloting import TakeOff, Landing\n'), ((3131, 3201), 'olympe.messages.ardrone3.PilotingState.FlyingStateChanged', 'FlyingStateChanged', ([], {'state': '"""hovering"""', '_timeout': '(5)', '_policy': '"""check_wait"""'}), "(state='hovering', _timeout=5, _policy='check_wait')\n", (3149, 3201), False, 'from olympe.messages.ardrone3.PilotingState import FlyingStateChanged\n')] |
import argparse
import csv
import glob
import json
import os
import re
import time
from math import ceil
from shutil import copyfile, rmtree
from urllib.parse import urlparse
import requests
from pyproc import Lpse, __version__
from pyproc.helpers import DetilDownloader
from urllib3 import disable_warnings
from urllib3.exceptions import InsecureRequestWarning
from datetime import datetime
EXIT_CODE = 0
def print_info():
print(r''' ____ ____
/ __ \__ __/ __ \_________ _____
/ /_/ / / / / /_/ / ___/ __ \/ ___/
/ ____/ /_/ / ____/ / / /_/ / /__
/_/ \__, /_/ /_/ \____/\___/
/____/
SPSE4 Downloader, PyProc v{}
'''.format(__version__))
def download_index(_lpse, pool_size, fetch_size, timeout, non_tender, index_path, index_path_exists, force, delay):
_lpse.timeout = timeout
lpse_pool = [_lpse]*pool_size
for i in lpse_pool:
i.session = requests.session()
i.session.verify = False
i.auth_token = i.get_auth_token()
print("url SPSE :", lpse_pool[0].host)
print("versi SPSE :", lpse_pool[0].version)
print("last update :", lpse_pool[0].last_update)
print("\nIndexing Data")
if index_path_exists and not force:
yield "- Menggunakan cache"
else:
if non_tender:
total_data = lpse_pool[0].get_paket_non_tender()['recordsTotal']
else:
total_data = lpse_pool[0].get_paket_tender()['recordsTotal']
batch_size = int(ceil(total_data / fetch_size))
downloaded_row = 0
with open(index_path, 'w', newline='', encoding='utf8',
errors="ignore") as index_file:
writer = csv.writer(index_file, delimiter='|', quoting=csv.QUOTE_ALL)
for page in range(batch_size):
lpse = lpse_pool[page % pool_size]
if non_tender:
data = lpse.get_paket_non_tender(start=page*fetch_size, length=fetch_size, data_only=True)
min_data = list(map(lambda x: [x[0], x[6]], data))
else:
data = lpse.get_paket_tender(start=page*fetch_size, length=fetch_size, data_only=True)
min_data = list(map(lambda x: [x[0], x[8]], data))
writer.writerows(min_data)
downloaded_row += len(min_data)
time.sleep(delay)
yield [page+1, batch_size, downloaded_row]
del lpse_pool
def get_detil(downloader, jenis_paket, tahun_anggaran, index_path):
detail_dir = os.path.join(get_folder_name(downloader.lpse.host, jenis_paket), 'detil')
os.makedirs(detail_dir, exist_ok=True)
downloader.download_dir = detail_dir
downloader.error_log = detail_dir+".err"
downloader.is_tender = True if jenis_paket == 'tender' else False
with open(index_path, 'r', encoding='utf8', errors="ignore") as f:
reader = csv.reader(f, delimiter='|')
for row in reader:
tahun_anggaran_data = re.findall(r'(20\d{2})', row[1])
if not download_by_ta(tahun_anggaran_data, tahun_anggaran):
continue
downloader.queue.put(row[0])
downloader.queue.join()
def combine_data(host, jenis_paket, remove=True, filename=None):
folder_name = get_folder_name(host, jenis_paket=jenis_paket)
detil_dir = os.path.join(folder_name, 'detil', '*')
detil_combined = os.path.join(folder_name, 'detil.dat')
detil_all = glob.glob(detil_dir)
pengumuman_nontender_keys = {
'id_paket': None,
'kode_paket': None,
'nama_paket': None,
'tanggal_pembuatan': None,
'keterangan': None,
'tahap_paket_saat_ini': None,
'instansi': None,
'satuan_kerja': None,
'kategori': None,
'metode_pengadaan': None,
'tahun_anggaran': None,
'nilai_pagu_paket': None,
'nilai_hps_paket': None,
'lokasi_pekerjaan': None,
'npwp': None,
'nama_peserta': None,
'penawaran': None,
'penawaran_terkoreksi': None,
'hasil_negosiasi': None,
'p': False,
'pk': False
}
pengumuman_keys = {
'id_paket': None,
'kode_tender': None,
'nama_tender': None,
'tanggal_pembuatan': None,
'keterangan': None,
'tahap_tender_saat_ini': None,
'instansi': None,
'satuan_kerja': None,
'kategori': None,
'sistem_pengadaan': None,
'tahun_anggaran': None,
'nilai_pagu_paket': None,
'nilai_hps_paket': None,
'lokasi_pekerjaan': None,
'npwp': None,
'nama_peserta': None,
'penawaran': None,
'penawaran_terkoreksi': None,
'hasil_negosiasi': None,
'p': False,
'pk': False
}
with open(detil_combined, 'w', encoding='utf8', errors="ignore", newline='') as csvf:
fieldnames = list(pengumuman_keys.keys() if jenis_paket == 'tender' else pengumuman_nontender_keys.keys())
fieldnames += ['penetapan_pemenang_mulai', 'penetapan_pemenang_sampai', 'penandatanganan_kontrak_mulai',
'penandatanganan_kontrak_sampai']
writer = csv.DictWriter(
csvf,
fieldnames=fieldnames
)
writer.writeheader()
for detil_file in detil_all:
detil = pengumuman_keys.copy() if jenis_paket == 'tender' else pengumuman_nontender_keys.copy()
detil.update(
{
'penetapan_pemenang_mulai': None,
'penetapan_pemenang_sampai': None,
}
)
with open(detil_file, 'r', encoding='utf8', errors="ignore") as f:
data = json.loads(f.read())
detil['id_paket'] = data['id_paket']
if data['pengumuman']:
detil.update((k, data['pengumuman'][k]) for k in detil.keys() & data['pengumuman'].keys())
detil['lokasi_pekerjaan'] = ' || '.join(detil['lokasi_pekerjaan'])
if jenis_paket == 'tender':
tahap = 'tahap_tender_saat_ini'
else:
tahap = 'tahap_paket_saat_ini'
if detil[tahap]:
detil[tahap] = detil[tahap].strip(r' [...]')
if data['jadwal']:
data_pemenang = list(filter(lambda x: x['tahap'] == 'Penetapan Pemenang', data['jadwal']))
data_kontrak = list(filter(lambda x: x['tahap'] == 'Penandatanganan Kontrak', data['jadwal']))
if data_pemenang:
detil['penetapan_pemenang_mulai'] = data_pemenang[0]['mulai']
detil['penetapan_pemenang_sampai'] = data_pemenang[0]['sampai']
if data_kontrak:
detil['penandatanganan_kontrak_mulai'] = data_kontrak[0]['mulai']
detil['penandatanganan_kontrak_sampai'] = data_kontrak[0]['sampai']
if data['hasil']:
pemenang = None
try:
pemenang = list(filter(lambda x: x['p'], data['hasil']))
except KeyError:
if jenis_paket == 'non_tender':
pemenang = data['hasil'][0:]
except Exception as e:
error_writer(
"{}|{} - {} - {}".format(host, detil['id_paket'], jenis_paket, str(e)),
update_exit_code=False
)
finally:
if pemenang is not None:
detil.update((k, pemenang[0][k]) for k in detil.keys() & pemenang[0].keys())
writer.writerow(detil)
del detil
copy_result(folder_name, remove=remove, filename=filename)
def error_writer(error, update_exit_code=True):
global EXIT_CODE
if update_exit_code:
EXIT_CODE = 1
with open('error.log', 'a', encoding='utf8', errors="ignore") as error_file:
error_file.write(error+'\n')
def get_folder_name(host, jenis_paket):
_url = urlparse(host)
netloc = _url.netloc if _url.netloc != '' else _url.path
return netloc.lower().replace('.', '_') + '_' + jenis_paket
def get_index_path(cache_folder, host, jenis_paket, last_paket_id):
index_dir = os.path.join(cache_folder, get_folder_name(host, jenis_paket))
os.makedirs(index_dir, exist_ok=True)
index_path = os.path.join(index_dir, 'index-{}-{}-{}'.format(*last_paket_id))
return os.path.isfile(index_path), index_path
def parse_tahun_anggaran(tahun_anggaran):
parsed_ta = tahun_anggaran.strip().split('-')
error = False
for i in range(len(parsed_ta)):
try:
parsed_ta[i] = int(parsed_ta[i])
except ValueError:
parsed_ta[i] = 0
if len(parsed_ta) > 2:
error = True
elif parsed_ta[-1] == 0:
parsed_ta[-1] = 9999
return error, parsed_ta
def download_by_ta(ta_data, ta_argumen):
if not ta_data:
return True
ta_data = [int(i) for i in ta_data]
for i in ta_data:
if ta_argumen[0] <= i <= ta_argumen[-1]:
return True
return False
def copy_result(folder_name, remove=True, filename=None):
if filename is None:
filename = folder_name
else:
filename = ''.join(filename.split('.')[:-1])
copyfile(os.path.join(folder_name, 'detil.dat'), filename + '.csv')
if os.path.isfile(os.path.join(folder_name, 'detil.err')):
copyfile(os.path.join(folder_name, 'detil.err'), filename + '_error.log')
if remove:
rmtree(folder_name)
def get_last_paket_id(lpse: Lpse, tender=True):
# first
if tender:
data_first = lpse.get_paket_tender(start=0, length=1)
data_last = lpse.get_paket_tender(start=0, length=1, ascending=True)
else:
data_first = lpse.get_paket_non_tender(start=0, length=1)
data_last = lpse.get_paket_non_tender(start=0, length=1, ascending=True)
if data_first and data_last:
if not data_first['recordsTotal'] == 0:
return [data_first['data'][0][0], data_last['data'][0][0], data_first['recordsTotal']]
return None
def create_cache_folder():
from pathlib import Path
home = str(Path.home())
cache_folder = os.path.join(home, '.pyproc')
os.makedirs(cache_folder, exist_ok=True)
return cache_folder
def lock_index(index_path):
return index_path+".lock"
def unlock_index(index_path):
unlocked_path = index_path.split(".lock")[0]
os.rename(index_path, unlocked_path)
return unlocked_path
def main():
print_info()
cache_folder = create_cache_folder()
disable_warnings(InsecureRequestWarning)
parser = argparse.ArgumentParser()
parser.add_argument("--host", help="Alamat Website LPSE", default=None, type=str)
parser.add_argument("--out", help="Nama file hasil download LPSE", default=None, type=str)
parser.add_argument("-r", "--read", help="Membaca host dari file", default=None, type=str)
parser.add_argument("--tahun-anggaran", help="Tahun Anggaran untuk di download", default=str(datetime.now().year),
type=str)
parser.add_argument("--workers", help="Jumlah worker untuk download detil paket", default=8, type=int)
parser.add_argument("--pool-size", help="Jumlah koneksi pada pool untuk download index paket", default=4, type=int)
parser.add_argument("--fetch-size", help="Jumlah row yang didownload per halaman", default=100, type=int)
parser.add_argument("--timeout", help="Set timeout", default=30, type=int)
parser.add_argument("--keep", help="Tidak menghapus folder cache", action="store_true")
parser.add_argument("--index-download-delay", help="Menambahkan delay untuk setiap iterasi halaman index",
default=1, type=int)
parser.add_argument("--non-tender", help="Download paket non tender (penunjukkan langsung)", action="store_true")
parser.add_argument("--force", "-f", help="Clear index sebelum mendownload data", action="store_true")
args = parser.parse_args()
error, tahun_anggaran = parse_tahun_anggaran(args.tahun_anggaran)
jenis_paket = 'non_tender' if args.non_tender else 'tender'
if error:
print("ERROR: format tahun anggaran tidak dikenal ", args.tahun_anggaran)
exit(1)
if args.host:
host_list = args.host.strip().split(',')
elif args.read:
with open(args.read, 'r', encoding='utf8', errors="ignore") as host_file:
host_list = host_file.read().strip().split()
else:
parser.print_help()
print("\nERROR: Argumen --host atau --read tidak ditemukan!")
exit(1)
# download index
detil_downloader = DetilDownloader(workers=args.workers, timeout=args.timeout)
detil_downloader.spawn_worker()
try:
for host in host_list:
_ = host.split(';')
host = _[0].strip()
custom_file_name = None
if args.host and args.out:
custom_file_name = args.out.strip()
elif len(_) > 1:
custom_file_name = _[1].strip()
try:
print("=" * len(host))
print(host)
print("=" * len(host))
print("tahun anggaran :", ' - '.join(map(str, tahun_anggaran)))
_lpse = Lpse(host=host, timeout=args.timeout)
last_paket_id = get_last_paket_id(_lpse, not args.non_tender)
if last_paket_id is None:
print("- Data kosong")
continue
index_path_exists, index_path = get_index_path(cache_folder, _lpse.host, jenis_paket, last_paket_id)
if args.force:
rmtree(os.path.dirname(index_path))
os.mkdir(os.path.dirname(index_path))
index_path_exists = False
if not index_path_exists:
index_path = lock_index(index_path)
for downloadinfo in download_index(_lpse, args.pool_size, args.fetch_size, args.timeout,
args.non_tender, index_path, index_path_exists, args.force,
args.index_download_delay):
if index_path_exists and not args.force:
print(downloadinfo, end='\r')
continue
print("- halaman {} of {} ({} row)".format(*downloadinfo), end='\r')
print("\n- download selesai\n")
index_path = unlock_index(index_path)
except Exception as e:
print("ERROR:", str(e))
error_writer('{}|{}'.format(host, str(e)))
continue
print("Downloading")
detil_downloader.reset()
detil_downloader.set_host(lpse=_lpse)
get_detil(downloader=detil_downloader, jenis_paket=jenis_paket, tahun_anggaran=tahun_anggaran,
index_path=index_path)
print("\n- download selesai\n")
print("Menggabungkan Data")
try:
combine_data(_lpse.host, jenis_paket, not args.keep, filename=custom_file_name)
except Exception as e:
print("ERROR:", str(e))
error_writer('{}|menggabungkan {}'.format(host, str(e)))
print("- proses selesai")
except KeyboardInterrupt:
error = "\n\nProses dibatalkan oleh user, bye!"
print(error)
error_writer("{}|{}".format(detil_downloader.lpse.host, error))
detil_downloader.stop_process()
except Exception as e:
print("\n\nERROR:", e)
error_writer("{}|{}".format(detil_downloader.lpse.host, str(e)))
detil_downloader.stop_process()
finally:
for i in range(detil_downloader.workers):
detil_downloader.queue.put(None)
for t in detil_downloader.threads_pool:
t.join()
if __name__ == '__main__':
main()
exit(EXIT_CODE)
| [
"csv.DictWriter",
"pyproc.helpers.DetilDownloader",
"pathlib.Path.home",
"time.sleep",
"argparse.ArgumentParser",
"pyproc.Lpse",
"csv.reader",
"glob.glob",
"os.rename",
"csv.writer",
"os.path.isfile",
"urllib3.disable_warnings",
"os.path.dirname",
"re.findall",
"requests.session",
"mat... | [((2671, 2709), 'os.makedirs', 'os.makedirs', (['detail_dir'], {'exist_ok': '(True)'}), '(detail_dir, exist_ok=True)\n', (2682, 2709), False, 'import os\n'), ((3397, 3436), 'os.path.join', 'os.path.join', (['folder_name', '"""detil"""', '"""*"""'], {}), "(folder_name, 'detil', '*')\n", (3409, 3436), False, 'import os\n'), ((3458, 3496), 'os.path.join', 'os.path.join', (['folder_name', '"""detil.dat"""'], {}), "(folder_name, 'detil.dat')\n", (3470, 3496), False, 'import os\n'), ((3513, 3533), 'glob.glob', 'glob.glob', (['detil_dir'], {}), '(detil_dir)\n', (3522, 3533), False, 'import glob\n'), ((8137, 8151), 'urllib.parse.urlparse', 'urlparse', (['host'], {}), '(host)\n', (8145, 8151), False, 'from urllib.parse import urlparse\n'), ((8432, 8469), 'os.makedirs', 'os.makedirs', (['index_dir'], {'exist_ok': '(True)'}), '(index_dir, exist_ok=True)\n', (8443, 8469), False, 'import os\n'), ((10362, 10391), 'os.path.join', 'os.path.join', (['home', '""".pyproc"""'], {}), "(home, '.pyproc')\n", (10374, 10391), False, 'import os\n'), ((10397, 10437), 'os.makedirs', 'os.makedirs', (['cache_folder'], {'exist_ok': '(True)'}), '(cache_folder, exist_ok=True)\n', (10408, 10437), False, 'import os\n'), ((10608, 10644), 'os.rename', 'os.rename', (['index_path', 'unlocked_path'], {}), '(index_path, unlocked_path)\n', (10617, 10644), False, 'import os\n'), ((10747, 10787), 'urllib3.disable_warnings', 'disable_warnings', (['InsecureRequestWarning'], {}), '(InsecureRequestWarning)\n', (10763, 10787), False, 'from urllib3 import disable_warnings\n'), ((10802, 10827), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (10825, 10827), False, 'import argparse\n'), ((12822, 12881), 'pyproc.helpers.DetilDownloader', 'DetilDownloader', ([], {'workers': 'args.workers', 'timeout': 'args.timeout'}), '(workers=args.workers, timeout=args.timeout)\n', (12837, 12881), False, 'from pyproc.helpers import DetilDownloader\n'), ((951, 969), 'requests.session', 'requests.session', ([], {}), '()\n', (967, 969), False, 'import requests\n'), ((2956, 2984), 'csv.reader', 'csv.reader', (['f'], {'delimiter': '"""|"""'}), "(f, delimiter='|')\n", (2966, 2984), False, 'import csv\n'), ((5247, 5290), 'csv.DictWriter', 'csv.DictWriter', (['csvf'], {'fieldnames': 'fieldnames'}), '(csvf, fieldnames=fieldnames)\n', (5261, 5290), False, 'import csv\n'), ((8565, 8591), 'os.path.isfile', 'os.path.isfile', (['index_path'], {}), '(index_path)\n', (8579, 8591), False, 'import os\n'), ((9436, 9474), 'os.path.join', 'os.path.join', (['folder_name', '"""detil.dat"""'], {}), "(folder_name, 'detil.dat')\n", (9448, 9474), False, 'import os\n'), ((9518, 9556), 'os.path.join', 'os.path.join', (['folder_name', '"""detil.err"""'], {}), "(folder_name, 'detil.err')\n", (9530, 9556), False, 'import os\n'), ((9665, 9684), 'shutil.rmtree', 'rmtree', (['folder_name'], {}), '(folder_name)\n', (9671, 9684), False, 'from shutil import copyfile, rmtree\n'), ((10330, 10341), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (10339, 10341), False, 'from pathlib import Path\n'), ((1532, 1561), 'math.ceil', 'ceil', (['(total_data / fetch_size)'], {}), '(total_data / fetch_size)\n', (1536, 1561), False, 'from math import ceil\n'), ((1727, 1787), 'csv.writer', 'csv.writer', (['index_file'], {'delimiter': '"""|"""', 'quoting': 'csv.QUOTE_ALL'}), "(index_file, delimiter='|', quoting=csv.QUOTE_ALL)\n", (1737, 1787), False, 'import csv\n'), ((3047, 3079), 're.findall', 're.findall', (['"""(20\\\\d{2})"""', 'row[1]'], {}), "('(20\\\\d{2})', row[1])\n", (3057, 3079), False, 'import re\n'), ((9576, 9614), 'os.path.join', 'os.path.join', (['folder_name', '"""detil.err"""'], {}), "(folder_name, 'detil.err')\n", (9588, 9614), False, 'import os\n'), ((2408, 2425), 'time.sleep', 'time.sleep', (['delay'], {}), '(delay)\n', (2418, 2425), False, 'import time\n'), ((13456, 13493), 'pyproc.Lpse', 'Lpse', ([], {'host': 'host', 'timeout': 'args.timeout'}), '(host=host, timeout=args.timeout)\n', (13460, 13493), False, 'from pyproc import Lpse, __version__\n'), ((11201, 11215), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (11213, 11215), False, 'from datetime import datetime\n'), ((13864, 13891), 'os.path.dirname', 'os.path.dirname', (['index_path'], {}), '(index_path)\n', (13879, 13891), False, 'import os\n'), ((13922, 13949), 'os.path.dirname', 'os.path.dirname', (['index_path'], {}), '(index_path)\n', (13937, 13949), False, 'import os\n')] |
import tkinter as tk
from tkinter import ttk, messagebox, font, StringVar
from tkcalendar import DateEntry
from tkcrud.controller.client_controller import ClientController,\
saving_updating, get_clients, window_popup
class FormClientRegister(tk.Toplevel, ClientController):
def __init__(self, master, tree):
tk.Toplevel.__init__(self, master)
self.get_id = None
self.title('Clients Register')
frame = tk.LabelFrame(self, text='Register client')
frame.grid(row=0, column=0, columnspan=33, pady=30)
label_name = tk.Label(frame, text=self.table_fields[1])
label_name.grid(row=1, column=0)
name = tk.Entry(frame)
name.focus()
name.grid(row=1, column=1)
label_address = tk.Label(frame, text=self.table_fields[2])
label_address.grid(row=2, column=0)
address = tk.Entry(frame)
address.grid(row=2, column=1)
label_date_of_birth = tk.Label(frame, text=self.table_fields[3])
label_date_of_birth.grid(row=3, column=0)
date_of_birth = DateEntry(frame, date_pattern='y-mm-dd')
date_of_birth.grid(row=3, column=1)
label_sex = tk.Label(frame, text=self.table_fields[4])
label_sex.grid(row=4, column=0)
sex = ttk.Combobox(frame, values=["Male", "Female"], state="readonly")
sex.grid(row=4, column=1)
label_marital_status = tk.Label(frame, text=self.table_fields[5])
label_marital_status.grid(row=5, column=0)
marital_status = tk.Entry(frame)
marital_status.grid(row=5, column=1)
label_rg = tk.Label(frame, text=self.table_fields[6])
label_rg.grid(row=6, column=0)
rg = tk.Entry(frame)
rg.grid(row=6, column=1)
label_cpf = tk.Label(frame, text=self.table_fields[7])
label_cpf.grid(row=8, column=0)
cpf = tk.Entry(frame)
cpf.grid(row=8, column=1)
label_cell_phone = tk.Label(frame, text=self.table_fields[8])
label_cell_phone.grid(row=9, column=0)
cell_phone = tk.Entry(frame)
cell_phone.grid(row=9, column=1)
label_email = tk.Label(frame, text=self.table_fields[9])
label_email.grid(row=10, column=0)
email = tk.Entry(frame)
email.grid(row=10, column=1)
btn_register_save = tk.Button(frame,
text='Save', cursor="hand2",
command=lambda: saving_updating(
tree, tk.END, 'insert', messagebox,
self.get_id, name.get(), address.get(),
date_of_birth.get(), sex.get(),
marital_status.get(), rg.get(),
cpf.get(), cell_phone.get(),
email.get()))
btn_register_save.grid(row=12, columnspan=2, sticky='we')
message = tk.Label(frame, text='', fg='red')
message.grid(row=13, column=0, columnspan=2, sticky='we')
self.resizable(0, 0)
self.transient(master)
self.grab_set()
master.wait_window(self)
class FormClientUpdate(tk.Toplevel, ClientController):
def __init__(self, master, tree):
try:
self.id = tree.item(tree.selection())['values'][0]
tk.Toplevel.__init__(self, master)
self.title('Update client')
frame = tk.LabelFrame(self, text='Update client')
frame.grid(row=0, column=0, columnspan=33, pady=30)
self.label_name = tk.Label(frame, text=self.table_fields[1])
self.label_name.grid(row=1, column=0)
old_name = tree.item(tree.selection())['values'][1]
name = tk.Entry(frame, textvariable=StringVar(self, value=old_name))
name.focus()
name.grid(row=1, column=1)
label_address = tk.Label(frame, text=self.table_fields[2])
label_address.grid(row=2, column=0)
old_address = tree.item(tree.selection())['values'][2]
address = tk.Entry(frame, textvariable=StringVar(self, value=old_address))
address.grid(row=2, column=1)
label_date_of_birth = tk.Label(frame, text=self.table_fields[3])
label_date_of_birth.grid(row=3, column=0)
old_date_of_birth = tree.item(tree.selection())['values'][3]
date_of_birth = DateEntry(frame, date_pattern='y-mm-dd',
value=old_date_of_birth)
date_of_birth.grid(row=3, column=1)
label_sex = tk.Label(frame, text=self.table_fields[4])
label_sex.grid(row=4, column=0)
old_sex = tree.item(tree.selection())['values'][4]
sex_value = StringVar()
sex = ttk.Combobox(frame, textvariable=sex_value, state="readonly")
sex['values'] = ('Male', 'Female')
if old_sex == sex['values'][0]:
sex.current(0)
else:
sex.current(1)
sex.grid(row=4, column=1)
label_marital_status = tk.Label(frame, text=self.table_fields[5])
label_marital_status.grid(row=5, column=0)
old_marital_status = tree.item(tree.selection())['values'][5]
marital_status = tk.Entry(frame,
textvariable=StringVar(self,
value=old_marital_status))
marital_status.grid(row=5, column=1)
label_rg = tk.Label(frame, text=self.table_fields[6])
label_rg.grid(row=6, column=0)
old_rg = tree.item(tree.selection())['values'][6]
rg = tk.Entry(frame, textvariable=StringVar(self, value=old_rg))
rg.grid(row=6, column=1)
label_cpf = tk.Label(frame, text=self.table_fields[7])
label_cpf.grid(row=8, column=0)
old_cpf = tree.item(tree.selection())['values'][7]
cpf = tk.Entry(frame, textvariable=StringVar(self, value=old_cpf))
cpf.grid(row=8, column=1)
label_cell_phone = tk.Label(frame, text=self.table_fields[8])
label_cell_phone.grid(row=9, column=0)
old_cell_phone = tree.item(tree.selection())['values'][8]
cell_phone = tk.Entry(frame,
textvariable=StringVar(self,
value=old_cell_phone))
cell_phone.grid(row=9, column=1)
label_email = tk.Label(frame, text=self.table_fields[9])
label_email.grid(row=10, column=0)
old_email = tree.item(tree.selection())['values'][9]
email = tk.Entry(frame, textvariable=StringVar(self, value=old_email))
email.grid(row=10, column=1)
btn_save = tk.Button(frame, text='Save', cursor='hand2',
command=lambda event=None: saving_updating(
tree, tk.END, 'update', messagebox,
self.id, name.get(), address.get(),
date_of_birth.get(), sex.get(),
marital_status.get(), rg.get(), cpf.get(),
cell_phone.get(), email.get()))
btn_save.grid(row=12, columnspan=2, sticky='we')
message = tk.Label(frame, text='', fg='red')
message.grid(row=13, column=0, columnspan=2, sticky='we')
self.resizable(0, 0)
self.transient(master)
self.grab_set()
master.wait_window(self)
except IndexError:
window_popup(messagebox, 'Please, select record')
return
class FormClient(tk.Toplevel, ClientController):
def __init__(self, master):
tk.Toplevel.__init__(self, master)
tree = ttk.Treeview(self, columns=('#0', '#1', '#2', '#3',
'#4', '#5', '#6', '#7',
'#8', '#9'), show='headings')
font_default = ('Sans Serif', 10, 'bold')
self.geometry("980x580")
self.title('Clients List')
self.grid_rowconfigure(1, weight=1)
self.grid_columnconfigure(1, weight=1)
combo_list_font = font.Font(family='', size=12)
self.option_add("*TCombobox*Listbox*Font", combo_list_font)
label_search = tk.Label(self, text="Search by:", font=font_default)
label_search.grid(row=0, column=0)
type_search = ttk.Combobox(self, values=["ID", "Name"], state="readonly",
font=('', 12, "bold"))
type_search.grid(row=0, column=1)
search_entry = tk.Entry(self, font=('', 12, "bold"))
search_entry.grid(row=0, column=2)
submit_search = tk.Button(self, text="Search",
cursor="hand2", font=font_default,
command=lambda event=None: self.search_client(
tree, tk.END, messagebox,
search_entry.get(),
type_search.get()
))
submit_search.grid(row=0, column=3)
vsb = ttk.Scrollbar(self, orient="vertical", command=tree.yview)
hsb = ttk.Scrollbar(self, orient="horizontal", command=tree.xview)
tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
tree.grid(row=1, columnspan=4, sticky='nsew')
vsb.grid(row=1, column=4, rowspan=2, sticky='ns')
hsb.grid(row=2, column=0, columnspan=4, sticky='ew')
tree.heading('#1', text=self.table_fields[0])
tree.heading('#2', text=self.table_fields[1])
tree.heading('#3', text=self.table_fields[2])
tree.heading('#4', text=self.table_fields[3])
tree.heading('#5', text=self.table_fields[4])
tree.heading('#6', text=self.table_fields[5])
tree.heading('#7', text=self.table_fields[6])
tree.heading('#8', text=self.table_fields[7])
tree.heading('#9', text=self.table_fields[8])
tree.heading('#10', text=self.table_fields[9])
tree.bind('<Double-1>',
lambda event=None: FormClientUpdate(master, tree))
get_clients(tree, tk.END)
frame = tk.LabelFrame(self, text='Actions')
frame.grid(row=3, column=0, columnspan=4)
button_add = tk.Button(frame, text="Create", width='10',
cursor="hand2", font=font_default,
command=lambda: FormClientRegister(master, tree))
button_add.grid(row=1, column=1)
button_edit = tk.Button(frame, text="Read All", width='10',
cursor="hand2", font=font_default,
command=lambda: get_clients(tree, tk.END))
button_edit.grid(row=1, column=2)
button_delete = tk.Button(frame, text="Update", width='10',
cursor="hand2", font=font_default,
command=lambda event=None:
FormClientUpdate(master, tree))
button_delete.grid(row=1, column=3)
button_delete = tk.Button(frame, text="Delete", width='10',
cursor="hand2", font=font_default,
command=lambda event=None:
self.client_delete(tree, tk.END, messagebox))
button_delete.grid(row=1, column=4)
self.resizable(0, 0)
self.transient(master)
self.grab_set()
master.wait_window(self)
| [
"tkinter.LabelFrame",
"tkinter.Entry",
"tkinter.Toplevel.__init__",
"tkcalendar.DateEntry",
"tkinter.ttk.Scrollbar",
"tkcrud.controller.client_controller.get_clients",
"tkinter.font.Font",
"tkinter.StringVar",
"tkinter.Label",
"tkinter.ttk.Combobox",
"tkcrud.controller.client_controller.window_p... | [((327, 361), 'tkinter.Toplevel.__init__', 'tk.Toplevel.__init__', (['self', 'master'], {}), '(self, master)\n', (347, 361), True, 'import tkinter as tk\n'), ((444, 487), 'tkinter.LabelFrame', 'tk.LabelFrame', (['self'], {'text': '"""Register client"""'}), "(self, text='Register client')\n", (457, 487), True, 'import tkinter as tk\n'), ((569, 611), 'tkinter.Label', 'tk.Label', (['frame'], {'text': 'self.table_fields[1]'}), '(frame, text=self.table_fields[1])\n', (577, 611), True, 'import tkinter as tk\n'), ((668, 683), 'tkinter.Entry', 'tk.Entry', (['frame'], {}), '(frame)\n', (676, 683), True, 'import tkinter as tk\n'), ((764, 806), 'tkinter.Label', 'tk.Label', (['frame'], {'text': 'self.table_fields[2]'}), '(frame, text=self.table_fields[2])\n', (772, 806), True, 'import tkinter as tk\n'), ((869, 884), 'tkinter.Entry', 'tk.Entry', (['frame'], {}), '(frame)\n', (877, 884), True, 'import tkinter as tk\n'), ((953, 995), 'tkinter.Label', 'tk.Label', (['frame'], {'text': 'self.table_fields[3]'}), '(frame, text=self.table_fields[3])\n', (961, 995), True, 'import tkinter as tk\n'), ((1070, 1110), 'tkcalendar.DateEntry', 'DateEntry', (['frame'], {'date_pattern': '"""y-mm-dd"""'}), "(frame, date_pattern='y-mm-dd')\n", (1079, 1110), False, 'from tkcalendar import DateEntry\n'), ((1175, 1217), 'tkinter.Label', 'tk.Label', (['frame'], {'text': 'self.table_fields[4]'}), '(frame, text=self.table_fields[4])\n', (1183, 1217), True, 'import tkinter as tk\n'), ((1272, 1336), 'tkinter.ttk.Combobox', 'ttk.Combobox', (['frame'], {'values': "['Male', 'Female']", 'state': '"""readonly"""'}), "(frame, values=['Male', 'Female'], state='readonly')\n", (1284, 1336), False, 'from tkinter import ttk, messagebox, font, StringVar\n'), ((1402, 1444), 'tkinter.Label', 'tk.Label', (['frame'], {'text': 'self.table_fields[5]'}), '(frame, text=self.table_fields[5])\n', (1410, 1444), True, 'import tkinter as tk\n'), ((1521, 1536), 'tkinter.Entry', 'tk.Entry', (['frame'], {}), '(frame)\n', (1529, 1536), True, 'import tkinter as tk\n'), ((1601, 1643), 'tkinter.Label', 'tk.Label', (['frame'], {'text': 'self.table_fields[6]'}), '(frame, text=self.table_fields[6])\n', (1609, 1643), True, 'import tkinter as tk\n'), ((1696, 1711), 'tkinter.Entry', 'tk.Entry', (['frame'], {}), '(frame)\n', (1704, 1711), True, 'import tkinter as tk\n'), ((1765, 1807), 'tkinter.Label', 'tk.Label', (['frame'], {'text': 'self.table_fields[7]'}), '(frame, text=self.table_fields[7])\n', (1773, 1807), True, 'import tkinter as tk\n'), ((1862, 1877), 'tkinter.Entry', 'tk.Entry', (['frame'], {}), '(frame)\n', (1870, 1877), True, 'import tkinter as tk\n'), ((1939, 1981), 'tkinter.Label', 'tk.Label', (['frame'], {'text': 'self.table_fields[8]'}), '(frame, text=self.table_fields[8])\n', (1947, 1981), True, 'import tkinter as tk\n'), ((2050, 2065), 'tkinter.Entry', 'tk.Entry', (['frame'], {}), '(frame)\n', (2058, 2065), True, 'import tkinter as tk\n'), ((2129, 2171), 'tkinter.Label', 'tk.Label', (['frame'], {'text': 'self.table_fields[9]'}), '(frame, text=self.table_fields[9])\n', (2137, 2171), True, 'import tkinter as tk\n'), ((2231, 2246), 'tkinter.Entry', 'tk.Entry', (['frame'], {}), '(frame)\n', (2239, 2246), True, 'import tkinter as tk\n'), ((2999, 3033), 'tkinter.Label', 'tk.Label', (['frame'], {'text': '""""""', 'fg': '"""red"""'}), "(frame, text='', fg='red')\n", (3007, 3033), True, 'import tkinter as tk\n'), ((7933, 7967), 'tkinter.Toplevel.__init__', 'tk.Toplevel.__init__', (['self', 'master'], {}), '(self, master)\n', (7953, 7967), True, 'import tkinter as tk\n'), ((7983, 8092), 'tkinter.ttk.Treeview', 'ttk.Treeview', (['self'], {'columns': "('#0', '#1', '#2', '#3', '#4', '#5', '#6', '#7', '#8', '#9')", 'show': '"""headings"""'}), "(self, columns=('#0', '#1', '#2', '#3', '#4', '#5', '#6', '#7',\n '#8', '#9'), show='headings')\n", (7995, 8092), False, 'from tkinter import ttk, messagebox, font, StringVar\n'), ((8410, 8439), 'tkinter.font.Font', 'font.Font', ([], {'family': '""""""', 'size': '(12)'}), "(family='', size=12)\n", (8419, 8439), False, 'from tkinter import ttk, messagebox, font, StringVar\n'), ((8532, 8584), 'tkinter.Label', 'tk.Label', (['self'], {'text': '"""Search by:"""', 'font': 'font_default'}), "(self, text='Search by:', font=font_default)\n", (8540, 8584), True, 'import tkinter as tk\n'), ((8650, 8736), 'tkinter.ttk.Combobox', 'ttk.Combobox', (['self'], {'values': "['ID', 'Name']", 'state': '"""readonly"""', 'font': "('', 12, 'bold')"}), "(self, values=['ID', 'Name'], state='readonly', font=('', 12,\n 'bold'))\n", (8662, 8736), False, 'from tkinter import ttk, messagebox, font, StringVar\n'), ((8833, 8870), 'tkinter.Entry', 'tk.Entry', (['self'], {'font': "('', 12, 'bold')"}), "(self, font=('', 12, 'bold'))\n", (8841, 8870), True, 'import tkinter as tk\n'), ((9392, 9450), 'tkinter.ttk.Scrollbar', 'ttk.Scrollbar', (['self'], {'orient': '"""vertical"""', 'command': 'tree.yview'}), "(self, orient='vertical', command=tree.yview)\n", (9405, 9450), False, 'from tkinter import ttk, messagebox, font, StringVar\n'), ((9465, 9525), 'tkinter.ttk.Scrollbar', 'ttk.Scrollbar', (['self'], {'orient': '"""horizontal"""', 'command': 'tree.xview'}), "(self, orient='horizontal', command=tree.xview)\n", (9478, 9525), False, 'from tkinter import ttk, messagebox, font, StringVar\n'), ((10422, 10447), 'tkcrud.controller.client_controller.get_clients', 'get_clients', (['tree', 'tk.END'], {}), '(tree, tk.END)\n', (10433, 10447), False, 'from tkcrud.controller.client_controller import ClientController, saving_updating, get_clients, window_popup\n'), ((10465, 10500), 'tkinter.LabelFrame', 'tk.LabelFrame', (['self'], {'text': '"""Actions"""'}), "(self, text='Actions')\n", (10478, 10500), True, 'import tkinter as tk\n'), ((3401, 3435), 'tkinter.Toplevel.__init__', 'tk.Toplevel.__init__', (['self', 'master'], {}), '(self, master)\n', (3421, 3435), True, 'import tkinter as tk\n'), ((3496, 3537), 'tkinter.LabelFrame', 'tk.LabelFrame', (['self'], {'text': '"""Update client"""'}), "(self, text='Update client')\n", (3509, 3537), True, 'import tkinter as tk\n'), ((3633, 3675), 'tkinter.Label', 'tk.Label', (['frame'], {'text': 'self.table_fields[1]'}), '(frame, text=self.table_fields[1])\n', (3641, 3675), True, 'import tkinter as tk\n'), ((3964, 4006), 'tkinter.Label', 'tk.Label', (['frame'], {'text': 'self.table_fields[2]'}), '(frame, text=self.table_fields[2])\n', (3972, 4006), True, 'import tkinter as tk\n'), ((4286, 4328), 'tkinter.Label', 'tk.Label', (['frame'], {'text': 'self.table_fields[3]'}), '(frame, text=self.table_fields[3])\n', (4294, 4328), True, 'import tkinter as tk\n'), ((4484, 4549), 'tkcalendar.DateEntry', 'DateEntry', (['frame'], {'date_pattern': '"""y-mm-dd"""', 'value': 'old_date_of_birth'}), "(frame, date_pattern='y-mm-dd', value=old_date_of_birth)\n", (4493, 4549), False, 'from tkcalendar import DateEntry\n'), ((4661, 4703), 'tkinter.Label', 'tk.Label', (['frame'], {'text': 'self.table_fields[4]'}), '(frame, text=self.table_fields[4])\n', (4669, 4703), True, 'import tkinter as tk\n'), ((4835, 4846), 'tkinter.StringVar', 'StringVar', ([], {}), '()\n', (4844, 4846), False, 'from tkinter import ttk, messagebox, font, StringVar\n'), ((4865, 4926), 'tkinter.ttk.Combobox', 'ttk.Combobox', (['frame'], {'textvariable': 'sex_value', 'state': '"""readonly"""'}), "(frame, textvariable=sex_value, state='readonly')\n", (4877, 4926), False, 'from tkinter import ttk, messagebox, font, StringVar\n'), ((5172, 5214), 'tkinter.Label', 'tk.Label', (['frame'], {'text': 'self.table_fields[5]'}), '(frame, text=self.table_fields[5])\n', (5180, 5214), True, 'import tkinter as tk\n'), ((5617, 5659), 'tkinter.Label', 'tk.Label', (['frame'], {'text': 'self.table_fields[6]'}), '(frame, text=self.table_fields[6])\n', (5625, 5659), True, 'import tkinter as tk\n'), ((5904, 5946), 'tkinter.Label', 'tk.Label', (['frame'], {'text': 'self.table_fields[7]'}), '(frame, text=self.table_fields[7])\n', (5912, 5946), True, 'import tkinter as tk\n'), ((6203, 6245), 'tkinter.Label', 'tk.Label', (['frame'], {'text': 'self.table_fields[8]'}), '(frame, text=self.table_fields[8])\n', (6211, 6245), True, 'import tkinter as tk\n'), ((6623, 6665), 'tkinter.Label', 'tk.Label', (['frame'], {'text': 'self.table_fields[9]'}), '(frame, text=self.table_fields[9])\n', (6631, 6665), True, 'import tkinter as tk\n'), ((7497, 7531), 'tkinter.Label', 'tk.Label', (['frame'], {'text': '""""""', 'fg': '"""red"""'}), "(frame, text='', fg='red')\n", (7505, 7531), True, 'import tkinter as tk\n'), ((7776, 7825), 'tkcrud.controller.client_controller.window_popup', 'window_popup', (['messagebox', '"""Please, select record"""'], {}), "(messagebox, 'Please, select record')\n", (7788, 7825), False, 'from tkcrud.controller.client_controller import ClientController, saving_updating, get_clients, window_popup\n'), ((3838, 3869), 'tkinter.StringVar', 'StringVar', (['self'], {'value': 'old_name'}), '(self, value=old_name)\n', (3847, 3869), False, 'from tkinter import ttk, messagebox, font, StringVar\n'), ((4173, 4207), 'tkinter.StringVar', 'StringVar', (['self'], {'value': 'old_address'}), '(self, value=old_address)\n', (4182, 4207), False, 'from tkinter import ttk, messagebox, font, StringVar\n'), ((5440, 5481), 'tkinter.StringVar', 'StringVar', (['self'], {'value': 'old_marital_status'}), '(self, value=old_marital_status)\n', (5449, 5481), False, 'from tkinter import ttk, messagebox, font, StringVar\n'), ((5811, 5840), 'tkinter.StringVar', 'StringVar', (['self'], {'value': 'old_rg'}), '(self, value=old_rg)\n', (5820, 5840), False, 'from tkinter import ttk, messagebox, font, StringVar\n'), ((6101, 6131), 'tkinter.StringVar', 'StringVar', (['self'], {'value': 'old_cpf'}), '(self, value=old_cpf)\n', (6110, 6131), False, 'from tkinter import ttk, messagebox, font, StringVar\n'), ((6455, 6492), 'tkinter.StringVar', 'StringVar', (['self'], {'value': 'old_cell_phone'}), '(self, value=old_cell_phone)\n', (6464, 6492), False, 'from tkinter import ttk, messagebox, font, StringVar\n'), ((6827, 6859), 'tkinter.StringVar', 'StringVar', (['self'], {'value': 'old_email'}), '(self, value=old_email)\n', (6836, 6859), False, 'from tkinter import ttk, messagebox, font, StringVar\n'), ((10987, 11012), 'tkcrud.controller.client_controller.get_clients', 'get_clients', (['tree', 'tk.END'], {}), '(tree, tk.END)\n', (10998, 11012), False, 'from tkcrud.controller.client_controller import ClientController, saving_updating, get_clients, window_popup\n')] |
import sys, os, re, json, pprint, traceback
from pathlib import Path
from aiohttp import web
routes = web.RouteTableDef()
async def app():
from web_chains_202105 import directories
app = web.Application(middlewares=[exception_middleware])
app.add_routes(routes)
app.router.add_static("/js/", path="js", name="js")
directories.load(app)
app["charts"] = {} # loaded charts: {ace-path: acmacs.Chart}, loading is done on demand
sys.path[:0] = ["lib"] # to be abel to import acmacs module (acmacs_py) by web_chains_202105.chart
return app
# ======================================================================
# https://docs.aiohttp.org/en/stable/web_advanced.html
@web.middleware
async def exception_middleware(request, handler):
try:
return await handler(request)
except Exception as err:
import cgitb
context = 10
if "/api" in request.path:
return web.json_response({"ERROR": str(err), "tb": cgitb.text(sys.exc_info(), context=context)})
else:
return web.Response(text=cgitb.html(sys.exc_info(), context=context), content_type='text/html')
# ======================================================================
# pages
# ======================================================================
@routes.get("/")
async def index(request):
from web_chains_202105.index_page import index_page
return index_page(request=request)
# ----------------------------------------------------------------------
@routes.get("/table")
async def table_data(request):
from web_chains_202105.table_page import table_page
return table_page(request=request, subtype_id=request.query["subtype_id"], table_date=request.query["date"])
@routes.get("/chain")
async def chain_data(request):
from web_chains_202105.chain_page import chain_page
return chain_page(request=request, subtype_id=request.query["subtype_id"], chain_id=request.query["chain_id"])
# ======================================================================
# images
# ======================================================================
def image(request, image_type):
from web_chains_202105.chart import get_map
args = request_args(request)
if args["type"] == "map":
headers = {
"pid": str(os.getpid()),
"Content-Disposition": f'inline; filename="{Path(args["ace"]).with_suffix("." + image_type).name}"',
}
return web.Response(body=get_map(request=request, image_type=image_type, **args), content_type=sMimeType[image_type], headers=headers)
elif args["type"] == "pc":
headers = {
"pid": str(os.getpid()),
"Content-Disposition": f'inline; filename="pc-{Path(args["ace1"]).stem}-vs-{Path(args["ace2"]).stem}.{image_type}"',
}
return web.Response(body=get_map(request=request, image_type=image_type, **args), content_type=sMimeType[image_type], headers=headers)
else:
print(f">> WARNING: unsupported {image_type}:", request.query)
return web.Response(text=str(request.query), status=418, headers={"Error": f"unsupported {image_type}"})
@routes.get("/png")
async def png(request):
return image(request=request, image_type="png")
@routes.get("/pdf")
async def pdf(request):
return image(request=request, image_type="pdf")
# ======================================================================
# ace
# ======================================================================
@routes.get("/ace")
async def ace(request):
args = {kk: v for kk, v in ((k, t(request.query.get(k))) for k,t in [["ace", Path]]) if v is not None}
headers = {
"pid": str(os.getpid()),
"Content-Disposition": f'inline; filename="{args["ace"].name}"',
}
return web.Response(body=args["ace"].open("rb").read(), content_type=sMimeType["ace"], headers=headers)
# ======================================================================
# api
# ======================================================================
@routes.get("/api/subtype-data/")
async def subtype_data(request):
from web_chains_202105.index_page import collect_tables_of_subtype
subtype_id = request.query["subtype_id"]
return web.json_response({
"tables": collect_tables_of_subtype(subtype_id),
"subtype_id": subtype_id,
})
# ======================================================================
# utils
# ======================================================================
def bool_from_str(src):
return src and src.lower() in ["true", "yes", "1"]
sMimeType = {
"png": "image/png",
"pdf": "application/pdf",
"ace": "application/octet-stream",
}
sRequestArgTypes = [
["type", str],
["ace", str],
["ace1", str], # pc
["ace2", str], # pc
["coloring", str],
["size", int],
["save_chart", bool_from_str]
]
def request_args(request):
return {kk: v for kk, v in ((k, t(request.query.get(k))) for k,t in sRequestArgTypes) if v is not None}
# ======================================================================
| [
"web_chains_202105.chart.get_map",
"pathlib.Path",
"web_chains_202105.table_page.table_page",
"web_chains_202105.directories.load",
"web_chains_202105.index_page.index_page",
"aiohttp.web.Application",
"sys.exc_info",
"aiohttp.web.RouteTableDef",
"web_chains_202105.chain_page.chain_page",
"os.getp... | [((103, 122), 'aiohttp.web.RouteTableDef', 'web.RouteTableDef', ([], {}), '()\n', (120, 122), False, 'from aiohttp import web\n'), ((197, 248), 'aiohttp.web.Application', 'web.Application', ([], {'middlewares': '[exception_middleware]'}), '(middlewares=[exception_middleware])\n', (212, 248), False, 'from aiohttp import web\n'), ((336, 357), 'web_chains_202105.directories.load', 'directories.load', (['app'], {}), '(app)\n', (352, 357), False, 'from web_chains_202105 import directories\n'), ((1425, 1452), 'web_chains_202105.index_page.index_page', 'index_page', ([], {'request': 'request'}), '(request=request)\n', (1435, 1452), False, 'from web_chains_202105.index_page import index_page\n'), ((1648, 1753), 'web_chains_202105.table_page.table_page', 'table_page', ([], {'request': 'request', 'subtype_id': "request.query['subtype_id']", 'table_date': "request.query['date']"}), "(request=request, subtype_id=request.query['subtype_id'],\n table_date=request.query['date'])\n", (1658, 1753), False, 'from web_chains_202105.table_page import table_page\n'), ((1871, 1978), 'web_chains_202105.chain_page.chain_page', 'chain_page', ([], {'request': 'request', 'subtype_id': "request.query['subtype_id']", 'chain_id': "request.query['chain_id']"}), "(request=request, subtype_id=request.query['subtype_id'],\n chain_id=request.query['chain_id'])\n", (1881, 1978), False, 'from web_chains_202105.chain_page import chain_page\n'), ((3696, 3707), 'os.getpid', 'os.getpid', ([], {}), '()\n', (3705, 3707), False, 'import sys, os, re, json, pprint, traceback\n'), ((4284, 4321), 'web_chains_202105.index_page.collect_tables_of_subtype', 'collect_tables_of_subtype', (['subtype_id'], {}), '(subtype_id)\n', (4309, 4321), False, 'from web_chains_202105.index_page import collect_tables_of_subtype\n'), ((2318, 2329), 'os.getpid', 'os.getpid', ([], {}), '()\n', (2327, 2329), False, 'import sys, os, re, json, pprint, traceback\n'), ((2488, 2543), 'web_chains_202105.chart.get_map', 'get_map', ([], {'request': 'request', 'image_type': 'image_type'}), '(request=request, image_type=image_type, **args)\n', (2495, 2543), False, 'from web_chains_202105.chart import get_map\n'), ((2672, 2683), 'os.getpid', 'os.getpid', ([], {}), '()\n', (2681, 2683), False, 'import sys, os, re, json, pprint, traceback\n'), ((2858, 2913), 'web_chains_202105.chart.get_map', 'get_map', ([], {'request': 'request', 'image_type': 'image_type'}), '(request=request, image_type=image_type, **args)\n', (2865, 2913), False, 'from web_chains_202105.chart import get_map\n'), ((1002, 1016), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (1014, 1016), False, 'import sys, os, re, json, pprint, traceback\n'), ((1099, 1113), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (1111, 1113), False, 'import sys, os, re, json, pprint, traceback\n'), ((2745, 2763), 'pathlib.Path', 'Path', (["args['ace1']"], {}), "(args['ace1'])\n", (2749, 2763), False, 'from pathlib import Path\n'), ((2774, 2792), 'pathlib.Path', 'Path', (["args['ace2']"], {}), "(args['ace2'])\n", (2778, 2792), False, 'from pathlib import Path\n'), ((2388, 2405), 'pathlib.Path', 'Path', (["args['ace']"], {}), "(args['ace'])\n", (2392, 2405), False, 'from pathlib import Path\n')] |
# Copyright 2019 Zuru Tech HK Limited. 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.
"""GAN metrics."""
from __future__ import annotations
import operator
import os
import types
from pathlib import Path
from typing import TYPE_CHECKING, Callable, Union
import tensorflow as tf
import tensorflow_hub as hub
from ashpy.metrics import ClassifierMetric, Metric
from ashpy.modes import LogEvalMode
if TYPE_CHECKING:
from ashpy.contexts import ( # pylint: disable=ungrouped-imports
GANContext,
GANEncoderContext,
)
__ALL__ = [
"DiscriminatorLoss",
"EncoderLoss",
"EncodingAccuracy",
"GeneratorLoss",
"InceptionScore",
]
class DiscriminatorLoss(Metric):
"""The Discriminator loss value."""
def __init__(
self,
name: str = "d_loss",
model_selection_operator: Callable = None,
logdir: Union[Path, str] = Path().cwd() / "log",
) -> None:
"""
Initialize the Metric.
Args:
name (str): Name of the metric.
model_selection_operator (:py:obj:`typing.Callable`): The operation that will
be used when `model_selection` is triggered to compare the metrics,
used by the `update_state`.
Any :py:obj:`typing.Callable` behaving like an :py:mod:`operator` is accepted.
.. note::
Model selection is done ONLY if an operator is specified here.
logdir (str): Path to the log dir, defaults to a `log` folder in the current
directory.
"""
super().__init__(
name=name,
metric=tf.metrics.Mean(name=name, dtype=tf.float32),
model_selection_operator=model_selection_operator,
logdir=logdir,
)
def update_state(self, context: GANContext) -> None:
"""
Update the internal state of the metric, using the information from the context object.
Args:
context (:py:class:`ashpy.contexts.gan.GANContext`): An AshPy Context Object
that carries all the information the Metric needs.
"""
updater = lambda value: lambda: self._metric.update_state(value)
for real_xy, noise in context.dataset:
real_x, real_y = real_xy
g_inputs = noise
if len(context.generator_model.inputs) == 2:
g_inputs = [noise, real_y]
fake = context.generator_model(
g_inputs, training=context.log_eval_mode == LogEvalMode.TRAIN
)
loss = context.discriminator_loss(
context,
fake=fake,
real=real_x,
condition=real_y,
training=context.log_eval_mode == LogEvalMode.TRAIN,
)
self._distribute_strategy.experimental_run_v2(updater(loss))
class GeneratorLoss(Metric):
"""Generator loss value."""
def __init__(
self,
name: str = "g_loss",
model_selection_operator: Callable = None,
logdir: Union[Path, str] = Path().cwd() / "log",
):
"""
Initialize the Metric.
Args:
name (str): Name of the metric.
model_selection_operator (:py:obj:`typing.Callable`): The operation that will
be used when `model_selection` is triggered to compare the metrics,
used by the `update_state`.
Any :py:obj:`typing.Callable` behaving like an :py:mod:`operator` is accepted.
.. note::
Model selection is done ONLY if an operator is specified here.
logdir (str): Path to the log dir, defaults to a `log` folder in the current
directory.
"""
super().__init__(
name=name,
metric=tf.metrics.Mean(name=name, dtype=tf.float32),
model_selection_operator=model_selection_operator,
logdir=logdir,
)
def update_state(self, context: GANContext) -> None:
"""
Update the internal state of the metric, using the information from the context object.
Args:
context (:py:class:`ashpy.contexts.GANContext`): An AshPy Context Object that carries
all the information the Metric needs.
"""
updater = lambda value: lambda: self._metric.update_state(value)
for real_xy, noise in context.dataset:
real_x, real_y = real_xy
g_inputs = noise
if len(context.generator_model.inputs) == 2:
g_inputs = [noise, real_y]
fake = context.generator_model(
g_inputs, training=context.log_eval_mode == LogEvalMode.TRAIN
)
loss = context.generator_loss(
context,
fake=fake,
real=real_x,
condition=real_y,
training=context.log_eval_mode == LogEvalMode.TRAIN,
)
self._distribute_strategy.experimental_run_v2(updater(loss))
class EncoderLoss(Metric):
"""Encoder Loss value."""
def __init__(
self,
name: str = "e_loss",
model_selection_operator: Callable = None,
logdir: Union[Path, str] = Path().cwd() / "log",
) -> None:
"""
Initialize the Metric.
Args:
name (str): Name of the metric.
model_selection_operator (:py:obj:`typing.Callable`): The operation that will
be used when `model_selection` is triggered to compare the metrics,
used by the `update_state`.
Any :py:obj:`typing.Callable` behaving like an :py:mod:`operator` is accepted.
.. note::
Model selection is done ONLY if an operator is specified here.
logdir (str): Path to the log dir, defaults to a `log` folder in the current
directory.
"""
super().__init__(
name=name,
metric=tf.metrics.Mean(name=name, dtype=tf.float32),
model_selection_operator=model_selection_operator,
logdir=logdir,
)
def update_state(self, context: GANEncoderContext) -> None:
"""
Update the internal state of the metric, using the information from the context object.
Args:
context (:py:class:`ashpy.contexts.gan.GANEncoderContext`): An AshPy Context Object
that carries all the information the Metric needs.
"""
updater = lambda value: lambda: self._metric.update_state(value)
for real_xy, noise in context.dataset:
real_x, real_y = real_xy
g_inputs = noise
if len(context.generator_model.inputs) == 2:
g_inputs = [noise, real_y]
fake = context.generator_model(
g_inputs, training=context.log_eval_mode == LogEvalMode.TRAIN
)
loss = context.encoder_loss(
context,
fake=fake,
real=real_x,
condition=real_y,
training=context.log_eval_mode == LogEvalMode.TRAIN,
)
self._distribute_strategy.experimental_run_v2(updater(loss))
class InceptionScore(Metric):
r"""
Inception Score Metric.
This class is an implementation of the Inception Score technique for evaluating a GAN.
See Improved Techniques for Training GANs [1]_.
.. [1] Improved Techniques for Training GANs https://arxiv.org/abs/1606.03498
"""
def __init__(
self,
inception: tf.keras.Model,
name: str = "inception_score",
model_selection_operator=operator.gt,
logdir=Path().cwd() / "log",
):
"""
Initialize the Metric.
Args:
inception (:py:class:`tf.keras.Model`): Keras Inception model.
name (str): Name of the metric.
model_selection_operator (:py:obj:`typing.Callable`): The operation that will
be used when `model_selection` is triggered to compare the metrics,
used by the `update_state`.
Any :py:obj:`typing.Callable` behaving like an :py:mod:`operator` is accepted.
.. note::
Model selection is done ONLY if an operator is specified here.
logdir (str): Path to the log dir, defaults to a `log` folder in the current
directory.
"""
super().__init__(
name=name,
metric=tf.metrics.Mean(name),
model_selection_operator=model_selection_operator,
logdir=logdir,
)
self._inception_model = inception
# add softmax layer if not present
if "softmax" not in self._inception_model.layers[-1].name.lower():
self._inception_model = tf.keras.Sequential(
[self._inception_model, tf.keras.layers.Softmax()]
)
def update_state(self, context: GANContext) -> None:
"""
Update the internal state of the metric, using the information from the context object.
Args:
context (:py:class:`ashpy.contexts.ClassifierContext`): An AshPy Context
holding all the information the Metric needs.
"""
updater = lambda value: lambda: self._metric.update_state(value)
# Generate the images created with the AshPy Context's generator
for real_xy, noise in context.dataset:
_, real_y = real_xy
g_inputs = noise
if len(context.generator_model.inputs) == 2:
g_inputs = [noise, real_y]
fake = context.generator_model(
g_inputs, training=context.log_eval_mode == LogEvalMode.TRAIN
)
# rescale images between 0 and 1
fake = (fake + 1.0) / 2.0
# Resize images to 299x299
fake = tf.image.resize(fake, (299, 299))
try:
fake = tf.image.grayscale_to_rgb(fake)
except ValueError:
# Images are already RGB
pass
# Calculate the inception score
inception_score_per_batch = self.inception_score(fake)
# Update the Mean metric created for this context
# self._metric.update_state(mean)
self._distribute_strategy.experimental_run_v2(
updater(inception_score_per_batch)
)
def inception_score(self, images: tf.Tensor) -> tf.Tensor:
"""
Compute the Inception Score.
Args:
images (:py:obj:`list` of [:py:class:`numpy.ndarray`]): A list of ndarray of
generated images of 299x299 of size.
Returns:
:obj:`tuple` of (:py:class:`numpy.ndarray`, :py:class:`numpy.ndarray`): Mean and STD.
"""
print("Computing inception score...")
predictions: tf.Tensor = self._inception_model(images)
kl_divergence = predictions * (
tf.math.log(predictions)
- tf.math.log(tf.math.reduce_mean(predictions, axis=0, keepdims=True))
)
kl_divergence = tf.math.reduce_mean(tf.math.reduce_sum(kl_divergence, axis=1))
inception_score_per_batch = tf.math.exp(kl_divergence)
return inception_score_per_batch
@staticmethod
def get_or_train_inception(
dataset: tf.data.Dataset,
name: str,
num_classes: int,
epochs: int,
fine_tuning: bool = False,
loss_fn: tf.keras.losses.Loss = tf.keras.losses.SparseCategoricalCrossentropy(
from_logits=True
),
optimizer: tf.keras.optimizers.Adam = tf.keras.optimizers.Adam(1e-5),
logdir: Union[Path, str] = Path().cwd() / "log",
) -> tf.keras.Model:
"""
Restore or train (and save) the Inception model.
Args:
dataset (:py:class:`tf.data.Dataset`): Dataset to re-train Inception Model on.
name (str): Name of this new Inception Model, used for saving it.
num_classes (int): Number of classes to use for classification.
epochs (int): Epochs to train the Inception model for.
fine_tuning (bool): Controls wether the model will be fine-tuned or used as is.
loss_fn (:py:class:`tf.keras.losses.Loss`): Keras Loss for the model.
optimizer (:py:class:`tf.keras.optimizers.Optimizer`): Keras optimizer for the model.
logdir (str): Path to the log dir, defaults to a `log` folder in the current
directory.
Returns:
:py:class:`tf.keras.Model`: The Inception Model.
"""
os.environ["TFHUB_DOWNLOAD_PROGRESS"] = "1"
model = tf.keras.Sequential(
[
hub.KerasLayer(
"https://tfhub.dev/google/tf2-preview/inception_v3/feature_vector/2",
output_shape=[2048],
trainable=fine_tuning,
),
tf.keras.layers.Dense(512),
tf.keras.layers.LeakyReLU(alpha=0.05),
tf.keras.layers.Dense(num_classes),
]
)
del os.environ["TFHUB_DOWNLOAD_PROGRESS"]
step = tf.Variable(0, trainable=False, dtype=tf.int64)
ckpt = tf.train.Checkpoint()
ckpt.objects = []
ckpt.objects.extend([model, step])
logdir = logdir
manager = tf.train.CheckpointManager(
ckpt, logdir / "inception", name, max_to_keep=1
)
if manager.latest_checkpoint:
ckpt.restore(manager.latest_checkpoint)
print(f"Restored checkpoint {manager.latest_checkpoint}.")
return model
print("Training the InceptionV3 model")
# callback checkpoint
model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(logdir)
model.compile(loss=loss_fn, optimizer=optimizer)
model.fit(dataset, epochs=epochs, callbacks=[model_checkpoint_callback])
return model
class EncodingAccuracy(ClassifierMetric):
"""
Generator and Encoder accuracy performance.
Measure the Generator and Encoder performance together, by classifying:
`G(E(x)), y` using a pre-trained classified (on the dataset of x).
"""
def __init__(
self,
classifier: tf.keras.Model,
name: str = "encoding_accuracy",
model_selection_operator: Callable = None,
logdir=Path().cwd() / "log",
) -> None:
"""
Measure the Generator and Encoder performance together.
This is done by classifying: `G(E(x)), y` using a pre-trained classified
(on the dataset of x).
Args:
classifier (:py:class:`tf.keras.Model`): Keras Model to use as a Classifier to
measure the accuracy. Generally assumed to be the Inception Model.
name (str): Name of the metric.
model_selection_operator (:py:obj:`typing.Callable`): The operation that will
be used when `model_selection` is triggered to compare the metrics,
used by the `update_state`.
Any :py:obj:`typing.Callable` behaving like an :py:mod:`operator` is accepted.
.. note::
Model selection is done ONLY if an operator is specified here.
logdir (str): Path to the log dir, defaults to a `log` folder in the current
directory.
"""
super().__init__(
metric=tf.metrics.Accuracy(name),
model_selection_operator=model_selection_operator,
logdir=logdir,
)
self._classifier = classifier
def update_state(self, context: GANEncoderContext) -> None:
"""
Update the internal state of the metric, using the information from the context object.
Args:
context (:py:class:`ashpy.contexts.GANEncoderContext`): An AshPy Context Object
that carries all the information the Metric needs.
"""
inner_context = types.SimpleNamespace()
inner_context.classifier_model = self._classifier
inner_context.log_eval_mode = LogEvalMode.TEST
# Return G(E(x)), y
def _gen(real_xy, _):
real_x, real_y = real_xy
out = context.generator_model(
context.encoder_model(
real_x, training=context.log_eval_mode == LogEvalMode.TRAIN
),
training=context.log_eval_mode == LogEvalMode.TRAIN,
)
return out, real_y
dataset = context.dataset.map(_gen)
inner_context.dataset = dataset
# Classify using the pre-trained classifier (self._classifier)
# G(E(x)) and check the accuracy (with y)
super().update_state(inner_context)
| [
"tensorflow.train.Checkpoint",
"tensorflow.metrics.Mean",
"tensorflow.math.log",
"tensorflow.metrics.Accuracy",
"tensorflow.keras.layers.Dense",
"tensorflow.math.exp",
"pathlib.Path",
"tensorflow.image.grayscale_to_rgb",
"tensorflow.math.reduce_mean",
"tensorflow_hub.KerasLayer",
"tensorflow.ker... | [((11863, 11889), 'tensorflow.math.exp', 'tf.math.exp', (['kl_divergence'], {}), '(kl_divergence)\n', (11874, 11889), True, 'import tensorflow as tf\n'), ((12157, 12220), 'tensorflow.keras.losses.SparseCategoricalCrossentropy', 'tf.keras.losses.SparseCategoricalCrossentropy', ([], {'from_logits': '(True)'}), '(from_logits=True)\n', (12202, 12220), True, 'import tensorflow as tf\n'), ((12290, 12321), 'tensorflow.keras.optimizers.Adam', 'tf.keras.optimizers.Adam', (['(1e-05)'], {}), '(1e-05)\n', (12314, 12321), True, 'import tensorflow as tf\n'), ((13848, 13895), 'tensorflow.Variable', 'tf.Variable', (['(0)'], {'trainable': '(False)', 'dtype': 'tf.int64'}), '(0, trainable=False, dtype=tf.int64)\n', (13859, 13895), True, 'import tensorflow as tf\n'), ((13912, 13933), 'tensorflow.train.Checkpoint', 'tf.train.Checkpoint', ([], {}), '()\n', (13931, 13933), True, 'import tensorflow as tf\n'), ((14045, 14120), 'tensorflow.train.CheckpointManager', 'tf.train.CheckpointManager', (['ckpt', "(logdir / 'inception')", 'name'], {'max_to_keep': '(1)'}), "(ckpt, logdir / 'inception', name, max_to_keep=1)\n", (14071, 14120), True, 'import tensorflow as tf\n'), ((14446, 14488), 'tensorflow.keras.callbacks.ModelCheckpoint', 'tf.keras.callbacks.ModelCheckpoint', (['logdir'], {}), '(logdir)\n', (14480, 14488), True, 'import tensorflow as tf\n'), ((16689, 16712), 'types.SimpleNamespace', 'types.SimpleNamespace', ([], {}), '()\n', (16710, 16712), False, 'import types\n'), ((10515, 10548), 'tensorflow.image.resize', 'tf.image.resize', (['fake', '(299, 299)'], {}), '(fake, (299, 299))\n', (10530, 10548), True, 'import tensorflow as tf\n'), ((11784, 11825), 'tensorflow.math.reduce_sum', 'tf.math.reduce_sum', (['kl_divergence'], {'axis': '(1)'}), '(kl_divergence, axis=1)\n', (11802, 11825), True, 'import tensorflow as tf\n'), ((2165, 2209), 'tensorflow.metrics.Mean', 'tf.metrics.Mean', ([], {'name': 'name', 'dtype': 'tf.float32'}), '(name=name, dtype=tf.float32)\n', (2180, 2209), True, 'import tensorflow as tf\n'), ((4369, 4413), 'tensorflow.metrics.Mean', 'tf.metrics.Mean', ([], {'name': 'name', 'dtype': 'tf.float32'}), '(name=name, dtype=tf.float32)\n', (4384, 4413), True, 'import tensorflow as tf\n'), ((6568, 6612), 'tensorflow.metrics.Mean', 'tf.metrics.Mean', ([], {'name': 'name', 'dtype': 'tf.float32'}), '(name=name, dtype=tf.float32)\n', (6583, 6612), True, 'import tensorflow as tf\n'), ((9115, 9136), 'tensorflow.metrics.Mean', 'tf.metrics.Mean', (['name'], {}), '(name)\n', (9130, 9136), True, 'import tensorflow as tf\n'), ((10590, 10621), 'tensorflow.image.grayscale_to_rgb', 'tf.image.grayscale_to_rgb', (['fake'], {}), '(fake)\n', (10615, 10621), True, 'import tensorflow as tf\n'), ((11622, 11646), 'tensorflow.math.log', 'tf.math.log', (['predictions'], {}), '(predictions)\n', (11633, 11646), True, 'import tensorflow as tf\n'), ((13399, 13536), 'tensorflow_hub.KerasLayer', 'hub.KerasLayer', (['"""https://tfhub.dev/google/tf2-preview/inception_v3/feature_vector/2"""'], {'output_shape': '[2048]', 'trainable': 'fine_tuning'}), "(\n 'https://tfhub.dev/google/tf2-preview/inception_v3/feature_vector/2',\n output_shape=[2048], trainable=fine_tuning)\n", (13413, 13536), True, 'import tensorflow_hub as hub\n'), ((13624, 13650), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(512)'], {}), '(512)\n', (13645, 13650), True, 'import tensorflow as tf\n'), ((13668, 13705), 'tensorflow.keras.layers.LeakyReLU', 'tf.keras.layers.LeakyReLU', ([], {'alpha': '(0.05)'}), '(alpha=0.05)\n', (13693, 13705), True, 'import tensorflow as tf\n'), ((13723, 13757), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['num_classes'], {}), '(num_classes)\n', (13744, 13757), True, 'import tensorflow as tf\n'), ((16139, 16164), 'tensorflow.metrics.Accuracy', 'tf.metrics.Accuracy', (['name'], {}), '(name)\n', (16158, 16164), True, 'import tensorflow as tf\n'), ((1405, 1411), 'pathlib.Path', 'Path', ([], {}), '()\n', (1409, 1411), False, 'from pathlib import Path\n'), ((3617, 3623), 'pathlib.Path', 'Path', ([], {}), '()\n', (3621, 3623), False, 'from pathlib import Path\n'), ((5808, 5814), 'pathlib.Path', 'Path', ([], {}), '()\n', (5812, 5814), False, 'from pathlib import Path\n'), ((8288, 8294), 'pathlib.Path', 'Path', ([], {}), '()\n', (8292, 8294), False, 'from pathlib import Path\n'), ((9497, 9522), 'tensorflow.keras.layers.Softmax', 'tf.keras.layers.Softmax', ([], {}), '()\n', (9520, 9522), True, 'import tensorflow as tf\n'), ((11673, 11728), 'tensorflow.math.reduce_mean', 'tf.math.reduce_mean', (['predictions'], {'axis': '(0)', 'keepdims': '(True)'}), '(predictions, axis=0, keepdims=True)\n', (11692, 11728), True, 'import tensorflow as tf\n'), ((12357, 12363), 'pathlib.Path', 'Path', ([], {}), '()\n', (12361, 12363), False, 'from pathlib import Path\n'), ((15082, 15088), 'pathlib.Path', 'Path', ([], {}), '()\n', (15086, 15088), False, 'from pathlib import Path\n')] |
# -*- coding: utf-8 -*-
"""Database module, including the SQLAlchemy database object and DB-related utilities."""
import json
from sqlalchemy.inspection import inspect
from sqlalchemy.orm import relationship
from .extensions import db
# Alias common SQLAlchemy names
Column = db.Column
relationship = relationship
class CRUDMixin(object):
"""Mixin that adds convenience methods for CRUD (create, read, update, delete) operations."""
@classmethod
def create(cls, **kwargs):
"""Create a new record and save it the database."""
instance = cls(**kwargs)
return instance.save()
def update(self, commit=True, **kwargs):
"""Update specific fields of a record."""
for attr, value in kwargs.items():
setattr(self, attr, value)
return commit and self.save() or self
def save(self, commit=True):
"""Save the record."""
db.session.add(self)
if commit:
db.session.commit()
return self
def delete(self, commit=True):
"""Remove the record from the database."""
db.session.delete(self)
return commit and db.session.commit()
class Model(CRUDMixin, db.Model):
"""Base model class that includes CRUD convenience methods."""
__abstract__ = True
def serialize(self, includes=None):
return {c: getattr(self, c) for c in inspect(self).attrs.keys()}
def to_json(self, includes=None):
return json.dumps(self.serialize(includes))
@classmethod
def serialize_list(cls, l, includes=None):
return [m.serialize(includes) for m in l]
@classmethod
def list_to_json(cls, l, includes=None):
return json.dumps(cls.serialize_list(l, includes))
| [
"sqlalchemy.inspection.inspect"
] | [((1383, 1396), 'sqlalchemy.inspection.inspect', 'inspect', (['self'], {}), '(self)\n', (1390, 1396), False, 'from sqlalchemy.inspection import inspect\n')] |
from owslib.wms import WebMapService
from owslib import crs
from PIL import Image, ImageEnhance, ImageFilter
import cv2
import numpy as np
from pyspark import SparkContext
from pyproj import Proj
c = crs.Crs('EPSG:3857')
wms = WebMapService('http://www.ign.es/wms-inspire/pnoa-ma', version='1.3.0')
box = 1000 # m?
x=236814#m?
y=5068880 #m?
picsize = 512
img = wms.getmap(
layers=['OI.OrthoimageCoverage'],
styles=[],
srs='EPSG:3857',
bbox=(x - box, y - box, x + box, y + box),
size=(picsize,picsize), #W,H px
format='image/png',
transparent=False
)
with open('image.png','wb') as out:
out.write(img.read())
def green_detection():
img = cv2.imread('image.png')
# Green fields detection
hsv= cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
#Threshold for detecting green
lower = np.array([15, 58, 15])
upper = np.array([100,240,100])
# Apply mask
mask = cv2.inRange(hsv, lower, upper)
output = cv2.bitwise_and(img, img, mask = mask)
hsv_gray= cv2.cvtColor(output, cv2.COLOR_BGR2GRAY)
green_edges=cv2.Canny(hsv_gray,100,200)
cv2.imwrite('green_hsv.png',hsv)
cv2.imwrite('green.png',output)
cv2.imwrite('green_edges.png', green_edges)
def contour_detection():
# Get the contours
canny_img= cv2.imread('green_edges.png',0)
img= cv2.imread('image.png',1)
img2= cv2.imread('image.png',1)
_, contours, hierarchy=cv2.findContours(canny_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img,contours,-1,(0,255,0))
cv2.imwrite('image_contours.png',img)
#Filter the contours corresponding to football fields comparing the areas of the contours
k=0
filteredContours=[]
fields_x_positions=[]
fields_y_positions=[]
thresholdarea= 800
while(k < len(contours)):
epsilon = 0.1*cv2.arcLength(contours[k],True)
contours[k] = cv2.approxPolyDP(contours[k],epsilon,True)
area = cv2.contourArea(contours[k])
print("Area; ",area)
if thresholdarea + 200 > area > thresholdarea - 200:
filteredContours.append(contours[k])
k+=1
cv2.drawContours(img2,filteredContours,-1,(0,255,0))
cv2.imwrite('image_contours_filtered.png',img2)
return filteredContours
def location_convertor(contours,xm,ym,box,picsize):
p1 = Proj(init='epsg:3857')
c=[]
for i,e in enumerate(contours):
# We calculate the center point of each contour
print(e.tolist())
bounds= cv2.boundingRect(contours[i])
x1,y1,w,h = bounds
x=x1+w/2
y=y1+h/2
print(x,y)
# Pixel to meter conversion
x = (xm-box) + 2*box*(x1/picsize)
y = (ym+box) - 2*box*(y1/picsize)
# Meter to lon,lat conversion
lon, lat = p1(x,y,inverse=True)
c+=[[lon,lat]]
return c
if __name__ == "__main__":
green_detection()
c=contour_detection()
centers=location_convertor(c,x,y,box,picsize)
print(centers) | [
"cv2.imwrite",
"cv2.drawContours",
"owslib.wms.WebMapService",
"cv2.inRange",
"owslib.crs.Crs",
"cv2.arcLength",
"cv2.bitwise_and",
"cv2.contourArea",
"numpy.array",
"cv2.approxPolyDP",
"cv2.cvtColor",
"pyproj.Proj",
"cv2.findContours",
"cv2.Canny",
"cv2.imread",
"cv2.boundingRect"
] | [((201, 221), 'owslib.crs.Crs', 'crs.Crs', (['"""EPSG:3857"""'], {}), "('EPSG:3857')\n", (208, 221), False, 'from owslib import crs\n'), ((228, 299), 'owslib.wms.WebMapService', 'WebMapService', (['"""http://www.ign.es/wms-inspire/pnoa-ma"""'], {'version': '"""1.3.0"""'}), "('http://www.ign.es/wms-inspire/pnoa-ma', version='1.3.0')\n", (241, 299), False, 'from owslib.wms import WebMapService\n'), ((682, 705), 'cv2.imread', 'cv2.imread', (['"""image.png"""'], {}), "('image.png')\n", (692, 705), False, 'import cv2\n'), ((744, 780), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2HSV'], {}), '(img, cv2.COLOR_BGR2HSV)\n', (756, 780), False, 'import cv2\n'), ((829, 851), 'numpy.array', 'np.array', (['[15, 58, 15]'], {}), '([15, 58, 15])\n', (837, 851), True, 'import numpy as np\n'), ((864, 889), 'numpy.array', 'np.array', (['[100, 240, 100]'], {}), '([100, 240, 100])\n', (872, 889), True, 'import numpy as np\n'), ((921, 951), 'cv2.inRange', 'cv2.inRange', (['hsv', 'lower', 'upper'], {}), '(hsv, lower, upper)\n', (932, 951), False, 'import cv2\n'), ((965, 1001), 'cv2.bitwise_and', 'cv2.bitwise_and', (['img', 'img'], {'mask': 'mask'}), '(img, img, mask=mask)\n', (980, 1001), False, 'import cv2\n'), ((1019, 1059), 'cv2.cvtColor', 'cv2.cvtColor', (['output', 'cv2.COLOR_BGR2GRAY'], {}), '(output, cv2.COLOR_BGR2GRAY)\n', (1031, 1059), False, 'import cv2\n'), ((1076, 1105), 'cv2.Canny', 'cv2.Canny', (['hsv_gray', '(100)', '(200)'], {}), '(hsv_gray, 100, 200)\n', (1085, 1105), False, 'import cv2\n'), ((1109, 1142), 'cv2.imwrite', 'cv2.imwrite', (['"""green_hsv.png"""', 'hsv'], {}), "('green_hsv.png', hsv)\n", (1120, 1142), False, 'import cv2\n'), ((1146, 1178), 'cv2.imwrite', 'cv2.imwrite', (['"""green.png"""', 'output'], {}), "('green.png', output)\n", (1157, 1178), False, 'import cv2\n'), ((1182, 1225), 'cv2.imwrite', 'cv2.imwrite', (['"""green_edges.png"""', 'green_edges'], {}), "('green_edges.png', green_edges)\n", (1193, 1225), False, 'import cv2\n'), ((1291, 1323), 'cv2.imread', 'cv2.imread', (['"""green_edges.png"""', '(0)'], {}), "('green_edges.png', 0)\n", (1301, 1323), False, 'import cv2\n'), ((1332, 1358), 'cv2.imread', 'cv2.imread', (['"""image.png"""', '(1)'], {}), "('image.png', 1)\n", (1342, 1358), False, 'import cv2\n'), ((1368, 1394), 'cv2.imread', 'cv2.imread', (['"""image.png"""', '(1)'], {}), "('image.png', 1)\n", (1378, 1394), False, 'import cv2\n'), ((1421, 1488), 'cv2.findContours', 'cv2.findContours', (['canny_img', 'cv2.RETR_TREE', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(canny_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n', (1437, 1488), False, 'import cv2\n'), ((1491, 1539), 'cv2.drawContours', 'cv2.drawContours', (['img', 'contours', '(-1)', '(0, 255, 0)'], {}), '(img, contours, -1, (0, 255, 0))\n', (1507, 1539), False, 'import cv2\n'), ((1539, 1577), 'cv2.imwrite', 'cv2.imwrite', (['"""image_contours.png"""', 'img'], {}), "('image_contours.png', img)\n", (1550, 1577), False, 'import cv2\n'), ((2131, 2188), 'cv2.drawContours', 'cv2.drawContours', (['img2', 'filteredContours', '(-1)', '(0, 255, 0)'], {}), '(img2, filteredContours, -1, (0, 255, 0))\n', (2147, 2188), False, 'import cv2\n'), ((2188, 2236), 'cv2.imwrite', 'cv2.imwrite', (['"""image_contours_filtered.png"""', 'img2'], {}), "('image_contours_filtered.png', img2)\n", (2199, 2236), False, 'import cv2\n'), ((2329, 2351), 'pyproj.Proj', 'Proj', ([], {'init': '"""epsg:3857"""'}), "(init='epsg:3857')\n", (2333, 2351), False, 'from pyproj import Proj\n'), ((1887, 1931), 'cv2.approxPolyDP', 'cv2.approxPolyDP', (['contours[k]', 'epsilon', '(True)'], {}), '(contours[k], epsilon, True)\n', (1903, 1931), False, 'import cv2\n'), ((1945, 1973), 'cv2.contourArea', 'cv2.contourArea', (['contours[k]'], {}), '(contours[k])\n', (1960, 1973), False, 'import cv2\n'), ((2473, 2502), 'cv2.boundingRect', 'cv2.boundingRect', (['contours[i]'], {}), '(contours[i])\n', (2489, 2502), False, 'import cv2\n'), ((1833, 1865), 'cv2.arcLength', 'cv2.arcLength', (['contours[k]', '(True)'], {}), '(contours[k], True)\n', (1846, 1865), False, 'import cv2\n')] |
"""Set of basic widgets for BioImageIT
Classes
-------
BiWebBrowser
"""
from qtpy.QtWebEngineWidgets import QWebEngineView
from qtpy.QtWidgets import (QWidget, QPushButton,
QHBoxLayout, QVBoxLayout)
class BiWebBrowser(QWidget):
def __init__(self, parent: QWidget):
super(BiWebBrowser, self).__init__(parent)
thisLayout = QVBoxLayout()
thisLayout.setContentsMargins(0,0,0,0)
thisLayout.setSpacing(0)
self.toolBar = self.createToolBar()
self.toolBar.setMaximumHeight(48)
self.webView = QWebEngineView(self)
thisLayout.addWidget(self.toolBar)
thisLayout.addWidget(self.webView)
totalWidget = QWidget()
totalLayout = QVBoxLayout()
totalLayout.setContentsMargins(0,0,0,0)
totalWidget.setLayout(thisLayout)
self.setLayout(totalLayout)
totalLayout.addWidget(totalWidget)
totalWidget.setObjectName("BiWebBrowser")
def setToolBarVisible(self, visible:bool):
self.toolBar.setVisible(visible)
def createToolBar(self) -> QWidget:
toolbar = QWidget()
toolbar.setObjectName("BiSubToolBar")
backButton = QPushButton()
backButton.setFixedSize(32,32)
backButton.pressed.connect(self.back)
backButton.setObjectName("BiWebBrowserBack")
forwardButton = QPushButton()
forwardButton.setFixedSize(32,32)
forwardButton.pressed.connect(self.forward)
forwardButton.setObjectName("BiWebBrowserForward")
homeButton = QPushButton()
homeButton.setFixedSize(32,32)
homeButton.pressed.connect(self.home)
homeButton.setObjectName("BiWebBrowserHome")
barLayout = QHBoxLayout()
barLayout.setSpacing(1)
barLayout.setContentsMargins(2,2,2,2)
barLayout.addWidget(backButton)
barLayout.addWidget(forwardButton)
barLayout.addWidget(homeButton)
barLayout.addWidget(QWidget())
toolbar.setLayout(barLayout)
return toolbar
def forward(self):
self.webView.forward()
def back(self):
self.webView.back()
def home(self):
self.setHomePage(self.homeURL, self.isWebURL)
def setHomePageHtml(self, html:str):
self.webView.setHtml(html)
def setHomePage(self, pageURL: str, isWebURL: bool):
self.homeURL = pageURL
self.isWebURL = isWebURL
if self.isWebURL:
self.webView.load(pageURL)
else:
self.homeURL = self.homeURL.replace("\\", "/")
self.webView.load( "file:///" + self.homeURL)
| [
"qtpy.QtWidgets.QVBoxLayout",
"qtpy.QtWidgets.QWidget",
"qtpy.QtWebEngineWidgets.QWebEngineView",
"qtpy.QtWidgets.QPushButton",
"qtpy.QtWidgets.QHBoxLayout"
] | [((377, 390), 'qtpy.QtWidgets.QVBoxLayout', 'QVBoxLayout', ([], {}), '()\n', (388, 390), False, 'from qtpy.QtWidgets import QWidget, QPushButton, QHBoxLayout, QVBoxLayout\n'), ((581, 601), 'qtpy.QtWebEngineWidgets.QWebEngineView', 'QWebEngineView', (['self'], {}), '(self)\n', (595, 601), False, 'from qtpy.QtWebEngineWidgets import QWebEngineView\n'), ((712, 721), 'qtpy.QtWidgets.QWidget', 'QWidget', ([], {}), '()\n', (719, 721), False, 'from qtpy.QtWidgets import QWidget, QPushButton, QHBoxLayout, QVBoxLayout\n'), ((744, 757), 'qtpy.QtWidgets.QVBoxLayout', 'QVBoxLayout', ([], {}), '()\n', (755, 757), False, 'from qtpy.QtWidgets import QWidget, QPushButton, QHBoxLayout, QVBoxLayout\n'), ((1129, 1138), 'qtpy.QtWidgets.QWidget', 'QWidget', ([], {}), '()\n', (1136, 1138), False, 'from qtpy.QtWidgets import QWidget, QPushButton, QHBoxLayout, QVBoxLayout\n'), ((1207, 1220), 'qtpy.QtWidgets.QPushButton', 'QPushButton', ([], {}), '()\n', (1218, 1220), False, 'from qtpy.QtWidgets import QWidget, QPushButton, QHBoxLayout, QVBoxLayout\n'), ((1384, 1397), 'qtpy.QtWidgets.QPushButton', 'QPushButton', ([], {}), '()\n', (1395, 1397), False, 'from qtpy.QtWidgets import QWidget, QPushButton, QHBoxLayout, QVBoxLayout\n'), ((1573, 1586), 'qtpy.QtWidgets.QPushButton', 'QPushButton', ([], {}), '()\n', (1584, 1586), False, 'from qtpy.QtWidgets import QWidget, QPushButton, QHBoxLayout, QVBoxLayout\n'), ((1746, 1759), 'qtpy.QtWidgets.QHBoxLayout', 'QHBoxLayout', ([], {}), '()\n', (1757, 1759), False, 'from qtpy.QtWidgets import QWidget, QPushButton, QHBoxLayout, QVBoxLayout\n'), ((1989, 1998), 'qtpy.QtWidgets.QWidget', 'QWidget', ([], {}), '()\n', (1996, 1998), False, 'from qtpy.QtWidgets import QWidget, QPushButton, QHBoxLayout, QVBoxLayout\n')] |
import launch
import launch_ros
def generate_launch_description():
server_node_container = launch_ros.actions.ComposableNodeContainer(
node_name='server_node_container',
node_namespace='',
package='rclcpp_components',
node_executable='component_container',
composable_node_descriptions=[
launch_ros.descriptions.ComposableNode(
package='hello_world_cpp',
node_plugin='hello_world_cpp::Server',
node_name='server'
)
],
output='screen'
)
return launch.LaunchDescription([server_node_container])
| [
"launch.LaunchDescription",
"launch_ros.descriptions.ComposableNode"
] | [((649, 698), 'launch.LaunchDescription', 'launch.LaunchDescription', (['[server_node_container]'], {}), '([server_node_container])\n', (673, 698), False, 'import launch\n'), ((370, 498), 'launch_ros.descriptions.ComposableNode', 'launch_ros.descriptions.ComposableNode', ([], {'package': '"""hello_world_cpp"""', 'node_plugin': '"""hello_world_cpp::Server"""', 'node_name': '"""server"""'}), "(package='hello_world_cpp',\n node_plugin='hello_world_cpp::Server', node_name='server')\n", (408, 498), False, 'import launch_ros\n')] |