code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
r"""
===============================================================================
pore_topology -- functions for monitoring and adjusting topology
===============================================================================
"""
import scipy as _sp
def get_subscripts(network, shape, **kwargs):
r"""
Return the 3D subscripts (i,j,k) into the cubic network
Parameters
----------
shape : list
The (i,j,k) shape of the network in number of pores in each direction
"""
if network.num_pores('internal') != _sp.prod(shape):
print('Supplied shape does not match Network size, cannot proceed')
else:
template = _sp.atleast_3d(_sp.empty(shape))
a = _sp.indices(_sp.shape(template))
i = a[0].flatten()
j = a[1].flatten()
k = a[2].flatten()
ind = _sp.vstack((i, j, k)).T
vals = _sp.ones((network.Np, 3))*_sp.nan
vals[network.pores('internal')] = ind
return vals
def adjust_spacing(network, new_spacing, **kwargs):
r"""
Adjust the the pore-to-pore lattice spacing on a cubic network
Parameters
----------
new_spacing : float
The new lattice spacing to apply
Notes
-----
At present this method only applies a uniform spacing in all directions.
This is a limiation of OpenPNM Cubic Networks in general, and not of the
method.
"""
coords = network['pore.coords']
try:
spacing = network._spacing
coords = coords/spacing*new_spacing
network._spacing = new_spacing
except:
pass
return coords
def reduce_coordination(network, z, mode='random', **kwargs):
r"""
Reduce the coordination number to the specified z value
Parameters
----------
z : int
The coordination number or number of throats connected a pore
mode : string, optional
Controls the logic used to trim connections. Options are:
- 'random': (default) Throats will be randomly removed to achieve a
coordination of z
- 'max': All pores will be adjusted to have a maximum coordination of z
(not implemented yet)
Returns
-------
A label array indicating which throats should be trimmed to achieve desired
coordination.
Notes
-----
Pores with only 1 throat will be ignored in all calculations since these
are generally boundary pores.
"""
T_trim = ~network['throat.all']
T_nums = network.num_neighbors(network.pores())
# Find protected throats
T_keep = network.find_neighbor_throats(pores=(T_nums == 1))
if mode == 'random':
z_ave = _sp.average(T_nums[T_nums > 1])
f_trim = (z_ave - z)/z_ave
T_trim = _sp.rand(network.Nt) < f_trim
T_trim = T_trim*(~network.tomask(throats=T_keep))
if mode == 'max':
pass
return T_trim
| [
"scipy.prod",
"scipy.ones",
"scipy.empty",
"scipy.vstack",
"scipy.average",
"scipy.rand",
"scipy.shape"
] | [((547, 562), 'scipy.prod', '_sp.prod', (['shape'], {}), '(shape)\n', (555, 562), True, 'import scipy as _sp\n'), ((2670, 2701), 'scipy.average', '_sp.average', (['T_nums[T_nums > 1]'], {}), '(T_nums[T_nums > 1])\n', (2681, 2701), True, 'import scipy as _sp\n'), ((684, 700), 'scipy.empty', '_sp.empty', (['shape'], {}), '(shape)\n', (693, 700), True, 'import scipy as _sp\n'), ((726, 745), 'scipy.shape', '_sp.shape', (['template'], {}), '(template)\n', (735, 745), True, 'import scipy as _sp\n'), ((842, 863), 'scipy.vstack', '_sp.vstack', (['(i, j, k)'], {}), '((i, j, k))\n', (852, 863), True, 'import scipy as _sp\n'), ((881, 906), 'scipy.ones', '_sp.ones', (['(network.Np, 3)'], {}), '((network.Np, 3))\n', (889, 906), True, 'import scipy as _sp\n'), ((2754, 2774), 'scipy.rand', '_sp.rand', (['network.Nt'], {}), '(network.Nt)\n', (2762, 2774), True, 'import scipy as _sp\n')] |
# Copyright (C) 2007 <NAME>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
from SpiffWorkflow.Task import Task
from SpiffWorkflow.Exception import WorkflowException
from SpiffWorkflow.Operators import valueof
from TaskSpec import TaskSpec
class Join(TaskSpec):
"""
A task for synchronizing branches that were previously split using a
conditional task, such as MultiChoice. It has two or more incoming
branches and one or more outputs.
"""
def __init__(self, parent, name, split_task = None, **kwargs):
"""
Constructor.
@type parent: Workflow
@param parent: A reference to the parent (usually a workflow).
@type name: string
@param name: A name for the task.
@type split_task: TaskSpec
@param split_task: The task that was previously used to split the
branch.
@type kwargs: dict
@param kwargs: The following options are supported:
- threshold: Specifies how many incoming branches need
to complete before the task triggers.
When the limit is reached, the task fires but still
expects all other branches to complete.
You may also pass an attribute, in which case the
value is determined at runtime.
- cancel: When True, any remaining incoming branches
are cancelled as soon as the discriminator is activated.
The default is False.
"""
TaskSpec.__init__(self, parent, name, **kwargs)
self.split_task = split_task
self.threshold = kwargs.get('threshold', None)
self.cancel_remaining = kwargs.get('cancel', False)
def _branch_is_complete(self, my_task):
# Determine whether that branch is now completed by checking whether
# it has any waiting items other than myself in it.
skip = None
for task in Task.Iterator(my_task, my_task.NOT_FINISHED_MASK):
# If the current task is a child of myself, ignore it.
if skip is not None and task._is_descendant_of(skip):
continue
if task.spec == self:
skip = task
continue
return False
return True
def _branch_may_merge_at(self, task):
for child in task:
# Ignore tasks that were created by a trigger.
if child._has_state(Task.TRIGGERED):
continue
# Merge found.
if child.spec == self:
return True
# If the task is predicted with less outputs than he has
# children, that means the prediction may be incomplete (for
# example, because a prediction is not yet possible at this time).
if not child._is_definite() \
and len(child.spec.outputs) > len(child.children):
return True
return False
def _fire(self, my_task, waiting_tasks):
"""
Fire, and cancel remaining tasks, if so requested.
"""
# If this is a cancelling join, cancel all incoming branches,
# except for the one that just completed.
if self.cancel_remaining:
for task in waiting_tasks:
task.cancel()
def _try_fire_unstructured(self, my_task, force = False):
# If the threshold was already reached, there is nothing else to do.
if my_task._has_state(Task.COMPLETED):
return False
if my_task._has_state(Task.READY):
return True
# The default threshold is the number of inputs.
threshold = valueof(my_task, self.threshold)
if threshold is None:
threshold = len(self.inputs)
# Look at the tree to find all places where this task is used.
tasks = []
for input in self.inputs:
for task in my_task.job.task_tree:
if task.thread_id != my_task.thread_id:
continue
if task.spec != input:
continue
tasks.append(task)
# Look up which tasks have already completed.
waiting_tasks = []
completed = 0
for task in tasks:
if task.parent is None or task._has_state(Task.COMPLETED):
completed += 1
else:
waiting_tasks.append(task)
# If the threshold was reached, get ready to fire.
if force or completed >= threshold:
self._fire(my_task, waiting_tasks)
return True
# We do NOT set the task state to COMPLETED, because in
# case all other incoming tasks get cancelled (or never reach
# the Join for other reasons, such as reaching a stub branch), we
# we need to revisit it.
return False
def _try_fire_structured(self, my_task, force = False):
# If the threshold was already reached, there is nothing else to do.
if my_task._has_state(Task.READY):
return True
if my_task._has_state(Task.COMPLETED):
return False
# Retrieve a list of all activated tasks from the associated
# task that did the conditional parallel split.
split_task = my_task._find_ancestor_from_name(self.split_task)
if split_task is None:
msg = 'Join with %s, which was not reached' % self.split_task
raise WorkflowException(self, msg)
tasks = split_task.spec._get_activated_tasks(split_task, my_task)
# The default threshold is the number of branches that were started.
threshold = valueof(my_task, self.threshold)
if threshold is None:
threshold = len(tasks)
# Look up which tasks have already completed.
waiting_tasks = []
completed = 0
for task in tasks:
# Refresh path prediction.
task.spec._predict(task)
if not self._branch_may_merge_at(task):
completed += 1
elif self._branch_is_complete(task):
completed += 1
else:
waiting_tasks.append(task)
# If the threshold was reached, get ready to fire.
if force or completed >= threshold:
self._fire(my_task, waiting_tasks)
return True
# We do NOT set the task state to COMPLETED, because in
# case all other incoming tasks get cancelled (or never reach
# the Join for other reasons, such as reaching a stub branch), we
# need to revisit it.
return False
def try_fire(self, my_task, force = False):
if self.split_task is None:
return self._try_fire_unstructured(my_task, force)
return self._try_fire_structured(my_task, force)
def _do_join(self, my_task):
if self.split_task:
split_task = my_task.job.get_task_from_name(self.split_task)
split_task = my_task._find_ancestor(split_task)
else:
split_task = my_task.job.task_tree
# Find the inbound node that was completed last.
last_changed = None
thread_tasks = []
for task in split_task._find_any(self):
if task.thread_id != my_task.thread_id:
continue
if self.split_task and task._is_descendant_of(my_task):
continue
changed = task.parent.last_state_change
if last_changed is None \
or changed > last_changed.parent.last_state_change:
last_changed = task
thread_tasks.append(task)
# Mark all nodes in this thread that reference this task as
# completed, except for the first one, which should be READY.
for task in thread_tasks:
if task == last_changed:
self.signal_emit('entered', my_task.job, my_task)
task._ready()
else:
task.state = Task.COMPLETED
task._drop_children()
return False
def _on_trigger(self, my_task):
"""
May be called to fire the Join before the incoming branches are
completed.
"""
for task in my_task.job.task_tree._find_any(self):
if task.thread_id != my_task.thread_id:
continue
return self._do_join(task)
def _update_state_hook(self, my_task):
if not self.try_fire(my_task):
my_task.state = Task.WAITING
return False
return self._do_join(my_task)
def _on_complete_hook(self, my_task):
"""
Runs the task. Should not be called directly.
Returns True if completed, False otherwise.
"""
return TaskSpec._on_complete_hook(self, my_task)
| [
"SpiffWorkflow.Operators.valueof",
"TaskSpec.TaskSpec.__init__",
"SpiffWorkflow.Task.Task.Iterator",
"TaskSpec.TaskSpec._on_complete_hook",
"SpiffWorkflow.Exception.WorkflowException"
] | [((2222, 2269), 'TaskSpec.TaskSpec.__init__', 'TaskSpec.__init__', (['self', 'parent', 'name'], {}), '(self, parent, name, **kwargs)\n', (2239, 2269), False, 'from TaskSpec import TaskSpec\n'), ((2662, 2711), 'SpiffWorkflow.Task.Task.Iterator', 'Task.Iterator', (['my_task', 'my_task.NOT_FINISHED_MASK'], {}), '(my_task, my_task.NOT_FINISHED_MASK)\n', (2675, 2711), False, 'from SpiffWorkflow.Task import Task\n'), ((4387, 4419), 'SpiffWorkflow.Operators.valueof', 'valueof', (['my_task', 'self.threshold'], {}), '(my_task, self.threshold)\n', (4394, 4419), False, 'from SpiffWorkflow.Operators import valueof\n'), ((6386, 6418), 'SpiffWorkflow.Operators.valueof', 'valueof', (['my_task', 'self.threshold'], {}), '(my_task, self.threshold)\n', (6393, 6418), False, 'from SpiffWorkflow.Operators import valueof\n'), ((9511, 9552), 'TaskSpec.TaskSpec._on_complete_hook', 'TaskSpec._on_complete_hook', (['self', 'my_task'], {}), '(self, my_task)\n', (9537, 9552), False, 'from TaskSpec import TaskSpec\n'), ((6185, 6213), 'SpiffWorkflow.Exception.WorkflowException', 'WorkflowException', (['self', 'msg'], {}), '(self, msg)\n', (6202, 6213), False, 'from SpiffWorkflow.Exception import WorkflowException\n')] |
import os
import math
from pathlib import Path
import clip
import torch
from PIL import Image
import numpy as np
import pandas as pd
from common import common_path
# Set the path to the photos
# dataset_version = "lite" # Use "lite" or "full"
# photos_path = Path("unsplash-dataset") / dataset_version / "photos"
photos_path = os.path.join(common_path.project_dir, 'unsplash-dataset/lite/photos')
# List all JPGs in the folder
photos_files = list(Path(photos_path).glob("*.jpg"))
# Print some statistics
print(f"Photos found: {len(photos_files)}")
# Load the open CLIP model
device = "cuda" if torch.cuda.is_available() else "cpu"
model, preprocess = clip.load("ViT-B/32", device=device)
# Function that computes the feature vectors for a batch of images
def compute_clip_features(photos_batch):
# Load all the photos from the files
photos = [Image.open(photo_file) for photo_file in photos_batch]
# Preprocess all photos
photos_preprocessed = torch.stack([preprocess(photo) for photo in photos]).to(device)
with torch.no_grad():
# Encode the photos batch to compute the feature vectors and normalize them
photos_features = model.encode_image(photos_preprocessed)
photos_features /= photos_features.norm(dim=-1, keepdim=True)
# Transfer the feature vectors back to the CPU and convert to numpy
return photos_features.cpu().numpy()
# Define the batch size so that it fits on your GPU. You can also do the processing on the CPU, but it will be slower.
batch_size = 16
# Path where the feature vectors will be stored
features_path = os.path.join(common_path.project_dir, 'unsplash-dataset/lite/features')
# Compute how many batches are needed
batches = math.ceil(len(photos_files) / batch_size)
# Process each batch
for i in range(batches):
print(f"Processing batch {i + 1}/{batches}")
batch_ids_path = os.path.join(features_path, f"{i:010d}.csv")
batch_features_path = os.path.join(features_path, f"{i:010d}.npy")
# Only do the processing if the batch wasn't processed yet
if not os.path.exists(batch_features_path):
try:
# Select the photos for the current batch
batch_files = photos_files[i * batch_size: (i + 1) * batch_size]
# Compute the features and save to a numpy file
batch_features = compute_clip_features(batch_files)
np.save(batch_features_path, batch_features)
# Save the photo IDs to a CSV file
photo_ids = [photo_file.name.split(".")[0] for photo_file in batch_files]
photo_ids_data = pd.DataFrame(photo_ids, columns=['photo_id'])
photo_ids_data.to_csv(batch_ids_path, index=False)
except:
# Catch problems with the processing to make the process more robust
print(f'Problem with batch {i}')
# Load all numpy files
features_list = [np.load(features_file) for features_file in sorted(Path(features_path).glob("*.npy"))]
# Concatenate the features and store in a merged file
features = np.concatenate(features_list)
np.save(os.path.join(features_path, "features.npy"), features)
# Load all the photo IDs
photo_ids = pd.concat([pd.read_csv(ids_file) for ids_file in sorted(Path(features_path).glob("*.csv"))])
photo_ids.to_csv(os.path.join(features_path, "photo_ids.csv"), index=False)
| [
"os.path.exists",
"PIL.Image.open",
"pandas.read_csv",
"pathlib.Path",
"os.path.join",
"torch.cuda.is_available",
"numpy.concatenate",
"clip.load",
"pandas.DataFrame",
"torch.no_grad",
"numpy.load",
"numpy.save"
] | [((332, 401), 'os.path.join', 'os.path.join', (['common_path.project_dir', '"""unsplash-dataset/lite/photos"""'], {}), "(common_path.project_dir, 'unsplash-dataset/lite/photos')\n", (344, 401), False, 'import os\n'), ((659, 695), 'clip.load', 'clip.load', (['"""ViT-B/32"""'], {'device': 'device'}), "('ViT-B/32', device=device)\n", (668, 695), False, 'import clip\n'), ((1598, 1669), 'os.path.join', 'os.path.join', (['common_path.project_dir', '"""unsplash-dataset/lite/features"""'], {}), "(common_path.project_dir, 'unsplash-dataset/lite/features')\n", (1610, 1669), False, 'import os\n'), ((3041, 3070), 'numpy.concatenate', 'np.concatenate', (['features_list'], {}), '(features_list)\n', (3055, 3070), True, 'import numpy as np\n'), ((602, 627), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (625, 627), False, 'import torch\n'), ((1879, 1923), 'os.path.join', 'os.path.join', (['features_path', 'f"""{i:010d}.csv"""'], {}), "(features_path, f'{i:010d}.csv')\n", (1891, 1923), False, 'import os\n'), ((1950, 1994), 'os.path.join', 'os.path.join', (['features_path', 'f"""{i:010d}.npy"""'], {}), "(features_path, f'{i:010d}.npy')\n", (1962, 1994), False, 'import os\n'), ((2888, 2910), 'numpy.load', 'np.load', (['features_file'], {}), '(features_file)\n', (2895, 2910), True, 'import numpy as np\n'), ((3079, 3122), 'os.path.join', 'os.path.join', (['features_path', '"""features.npy"""'], {}), "(features_path, 'features.npy')\n", (3091, 3122), False, 'import os\n'), ((3282, 3326), 'os.path.join', 'os.path.join', (['features_path', '"""photo_ids.csv"""'], {}), "(features_path, 'photo_ids.csv')\n", (3294, 3326), False, 'import os\n'), ((861, 883), 'PIL.Image.open', 'Image.open', (['photo_file'], {}), '(photo_file)\n', (871, 883), False, 'from PIL import Image\n'), ((1045, 1060), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1058, 1060), False, 'import torch\n'), ((2070, 2105), 'os.path.exists', 'os.path.exists', (['batch_features_path'], {}), '(batch_features_path)\n', (2084, 2105), False, 'import os\n'), ((3183, 3204), 'pandas.read_csv', 'pd.read_csv', (['ids_file'], {}), '(ids_file)\n', (3194, 3204), True, 'import pandas as pd\n'), ((453, 470), 'pathlib.Path', 'Path', (['photos_path'], {}), '(photos_path)\n', (457, 470), False, 'from pathlib import Path\n'), ((2388, 2432), 'numpy.save', 'np.save', (['batch_features_path', 'batch_features'], {}), '(batch_features_path, batch_features)\n', (2395, 2432), True, 'import numpy as np\n'), ((2596, 2641), 'pandas.DataFrame', 'pd.DataFrame', (['photo_ids'], {'columns': "['photo_id']"}), "(photo_ids, columns=['photo_id'])\n", (2608, 2641), True, 'import pandas as pd\n'), ((2939, 2958), 'pathlib.Path', 'Path', (['features_path'], {}), '(features_path)\n', (2943, 2958), False, 'from pathlib import Path\n'), ((3228, 3247), 'pathlib.Path', 'Path', (['features_path'], {}), '(features_path)\n', (3232, 3247), False, 'from pathlib import Path\n')] |
import numpy as np
import datajoint as dj
from treadmill_pipeline import project_database_prefix
from ephys.utilities import ingestion, time_sync
from ephys import get_schema_name
schema = dj.schema(project_database_prefix + 'treadmill_pipeline')
reference = dj.create_virtual_module('reference', get_schema_name('reference'))
acquisition = dj.create_virtual_module('acquisition', get_schema_name('acquisition'))
behavior = dj.create_virtual_module('behavior', get_schema_name('behavior'))
@schema
class TreadmillTracking(dj.Imported):
definition = """ # session-level tracking data from the treadmill_pipeline(s) employed in the experiment
-> acquisition.Session
treadmill_tracking_time: datetime # start time of this treadmill_pipeline speed recording
---
treadmill_tracking_name: varchar(40) # user-assign name of this treadmill_pipeline tracking (e.g. 27032019laserSess1)
treadmill_timestamps: blob@ephys_store # (s) timestamps of the treadmill_pipeline speed samples
"""
class TreadmillSync(dj.Part):
definition = """
-> master
---
sync_master_clock: varchar(128) # name of the sync-master
track_sync_data=null: blob@ephys_store # sync data (binary)
track_time_zero=null: float # (s) the first time point of this tracking
track_sync_timestamps=null: blob@ephys_store # (s) timestamps of sync data in tracking clock
track_sync_master_timestamps=null: blob@ephys_store # (s) timestamps of sync data in master clock
"""
class Speed(dj.Part):
definition = """
-> master
treadmill_name: varchar(32)
---
treadmill_speed: blob@ephys_store # (s) treadmill_pipeline speed at each timestamp
"""
key_source = acquisition.Session & acquisition.Recording # wait for recording to be ingested first before tracking
def make(self, key):
input_dir = ingestion.find_input_directory(key)
if not input_dir:
print(f'{input_dir} not found in this machine, skipping...')
return
rec_type, recordings = ingestion.get_recordings(input_dir)
if rec_type in ('neuropixels', 'neurologger'): # if 'neuropixels' recording, check for OptiTrack's `motive` or `.csv`
opti_list = ingestion.get_optitrack(input_dir)
if not opti_list:
raise FileNotFoundError('No OptiTrack "matmot.mtv" or ".csv" found')
for opti in opti_list:
if 'Format Version' not in opti.meta:
raise NotImplementedError('Treadmill data ingest from type other than "optitrack.csv" not implemented')
secondary_data = opti.secondary_data
if 'Treadmill' not in secondary_data:
raise KeyError('No "Treadmill" found in the secondary data of optitrack.csv')
treadmill_key = dict(key, treadmill_tracking_time=opti.recording_time)
self.insert1(dict(treadmill_key,
treadmill_tracking_name=opti.tracking_name, # name of the session folder
treadmill_timestamps=secondary_data['t']))
if hasattr(opti, 'sync_data'):
self.TreadmillSync.insert1(dict(treadmill_key,
sync_master_clock=opti.sync_data['master_name'],
track_time_zero=secondary_data['t'][0],
track_sync_timestamps=opti.sync_data['slave'],
track_sync_master_timestamps=opti.sync_data['master']))
else: # data presynced with tracking-recording pair,
# still need for a linear shift from session start to the recording this tracking is synced to
self.TrackingSync.insert1(time_sync.create_tracking_sync_data(
treadmill_key, np.array([secondary_data['t'][0], secondary_data['t'][-1]])))
self.Speed.insert1([dict(treadmill_key, treadmill_name=k, treadmill_speed=v['speed'])
for k, v in secondary_data['Treadmill'].items()])
print(f'Insert {len(opti_list)} treadmill_pipeline tracking(s): {input_dir.stem}')
else:
raise NotImplementedError(f'Treadmill Tracking ingestion for recording type {rec_type} not implemented')
| [
"ephys.utilities.ingestion.find_input_directory",
"ephys.utilities.ingestion.get_optitrack",
"numpy.array",
"ephys.utilities.ingestion.get_recordings",
"datajoint.schema",
"ephys.get_schema_name"
] | [((192, 249), 'datajoint.schema', 'dj.schema', (["(project_database_prefix + 'treadmill_pipeline')"], {}), "(project_database_prefix + 'treadmill_pipeline')\n", (201, 249), True, 'import datajoint as dj\n'), ((301, 329), 'ephys.get_schema_name', 'get_schema_name', (['"""reference"""'], {}), "('reference')\n", (316, 329), False, 'from ephys import get_schema_name\n'), ((385, 415), 'ephys.get_schema_name', 'get_schema_name', (['"""acquisition"""'], {}), "('acquisition')\n", (400, 415), False, 'from ephys import get_schema_name\n'), ((465, 492), 'ephys.get_schema_name', 'get_schema_name', (['"""behavior"""'], {}), "('behavior')\n", (480, 492), False, 'from ephys import get_schema_name\n'), ((2041, 2076), 'ephys.utilities.ingestion.find_input_directory', 'ingestion.find_input_directory', (['key'], {}), '(key)\n', (2071, 2076), False, 'from ephys.utilities import ingestion, time_sync\n'), ((2227, 2262), 'ephys.utilities.ingestion.get_recordings', 'ingestion.get_recordings', (['input_dir'], {}), '(input_dir)\n', (2251, 2262), False, 'from ephys.utilities import ingestion, time_sync\n'), ((2415, 2449), 'ephys.utilities.ingestion.get_optitrack', 'ingestion.get_optitrack', (['input_dir'], {}), '(input_dir)\n', (2438, 2449), False, 'from ephys.utilities import ingestion, time_sync\n'), ((4133, 4192), 'numpy.array', 'np.array', (["[secondary_data['t'][0], secondary_data['t'][-1]]"], {}), "([secondary_data['t'][0], secondary_data['t'][-1]])\n", (4141, 4192), True, 'import numpy as np\n')] |
from rest_framework import serializers
from management.models.main import MailSetting, LdapSetting, ShopSetting, LegalSetting, Header, CacheSetting, Footer
class MailSettingSerializer(serializers.ModelSerializer):
id = serializers.ReadOnlyField()
class Meta:
model = MailSetting
fields = '__all__'
class LdapSettingSerializer(serializers.ModelSerializer):
id = serializers.ReadOnlyField()
class Meta:
model = LdapSetting
fields = '__all__'
class ShopSettingSerializer(serializers.ModelSerializer):
id = serializers.ReadOnlyField()
class Meta:
model = ShopSetting
fields = '__all__'
class LegalSettingSerializer(serializers.ModelSerializer):
id = serializers.ReadOnlyField()
class Meta:
model = LegalSetting
fields = '__all__'
class HeaderSerializer(serializers.ModelSerializer):
id = serializers.ReadOnlyField()
class Meta:
model = Header
fields = '__all__'
class FooterSerializer(serializers.ModelSerializer):
id = serializers.ReadOnlyField()
class Meta:
model = Footer
fields = '__all__'
class CacheSettingSerializer(serializers.ModelSerializer):
id = serializers.ReadOnlyField()
class Meta:
model = CacheSetting
fields = '__all__'
| [
"rest_framework.serializers.ReadOnlyField"
] | [((226, 253), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {}), '()\n', (251, 253), False, 'from rest_framework import serializers\n'), ((395, 422), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {}), '()\n', (420, 422), False, 'from rest_framework import serializers\n'), ((564, 591), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {}), '()\n', (589, 591), False, 'from rest_framework import serializers\n'), ((734, 761), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {}), '()\n', (759, 761), False, 'from rest_framework import serializers\n'), ((899, 926), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {}), '()\n', (924, 926), False, 'from rest_framework import serializers\n'), ((1058, 1085), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {}), '()\n', (1083, 1085), False, 'from rest_framework import serializers\n'), ((1223, 1250), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {}), '()\n', (1248, 1250), False, 'from rest_framework import serializers\n')] |
"""Unit test optimal lineup functions."""
import unittest
import copy
import ff_espn_api # pylint: disable=import-error
from collections import defaultdict
from fantasy_coty.main import add_to_optimal
class TestAddToOptimal(unittest.TestCase):
"""Test add_to_optimal() function."""
def setUp(self):
"""Set up settings and optimal objects for each function."""
self.settings = defaultdict(int)
self.settings["QB"] = 1
self.settings["RB"] = 2
self.settings["WR"] = 2
self.settings["TE"] = 1
self.settings["RB/WR/TE"] = 1
self.settings["D/ST"] = 1
self.settings["K"] = 1
self.optimal = defaultdict(list)
self.flex = "RB/WR/TE"
# all of this is garbage in order to create a default BoxPlayer that we can modify
data = {}
data["proTeamId"] = 1
data["player"] = {}
data["player"]["proTeamId"] = 1
data["player"]["stats"] = []
pro_schedule = {}
pos_rankings = {}
week = 0
self.default_players = {}
self.default_players["QB"] = ff_espn_api.BoxPlayer(data, pro_schedule, pos_rankings, week)
self.default_players["QB"].eligibleSlots = ["QB", "OP", "BE", "IR"]
self.default_players["QB"].position = "QB"
self.default_players["RB"] = ff_espn_api.BoxPlayer(data, pro_schedule, pos_rankings, week)
self.default_players["RB"].eligibleSlots = [
"RB",
"RB/WR",
"RB/WR/TE",
"OP",
"BE",
"IR",
]
self.default_players["RB"].position = "RB"
self.default_players["WR"] = ff_espn_api.BoxPlayer(data, pro_schedule, pos_rankings, week)
self.default_players["WR"].eligibleSlots = [
"RB/WR",
"WR",
"WR/TE",
"RB/WR/TE",
"OP",
"BE",
"IR",
]
self.default_players["WR"].position = "WR"
self.default_players["TE"] = ff_espn_api.BoxPlayer(data, pro_schedule, pos_rankings, week)
self.default_players["TE"].eligibleSlots = [
"WR/TE",
"TE",
"RB/WR/TE",
"OP",
"BE",
"IR",
]
self.default_players["TE"].position = "TE"
self.default_players["D/ST"] = ff_espn_api.BoxPlayer(data, pro_schedule, pos_rankings, week)
self.default_players["D/ST"].eligibleSlots = ["D/ST", "BE", "IR"]
self.default_players["D/ST"].position = "D/ST"
self.default_players["K"] = ff_espn_api.BoxPlayer(data, pro_schedule, pos_rankings, week)
self.default_players["K"].eligibleSlots = ["K", "BE", "IR"]
self.default_players["K"].position = "K"
def test_basic_functionality(self):
"""Test basic functionality of add_to_optimal()."""
# test basic replacement functionality
qb1 = copy.deepcopy(self.default_players["QB"])
qb1.points = 10
self.optimal = add_to_optimal(self.optimal, self.settings, qb1)
self.assertEqual(self.optimal["QB"][0].points, 10)
self.assertEqual(len(self.optimal["QB"]), self.settings["QB"])
qb2 = copy.deepcopy(self.default_players["QB"])
qb2.points = 8
self.optimal = add_to_optimal(self.optimal, self.settings, qb2)
self.assertEqual(self.optimal["QB"][0].points, 10)
self.assertEqual(len(self.optimal["QB"]), self.settings["QB"])
qb3 = copy.deepcopy(self.default_players["QB"])
qb3.points = 12
self.optimal = add_to_optimal(self.optimal, self.settings, qb3)
self.assertEqual(self.optimal["QB"][0].points, 12)
self.assertEqual(len(self.optimal["QB"]), self.settings["QB"])
def test_flex_replacement(self):
"""Test functionality involving of add_to_optimal() involving FLEX."""
rb1 = copy.deepcopy(self.default_players["RB"])
rb1.points = 20
self.optimal = add_to_optimal(self.optimal, self.settings, rb1)
self.assertEqual(self.optimal["RB"][0].points, rb1.points)
self.assertLess(len(self.optimal["RB"]), self.settings["RB"])
rb2 = copy.deepcopy(self.default_players["RB"])
rb2.points = 12
self.optimal = add_to_optimal(self.optimal, self.settings, rb2)
self.assertIn(rb1.points, [x.points for x in self.optimal["RB"]])
self.assertIn(rb2.points, [x.points for x in self.optimal["RB"]])
self.assertEqual(len(self.optimal["RB"]), self.settings["RB"])
# test adding to FLEX when less than the other 2 RBs
rb3 = copy.deepcopy(self.default_players["RB"])
rb3.points = 8
self.optimal = add_to_optimal(self.optimal, self.settings, rb3)
self.assertIn(rb1.points, [x.points for x in self.optimal["RB"]])
self.assertIn(rb2.points, [x.points for x in self.optimal["RB"]])
self.assertEqual(len(self.optimal["RB"]), self.settings["RB"])
self.assertIn(rb3.points, [x.points for x in self.optimal[self.flex]])
self.assertEqual(len(self.optimal[self.flex]), self.settings[self.flex])
# test bumping one RB from RB2 to FLEX
rb4 = copy.deepcopy(self.default_players["RB"])
rb4.points = 16
self.optimal = add_to_optimal(self.optimal, self.settings, rb4)
self.assertIn(rb1.points, [x.points for x in self.optimal["RB"]])
self.assertIn(rb4.points, [x.points for x in self.optimal["RB"]])
self.assertEqual(len(self.optimal["RB"]), self.settings["RB"])
self.assertIn(rb2.points, [x.points for x in self.optimal[self.flex]])
self.assertEqual(len(self.optimal[self.flex]), self.settings[self.flex])
# test putting something straight away in flex
rb5 = copy.deepcopy(self.default_players["RB"])
rb5.points = 14
self.optimal = add_to_optimal(self.optimal, self.settings, rb5)
self.assertIn(rb1.points, [x.points for x in self.optimal["RB"]])
self.assertIn(rb4.points, [x.points for x in self.optimal["RB"]])
self.assertEqual(len(self.optimal["RB"]), self.settings["RB"])
self.assertIn(rb5.points, [x.points for x in self.optimal[self.flex]])
self.assertEqual(len(self.optimal[self.flex]), self.settings[self.flex])
# test putting in low WRs with flex spot full
wr1 = copy.deepcopy(self.default_players["WR"])
wr1.points = 5
self.optimal = add_to_optimal(self.optimal, self.settings, wr1)
self.assertIn(wr1.points, [x.points for x in self.optimal["WR"]])
self.assertLess(len(self.optimal["WR"]), self.settings["WR"])
wr2 = copy.deepcopy(self.default_players["WR"])
wr2.points = 7
self.optimal = add_to_optimal(self.optimal, self.settings, wr2)
self.assertIn(wr1.points, [x.points for x in self.optimal["WR"]])
self.assertIn(wr2.points, [x.points for x in self.optimal["WR"]])
self.assertEqual(len(self.optimal["WR"]), self.settings["WR"])
# test putting in a very high WR, shouldn't bump anything to FLEX
wr3 = copy.deepcopy(self.default_players["WR"])
wr3.points = 30
self.optimal = add_to_optimal(self.optimal, self.settings, wr3)
self.assertIn(wr3.points, [x.points for x in self.optimal["WR"]])
self.assertIn(wr2.points, [x.points for x in self.optimal["WR"]])
self.assertEqual(len(self.optimal["WR"]), self.settings["WR"])
self.assertIn(rb5.points, [x.points for x in self.optimal[self.flex]])
self.assertEqual(len(self.optimal[self.flex]), self.settings[self.flex])
# two more receivers, the second one should bump something to FLEX
wr4 = copy.deepcopy(self.default_players["WR"])
wr4.points = 28
self.optimal = add_to_optimal(self.optimal, self.settings, wr4)
self.assertIn(wr3.points, [x.points for x in self.optimal["WR"]])
self.assertIn(wr4.points, [x.points for x in self.optimal["WR"]])
self.assertEqual(len(self.optimal["WR"]), self.settings["WR"])
self.assertIn(rb5.points, [x.points for x in self.optimal[self.flex]])
self.assertEqual(len(self.optimal[self.flex]), self.settings[self.flex])
# this should bump WR4 to FLEX
wr5 = copy.deepcopy(self.default_players["WR"])
wr5.points = 29
self.optimal = add_to_optimal(self.optimal, self.settings, wr5)
self.assertIn(wr3.points, [x.points for x in self.optimal["WR"]])
self.assertIn(wr5.points, [x.points for x in self.optimal["WR"]])
self.assertEqual(len(self.optimal["WR"]), self.settings["WR"])
self.assertIn(wr4.points, [x.points for x in self.optimal[self.flex]])
self.assertEqual(len(self.optimal[self.flex]), self.settings[self.flex])
# finally, this should go directly in FLEX
wr6 = copy.deepcopy(self.default_players["WR"])
wr6.points = 28.5
self.optimal = add_to_optimal(self.optimal, self.settings, wr6)
self.assertIn(wr3.points, [x.points for x in self.optimal["WR"]])
self.assertIn(wr5.points, [x.points for x in self.optimal["WR"]])
self.assertEqual(len(self.optimal["WR"]), self.settings["WR"])
self.assertIn(wr6.points, [x.points for x in self.optimal[self.flex]])
self.assertEqual(len(self.optimal[self.flex]), self.settings[self.flex])
def test_negative_player(self):
"""Make sure negative-scoring players aren't optimal, no matter what."""
d1 = copy.deepcopy(self.default_players["D/ST"])
d1.points = -0.1
self.optimal = add_to_optimal(self.optimal, self.settings, d1)
self.assertNotIn(d1.points, [x.points for x in self.optimal["D/ST"]])
self.assertLess(len(self.optimal["D/ST"]), self.settings["D/ST"])
if __name__ == "__main__":
unittest.main()
| [
"fantasy_coty.main.add_to_optimal",
"collections.defaultdict",
"ff_espn_api.BoxPlayer",
"copy.deepcopy",
"unittest.main"
] | [((9838, 9853), 'unittest.main', 'unittest.main', ([], {}), '()\n', (9851, 9853), False, 'import unittest\n'), ((404, 420), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (415, 420), False, 'from collections import defaultdict\n'), ((676, 693), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (687, 693), False, 'from collections import defaultdict\n'), ((1111, 1172), 'ff_espn_api.BoxPlayer', 'ff_espn_api.BoxPlayer', (['data', 'pro_schedule', 'pos_rankings', 'week'], {}), '(data, pro_schedule, pos_rankings, week)\n', (1132, 1172), False, 'import ff_espn_api\n'), ((1338, 1399), 'ff_espn_api.BoxPlayer', 'ff_espn_api.BoxPlayer', (['data', 'pro_schedule', 'pos_rankings', 'week'], {}), '(data, pro_schedule, pos_rankings, week)\n', (1359, 1399), False, 'import ff_espn_api\n'), ((1669, 1730), 'ff_espn_api.BoxPlayer', 'ff_espn_api.BoxPlayer', (['data', 'pro_schedule', 'pos_rankings', 'week'], {}), '(data, pro_schedule, pos_rankings, week)\n', (1690, 1730), False, 'import ff_espn_api\n'), ((2021, 2082), 'ff_espn_api.BoxPlayer', 'ff_espn_api.BoxPlayer', (['data', 'pro_schedule', 'pos_rankings', 'week'], {}), '(data, pro_schedule, pos_rankings, week)\n', (2042, 2082), False, 'import ff_espn_api\n'), ((2354, 2415), 'ff_espn_api.BoxPlayer', 'ff_espn_api.BoxPlayer', (['data', 'pro_schedule', 'pos_rankings', 'week'], {}), '(data, pro_schedule, pos_rankings, week)\n', (2375, 2415), False, 'import ff_espn_api\n'), ((2582, 2643), 'ff_espn_api.BoxPlayer', 'ff_espn_api.BoxPlayer', (['data', 'pro_schedule', 'pos_rankings', 'week'], {}), '(data, pro_schedule, pos_rankings, week)\n', (2603, 2643), False, 'import ff_espn_api\n'), ((2923, 2964), 'copy.deepcopy', 'copy.deepcopy', (["self.default_players['QB']"], {}), "(self.default_players['QB'])\n", (2936, 2964), False, 'import copy\n'), ((3012, 3060), 'fantasy_coty.main.add_to_optimal', 'add_to_optimal', (['self.optimal', 'self.settings', 'qb1'], {}), '(self.optimal, self.settings, qb1)\n', (3026, 3060), False, 'from fantasy_coty.main import add_to_optimal\n'), ((3206, 3247), 'copy.deepcopy', 'copy.deepcopy', (["self.default_players['QB']"], {}), "(self.default_players['QB'])\n", (3219, 3247), False, 'import copy\n'), ((3294, 3342), 'fantasy_coty.main.add_to_optimal', 'add_to_optimal', (['self.optimal', 'self.settings', 'qb2'], {}), '(self.optimal, self.settings, qb2)\n', (3308, 3342), False, 'from fantasy_coty.main import add_to_optimal\n'), ((3488, 3529), 'copy.deepcopy', 'copy.deepcopy', (["self.default_players['QB']"], {}), "(self.default_players['QB'])\n", (3501, 3529), False, 'import copy\n'), ((3577, 3625), 'fantasy_coty.main.add_to_optimal', 'add_to_optimal', (['self.optimal', 'self.settings', 'qb3'], {}), '(self.optimal, self.settings, qb3)\n', (3591, 3625), False, 'from fantasy_coty.main import add_to_optimal\n'), ((3887, 3928), 'copy.deepcopy', 'copy.deepcopy', (["self.default_players['RB']"], {}), "(self.default_players['RB'])\n", (3900, 3928), False, 'import copy\n'), ((3976, 4024), 'fantasy_coty.main.add_to_optimal', 'add_to_optimal', (['self.optimal', 'self.settings', 'rb1'], {}), '(self.optimal, self.settings, rb1)\n', (3990, 4024), False, 'from fantasy_coty.main import add_to_optimal\n'), ((4177, 4218), 'copy.deepcopy', 'copy.deepcopy', (["self.default_players['RB']"], {}), "(self.default_players['RB'])\n", (4190, 4218), False, 'import copy\n'), ((4266, 4314), 'fantasy_coty.main.add_to_optimal', 'add_to_optimal', (['self.optimal', 'self.settings', 'rb2'], {}), '(self.optimal, self.settings, rb2)\n', (4280, 4314), False, 'from fantasy_coty.main import add_to_optimal\n'), ((4610, 4651), 'copy.deepcopy', 'copy.deepcopy', (["self.default_players['RB']"], {}), "(self.default_players['RB'])\n", (4623, 4651), False, 'import copy\n'), ((4698, 4746), 'fantasy_coty.main.add_to_optimal', 'add_to_optimal', (['self.optimal', 'self.settings', 'rb3'], {}), '(self.optimal, self.settings, rb3)\n', (4712, 4746), False, 'from fantasy_coty.main import add_to_optimal\n'), ((5188, 5229), 'copy.deepcopy', 'copy.deepcopy', (["self.default_players['RB']"], {}), "(self.default_players['RB'])\n", (5201, 5229), False, 'import copy\n'), ((5277, 5325), 'fantasy_coty.main.add_to_optimal', 'add_to_optimal', (['self.optimal', 'self.settings', 'rb4'], {}), '(self.optimal, self.settings, rb4)\n', (5291, 5325), False, 'from fantasy_coty.main import add_to_optimal\n'), ((5775, 5816), 'copy.deepcopy', 'copy.deepcopy', (["self.default_players['RB']"], {}), "(self.default_players['RB'])\n", (5788, 5816), False, 'import copy\n'), ((5864, 5912), 'fantasy_coty.main.add_to_optimal', 'add_to_optimal', (['self.optimal', 'self.settings', 'rb5'], {}), '(self.optimal, self.settings, rb5)\n', (5878, 5912), False, 'from fantasy_coty.main import add_to_optimal\n'), ((6361, 6402), 'copy.deepcopy', 'copy.deepcopy', (["self.default_players['WR']"], {}), "(self.default_players['WR'])\n", (6374, 6402), False, 'import copy\n'), ((6449, 6497), 'fantasy_coty.main.add_to_optimal', 'add_to_optimal', (['self.optimal', 'self.settings', 'wr1'], {}), '(self.optimal, self.settings, wr1)\n', (6463, 6497), False, 'from fantasy_coty.main import add_to_optimal\n'), ((6657, 6698), 'copy.deepcopy', 'copy.deepcopy', (["self.default_players['WR']"], {}), "(self.default_players['WR'])\n", (6670, 6698), False, 'import copy\n'), ((6745, 6793), 'fantasy_coty.main.add_to_optimal', 'add_to_optimal', (['self.optimal', 'self.settings', 'wr2'], {}), '(self.optimal, self.settings, wr2)\n', (6759, 6793), False, 'from fantasy_coty.main import add_to_optimal\n'), ((7102, 7143), 'copy.deepcopy', 'copy.deepcopy', (["self.default_players['WR']"], {}), "(self.default_players['WR'])\n", (7115, 7143), False, 'import copy\n'), ((7191, 7239), 'fantasy_coty.main.add_to_optimal', 'add_to_optimal', (['self.optimal', 'self.settings', 'wr3'], {}), '(self.optimal, self.settings, wr3)\n', (7205, 7239), False, 'from fantasy_coty.main import add_to_optimal\n'), ((7709, 7750), 'copy.deepcopy', 'copy.deepcopy', (["self.default_players['WR']"], {}), "(self.default_players['WR'])\n", (7722, 7750), False, 'import copy\n'), ((7798, 7846), 'fantasy_coty.main.add_to_optimal', 'add_to_optimal', (['self.optimal', 'self.settings', 'wr4'], {}), '(self.optimal, self.settings, wr4)\n', (7812, 7846), False, 'from fantasy_coty.main import add_to_optimal\n'), ((8280, 8321), 'copy.deepcopy', 'copy.deepcopy', (["self.default_players['WR']"], {}), "(self.default_players['WR'])\n", (8293, 8321), False, 'import copy\n'), ((8369, 8417), 'fantasy_coty.main.add_to_optimal', 'add_to_optimal', (['self.optimal', 'self.settings', 'wr5'], {}), '(self.optimal, self.settings, wr5)\n', (8383, 8417), False, 'from fantasy_coty.main import add_to_optimal\n'), ((8863, 8904), 'copy.deepcopy', 'copy.deepcopy', (["self.default_players['WR']"], {}), "(self.default_players['WR'])\n", (8876, 8904), False, 'import copy\n'), ((8954, 9002), 'fantasy_coty.main.add_to_optimal', 'add_to_optimal', (['self.optimal', 'self.settings', 'wr6'], {}), '(self.optimal, self.settings, wr6)\n', (8968, 9002), False, 'from fantasy_coty.main import add_to_optimal\n'), ((9513, 9556), 'copy.deepcopy', 'copy.deepcopy', (["self.default_players['D/ST']"], {}), "(self.default_players['D/ST'])\n", (9526, 9556), False, 'import copy\n'), ((9605, 9652), 'fantasy_coty.main.add_to_optimal', 'add_to_optimal', (['self.optimal', 'self.settings', 'd1'], {}), '(self.optimal, self.settings, d1)\n', (9619, 9652), False, 'from fantasy_coty.main import add_to_optimal\n')] |
from pyspark import SparkConf, SparkContext
from pyspark.sql import SparkSession, functions, types
from pyspark.sql.functions import date_format
from pyspark.sql.functions import year, month, dayofmonth
import sys
import json
import argparse
assert sys.version_info >= (3, 5) # make sure we have Python 3.5+
# add more functions as necessary
def main(posts_inputs, users_inputs,temp_bucket_input,dataset_input):
# main logic starts here
#Hariish - Users and Tags
users = spark.read.parquet(users_inputs)
posts = spark.read.parquet(posts_inputs)
#User and posts join
posts = posts.withColumn("creation_year",year(posts['creation_date']))
res = users.join(posts,(posts['owner_user_id'] == users['id'])).select(users.display_name,users.id,posts.post_id,posts.creation_year,users.location,posts.owner_user_id,posts.post_type_id,posts.accepted_answer_id,posts.tags)
#Active users over years:
res1 = res.groupBy(res['id'],res['display_name'],res['creation_year']).agg(functions.count(res['post_id']).alias('post_count')).orderBy('post_count')
res2 = res1.groupBy(res1['id'],res['display_name']).pivot('creation_year').sum('post_count')
res3 = res2.na.fill(value=0)
res4 = res3.withColumn("overall_posts",res3['2015']+res3['2016']+res3['2017']+res3['2018']+res3['2019']+res3['2020']+res3['2021'])
active_users = res4.orderBy(res4['overall_posts'].desc()).select('id','display_name','2015','2016','2017','2018','2019','2020','2021','overall_posts')
act_id = active_users.limit(10).select('id','display_name')
active_users = active_users.withColumnRenamed('2015','y_2015').withColumnRenamed('2016','y_2016').withColumnRenamed('2017','y_2017').withColumnRenamed('2018','y_2018').withColumnRenamed('2019','y_2019').withColumnRenamed('2020','y_2020').withColumnRenamed('2021','y_2021')
active_users = active_users.limit(10)
a1 = active_users.selectExpr("display_name", "stack(8, 'y_2015', y_2015, 'y_2016', y_2016, 'y_2017', y_2017,'y_2018',y_2018,'y_2019',y_2019,'y_2020',y_2020,'y_2021',y_2021 ,'overall_posts',overall_posts) as (creation_year, values)").where("values is not null")
a1 = a1.select('creation_year','display_name','values')
act_user = a1.groupBy(a1['creation_year']).pivot('display_name').sum('values')
act_user = act_user.withColumnRenamed('<NAME>',"Gordon_Linoff").withColumnRenamed('<NAME>','Nina_Scholz').withColumnRenamed('<NAME>','Ronak_Shah').withColumnRenamed('<NAME>','TJ_Crowder').withColumnRenamed('<NAME>','Tim_Biegeleisen').withColumnRenamed('<NAME>','Wiktor_Stribiżew')
#act_user.show()
#Famous Tags over the year
p1 = posts.withColumn("new",functions.arrays_zip("tags")).withColumn("new", functions.explode("new")).select('post_id',functions.col("new.tags").alias("tags"),'creation_year')
p2 = p1.groupBy(p1['tags'],p1['creation_year']).agg(functions.count(p1['tags']).alias('tag_count'))
p3 = p2.groupBy(p2['tags']).pivot('creation_year').sum('tag_count')
p3 = p3.na.fill(value=0)
p4 = p3.withColumn("overall_tag_usage",p3['2015']+p3['2016']+p3['2017']+p3['2018']+p3['2019']+p3['2020']+p3['2021'])
tag_trends = p4.orderBy(p4['overall_tag_usage'].desc()).select('tags','2015','2016','2017','2018','2019','2020','2021','overall_tag_usage')
tag_trends = tag_trends.withColumnRenamed('2015','y_2015').withColumnRenamed('2016','y_2016').withColumnRenamed('2017','y_2017').withColumnRenamed('2018','y_2018').withColumnRenamed('2019','y_2019').withColumnRenamed('2020','y_2020').withColumnRenamed('2021','y_2021')
tag_trends = tag_trends.limit(10)
t1 = tag_trends.selectExpr("tags", "stack(8, 'y_2015', y_2015, 'y_2016', y_2016, 'y_2017', y_2017,'y_2018',y_2018,'y_2019',y_2019,'y_2020',y_2020,'y_2021',y_2021 ,'overall_tag_usage',overall_tag_usage) as (creation_year, values)").where("values is not null")
t1 = t1.select('creation_year','tags','values')
tag_view = t1.groupBy(t1['creation_year']).pivot('tags').sum('values')
#tag_view.show()
#writing:
act_user.write.mode('overwrite').format('bigquery').option("temporaryGcsBucket",temp_bucket_input).option('table',dataset_input+".active_users").save()
tag_view.write.mode('overwrite').format('bigquery').option("temporaryGcsBucket",temp_bucket_input).option('table',dataset_input+".tag_trends").save()
act_id.write.mode('overwrite').format('bigquery').option("temporaryGcsBucket",temp_bucket_input).option('table',dataset_input+".top10_user_details").save()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-posts_src", action="store", dest="posts_src", type=str)
parser.add_argument("-users_src", action="store", dest="users_src", type=str)
parser.add_argument("-tempbucket_src", action="store", dest="tempbucket_src", type=str)
parser.add_argument("-dataset_src", action="store", dest="dataset_src", type=str)
args = parser.parse_args()
posts_inputs = args.posts_src
users_inputs = args.users_src
temp_bucket_input = args.tempbucket_src
dataset_input = args.dataset_src
spark = SparkSession.builder.appName('Explorer DF').getOrCreate()
assert spark.version >= '3.0' # make sure we have Spark 3.0+
spark.sparkContext.setLogLevel('WARN')
main(posts_inputs, users_inputs,temp_bucket_input,dataset_input) | [
"pyspark.sql.functions.arrays_zip",
"argparse.ArgumentParser",
"pyspark.sql.functions.explode",
"pyspark.sql.functions.col",
"pyspark.sql.functions.year",
"pyspark.sql.SparkSession.builder.appName",
"pyspark.sql.functions.count"
] | [((4544, 4569), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (4567, 4569), False, 'import argparse\n'), ((644, 672), 'pyspark.sql.functions.year', 'year', (["posts['creation_date']"], {}), "(posts['creation_date'])\n", (648, 672), False, 'from pyspark.sql.functions import year, month, dayofmonth\n'), ((5107, 5150), 'pyspark.sql.SparkSession.builder.appName', 'SparkSession.builder.appName', (['"""Explorer DF"""'], {}), "('Explorer DF')\n", (5135, 5150), False, 'from pyspark.sql import SparkSession, functions, types\n'), ((2726, 2750), 'pyspark.sql.functions.explode', 'functions.explode', (['"""new"""'], {}), "('new')\n", (2743, 2750), False, 'from pyspark.sql import SparkSession, functions, types\n'), ((2769, 2794), 'pyspark.sql.functions.col', 'functions.col', (['"""new.tags"""'], {}), "('new.tags')\n", (2782, 2794), False, 'from pyspark.sql import SparkSession, functions, types\n'), ((2882, 2909), 'pyspark.sql.functions.count', 'functions.count', (["p1['tags']"], {}), "(p1['tags'])\n", (2897, 2909), False, 'from pyspark.sql import SparkSession, functions, types\n'), ((1016, 1047), 'pyspark.sql.functions.count', 'functions.count', (["res['post_id']"], {}), "(res['post_id'])\n", (1031, 1047), False, 'from pyspark.sql import SparkSession, functions, types\n'), ((2678, 2706), 'pyspark.sql.functions.arrays_zip', 'functions.arrays_zip', (['"""tags"""'], {}), "('tags')\n", (2698, 2706), False, 'from pyspark.sql import SparkSession, functions, types\n')] |
import pandas as pd
from suzieq.engines.pandas.engineobj import SqPandasEngine
from suzieq.sqobjects import get_sqobject
class TableObj(SqPandasEngine):
@staticmethod
def table_name():
return 'tables'
def get(self, **kwargs):
"""Show the known tables for which we have information"""
table_list = self._dbeng.get_tables()
df = pd.DataFrame()
columns = kwargs.pop('columns', ['default'])
unknown_tables = []
tables = []
for table in table_list:
table_obj = get_sqobject(table)
if not table_obj:
# This is a table without an sqobject backing store
# this happens either because we haven't yet implemented the
# table functions or because this table is collapsed into a
# single table as in the case of ospf
unknown_tables.append(table)
table_inst = get_sqobject('tables')(context=self.ctxt)
table_inst._table = table
else:
table_inst = table_obj(context=self.ctxt)
info = {'table': table}
info.update(table_inst.get_table_info(
table, columns=['namespace', 'hostname', 'timestamp'],
**kwargs))
tables.append(info)
df = pd.DataFrame.from_dict(tables)
if df.empty:
return df
df = df.sort_values(by=['table']).reset_index(drop=True)
cols = df.columns
total = pd.DataFrame([['TOTAL', df['firstTime'].min(),
df['latestTime'].max(),
df['intervals'].max(),
df['allRows'].sum(),
df['namespaces'].max(),
df['deviceCnt'].max()]],
columns=cols)
df = df.append(total, ignore_index=True).dropna()
return df
def summarize(self, **kwargs):
df = self.get(**kwargs)
if df.empty or ('error' in df.columns):
return df
df = df.set_index(['table'])
sdf = pd.DataFrame({
'serviceCnt': [df.index.nunique()-1],
'namespaceCnt': [df.at['TOTAL', 'namespaces']],
'deviceCnt': [df.at['device', 'deviceCnt']],
'earliestTimestamp': [df.firstTime.min()],
'lastTimestamp': [df.latestTime.max()],
'firstTime99': [df.firstTime.quantile(0.99)],
'latestTime99': [df.latestTime.quantile(0.99)],
})
return sdf.T.rename(columns={0: 'summary'})
def top(self, **kwargs):
"Tables implementation of top has to eliminate the TOTAL row"
what = kwargs.pop("what", None)
reverse = kwargs.pop("reverse", False)
sqTopCount = kwargs.pop("count", 5)
if not what:
return pd.DataFrame()
df = self.get(addnl_fields=self.iobj._addnl_fields, **kwargs)
if df.empty or ('error' in df.columns):
return df
if reverse:
return df.query('table != "TOTAL"') \
.nsmallest(sqTopCount, columns=what, keep="all") \
.head(sqTopCount)
else:
return df.query('table != "TOTAL"') \
.nlargest(sqTopCount, columns=what, keep="all") \
.head(sqTopCount)
| [
"pandas.DataFrame",
"suzieq.sqobjects.get_sqobject",
"pandas.DataFrame.from_dict"
] | [((377, 391), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (389, 391), True, 'import pandas as pd\n'), ((1343, 1373), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['tables'], {}), '(tables)\n', (1365, 1373), True, 'import pandas as pd\n'), ((551, 570), 'suzieq.sqobjects.get_sqobject', 'get_sqobject', (['table'], {}), '(table)\n', (563, 570), False, 'from suzieq.sqobjects import get_sqobject\n'), ((2899, 2913), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (2911, 2913), True, 'import pandas as pd\n'), ((951, 973), 'suzieq.sqobjects.get_sqobject', 'get_sqobject', (['"""tables"""'], {}), "('tables')\n", (963, 973), False, 'from suzieq.sqobjects import get_sqobject\n')] |
import datetime
from typing import Optional, Type, Generic, List, Tuple
from ..base import T
from .generic import PersistenceVariable
class InMemoryPersistenceVariable(PersistenceVariable, Generic[T]):
def __init__(self, type_: Type[T], keep: datetime.timedelta):
super().__init__(type_, log=True)
self.data: List[Tuple[datetime.datetime, T]] = []
self.keep = keep
async def _write_to_log(self, value: T):
self.clean_up()
self.data.append((datetime.datetime.now(datetime.timezone.utc), value))
def clean_up(self) -> None:
begin = datetime.datetime.now(datetime.timezone.utc) - self.keep
keep_from: Optional[int] = None
for i, (ts, _v) in enumerate(self.data):
if ts > begin:
keep_from = i
break
self.data = self.data[keep_from:]
async def _read_from_log(self) -> Optional[T]:
if not self.data:
return None
return self.data[-1][1]
async def retrieve_log(self, start_time: datetime.datetime, end_time: datetime.datetime,
include_previous: bool = False) -> List[Tuple[datetime.datetime, T]]:
iterator = iter(enumerate(self.data))
try:
start_index = next(i for i, (ts, _v) in iterator if ts >= start_time)
except StopIteration:
if include_previous and self.data:
return self.data[-1:]
else:
return []
if include_previous and start_index > 0:
start_index -= 1
try:
end_index = next(i for i, (ts, _v) in iterator if ts > end_time)
except StopIteration:
return self.data[start_index:]
return self.data[start_index:end_index]
| [
"datetime.datetime.now"
] | [((595, 639), 'datetime.datetime.now', 'datetime.datetime.now', (['datetime.timezone.utc'], {}), '(datetime.timezone.utc)\n', (616, 639), False, 'import datetime\n'), ((492, 536), 'datetime.datetime.now', 'datetime.datetime.now', (['datetime.timezone.utc'], {}), '(datetime.timezone.utc)\n', (513, 536), False, 'import datetime\n')] |
"""
Author: <NAME> - <EMAIL>
Description: Transplant from "https://github.com/xunhuang1995/AdaIN-style/blob/master/train.lua"
"""
import functools
import os
from collections import OrderedDict
import torch
import torch.nn as nn
from torchvision.models import vgg19
from datasets.utils import denorm
from models.blocks import AdaptiveInstanceNorm2d
from models.blocks.vgg import rename_sequential
from models.helpers import init_weights
class _Encoder(nn.Module):
def __init__(self, pretrained=True, init_type="normal", endlayer='relu4_1', feature_hook=None):
super(_Encoder, self).__init__()
self.init_type = init_type
self.pretrained = pretrained
self.feature_hook = ["relu1_1", "relu2_1", "relu3_1", "relu4_1"] if feature_hook is None else feature_hook
self.core = nn.Sequential()
backbone = vgg19(pretrained=pretrained, progress=True)
feature_extractor = rename_sequential(backbone.features)
for name, layer in feature_extractor.named_children():
self.core.add_module(name, layer)
if name == endlayer:
break
idx = -1
while not hasattr(self.core[idx], "out_channels"):
idx -= 1
self.out_channels = self.core[idx].out_channels
def init_param(self) -> None:
if self.pretrained:
return
init_weights(self.model, self.init_type)
def frozen(self):
for param in self.core.parameters():
param.requires_grad = False
def forward(self, inputs, feature_hook=None):
if feature_hook is None:
feature_hook = self.feature_hook
results = OrderedDict()
for name, layer in self.core.named_children():
inputs = layer(inputs)
if name in feature_hook:
results[name] = inputs
return results
class _Decoder(nn.Module):
def __init__(self, enc: nn.Module, activation="relu", remove_idx=-1):
super(_Decoder, self).__init__()
core_list = []
nonlinear_act = nn.ReLU
if activation == "lrelu":
nonlinear_act = functools.partial(nn.LeakyReLU, negative_slope=0.2)
for name, layer in enc.core.named_children():
if 'conv' in name:
in_channels, out_channels = layer.in_channels, layer.out_channels
core_list.append((activation + name.replace("conv", ""),
nonlinear_act(inplace=True)))
# core_list.append(("in{}".format(name.replace("conv", "")),
# nn.InstanceNorm2d(num_features=in_channels)))
core_list.append(("conv{}".format(name.replace("conv", "")),
nn.Conv2d(out_channels, in_channels, kernel_size=3, stride=1)))
core_list.append(("pad{}".format(name.replace("conv", "")),
nn.ReflectionPad2d(padding=(1, 1, 1, 1))))
if 'pool' in name:
core_list.append(("up{}".format(name.replace("pool", "")),
nn.UpsamplingNearest2d(scale_factor=2)))
self.core = rename_sequential(nn.Sequential(OrderedDict(reversed(core_list))))
# print(self)
def forward(self, inputs) -> torch.Tensor:
return self.core(inputs)
class AdaIN:
def __init__(self, opt):
self.name = "AdaIN-Style model"
self.opt = opt
self.in_channel = opt.channel
self.init_type = self.opt.init_type
self.gpu_ids = opt.gpu_ids if opt.gpu_ids else []
self.device = torch.device("cuda:0" if (torch.cuda.is_available() and len(self.gpu_ids) > 0) else "cpu")
self.dtype = torch.cuda.FloatTensor if self.device != torch.device("cpu") else torch.FloatTensor
self.save_dir = opt.expr_dir
self.encoder = _Encoder()
if self.opt.freeze_enc:
self.encoder.frozen()
self.decoder = _Decoder(self.encoder)
self.adain = AdaptiveInstanceNorm2d(num_features=self.encoder.out_channels)
self.optimizer = torch.optim.Adam(self.decoder.parameters(), lr=self.opt.lr, betas=(self.opt.beta1, 0.999))
if self.opt.resume_path is not None:
pass
# place_holders
self.inputs = None
self.loss = None
self.metrics = None
self.current_minibatch = self.opt.batchSize
if self.opt.resume_path is not None:
self.load_model(self.opt.resume_path)
self.cuda()
def cuda(self):
if torch.cuda.is_available():
self.encoder.cuda(self.device)
self.decoder.cuda(self.device)
self.adain.cuda(self.device)
def train_decoder(self, content, style, alpha=1.0):
self.optimizer.zero_grad()
# find all the features with frozen VGG
style_features = self.encoder(style)
content_latent = self.encoder(content, feature_hook=["relu4_1"])
# Find adain
trans_content = self.adain(content=content_latent["relu4_1"],
style=style_features["relu4_1"])
interpolate_latent = (1.0 - alpha) * content_latent["relu4_1"] + \
alpha * trans_content
transferred_image = self.decoder(interpolate_latent)
transferred_features = self.encoder(transferred_image)
c_loss = self.loss["content_loss"](transferred_features["relu4_1"], interpolate_latent)
s_loss = self.loss["style_loss"](transferred_features, style_features)
smooth_reg = self.loss["smooth_reg"](transferred_image)
loss = c_loss.mean() + s_loss.mean() + smooth_reg.mean()
loss.backward()
self.optimizer.step()
return c_loss, s_loss, smooth_reg, transferred_image
def train_batch(self, inputs: dict, loss: dict, metrics: dict, niter: int = 0, epoch: int = 0) -> dict:
self.inputs = inputs
self.loss = loss if self.loss is None else self.loss
self.metrics = metrics if self.metrics is None else self.metrics
self.current_minibatch = inputs["Source"].shape[0]
c_loss, s_loss, smooth_reg, transferred_image = self.train_decoder(inputs["Source"].to(self.device),
inputs["Style"].to(self.device))
store_val = {"vis": {"Target": denorm(transferred_image, self.device, to_board=True),
"Source": denorm(inputs["Source"], self.device, to_board=True),
"Style": denorm(inputs["Style"], self.device, to_board=True)},
"loss": {"loss_content": c_loss,
"loss_style": s_loss,
"smooth_reg": smooth_reg,
}
}
if epoch % 30 == 5:
self.save_model(epoch, store=store_val)
return store_val
def predict_batch(self, inputs: dict, loss=None, metrics=None, niter=None, epoch=None):
self.current_minibatch = self.opt.batchSize
return {
"vis": {"Target": None},
"loss": {}
}
def save_model(self, epoch, store):
store_dict = {
"epoch": epoch,
"model_state_dict": {
"decoder_model_state_dict": self.decoder.state_dict(),
},
"optimizer_state_dict": {
"decoder_optimizer_state_dict": self.optimizer.state_dict(),
}
}
store_dict.update(store)
torch.save(store_dict, os.path.join(self.opt.expr_dir, "epoch_{}.pth".format(epoch)))
torch.save(store_dict, os.path.join(self.opt.expr_dir, "latest.pth".format(epoch)))
def load_model(self, store_path, no_opt=False):
store_dict = torch.load(store_path)
self.decoder.load_state_dict(store_dict["model_state_dict"]["decoder_model_state_dict"])
if no_opt:
return
self.optimizer.load_state_dict(store_dict["optimizer_state_dict"]["decoder_optimizer_state_dict"])
if __name__ == '__main__':
bs = 10
w, h = 128, 128
image = torch.rand((bs, 3, w, h))
# g = _Generator_ResizeConv()
e = _Encoder()
d = _Decoder(e)
adain = AdaptiveInstanceNorm2d(e.out_channels)
te = adain(e(image)["relu4_1"], e(image)["relu4_1"])
print(d)
print(d(te).shape)
# print(e(image).shape)
# print(d(e(image)).shape)
# print(.out_channels)
# fak = g(z)
# print(fak.shape)
# print(d(fak).shape)
| [
"torch.nn.UpsamplingNearest2d",
"collections.OrderedDict",
"models.helpers.init_weights",
"torch.rand",
"torchvision.models.vgg19",
"torch.nn.Sequential",
"torch.nn.ReflectionPad2d",
"torch.load",
"torch.nn.Conv2d",
"torch.cuda.is_available",
"functools.partial",
"datasets.utils.denorm",
"mo... | [((8174, 8199), 'torch.rand', 'torch.rand', (['(bs, 3, w, h)'], {}), '((bs, 3, w, h))\n', (8184, 8199), False, 'import torch\n'), ((8285, 8323), 'models.blocks.AdaptiveInstanceNorm2d', 'AdaptiveInstanceNorm2d', (['e.out_channels'], {}), '(e.out_channels)\n', (8307, 8323), False, 'from models.blocks import AdaptiveInstanceNorm2d\n'), ((827, 842), 'torch.nn.Sequential', 'nn.Sequential', ([], {}), '()\n', (840, 842), True, 'import torch.nn as nn\n'), ((862, 905), 'torchvision.models.vgg19', 'vgg19', ([], {'pretrained': 'pretrained', 'progress': '(True)'}), '(pretrained=pretrained, progress=True)\n', (867, 905), False, 'from torchvision.models import vgg19\n'), ((934, 970), 'models.blocks.vgg.rename_sequential', 'rename_sequential', (['backbone.features'], {}), '(backbone.features)\n', (951, 970), False, 'from models.blocks.vgg import rename_sequential\n'), ((1378, 1418), 'models.helpers.init_weights', 'init_weights', (['self.model', 'self.init_type'], {}), '(self.model, self.init_type)\n', (1390, 1418), False, 'from models.helpers import init_weights\n'), ((1674, 1687), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (1685, 1687), False, 'from collections import OrderedDict\n'), ((4023, 4085), 'models.blocks.AdaptiveInstanceNorm2d', 'AdaptiveInstanceNorm2d', ([], {'num_features': 'self.encoder.out_channels'}), '(num_features=self.encoder.out_channels)\n', (4045, 4085), False, 'from models.blocks import AdaptiveInstanceNorm2d\n'), ((4567, 4592), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (4590, 4592), False, 'import torch\n'), ((7836, 7858), 'torch.load', 'torch.load', (['store_path'], {}), '(store_path)\n', (7846, 7858), False, 'import torch\n'), ((2138, 2189), 'functools.partial', 'functools.partial', (['nn.LeakyReLU'], {'negative_slope': '(0.2)'}), '(nn.LeakyReLU, negative_slope=0.2)\n', (2155, 2189), False, 'import functools\n'), ((3776, 3795), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (3788, 3795), False, 'import torch\n'), ((6398, 6451), 'datasets.utils.denorm', 'denorm', (['transferred_image', 'self.device'], {'to_board': '(True)'}), '(transferred_image, self.device, to_board=True)\n', (6404, 6451), False, 'from datasets.utils import denorm\n'), ((6492, 6544), 'datasets.utils.denorm', 'denorm', (["inputs['Source']", 'self.device'], {'to_board': '(True)'}), "(inputs['Source'], self.device, to_board=True)\n", (6498, 6544), False, 'from datasets.utils import denorm\n'), ((6584, 6635), 'datasets.utils.denorm', 'denorm', (["inputs['Style']", 'self.device'], {'to_board': '(True)'}), "(inputs['Style'], self.device, to_board=True)\n", (6590, 6635), False, 'from datasets.utils import denorm\n'), ((3649, 3674), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (3672, 3674), False, 'import torch\n'), ((2764, 2825), 'torch.nn.Conv2d', 'nn.Conv2d', (['out_channels', 'in_channels'], {'kernel_size': '(3)', 'stride': '(1)'}), '(out_channels, in_channels, kernel_size=3, stride=1)\n', (2773, 2825), True, 'import torch.nn as nn\n'), ((2938, 2978), 'torch.nn.ReflectionPad2d', 'nn.ReflectionPad2d', ([], {'padding': '(1, 1, 1, 1)'}), '(padding=(1, 1, 1, 1))\n', (2956, 2978), True, 'import torch.nn as nn\n'), ((3122, 3160), 'torch.nn.UpsamplingNearest2d', 'nn.UpsamplingNearest2d', ([], {'scale_factor': '(2)'}), '(scale_factor=2)\n', (3144, 3160), True, 'import torch.nn as nn\n')] |
# Generated by Django 3.0.7 on 2020-10-14 07:46
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("posthog", "0086_team_session_recording_opt_in"),
]
operations = [
migrations.AlterField(
model_name="annotation",
name="created_at",
field=models.DateTimeField(default=django.utils.timezone.now, null=True),
),
]
| [
"django.db.models.DateTimeField"
] | [((384, 450), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'default': 'django.utils.timezone.now', 'null': '(True)'}), '(default=django.utils.timezone.now, null=True)\n', (404, 450), False, 'from django.db import migrations, models\n')] |
"""
Create a cartoon of a tumor given the frequencies of different genotypes.
"""
from .util import *
import pandas as pd
import matplotlib.pyplot as plt
import click
import os
from pathlib import Path
from pymuller import muller
@click.command(help="Plot the evolution of a tumor.")
@click.argument(
"genotype-counts",
type=click.Path(exists=True, dir_okay=False),
)
@click.argument(
"genotype-parents",
type=click.Path(exists=True, dir_okay=False),
)
@click.option("-c", "--cells", default=100, help="Number of cells in slice plot.")
@click.option(
"-r",
"--average-radius",
default=10,
help="Average radius of circles in slice plot.",
)
@click.option("--grid-file", default="", help="Path to grid file.")
@click.option("--colormap", default="gnuplot", help="Colormap for genotypes.")
@click.option("--dpi", default=100, help="DPI for figures.")
@click.option("--plot", is_flag=True, help="Plot all the figures.")
@click.option("--do-muller", is_flag=True, help="Make a Muller plot.")
@click.option("--do-slice", is_flag=True, help="Make a slice plot.")
@click.option("--do-tree", is_flag=True, help="Make a clone tree plot.")
@click.option(
"--normalize", is_flag=True, help="Normalize the abundances in the Muller plot."
)
@click.option("--labels", is_flag=True, help="Annotate the clone tree plot.")
@click.option(
"--remove", is_flag=True, help="Remove empty clones in the clone tree plot."
)
@click.option(
"-o", "--output-path", default="./", help="Directory to write figures into."
)
def main(
genotype_counts,
genotype_parents,
cells,
average_radius,
grid_file,
colormap,
dpi,
plot,
do_muller,
do_slice,
do_tree,
normalize,
labels,
remove,
output_path,
):
genotype_counts = pd.read_csv(genotype_counts, index_col=0)
genotype_parents = pd.read_csv(genotype_parents, index_col=0, dtype=str)
if grid_file != "":
grid = pd.read_csv(grid_file, index_col=0, dtype=str)
pop_df, anc_df, color_by = prepare_plots(genotype_counts, genotype_parents)
cmap, genotypes = get_colormap(pop_df, anc_df, color_by, colormap)
if plot:
fig, ax_list = plt.subplots(ncols=3, sharex=False, dpi=dpi, figsize=(8, 2))
muller(
pop_df,
anc_df,
color_by,
ax=ax_list[0],
colorbar=False,
colormap=colormap,
normalize=normalize,
background_strain=False,
)
plt.axis("off")
if grid_file == "":
plot_deme(
cells,
genotype_counts.iloc[-1],
pop_df,
anc_df,
color_by,
average_radius=average_radius,
colormap=colormap,
ax=ax_list[1],
)
else:
plot_grid(grid, cmap, genotypes, ax=ax_list[1])
plot_tree(
genotype_parents,
pop_df,
anc_df,
color_by,
genotype_counts=genotype_counts.iloc[-1],
filter_clones=remove,
labels=labels,
colormap=colormap,
ax=ax_list[2],
)
plt.show()
else:
Path(output_path).mkdir(parents=True, exist_ok=True)
if do_muller:
ax = muller(
pop_df,
anc_df,
color_by,
colorbar=False,
colormap=colormap,
normalize=normalize,
)
plt.axis("off")
plt.savefig(
os.path.join(output_path, "muller.pdf"), dpi=dpi, bbox_inches="tight"
)
if do_slice:
if grid_file == "":
ax = plot_deme(
cells,
genotype_counts.iloc[-1],
pop_df,
anc_df,
color_by,
average_radius=average_radius,
colormap=colormap,
)
else:
ax = plot_grid(grid, cmap)
plt.savefig(
os.path.join(output_path, "slice.pdf"), dpi=dpi, bbox_inches="tight"
)
if do_tree:
ax = plot_tree(
genotype_parents,
pop_df,
anc_df,
color_by,
genotype_counts=genotype_counts.iloc[-1],
filter_clones=remove,
labels=labels,
colormap=colormap,
)
plt.savefig(
os.path.join(output_path, "tree.pdf"), dpi=dpi, bbox_inches="tight"
)
if __name__ == "__main__":
main()
| [
"pandas.read_csv",
"pathlib.Path",
"click.option",
"os.path.join",
"pymuller.muller",
"click.Path",
"matplotlib.pyplot.axis",
"click.command",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((236, 288), 'click.command', 'click.command', ([], {'help': '"""Plot the evolution of a tumor."""'}), "(help='Plot the evolution of a tumor.')\n", (249, 288), False, 'import click\n'), ((475, 561), 'click.option', 'click.option', (['"""-c"""', '"""--cells"""'], {'default': '(100)', 'help': '"""Number of cells in slice plot."""'}), "('-c', '--cells', default=100, help=\n 'Number of cells in slice plot.')\n", (487, 561), False, 'import click\n'), ((558, 662), 'click.option', 'click.option', (['"""-r"""', '"""--average-radius"""'], {'default': '(10)', 'help': '"""Average radius of circles in slice plot."""'}), "('-r', '--average-radius', default=10, help=\n 'Average radius of circles in slice plot.')\n", (570, 662), False, 'import click\n'), ((678, 744), 'click.option', 'click.option', (['"""--grid-file"""'], {'default': '""""""', 'help': '"""Path to grid file."""'}), "('--grid-file', default='', help='Path to grid file.')\n", (690, 744), False, 'import click\n'), ((746, 823), 'click.option', 'click.option', (['"""--colormap"""'], {'default': '"""gnuplot"""', 'help': '"""Colormap for genotypes."""'}), "('--colormap', default='gnuplot', help='Colormap for genotypes.')\n", (758, 823), False, 'import click\n'), ((825, 884), 'click.option', 'click.option', (['"""--dpi"""'], {'default': '(100)', 'help': '"""DPI for figures."""'}), "('--dpi', default=100, help='DPI for figures.')\n", (837, 884), False, 'import click\n'), ((886, 952), 'click.option', 'click.option', (['"""--plot"""'], {'is_flag': '(True)', 'help': '"""Plot all the figures."""'}), "('--plot', is_flag=True, help='Plot all the figures.')\n", (898, 952), False, 'import click\n'), ((954, 1023), 'click.option', 'click.option', (['"""--do-muller"""'], {'is_flag': '(True)', 'help': '"""Make a Muller plot."""'}), "('--do-muller', is_flag=True, help='Make a Muller plot.')\n", (966, 1023), False, 'import click\n'), ((1025, 1092), 'click.option', 'click.option', (['"""--do-slice"""'], {'is_flag': '(True)', 'help': '"""Make a slice plot."""'}), "('--do-slice', is_flag=True, help='Make a slice plot.')\n", (1037, 1092), False, 'import click\n'), ((1094, 1165), 'click.option', 'click.option', (['"""--do-tree"""'], {'is_flag': '(True)', 'help': '"""Make a clone tree plot."""'}), "('--do-tree', is_flag=True, help='Make a clone tree plot.')\n", (1106, 1165), False, 'import click\n'), ((1167, 1266), 'click.option', 'click.option', (['"""--normalize"""'], {'is_flag': '(True)', 'help': '"""Normalize the abundances in the Muller plot."""'}), "('--normalize', is_flag=True, help=\n 'Normalize the abundances in the Muller plot.')\n", (1179, 1266), False, 'import click\n'), ((1269, 1345), 'click.option', 'click.option', (['"""--labels"""'], {'is_flag': '(True)', 'help': '"""Annotate the clone tree plot."""'}), "('--labels', is_flag=True, help='Annotate the clone tree plot.')\n", (1281, 1345), False, 'import click\n'), ((1347, 1442), 'click.option', 'click.option', (['"""--remove"""'], {'is_flag': '(True)', 'help': '"""Remove empty clones in the clone tree plot."""'}), "('--remove', is_flag=True, help=\n 'Remove empty clones in the clone tree plot.')\n", (1359, 1442), False, 'import click\n'), ((1445, 1540), 'click.option', 'click.option', (['"""-o"""', '"""--output-path"""'], {'default': '"""./"""', 'help': '"""Directory to write figures into."""'}), "('-o', '--output-path', default='./', help=\n 'Directory to write figures into.')\n", (1457, 1540), False, 'import click\n'), ((1797, 1838), 'pandas.read_csv', 'pd.read_csv', (['genotype_counts'], {'index_col': '(0)'}), '(genotype_counts, index_col=0)\n', (1808, 1838), True, 'import pandas as pd\n'), ((1862, 1915), 'pandas.read_csv', 'pd.read_csv', (['genotype_parents'], {'index_col': '(0)', 'dtype': 'str'}), '(genotype_parents, index_col=0, dtype=str)\n', (1873, 1915), True, 'import pandas as pd\n'), ((1955, 2001), 'pandas.read_csv', 'pd.read_csv', (['grid_file'], {'index_col': '(0)', 'dtype': 'str'}), '(grid_file, index_col=0, dtype=str)\n', (1966, 2001), True, 'import pandas as pd\n'), ((2191, 2251), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'ncols': '(3)', 'sharex': '(False)', 'dpi': 'dpi', 'figsize': '(8, 2)'}), '(ncols=3, sharex=False, dpi=dpi, figsize=(8, 2))\n', (2203, 2251), True, 'import matplotlib.pyplot as plt\n'), ((2260, 2393), 'pymuller.muller', 'muller', (['pop_df', 'anc_df', 'color_by'], {'ax': 'ax_list[0]', 'colorbar': '(False)', 'colormap': 'colormap', 'normalize': 'normalize', 'background_strain': '(False)'}), '(pop_df, anc_df, color_by, ax=ax_list[0], colorbar=False, colormap=\n colormap, normalize=normalize, background_strain=False)\n', (2266, 2393), False, 'from pymuller import muller\n'), ((2504, 2519), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (2512, 2519), True, 'import matplotlib.pyplot as plt\n'), ((3215, 3225), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3223, 3225), True, 'import matplotlib.pyplot as plt\n'), ((338, 377), 'click.Path', 'click.Path', ([], {'exists': '(True)', 'dir_okay': '(False)'}), '(exists=True, dir_okay=False)\n', (348, 377), False, 'import click\n'), ((431, 470), 'click.Path', 'click.Path', ([], {'exists': '(True)', 'dir_okay': '(False)'}), '(exists=True, dir_okay=False)\n', (441, 470), False, 'import click\n'), ((3336, 3428), 'pymuller.muller', 'muller', (['pop_df', 'anc_df', 'color_by'], {'colorbar': '(False)', 'colormap': 'colormap', 'normalize': 'normalize'}), '(pop_df, anc_df, color_by, colorbar=False, colormap=colormap,\n normalize=normalize)\n', (3342, 3428), False, 'from pymuller import muller\n'), ((3548, 3563), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (3556, 3563), True, 'import matplotlib.pyplot as plt\n'), ((3244, 3261), 'pathlib.Path', 'Path', (['output_path'], {}), '(output_path)\n', (3248, 3261), False, 'from pathlib import Path\n'), ((3605, 3644), 'os.path.join', 'os.path.join', (['output_path', '"""muller.pdf"""'], {}), "(output_path, 'muller.pdf')\n", (3617, 3644), False, 'import os\n'), ((4144, 4182), 'os.path.join', 'os.path.join', (['output_path', '"""slice.pdf"""'], {}), "(output_path, 'slice.pdf')\n", (4156, 4182), False, 'import os\n'), ((4601, 4638), 'os.path.join', 'os.path.join', (['output_path', '"""tree.pdf"""'], {}), "(output_path, 'tree.pdf')\n", (4613, 4638), False, 'import os\n')] |
from django.conf.urls import url
from .views import get_online_users, set_online
app_name = 'online_users'
urlpatterns = [
url(r'^so/$', set_online),
url(r'^ous/$', get_online_users),
]
| [
"django.conf.urls.url"
] | [((129, 153), 'django.conf.urls.url', 'url', (['"""^so/$"""', 'set_online'], {}), "('^so/$', set_online)\n", (132, 153), False, 'from django.conf.urls import url\n'), ((160, 191), 'django.conf.urls.url', 'url', (['"""^ous/$"""', 'get_online_users'], {}), "('^ous/$', get_online_users)\n", (163, 191), False, 'from django.conf.urls import url\n')] |
#!/usr/bin/py
import pandas as pd
import os
# Holds investing.com candlestick patterns
class CSPatternList:
def __init__(self, path):
self.data = None
with os.scandir(path) as entries:
for e in entries:
if e.is_file() and os.path.splitext(e.path)[1] == '.csv':
if self.data is None:
self.data = pd.read_csv(e.path)
else:
self.data.append(pd.read_csv(e.path))
# imgui settings
self.selected_row = 0
def draw_filter_menu(self, imgui):
imgui.separator()
def draw(self, imgui):
imgui.begin("CS Patterns")
imgui.columns(len(self.data.columns) + 1, "asodf")
imgui.separator()
imgui.text("")
imgui.next_column()
for c in self.data.columns:
imgui.text(c)
imgui.next_column()
imgui.separator()
# fill with data
for i in range(10):
label = str(i)
clicked, _ = imgui.selectable(
label=label,
selected=self.selected_row == i,
flags=imgui.SELECTABLE_SPAN_ALL_COLUMNS,
)
if clicked:
self.selected_row = i
hovered = imgui.is_item_hovered()
row = self.data.loc[i]
imgui.next_column()
for c in self.data.columns:
imgui.text(row[c])
imgui.next_column()
imgui.end()
| [
"os.scandir",
"os.path.splitext",
"pandas.read_csv"
] | [((179, 195), 'os.scandir', 'os.scandir', (['path'], {}), '(path)\n', (189, 195), False, 'import os\n'), ((390, 409), 'pandas.read_csv', 'pd.read_csv', (['e.path'], {}), '(e.path)\n', (401, 409), True, 'import pandas as pd\n'), ((273, 297), 'os.path.splitext', 'os.path.splitext', (['e.path'], {}), '(e.path)\n', (289, 297), False, 'import os\n'), ((477, 496), 'pandas.read_csv', 'pd.read_csv', (['e.path'], {}), '(e.path)\n', (488, 496), True, 'import pandas as pd\n')] |
from setuptools import setup
setup(
name='netspeed',
version='0.1',
py_modules=['netspeed'],
install_requires=[
'Click',
'pyspeedtest'
],
entry_points='''
[console_scripts]
netspeed=netspeed:cli
''',
)
| [
"setuptools.setup"
] | [((30, 226), 'setuptools.setup', 'setup', ([], {'name': '"""netspeed"""', 'version': '"""0.1"""', 'py_modules': "['netspeed']", 'install_requires': "['Click', 'pyspeedtest']", 'entry_points': '"""\n [console_scripts]\n netspeed=netspeed:cli\n """'}), '(name=\'netspeed\', version=\'0.1\', py_modules=[\'netspeed\'],\n install_requires=[\'Click\', \'pyspeedtest\'], entry_points=\n """\n [console_scripts]\n netspeed=netspeed:cli\n """)\n', (35, 226), False, 'from setuptools import setup\n')] |
from django.contrib import admin
from .models import (Dish, Payments, Order, Delivery, OrderItem)
admin.site.register(Dish)
admin.site.register(Payments)
admin.site.register(Order)
admin.site.register(Delivery)
admin.site.register(OrderItem)
| [
"django.contrib.admin.site.register"
] | [((99, 124), 'django.contrib.admin.site.register', 'admin.site.register', (['Dish'], {}), '(Dish)\n', (118, 124), False, 'from django.contrib import admin\n'), ((125, 154), 'django.contrib.admin.site.register', 'admin.site.register', (['Payments'], {}), '(Payments)\n', (144, 154), False, 'from django.contrib import admin\n'), ((155, 181), 'django.contrib.admin.site.register', 'admin.site.register', (['Order'], {}), '(Order)\n', (174, 181), False, 'from django.contrib import admin\n'), ((182, 211), 'django.contrib.admin.site.register', 'admin.site.register', (['Delivery'], {}), '(Delivery)\n', (201, 211), False, 'from django.contrib import admin\n'), ((212, 242), 'django.contrib.admin.site.register', 'admin.site.register', (['OrderItem'], {}), '(OrderItem)\n', (231, 242), False, 'from django.contrib import admin\n')] |
import os
from dataclasses import dataclass, field
from typing import AnyStr, Dict, Optional
from urllib.parse import urljoin
@dataclass
class FreshChatConfiguration:
"""
Class represents the base configuration for Freshchat
"""
app_id: str
token: str = field(repr=False)
default_channel_id: Optional[str] = field(default=None)
default_initial_message: Optional[str] = field(default=None)
url: Optional[str] = field(
default_factory=lambda: os.environ.get(
"FRESHCHAT_API_URL", "https://api.freshchat.com/v2/"
)
)
@property
def authorization_header(self) -> Dict[AnyStr, AnyStr]:
"""
Property which returns the proper format of the authorization header
"""
return {
"Authorization": f"Bearer {self.token}"
if "Bearer" not in self.token
else self.token
}
def get_url(self, endpoint: str) -> str:
"""
Method responsible to build the url using the given endpoint
:param endpoint: String with the endpoint which needs to attached to URL
:return: a string which represents URL
"""
return urljoin(self.url, endpoint.lstrip("/"))
| [
"os.environ.get",
"dataclasses.field"
] | [((277, 294), 'dataclasses.field', 'field', ([], {'repr': '(False)'}), '(repr=False)\n', (282, 294), False, 'from dataclasses import dataclass, field\n'), ((335, 354), 'dataclasses.field', 'field', ([], {'default': 'None'}), '(default=None)\n', (340, 354), False, 'from dataclasses import dataclass, field\n'), ((400, 419), 'dataclasses.field', 'field', ([], {'default': 'None'}), '(default=None)\n', (405, 419), False, 'from dataclasses import dataclass, field\n'), ((484, 552), 'os.environ.get', 'os.environ.get', (['"""FRESHCHAT_API_URL"""', '"""https://api.freshchat.com/v2/"""'], {}), "('FRESHCHAT_API_URL', 'https://api.freshchat.com/v2/')\n", (498, 552), False, 'import os\n')] |
from math import log2
import torch
from torch import nn, einsum
import torch.nn.functional as F
from einops import rearrange
from x_transformers import Encoder, Decoder
# helpers
def exists(val):
return val is not None
def masked_mean(t, mask, dim = 1):
t = t.masked_fill(~mask[:, :, None], 0.)
return t.sum(dim = 1) / mask.sum(dim = 1)[..., None]
# classes
class DiscreteVAE(nn.Module):
def __init__(
self,
num_tokens,
dim = 512,
hidden_dim = 64
):
super().__init__()
hdim = hidden_dim
self.encoder = nn.Sequential(
nn.Conv2d(3, hdim, 4, stride = 2, padding = 1),
nn.ReLU(),
nn.Conv2d(hdim, hdim, 4, stride = 2, padding = 1),
nn.ReLU(),
nn.Conv2d(hdim, hdim, 4, stride = 2, padding = 1),
nn.ReLU(),
nn.Conv2d(hdim, num_tokens, 1)
)
self.decoder = nn.Sequential(
nn.ConvTranspose2d(dim, hdim, 4, stride = 2, padding = 1),
nn.ReLU(),
nn.ConvTranspose2d(hdim, hdim, 4, stride = 2, padding = 1),
nn.ReLU(),
nn.ConvTranspose2d(hdim, hdim, 4, stride = 2, padding = 1),
nn.ReLU(),
nn.Conv2d(hdim, 3, 1)
)
self.num_tokens = num_tokens
self.codebook = nn.Embedding(num_tokens, dim)
def forward(
self,
img,
return_recon_loss = False,
return_logits = False
):
logits = self.encoder(img)
if return_logits:
return logits # return logits for getting hard image indices for DALL-E training
soft_one_hot = F.gumbel_softmax(logits, tau = 1.)
sampled = einsum('b n h w, n d -> b d h w', soft_one_hot, self.codebook.weight)
out = self.decoder(sampled)
if not return_recon_loss:
return out
loss = F.mse_loss(img, out)
return loss
# main classes
class CLIP(nn.Module):
def __init__(
self,
*,
dim = 512,
num_text_tokens = 10000,
num_visual_tokens = 512,
text_enc_depth = 6,
visual_enc_depth = 6,
text_seq_len = 256,
visual_seq_len = 1024,
text_heads = 8,
visual_heads = 8
):
super().__init__()
self.scale = dim ** -0.5
self.text_emb = nn.Embedding(num_text_tokens, dim)
self.visual_emb = nn.Embedding(num_visual_tokens, dim)
self.text_pos_emb = nn.Embedding(text_seq_len, dim)
self.visual_pos_emb = nn.Embedding(visual_seq_len, dim)
self.text_transformer = Encoder(dim = dim, depth = text_enc_depth, heads = text_heads)
self.visual_transformer = Encoder(dim = dim, depth = visual_enc_depth, heads = visual_heads)
def forward(
self,
text,
image,
text_mask = None,
return_loss = False
):
b, device = text.shape[0], text.device
text_emb = self.text_emb(text)
text_emb += self.text_pos_emb(torch.arange(text.shape[1], device = device))
image_emb = self.visual_emb(image)
image_emb += self.visual_pos_emb(torch.arange(image.shape[1], device = device))
enc_text = self.text_transformer(text_emb, mask = text_mask)
enc_image = self.visual_transformer(image_emb)
if exists(text_mask):
text_latents = masked_mean(enc_text, text_mask, dim = 1)
else:
text_latents = enc_text.mean(dim = 1)
image_latents = enc_image.mean(dim = 1)
sim = einsum('i d, j d -> i j', text_latents, image_latents) * self.scale
if not return_loss:
return sim
labels = torch.arange(b, device = device)
loss = F.cross_entropy(sim, labels)
return loss
class DALLE(nn.Module):
def __init__(
self,
*,
dim,
num_text_tokens = 10000,
num_image_tokens = 512,
text_seq_len = 256,
image_seq_len = 1024,
depth = 6, # should be 64
heads = 8,
vae = None
):
super().__init__()
self.text_emb = nn.Embedding(num_text_tokens, dim)
self.image_emb = nn.Embedding(num_image_tokens, dim)
self.text_pos_emb = nn.Embedding(text_seq_len, dim)
self.image_pos_emb = nn.Embedding(image_seq_len, dim)
self.num_text_tokens = num_text_tokens # for offsetting logits index and calculating cross entropy loss
self.image_seq_len = image_seq_len
self.total_tokens = num_text_tokens + num_image_tokens + 1 # extra for EOS
self.vae = vae
self.image_emb = vae.codebook
self.transformer = Decoder(dim = dim, depth = depth, heads = heads)
self.to_logits = nn.Sequential(
nn.LayerNorm(dim),
nn.Linear(dim, self.total_tokens),
)
def forward(
self,
text,
image,
mask = None,
return_loss = False
):
device = text.device
is_raw_image = len(image.shape) == 4
text_emb = self.text_emb(text)
text_emb += self.text_pos_emb(torch.arange(text.shape[1], device = device))
if is_raw_image:
assert exists(self.vae), 'VAE must be passed into constructor if you are to train directly on raw images'
image_logits = self.vae(image, return_logits = True)
codebook_indices = image_logits.argmax(dim = 1).flatten(1)
image = codebook_indices
image_emb = self.image_emb(image)
image_emb += self.image_pos_emb(torch.arange(image.shape[1], device = device))
tokens = torch.cat((text_emb, image_emb), dim = 1)
if exists(mask):
mask = F.pad(mask, (0, self.image_seq_len), value = True)
out = self.transformer(tokens, mask = mask)
out = self.to_logits(out)
if not return_loss:
return out
offsetted_image = image + self.num_text_tokens
labels = torch.cat((text, offsetted_image), dim = 1)
labels = F.pad(labels, (0, 1), value = (self.total_tokens - 1)) # last token predicts EOS
loss = F.cross_entropy(out.transpose(1, 2), labels[:, 1:])
return loss
| [
"torch.nn.ReLU",
"torch.nn.functional.mse_loss",
"torch.nn.functional.gumbel_softmax",
"x_transformers.Encoder",
"x_transformers.Decoder",
"torch.nn.LayerNorm",
"torch.nn.Conv2d",
"torch.cat",
"torch.arange",
"torch.einsum",
"torch.nn.functional.cross_entropy",
"torch.nn.Linear",
"torch.nn.f... | [((1337, 1366), 'torch.nn.Embedding', 'nn.Embedding', (['num_tokens', 'dim'], {}), '(num_tokens, dim)\n', (1349, 1366), False, 'from torch import nn, einsum\n'), ((1663, 1696), 'torch.nn.functional.gumbel_softmax', 'F.gumbel_softmax', (['logits'], {'tau': '(1.0)'}), '(logits, tau=1.0)\n', (1679, 1696), True, 'import torch.nn.functional as F\n'), ((1716, 1785), 'torch.einsum', 'einsum', (['"""b n h w, n d -> b d h w"""', 'soft_one_hot', 'self.codebook.weight'], {}), "('b n h w, n d -> b d h w', soft_one_hot, self.codebook.weight)\n", (1722, 1785), False, 'from torch import nn, einsum\n'), ((1896, 1916), 'torch.nn.functional.mse_loss', 'F.mse_loss', (['img', 'out'], {}), '(img, out)\n', (1906, 1916), True, 'import torch.nn.functional as F\n'), ((2362, 2396), 'torch.nn.Embedding', 'nn.Embedding', (['num_text_tokens', 'dim'], {}), '(num_text_tokens, dim)\n', (2374, 2396), False, 'from torch import nn, einsum\n'), ((2423, 2459), 'torch.nn.Embedding', 'nn.Embedding', (['num_visual_tokens', 'dim'], {}), '(num_visual_tokens, dim)\n', (2435, 2459), False, 'from torch import nn, einsum\n'), ((2489, 2520), 'torch.nn.Embedding', 'nn.Embedding', (['text_seq_len', 'dim'], {}), '(text_seq_len, dim)\n', (2501, 2520), False, 'from torch import nn, einsum\n'), ((2551, 2584), 'torch.nn.Embedding', 'nn.Embedding', (['visual_seq_len', 'dim'], {}), '(visual_seq_len, dim)\n', (2563, 2584), False, 'from torch import nn, einsum\n'), ((2618, 2674), 'x_transformers.Encoder', 'Encoder', ([], {'dim': 'dim', 'depth': 'text_enc_depth', 'heads': 'text_heads'}), '(dim=dim, depth=text_enc_depth, heads=text_heads)\n', (2625, 2674), False, 'from x_transformers import Encoder, Decoder\n'), ((2715, 2775), 'x_transformers.Encoder', 'Encoder', ([], {'dim': 'dim', 'depth': 'visual_enc_depth', 'heads': 'visual_heads'}), '(dim=dim, depth=visual_enc_depth, heads=visual_heads)\n', (2722, 2775), False, 'from x_transformers import Encoder, Decoder\n'), ((3698, 3728), 'torch.arange', 'torch.arange', (['b'], {'device': 'device'}), '(b, device=device)\n', (3710, 3728), False, 'import torch\n'), ((3746, 3774), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['sim', 'labels'], {}), '(sim, labels)\n', (3761, 3774), True, 'import torch.nn.functional as F\n'), ((4130, 4164), 'torch.nn.Embedding', 'nn.Embedding', (['num_text_tokens', 'dim'], {}), '(num_text_tokens, dim)\n', (4142, 4164), False, 'from torch import nn, einsum\n'), ((4190, 4225), 'torch.nn.Embedding', 'nn.Embedding', (['num_image_tokens', 'dim'], {}), '(num_image_tokens, dim)\n', (4202, 4225), False, 'from torch import nn, einsum\n'), ((4255, 4286), 'torch.nn.Embedding', 'nn.Embedding', (['text_seq_len', 'dim'], {}), '(text_seq_len, dim)\n', (4267, 4286), False, 'from torch import nn, einsum\n'), ((4316, 4348), 'torch.nn.Embedding', 'nn.Embedding', (['image_seq_len', 'dim'], {}), '(image_seq_len, dim)\n', (4328, 4348), False, 'from torch import nn, einsum\n'), ((4677, 4719), 'x_transformers.Decoder', 'Decoder', ([], {'dim': 'dim', 'depth': 'depth', 'heads': 'heads'}), '(dim=dim, depth=depth, heads=heads)\n', (4684, 4719), False, 'from x_transformers import Encoder, Decoder\n'), ((5635, 5674), 'torch.cat', 'torch.cat', (['(text_emb, image_emb)'], {'dim': '(1)'}), '((text_emb, image_emb), dim=1)\n', (5644, 5674), False, 'import torch\n'), ((5985, 6026), 'torch.cat', 'torch.cat', (['(text, offsetted_image)'], {'dim': '(1)'}), '((text, offsetted_image), dim=1)\n', (5994, 6026), False, 'import torch\n'), ((6046, 6096), 'torch.nn.functional.pad', 'F.pad', (['labels', '(0, 1)'], {'value': '(self.total_tokens - 1)'}), '(labels, (0, 1), value=self.total_tokens - 1)\n', (6051, 6096), True, 'import torch.nn.functional as F\n'), ((612, 654), 'torch.nn.Conv2d', 'nn.Conv2d', (['(3)', 'hdim', '(4)'], {'stride': '(2)', 'padding': '(1)'}), '(3, hdim, 4, stride=2, padding=1)\n', (621, 654), False, 'from torch import nn, einsum\n'), ((672, 681), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (679, 681), False, 'from torch import nn, einsum\n'), ((695, 740), 'torch.nn.Conv2d', 'nn.Conv2d', (['hdim', 'hdim', '(4)'], {'stride': '(2)', 'padding': '(1)'}), '(hdim, hdim, 4, stride=2, padding=1)\n', (704, 740), False, 'from torch import nn, einsum\n'), ((758, 767), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (765, 767), False, 'from torch import nn, einsum\n'), ((781, 826), 'torch.nn.Conv2d', 'nn.Conv2d', (['hdim', 'hdim', '(4)'], {'stride': '(2)', 'padding': '(1)'}), '(hdim, hdim, 4, stride=2, padding=1)\n', (790, 826), False, 'from torch import nn, einsum\n'), ((844, 853), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (851, 853), False, 'from torch import nn, einsum\n'), ((867, 897), 'torch.nn.Conv2d', 'nn.Conv2d', (['hdim', 'num_tokens', '(1)'], {}), '(hdim, num_tokens, 1)\n', (876, 897), False, 'from torch import nn, einsum\n'), ((959, 1012), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['dim', 'hdim', '(4)'], {'stride': '(2)', 'padding': '(1)'}), '(dim, hdim, 4, stride=2, padding=1)\n', (977, 1012), False, 'from torch import nn, einsum\n'), ((1030, 1039), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (1037, 1039), False, 'from torch import nn, einsum\n'), ((1053, 1107), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['hdim', 'hdim', '(4)'], {'stride': '(2)', 'padding': '(1)'}), '(hdim, hdim, 4, stride=2, padding=1)\n', (1071, 1107), False, 'from torch import nn, einsum\n'), ((1125, 1134), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (1132, 1134), False, 'from torch import nn, einsum\n'), ((1148, 1202), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['hdim', 'hdim', '(4)'], {'stride': '(2)', 'padding': '(1)'}), '(hdim, hdim, 4, stride=2, padding=1)\n', (1166, 1202), False, 'from torch import nn, einsum\n'), ((1220, 1229), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (1227, 1229), False, 'from torch import nn, einsum\n'), ((1243, 1264), 'torch.nn.Conv2d', 'nn.Conv2d', (['hdim', '(3)', '(1)'], {}), '(hdim, 3, 1)\n', (1252, 1264), False, 'from torch import nn, einsum\n'), ((3029, 3071), 'torch.arange', 'torch.arange', (['text.shape[1]'], {'device': 'device'}), '(text.shape[1], device=device)\n', (3041, 3071), False, 'import torch\n'), ((3160, 3203), 'torch.arange', 'torch.arange', (['image.shape[1]'], {'device': 'device'}), '(image.shape[1], device=device)\n', (3172, 3203), False, 'import torch\n'), ((3560, 3614), 'torch.einsum', 'einsum', (['"""i d, j d -> i j"""', 'text_latents', 'image_latents'], {}), "('i d, j d -> i j', text_latents, image_latents)\n", (3566, 3614), False, 'from torch import nn, einsum\n'), ((4779, 4796), 'torch.nn.LayerNorm', 'nn.LayerNorm', (['dim'], {}), '(dim)\n', (4791, 4796), False, 'from torch import nn, einsum\n'), ((4810, 4843), 'torch.nn.Linear', 'nn.Linear', (['dim', 'self.total_tokens'], {}), '(dim, self.total_tokens)\n', (4819, 4843), False, 'from torch import nn, einsum\n'), ((5124, 5166), 'torch.arange', 'torch.arange', (['text.shape[1]'], {'device': 'device'}), '(text.shape[1], device=device)\n', (5136, 5166), False, 'import torch\n'), ((5570, 5613), 'torch.arange', 'torch.arange', (['image.shape[1]'], {'device': 'device'}), '(image.shape[1], device=device)\n', (5582, 5613), False, 'import torch\n'), ((5722, 5770), 'torch.nn.functional.pad', 'F.pad', (['mask', '(0, self.image_seq_len)'], {'value': '(True)'}), '(mask, (0, self.image_seq_len), value=True)\n', (5727, 5770), True, 'import torch.nn.functional as F\n')] |
"Test list input."
# For support of python 2.5
from __future__ import with_statement
import numpy as np
from numpy.testing import assert_equal, assert_array_almost_equal
import bottleneck as bn
# ---------------------------------------------------------------------------
# Check that functions can handle list input
def lists():
"Iterator that yields lists to use for unit testing."
ss = {}
ss[1] = {'size': 4, 'shapes': [(4,)]}
ss[2] = {'size': 6, 'shapes': [(1, 6), (2, 3)]}
ss[3] = {'size': 6, 'shapes': [(1, 2, 3)]}
ss[4] = {'size': 24, 'shapes': [(1, 2, 3, 4)]} # Unaccelerated
for ndim in ss:
size = ss[ndim]['size']
shapes = ss[ndim]['shapes']
a = np.arange(size)
for shape in shapes:
a = a.reshape(shape)
yield a.tolist()
def unit_maker(func, func0, args=tuple()):
"Test that bn.xxx gives the same output as bn.slow.xxx for list input."
msg = '\nfunc %s | input %s | shape %s\n'
msg += '\nInput array:\n%s\n'
for i, arr in enumerate(lists()):
argsi = tuple([list(arr)] + list(args))
actual = func(*argsi)
desired = func0(*argsi)
tup = (func.__name__, 'a'+str(i), str(np.array(arr).shape), arr)
err_msg = msg % tup
assert_array_almost_equal(actual, desired, err_msg=err_msg)
def test_nansum():
"Test nansum."
yield unit_maker, bn.nansum, bn.slow.nansum
def test_nanmax():
"Test nanmax."
yield unit_maker, bn.nanmax, bn.slow.nanmax
def test_nanargmin():
"Test nanargmin."
yield unit_maker, bn.nanargmin, bn.slow.nanargmin
def test_nanargmax():
"Test nanargmax."
yield unit_maker, bn.nanargmax, bn.slow.nanargmax
def test_nanmin():
"Test nanmin."
yield unit_maker, bn.nanmin, bn.slow.nanmin
def test_nanmean():
"Test nanmean."
yield unit_maker, bn.nanmean, bn.slow.nanmean
def test_nanstd():
"Test nanstd."
yield unit_maker, bn.nanstd, bn.slow.nanstd
def test_nanvar():
"Test nanvar."
yield unit_maker, bn.nanvar, bn.slow.nanvar
def test_median():
"Test median."
yield unit_maker, bn.median, bn.slow.median
def test_nanmedian():
"Test nanmedian."
yield unit_maker, bn.nanmedian, bn.slow.nanmedian
def test_rankdata():
"Test rankdata."
yield unit_maker, bn.rankdata, bn.slow.rankdata
def test_nanrankdata():
"Test nanrankdata."
yield unit_maker, bn.nanrankdata, bn.slow.nanrankdata
def test_partsort():
"Test partsort."
yield unit_maker, bn.partsort, bn.slow.partsort, (2,)
def test_argpartsort():
"Test argpartsort."
yield unit_maker, bn.argpartsort, bn.slow.argpartsort, (2,)
def test_ss():
"Test ss."
yield unit_maker, bn.ss, bn.slow.ss
def test_nn():
"Test nn."
a = [[1, 2], [3, 4]]
a0 = [1, 2]
assert_equal(bn.nn(a, a0), bn.slow.nn(a, a0))
def test_anynan():
"Test anynan."
yield unit_maker, bn.anynan, bn.slow.anynan
def test_allnan():
"Test allnan."
yield unit_maker, bn.allnan, bn.slow.allnan
def test_move_sum():
"Test move_sum."
yield unit_maker, bn.move_sum, bn.slow.move_sum, (2,)
def test_move_nansum():
"Test move_nansum."
yield unit_maker, bn.move_nansum, bn.slow.move_nansum, (2,)
def test_move_mean():
"Test move_mean."
yield unit_maker, bn.move_mean, bn.slow.move_mean, (2,)
def test_move_median():
"Test move_median."
yield unit_maker, bn.move_median, bn.slow.move_median, (2,)
def test_move_nanmean():
"Test move_nanmean."
yield unit_maker, bn.move_nanmean, bn.slow.move_nanmean, (2,)
def test_move_std():
"Test move_std."
yield unit_maker, bn.move_std, bn.slow.move_std, (2,)
def test_move_nanstd():
"Test move_nanstd."
yield unit_maker, bn.move_nanstd, bn.slow.move_nanstd, (2,)
def test_move_min():
"Test move_min."
yield unit_maker, bn.move_min, bn.slow.move_min, (2,)
def test_move_max():
"Test move_max."
yield unit_maker, bn.move_max, bn.slow.move_max, (2,)
def test_move_nanmin():
"Test move_nanmin."
yield unit_maker, bn.move_nanmin, bn.slow.move_nanmin, (2,)
def test_move_nanmax():
"Test move_nanmax."
yield unit_maker, bn.move_nanmax, bn.slow.move_nanmax, (2,)
| [
"numpy.testing.assert_array_almost_equal",
"bottleneck.slow.nn",
"numpy.array",
"numpy.arange",
"bottleneck.nn"
] | [((717, 732), 'numpy.arange', 'np.arange', (['size'], {}), '(size)\n', (726, 732), True, 'import numpy as np\n'), ((1282, 1341), 'numpy.testing.assert_array_almost_equal', 'assert_array_almost_equal', (['actual', 'desired'], {'err_msg': 'err_msg'}), '(actual, desired, err_msg=err_msg)\n', (1307, 1341), False, 'from numpy.testing import assert_equal, assert_array_almost_equal\n'), ((2844, 2856), 'bottleneck.nn', 'bn.nn', (['a', 'a0'], {}), '(a, a0)\n', (2849, 2856), True, 'import bottleneck as bn\n'), ((2858, 2875), 'bottleneck.slow.nn', 'bn.slow.nn', (['a', 'a0'], {}), '(a, a0)\n', (2868, 2875), True, 'import bottleneck as bn\n'), ((1219, 1232), 'numpy.array', 'np.array', (['arr'], {}), '(arr)\n', (1227, 1232), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Dataset',
fields=[
('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),
('state', models.CharField(choices=[('nc', 'North Carolina'), ('md', 'Maryland')], max_length=2)),
('name', models.CharField(unique=True, max_length=255)),
('date_added', models.DateTimeField(auto_now_add=True)),
('date_received', models.DateField()),
('url', models.URLField(unique=True, verbose_name='URL')),
('destination', models.CharField(blank=True, max_length=1024, help_text='Absolute path to destination directory (helpful for testing)')),
],
),
migrations.CreateModel(
name='Import',
fields=[
('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),
('date_started', models.DateTimeField(auto_now_add=True)),
('date_finished', models.DateTimeField(null=True)),
('successful', models.BooleanField(default=False)),
('dataset', models.ForeignKey(to='tsdata.Dataset')),
],
),
]
| [
"django.db.models.DateField",
"django.db.models.ForeignKey",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.DateTimeField",
"django.db.models.URLField",
"django.db.models.CharField"
] | [((299, 392), 'django.db.models.AutoField', 'models.AutoField', ([], {'primary_key': '(True)', 'auto_created': '(True)', 'verbose_name': '"""ID"""', 'serialize': '(False)'}), "(primary_key=True, auto_created=True, verbose_name='ID',\n serialize=False)\n", (315, 392), False, 'from django.db import migrations, models\n'), ((417, 507), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('nc', 'North Carolina'), ('md', 'Maryland')]", 'max_length': '(2)'}), "(choices=[('nc', 'North Carolina'), ('md', 'Maryland')],\n max_length=2)\n", (433, 507), False, 'from django.db import migrations, models\n'), ((531, 576), 'django.db.models.CharField', 'models.CharField', ([], {'unique': '(True)', 'max_length': '(255)'}), '(unique=True, max_length=255)\n', (547, 576), False, 'from django.db import migrations, models\n'), ((610, 649), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\n', (630, 649), False, 'from django.db import migrations, models\n'), ((686, 704), 'django.db.models.DateField', 'models.DateField', ([], {}), '()\n', (702, 704), False, 'from django.db import migrations, models\n'), ((731, 779), 'django.db.models.URLField', 'models.URLField', ([], {'unique': '(True)', 'verbose_name': '"""URL"""'}), "(unique=True, verbose_name='URL')\n", (746, 779), False, 'from django.db import migrations, models\n'), ((814, 938), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(1024)', 'help_text': '"""Absolute path to destination directory (helpful for testing)"""'}), "(blank=True, max_length=1024, help_text=\n 'Absolute path to destination directory (helpful for testing)')\n", (830, 938), False, 'from django.db import migrations, models\n'), ((1065, 1158), 'django.db.models.AutoField', 'models.AutoField', ([], {'primary_key': '(True)', 'auto_created': '(True)', 'verbose_name': '"""ID"""', 'serialize': '(False)'}), "(primary_key=True, auto_created=True, verbose_name='ID',\n serialize=False)\n", (1081, 1158), False, 'from django.db import migrations, models\n'), ((1190, 1229), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\n', (1210, 1229), False, 'from django.db import migrations, models\n'), ((1266, 1297), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'null': '(True)'}), '(null=True)\n', (1286, 1297), False, 'from django.db import migrations, models\n'), ((1331, 1365), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (1350, 1365), False, 'from django.db import migrations, models\n'), ((1396, 1434), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'to': '"""tsdata.Dataset"""'}), "(to='tsdata.Dataset')\n", (1413, 1434), False, 'from django.db import migrations, models\n')] |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('orgs', '0015_auto_20160209_0926'),
]
operations = [
migrations.CreateModel(
name='Contact',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('uuid', models.CharField(unique=True, max_length=36)),
('name', models.CharField(max_length=128, verbose_name='Name')),
('is_active', models.BooleanField(default=True)),
('org', models.ForeignKey(to='orgs.Org', on_delete=models.PROTECT)),
],
),
]
| [
"django.db.models.ForeignKey",
"django.db.models.AutoField",
"django.db.models.CharField",
"django.db.models.BooleanField"
] | [((279, 372), '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", (295, 372), False, 'from django.db import migrations, models\n'), ((396, 440), 'django.db.models.CharField', 'models.CharField', ([], {'unique': '(True)', 'max_length': '(36)'}), '(unique=True, max_length=36)\n', (412, 440), False, 'from django.db import migrations, models\n'), ((468, 521), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(128)', 'verbose_name': '"""Name"""'}), "(max_length=128, verbose_name='Name')\n", (484, 521), False, 'from django.db import migrations, models\n'), ((554, 587), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)'}), '(default=True)\n', (573, 587), False, 'from django.db import migrations, models\n'), ((614, 672), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'to': '"""orgs.Org"""', 'on_delete': 'models.PROTECT'}), "(to='orgs.Org', on_delete=models.PROTECT)\n", (631, 672), False, 'from django.db import migrations, models\n')] |
# -*- coding: utf-8 -*-
import sys
import argparse
arg_no = len(sys.argv)
tool_parser = argparse.ArgumentParser(add_help=False)
tool_subparsers = tool_parser.add_subparsers(help='commands', dest='command')
# The rename command.
rename_parser = tool_subparsers.add_parser('rename', help='rename an existing user account.')
rename_parser.add_argument(
'name', action='store', metavar='<name>', help='account name'
)
rename_parser.add_argument(
'--new-name', '-n', action='store', dest='newName', metavar='<new account name>'
)
# The add command.
add_parser = tool_subparsers.add_parser('add', help='add new user account to the directory.')
add_parser.add_argument(
'--type', '-t', action='store', default='generic', dest='account_type', metavar='<type of account>'
)
add_parser.add_argument(
'name', action='store', help='account name', metavar='<name>'
)
group1_parser = add_parser.add_argument_group('account specific')
group1_parser.add_argument(
'--password', '-P', action='store', dest='userPassword', metavar='<account\'s owner password>'
)
group1_parser.add_argument(
'--home', action='store', dest='homeDirectory', metavar='<path to the home directory>'
)
group1_parser.add_argument(
'--shell', action='store', dest='loginShell', metavar='<path to the shell interpreter>'
)
group1_parser = add_parser.add_argument_group('personal information')
group1_parser.add_argument(
'--phone-no', action='append', dest='telephoneNumber', metavar='<phone number>'
)
group1_parser.add_argument(
'--last-name', action='store', dest='sn', metavar='<account owner\'s last name>'
)
group1_parser.add_argument(
'--first-name', action='store', dest='givenName', metavar='<account owner\'s first name>'
)
group1_parser.add_argument(
'--organization', '-o', action='store', dest='o', metavar='<organization>'
)
group1_parser.add_argument(
'--email', action='append', dest='mail', metavar='<email>'
)
group1_parser.add_argument(
'--full-name', action='store', dest='cn', metavar='<account owner\'s full name>'
)
group1_parser = add_parser.add_argument_group('uid and group management')
group1_parser.add_argument(
'--uid', action='store', dest='uid', metavar='<user\'s uid>'
)
group1_parser.add_argument(
'--add-group', action='append', dest='group', metavar='<secondary group>'
)
group1_parser.add_argument(
'--uid-number', action='store', dest='uidNumber', metavar='<user id number>'
)
group1_parser.add_argument(
'--gid', action='store', dest='gidNumber', metavar='<primary group id>'
)
# The show command.
show_parser = tool_subparsers.add_parser('show', help='show account data')
show_parser.add_argument(
'name', action='append', nargs='*', help='account name'
)
show_parser.add_argument(
'--verbose', '-v', action='store_true', dest='verbose', help='be verbose about it'
)
# The edit command.
edit_parser = tool_subparsers.add_parser('edit', help='edit existing user data in the directory')
edit_parser.add_argument(
'--type', '-t', action='store', dest='account_type', metavar='<change account type>'
)
edit_parser.add_argument(
'name', action='store', help='account name'
)
group1_parser = edit_parser.add_argument_group('account specific')
group1_parser.add_argument(
'--reset-password', '-r', dest='resetPassword', action='store_true', help='<reset user\'s password>'
)
group1_parser.add_argument(
'--home', action='store', dest='homeDirectory', metavar='<new home directory path>'
)
group1_parser.add_argument(
'--shell', action='store', dest='loginShell', metavar='<new shell interpreter path>'
)
group1_parser = edit_parser.add_argument_group('personal information')
group1_parser.add_argument(
'--first-name', action='store', dest='givenName', metavar='<new first name>'
)
group1_parser.add_argument(
'--del-email', action='append', dest='delMail', metavar='<remove email address>'
)
group1_parser.add_argument(
'--last-name', action='store', dest='sn', metavar='<new last name>'
)
group1_parser.add_argument(
'--add-email', action='append', dest='addMail', metavar='<add new email address>'
)
group1_parser.add_argument(
'--del-phone-no', action='append', dest='delTelephoneNumber', metavar='<phone number to remove>'
)
group1_parser.add_argument(
'--organization', '-o', action='store', dest='o', metavar='<organization>'
)
group1_parser.add_argument(
'--add-phone-no', action='append', dest='addTelephoneNumber', metavar='<phone number to add>'
)
group1_parser.add_argument(
'--full-name', action='store', dest='cn', metavar='<new full name>'
)
group1_parser = edit_parser.add_argument_group('uid and group management')
group1_parser.add_argument(
'--del-group', action='append', dest='delgroup', metavar='<remove user from the group>'
)
group1_parser.add_argument(
'--group-id', action='store', dest='gidNumber', metavar='<change primary group ID>'
)
group1_parser.add_argument(
'--add-group', action='append', dest='addgroup', metavar='<add user to the group>'
)
group1_parser.add_argument(
'--uid-number', action='store', dest='uidNumber', metavar='<change user ID number>'
)
group1_parser.add_argument(
'--uid', action='store', dest='uid', metavar='<user\'s uid>'
)
# The retire command.
retire_parser = tool_subparsers.add_parser('retire', help='retire an existing account and remove all its privileges.')
retire_parser.add_argument(
'name', action='store', metavar='<name>', help='account name'
)
# The type command.
type_parser = tool_subparsers.add_parser('type', help='manage user types')
type_parser.add_argument(
'--list', '-l', action='store_true', dest='list_types', help='list user types'
)
# The remove command.
remove_parser = tool_subparsers.add_parser('remove', help='remove an existing account.')
remove_parser.add_argument(
'name', action='store', metavar='<name>', help='account name'
)
| [
"argparse.ArgumentParser"
] | [((91, 130), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'add_help': '(False)'}), '(add_help=False)\n', (114, 130), False, 'import argparse\n')] |
"""
Climate Platform Device for Wiser Smart
https://github.com/tomtomfx/wiserSmartForHA
<EMAIL>
"""
import asyncio
import logging
import voluptuous as vol
from functools import partial
from ruamel.yaml import YAML as yaml
from homeassistant.components.climate import ClimateEntity
from homeassistant.core import callback
from homeassistant.components.climate.const import (
SUPPORT_TARGET_TEMPERATURE,
ATTR_CURRENT_TEMPERATURE,
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
)
from homeassistant.const import (
ATTR_TEMPERATURE,
TEMP_CELSIUS,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import Entity
from .const import (
_LOGGER,
DOMAIN,
MANUFACTURER,
ROOM,
WISER_SMART_SERVICES,
)
SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Wiser climate device"""
data = hass.data[DOMAIN]
wiser_rooms = [
WiserSmartRoom(hass, data, room) for room in data.wiserSmart.getWiserRoomsThermostat()
]
async_add_entities(wiser_rooms, True)
""" Definition of WiserSmartRoom """
class WiserSmartRoom(ClimateEntity):
def __init__(self, hass, data, room_id):
"""Initialize the sensor."""
self.data = data
self.hass = hass
self.current_temp = None
self.target_temp = None
self.room_id = room_id
self._force_update = False
self._hvac_modes_list = [HVAC_MODE_HEAT, HVAC_MODE_OFF]
_LOGGER.info(
"WiserSmart Room: Initialisation for {}".format(self.room_id)
)
async def async_update(self):
_LOGGER.debug("WiserSmartRoom: Update requested for {}".format(self.name))
if self._force_update:
await self.data.async_update(no_throttle=True)
self._force_update = False
room = self.data.wiserSmart.getWiserRoomInfo(self.room_id)
self.current_temp = room.get("currentValue")
self.target_temp = room.get("targetValue")
if self.target_temp is None:
self.target_temp = -1
@property
def supported_features(self):
"""Return the list of supported features."""
return SUPPORT_FLAGS
@property
def should_poll(self):
return False
@property
def state(self):
room = self.data.wiserSmart.getWiserRoomInfo(self.room_id)
self.current_temp = room.get("currentValue")
self.target_temp = room.get("targetValue")
if self.target_temp is None:
self.target_temp = -1
if self.current_temp < self.target_temp:
state = HVAC_MODE_HEAT
else:
state = HVAC_MODE_OFF
return state
@property
def name(self):
return "WiserSmart - Thermostat - " + self.room_id
@property
def temperature_unit(self):
return TEMP_CELSIUS
@property
def min_temp(self):
return self.data.minimum_temp
@property
def max_temp(self):
return self.data.maximum_temp
@property
def current_temperature(self):
temp = self.data.wiserSmart.getWiserRoomInfo(self.room_id).get("currentValue")
return temp
@property
def icon(self):
# Change icon to show if radiator is heating, not heating or set to off.
room = self.data.wiserSmart.getWiserRoomInfo(self.room_id)
self.current_temp = room.get("currentValue")
self.target_temp = room.get("targetValue")
if self.target_temp is None:
self.target_temp = -1
if self.current_temp < self.target_temp:
return "mdi:radiator"
else:
return "mdi:radiator-off"
@property
def unique_id(self):
return "WiserSmartRoom - {}".format(self.room_id)
@property
def device_info(self):
"""Return device specific attributes."""
return {
"name": self.name,
"identifiers": {(DOMAIN, self.unique_id)},
"manufacturer": MANUFACTURER,
"model": "Wiser Smart Room",
}
@property
def hvac_mode(self):
state = self.state()
return state
@property
def hvac_modes(self):
"""Return the list of available operation modes."""
return self._hvac_modes_list
@property
def target_temperature(self):
return self.data.wiserSmart.getWiserRoomInfo(self.room_id).get("targetValue")
@property
def state_attributes(self):
"""Return state attributes."""
# Generic attributes
attrs = super().state_attributes
# If VACT return valves infos
i = 1
valves = self.data.wiserSmart.getWiserRoomInfo(self.room_id).get("valve")
if (valves == None):
return attrs
for valve in valves:
attrs["valvePosition_" + str(i)] = valve.get("valvePosition")
attrs["calibrationStatus_" + str(i)] = valve.get("calibrationStatus")
attrs["internalTemp_" + str(i)] = valve.get("internalTemp")
i = i + 1
return attrs
async def async_set_temperature(self, **kwargs):
"""Set new target temperatures."""
target_temperature = kwargs.get(ATTR_TEMPERATURE)
if target_temperature is None:
_LOGGER.debug(
"No target temperature set for {}".format(self.name)
)
return False
_LOGGER.debug(
"Setting temperature for {} to {}".format(self.name, target_temperature)
)
await self.hass.async_add_executor_job(
partial(self.data.wiserSmart.setWiserRoomTemp, self.room_id, target_temperature)
)
self._force_update = True
await self.async_update_ha_state(True)
return True
async def async_added_to_hass(self):
"""Subscribe for update from the Controller"""
async def async_update_state():
"""Update sensor state."""
await self.async_update_ha_state(True)
async_dispatcher_connect(self.hass, "WiserSmartUpdateMessage", async_update_state)
| [
"functools.partial",
"homeassistant.helpers.dispatcher.async_dispatcher_connect"
] | [((6136, 6222), 'homeassistant.helpers.dispatcher.async_dispatcher_connect', 'async_dispatcher_connect', (['self.hass', '"""WiserSmartUpdateMessage"""', 'async_update_state'], {}), "(self.hass, 'WiserSmartUpdateMessage',\n async_update_state)\n", (6160, 6222), False, 'from homeassistant.helpers.dispatcher import async_dispatcher_connect\n'), ((5706, 5791), 'functools.partial', 'partial', (['self.data.wiserSmart.setWiserRoomTemp', 'self.room_id', 'target_temperature'], {}), '(self.data.wiserSmart.setWiserRoomTemp, self.room_id, target_temperature\n )\n', (5713, 5791), False, 'from functools import partial\n')] |
import os
from functools import partial
from multiprocessing import Pool
from typing import Any, Callable, Dict, List, Optional
import numpy as np
import pandas as pd
from tqdm import tqdm
from src.dataset.utils.waveform_preprocessings import preprocess_strain
def id_2_path(
image_id: str,
is_train: bool = True,
data_dir: str = "../input/g2net-gravitational-wave-detection",
) -> str:
"""
modify from https://www.kaggle.com/ihelon/g2net-eda-and-modeling
"""
folder = "train" if is_train else "test"
return "{}/{}/{}/{}/{}/{}.npy".format(
data_dir, folder, image_id[0], image_id[1], image_id[2], image_id
)
def path_2_id(path: str) -> str:
return os.path.basename(path).replace(".npy", "")
def add_dir(df: pd.DataFrame) -> pd.DataFrame:
df["top_dir"] = df["id"].apply(lambda x: x[0])
df["bottom_dir"] = df["id"].apply(lambda x: x[:3])
return df
def add_data_path(
df: pd.DataFrame,
is_train: bool = False,
data_dir: str = "../input/g2net-gravitational-wave-detection",
) -> pd.DataFrame:
df = add_dir(df=df)
df["path"] = df["id"].apply(
lambda x: id_2_path(image_id=x, is_train=is_train, data_dir=data_dir)
)
return df
def get_agg_feats(
path: str,
interp_psd: Optional[Callable] = None,
psds: Optional[np.ndarray] = None,
window: str = "tukey",
fs: int = 2048,
fband: List[int] = [10, 912],
psd_cache_path_suffix: Optional[str] = None,
T: float = 2.0,
) -> Dict[str, Any]:
sample_data = np.load(path)
data_id = path_2_id(path)
if interp_psd is None:
for i, strain in enumerate(sample_data):
_, strain_bp = preprocess_strain(
strain=strain,
interp_psd=interp_psd,
psd=psds[i],
window=window,
fs=fs,
fband=fband,
)
sample_data[i] = strain_bp
mean = sample_data.mean(axis=-1)
std = sample_data.std(axis=-1)
minim = sample_data.min(axis=-1)
maxim = sample_data.max(axis=-1)
ene = (sample_data ** 2).sum(axis=-1)
agg_dict = {
"id": data_id,
"mean_site0": mean[0],
"mean_site1": mean[1],
"mean_site2": mean[2],
"std_site0": std[0],
"std_site1": std[1],
"std_site2": std[2],
"min_site0": minim[0],
"min_site1": minim[1],
"min_site2": minim[2],
"max_site0": maxim[0],
"max_site1": maxim[1],
"max_site2": maxim[2],
"ene_site0": ene[0],
"ene_site1": ene[1],
"ene_site2": ene[2],
}
if psd_cache_path_suffix is not None:
cache_path = path.replace(".npy", psd_cache_path_suffix)
if os.path.exists(cache_path):
psd = np.load(cache_path)
psd_ranges = [10, 35, 350, 500, 912]
psd_hz_begin = 0
for psd_hz_end in psd_ranges:
psd_mean = psd[:, int(psd_hz_begin * T) : int(psd_hz_end * T)].mean(
axis=-1
)
for site_id, psd_mean_for_site in enumerate(psd_mean):
agg_dict[
f"psd_{psd_hz_begin}-{psd_hz_end}hz_site{site_id}"
] = psd_mean_for_site
psd_hz_begin = psd_hz_end
for site_id, psd_mean_for_site in enumerate(psd.mean(axis=-1)):
agg_dict[f"psd_all-hz_site{site_id}"] = psd_mean_for_site
return agg_dict
def get_site_metrics(
df: pd.DataFrame,
interp_psd: Optional[Callable] = None,
psds: Optional[np.ndarray] = None,
window: str = "tukey",
fs: int = 2048,
fband: List[int] = [10, 912],
psd_cache_path_suffix: Optional[str] = None,
num_workers: int = 8,
):
"""
Compute for each id the metrics for each site.
df: the complete df
modify from
https://www.kaggle.com/andradaolteanu/g2net-searching-the-sky-pytorch-effnet-w-meta
"""
func_ = partial(
get_agg_feats,
interp_psd=interp_psd,
psds=psds,
window=window,
fs=fs,
fband=fband,
psd_cache_path_suffix=psd_cache_path_suffix,
)
if num_workers > 1:
with Pool(processes=num_workers) as pool:
agg_dicts = list(
tqdm(
pool.imap(func_, df["path"].tolist()),
total=len(df),
)
)
else:
agg_dicts = []
for ID, path in tqdm(zip(df["id"].values, df["path"].values)):
# First extract the cronological info
agg_dict = func_(path=path)
agg_dicts.append(agg_dict)
agg_df = pd.DataFrame(agg_dicts)
df = pd.merge(df, agg_df, on="id")
return df
| [
"os.path.exists",
"src.dataset.utils.waveform_preprocessings.preprocess_strain",
"pandas.merge",
"functools.partial",
"os.path.basename",
"multiprocessing.Pool",
"pandas.DataFrame",
"numpy.load"
] | [((1533, 1546), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (1540, 1546), True, 'import numpy as np\n'), ((3986, 4127), 'functools.partial', 'partial', (['get_agg_feats'], {'interp_psd': 'interp_psd', 'psds': 'psds', 'window': 'window', 'fs': 'fs', 'fband': 'fband', 'psd_cache_path_suffix': 'psd_cache_path_suffix'}), '(get_agg_feats, interp_psd=interp_psd, psds=psds, window=window, fs=\n fs, fband=fband, psd_cache_path_suffix=psd_cache_path_suffix)\n', (3993, 4127), False, 'from functools import partial\n'), ((4686, 4709), 'pandas.DataFrame', 'pd.DataFrame', (['agg_dicts'], {}), '(agg_dicts)\n', (4698, 4709), True, 'import pandas as pd\n'), ((4720, 4749), 'pandas.merge', 'pd.merge', (['df', 'agg_df'], {'on': '"""id"""'}), "(df, agg_df, on='id')\n", (4728, 4749), True, 'import pandas as pd\n'), ((2741, 2767), 'os.path.exists', 'os.path.exists', (['cache_path'], {}), '(cache_path)\n', (2755, 2767), False, 'import os\n'), ((702, 724), 'os.path.basename', 'os.path.basename', (['path'], {}), '(path)\n', (718, 724), False, 'import os\n'), ((1680, 1788), 'src.dataset.utils.waveform_preprocessings.preprocess_strain', 'preprocess_strain', ([], {'strain': 'strain', 'interp_psd': 'interp_psd', 'psd': 'psds[i]', 'window': 'window', 'fs': 'fs', 'fband': 'fband'}), '(strain=strain, interp_psd=interp_psd, psd=psds[i], window\n =window, fs=fs, fband=fband)\n', (1697, 1788), False, 'from src.dataset.utils.waveform_preprocessings import preprocess_strain\n'), ((2787, 2806), 'numpy.load', 'np.load', (['cache_path'], {}), '(cache_path)\n', (2794, 2806), True, 'import numpy as np\n'), ((4224, 4251), 'multiprocessing.Pool', 'Pool', ([], {'processes': 'num_workers'}), '(processes=num_workers)\n', (4228, 4251), False, 'from multiprocessing import Pool\n')] |
#!/usr/bin/env python3
import os
import boto3
import botocore.exceptions
import argparse
import yaml
from nephele2 import NepheleError
mand_vars = ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY']
perm_error = """\n\nIt seems you have not set up your AWS correctly.
Should you be running this with Awssume? Or have profile with appropriate role?
Exiting now.\n"""
def main(args):
"""Launch ec2 instance"""
if args.profile is None:
ec2_resource = boto3.Session(region_name='us-east-1').resource('ec2')
else:
ec2_resource = boto3.Session(region_name='us-east-1', profile_name=args.profile).resource('ec2')
test_sanity(ec2_resource, args)
envs = load_stack_vars(args.yaml_env.name)
start_EC2(ec2_resource, args.ami_id, args.instance_type,
args.key_path, args.label, envs, args.dry_run)
def load_stack_vars(fname):
try:
with open(fname) as f:
data_map = yaml.safe_load(f)
return data_map
except FileNotFoundError as fnf:
print(fnf)
print('Unable to find yaml file, exiting.')
exit(1)
except:
raise
def gen_mnt_str(efs_ip):
mnt_opts = 'nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport' # from AWS
return 'mount -t nfs -o {opts} {trgt}:/ {mnt}/'.format(opts=mnt_opts,
trgt=efs_ip,
mnt='/mnt/EFS')
def read_key(key_path):
try:
with open(key_path, 'r') as f:
key = f.read()
return key
except:
raise
def test_sanity(ec2_resource, args):
"""Test if env vars are set, key exists, and can access ec2"""
if args.profile is None:
for var in mand_vars:
if os.environ.get(var) is None:
print(var + ' must be set as an evironment variable. \nExiting.')
exit(1)
if not os.path.exists(args.key_path):
print('Unable to see your key: {}, exiting now :-('.format(args.key_path))
exit(1)
try:
ec2_resource.instances.all().__iter__().__next__()
except botocore.exceptions.ClientError as expn:
print(expn)
print(perm_error)
exit(1)
def create_EC2(ec2_resource, ami_id, i_type, envs, u_data='', dry_run=True):
"""create ec2 instance. by default DryRun is T, and only checks perms."""
inst = ec2_resource.create_instances(
DryRun=dry_run,
SecurityGroupIds=[envs['INTERNAL_SECURITY_GROUP'],
envs['ecs_cluster_security_group_id']],
IamInstanceProfile={'Arn': envs['N2_WORKER_INSTANCE_PROFILE']},
InstanceType=i_type,
ImageId=ami_id,
MinCount=1,
MaxCount=1,
InstanceInitiatedShutdownBehavior='terminate',
SubnetId=envs['VPC_SUBNET'],
UserData=u_data
)
return inst
def start_EC2(ec2_resource, ami_id, i_type, key_path, label, envs, dry_run):
"""check if have perms to create instance.
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/ec2-example-managing-instances.html#start-and-stop-instances
if so, the create instance and tag with label.
"""
try:
create_EC2(ec2_resource, ami_id, i_type, envs)
except botocore.exceptions.ClientError as e:
if 'DryRunOperation' not in str(e):
print(e.response['Error']['Message'])
print(perm_error)
exit(1)
elif dry_run:
print(e.response['Error']['Message'])
exit(0)
else:
pass
mnt_str = gen_mnt_str(envs['EFS_IP'])
key_str = read_key(key_path)
auth_key_str = 'printf "{}" >> /home/admin/.ssh/authorized_keys;'.format(
key_str)
u_data = '#!/bin/bash\n{mnt_str}\n{auth_key_str}\n'.format(mnt_str=mnt_str,
auth_key_str=auth_key_str)
print('Creating EC2...')
try:
instances = create_EC2(ec2_resource, ami_id, i_type, envs, u_data, False)
except botocore.exceptions.ClientError as bce:
print(bce)
print('\nUnable to launch EC2. \nExiting.')
exit(1)
if len(instances) is not 1:
msg = 'Instances launched: %s' % str(instances)
raise NepheleError.UnableToStartEC2Exception(msg=msg)
instance = instances[0]
instance.wait_until_running()
instance.create_tags(Tags=[{'Key': 'Name', 'Value': label}])
print(str(instance) + ' has been created.')
print('To connect type:\nssh {ip_addr}'.format(
ip_addr=instance.instance_id))
print('To terminate instance type:')
print('awssume aws ec2 terminate-instances --instance-ids ' + instance.instance_id)
if __name__ == "__main__":
usage = 'Eg:\nsource ~/code/neph2-envs/dev/environment_vars\n'\
'awssume launch_ec2.py -e ../../neph2-envs/dev/dev_outputs.yaml -a ami-0ae1b7201f4a236f9 -t m5.4xlarge -k ~/.ssh/id_rsa.pub --label instance_name_tag\n\n'\
'Alternately, pass profile which has correct role/permissions:\n'\
'launch_ec2.py -e dev_outputs.yaml -a ami-003eed27e5bf2ef91 -t t2.micro -k ~/.ssh/id_rsa.pub -l name_tag --profile aws_profile_name'
parser = argparse.ArgumentParser(
description='CLI Interface to N2.', usage=usage)
req = parser.add_argument_group('required args')
req.add_argument("-e", "--yaml_env",
type=argparse.FileType('r'), required=True)
req.add_argument("-t", "--instance_type", type=str, required=True)
req.add_argument("-a", "--ami_id", type=str, required=True)
req.add_argument("-k", "--key_path", type=str, required=True)
req.add_argument("-l", "--label", type=str, required=True)
parser.add_argument("-p", "--profile", type=str)
parser.add_argument("-d", "--dry_run", action='store_true')
args = parser.parse_args()
main(args)
| [
"os.path.exists",
"argparse.FileType",
"argparse.ArgumentParser",
"boto3.Session",
"os.environ.get",
"yaml.safe_load",
"nephele2.NepheleError.UnableToStartEC2Exception"
] | [((5309, 5381), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""CLI Interface to N2."""', 'usage': 'usage'}), "(description='CLI Interface to N2.', usage=usage)\n", (5332, 5381), False, 'import argparse\n'), ((1955, 1984), 'os.path.exists', 'os.path.exists', (['args.key_path'], {}), '(args.key_path)\n', (1969, 1984), False, 'import os\n'), ((4364, 4411), 'nephele2.NepheleError.UnableToStartEC2Exception', 'NepheleError.UnableToStartEC2Exception', ([], {'msg': 'msg'}), '(msg=msg)\n', (4402, 4411), False, 'from nephele2 import NepheleError\n'), ((935, 952), 'yaml.safe_load', 'yaml.safe_load', (['f'], {}), '(f)\n', (949, 952), False, 'import yaml\n'), ((5514, 5536), 'argparse.FileType', 'argparse.FileType', (['"""r"""'], {}), "('r')\n", (5531, 5536), False, 'import argparse\n'), ((467, 505), 'boto3.Session', 'boto3.Session', ([], {'region_name': '"""us-east-1"""'}), "(region_name='us-east-1')\n", (480, 505), False, 'import boto3\n'), ((555, 620), 'boto3.Session', 'boto3.Session', ([], {'region_name': '"""us-east-1"""', 'profile_name': 'args.profile'}), "(region_name='us-east-1', profile_name=args.profile)\n", (568, 620), False, 'import boto3\n'), ((1809, 1828), 'os.environ.get', 'os.environ.get', (['var'], {}), '(var)\n', (1823, 1828), False, 'import os\n')] |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 27 18:16:24 2015
@author: <NAME>
A raíz del cambio previsto:
DESCONEXIÓN DE LA WEB PÚBLICA CLÁSICA DE E·SIOS
La Web pública clásica de e·sios (http://www.esios.ree.es) será desconectada el día 29 de marzo de 2016.
Continuaremos ofreciendo servicio en la nueva Web del Operador del Sistema:
https://www.esios.ree.es.
Por favor, actualice sus favoritos apuntando a la nueva Web.
IMPORTANTE!!!
En la misma fecha (29/03/2016), también dejará de funcionar el servicio Solicitar y Descargar,
utilizado para descargar información de la Web pública clásica de e·sios.
Por favor, infórmese sobre descarga de información en
https://www.esios.ree.es/es/pagina/api
y actualice sus procesos de descarga.
"""
import json
import pandas as pd
import re
from dataweb.requestweb import get_data_en_intervalo
from esiosdata.esios_config import DATE_FMT, TZ, SERVER, HEADERS, D_TIPOS_REQ_DEM, KEYS_DATA_DEM
from esiosdata.prettyprinting import print_redb, print_err
__author__ = '<NAME>'
__copyright__ = "Copyright 2015, AzogueLabs"
__credits__ = ["<NAME>"]
__license__ = "GPL"
__version__ = "1.0"
__maintainer__ = "<NAME>"
RG_FUNC_CONTENT = re.compile('(?P<func>.*)\((?P<json>.*)\);')
def dem_url_dia(dt_day='2015-06-22'):
"""Obtiene las urls de descarga de los datos de demanda energética de un día concreto."""
def _url_tipo_dato(str_dia, k):
url = SERVER + '/archives/{}/download_json?locale=es'.format(D_TIPOS_REQ_DEM[k])
if type(str_dia) is str:
return url + '&date=' + str_dia
else:
return url + '&date=' + str_dia.date().isoformat()
urls = [_url_tipo_dato(dt_day, k) for k in D_TIPOS_REQ_DEM.keys()]
return urls
def _extract_func_json_data(data_raw):
try:
busca = RG_FUNC_CONTENT.match(data_raw).groupdict()
ind, data = busca['func'], None
data = json.loads(busca['json'])
if len(data.keys()) == 1:
return ind, data[list(data.keys())[0]]
else:
return ind, data
except AttributeError:
# print('ERROR REG_EXP [{}] --> RAW: {}'.format(e, data_raw))
return None, None
def _import_daily_max_min(data):
# IND_MaxMinRenovEol / IND_MaxMin
df = pd.DataFrame(data, index=[0])
cols_ts = df.columns.str.startswith('ts')
is_max_min_renov = any(cols_ts)
if is_max_min_renov:
df.index = pd.DatetimeIndex([pd.Timestamp(df['tsMaxRenov'][0]).date()], freq='D')
else:
df = pd.DataFrame(df.set_index(pd.DatetimeIndex([pd.Timestamp(df['date'][0]).date()], freq='D')
).drop('date', axis=1))
cols_ts = df.columns.str.contains('timeStamp', regex=False)
for c, is_ts in zip(df.columns, cols_ts):
if is_ts:
df[c] = df[c].apply(pd.Timestamp)
else:
df[c] = df[c].astype(float)
return df
def _import_json_ts_data(data):
df = pd.DataFrame(data)
try:
return pd.DataFrame(df.set_index(pd.DatetimeIndex(df['ts'].apply(lambda x: pd.Timestamp(x, tz=TZ)),
freq='10T', tz=TZ), verify_integrity=True
).drop('ts', axis=1)).sort_index().applymap(float)
except ValueError: # ES DST
df['ts'] = pd.DatetimeIndex(start=pd.Timestamp(df['ts'].iloc[0]), periods=len(df), freq='10T', tz=TZ)
# , ambiguous="infer")
return df.set_index('ts', verify_integrity=True).sort_index().applymap(float)
def dem_procesa_datos_dia(key_day, response):
"""Procesa los datos descargados en JSON."""
dfs_import, df_import, dfs_maxmin, hay_errores = [], None, [], 0
for r in response:
tipo_datos, data = _extract_func_json_data(r)
if tipo_datos is not None:
if ('IND_MaxMin' in tipo_datos) and data:
df_import = _import_daily_max_min(data)
dfs_maxmin.append(df_import)
elif data:
df_import = _import_json_ts_data(data)
dfs_import.append(df_import)
if tipo_datos is None or df_import is None:
hay_errores += 1
if hay_errores == 4:
# No hay nada, salida temprana sin retry:
print_redb('** No hay datos para el día {}!'.format(key_day))
return None, -2
else: # if hay_errores < 3:
# TODO formar datos incompletos!! (max-min con NaN's, etc.)
data_import = {}
if dfs_import:
data_import[KEYS_DATA_DEM[0]] = dfs_import[0].join(dfs_import[1])
if len(dfs_maxmin) == 2:
data_import[KEYS_DATA_DEM[1]] = dfs_maxmin[0].join(dfs_maxmin[1])
elif dfs_maxmin:
data_import[KEYS_DATA_DEM[1]] = dfs_maxmin[0]
if not data_import:
print_err('DÍA: {} -> # ERRORES: {}'.format(key_day, hay_errores))
return None, -2
return data_import, 0
def dem_data_dia(str_dia='2015-10-10', str_dia_fin=None):
"""Obtiene datos de demanda energética en un día concreto o un intervalo, accediendo directamente a la web."""
params = {'date_fmt': DATE_FMT, 'usar_multithread': False, 'num_retries': 1, "timeout": 10,
'func_procesa_data_dia': dem_procesa_datos_dia, 'func_url_data_dia': dem_url_dia,
'data_extra_request': {'json_req': False, 'headers': HEADERS}}
if str_dia_fin is not None:
params['usar_multithread'] = True
data, hay_errores, str_import = get_data_en_intervalo(str_dia, str_dia_fin, **params)
else:
data, hay_errores, str_import = get_data_en_intervalo(str_dia, str_dia, **params)
if not hay_errores:
return data
else:
print_err(str_import)
return None
| [
"json.loads",
"esiosdata.prettyprinting.print_err",
"re.compile",
"dataweb.requestweb.get_data_en_intervalo",
"pandas.DataFrame",
"pandas.Timestamp",
"esiosdata.esios_config.D_TIPOS_REQ_DEM.keys"
] | [((1184, 1229), 're.compile', 're.compile', (['"""(?P<func>.*)\\\\((?P<json>.*)\\\\);"""'], {}), "('(?P<func>.*)\\\\((?P<json>.*)\\\\);')\n", (1194, 1229), False, 'import re\n'), ((2254, 2283), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {'index': '[0]'}), '(data, index=[0])\n', (2266, 2283), True, 'import pandas as pd\n'), ((2947, 2965), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (2959, 2965), True, 'import pandas as pd\n'), ((1895, 1920), 'json.loads', 'json.loads', (["busca['json']"], {}), "(busca['json'])\n", (1905, 1920), False, 'import json\n'), ((5485, 5538), 'dataweb.requestweb.get_data_en_intervalo', 'get_data_en_intervalo', (['str_dia', 'str_dia_fin'], {}), '(str_dia, str_dia_fin, **params)\n', (5506, 5538), False, 'from dataweb.requestweb import get_data_en_intervalo\n'), ((5589, 5638), 'dataweb.requestweb.get_data_en_intervalo', 'get_data_en_intervalo', (['str_dia', 'str_dia'], {}), '(str_dia, str_dia, **params)\n', (5610, 5638), False, 'from dataweb.requestweb import get_data_en_intervalo\n'), ((5701, 5722), 'esiosdata.prettyprinting.print_err', 'print_err', (['str_import'], {}), '(str_import)\n', (5710, 5722), False, 'from esiosdata.prettyprinting import print_redb, print_err\n'), ((1690, 1712), 'esiosdata.esios_config.D_TIPOS_REQ_DEM.keys', 'D_TIPOS_REQ_DEM.keys', ([], {}), '()\n', (1710, 1712), False, 'from esiosdata.esios_config import DATE_FMT, TZ, SERVER, HEADERS, D_TIPOS_REQ_DEM, KEYS_DATA_DEM\n'), ((3350, 3380), 'pandas.Timestamp', 'pd.Timestamp', (["df['ts'].iloc[0]"], {}), "(df['ts'].iloc[0])\n", (3362, 3380), True, 'import pandas as pd\n'), ((2428, 2461), 'pandas.Timestamp', 'pd.Timestamp', (["df['tsMaxRenov'][0]"], {}), "(df['tsMaxRenov'][0])\n", (2440, 2461), True, 'import pandas as pd\n'), ((2548, 2575), 'pandas.Timestamp', 'pd.Timestamp', (["df['date'][0]"], {}), "(df['date'][0])\n", (2560, 2575), True, 'import pandas as pd\n'), ((3058, 3080), 'pandas.Timestamp', 'pd.Timestamp', (['x'], {'tz': 'TZ'}), '(x, tz=TZ)\n', (3070, 3080), True, 'import pandas as pd\n')] |
#!#!/usr/bin/env python
import os
from github import Github
from libraries.notify import Notify
import json
print("")
print("Scanning Github repos")
GITHUB_API_KEY = os.environ.get('GITHUB_API_KEY')
WHITELIST = json.loads(os.environ.get('GITHUB_WHITELIST').lower())
GITHUB_SCAN = json.loads(os.environ.get('GITHUB_SCAN'))
SENDGRID_API_KEY = os.environ.get('SENDGRID_API_KEY')
SENDGRID_FROM = os.environ.get('SENDGRID_FROM')
SENDGRID_SUBJECT = os.environ.get('SENDGRID_SUBJECT')
SENDGRID_TEMPLATE = os.environ.get('SENDGRID_TEMPLATE')
SENDGRID_NOTIFY = json.loads(os.environ.get('SENDGRID_NOTIFY'))
results = []
print(" Target: {}".format(GITHUB_SCAN))
print(" Github:{}".format(len(GITHUB_API_KEY[:-4])*"#"+GITHUB_API_KEY[-4:]))
print(" Whitelist: {}".format(WHITELIST))
print("")
def load_template(_file):
try:
with open(_file) as f:
# print(f.readlines())
return f.readlines()
except IOError:
print("Template file not accessible")
# or using an access token
g = Github(GITHUB_API_KEY)
for ITEM in GITHUB_SCAN:
print("Checking {}".format(ITEM))
for repo in g.get_user(ITEM).get_repos():
if repo.name.lower() in WHITELIST:
print(" [-] {}".format(repo.name))
# commits = repo.get_commits()
# for com in commits:
# print(com)
else:
print(" [+] {}".format(repo.name))
results.append("{}/{}".format(ITEM,repo.name))
if results:
print("FOUND NEW REPOs!!! SENDING EMAIL!!!")
#exit()
notify = Notify(SENDGRID_API_KEY)
notify.add_from(SENDGRID_FROM)
notify.add_mailto(SENDGRID_NOTIFY)
notify.add_subject(SENDGRID_SUBJECT)
notify.add_content_html(load_template(SENDGRID_TEMPLATE))
notify.update_content_html("<!--RESULTS-->", results)
notify.send_mail()
else:
print("Nothing found, going to sleep")
| [
"libraries.notify.Notify",
"os.environ.get",
"github.Github"
] | [((168, 200), 'os.environ.get', 'os.environ.get', (['"""GITHUB_API_KEY"""'], {}), "('GITHUB_API_KEY')\n", (182, 200), False, 'import os\n'), ((343, 377), 'os.environ.get', 'os.environ.get', (['"""SENDGRID_API_KEY"""'], {}), "('SENDGRID_API_KEY')\n", (357, 377), False, 'import os\n'), ((394, 425), 'os.environ.get', 'os.environ.get', (['"""SENDGRID_FROM"""'], {}), "('SENDGRID_FROM')\n", (408, 425), False, 'import os\n'), ((445, 479), 'os.environ.get', 'os.environ.get', (['"""SENDGRID_SUBJECT"""'], {}), "('SENDGRID_SUBJECT')\n", (459, 479), False, 'import os\n'), ((500, 535), 'os.environ.get', 'os.environ.get', (['"""SENDGRID_TEMPLATE"""'], {}), "('SENDGRID_TEMPLATE')\n", (514, 535), False, 'import os\n'), ((1018, 1040), 'github.Github', 'Github', (['GITHUB_API_KEY'], {}), '(GITHUB_API_KEY)\n', (1024, 1040), False, 'from github import Github\n'), ((293, 322), 'os.environ.get', 'os.environ.get', (['"""GITHUB_SCAN"""'], {}), "('GITHUB_SCAN')\n", (307, 322), False, 'import os\n'), ((565, 598), 'os.environ.get', 'os.environ.get', (['"""SENDGRID_NOTIFY"""'], {}), "('SENDGRID_NOTIFY')\n", (579, 598), False, 'import os\n'), ((1553, 1577), 'libraries.notify.Notify', 'Notify', (['SENDGRID_API_KEY'], {}), '(SENDGRID_API_KEY)\n', (1559, 1577), False, 'from libraries.notify import Notify\n'), ((224, 258), 'os.environ.get', 'os.environ.get', (['"""GITHUB_WHITELIST"""'], {}), "('GITHUB_WHITELIST')\n", (238, 258), False, 'import os\n')] |
from flask.ext.sqlalchemy import SQLAlchemy
from util import hex_to_rgb, rgb_to_hex
from time2words import relative_time_to_text
from datetime import datetime
from dateutil.tz import tzutc
import pytz
db = SQLAlchemy()
def created_on_default():
return datetime.utcnow()
class Counter(db.Model):
__tablename__ = 'counters'
id = db.Column(db.Integer, primary_key=True)
created_on = db.Column(db.DateTime, default=created_on_default)
updated_on = db.Column(
db.DateTime, default=created_on_default, onupdate=created_on_default)
time = db.Column(db.DateTime)
text_after = db.Column(db.String())
text_before = db.Column(db.String())
theme = db.Column(
db.Enum('simple', 'trip', name='themes'), default='simple')
url = db.Column(db.String, unique=True)
secret = db.Column(db.String)
# Foreign keys
trip_theme = db.relationship(
'TripTheme', backref='counter', lazy='joined', uselist=False)
def __repr__(self):
return '<Counter (id: {0}, time:{1})>'.format(self.id, self.time)
def time_left_in_text(self):
time_in_seconds = int((self.time.replace(tzinfo=pytz.utc)
- datetime.utcnow().replace(tzinfo=pytz.utc)).total_seconds())
return relative_time_to_text(seconds=abs(time_in_seconds))
def has_passed(self):
return self.time.replace(tzinfo=pytz.utc) < datetime.utcnow().replace(tzinfo=pytz.utc)
def full_text(self):
full_text_list = []
if self.has_passed():
full_text_list = [self.time_left_in_text(), "ago"]
else:
if len(self.text_before) > 0:
full_text_list.append(self.text_before)
full_text_list.append(self.time_left_in_text())
if len(self.text_after) > 0:
full_text_list.append(self.text_after)
full_text = " ".join(full_text_list)
full_text = full_text[0].upper() + full_text[1:]
return full_text
def to_dict(self, just_created=False):
data = {
'id': self.id,
'created_on': self.created_on,
'updated_on': self.updated_on,
'time': self.time,
'text_after': self.text_after,
'text_before': self.text_before,
'full_text': self.full_text(),
'url': self.url,
'theme': self.theme
}
if self.theme == 'trip':
data['city_origin'] = self.trip_theme.origin
data['city_destination'] = self.trip_theme.destination
if just_created:
data['secret'] = self.secret
return data
def to_json(self):
return jsonify(self.to_dict())
class TripTheme(db.Model):
__tablename__ = 'trip_themes'
id = db.Column(db.Integer, primary_key=True)
created_on = db.Column(db.DateTime, default=created_on_default)
updated_on = db.Column(
db.DateTime, default=created_on_default, onupdate=created_on_default)
origin = db.Column(db.String(255), nullable=False)
destination = db.Column(db.String(255), nullable=False)
# Relationships
counter_id = db.Column(
db.Integer, db.ForeignKey('counters.id'), nullable=False)
def to_dict(self):
data = {
'origin': self.origin,
'destination': self.destination
}
return data
def get_or_create(session, model, **kwargs):
instance = session.query(model).filter_by(**kwargs).first()
if instance:
return instance
else:
instance = model(**kwargs)
session.add(instance)
session.commit()
return instance
| [
"flask.ext.sqlalchemy.SQLAlchemy",
"datetime.datetime.utcnow"
] | [((207, 219), 'flask.ext.sqlalchemy.SQLAlchemy', 'SQLAlchemy', ([], {}), '()\n', (217, 219), False, 'from flask.ext.sqlalchemy import SQLAlchemy\n'), ((258, 275), 'datetime.datetime.utcnow', 'datetime.utcnow', ([], {}), '()\n', (273, 275), False, 'from datetime import datetime\n'), ((1388, 1405), 'datetime.datetime.utcnow', 'datetime.utcnow', ([], {}), '()\n', (1403, 1405), False, 'from datetime import datetime\n'), ((1181, 1198), 'datetime.datetime.utcnow', 'datetime.utcnow', ([], {}), '()\n', (1196, 1198), False, 'from datetime import datetime\n')] |
#!/usr/bin/env python3
import os
import setuptools
DIR = os.path.dirname(__file__)
REQUIREMENTS = os.path.join(DIR, "requirements.txt")
with open(REQUIREMENTS) as f:
reqs = f.read().strip().split("\n")
setuptools.setup(
name="rl",
version="0.0.1",
description="Reinforcement Learning: An Introduction",
url="github.com/manuelmeraz/ReinforcementLearning",
author="<NAME>",
license="MIT",
packages=setuptools.find_packages(),
install_requires=reqs,
entry_points={
"console_scripts": [
"tictactoe = rl.book.chapter_1.tictactoe.main:main",
"bandits = rl.book.chapter_2.main:main",
"rlgrid = rl.rlgrid.main:main",
]
},
)
| [
"os.path.dirname",
"setuptools.find_packages",
"os.path.join"
] | [((59, 84), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (74, 84), False, 'import os\n'), ((100, 137), 'os.path.join', 'os.path.join', (['DIR', '"""requirements.txt"""'], {}), "(DIR, 'requirements.txt')\n", (112, 137), False, 'import os\n'), ((432, 458), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (456, 458), False, 'import setuptools\n')] |
# pylint: disable=missing-docstring
from __future__ import annotations
import hashlib
from io import BytesIO
from pathlib import Path
from typing import Any
import pytest
from beancount.core.compare import hash_entry
from flask import url_for
from flask.testing import FlaskClient
from fava.context import g
from fava.core import FavaLedger
from fava.core.charts import PRETTY_ENCODER
from fava.core.misc import align
from fava.json_api import validate_func_arguments
from fava.json_api import ValidationError
dumps = PRETTY_ENCODER.encode
def test_validate_get_args() -> None:
def func(test: str):
assert test and isinstance(test, str)
validator = validate_func_arguments(func)
with pytest.raises(ValidationError):
validator({"notest": "value"})
assert validator({"test": "value"}) == ["value"]
def assert_api_error(response, msg: str | None = None) -> None:
"""Asserts that the response errored and contains the message."""
assert response.status_code == 200
assert not response.json["success"], response.json
if msg:
assert msg == response.json["error"]
def assert_api_success(response, data: Any | None = None) -> None:
"""Asserts that the request was successful and contains the data."""
assert response.status_code == 200
assert response.json["success"], response.json
if data:
assert data == response.json["data"]
def test_api_changed(app, test_client: FlaskClient) -> None:
with app.test_request_context("/long-example/"):
app.preprocess_request()
url = url_for("json_api.get_changed")
response = test_client.get(url)
assert_api_success(response, False)
def test_api_add_document(
app, test_client: FlaskClient, tmp_path, monkeypatch
) -> None:
with app.test_request_context("/long-example/"):
app.preprocess_request()
monkeypatch.setitem(g.ledger.options, "documents", [str(tmp_path)])
request_data = {
"folder": str(tmp_path),
"account": "Expenses:Food:Restaurant",
"file": (BytesIO(b"asdfasdf"), "2015-12-12 test"),
}
url = url_for("json_api.put_add_document")
response = test_client.put(url)
assert_api_error(response, "No file uploaded.")
filename = (
tmp_path / "Expenses" / "Food" / "Restaurant" / "2015-12-12 test"
)
response = test_client.put(url, data=request_data)
assert_api_success(response, f"Uploaded to {filename}")
assert Path(filename).is_file()
request_data["file"] = (BytesIO(b"asdfasdf"), "2015-12-12 test")
response = test_client.put(url, data=request_data)
assert_api_error(response, f"{filename} already exists.")
def test_api_errors(app, test_client: FlaskClient) -> None:
with app.test_request_context("/long-example/"):
app.preprocess_request()
url = url_for("json_api.get_errors")
response = test_client.get(url)
assert_api_success(response, 0)
def test_api_context(
app, test_client: FlaskClient, snapshot, example_ledger: FavaLedger
) -> None:
with app.test_request_context("/long-example/"):
app.preprocess_request()
url = url_for("json_api.get_context")
response = test_client.get(url)
assert_api_error(
response, "Invalid API request: Parameter `entry_hash` is missing."
)
url = url_for(
"json_api.get_context",
entry_hash=hash_entry(
next(
entry
for entry in example_ledger.all_entries
if entry.meta["lineno"] == 3732
)
),
)
response = test_client.get(url)
assert_api_success(response)
snapshot(response.json)
url = url_for(
"json_api.get_context",
entry_hash=hash_entry(example_ledger.entries[10]),
)
response = test_client.get(url)
assert_api_success(response)
assert not response.json.get("balances_before")
snapshot(response.json)
def test_api_payee_accounts(app, test_client: FlaskClient) -> None:
with app.test_request_context("/long-example/"):
app.preprocess_request()
url = url_for("json_api.get_payee_accounts", payee="test")
response = test_client.get(url)
assert_api_success(response, [])
def test_api_move(app, test_client: FlaskClient) -> None:
with app.test_request_context("/long-example/"):
app.preprocess_request()
url = url_for("json_api.get_move")
response = test_client.get(url)
assert_api_error(
response, "Invalid API request: Parameter `account` is missing."
)
def test_api_source_put(app, test_client: FlaskClient) -> None:
with app.test_request_context("/long-example/"):
app.preprocess_request()
url = url_for("json_api.put_source")
path = g.ledger.beancount_file_path
# test bad request
response = test_client.put(url)
assert_api_error(response, "Invalid JSON request.")
with open(path, encoding="utf-8") as file_handle:
payload = file_handle.read()
with open(path, mode="rb") as bfile_handle:
sha256sum = hashlib.sha256(bfile_handle.read()).hexdigest()
# change source
response = test_client.put(
url,
data=dumps(
{
"source": "asdf" + payload,
"sha256sum": sha256sum,
"file_path": path,
}
),
content_type="application/json",
)
with open(path, mode="rb") as bfile_handle:
sha256sum = hashlib.sha256(bfile_handle.read()).hexdigest()
assert_api_success(response, sha256sum)
# check if the file has been written
with open(path, encoding="utf-8") as file_handle:
assert file_handle.read() == "asdf" + payload
# write original source file
result = test_client.put(
url,
data=dumps(
{"source": payload, "sha256sum": sha256sum, "file_path": path}
),
content_type="application/json",
)
assert result.status_code == 200
with open(path, encoding="utf-8") as file_handle:
assert file_handle.read() == payload
def test_api_format_source(app, test_client: FlaskClient) -> None:
with app.test_request_context("/long-example/"):
app.preprocess_request()
url = url_for("json_api.put_format_source")
path = g.ledger.beancount_file_path
with open(path, encoding="utf-8") as file_handle:
payload = file_handle.read()
response = test_client.put(
url,
data=dumps({"source": payload}),
content_type="application/json",
)
assert_api_success(response, align(payload, 61))
def test_api_format_source_options(
app, test_client: FlaskClient, monkeypatch
) -> None:
with app.test_request_context("/long-example/"):
app.preprocess_request()
path = g.ledger.beancount_file_path
with open(path, encoding="utf-8") as file_handle:
payload = file_handle.read()
url = url_for("json_api.put_format_source")
monkeypatch.setattr(g.ledger.fava_options, "currency_column", 90)
response = test_client.put(
url,
data=dumps({"source": payload}),
content_type="application/json",
)
assert_api_success(response, align(payload, 90))
def test_api_add_entries(app, test_client: FlaskClient, tmp_path, monkeypatch):
with app.test_request_context("/long-example/"):
app.preprocess_request()
test_file = tmp_path / "test_file"
test_file.open("a")
monkeypatch.setattr(g.ledger, "beancount_file_path", str(test_file))
data = {
"entries": [
{
"type": "Transaction",
"date": "2017-12-12",
"flag": "*",
"payee": "Test3",
"narration": "",
"meta": {},
"postings": [
{
"account": "Assets:US:ETrade:Cash",
"amount": "100 USD",
},
{"account": "Assets:US:ETrade:GLD"},
],
},
{
"type": "Transaction",
"date": "2017-01-12",
"flag": "*",
"payee": "Test1",
"narration": "",
"meta": {},
"postings": [
{
"account": "Assets:US:ETrade:Cash",
"amount": "100 USD",
},
{"account": "Assets:US:ETrade:GLD"},
],
},
{
"type": "Transaction",
"date": "2017-02-12",
"flag": "*",
"payee": "Test",
"narration": "Test",
"meta": {},
"postings": [
{
"account": "Assets:US:ETrade:Cash",
"amount": "100 USD",
},
{"account": "Assets:US:ETrade:GLD"},
],
},
]
}
url = url_for("json_api.put_add_entries")
response = test_client.put(
url, data=dumps(data), content_type="application/json"
)
assert_api_success(response, "Stored 3 entries.")
assert (
test_file.read_text("utf-8")
== """
2017-01-12 * "Test1" ""
Assets:US:ETrade:Cash 100 USD
Assets:US:ETrade:GLD
2017-02-12 * "Test" "Test"
Assets:US:ETrade:Cash 100 USD
Assets:US:ETrade:GLD
2017-12-12 * "Test3" ""
Assets:US:ETrade:Cash 100 USD
Assets:US:ETrade:GLD
"""
)
@pytest.mark.parametrize(
"query_string,result_str",
[
("balances from year = 2014", "5086.65 USD"),
("nononono", "ERROR: Syntax error near"),
("select sum(day)", "43558"),
],
)
def test_api_query_result(
query_string, result_str, app, test_client: FlaskClient
) -> None:
with app.test_request_context("/long-example/"):
app.preprocess_request()
url = url_for("json_api.get_query_result", query_string=query_string)
response = test_client.get(url)
assert response.status_code == 200
assert result_str in response.get_data(True)
def test_api_query_result_filters(app, test_client: FlaskClient) -> None:
with app.test_request_context("/long-example/"):
app.preprocess_request()
url = url_for(
"json_api.get_query_result",
query_string="select sum(day)",
time="2021",
)
response = test_client.get(url)
assert response.status_code == 200
assert "6882" in response.get_data(True)
| [
"fava.core.misc.align",
"pathlib.Path",
"beancount.core.compare.hash_entry",
"io.BytesIO",
"flask.url_for",
"fava.json_api.validate_func_arguments",
"pytest.mark.parametrize",
"pytest.raises"
] | [((10148, 10327), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""query_string,result_str"""', "[('balances from year = 2014', '5086.65 USD'), ('nononono',\n 'ERROR: Syntax error near'), ('select sum(day)', '43558')]"], {}), "('query_string,result_str', [(\n 'balances from year = 2014', '5086.65 USD'), ('nononono',\n 'ERROR: Syntax error near'), ('select sum(day)', '43558')])\n", (10171, 10327), False, 'import pytest\n'), ((673, 702), 'fava.json_api.validate_func_arguments', 'validate_func_arguments', (['func'], {}), '(func)\n', (696, 702), False, 'from fava.json_api import validate_func_arguments\n'), ((712, 742), 'pytest.raises', 'pytest.raises', (['ValidationError'], {}), '(ValidationError)\n', (725, 742), False, 'import pytest\n'), ((1576, 1607), 'flask.url_for', 'url_for', (['"""json_api.get_changed"""'], {}), "('json_api.get_changed')\n", (1583, 1607), False, 'from flask import url_for\n'), ((2145, 2181), 'flask.url_for', 'url_for', (['"""json_api.put_add_document"""'], {}), "('json_api.put_add_document')\n", (2152, 2181), False, 'from flask import url_for\n'), ((2914, 2944), 'flask.url_for', 'url_for', (['"""json_api.get_errors"""'], {}), "('json_api.get_errors')\n", (2921, 2944), False, 'from flask import url_for\n'), ((3226, 3257), 'flask.url_for', 'url_for', (['"""json_api.get_context"""'], {}), "('json_api.get_context')\n", (3233, 3257), False, 'from flask import url_for\n'), ((4289, 4341), 'flask.url_for', 'url_for', (['"""json_api.get_payee_accounts"""'], {'payee': '"""test"""'}), "('json_api.get_payee_accounts', payee='test')\n", (4296, 4341), False, 'from flask import url_for\n'), ((4576, 4604), 'flask.url_for', 'url_for', (['"""json_api.get_move"""'], {}), "('json_api.get_move')\n", (4583, 4604), False, 'from flask import url_for\n'), ((4909, 4939), 'flask.url_for', 'url_for', (['"""json_api.put_source"""'], {}), "('json_api.put_source')\n", (4916, 4939), False, 'from flask import url_for\n'), ((6444, 6481), 'flask.url_for', 'url_for', (['"""json_api.put_format_source"""'], {}), "('json_api.put_format_source')\n", (6451, 6481), False, 'from flask import url_for\n'), ((6785, 6803), 'fava.core.misc.align', 'align', (['payload', '(61)'], {}), '(payload, 61)\n', (6790, 6803), False, 'from fava.core.misc import align\n'), ((7145, 7182), 'flask.url_for', 'url_for', (['"""json_api.put_format_source"""'], {}), "('json_api.put_format_source')\n", (7152, 7182), False, 'from flask import url_for\n'), ((9507, 9542), 'flask.url_for', 'url_for', (['"""json_api.put_add_entries"""'], {}), "('json_api.put_add_entries')\n", (9514, 9542), False, 'from flask import url_for\n'), ((10559, 10622), 'flask.url_for', 'url_for', (['"""json_api.get_query_result"""'], {'query_string': 'query_string'}), "('json_api.get_query_result', query_string=query_string)\n", (10566, 10622), False, 'from flask import url_for\n'), ((10924, 11010), 'flask.url_for', 'url_for', (['"""json_api.get_query_result"""'], {'query_string': '"""select sum(day)"""', 'time': '"""2021"""'}), "('json_api.get_query_result', query_string='select sum(day)', time=\n '2021')\n", (10931, 11010), False, 'from flask import url_for\n'), ((2586, 2606), 'io.BytesIO', 'BytesIO', (["b'asdfasdf'"], {}), "(b'asdfasdf')\n", (2593, 2606), False, 'from io import BytesIO\n'), ((7449, 7467), 'fava.core.misc.align', 'align', (['payload', '(90)'], {}), '(payload, 90)\n', (7454, 7467), False, 'from fava.core.misc import align\n'), ((2079, 2099), 'io.BytesIO', 'BytesIO', (["b'asdfasdf'"], {}), "(b'asdfasdf')\n", (2086, 2099), False, 'from io import BytesIO\n'), ((2528, 2542), 'pathlib.Path', 'Path', (['filename'], {}), '(filename)\n', (2532, 2542), False, 'from pathlib import Path\n'), ((3904, 3942), 'beancount.core.compare.hash_entry', 'hash_entry', (['example_ledger.entries[10]'], {}), '(example_ledger.entries[10])\n', (3914, 3942), False, 'from beancount.core.compare import hash_entry\n')] |
from luminoso_api.v5_client import LuminosoClient
from luminoso_api.v5_upload import create_project_with_docs, BATCH_SIZE
from unittest.mock import patch
import pytest
BASE_URL = 'http://mock-api.localhost/api/v5/'
DOCS_TO_UPLOAD = [
{'title': 'Document 1', 'text': 'Bonjour', 'extra': 'field'},
{'title': 'Document 2', 'text': 'Au revoir'},
]
DOCS_UPLOADED = [
{'title': 'Document 1', 'text': 'Bonjour', 'metadata': []},
{'title': 'Document 2', 'text': 'Au revoir', 'metadata': []},
]
REPETITIVE_DOC = {'title': 'Yadda', 'text': 'yadda yadda', 'metadata': []}
def _build_info_response(ndocs, language, done):
"""
Construct the expected response when we get the project's info after
requesting a build.
"""
response = {
'json': {
'project_id': 'projid',
'document_count': ndocs,
'language': language,
'last_build_info': {
'number': 1,
'start_time': 0.,
'stop_time': None,
},
}
}
if done:
response['json']['last_build_info']['success'] = True
response['json']['last_build_info']['stop_time'] = 1.
return response
def test_project_creation(requests_mock):
"""
Test creating a project by mocking what happens when it is successful.
"""
# First, configure what the mock responses should be:
# The initial response from creating the project
requests_mock.post(
BASE_URL + 'projects/',
json={
'project_id': 'projid',
'document_count': 0,
'language': 'fr',
'last_build_info': None,
},
)
# Empty responses from further build steps
requests_mock.post(BASE_URL + 'projects/projid/upload/', json={})
requests_mock.post(BASE_URL + 'projects/projid/build/', json={})
# Build status response, which isn't done yet the first time it's checked,
# and is done the second time
requests_mock.get(
BASE_URL + 'projects/projid/',
[
_build_info_response(2, 'fr', done=False),
_build_info_response(2, 'fr', done=True),
],
)
# Now run the main uploader function and get the result
client = LuminosoClient.connect(BASE_URL, token='fake')
with patch('time.sleep', return_value=None):
response = create_project_with_docs(
client,
DOCS_TO_UPLOAD,
language='fr',
name='Projet test',
progress=False,
)
# Test that the right sequence of requests happened
history = requests_mock.request_history
assert history[0].method == 'POST'
assert history[0].url == BASE_URL + 'projects/'
params = history[0].json()
assert params['name'] == 'Projet test'
assert params['language'] == 'fr'
assert history[1].method == 'POST'
assert history[1].url == BASE_URL + 'projects/projid/upload/'
params = history[1].json()
assert params['docs'] == DOCS_UPLOADED
assert history[2].method == 'POST'
assert history[2].url == BASE_URL + 'projects/projid/build/'
assert history[2].json() == {}
assert history[3].method == 'GET'
assert history[3].url == BASE_URL + 'projects/projid/'
assert history[4].method == 'GET'
assert history[4].url == BASE_URL + 'projects/projid/'
assert len(history) == 5
assert response['last_build_info']['success']
def test_missing_text(requests_mock):
"""
Test a project that fails to be created, on the client side, because a bad
document is supplied.
"""
# The initial response from creating the project
requests_mock.post(
BASE_URL + 'projects/',
json={
'project_id': 'projid',
'document_count': 0,
'language': 'en',
'last_build_info': None,
},
)
with pytest.raises(ValueError):
client = LuminosoClient.connect(BASE_URL, token='fake')
create_project_with_docs(
client,
[{'bad': 'document'}],
language='en',
name='Bad project test',
progress=False,
)
def test_pagination(requests_mock):
"""
Test that we can create a project whose documents would be broken into
multiple pages, and when we iterate over its documents, we correctly
request all the pages.
"""
# The initial response from creating the project
requests_mock.post(
BASE_URL + 'projects/',
json={
'project_id': 'projid',
'document_count': 0,
'language': 'fr',
'last_build_info': None,
},
)
# Empty responses from further build steps
requests_mock.post(BASE_URL + 'projects/projid/upload/', json={})
requests_mock.post(BASE_URL + 'projects/projid/build/', json={})
ndocs = BATCH_SIZE + 2
# Build status response, which isn't done yet the first or second time
# it's checked, and is done the third time
requests_mock.get(
BASE_URL + 'projects/projid/',
[
_build_info_response(ndocs, 'fr', done=False),
_build_info_response(ndocs, 'fr', done=False),
_build_info_response(ndocs, 'fr', done=True),
],
)
# Now run the main uploader function and get the result
client = LuminosoClient.connect(BASE_URL, token='fake')
with patch('time.sleep', return_value=None):
create_project_with_docs(
client,
[REPETITIVE_DOC] * (BATCH_SIZE + 2),
language='fr',
name='Projet test',
progress=False,
)
# Test that the right sequence of requests happened, this time just as
# a list of URLs
history = requests_mock.request_history
reqs = [(req.method, req.url) for req in history]
assert reqs == [
('POST', BASE_URL + 'projects/'),
('POST', BASE_URL + 'projects/projid/upload/'),
('POST', BASE_URL + 'projects/projid/upload/'),
('POST', BASE_URL + 'projects/projid/build/'),
('GET', BASE_URL + 'projects/projid/'),
('GET', BASE_URL + 'projects/projid/'),
('GET', BASE_URL + 'projects/projid/'),
]
| [
"luminoso_api.v5_client.LuminosoClient.connect",
"unittest.mock.patch",
"luminoso_api.v5_upload.create_project_with_docs",
"pytest.raises"
] | [((2250, 2296), 'luminoso_api.v5_client.LuminosoClient.connect', 'LuminosoClient.connect', (['BASE_URL'], {'token': '"""fake"""'}), "(BASE_URL, token='fake')\n", (2272, 2296), False, 'from luminoso_api.v5_client import LuminosoClient\n'), ((5347, 5393), 'luminoso_api.v5_client.LuminosoClient.connect', 'LuminosoClient.connect', (['BASE_URL'], {'token': '"""fake"""'}), "(BASE_URL, token='fake')\n", (5369, 5393), False, 'from luminoso_api.v5_client import LuminosoClient\n'), ((2306, 2344), 'unittest.mock.patch', 'patch', (['"""time.sleep"""'], {'return_value': 'None'}), "('time.sleep', return_value=None)\n", (2311, 2344), False, 'from unittest.mock import patch\n'), ((2365, 2469), 'luminoso_api.v5_upload.create_project_with_docs', 'create_project_with_docs', (['client', 'DOCS_TO_UPLOAD'], {'language': '"""fr"""', 'name': '"""Projet test"""', 'progress': '(False)'}), "(client, DOCS_TO_UPLOAD, language='fr', name=\n 'Projet test', progress=False)\n", (2389, 2469), False, 'from luminoso_api.v5_upload import create_project_with_docs, BATCH_SIZE\n'), ((3884, 3909), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (3897, 3909), False, 'import pytest\n'), ((3928, 3974), 'luminoso_api.v5_client.LuminosoClient.connect', 'LuminosoClient.connect', (['BASE_URL'], {'token': '"""fake"""'}), "(BASE_URL, token='fake')\n", (3950, 3974), False, 'from luminoso_api.v5_client import LuminosoClient\n'), ((3983, 4099), 'luminoso_api.v5_upload.create_project_with_docs', 'create_project_with_docs', (['client', "[{'bad': 'document'}]"], {'language': '"""en"""', 'name': '"""Bad project test"""', 'progress': '(False)'}), "(client, [{'bad': 'document'}], language='en', name\n ='Bad project test', progress=False)\n", (4007, 4099), False, 'from luminoso_api.v5_upload import create_project_with_docs, BATCH_SIZE\n'), ((5403, 5441), 'unittest.mock.patch', 'patch', (['"""time.sleep"""'], {'return_value': 'None'}), "('time.sleep', return_value=None)\n", (5408, 5441), False, 'from unittest.mock import patch\n'), ((5451, 5575), 'luminoso_api.v5_upload.create_project_with_docs', 'create_project_with_docs', (['client', '([REPETITIVE_DOC] * (BATCH_SIZE + 2))'], {'language': '"""fr"""', 'name': '"""Projet test"""', 'progress': '(False)'}), "(client, [REPETITIVE_DOC] * (BATCH_SIZE + 2),\n language='fr', name='Projet test', progress=False)\n", (5475, 5575), False, 'from luminoso_api.v5_upload import create_project_with_docs, BATCH_SIZE\n')] |
import unittest
import shutil
import tempfile
import numpy as np
# import pandas as pd
# import pymc3 as pm
# from pymc3 import summary
# from sklearn.mixture import BayesianGaussianMixture as skBayesianGaussianMixture
from sklearn.model_selection import train_test_split
from pmlearn.exceptions import NotFittedError
from pmlearn.mixture import DirichletProcessMixture
class DirichletProcessMixtureTestCase(unittest.TestCase):
def setUp(self):
self.num_truncate = 3
self.num_components = 3
self.num_pred = 1
self.num_training_samples = 100
self.pi = np.array([0.35, 0.4, 0.25])
self.means = np.array([0, 5, 10])
self.sigmas = np.array([0.5, 0.5, 1.0])
self.components = np.random.randint(0,
self.num_components,
self.num_training_samples)
X = np.random.normal(loc=self.means[self.components],
scale=self.sigmas[self.components])
X.shape = (self.num_training_samples, 1)
self.X_train, self.X_test = train_test_split(X, test_size=0.3)
self.test_DPMM = DirichletProcessMixture()
self.test_nuts_DPMM = DirichletProcessMixture()
self.test_dir = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.test_dir)
# class DirichletProcessMixtureFitTestCase(DirichletProcessMixtureTestCase):
# def test_advi_fit_returns_correct_model(self):
# # This print statement ensures PyMC3 output won't overwrite the test name
# print('')
# self.test_DPMM.fit(self.X_train)
#
# self.assertEqual(self.num_pred, self.test_DPMM.num_pred)
# self.assertEqual(self.num_components, self.test_DPMM.num_components)
# self.assertEqual(self.num_truncate, self.test_DPMM.num_truncate)
#
# self.assertAlmostEqual(self.pi[0],
# self.test_DPMM.summary['mean']['pi__0'],
# 0)
# self.assertAlmostEqual(self.pi[1],
# self.test_DPMM.summary['mean']['pi__1'],
# 0)
# self.assertAlmostEqual(self.pi[2],
# self.test_DPMM.summary['mean']['pi__2'],
# 0)
#
# self.assertAlmostEqual(
# self.means[0],
# self.test_DPMM.summary['mean']['cluster_center_0__0'],
# 0)
# self.assertAlmostEqual(
# self.means[1],
# self.test_DPMM.summary['mean']['cluster_center_1__0'],
# 0)
# self.assertAlmostEqual(
# self.means[2],
# self.test_DPMM.summary['mean']['cluster_center_2__0'],
# 0)
#
# self.assertAlmostEqual(
# self.sigmas[0],
# self.test_DPMM.summary['mean']['cluster_variance_0__0'],
# 0)
# self.assertAlmostEqual(
# self.sigmas[1],
# self.test_DPMM.summary['mean']['cluster_variance_1__0'],
# 0)
# self.assertAlmostEqual(
# self.sigmas[2],
# self.test_DPMM.summary['mean']['cluster_variance_2__0'],
# 0)
#
# def test_nuts_fit_returns_correct_model(self):
# # This print statement ensures PyMC3 output won't overwrite the test name
# print('')
# self.test_nuts_DPMM.fit(self.X_train,
# inference_type='nuts',
# inference_args={'draws': 1000,
# 'chains': 2})
#
# self.assertEqual(self.num_pred, self.test_nuts_DPMM.num_pred)
# self.assertEqual(self.num_components, self.test_nuts_DPMM.num_components)
# self.assertEqual(self.num_components, self.test_nuts_DPMM.num_truncate)
#
# self.assertAlmostEqual(self.pi[0],
# self.test_nuts_DPMM.summary['mean']['pi__0'],
# 0)
# self.assertAlmostEqual(self.pi[1],
# self.test_nuts_DPMM.summary['mean']['pi__1'],
# 0)
# self.assertAlmostEqual(self.pi[2],
# self.test_nuts_DPMM.summary['mean']['pi__2'],
# 0)
#
# self.assertAlmostEqual(
# self.means[0],
# self.test_nuts_DPMM.summary['mean']['cluster_center_0__0'],
# 0)
# self.assertAlmostEqual(
# self.means[1],
# self.test_nuts_DPMM.summary['mean']['cluster_center_1__0'],
# 0)
# self.assertAlmostEqual(
# self.means[2],
# self.test_nuts_DPMM.summary['mean']['cluster_center_2__0'],
# 0)
#
# self.assertAlmostEqual(
# self.sigmas[0],
# self.test_nuts_DPMM.summary['mean']['cluster_variance_0__0'],
# 0)
# self.assertAlmostEqual(
# self.sigmas[1],
# self.test_nuts_DPMM.summary['mean']['cluster_variance_1__0'],
# 0)
# self.assertAlmostEqual(
# self.sigmas[2],
# self.test_nuts_DPMM.summary['mean']['cluster_variance_2__0'],
# 0)
#
#
class DirichletProcessMixturePredictTestCase(DirichletProcessMixtureTestCase):
# def test_predict_returns_predictions(self):
# print('')
# self.test_DPMM.fit(self.X_train, self.y_train)
# preds = self.test_DPMM.predict(self.X_test)
# self.assertEqual(self.y_test.shape, preds.shape)
# def test_predict_returns_mean_predictions_and_std(self):
# print('')
# self.test_DPMM.fit(self.X_train, self.y_train)
# preds, stds = self.test_DPMM.predict(self.X_test, return_std=True)
# self.assertEqual(self.y_test.shape, preds.shape)
# self.assertEqual(self.y_test.shape, stds.shape)
def test_predict_raises_error_if_not_fit(self):
print('')
with self.assertRaises(NotFittedError) as no_fit_error:
test_DPMM = DirichletProcessMixture()
test_DPMM.predict(self.X_train)
expected = 'Run fit on the model before predict.'
self.assertEqual(str(no_fit_error.exception), expected)
# class DirichletProcessMixtureScoreTestCase(DirichletProcessMixtureTestCase):
# def test_score_matches_sklearn_performance(self):
# print('')
# skDPMM = skBayesianGaussianMixture(n_components=3)
# skDPMM.fit(self.X_train)
# skDPMM_score = skDPMM.score(self.X_test)
#
# self.test_DPMM.fit(self.X_train)
# test_DPMM_score = self.test_DPMM.score(self.X_test)
#
# self.assertAlmostEqual(skDPMM_score, test_DPMM_score, 0)
#
#
# class DirichletProcessMixtureSaveAndLoadTestCase(DirichletProcessMixtureTestCase):
# def test_save_and_load_work_correctly(self):
# print('')
# self.test_DPMM.fit(self.X_train)
# score1 = self.test_DPMM.score(self.X_test)
# self.test_DPMM.save(self.test_dir)
#
# DPMM2 = DirichletProcessMixture()
# DPMM2.load(self.test_dir)
#
# self.assertEqual(self.test_DPMM.inference_type, DPMM2.inference_type)
# self.assertEqual(self.test_DPMM.num_pred, DPMM2.num_pred)
# self.assertEqual(self.test_DPMM.num_training_samples,
# DPMM2.num_training_samples)
# self.assertEqual(self.test_DPMM.num_truncate, DPMM2.num_truncate)
#
# pd.testing.assert_frame_equal(summary(self.test_DPMM.trace),
# summary(DPMM2.trace))
#
# score2 = DPMM2.score(self.X_test)
# self.assertAlmostEqual(score1, score2, 0)
| [
"numpy.random.normal",
"sklearn.model_selection.train_test_split",
"numpy.array",
"numpy.random.randint",
"tempfile.mkdtemp",
"shutil.rmtree",
"pmlearn.mixture.DirichletProcessMixture"
] | [((601, 628), 'numpy.array', 'np.array', (['[0.35, 0.4, 0.25]'], {}), '([0.35, 0.4, 0.25])\n', (609, 628), True, 'import numpy as np\n'), ((650, 670), 'numpy.array', 'np.array', (['[0, 5, 10]'], {}), '([0, 5, 10])\n', (658, 670), True, 'import numpy as np\n'), ((693, 718), 'numpy.array', 'np.array', (['[0.5, 0.5, 1.0]'], {}), '([0.5, 0.5, 1.0])\n', (701, 718), True, 'import numpy as np\n'), ((746, 814), 'numpy.random.randint', 'np.random.randint', (['(0)', 'self.num_components', 'self.num_training_samples'], {}), '(0, self.num_components, self.num_training_samples)\n', (763, 814), True, 'import numpy as np\n'), ((916, 1006), 'numpy.random.normal', 'np.random.normal', ([], {'loc': 'self.means[self.components]', 'scale': 'self.sigmas[self.components]'}), '(loc=self.means[self.components], scale=self.sigmas[self.\n components])\n', (932, 1006), True, 'import numpy as np\n'), ((1117, 1151), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X'], {'test_size': '(0.3)'}), '(X, test_size=0.3)\n', (1133, 1151), False, 'from sklearn.model_selection import train_test_split\n'), ((1178, 1203), 'pmlearn.mixture.DirichletProcessMixture', 'DirichletProcessMixture', ([], {}), '()\n', (1201, 1203), False, 'from pmlearn.mixture import DirichletProcessMixture\n'), ((1234, 1259), 'pmlearn.mixture.DirichletProcessMixture', 'DirichletProcessMixture', ([], {}), '()\n', (1257, 1259), False, 'from pmlearn.mixture import DirichletProcessMixture\n'), ((1284, 1302), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (1300, 1302), False, 'import tempfile\n'), ((1336, 1364), 'shutil.rmtree', 'shutil.rmtree', (['self.test_dir'], {}), '(self.test_dir)\n', (1349, 1364), False, 'import shutil\n'), ((6110, 6135), 'pmlearn.mixture.DirichletProcessMixture', 'DirichletProcessMixture', ([], {}), '()\n', (6133, 6135), False, 'from pmlearn.mixture import DirichletProcessMixture\n')] |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import numpy as np
from skimage import draw
from skimage import measure
from astropy.io import fits
from astropy import units as u
from astropy import wcs, coordinates
from scipy.ndimage.filters import gaussian_filter
def standard(X):
"""
standard : This function makes data ragbe between 0 and 1.
Arguments:
X (numoy array) : input data.
--------
Returns:
standard data.
"""
xmin = X.min()
X = X-xmin
xmax = X.max()
X = X/xmax
return X
def fetch_data(image_file,model_file,do_standard=True,ignore_error=False):
"""
fetch_data : This function reads image and model.
Arguments:
image_file (string) : path to image file.
model_file (string) : path to model file.
do_standard (logical) (default=True) : if true, minimum/maximum value of image will be set to 0/1.
--------
Returns:
image, x coordinates, y coordinates
"""
with fits.open(image_file) as hdulist:
data = hdulist[0].data
header = hdulist[0].header
lx = header['NAXIS1']
ly = header['NAXIS2']
coord_sys = wcs.WCS(header)
model_file = model_file
sources = np.loadtxt(model_file, dtype={'names': ('name', 'ra', 'dec', 'I'),
'formats': ('S10', 'f4', 'f4', 'f4')})
ra, dec = sources['ra'],sources['dec']
num_sources = len(ra)
radec_coords = coordinates.SkyCoord(ra, dec, unit='deg', frame='fk5')
coords_ar = np.vstack([radec_coords.ra*u.deg, radec_coords.dec*u.deg,
np.zeros(num_sources), np.zeros(num_sources)]).T
xy_coords = coord_sys.wcs_world2pix(coords_ar, 0)
x_coords, y_coords = xy_coords[:,0], xy_coords[:,1]
filt = (0<=x_coords) & (x_coords<lx) & (0<=y_coords) & (y_coords<ly)
if ignore_error:
x_coords, y_coords = x_coords[filt], y_coords[filt]
else:
assert np.sum(filt)==num_sources,'There are some sources out of images! The problem might be in coordinate conversion system or simulation!'
if do_standard==True:
data = standard(data)
return np.moveaxis(data, 0, -1), x_coords, y_coords
def fetch_data_3ch(image_file,model_file,do_standard=True):
"""
fetch_data_3ch : This function reads 3 images of 3 robust and model.
Arguments:
image_file (string) : path to robust 0 image file.
model_file (string) : path to model file.
do_standard (logical) (default=True) : if true, minimum/maximum value of image will be set to 0/1.
--------
Returns:
image, x coordinates, y coordinates
"""
data0, x_coords, y_coords = fetch_data(image_file,model_file,do_standard=do_standard)
# lx,ly = data0[0,:,:,0].shape
try:
data1, x_coords, y_coords = fetch_data(image_file.replace('robust-0','robust-1'),model_file,do_standard=do_standard)
except:
assert 0,'Robust 1 does not exist.'
try:
data2, x_coords, y_coords = fetch_data(image_file.replace('robust-0','robust-2'),model_file,do_standard=do_standard)
except:
assert 0,'Robust 1 does not exist.'
return np.concatenate((data0,data1,data2), axis=-1), x_coords, y_coords
def cat2map(lx,ly,x_coords,y_coords):
"""
cat2map : This function converts a catalog to a 0/1 map which are representing background/point source.
Arguments:
lx (int): number of pixels of the image in first dimension.
ly (int): number of pixels of the image in second dimension.
x_coords (numpy array): list of the first dimension of point source positions.
y_coords (numpy array): list of the second dimension of point source positions.
--------
Returns:
catalog image as nupmy array.
"""
cat = np.zeros((lx,ly))
for i,j in zip(x_coords.astype(int), y_coords.astype(int)):
cat[j, i] = 1
return cat
def magnifier(y,radius=15,value=1):
"""
magnifier (numpy array): This function magnifies any pixel with value one by a given value.
Arguments:
y : input 2D map.
radius (int) (default=15) : radius of magnification.
value (float) (default=True) : the value you want to use in magnified pixels.
--------
Returns:
image with magnified objects as numpy array.
"""
mag = np.zeros(y.shape)
for i,j in np.argwhere(y==1):
rr, cc = draw.circle(i, j, radius=radius, shape=mag.shape)
mag[rr, cc] = value
return mag
def circle(y,radius=15):
"""
circle : This function add some circles around any pixel with value one.
Arguments:
y (numpy array): input 2D map.
radius (int) (default=15): circle radius.
--------
Returns:
image with circles around objects.
"""
mag = np.zeros(y.shape)
for i,j in np.argwhere(y==1):
rr, cc = draw.circle_perimeter(i, j, radius=radius, shape=mag.shape)
mag[rr, cc] = 1
return mag
def horn_kernel(y,radius=10,step_height=1):
"""
horn_kernel : Horn shape kernel.
Arguments:
y (numpy array): input 2D map.
radius (int) (default=15): effective radius of kernel.
--------
Returns:
kerneled image.
"""
mag = np.zeros(y.shape)
for r in range(1,radius):
for i,j in np.argwhere(y==1):
rr, cc = draw.circle(i, j, radius=r, shape=mag.shape)
mag[rr, cc] += 1.*step_height/radius
return mag
def gaussian_kernel(y,sigma=7):
"""
gaussian_kernel: Gaussian filter.
Arguments:
y (numpy array): input 2D map.
sigma (float) (default=7): effective length of Gaussian smoothing.
--------
Returns:
kerneled image.
"""
return gaussian_filter(y, sigma)
def ch_mkdir(directory):
"""
ch_mkdir : This function creates a directory if it does not exist.
Arguments:
directory (string): Path to the directory.
--------
Returns:
null.
"""
if not os.path.exists(directory):
os.makedirs(directory)
def the_print(text,style='bold',tc='gray',bgc='red'):
"""
prints table of formatted text format options
"""
colors = ['black','red','green','yellow','blue','purple','skyblue','gray']
if style == 'bold':
style = 1
elif style == 'underlined':
style = 4
else:
style = 0
fg = 30+colors.index(tc)
bg = 40+colors.index(bgc)
form = ';'.join([str(style), str(fg), str(bg)])
print('\x1b[%sm %s \x1b[0m' % (form, text))
#def ps_extract(xp):
# xp = xp-xp.min()
# xp = xp/xp.max()
# nb = []
# for trsh in np.linspace(0,0.2,200):
# blobs = measure.label(xp>trsh)
# nn = np.unique(blobs).shape[0]
# nb.append(nn)
# nb = np.array(nb)
# nb = np.diff(nb)
# trshs = np.linspace(0,0.2,200)[:-1]
# thrsl = trshs[~((-5<nb) & (nb<5))]
# if thrsl.shape[0]==0:
# trsh = 0.1
# else:
# trsh = thrsl[-1]
#2: 15, 20
#3: 30,10
#4: 50, 10
# nnp = 0
# for tr in np.linspace(1,0,1000):
# blobs = measure.label(xp>tr)
# nn = np.unique(blobs).shape[0]
# if nn-nnp>50:
# break
# nnp = nn
# trsh = tr
# blobs = measure.label(xp>trsh)
# xl = []
# yl = []
# pl = []
# for v in np.unique(blobs)[1:]:
# filt = blobs==v
# pnt = np.round(np.mean(np.argwhere(filt),axis=0)).astype(int)
# if filt.sum()>10:
# xl.append(pnt[1])
# yl.append(pnt[0])
# pl.append(np.mean(xp[blobs==v]))
# return np.array([xl,yl]).T,np.array(pl)
| [
"skimage.draw.circle",
"os.path.exists",
"scipy.ndimage.filters.gaussian_filter",
"os.makedirs",
"astropy.coordinates.SkyCoord",
"numpy.sum",
"numpy.zeros",
"numpy.argwhere",
"skimage.draw.circle_perimeter",
"numpy.concatenate",
"astropy.io.fits.open",
"numpy.moveaxis",
"numpy.loadtxt",
"a... | [((1351, 1460), 'numpy.loadtxt', 'np.loadtxt', (['model_file'], {'dtype': "{'names': ('name', 'ra', 'dec', 'I'), 'formats': ('S10', 'f4', 'f4', 'f4')}"}), "(model_file, dtype={'names': ('name', 'ra', 'dec', 'I'),\n 'formats': ('S10', 'f4', 'f4', 'f4')})\n", (1361, 1460), True, 'import numpy as np\n'), ((1583, 1637), 'astropy.coordinates.SkyCoord', 'coordinates.SkyCoord', (['ra', 'dec'], {'unit': '"""deg"""', 'frame': '"""fk5"""'}), "(ra, dec, unit='deg', frame='fk5')\n", (1603, 1637), False, 'from astropy import wcs, coordinates\n'), ((3975, 3993), 'numpy.zeros', 'np.zeros', (['(lx, ly)'], {}), '((lx, ly))\n', (3983, 3993), True, 'import numpy as np\n'), ((4536, 4553), 'numpy.zeros', 'np.zeros', (['y.shape'], {}), '(y.shape)\n', (4544, 4553), True, 'import numpy as np\n'), ((4569, 4588), 'numpy.argwhere', 'np.argwhere', (['(y == 1)'], {}), '(y == 1)\n', (4580, 4588), True, 'import numpy as np\n'), ((5014, 5031), 'numpy.zeros', 'np.zeros', (['y.shape'], {}), '(y.shape)\n', (5022, 5031), True, 'import numpy as np\n'), ((5047, 5066), 'numpy.argwhere', 'np.argwhere', (['(y == 1)'], {}), '(y == 1)\n', (5058, 5066), True, 'import numpy as np\n'), ((5471, 5488), 'numpy.zeros', 'np.zeros', (['y.shape'], {}), '(y.shape)\n', (5479, 5488), True, 'import numpy as np\n'), ((5986, 6011), 'scipy.ndimage.filters.gaussian_filter', 'gaussian_filter', (['y', 'sigma'], {}), '(y, sigma)\n', (6001, 6011), False, 'from scipy.ndimage.filters import gaussian_filter\n'), ((1102, 1123), 'astropy.io.fits.open', 'fits.open', (['image_file'], {}), '(image_file)\n', (1111, 1123), False, 'from astropy.io import fits\n'), ((1292, 1307), 'astropy.wcs.WCS', 'wcs.WCS', (['header'], {}), '(header)\n', (1299, 1307), False, 'from astropy import wcs, coordinates\n'), ((2283, 2307), 'numpy.moveaxis', 'np.moveaxis', (['data', '(0)', '(-1)'], {}), '(data, 0, -1)\n', (2294, 2307), True, 'import numpy as np\n'), ((3334, 3380), 'numpy.concatenate', 'np.concatenate', (['(data0, data1, data2)'], {'axis': '(-1)'}), '((data0, data1, data2), axis=-1)\n', (3348, 3380), True, 'import numpy as np\n'), ((4607, 4656), 'skimage.draw.circle', 'draw.circle', (['i', 'j'], {'radius': 'radius', 'shape': 'mag.shape'}), '(i, j, radius=radius, shape=mag.shape)\n', (4618, 4656), False, 'from skimage import draw\n'), ((5085, 5144), 'skimage.draw.circle_perimeter', 'draw.circle_perimeter', (['i', 'j'], {'radius': 'radius', 'shape': 'mag.shape'}), '(i, j, radius=radius, shape=mag.shape)\n', (5106, 5144), False, 'from skimage import draw\n'), ((5538, 5557), 'numpy.argwhere', 'np.argwhere', (['(y == 1)'], {}), '(y == 1)\n', (5549, 5557), True, 'import numpy as np\n'), ((6264, 6289), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (6278, 6289), False, 'import os\n'), ((6301, 6323), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (6312, 6323), False, 'import os\n'), ((2080, 2092), 'numpy.sum', 'np.sum', (['filt'], {}), '(filt)\n', (2086, 2092), True, 'import numpy as np\n'), ((5582, 5626), 'skimage.draw.circle', 'draw.circle', (['i', 'j'], {'radius': 'r', 'shape': 'mag.shape'}), '(i, j, radius=r, shape=mag.shape)\n', (5593, 5626), False, 'from skimage import draw\n'), ((1741, 1762), 'numpy.zeros', 'np.zeros', (['num_sources'], {}), '(num_sources)\n', (1749, 1762), True, 'import numpy as np\n'), ((1764, 1785), 'numpy.zeros', 'np.zeros', (['num_sources'], {}), '(num_sources)\n', (1772, 1785), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
import os
import sys
import yaml
file_name=sys.argv[1]
file_name = '/root/etcd/' + file_name + '.yaml'
with open(file_name) as f:
y=yaml.safe_load(f)
del y['metadata']['creationTimestamp']
del y['metadata']['generation']
del y['metadata']['resourceVersion']
del y['metadata']['uid']
del y['status']
with open(file_name, 'w') as outputFile:
yaml.dump(y,outputFile, default_flow_style=False, sort_keys=False)
| [
"yaml.safe_load",
"yaml.dump"
] | [((161, 178), 'yaml.safe_load', 'yaml.safe_load', (['f'], {}), '(f)\n', (175, 178), False, 'import yaml\n'), ((400, 467), 'yaml.dump', 'yaml.dump', (['y', 'outputFile'], {'default_flow_style': '(False)', 'sort_keys': '(False)'}), '(y, outputFile, default_flow_style=False, sort_keys=False)\n', (409, 467), False, 'import yaml\n')] |
import os
import cv2
from Segmentation import CombinedHist, get_histograms, HistQueue
import matplotlib.pyplot as plt
import numpy as np
listofFiles = os.listdir('generated_frames')
# change the size of queue accordingly
queue_of_hists = HistQueue.HistQueue(25)
x = []
y_r = []
y_g = []
y_b = []
def compare(current_hist, frame_no):
avg_histr = queue_of_hists.getAverageHist()
red_result = cv2.compareHist(current_hist.getRedHistr(), avg_histr.getRedHistr(), 0)
green_result = cv2.compareHist(current_hist.getGreenHistr(), avg_histr.getGreenHistr(), 0)
blue_result = cv2.compareHist(current_hist.getBlueHistr(), avg_histr.getBlueHistr(), 0)
x.append(i)
y_r.append(red_result)
y_g.append(green_result)
y_b.append(blue_result)
# print(red_result)
for i in range(0, 4000):
blue_histr, green_histr, red_histr = get_histograms.get_histograms('generated_frames/frame' + str(i) + ".jpg")
hist_of_image = CombinedHist.CombinedHist(blue_histr, green_histr, red_histr)
compare(hist_of_image, i)
queue_of_hists.insert_histr(hist_of_image)
print("frame" + str(i) + ".jpg")
fig = plt.figure(figsize=(18, 5))
y = np.add(np.add(y_r, y_g), y_b) / 3
value = np.percentile(y, 5)
median = np.median(y)
minimum = np.amin(y)
y_sorted = np.sort(y)
getting_index = y_sorted[8]
print("quartile" + str(value))
print("median" + str(median))
plt.plot(x, y, color='k')
plt.axhline(y=value, color='r', linestyle='-')
plt.xticks(np.arange(min(x), max(x) + 1, 100.0))
plt.show()
| [
"numpy.median",
"os.listdir",
"numpy.amin",
"Segmentation.CombinedHist.CombinedHist",
"numpy.add",
"numpy.sort",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.axhline",
"matplotlib.pyplot.figure",
"Segmentation.HistQueue.HistQueue",
"numpy.percentile",
"matplotlib.pyplot.show"
] | [((152, 182), 'os.listdir', 'os.listdir', (['"""generated_frames"""'], {}), "('generated_frames')\n", (162, 182), False, 'import os\n'), ((239, 262), 'Segmentation.HistQueue.HistQueue', 'HistQueue.HistQueue', (['(25)'], {}), '(25)\n', (258, 262), False, 'from Segmentation import CombinedHist, get_histograms, HistQueue\n'), ((1131, 1158), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(18, 5)'}), '(figsize=(18, 5))\n', (1141, 1158), True, 'import matplotlib.pyplot as plt\n'), ((1206, 1225), 'numpy.percentile', 'np.percentile', (['y', '(5)'], {}), '(y, 5)\n', (1219, 1225), True, 'import numpy as np\n'), ((1236, 1248), 'numpy.median', 'np.median', (['y'], {}), '(y)\n', (1245, 1248), True, 'import numpy as np\n'), ((1259, 1269), 'numpy.amin', 'np.amin', (['y'], {}), '(y)\n', (1266, 1269), True, 'import numpy as np\n'), ((1281, 1291), 'numpy.sort', 'np.sort', (['y'], {}), '(y)\n', (1288, 1291), True, 'import numpy as np\n'), ((1381, 1406), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {'color': '"""k"""'}), "(x, y, color='k')\n", (1389, 1406), True, 'import matplotlib.pyplot as plt\n'), ((1407, 1453), 'matplotlib.pyplot.axhline', 'plt.axhline', ([], {'y': 'value', 'color': '"""r"""', 'linestyle': '"""-"""'}), "(y=value, color='r', linestyle='-')\n", (1418, 1453), True, 'import matplotlib.pyplot as plt\n'), ((1503, 1513), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1511, 1513), True, 'import matplotlib.pyplot as plt\n'), ((948, 1009), 'Segmentation.CombinedHist.CombinedHist', 'CombinedHist.CombinedHist', (['blue_histr', 'green_histr', 'red_histr'], {}), '(blue_histr, green_histr, red_histr)\n', (973, 1009), False, 'from Segmentation import CombinedHist, get_histograms, HistQueue\n'), ((1171, 1187), 'numpy.add', 'np.add', (['y_r', 'y_g'], {}), '(y_r, y_g)\n', (1177, 1187), True, 'import numpy as np\n')] |
"""
-------------------------------------------------------------------------
shine -
setup
!!TODO: add file description here!!
created: 2017/06/04 in PyCharm
(c) 2017 Sven - ducandu GmbH
-------------------------------------------------------------------------
"""
from setuptools import setup
setup(name='aiopening', version='1.0', description='AI (but even opener)', url='http://github.com/sven1977/aiopening', author='<NAME>',
author_email='<EMAIL>', license='MIT', packages=['aiopening'], zip_safe=False) | [
"setuptools.setup"
] | [((311, 538), 'setuptools.setup', 'setup', ([], {'name': '"""aiopening"""', 'version': '"""1.0"""', 'description': '"""AI (but even opener)"""', 'url': '"""http://github.com/sven1977/aiopening"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'license': '"""MIT"""', 'packages': "['aiopening']", 'zip_safe': '(False)'}), "(name='aiopening', version='1.0', description='AI (but even opener)',\n url='http://github.com/sven1977/aiopening', author='<NAME>',\n author_email='<EMAIL>', license='MIT', packages=['aiopening'], zip_safe\n =False)\n", (316, 538), False, 'from setuptools import setup\n')] |
"""
List of podcasts and their filename parser types.
"""
from .rss_parsers import BaseItem, TalkPythonItem, ChangelogItem, IndieHackersItem
import attr
@attr.s(slots=True, frozen=True)
class Podcast:
name = attr.ib(type=str)
title = attr.ib(type=str)
url = attr.ib(type=str)
rss = attr.ib(type=str)
rss_parser = attr.ib(type=BaseItem)
PODCASTS = [
Podcast(
name="talkpython",
title="Talk Python To Me",
url="https://talkpython.fm",
rss="https://talkpython.fm/episodes/rss",
rss_parser=TalkPythonItem,
),
Podcast(
name="pythonbytes",
title="Python Bytes",
url="https://pythonbytes.fm/",
rss="https://pythonbytes.fm/episodes/rss",
rss_parser=TalkPythonItem,
),
Podcast(
name="changelog",
title="The Changelog",
url="https://changelog.com/podcast",
rss="https://changelog.com/podcast/feed",
rss_parser=ChangelogItem,
),
Podcast(
name="podcastinit",
title="Podcast.__init__",
url="https://www.podcastinit.com/",
rss="https://www.podcastinit.com/feed/mp3/",
rss_parser=BaseItem,
),
Podcast(
name="indiehackers",
title="Indie Hackers",
url="https://www.indiehackers.com/podcast",
rss="http://feeds.backtracks.fm/feeds/indiehackers/indiehackers/feed.xml",
rss_parser=IndieHackersItem,
),
Podcast(
name="realpython",
title="Real Python",
url="https://realpython.com/podcasts/rpp/",
rss="https://realpython.com/podcasts/rpp/feed",
rss_parser=BaseItem,
),
Podcast(
name="kubernetespodcast",
title="Kubernetes Podcast",
url="https://kubernetespodcast.com/",
rss="https://kubernetespodcast.com/feeds/audio.xml",
rss_parser=BaseItem,
),
]
PODCAST_MAP = {p.name: p for p in PODCASTS}
| [
"attr.s",
"attr.ib"
] | [((156, 187), 'attr.s', 'attr.s', ([], {'slots': '(True)', 'frozen': '(True)'}), '(slots=True, frozen=True)\n', (162, 187), False, 'import attr\n'), ((214, 231), 'attr.ib', 'attr.ib', ([], {'type': 'str'}), '(type=str)\n', (221, 231), False, 'import attr\n'), ((244, 261), 'attr.ib', 'attr.ib', ([], {'type': 'str'}), '(type=str)\n', (251, 261), False, 'import attr\n'), ((272, 289), 'attr.ib', 'attr.ib', ([], {'type': 'str'}), '(type=str)\n', (279, 289), False, 'import attr\n'), ((300, 317), 'attr.ib', 'attr.ib', ([], {'type': 'str'}), '(type=str)\n', (307, 317), False, 'import attr\n'), ((335, 357), 'attr.ib', 'attr.ib', ([], {'type': 'BaseItem'}), '(type=BaseItem)\n', (342, 357), False, 'import attr\n')] |
#!/usr/bin/env python
# vim: set fileencoding=utf-8 ts=4 sts=4 sw=4 et tw=80 :
#
# Extract and save extended object catalogs from the specified data and
# uncertainty images. This version of the script jointly analyzes all
# images from a specific AOR/channel to enable more sophisticated
# analysis.
#
# <NAME>
# Created: 2021-02-02
# Last modified: 2021-08-24
#--------------------------------------------------------------------------
#**************************************************************************
#--------------------------------------------------------------------------
## Logging setup:
import logging
#logging.basicConfig(level=logging.DEBUG)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
#logger.setLevel(logging.DEBUG)
logger.setLevel(logging.INFO)
## Current version:
__version__ = "0.3.5"
## Python version-agnostic module reloading:
try:
reload # Python 2.7
except NameError:
try:
from importlib import reload # Python 3.4+
except ImportError:
from imp import reload # Python 3.0 - 3.3
## Modules:
import argparse
import shutil
#import resource
#import signal
import glob
#import gc
import os
import sys
import time
import numpy as np
#from numpy.lib.recfunctions import append_fields
#import datetime as dt
#from dateutil import parser as dtp
#from functools import partial
#from collections import OrderedDict
#from collections.abc import Iterable
#import multiprocessing as mp
#np.set_printoptions(suppress=True, linewidth=160)
_have_np_vers = float('.'.join(np.__version__.split('.')[:2]))
##--------------------------------------------------------------------------##
## Disable buffering on stdout/stderr:
class Unbuffered(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
sys.stdout = Unbuffered(sys.stdout)
sys.stderr = Unbuffered(sys.stderr)
##--------------------------------------------------------------------------##
## Spitzer pipeline filesystem helpers:
try:
import spitz_fs_helpers
reload(spitz_fs_helpers)
except ImportError:
logger.error("failed to import spitz_fs_helpers module!")
sys.exit(1)
sfh = spitz_fs_helpers
## Spitzer pipeline cross-correlation:
try:
import spitz_xcorr_stacking
reload(spitz_xcorr_stacking)
except ImportError:
logger.error("failed to import spitz_xcor_stacking module!")
sys.exit(1)
sxc = spitz_xcorr_stacking.SpitzerXCorr()
## Catalog pruning helpers:
try:
import catalog_tools
reload(catalog_tools)
except ImportError:
logger.error("failed to import catalog_tools module!")
sys.exit(1)
xcp = catalog_tools.XCorrPruner()
## Spitzer star detection routine:
try:
import spitz_extract
reload(spitz_extract)
spf = spitz_extract.SpitzFind()
except ImportError:
logger.error("spitz_extract module not found!")
sys.exit(1)
## Hybrid stack+individual position calculator:
try:
import spitz_stack_astrom
reload(spitz_stack_astrom)
ha = spitz_stack_astrom.HybridAstrom()
except ImportError:
logger.error("failed to import spitz_stack_astrom module!")
sys.exit(1)
## HORIZONS ephemeris tools:
try:
import jpl_eph_helpers
reload(jpl_eph_helpers)
except ImportError:
logger.error("failed to import jpl_eph_helpers module!")
sys.exit(1)
eee = jpl_eph_helpers.EphTool()
##--------------------------------------------------------------------------##
## Fast FITS I/O:
try:
import fitsio
except ImportError:
logger.error("fitsio module not found! Install and retry.")
sys.stderr.write("\nError: fitsio module not found!\n")
sys.exit(1)
## Save FITS image with clobber (fitsio):
def qsave(iname, idata, header=None, **kwargs):
this_func = sys._getframe().f_code.co_name
parent_func = sys._getframe(1).f_code.co_name
sys.stderr.write("Writing to '%s' ... " % iname)
fitsio.write(iname, idata, clobber=True, header=header, **kwargs)
sys.stderr.write("done.\n")
##--------------------------------------------------------------------------##
##------------------ Parse Command Line ----------------##
##--------------------------------------------------------------------------##
## Dividers:
halfdiv = '-' * 40
fulldiv = '-' * 80
## Parse arguments and run script:
class MyParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('error: %s\n' % message)
self.print_help()
sys.exit(2)
## Enable raw text AND display of defaults:
class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter,
argparse.RawDescriptionHelpFormatter):
pass
## Parse the command line:
if __name__ == '__main__':
# ------------------------------------------------------------------
prog_name = os.path.basename(__file__)
descr_txt = """
Extract catalogs from the listed Spitzer data/uncertainty images.
Version: %s
""" % __version__
parser = MyParser(prog=prog_name, description=descr_txt)
#formatter_class=argparse.RawTextHelpFormatter)
# ------------------------------------------------------------------
parser.set_defaults(imtype=None) #'cbcd') #'clean')
#parser.set_defaults(sigthresh=3.0)
parser.set_defaults(sigthresh=2.0)
parser.set_defaults(skip_existing=True)
parser.set_defaults(save_registered=True)
#parser.set_defaults(save_reg_subdir=None)
# ------------------------------------------------------------------
#parser.add_argument('firstpos', help='first positional argument')
#parser.add_argument('-w', '--whatever', required=False, default=5.0,
# help='some option with default [def: %(default)s]', type=float)
# ------------------------------------------------------------------
# ------------------------------------------------------------------
iogroup = parser.add_argument_group('File I/O')
iogroup.add_argument('--overwrite', required=False, dest='skip_existing',
action='store_false', help='overwrite existing catalogs')
#iogroup.add_argument('-E', '--ephem_data', default=None, required=True,
# help='CSV file with SST ephemeris data', type=str)
iogroup.add_argument('-I', '--input_folder', default=None, required=True,
help='where to find input images', type=str)
iogroup.add_argument('-O', '--output_folder', default=None, required=False,
help='where to save extended catalog outputs', type=str)
iogroup.add_argument('-W', '--walk', default=False, action='store_true',
help='recursively walk subfolders to find CBCD images')
imtype = iogroup.add_mutually_exclusive_group()
#imtype.add_argument('--cbcd', required=False, action='store_const',
# dest='imtype', const='cbcd', help='use cbcd images')
imtype.add_argument('--hcfix', required=False, action='store_const',
dest='imtype', const='hcfix', help='use hcfix images')
imtype.add_argument('--clean', required=False, action='store_const',
dest='imtype', const='clean', help='use clean images')
imtype.add_argument('--nudge', required=False, action='store_const',
dest='imtype', const='nudge', help='use nudge images')
#iogroup.add_argument('-R', '--ref_image', default=None, required=True,
# help='KELT image with WCS')
# ------------------------------------------------------------------
# ------------------------------------------------------------------
# Miscellany:
miscgroup = parser.add_argument_group('Miscellany')
miscgroup.add_argument('--debug', dest='debug', default=False,
help='Enable extra debugging messages', action='store_true')
miscgroup.add_argument('-q', '--quiet', action='count', default=0,
help='less progress/status reporting')
miscgroup.add_argument('-v', '--verbose', action='count', default=0,
help='more progress/status reporting')
# ------------------------------------------------------------------
context = parser.parse_args()
context.vlevel = 99 if context.debug else (context.verbose-context.quiet)
context.prog_name = prog_name
# Unless otherwise specified, output goes into input folder:
if not context.output_folder:
context.output_folder = context.input_folder
# Ensure an image type is selected:
if not context.imtype:
sys.stderr.write("\nNo image type selected!\n\n")
sys.exit(1)
## Use imtype-specific folder for registered file output:
#if not context.save_reg_subdir:
# context.save_reg_subdir = 'aligned_%s' % context.imtype
##--------------------------------------------------------------------------##
##------------------ Make Input Image List ----------------##
##--------------------------------------------------------------------------##
tstart = time.time()
sys.stderr.write("Listing %s frames ... " % context.imtype)
#im_wildpath = 'SPITZ*%s.fits' % context.imtype
#im_wildcard = os.path.join(context.input_folder, 'SPIT*'
#_img_types = ['cbcd', 'clean', 'cbunc']
#_type_suff = dict([(x, x+'.fits') for x in _im_types])
#img_list = {}
#for imsuff in suffixes:
# wpath = '%s/SPITZ*%s.fits' % (context.input_folder, imsuff)
# img_list[imsuff] = sorted(glob.glob(os.path.join(context.
#img_files = sorted(glob.glob(os.path.join(context.input_folder, im_wildpath)))
if context.walk:
img_files = sfh.get_files_walk(context.input_folder, flavor=context.imtype)
else:
img_files = sfh.get_files_single(context.input_folder, flavor=context.imtype)
sys.stderr.write("done.\n")
## Abort in case of no input:
if not img_files:
sys.stderr.write("No input (%s) files found in folder:\n" % context.imtype)
sys.stderr.write("--> %s\n\n" % context.input_folder)
sys.exit(1)
n_images = len(img_files)
## List of uncertainty frames (warn if any missing):
#unc_files = [x.replace(context.imtype, 'cbunc') for x in img_files]
#sys.stderr.write("Checking error-images ... ")
#have_unc = [os.path.isfile(x) for x in unc_files]
#if not all(have_unc):
# sys.stderr.write("WARNING: some uncertainty frames missing!\n")
#else:
# sys.stderr.write("done.\n")
##--------------------------------------------------------------------------##
##------------------ Load SST Ephemeris Data ----------------##
##--------------------------------------------------------------------------##
### Ephemeris data file must exist:
#if not context.ephem_data:
# logger.error("context.ephem_data not set?!?!")
# sys.exit(1)
#if not os.path.isfile(context.ephem_data):
# logger.error("Ephemeris file not found: %s" % context.ephem_data)
# sys.exit(1)
#
### Load ephemeris data:
#eee.load(context.ephem_data)
##--------------------------------------------------------------------------##
##------------------ Unique AOR/Channel Combos ----------------##
##--------------------------------------------------------------------------##
unique_tags = sorted(list(set([sfh.get_irac_aor_tag(x) for x in img_files])))
images_by_tag = {x:[] for x in unique_tags}
for ii in img_files:
images_by_tag[sfh.get_irac_aor_tag(ii)].append(ii)
##--------------------------------------------------------------------------##
##------------------ Diagnostic Region Files ----------------##
##--------------------------------------------------------------------------##
def regify_excat_pix(data, rpath, win=False, rr=2.0):
colnames = ('wx', 'wy') if win else ('x', 'y')
xpix, ypix = [data[x] for x in colnames]
with open(rpath, 'w') as rfile:
for xx,yy in zip(xpix, ypix):
rfile.write("image; circle(%8.3f, %8.3f, %8.3f)\n" % (xx, yy, rr))
return
##--------------------------------------------------------------------------##
##------------------ ExtendedCatalog Ephem Format ----------------##
##--------------------------------------------------------------------------##
#def reformat_ephem(edata):
##--------------------------------------------------------------------------##
##------------------ Stack/Image Comparison ----------------##
##--------------------------------------------------------------------------##
#def xcheck(idata, sdata):
# nstack = len(sdata)
# nimage = len(idata)
# sys.stderr.write("nstack: %d\n" % nstack)
# sys.stderr.write("nimage: %d\n" % nimage)
# return
##--------------------------------------------------------------------------##
##------------------ Process All Images ----------------##
##--------------------------------------------------------------------------##
ntodo = 0
nproc = 0
ntotal = len(img_files)
min_sobj = 10 # bark if fewer than this many found in stack
skip_stuff = False
#context.save_registered = False
#context.skip_existing = False
## Reduce bright pixel threshold:
#sxc.set_bp_thresh(10.0)
#sxc.set_bp_thresh(5.0)
sxc.set_bp_thresh(10.0)
#sxc.set_vlevel(10)
sxc.set_roi_rfrac(0.90)
sxc.set_roi_rfrac(2.00)
#sys.exit(0)
#for aor_tag,tag_files in images_by_tag.items():
for aor_tag in unique_tags:
sys.stderr.write("\n\nProcessing images from %s ...\n" % aor_tag)
tag_files = images_by_tag[aor_tag]
n_tagged = len(tag_files)
if n_tagged < 2:
sys.stderr.write("WARNING: only %d images with tag %s\n"
% (n_tagged, aor_tag))
sys.stderr.write("This case is not currently handled ...\n")
sys.exit(1)
# File/folder paths:
aor_dir = os.path.dirname(tag_files[0])
stack_ibase = '%s_%s_stack.fits' % (aor_tag, context.imtype)
stack_cbase = '%s_%s_stack.fcat' % (aor_tag, context.imtype)
medze_ibase = '%s_%s_medze.fits' % (aor_tag, context.imtype)
stack_ipath = os.path.join(aor_dir, stack_ibase)
stack_cpath = os.path.join(aor_dir, stack_cbase)
medze_ipath = os.path.join(aor_dir, medze_ibase)
#sys.stderr.write("stack_ibase: %s\n" % stack_ibase)
#sys.stderr.write("As of this point ...\n")
#sys.stderr.write("sxc._roi_rfrac: %.5f\n" % sxc._roi_rfrac)
sys.stderr.write("Cross-correlating and stacking ... ")
result = sxc.shift_and_stack(tag_files)
sys.stderr.write("done.\n")
sxc.save_istack(stack_ipath)
#sys.exit(0)
#istack = sxc.get_stacked()
#qsave(stack_ipath, istack)
# Dump registered data to disk:
if context.save_registered:
save_reg_subdir = 'aligned_%s_%s' % (aor_tag, context.imtype)
sys.stderr.write("Saving registered frames for inspection ...\n")
#reg_dir = os.path.join(aor_dir, context.save_reg_subdir)
reg_dir = os.path.join(aor_dir, save_reg_subdir)
if os.path.isdir(reg_dir):
shutil.rmtree(reg_dir)
os.mkdir(reg_dir)
sxc.dump_registered_images(reg_dir)
sxc.dump_bright_pixel_masks(reg_dir)
sys.stderr.write("\n")
# Extract stars from stacked image:
spf.use_images(ipath=stack_ipath)
stack_cat = spf.find_stars(context.sigthresh)
sdata = stack_cat.get_catalog()
nsobj = len(sdata)
sys.stderr.write(" \nFound %d sources in stacked image.\n\n" % nsobj)
if (nsobj < min_sobj):
sys.stderr.write("Fewer than %d objects found in stack ... \n" % min_sobj)
sys.stderr.write("Found %d objects.\n\n" % nsobj)
sys.stderr.write("--> %s\n\n" % stack_ipath)
sys.exit(1)
stack_cat.save_as_fits(stack_cpath, overwrite=True)
# region file for diagnostics:
stack_rfile = stack_ipath + '.reg'
regify_excat_pix(sdata, stack_rfile, win=True)
# Make/save 'medianize' stack for comparison:
sxc.make_mstack()
sxc.save_mstack(medze_ipath)
# Set up pruning system:
xshifts, yshifts = sxc.get_stackcat_offsets()
xcp.set_master_catalog(sdata)
xcp.set_image_offsets(xshifts, yshifts)
# Set up hybrid astrometry system:
ha.set_stack_excat(stack_cat) # catalog of detections
ha.set_xcorr_metadata(sxc) # pixel offsets by image
## Stop here for now ...
#if skip_stuff:
# continue
# process individual files with cross-correlation help:
for ii,img_ipath in enumerate(tag_files, 1):
sys.stderr.write("%s\n" % fulldiv)
unc_ipath = img_ipath.replace(context.imtype, 'cbunc')
if not os.path.isfile(unc_ipath):
sys.stderr.write("WARNING: file not found:\n--> %s\n" % unc_ipath)
continue
img_ibase = os.path.basename(img_ipath)
#cat_ibase = img_ibase.replace(context.imtype, 'fcat')
cat_fbase = img_ibase + '.fcat'
cat_pbase = img_ibase + '.pcat'
cat_mbase = img_ibase + '.mcat'
### FIXME ###
### context.output_folder is not appropriate for walk mode ...
save_dir = context.output_folder # NOT FOR WALK MODE
save_dir = os.path.dirname(img_ipath)
cat_fpath = os.path.join(save_dir, cat_fbase)
cat_ppath = os.path.join(save_dir, cat_pbase)
cat_mpath = os.path.join(save_dir, cat_mbase)
### FIXME ###
sys.stderr.write("Catalog %s ... " % cat_fpath)
if context.skip_existing:
if os.path.isfile(cat_mpath):
sys.stderr.write("exists! Skipping ... \n")
continue
nproc += 1
sys.stderr.write("not found ... creating ...\n")
spf.use_images(ipath=img_ipath, upath=unc_ipath)
result = spf.find_stars(context.sigthresh)
## FIXME: this just grabs the ephemeris from the header content
## of the first ExtendedCatalog produced. This should be obtained
## separately to make things easier to follow (and to eliminate
## the need to pre-modify the image headers ...)
eph_data = eee.eph_from_header(result.get_header())
result.set_ephem(eph_data)
result.save_as_fits(cat_fpath, overwrite=True)
nfound = len(result.get_catalog())
frame_rfile = img_ipath + '.reg'
regify_excat_pix(result.get_catalog(), frame_rfile, win=True)
# prune sources not detected in stacked frame:
pruned = xcp.prune_spurious(result.get_catalog(), img_ipath)
npruned = len(pruned)
sys.stderr.write("nfound: %d, npruned: %d\n" % (nfound, npruned))
if (len(pruned) < 5):
sys.stderr.write("BARKBARKBARK\n")
sys.exit(1)
result.set_catalog(pruned)
result.save_as_fits(cat_ppath, overwrite=True)
# build and save hybrid catalog:
mcat = ha.make_hybrid_excat(result)
mcat.set_ephem(eph_data)
mcat.save_as_fits(cat_mpath, overwrite=True)
mxcat_rfile = img_ipath + '.mcat.reg'
#regify_excat_pix(mcat.get_catalog(), mxcat_rfile, win=True)
# stop early if requested:
if (ntodo > 0) and (nproc >= ntodo):
break
#break
#sys.exit(0)
if (ntodo > 0) and (nproc >= ntodo):
break
tstop = time.time()
ttook = tstop - tstart
sys.stderr.write("Extraction completed in %.3f seconds.\n" % ttook)
#import astropy.io.fits as pf
#
#imra = np.array([hh['CRVAL1'] for hh in sxc._im_hdrs])
#imde = np.array([hh['CRVAL2'] for hh in sxc._im_hdrs])
#
##sys.stderr.write("\n\n\n")
##sys.stderr.write("sxc.shift_and_stack(tag_files)\n")
##result = sxc.shift_and_stack(tag_files)
#sys.exit(0)
#
#layers = sxc.pad_and_shift(sxc._im_data, sxc._x_shifts, sxc._y_shifts)
#tstack = sxc.dumb_stack(layers)
#pf.writeto('tstack.fits', tstack, overwrite=True)
#
#tdir = 'zzz'
#if not os.path.isdir(tdir):
# os.mkdir(tdir)
#
##tag_bases = [os.path.basename(x) for x in tag_files]
##for ibase,idata in zip(tag_bases, layers):
## tsave = os.path.join(tdir, 'r' + ibase)
## sys.stderr.write("Saving %s ... \n" % tsave)
## pf.writeto(tsave, idata, overwrite=True)
#
#sys.stderr.write("\n\n\n")
#sys.stderr.write("visual inspection with:\n")
#sys.stderr.write("flztfs %s\n" % ' '.join(tag_files))
##--------------------------------------------------------------------------##
######################################################################
# CHANGELOG (07_spitzer_aor_extraction.py):
#---------------------------------------------------------------------
#
# 2021-02-02:
# -- Increased __version__ to 0.1.0.
# -- First created 07_spitzer_aor_extraction.py.
#
| [
"logging.getLogger",
"sys.exit",
"jpl_eph_helpers.EphTool",
"sys._getframe",
"os.path.isdir",
"os.mkdir",
"spitz_extract.SpitzFind",
"imp.reload",
"os.path.isfile",
"sys.stderr.write",
"catalog_tools.XCorrPruner",
"os.path.dirname",
"time.time",
"logging.basicConfig",
"numpy.__version__.... | [((672, 711), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (691, 711), False, 'import logging\n'), ((721, 748), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (738, 748), False, 'import logging\n'), ((2585, 2620), 'spitz_xcorr_stacking.SpitzerXCorr', 'spitz_xcorr_stacking.SpitzerXCorr', ([], {}), '()\n', (2618, 2620), False, 'import spitz_xcorr_stacking\n'), ((2807, 2834), 'catalog_tools.XCorrPruner', 'catalog_tools.XCorrPruner', ([], {}), '()\n', (2832, 2834), False, 'import catalog_tools\n'), ((3502, 3527), 'jpl_eph_helpers.EphTool', 'jpl_eph_helpers.EphTool', ([], {}), '()\n', (3525, 3527), False, 'import jpl_eph_helpers\n'), ((9088, 9099), 'time.time', 'time.time', ([], {}), '()\n', (9097, 9099), False, 'import time\n'), ((9100, 9159), 'sys.stderr.write', 'sys.stderr.write', (["('Listing %s frames ... ' % context.imtype)"], {}), "('Listing %s frames ... ' % context.imtype)\n", (9116, 9159), False, 'import sys\n'), ((9798, 9825), 'sys.stderr.write', 'sys.stderr.write', (['"""done.\n"""'], {}), "('done.\\n')\n", (9814, 9825), False, 'import sys\n'), ((19163, 19174), 'time.time', 'time.time', ([], {}), '()\n', (19172, 19174), False, 'import time\n'), ((19198, 19265), 'sys.stderr.write', 'sys.stderr.write', (["('Extraction completed in %.3f seconds.\\n' % ttook)"], {}), "('Extraction completed in %.3f seconds.\\n' % ttook)\n", (19214, 19265), False, 'import sys\n'), ((2222, 2246), 'imp.reload', 'reload', (['spitz_fs_helpers'], {}), '(spitz_fs_helpers)\n', (2228, 2246), False, 'from imp import reload\n'), ((2449, 2477), 'imp.reload', 'reload', (['spitz_xcorr_stacking'], {}), '(spitz_xcorr_stacking)\n', (2455, 2477), False, 'from imp import reload\n'), ((2684, 2705), 'imp.reload', 'reload', (['catalog_tools'], {}), '(catalog_tools)\n', (2690, 2705), False, 'from imp import reload\n'), ((2905, 2926), 'imp.reload', 'reload', (['spitz_extract'], {}), '(spitz_extract)\n', (2911, 2926), False, 'from imp import reload\n'), ((2937, 2962), 'spitz_extract.SpitzFind', 'spitz_extract.SpitzFind', ([], {}), '()\n', (2960, 2962), False, 'import spitz_extract\n'), ((3139, 3165), 'imp.reload', 'reload', (['spitz_stack_astrom'], {}), '(spitz_stack_astrom)\n', (3145, 3165), False, 'from imp import reload\n'), ((3175, 3208), 'spitz_stack_astrom.HybridAstrom', 'spitz_stack_astrom.HybridAstrom', ([], {}), '()\n', (3206, 3208), False, 'import spitz_stack_astrom\n'), ((3375, 3398), 'imp.reload', 'reload', (['jpl_eph_helpers'], {}), '(jpl_eph_helpers)\n', (3381, 3398), False, 'from imp import reload\n'), ((4002, 4050), 'sys.stderr.write', 'sys.stderr.write', (['("Writing to \'%s\' ... " % iname)'], {}), '("Writing to \'%s\' ... " % iname)\n', (4018, 4050), False, 'import sys\n'), ((4055, 4120), 'fitsio.write', 'fitsio.write', (['iname', 'idata'], {'clobber': '(True)', 'header': 'header'}), '(iname, idata, clobber=True, header=header, **kwargs)\n', (4067, 4120), False, 'import fitsio\n'), ((4125, 4152), 'sys.stderr.write', 'sys.stderr.write', (['"""done.\n"""'], {}), "('done.\\n')\n", (4141, 4152), False, 'import sys\n'), ((4970, 4996), 'os.path.basename', 'os.path.basename', (['__file__'], {}), '(__file__)\n', (4986, 4996), False, 'import os\n'), ((9879, 9954), 'sys.stderr.write', 'sys.stderr.write', (["('No input (%s) files found in folder:\\n' % context.imtype)"], {}), "('No input (%s) files found in folder:\\n' % context.imtype)\n", (9895, 9954), False, 'import sys\n'), ((9959, 10012), 'sys.stderr.write', 'sys.stderr.write', (["('--> %s\\n\\n' % context.input_folder)"], {}), "('--> %s\\n\\n' % context.input_folder)\n", (9975, 10012), False, 'import sys\n'), ((10017, 10028), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (10025, 10028), False, 'import sys\n'), ((13359, 13425), 'sys.stderr.write', 'sys.stderr.write', (['("""\n\nProcessing images from %s ...\n""" % aor_tag)'], {}), '("""\n\nProcessing images from %s ...\n""" % aor_tag)\n', (13375, 13425), False, 'import sys\n'), ((13749, 13778), 'os.path.dirname', 'os.path.dirname', (['tag_files[0]'], {}), '(tag_files[0])\n', (13764, 13778), False, 'import os\n'), ((13992, 14026), 'os.path.join', 'os.path.join', (['aor_dir', 'stack_ibase'], {}), '(aor_dir, stack_ibase)\n', (14004, 14026), False, 'import os\n'), ((14045, 14079), 'os.path.join', 'os.path.join', (['aor_dir', 'stack_cbase'], {}), '(aor_dir, stack_cbase)\n', (14057, 14079), False, 'import os\n'), ((14098, 14132), 'os.path.join', 'os.path.join', (['aor_dir', 'medze_ibase'], {}), '(aor_dir, medze_ibase)\n', (14110, 14132), False, 'import os\n'), ((14309, 14364), 'sys.stderr.write', 'sys.stderr.write', (['"""Cross-correlating and stacking ... """'], {}), "('Cross-correlating and stacking ... ')\n", (14325, 14364), False, 'import sys\n'), ((14413, 14440), 'sys.stderr.write', 'sys.stderr.write', (['"""done.\n"""'], {}), "('done.\\n')\n", (14429, 14440), False, 'import sys\n'), ((15299, 15369), 'sys.stderr.write', 'sys.stderr.write', (['(""" \nFound %d sources in stacked image.\n\n""" % nsobj)'], {}), '(""" \nFound %d sources in stacked image.\n\n""" % nsobj)\n', (15315, 15369), False, 'import sys\n'), ((2333, 2344), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2341, 2344), False, 'import sys\n'), ((2567, 2578), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2575, 2578), False, 'import sys\n'), ((2789, 2800), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2797, 2800), False, 'import sys\n'), ((3039, 3050), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3047, 3050), False, 'import sys\n'), ((3297, 3308), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3305, 3308), False, 'import sys\n'), ((3484, 3495), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3492, 3495), False, 'import sys\n'), ((3738, 3795), 'sys.stderr.write', 'sys.stderr.write', (['"""\nError: fitsio module not found!\n"""'], {}), '("""\nError: fitsio module not found!\n""")\n', (3754, 3795), False, 'import sys\n'), ((3798, 3809), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3806, 3809), False, 'import sys\n'), ((4558, 4599), 'sys.stderr.write', 'sys.stderr.write', (["('error: %s\\n' % message)"], {}), "('error: %s\\n' % message)\n", (4574, 4599), False, 'import sys\n'), ((4634, 4645), 'sys.exit', 'sys.exit', (['(2)'], {}), '(2)\n', (4642, 4645), False, 'import sys\n'), ((8604, 8654), 'sys.stderr.write', 'sys.stderr.write', (['"""\nNo image type selected!\n\n"""'], {}), '("""\nNo image type selected!\n\n""")\n', (8620, 8654), False, 'import sys\n'), ((8662, 8673), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (8670, 8673), False, 'import sys\n'), ((13524, 13603), 'sys.stderr.write', 'sys.stderr.write', (["('WARNING: only %d images with tag %s\\n' % (n_tagged, aor_tag))"], {}), "('WARNING: only %d images with tag %s\\n' % (n_tagged, aor_tag))\n", (13540, 13603), False, 'import sys\n'), ((13628, 13688), 'sys.stderr.write', 'sys.stderr.write', (['"""This case is not currently handled ...\n"""'], {}), "('This case is not currently handled ...\\n')\n", (13644, 13688), False, 'import sys\n'), ((13697, 13708), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (13705, 13708), False, 'import sys\n'), ((14702, 14767), 'sys.stderr.write', 'sys.stderr.write', (['"""Saving registered frames for inspection ...\n"""'], {}), "('Saving registered frames for inspection ...\\n')\n", (14718, 14767), False, 'import sys\n'), ((14852, 14890), 'os.path.join', 'os.path.join', (['aor_dir', 'save_reg_subdir'], {}), '(aor_dir, save_reg_subdir)\n', (14864, 14890), False, 'import os\n'), ((14902, 14924), 'os.path.isdir', 'os.path.isdir', (['reg_dir'], {}), '(reg_dir)\n', (14915, 14924), False, 'import os\n'), ((14969, 14986), 'os.mkdir', 'os.mkdir', (['reg_dir'], {}), '(reg_dir)\n', (14977, 14986), False, 'import os\n'), ((15084, 15106), 'sys.stderr.write', 'sys.stderr.write', (['"""\n"""'], {}), "('\\n')\n", (15100, 15106), False, 'import sys\n'), ((15404, 15478), 'sys.stderr.write', 'sys.stderr.write', (["('Fewer than %d objects found in stack ... \\n' % min_sobj)"], {}), "('Fewer than %d objects found in stack ... \\n' % min_sobj)\n", (15420, 15478), False, 'import sys\n'), ((15487, 15536), 'sys.stderr.write', 'sys.stderr.write', (["('Found %d objects.\\n\\n' % nsobj)"], {}), "('Found %d objects.\\n\\n' % nsobj)\n", (15503, 15536), False, 'import sys\n'), ((15545, 15589), 'sys.stderr.write', 'sys.stderr.write', (["('--> %s\\n\\n' % stack_ipath)"], {}), "('--> %s\\n\\n' % stack_ipath)\n", (15561, 15589), False, 'import sys\n'), ((15598, 15609), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (15606, 15609), False, 'import sys\n'), ((16412, 16446), 'sys.stderr.write', 'sys.stderr.write', (["('%s\\n' % fulldiv)"], {}), "('%s\\n' % fulldiv)\n", (16428, 16446), False, 'import sys\n'), ((16672, 16699), 'os.path.basename', 'os.path.basename', (['img_ipath'], {}), '(img_ipath)\n', (16688, 16699), False, 'import os\n'), ((17060, 17086), 'os.path.dirname', 'os.path.dirname', (['img_ipath'], {}), '(img_ipath)\n', (17075, 17086), False, 'import os\n'), ((17107, 17140), 'os.path.join', 'os.path.join', (['save_dir', 'cat_fbase'], {}), '(save_dir, cat_fbase)\n', (17119, 17140), False, 'import os\n'), ((17161, 17194), 'os.path.join', 'os.path.join', (['save_dir', 'cat_pbase'], {}), '(save_dir, cat_pbase)\n', (17173, 17194), False, 'import os\n'), ((17215, 17248), 'os.path.join', 'os.path.join', (['save_dir', 'cat_mbase'], {}), '(save_dir, cat_mbase)\n', (17227, 17248), False, 'import os\n'), ((17280, 17327), 'sys.stderr.write', 'sys.stderr.write', (["('Catalog %s ... ' % cat_fpath)"], {}), "('Catalog %s ... ' % cat_fpath)\n", (17296, 17327), False, 'import sys\n'), ((17517, 17565), 'sys.stderr.write', 'sys.stderr.write', (['"""not found ... creating ...\n"""'], {}), "('not found ... creating ...\\n')\n", (17533, 17565), False, 'import sys\n'), ((18419, 18484), 'sys.stderr.write', 'sys.stderr.write', (["('nfound: %d, npruned: %d\\n' % (nfound, npruned))"], {}), "('nfound: %d, npruned: %d\\n' % (nfound, npruned))\n", (18435, 18484), False, 'import sys\n'), ((1599, 1624), 'numpy.__version__.split', 'np.__version__.split', (['"""."""'], {}), "('.')\n", (1619, 1624), True, 'import numpy as np\n'), ((3917, 3932), 'sys._getframe', 'sys._getframe', ([], {}), '()\n', (3930, 3932), False, 'import sys\n'), ((3966, 3982), 'sys._getframe', 'sys._getframe', (['(1)'], {}), '(1)\n', (3979, 3982), False, 'import sys\n'), ((14938, 14960), 'shutil.rmtree', 'shutil.rmtree', (['reg_dir'], {}), '(reg_dir)\n', (14951, 14960), False, 'import shutil\n'), ((16525, 16550), 'os.path.isfile', 'os.path.isfile', (['unc_ipath'], {}), '(unc_ipath)\n', (16539, 16550), False, 'import os\n'), ((16564, 16632), 'sys.stderr.write', 'sys.stderr.write', (['("""WARNING: file not found:\n--> %s\n""" % unc_ipath)'], {}), '("""WARNING: file not found:\n--> %s\n""" % unc_ipath)\n', (16580, 16632), False, 'import sys\n'), ((17377, 17402), 'os.path.isfile', 'os.path.isfile', (['cat_mpath'], {}), '(cat_mpath)\n', (17391, 17402), False, 'import os\n'), ((18527, 18561), 'sys.stderr.write', 'sys.stderr.write', (['"""BARKBARKBARK\n"""'], {}), "('BARKBARKBARK\\n')\n", (18543, 18561), False, 'import sys\n'), ((18574, 18585), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (18582, 18585), False, 'import sys\n'), ((17420, 17464), 'sys.stderr.write', 'sys.stderr.write', (['"""exists! Skipping ... \n"""'], {}), "('exists! Skipping ... \\n')\n", (17436, 17464), False, 'import sys\n')] |
"""
Helper functions to visualize a graph in a notebook or save the plot to file.
Import as:
import dataflow.core.visualization as dtfcorvisu
"""
import IPython
import networkx as networ
import pygraphviz
import dataflow.core.dag as dtfcordag
import helpers.hdbg as hdbg
import helpers.hio as hio
def draw(dag: dtfcordag.DAG) -> IPython.core.display.Image:
"""
Render DAG in a notebook.
"""
agraph = _extract_agraph_from_dag(dag)
image = IPython.display.Image(agraph.draw(format="png", prog="dot"))
return image
def draw_to_file(dag: dtfcordag.DAG, file_name: str = "graph.png") -> str:
"""
Save DAG rendering to a file.
"""
agraph = _extract_agraph_from_dag(dag)
# Save to file.
hio.create_enclosing_dir(file_name)
agraph.draw(file_name, prog="dot")
return file_name
def _extract_agraph_from_dag(dag: dtfcordag.DAG) -> pygraphviz.agraph.AGraph:
"""
Extract a pygraphviz `agraph` from a DAG.
"""
# Extract networkx DAG.
hdbg.dassert_isinstance(dag, dtfcordag.DAG)
graph = dag.dag
hdbg.dassert_isinstance(graph, networ.Graph)
# Convert the DAG into a pygraphviz graph.
agraph = networ.nx_agraph.to_agraph(graph)
return agraph
| [
"helpers.hdbg.dassert_isinstance",
"helpers.hio.create_enclosing_dir",
"networkx.nx_agraph.to_agraph"
] | [((736, 771), 'helpers.hio.create_enclosing_dir', 'hio.create_enclosing_dir', (['file_name'], {}), '(file_name)\n', (760, 771), True, 'import helpers.hio as hio\n'), ((1006, 1049), 'helpers.hdbg.dassert_isinstance', 'hdbg.dassert_isinstance', (['dag', 'dtfcordag.DAG'], {}), '(dag, dtfcordag.DAG)\n', (1029, 1049), True, 'import helpers.hdbg as hdbg\n'), ((1074, 1118), 'helpers.hdbg.dassert_isinstance', 'hdbg.dassert_isinstance', (['graph', 'networ.Graph'], {}), '(graph, networ.Graph)\n', (1097, 1118), True, 'import helpers.hdbg as hdbg\n'), ((1179, 1212), 'networkx.nx_agraph.to_agraph', 'networ.nx_agraph.to_agraph', (['graph'], {}), '(graph)\n', (1205, 1212), True, 'import networkx as networ\n')] |
"""Calculate pixel errors for a single run or all runs in an experiment dir."""
import torch
import itertools
import numpy as np
import imageio
import argparse
import os
import glob
from model.main import main as restore_model
from model.utils.utils import bw_transform
os.environ["CUDA_VISIBLE_DEVICES"] = '-1'
def run_fmt(x, with_under=False):
"""Format array x of ints to become valid run folder names."""
return 'run{:03d}'.format(x) if not with_under else 'run_{:03d}'.format(x)
def get_pixel_error(restore, linear=False, path='', real_mpe=False, checkpoint='checkpoint'):
"""Restore a model and calculate error from reconstructions."""
# do not write any new runs
extras = {
'nolog': True,
'checkpoint_path': os.path.join(restore, checkpoint)}
self = restore_model(restore=restore, extras=extras)
# ignore supairvised runs for now
if self.c.supairvised is True:
return None
# make sure all runs access the same data!
print(self.c.testdata)
step = self.c.frame_step
visible = self.c.num_visible
batch_size = self.c.batch_size
skip = self.c.skip
# make sure this is the same
print(step, visible, batch_size, skip)
long_rollout_length = self.c.num_frames // step - visible
lrl = long_rollout_length
total_images = self.test_dataset.total_img
total_labels = self.test_dataset.total_data
# apply step and batch size once
total_images = total_images[:batch_size, ::step]
total_labels = total_labels[:batch_size, ::step]
# true data to compare against
true_images = total_images[:, skip:(visible+long_rollout_length)]
true_images = torch.tensor(true_images).to(self.c.device).type(self.c.dtype)
# First obtain reconstruction of input.
stove_input = total_images[:, :visible]
stove_input = torch.tensor(stove_input).to(self.c.device).type(self.c.dtype)
_, prop_dict2, _ = self.stove(stove_input, self.c.plot_every)
z_recon = prop_dict2['z']
# Use last state to do rollout
if not linear:
z_pred, _ = self.stove.rollout(z_recon[:, -1], long_rollout_length)
else:
# propagate last speed
v = z_recon[:, -1, :, 4:6].unsqueeze(1)
v = v.repeat(1, long_rollout_length, 1, 1)
t = torch.arange(1, long_rollout_length+1)
t = t.repeat(v.shape[0], *v.shape[2:], 1).permute(0, 3, 1, 2).double()
dx = v * t
new_x = z_recon[:, -1, :, 2:4].unsqueeze(1)
new_x = new_x.repeat(1, long_rollout_length, 1, 1) + dx
z_pred = torch.cat(
[z_recon[:, -1, :, :2].unsqueeze(1).repeat(1, lrl, 1, 1),
new_x,
v,
z_recon[:, -1, :, 6:].unsqueeze(1).repeat(1, lrl, 1, 1)],
-1
)
z_seq = torch.cat([z_recon, z_pred], 1)
# sigmoid positions to make errors comparable
if linear:
print('clamp positions to 0.9')
frame_lim = 0.8 if self.c.coord_lim == 10 else 0.9
z_seq = torch.cat([
z_seq[..., :2],
torch.clamp(z_seq[..., 2:4], -frame_lim, frame_lim),
z_seq[..., 6:]], -1)
# Simple Reconstruction of Sequences
# stove_input = total_images[:10]
# stove_input = torch.tensor(stove_input).to(self.c.device).type(self.c.dtype)
# elbo, prop_dict2, _ = self.stove(stove_input, self.c.plot_every)
# z_recon = prop_dict2['z']
# if self.c.debug_bw:
# img = stove_input.sum(2)
# img = torch.clamp(img, 0, 1)
# img = torch.unsqueeze(img, 2)
# model_images = self.stove.reconstruct_from_z(
# z_recon, img[:, skip:], max_activation=False, single_image=False)
# use mpe to get reconstructed images
if real_mpe:
if self.c.debug_bw:
img = stove_input[:, skip].sum(1)
img = torch.clamp(img, 0, 1)
img = torch.unsqueeze(img, 1)
model_images = self.stove.reconstruct_from_z(
z_seq, img, max_activation=False, single_image=True)
else:
model_images = self.stove.reconstruct_from_z(z_seq)
if self.c.debug_bw:
true_images = bw_transform(true_images)
model_images = torch.clamp(model_images, 0, 1)
mse = torch.mean(((true_images - model_images)**2), dim=(0, 2, 3, 4))
plot_sample = model_images[:10, :, 0].detach().cpu().numpy()
plot_sample = (255 * plot_sample.reshape(-1, self.c.height, self.c.width))
plot_sample = plot_sample.astype(np.uint8)
filename = 'linear_' if linear else ''
filename += 'pixel_error_sample.gif'
filepath = os.path.join(path, filename)
print('Saving gif to ', filepath)
imageio.mimsave(
filepath, plot_sample, fps=24)
# also log state differences
# bug_potential... for some reason self.c.coord_lim is 30 but max
# true_states is 10 for gravity
true_states = total_labels[:, skip:(visible+long_rollout_length)]
print(true_states.max(), ' is coord max.')
true_states = torch.tensor(true_states).to(self.c.device).type(self.c.dtype)
permutations = list(itertools.permutations(range(0, self.c.num_obj)))
errors = []
for perm in permutations:
error = ((true_states[:, :5, :, :2]-z_seq[:, :5, perm, 2:4])**2).sum(-1)
error = torch.sqrt(error).mean((1, 2))
errors += [error]
errors = torch.stack(errors, 1)
_, idx = errors.min(1)
selector = list(zip(range(idx.shape[0]), idx.cpu().tolist()))
pos_matched = [z_seq[i, :, permutations[j]] for i, j in selector]
pos_matched = torch.stack(pos_matched, 0)
mse_states = torch.sqrt(((
true_states[..., :2] - pos_matched[..., 2:4])**2).sum(-1)).mean((0, 2))
return mse, mse_states
def main(script_args):
"""Parse arguments, find runs, execute pixel_error."""
parser = argparse.ArgumentParser()
parser.add_argument(
"-p", "--path", type=str,
help="Set folder from which to create pixel errors for." +
"Must contain runs of model.")
parser.add_argument(
'--linear', action='store_true',
help='create linear errors')
parser.add_argument(
'--no-save', dest='no_save', action='store_true')
parser.add_argument(
'--real-mpe', dest='real_mpe', action='store_true')
parser.add_argument(
'--checkpoint', type=str, default='checkpoint')
args = parser.parse_args(script_args)
filename = 'pixel_errors.csv'
if args.linear:
filename = 'linear_' + filename
if 'run' not in args.path[-10:]:
restores = glob.glob(args.path+'run*')
restores = sorted(restores)
else:
restores = [args.path]
print(restores)
if len(restores) == 0:
raise ValueError('No runs found in path {}.'.format(args.path))
# debug
# mse, mse_states = get_pixel_error(
# restores[0], args.linear, args.path, args.real_mpe, args.checkpoint)
# return 0
for restore in restores:
try:
mse, mse_states = get_pixel_error(
restore, args.linear, args.path, args.real_mpe, args.checkpoint)
except Exception as e:
print(e)
print('Not possible for run {}.'.format(restore))
continue
mse = mse.cpu().detach().numpy()
if args.no_save:
continue
save_dir = os.path.join(args.path, 'test')
if not os.path.exists(save_dir):
os.makedirs(save_dir)
with open(os.path.join(save_dir, filename), 'a') as f:
f.write(','.join(['{:.6f}'.format(i) for i in mse])+'\n')
with open(os.path.join(save_dir, 'states_'+filename), 'a') as f:
f.write(','.join(['{:.6f}'.format(i) for i in mse_states])+'\n')
| [
"os.path.exists",
"argparse.ArgumentParser",
"model.main.main",
"torch.mean",
"torch.unsqueeze",
"model.utils.utils.bw_transform",
"torch.stack",
"os.path.join",
"os.makedirs",
"torch.sqrt",
"torch.cat",
"torch.tensor",
"torch.arange",
"glob.glob",
"imageio.mimsave",
"torch.clamp"
] | [((805, 850), 'model.main.main', 'restore_model', ([], {'restore': 'restore', 'extras': 'extras'}), '(restore=restore, extras=extras)\n', (818, 850), True, 'from model.main import main as restore_model\n'), ((2788, 2819), 'torch.cat', 'torch.cat', (['[z_recon, z_pred]', '(1)'], {}), '([z_recon, z_pred], 1)\n', (2797, 2819), False, 'import torch\n'), ((4176, 4207), 'torch.clamp', 'torch.clamp', (['model_images', '(0)', '(1)'], {}), '(model_images, 0, 1)\n', (4187, 4207), False, 'import torch\n'), ((4218, 4281), 'torch.mean', 'torch.mean', (['((true_images - model_images) ** 2)'], {'dim': '(0, 2, 3, 4)'}), '((true_images - model_images) ** 2, dim=(0, 2, 3, 4))\n', (4228, 4281), False, 'import torch\n'), ((4574, 4602), 'os.path.join', 'os.path.join', (['path', 'filename'], {}), '(path, filename)\n', (4586, 4602), False, 'import os\n'), ((4645, 4691), 'imageio.mimsave', 'imageio.mimsave', (['filepath', 'plot_sample'], {'fps': '(24)'}), '(filepath, plot_sample, fps=24)\n', (4660, 4691), False, 'import imageio\n'), ((5327, 5349), 'torch.stack', 'torch.stack', (['errors', '(1)'], {}), '(errors, 1)\n', (5338, 5349), False, 'import torch\n'), ((5532, 5559), 'torch.stack', 'torch.stack', (['pos_matched', '(0)'], {}), '(pos_matched, 0)\n', (5543, 5559), False, 'import torch\n'), ((5797, 5822), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (5820, 5822), False, 'import argparse\n'), ((758, 791), 'os.path.join', 'os.path.join', (['restore', 'checkpoint'], {}), '(restore, checkpoint)\n', (770, 791), False, 'import os\n'), ((2287, 2327), 'torch.arange', 'torch.arange', (['(1)', '(long_rollout_length + 1)'], {}), '(1, long_rollout_length + 1)\n', (2299, 2327), False, 'import torch\n'), ((4130, 4155), 'model.utils.utils.bw_transform', 'bw_transform', (['true_images'], {}), '(true_images)\n', (4142, 4155), False, 'from model.utils.utils import bw_transform\n'), ((6536, 6565), 'glob.glob', 'glob.glob', (["(args.path + 'run*')"], {}), "(args.path + 'run*')\n", (6545, 6565), False, 'import glob\n'), ((7323, 7354), 'os.path.join', 'os.path.join', (['args.path', '"""test"""'], {}), "(args.path, 'test')\n", (7335, 7354), False, 'import os\n'), ((3828, 3850), 'torch.clamp', 'torch.clamp', (['img', '(0)', '(1)'], {}), '(img, 0, 1)\n', (3839, 3850), False, 'import torch\n'), ((3869, 3892), 'torch.unsqueeze', 'torch.unsqueeze', (['img', '(1)'], {}), '(img, 1)\n', (3884, 3892), False, 'import torch\n'), ((7370, 7394), 'os.path.exists', 'os.path.exists', (['save_dir'], {}), '(save_dir)\n', (7384, 7394), False, 'import os\n'), ((7408, 7429), 'os.makedirs', 'os.makedirs', (['save_dir'], {}), '(save_dir)\n', (7419, 7429), False, 'import os\n'), ((3052, 3103), 'torch.clamp', 'torch.clamp', (['z_seq[..., 2:4]', '(-frame_lim)', 'frame_lim'], {}), '(z_seq[..., 2:4], -frame_lim, frame_lim)\n', (3063, 3103), False, 'import torch\n'), ((5256, 5273), 'torch.sqrt', 'torch.sqrt', (['error'], {}), '(error)\n', (5266, 5273), False, 'import torch\n'), ((7449, 7481), 'os.path.join', 'os.path.join', (['save_dir', 'filename'], {}), '(save_dir, filename)\n', (7461, 7481), False, 'import os\n'), ((7582, 7626), 'os.path.join', 'os.path.join', (['save_dir', "('states_' + filename)"], {}), "(save_dir, 'states_' + filename)\n", (7594, 7626), False, 'import os\n'), ((1675, 1700), 'torch.tensor', 'torch.tensor', (['true_images'], {}), '(true_images)\n', (1687, 1700), False, 'import torch\n'), ((1845, 1870), 'torch.tensor', 'torch.tensor', (['stove_input'], {}), '(stove_input)\n', (1857, 1870), False, 'import torch\n'), ((4976, 5001), 'torch.tensor', 'torch.tensor', (['true_states'], {}), '(true_states)\n', (4988, 5001), False, 'import torch\n')] |
from django.contrib import admin
# Register your models here.
"""User admin classes."""
# Django
from django.contrib import admin
# Models
from users.models import User
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
"""User admin."""
list_display = ('pk', 'username', 'email','first_name','last_name') #Columnas de la tabla visibles, first and last name son campos intrínsecos de user
list_display_links = ('pk', 'username', 'email','first_name','last_name') #Cliqueables
search_fields = (
'email',
'username',
'first_name',
'last_name',
)
list_filter = (
'is_active',
'is_staff',
'date_joined',
'modified',
)
readonly_fields = ('date_joined', 'modified',) | [
"django.contrib.admin.register"
] | [((174, 194), 'django.contrib.admin.register', 'admin.register', (['User'], {}), '(User)\n', (188, 194), False, 'from django.contrib import admin\n')] |
# Copyright 2020 Toyota Research Institute. All rights reserved.
"""
Geometry utilities
"""
import numpy as np
def invert_pose_numpy(T):
"""
'Invert' 4x4 extrinsic matrix
Parameters
----------
T: 4x4 matrix (world to camera)
Returns
-------
4x4 matrix (camera to world)
"""
Tc = np.copy(T)
R, t = Tc[:3, :3], Tc[:3, 3]
Tc[:3, :3], Tc[:3, 3] = R.T, - np.matmul(R.T, t)
return Tc
| [
"numpy.copy",
"numpy.matmul"
] | [((326, 336), 'numpy.copy', 'np.copy', (['T'], {}), '(T)\n', (333, 336), True, 'import numpy as np\n'), ((405, 422), 'numpy.matmul', 'np.matmul', (['R.T', 't'], {}), '(R.T, t)\n', (414, 422), True, 'import numpy as np\n')] |
"""
Module that defines Corpus and DocumentSource/DocumentDestination classes which access documents
as lines or parts in a file.
"""
import json
from gatenlp.urlfileutils import yield_lines_from
from gatenlp.document import Document
from gatenlp.corpora.base import DocumentSource, DocumentDestination
from gatenlp.corpora.base import MultiProcessingAble
class BdocjsLinesFileSource(DocumentSource, MultiProcessingAble):
"""
A document source which reads one bdoc json serialization of a document from each line of the given file.
"""
def __init__(self, file):
"""
Create a JsonLinesFileSource.
Args:
file: the file path (a string) or an open file handle.
"""
self.file = file
def __iter__(self):
with open(self.file, "rt", encoding="utf-8") as infp:
for line in infp:
yield Document.load_mem(line, fmt="json")
class BdocjsLinesFileDestination(DocumentDestination):
"""
Writes one line of JSON per document to the a single output file.
"""
def __init__(self, file):
"""
Args:
file: the file to write to. If it exists, it gets overwritten without warning.
Expected to be a string or an open file handle.
"""
if isinstance(file, str):
self.fh = open(file, "wt", encoding="utf-8")
else:
self.fh = file
self.n = 0
def __enter__(self):
return self
def __exit__(self, extype, value, traceback):
self.fh.close()
def append(self, doc):
"""
Append a document to the destination.
Args:
doc: the document, if None, no action is performed.
"""
if doc is None:
return
assert isinstance(doc, Document)
self.fh.write(doc.save_mem(fmt="json"))
self.fh.write("\n")
self.n += 1
def close(self):
self.fh.close()
class JsonLinesFileSource(DocumentSource, MultiProcessingAble):
"""
A document source which reads one json serialization per line, creates a document from one field
in the json and optionally stores all or a selection of remaining fields as document feature "__data".
"""
def __init__(self, file, text_field="text", data_fields=None, data_feature="__data"):
"""
Create a JsonLinesFileSource.
Args:
file: the file path (a string) or an open file handle.
text_field: the field name where to get the document text from.
data_fields: if a list of names, store these fields in the "__data" feature. if True, store all fields.
data_feature: the name of the data feature, default is "__data"
"""
# feature_fields: NOT YET IMPLEMENTED -- a mapping from original json fields to document features
self.file = file
self.text_field = text_field
self.data_fields = data_fields
self.data_feature = data_feature
def __iter__(self):
with open(self.file, "rt", encoding="utf-8") as infp:
for line in infp:
data = json.loads(line)
# TODO: what if the field does not exist? should we use get(text_field, "") instead?
text = data[self.text_field]
doc = Document(text)
if self.data_fields:
if isinstance(self.data_fields, list):
tmp = {}
for fname in self.data_fields:
# TODO: what if the field does not exist?
tmp[fname] = data[fname]
else:
tmp = data
doc.features[self.data_feature] = tmp
yield doc
class JsonLinesFileDestination(DocumentDestination):
"""
Writes one line of JSON per document to the a single output file. This will either write the document json
as nested data or the document text to the field designated for the document and will write other json
fields from the "__data" document feature.
"""
def __init__(self, file, document_field="text", document_bdocjs=False, data_fields=True, data_feature="__data"):
"""
Args:
file: the file to write to. If it exists, it gets overwritten without warning.
Expected to be a string or an open file handle.
document_field: the name of the json field that will contain the document either just the text or
the bdocjs representation if document_bdocjs is True.
document_bdocjs: if True store the bdocjs serialization into the document_field instead of just the text
data_fields: if a list, only store these fields in the json, if False, do not store any additional fields.
Default is True: store all fields as is.
data_feature: the name of the data feature, default is "__data"
"""
if isinstance(file, str):
self.fh = open(file, "wt", encoding="utf-8")
else:
self.fh = file
self.n = 0
self.document_field = document_field
self.document_bdocjs = document_bdocjs
self.data_fields = data_fields
self.data_feature = data_feature
def __enter__(self):
return self
def __exit__(self, _extype, _value, _traceback):
self.fh.close()
def append(self, doc):
"""
Append a document to the destination.
Args:
doc: the document, if None, no action is performed.
"""
if doc is None:
return
assert isinstance(doc, Document)
data = {}
if self.data_fields:
if isinstance(self.data_fields, list):
for fname in self.data_fields:
data[fname] = doc.features[self.data_feature][fname]
else:
data.update(doc.features[self.data_feature])
# assign the document field last so it overwrites anything that comes from the data feature!
if self.document_bdocjs:
data[self.document_field] = doc.save_mem(fmt="json")
else:
data[self.document_field] = doc.text
self.fh.write(json.dumps(data))
self.fh.write("\n")
self.n += 1
def close(self):
self.fh.close()
class TsvFileSource(DocumentSource, MultiProcessingAble):
"""
A TsvFileSource is a DocumentSource which is a single TSV file with a fixed number of tab-separated
values per row. Each document in sequence is created from the text in one of the columns and
document features can be set from arbitrary columns as well.
"""
def __init__(self, source, hdr=True, text_col=None, feature_cols=None, data_cols=None, data_feature="__data"):
"""
Creates the TsvFileSource.
Args:
source: a file path or URL
hdr: if True (default), expects a header line with the column names, if a list, should be the list
of column names, if False/None, no header line is expected.
text_col: the column which contains the text for creating the document. Either the column number,
or the name of the column (only possible if there is a header line) or a function that should
take the list of fields and arbitrary kwargs and return the text. Also passes "cols" and "n"
as keyward arguments.
feature_cols: if not None, must be either a dictionary mapping document feature names to the
column numbers or column names of where to get the feature value from;
or a function that should take the list of fields and arbitrary kwargs and return a dictionary
with the features. Also passes "cols" (dict mapping column names to column indices, or None) and
"n" (current line number) as keyword arguments.
data_cols: if not None, either an iterable of the names of columns to store in the special document
feature "__data" or if "True", stores all columns. At the moment this only works if the tsv file
has a header line. The values are stored as a list in the order of the names given or the original
order of the values in the TSV file.
data_feature: the name of the document feature where to store the data, default is "__data"
"""
assert text_col is not None
self.hdr = hdr
self.text_col = text_col
self.feature_cols = feature_cols
self.data_cols = data_cols
self.source = source
self.n = 0
self.hdr2col = {}
if data_cols and not hdr:
raise Exception("Header must be present if data_cols should be used")
self.data_feature = data_feature
def __iter__(self):
reader = yield_lines_from(self.source)
if self.hdr and self.n == 0:
self.n += 1
self.hdr = next(reader).rstrip("\n\r").split("\t")
if self.hdr:
self.hdr2col = {name: idx for idx, name in enumerate(self.hdr)}
for line in reader:
line = line.rstrip("\n\r")
fields = line.split("\t")
if isinstance(self.text_col, int):
text = fields[self.text_col]
elif callable(self.text_col):
text = self.text_col(fields, cols=self.hdr2col, n=self.n)
else:
text = fields[self.hdr2col[self.text_col]]
doc = Document(text)
if self.feature_cols:
if callable(self.feature_cols):
doc.features.update(
self.feature_cols(fields, cols=self.hdr2col, n=self.n)
)
else:
for fname, colid in self.feature_cols.items():
if isinstance(colid, int):
value = fields[colid]
else:
value = fields[self.hdr2col[colid]]
doc.features[fname] = value
if self.data_cols:
if isinstance(self.data_cols, list):
data = {}
for cname in self.data_cols:
if isinstance(cname, str):
data[cname] = fields[self.hdr2col[cname]]
else:
# assume it is the column index!
data[cname] = fields[cname]
else:
data = fields
doc.features[self.data_feature] = data
self.n += 1
yield doc
| [
"json.loads",
"json.dumps",
"gatenlp.document.Document",
"gatenlp.document.Document.load_mem",
"gatenlp.urlfileutils.yield_lines_from"
] | [((8942, 8971), 'gatenlp.urlfileutils.yield_lines_from', 'yield_lines_from', (['self.source'], {}), '(self.source)\n', (8958, 8971), False, 'from gatenlp.urlfileutils import yield_lines_from\n'), ((6287, 6303), 'json.dumps', 'json.dumps', (['data'], {}), '(data)\n', (6297, 6303), False, 'import json\n'), ((9601, 9615), 'gatenlp.document.Document', 'Document', (['text'], {}), '(text)\n', (9609, 9615), False, 'from gatenlp.document import Document\n'), ((3152, 3168), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (3162, 3168), False, 'import json\n'), ((3337, 3351), 'gatenlp.document.Document', 'Document', (['text'], {}), '(text)\n', (3345, 3351), False, 'from gatenlp.document import Document\n'), ((890, 925), 'gatenlp.document.Document.load_mem', 'Document.load_mem', (['line'], {'fmt': '"""json"""'}), "(line, fmt='json')\n", (907, 925), False, 'from gatenlp.document import Document\n')] |
import fastapi
from starlette.requests import Request
from web.viewmodels.account.AccountViewModel import AccountViewModel
from web.viewmodels.account.LoginViewModel import LoginViewModel
from web.viewmodels.account.RegisterViewModel import RegisterViewModel
router = fastapi.APIRouter()
@router.get('/account')
def index(request: Request):
vm = AccountViewModel(request)
return vm.to_dict()
@router.get('/account/register')
def register(request: Request):
vm = RegisterViewModel(request)
return vm.to_dict()
@router.get('/account/login')
def login(request: Request):
vm = LoginViewModel(request)
return vm.to_dict()
@router.get('/account/logout')
def logout():
return {}
| [
"web.viewmodels.account.AccountViewModel.AccountViewModel",
"fastapi.APIRouter",
"web.viewmodels.account.RegisterViewModel.RegisterViewModel",
"web.viewmodels.account.LoginViewModel.LoginViewModel"
] | [((269, 288), 'fastapi.APIRouter', 'fastapi.APIRouter', ([], {}), '()\n', (286, 288), False, 'import fastapi\n'), ((353, 378), 'web.viewmodels.account.AccountViewModel.AccountViewModel', 'AccountViewModel', (['request'], {}), '(request)\n', (369, 378), False, 'from web.viewmodels.account.AccountViewModel import AccountViewModel\n'), ((479, 505), 'web.viewmodels.account.RegisterViewModel.RegisterViewModel', 'RegisterViewModel', (['request'], {}), '(request)\n', (496, 505), False, 'from web.viewmodels.account.RegisterViewModel import RegisterViewModel\n'), ((600, 623), 'web.viewmodels.account.LoginViewModel.LoginViewModel', 'LoginViewModel', (['request'], {}), '(request)\n', (614, 623), False, 'from web.viewmodels.account.LoginViewModel import LoginViewModel\n')] |
import numpy as np
from tests.test_utils import run_track_tests
from mirdata import annotations
from mirdata.datasets import tonas
TEST_DATA_HOME = "tests/resources/mir_datasets/tonas"
def test_track():
default_trackid = "01-D_AMairena"
dataset = tonas.Dataset(TEST_DATA_HOME)
track = dataset.track(default_trackid)
expected_attributes = {
"singer": "<NAME>",
"style": "Debla",
"title": "<NAME>",
"tuning_frequency": 451.0654725341684,
"f0_path": "tests/resources/mir_datasets/tonas/Deblas/01-D_AMairena.f0.Corrected",
"notes_path": "tests/resources/mir_datasets/tonas/Deblas/01-D_AMairena.notes.Corrected",
"audio_path": "tests/resources/mir_datasets/tonas/Deblas/01-D_AMairena.wav",
"track_id": "01-D_AMairena",
}
expected_property_types = {
"f0": annotations.F0Data,
"f0_automatic": annotations.F0Data,
"f0_corrected": annotations.F0Data,
"notes": annotations.NoteData,
"audio": tuple,
"singer": str,
"style": str,
"title": str,
"tuning_frequency": float,
}
run_track_tests(track, expected_attributes, expected_property_types)
def test_to_jams():
default_trackid = "01-D_AMairena"
dataset = tonas.Dataset(TEST_DATA_HOME)
track = dataset.track(default_trackid)
jam = track.to_jams()
# Validate cante100 jam schema
assert jam.validate()
# Validate melody
f0 = jam.search(namespace="pitch_contour")[0]["data"]
assert [note.time for note in f0] == [0.197, 0.209, 0.221, 0.232]
assert [note.duration for note in f0] == [0.0, 0.0, 0.0, 0.0]
assert [note.value for note in f0] == [
{"index": 0, "frequency": 0.0, "voiced": False},
{"index": 0, "frequency": 379.299, "voiced": True},
{"index": 0, "frequency": 379.299, "voiced": True},
{"index": 0, "frequency": 379.299, "voiced": True},
]
print([note.confidence for note in f0])
assert [note.confidence for note in f0] == [3.09e-06, 2.86e-06, 7.15e-06, 1.545e-05]
# Validate note transciption
notes = jam.search(namespace="note_hz")[0]["data"]
assert [note.time for note in notes] == [
0.216667,
0.65,
2.183333,
2.566667,
]
assert [note.duration for note in notes] == [
0.433333,
1.016667,
0.3833329999999999,
0.3333330000000001,
]
assert [note.value for note in notes] == [
388.8382625732775,
411.9597888711769,
388.8382625732775,
411.9597888711769,
]
assert [note.confidence for note in notes] == [None, None, None, None]
def test_load_melody():
default_trackid = "01-D_AMairena"
dataset = tonas.Dataset(TEST_DATA_HOME)
track = dataset.track(default_trackid)
f0_path = track.f0_path
f0_data_corrected = tonas.load_f0(f0_path, True)
f0_data_automatic = tonas.load_f0(f0_path, False)
# check types
assert type(f0_data_corrected) == annotations.F0Data
assert type(f0_data_corrected.times) is np.ndarray
assert type(f0_data_corrected.frequencies) is np.ndarray
assert type(f0_data_corrected.voicing) is np.ndarray
assert type(f0_data_corrected._confidence) is np.ndarray
assert type(f0_data_automatic) == annotations.F0Data
assert type(f0_data_automatic.times) is np.ndarray
assert type(f0_data_automatic.frequencies) is np.ndarray
assert type(f0_data_corrected.voicing) is np.ndarray
assert type(f0_data_automatic._confidence) is np.ndarray
# check values
assert np.array_equal(
f0_data_corrected.times,
np.array([0.197, 0.209, 0.221, 0.232]),
)
assert np.array_equal(
f0_data_corrected.frequencies, np.array([0.000, 379.299, 379.299, 379.299])
)
assert np.array_equal(
f0_data_corrected.voicing,
np.array([0.0, 1.0, 1.0, 1.0]),
)
assert np.array_equal(
f0_data_corrected._confidence,
np.array([3.090e-06, 0.00000286, 0.00000715, 0.00001545]),
)
# check values
assert np.array_equal(
f0_data_automatic.times,
np.array([0.197, 0.209, 0.221, 0.232]),
)
assert np.array_equal(
f0_data_automatic.frequencies,
np.array(
[
0.000,
0.000,
143.918,
143.918,
]
),
)
assert np.array_equal(
f0_data_automatic.voicing,
np.array([0.0, 0.0, 1.0, 1.0]),
)
assert np.array_equal(
f0_data_automatic._confidence,
np.array([3.090e-06, 2.860e-06, 0.00000715, 0.00001545]),
)
def test_load_notes():
default_trackid = "01-D_AMairena"
dataset = tonas.Dataset(TEST_DATA_HOME)
track = dataset.track(default_trackid)
notes_path = track.notes_path
notes_data = tonas.load_notes(notes_path)
tuning_frequency = tonas._load_tuning_frequency(notes_path)
# check types
assert type(notes_data) == annotations.NoteData
assert type(notes_data.intervals) is np.ndarray
assert type(notes_data.pitches) is np.ndarray
assert type(notes_data.confidence) is np.ndarray
assert type(tuning_frequency) is float
# check tuning frequency
assert tuning_frequency == 451.0654725341684
# check values
assert np.array_equal(
notes_data.intervals[:, 0], np.array([0.216667, 0.65, 2.183333, 2.566667])
)
assert np.array_equal(
notes_data.intervals[:, 1], np.array([0.65, 1.666667, 2.566666, 2.9])
)
assert np.array_equal(
notes_data.pitches,
np.array(
[388.8382625732775, 411.9597888711769, 388.8382625732775, 411.9597888711769]
),
)
assert np.array_equal(
notes_data.confidence,
np.array(
[
0.018007,
0.010794,
0.00698,
0.03265,
]
),
)
def test_load_audio():
default_trackid = "01-D_AMairena"
dataset = tonas.Dataset(TEST_DATA_HOME)
track = dataset.track(default_trackid)
audio_path = track.audio_path
audio, sr = tonas.load_audio(audio_path)
assert sr == 44100
assert type(audio) is np.ndarray
def test_metadata():
default_trackid = "01-D_AMairena"
dataset = tonas.Dataset(TEST_DATA_HOME)
metadata = dataset._metadata
assert metadata[default_trackid] == {
"title": "En el barrio de Triana",
"style": "Debla",
"singer": "<NAME>",
}
| [
"mirdata.datasets.tonas.Dataset",
"mirdata.datasets.tonas.load_audio",
"mirdata.datasets.tonas._load_tuning_frequency",
"mirdata.datasets.tonas.load_f0",
"numpy.array",
"tests.test_utils.run_track_tests",
"mirdata.datasets.tonas.load_notes"
] | [((260, 289), 'mirdata.datasets.tonas.Dataset', 'tonas.Dataset', (['TEST_DATA_HOME'], {}), '(TEST_DATA_HOME)\n', (273, 289), False, 'from mirdata.datasets import tonas\n'), ((1137, 1205), 'tests.test_utils.run_track_tests', 'run_track_tests', (['track', 'expected_attributes', 'expected_property_types'], {}), '(track, expected_attributes, expected_property_types)\n', (1152, 1205), False, 'from tests.test_utils import run_track_tests\n'), ((1280, 1309), 'mirdata.datasets.tonas.Dataset', 'tonas.Dataset', (['TEST_DATA_HOME'], {}), '(TEST_DATA_HOME)\n', (1293, 1309), False, 'from mirdata.datasets import tonas\n'), ((2749, 2778), 'mirdata.datasets.tonas.Dataset', 'tonas.Dataset', (['TEST_DATA_HOME'], {}), '(TEST_DATA_HOME)\n', (2762, 2778), False, 'from mirdata.datasets import tonas\n'), ((2874, 2902), 'mirdata.datasets.tonas.load_f0', 'tonas.load_f0', (['f0_path', '(True)'], {}), '(f0_path, True)\n', (2887, 2902), False, 'from mirdata.datasets import tonas\n'), ((2927, 2956), 'mirdata.datasets.tonas.load_f0', 'tonas.load_f0', (['f0_path', '(False)'], {}), '(f0_path, False)\n', (2940, 2956), False, 'from mirdata.datasets import tonas\n'), ((4739, 4768), 'mirdata.datasets.tonas.Dataset', 'tonas.Dataset', (['TEST_DATA_HOME'], {}), '(TEST_DATA_HOME)\n', (4752, 4768), False, 'from mirdata.datasets import tonas\n'), ((4863, 4891), 'mirdata.datasets.tonas.load_notes', 'tonas.load_notes', (['notes_path'], {}), '(notes_path)\n', (4879, 4891), False, 'from mirdata.datasets import tonas\n'), ((4915, 4955), 'mirdata.datasets.tonas._load_tuning_frequency', 'tonas._load_tuning_frequency', (['notes_path'], {}), '(notes_path)\n', (4943, 4955), False, 'from mirdata.datasets import tonas\n'), ((6030, 6059), 'mirdata.datasets.tonas.Dataset', 'tonas.Dataset', (['TEST_DATA_HOME'], {}), '(TEST_DATA_HOME)\n', (6043, 6059), False, 'from mirdata.datasets import tonas\n'), ((6153, 6181), 'mirdata.datasets.tonas.load_audio', 'tonas.load_audio', (['audio_path'], {}), '(audio_path)\n', (6169, 6181), False, 'from mirdata.datasets import tonas\n'), ((6317, 6346), 'mirdata.datasets.tonas.Dataset', 'tonas.Dataset', (['TEST_DATA_HOME'], {}), '(TEST_DATA_HOME)\n', (6330, 6346), False, 'from mirdata.datasets import tonas\n'), ((3647, 3685), 'numpy.array', 'np.array', (['[0.197, 0.209, 0.221, 0.232]'], {}), '([0.197, 0.209, 0.221, 0.232])\n', (3655, 3685), True, 'import numpy as np\n'), ((3759, 3801), 'numpy.array', 'np.array', (['[0.0, 379.299, 379.299, 379.299]'], {}), '([0.0, 379.299, 379.299, 379.299])\n', (3767, 3801), True, 'import numpy as np\n'), ((3880, 3910), 'numpy.array', 'np.array', (['[0.0, 1.0, 1.0, 1.0]'], {}), '([0.0, 1.0, 1.0, 1.0])\n', (3888, 3910), True, 'import numpy as np\n'), ((3992, 4043), 'numpy.array', 'np.array', (['[3.09e-06, 2.86e-06, 7.15e-06, 1.545e-05]'], {}), '([3.09e-06, 2.86e-06, 7.15e-06, 1.545e-05])\n', (4000, 4043), True, 'import numpy as np\n'), ((4145, 4183), 'numpy.array', 'np.array', (['[0.197, 0.209, 0.221, 0.232]'], {}), '([0.197, 0.209, 0.221, 0.232])\n', (4153, 4183), True, 'import numpy as np\n'), ((4265, 4303), 'numpy.array', 'np.array', (['[0.0, 0.0, 143.918, 143.918]'], {}), '([0.0, 0.0, 143.918, 143.918])\n', (4273, 4303), True, 'import numpy as np\n'), ((4486, 4516), 'numpy.array', 'np.array', (['[0.0, 0.0, 1.0, 1.0]'], {}), '([0.0, 0.0, 1.0, 1.0])\n', (4494, 4516), True, 'import numpy as np\n'), ((4598, 4649), 'numpy.array', 'np.array', (['[3.09e-06, 2.86e-06, 7.15e-06, 1.545e-05]'], {}), '([3.09e-06, 2.86e-06, 7.15e-06, 1.545e-05])\n', (4606, 4649), True, 'import numpy as np\n'), ((5387, 5433), 'numpy.array', 'np.array', (['[0.216667, 0.65, 2.183333, 2.566667]'], {}), '([0.216667, 0.65, 2.183333, 2.566667])\n', (5395, 5433), True, 'import numpy as np\n'), ((5503, 5544), 'numpy.array', 'np.array', (['[0.65, 1.666667, 2.566666, 2.9]'], {}), '([0.65, 1.666667, 2.566666, 2.9])\n', (5511, 5544), True, 'import numpy as np\n'), ((5614, 5705), 'numpy.array', 'np.array', (['[388.8382625732775, 411.9597888711769, 388.8382625732775, 411.9597888711769]'], {}), '([388.8382625732775, 411.9597888711769, 388.8382625732775, \n 411.9597888711769])\n', (5622, 5705), True, 'import numpy as np\n'), ((5796, 5844), 'numpy.array', 'np.array', (['[0.018007, 0.010794, 0.00698, 0.03265]'], {}), '([0.018007, 0.010794, 0.00698, 0.03265])\n', (5804, 5844), True, 'import numpy as np\n')] |
#encoding: utf-8
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
import zmq, sys, json
import seg
import detoken
import datautils
from random import sample
serverl=["tcp://127.0.0.1:"+str(port) for port in xrange(5556,5556+4)]
def _translate_core(jsond):
global serverl
sock = zmq.Context().socket(zmq.REQ)
sock.connect(sample(serverl, 1)[0])
sock.send(jsond)
return sock.recv()
def _translate(srctext):
return detoken.detoken(datautils.char2pinyin(datautils.restoreFromBatch(json.loads(_translate_core(json.dumps(datautils.makeBatch(datautils.cutParagraph(seg.segline(srctext)))))))))
def translate(srctext):
tmp=srctext.strip()
if tmp:
return _translate(tmp)
else:
return tmp
def poweron():
seg.poweron()
def poweroff():
seg.poweroff()
| [
"random.sample",
"sys.setdefaultencoding",
"seg.poweron",
"seg.poweroff",
"seg.segline",
"zmq.Context"
] | [((41, 72), 'sys.setdefaultencoding', 'sys.setdefaultencoding', (['"""utf-8"""'], {}), "('utf-8')\n", (63, 72), False, 'import zmq, sys, json\n'), ((725, 738), 'seg.poweron', 'seg.poweron', ([], {}), '()\n', (736, 738), False, 'import seg\n'), ((757, 771), 'seg.poweroff', 'seg.poweroff', ([], {}), '()\n', (769, 771), False, 'import seg\n'), ((294, 307), 'zmq.Context', 'zmq.Context', ([], {}), '()\n', (305, 307), False, 'import zmq, sys, json\n'), ((338, 356), 'random.sample', 'sample', (['serverl', '(1)'], {}), '(serverl, 1)\n', (344, 356), False, 'from random import sample\n'), ((579, 599), 'seg.segline', 'seg.segline', (['srctext'], {}), '(srctext)\n', (590, 599), False, 'import seg\n')] |
"""Configuration defaults and loading functions.
Pyleus will look for configuration files in the following file paths in order
of increasing precedence. The latter configuration overrides the previous one.
#. /etc/pyleus.conf
#. ~/.config/pyleus.conf
#. ~/.pyleus.conf
You can always specify a configuration file when running any pyleus CLI command
as following:
``$ pyleus -c /path/to/config_file CMD``
This will override previous configurations.
Configuration file example
--------------------------
The following file contains all options you can configure for all pyleus
invocations.
.. code-block:: ini
[storm]
# path to Storm executable (pyleus will automatically look in PATH)
storm_cmd_path: /usr/share/storm/bin/storm
# optional: use -n option of pyleus CLI instead
nimbus_host: 10.11.12.13
# optional: use -p option of pyleus CLI instead
nimbus_port: 6628
# java options to pass to Storm CLI
jvm_opts: -Djava.io.tmpdir=/home/myuser/tmp
[build]
# PyPI server to use during the build of your topologies
pypi_index_url: http://pypi.ninjacorp.com/simple/
# always use system-site-packages for pyleus virtualenvs (default: false)
system_site_packages: true
# list of packages to always include in your topologies
include_packages: foo bar<4.0 baz==0.1
"""
from __future__ import absolute_import
import collections
import os
from pyleus import BASE_JAR_PATH
from pyleus.utils import expand_path
from pyleus.exception import ConfigurationError
from pyleus.compat import configparser
# Configuration files paths in order of increasing precedence
# Please keep in sync with module docstring
CONFIG_FILES_PATH = [
"/etc/pyleus.conf",
"~/.config/pyleus.conf",
"~/.pyleus.conf"
]
Configuration = collections.namedtuple(
"Configuration",
"base_jar config_file debug func include_packages output_jar \
pypi_index_url nimbus_host nimbus_port storm_cmd_path \
system_site_packages topology_path topology_jar topology_name verbose \
wait_time jvm_opts"
)
"""Namedtuple containing all pyleus configuration values."""
DEFAULTS = Configuration(
base_jar=BASE_JAR_PATH,
config_file=None,
debug=False,
func=None,
include_packages=None,
output_jar=None,
pypi_index_url=None,
nimbus_host=None,
nimbus_port=None,
storm_cmd_path=None,
system_site_packages=False,
topology_path="pyleus_topology.yaml",
topology_jar=None,
topology_name=None,
verbose=False,
wait_time=None,
jvm_opts=None,
)
def _validate_config_file(config_file):
"""Ensure that config_file exists and is a file."""
if not os.path.exists(config_file):
raise ConfigurationError("Specified configuration file not"
" found: {0}".format(config_file))
if not os.path.isfile(config_file):
raise ConfigurationError("Specified configuration file is not"
" a file: {0}".format(config_file))
def update_configuration(config, update_dict):
"""Update configuration with new values passed as dictionary.
:return: new configuration ``namedtuple``
"""
tmp = config._asdict()
tmp.update(update_dict)
return Configuration(**tmp)
def load_configuration(cmd_line_file):
"""Load configurations from the more generic to the
more specific configuration file. The latter configurations
override the previous one.
If a file is specified from command line, it is considered
the most specific.
:return: configuration ``namedtuple``
"""
config_files_hierarchy = [expand_path(c) for c in CONFIG_FILES_PATH]
if cmd_line_file is not None:
_validate_config_file(cmd_line_file)
config_files_hierarchy.append(cmd_line_file)
config = configparser.SafeConfigParser()
config.read(config_files_hierarchy)
configs = update_configuration(
DEFAULTS,
dict(
(config_name, config_value)
for section in config.sections()
for config_name, config_value in config.items(section)
)
)
return configs
| [
"os.path.exists",
"collections.namedtuple",
"os.path.isfile",
"pyleus.compat.configparser.SafeConfigParser",
"pyleus.utils.expand_path"
] | [((1773, 2042), 'collections.namedtuple', 'collections.namedtuple', (['"""Configuration"""', '"""base_jar config_file debug func include_packages output_jar pypi_index_url nimbus_host nimbus_port storm_cmd_path system_site_packages topology_path topology_jar topology_name verbose wait_time jvm_opts"""'], {}), "('Configuration',\n 'base_jar config_file debug func include_packages output_jar pypi_index_url nimbus_host nimbus_port storm_cmd_path system_site_packages topology_path topology_jar topology_name verbose wait_time jvm_opts'\n )\n", (1795, 2042), False, 'import collections\n'), ((3804, 3835), 'pyleus.compat.configparser.SafeConfigParser', 'configparser.SafeConfigParser', ([], {}), '()\n', (3833, 3835), False, 'from pyleus.compat import configparser\n'), ((2653, 2680), 'os.path.exists', 'os.path.exists', (['config_file'], {}), '(config_file)\n', (2667, 2680), False, 'import os\n'), ((2829, 2856), 'os.path.isfile', 'os.path.isfile', (['config_file'], {}), '(config_file)\n', (2843, 2856), False, 'import os\n'), ((3614, 3628), 'pyleus.utils.expand_path', 'expand_path', (['c'], {}), '(c)\n', (3625, 3628), False, 'from pyleus.utils import expand_path\n')] |
from shutil import rmtree
from tempfile import mkdtemp
import pytest
import param
import pydrobert.param.serialization as serial
param.parameterized.warnings_as_exceptions = True
@pytest.fixture(params=["ruamel_yaml", "pyyaml"])
def yaml_loader(request):
if request.param == "ruamel_yaml":
try:
from ruamel_yaml import YAML # type: ignore
yaml_loader = YAML().load
except ImportError:
from ruamel.yaml import YAML # type: ignore
yaml_loader = YAML().load
module_names = ("ruamel_yaml", "ruamel.yaml")
else:
import yaml # type: ignore
def yaml_loader(x):
return yaml.load(x, Loader=yaml.FullLoader)
module_names = ("pyyaml",)
old_props = serial.YAML_MODULE_PRIORITIES
serial.YAML_MODULE_PRIORITIES = module_names
yield yaml_loader
serial.YAML_MODULE_PRIORITIES = old_props
@pytest.fixture(params=[True, False])
def with_yaml(request):
if request.param:
yield True
else:
old_props = serial.YAML_MODULE_PRIORITIES
serial.YAML_MODULE_PRIORITIES = tuple()
yield False
serial.YAML_MODULE_PRIORITIES = old_props
@pytest.fixture
def temp_dir():
dir_name = mkdtemp()
yield dir_name
rmtree(dir_name, ignore_errors=True)
| [
"yaml.load",
"ruamel.yaml.YAML",
"tempfile.mkdtemp",
"shutil.rmtree",
"pytest.fixture"
] | [((185, 233), 'pytest.fixture', 'pytest.fixture', ([], {'params': "['ruamel_yaml', 'pyyaml']"}), "(params=['ruamel_yaml', 'pyyaml'])\n", (199, 233), False, 'import pytest\n'), ((919, 955), 'pytest.fixture', 'pytest.fixture', ([], {'params': '[True, False]'}), '(params=[True, False])\n', (933, 955), False, 'import pytest\n'), ((1248, 1257), 'tempfile.mkdtemp', 'mkdtemp', ([], {}), '()\n', (1255, 1257), False, 'from tempfile import mkdtemp\n'), ((1281, 1317), 'shutil.rmtree', 'rmtree', (['dir_name'], {'ignore_errors': '(True)'}), '(dir_name, ignore_errors=True)\n', (1287, 1317), False, 'from shutil import rmtree\n'), ((680, 716), 'yaml.load', 'yaml.load', (['x'], {'Loader': 'yaml.FullLoader'}), '(x, Loader=yaml.FullLoader)\n', (689, 716), False, 'import yaml\n'), ((396, 402), 'ruamel.yaml.YAML', 'YAML', ([], {}), '()\n', (400, 402), False, 'from ruamel.yaml import YAML\n'), ((520, 526), 'ruamel.yaml.YAML', 'YAML', ([], {}), '()\n', (524, 526), False, 'from ruamel.yaml import YAML\n')] |
import argparse
import csv
import matplotlib
import matplotlib.ticker as tck
import matplotlib.pyplot as plt
import numpy as np
# Matplotlib export settings
matplotlib.use('pgf')
import matplotlib.pyplot as plt
matplotlib.rcParams.update({
'pgf.texsystem': 'pdflatex',
'font.size': 10,
'font.family': 'serif', # use serif/main font for text elements
'text.usetex': True, # use inline math for ticks
'pgf.rcfonts': False # don't setup fonts from rc parameters
})
# Main function
def main(args):
C_zero = 7.5240e-03 * 1e-6 # Farads/km
C_pos = 1.2027e-02 * 1e-6 # Farads/km
G_zero = 2.0000e-08 # Mhos/km
G_pos = 2.0000e-08 # Mhos/km
length = 300 # km
FREQ_INDEX = 0
R_ZERO_INDEX = 1
L_ZERO_INDEX = 2
R_POS_INDEX = 3
L_POS_INDEX = 4
MAGNITUDE_INDEX = 0
PHASE_INDEX = 1
# prepopulate data with a list of five empty lists
data = [[] for i in range(5)]
# Read in PSCAD .CSV data
print('*** Opening assignment 4 CSV data file...')
with open('data_assign04.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
# Read in row data
for row in csv_reader:
if line_count == 0:
print('Column names are: ' + ', '.join(row))
line_count += 1
else:
data[FREQ_INDEX].append(float(row[0]))
data[R_ZERO_INDEX].append(float(row[1])) # Ohms/km
data[L_ZERO_INDEX].append(float(row[2]) * 1e-3) # Henries/km
data[R_POS_INDEX].append(float(row[3])) # Ohms/km
data[L_POS_INDEX].append(float(row[4]) * 1e-3) # Henries/km
line_count += 1
# Figure out when break switched
print('Processed ' + str(line_count) + ' lines.')
num_data_points = len(data[FREQ_INDEX])
# Prepare values for Z(w) magnitude and phase
impedance_zero = [[],[]]
impedance_pos = [[],[]]
for index in range(num_data_points):
omega = 2*np.pi*data[FREQ_INDEX][index]
impedance_zero_val = np.sqrt((data[R_ZERO_INDEX][index] + (1j*omega*data[L_ZERO_INDEX][index]))/(G_zero + (1j*omega*C_zero)))
impedance_pos_val = np.sqrt((data[R_POS_INDEX][index] + (1j*omega*data[L_POS_INDEX][index])) /(G_pos + (1j*omega*C_pos)))
# print("F: " + str(data[FREQ_INDEX][index]))
# print("Omega: " + str(omega))
# print("R_0: " + str(data[R_ZERO_INDEX][index]))
# print("L_0: " + str(data[L_ZERO_INDEX][index]))
# print("C_0: " + str(C_zero))
# print("G_0: " + str(G_zero))
# print("R_+: " + str(data[R_POS_INDEX][index]))
# print("L_+: " + str(data[L_POS_INDEX][index]))
# print("C_+: " + str(C_pos))
# print("G_+: " + str(G_pos))
# print("Zc_0: " + str(impedance_zero_val))
# print("Zc_0 mag: " + str(np.absolute(impedance_zero_val)))
# print("Zc_+: " + str(impedance_pos_val))
# print("Zc_+ mag: " + str(np.absolute(impedance_pos_val)))
impedance_zero[MAGNITUDE_INDEX].append(np.absolute(impedance_zero_val))
impedance_zero[PHASE_INDEX].append(np.angle(impedance_zero_val))
impedance_pos[MAGNITUDE_INDEX].append(np.absolute(impedance_pos_val))
impedance_pos[PHASE_INDEX].append(np.angle(impedance_pos_val))
print("\r\n")
# Prepare values for propagation function magnitude and phase as well
# Prepare values for attenuation alpha(w) (nepers/km)
# Prepare values for phase displacement beta(w) (radians/km)
# Prepare values for propagation speed a(w) (km/s)
propagation_zero = [[],[]]
propagation_pos = [[],[]]
attenuation_zero = []
attenuation_pos = []
phase_zero = []
phase_pos = []
propagation_speed_zero = []
propagation_speed_pos = []
for index in range(num_data_points):
omega = 2*np.pi*data[FREQ_INDEX][index]
gamma_zero = np.sqrt((data[R_ZERO_INDEX][index] + 1j*omega*data[L_ZERO_INDEX][index])*(G_zero + 1j*omega*C_zero))
gamma_pos = np.sqrt((data[R_POS_INDEX][index] + 1j*omega*data[L_POS_INDEX][index])*(G_pos + 1j*omega*C_pos))
# propagation function magnitude and phase
propagation_zero[MAGNITUDE_INDEX].append(np.absolute(np.exp(-1*gamma_zero*length)))
propagation_zero[PHASE_INDEX].append(-np.imag(gamma_zero)*length)
propagation_pos[MAGNITUDE_INDEX].append(np.absolute(np.exp(-1*gamma_pos*length)))
propagation_pos[PHASE_INDEX].append(-np.imag(gamma_pos)*length)
# attenuation (real component of gamma) (nepers/km)
attenuation_zero.append(np.real(gamma_zero))
attenuation_pos.append(np.real(gamma_pos))
# phase displacement (imaginary component of gamma) (radians/km)
phase_zero.append(np.imag(gamma_zero))
phase_pos.append(np.imag(gamma_pos))
# propagation speed (omega/phase_displacement) (km/s)
propagation_speed_zero.append(omega/phase_zero[-1])
propagation_speed_pos.append(omega/phase_pos[-1])
# propagation_speed_zero.append(1/np.sqrt(data[L_ZERO_INDEX][index]*C_zero))
# propagation_speed_pos.append(1/np.sqrt(data[L_POS_INDEX][index]*C_pos))
# Plots for publication
legend_font_size = 6
# Plot Z(w) magnitude and phase
fig, ax = plt.subplots(2)
ax[0].plot(data[FREQ_INDEX], impedance_zero[MAGNITUDE_INDEX], color='b', label='zero sequence')
ax[0].plot(data[FREQ_INDEX], impedance_pos[MAGNITUDE_INDEX], color='g', label='positive sequence')
ax[0].set(xlabel='Frequency $Hz$', ylabel='Magnitude ($\Omega/km$)', title='$Z_c$ - Magnitude vs. Frequency')
ax[0].grid()
ax[0].set_xscale('log')
ax[0].legend(loc='best', prop={'size':legend_font_size}, fancybox=True, shadow=True)
ax[1].plot(data[FREQ_INDEX], impedance_zero[PHASE_INDEX], color='b', label='zero sequence')
ax[1].plot(data[FREQ_INDEX], impedance_pos[PHASE_INDEX], color='g', label='positive sequence')
ax[1].yaxis.set_major_formatter(tck.FormatStrFormatter('%1.1f $\pi$'))
ax[1].yaxis.set_major_locator(tck.MultipleLocator(base=1/5))
ax[1].set(xlabel='Frequency $Hz$', ylabel='Phase ($rad$)', title='$Z_c$ - Phase vs. Frequency')
ax[1].grid()
ax[1].set_xscale('log')
ax[1].legend(loc='best', prop={'size':legend_font_size}, fancybox=True, shadow=True)
fig.set_size_inches(6.5,8)
fig.tight_layout()
fig.savefig('zc_magnitude_phase_plots.pgf')
fig.savefig('zc_magnitude_phase_plots.png')
# Plot propagation function magnitude and phase
fig, ax = plt.subplots(2)
ax[0].plot(data[FREQ_INDEX], propagation_zero[MAGNITUDE_INDEX], color='b', label='zero sequence')
ax[0].plot(data[FREQ_INDEX], propagation_pos[MAGNITUDE_INDEX], color='g', label='positive sequence')
ax[0].set(xlabel='Frequency $Hz$', ylabel=r'Magnitude $\left|e^{-\gamma{}l}\right|$', title='$e^{-\gamma{}l}$ - Magnitude vs. Frequency')
ax[0].grid()
ax[0].set_xscale('log')
ax[0].legend(loc='best', prop={'size':legend_font_size}, fancybox=True, shadow=True)
ax[1].plot(data[FREQ_INDEX], propagation_zero[PHASE_INDEX], color='b', label='zero sequence')
ax[1].plot(data[FREQ_INDEX], propagation_pos[PHASE_INDEX], color='g', label='positive sequence')
ax[1].set(xlabel='Frequency $Hz$', ylabel=r'Phase $\phi{}=\beta{}l=\omega{}\tau$ ($rad$)', title='$e^{-\gamma{}l}$ - Phase vs. Frequency')
ax[1].grid()
ax[1].set_xscale('log')
ax[1].legend(loc='best', prop={'size':legend_font_size}, fancybox=True, shadow=True)
fig.set_size_inches(6.5,8)
fig.tight_layout()
fig.savefig('prop_magnitude_phase_plots.pgf')
fig.savefig('prop_magnitude_phase_plots.png')
# Plot propagation function magnitude and phase (no long for frequency)
fig, ax = plt.subplots(1)
ax.plot(data[FREQ_INDEX], propagation_zero[PHASE_INDEX], color='b', label='zero sequence')
ax.plot(data[FREQ_INDEX], propagation_pos[PHASE_INDEX], color='g', label='positive sequence')
ax.set(xlabel='Frequency $Hz$', ylabel=r'Phase $\phi{}=\beta{}l=\omega{}\tau$ ($rad$)', title='$e^{-\gamma{}l}$ - Phase vs. Frequency')
ax.grid()
ax.legend(loc='best', prop={'size':legend_font_size}, fancybox=True, shadow=True)
fig.set_size_inches(6.5,3.5)
fig.tight_layout()
fig.savefig('prop_phase_plot_nolog.pgf')
fig.savefig('prop_phase_plot_nolog.png')
# Plot attenuation (real component of gamma) (nepers/km)
fig, ax = plt.subplots()
ax.plot(data[FREQ_INDEX], attenuation_zero, color='b', label='zero sequence')
ax.plot(data[FREQ_INDEX], attenuation_pos, color='g', label='positive sequence')
ax.set(xlabel='Frequency $Hz$', ylabel=r'Attenuation $\alpha{}(\omega)$ $(nepers/km)$', title=r'Attenuation $\alpha{}(\omega)$ vs. Frequency')
ax.grid()
ax.set_xscale('log')
ax.legend(loc='best', prop={'size':legend_font_size}, fancybox=True, shadow=True)
fig.set_size_inches(6.5,3.5)
fig.tight_layout()
fig.savefig('attenuation_plots.pgf')
fig.savefig('attenuation_plots.png')
# Plot phase displacement beta(w) (radians/km)
fig, ax = plt.subplots()
ax.plot(data[FREQ_INDEX], phase_zero, color='b', label='zero sequence')
ax.plot(data[FREQ_INDEX], phase_pos, color='g', label='positive sequence')
ax.set(xlabel='Frequency $Hz$', ylabel=r'Phase Displacement $\beta{}(\omega)$ $(rad/km)$', title=r'Phase Displacement $\beta{}(\omega)$ vs. Frequency')
ax.grid()
ax.set_xscale('log')
ax.legend(loc='best', prop={'size':legend_font_size}, fancybox=True, shadow=True)
fig.set_size_inches(6.5,3.5)
fig.tight_layout()
fig.savefig('phase_displacement_plots.pgf')
fig.savefig('phase_displacement_plots.png')
# Plot propagation speed a(w) (km/s)
fig, ax = plt.subplots()
ax.plot(data[FREQ_INDEX], propagation_speed_zero, color='b', label='zero sequence')
ax.plot(data[FREQ_INDEX], propagation_speed_pos, color='g', label='positive sequence')
ax.set(xlabel='Frequency $Hz$', ylabel=r'Propagation Speed $a(\omega)$ $(km/s)$', title=r'Propagation Speed $a(\omega)$ vs. Frequency')
ax.grid()
ax.set_xscale('log')
ax.legend(loc='best', prop={'size':legend_font_size}, fancybox=True, shadow=True)
fig.set_size_inches(6.5,3.5)
fig.tight_layout()
fig.savefig('propagation_speed_plots.pgf')
fig.savefig('propagation_speed_plots.png')
if __name__ == '__main__':
# the following sets up the argument parser for the program
parser = argparse.ArgumentParser(description='Assignment 4 solution generator')
args = parser.parse_args()
main(args) | [
"numpy.sqrt",
"argparse.ArgumentParser",
"matplotlib.rcParams.update",
"matplotlib.use",
"matplotlib.ticker.MultipleLocator",
"numpy.absolute",
"numpy.imag",
"numpy.angle",
"numpy.exp",
"numpy.real",
"matplotlib.ticker.FormatStrFormatter",
"csv.reader",
"matplotlib.pyplot.subplots"
] | [((160, 181), 'matplotlib.use', 'matplotlib.use', (['"""pgf"""'], {}), "('pgf')\n", (174, 181), False, 'import matplotlib\n'), ((214, 359), 'matplotlib.rcParams.update', 'matplotlib.rcParams.update', (["{'pgf.texsystem': 'pdflatex', 'font.size': 10, 'font.family': 'serif',\n 'text.usetex': True, 'pgf.rcfonts': False}"], {}), "({'pgf.texsystem': 'pdflatex', 'font.size': 10,\n 'font.family': 'serif', 'text.usetex': True, 'pgf.rcfonts': False})\n", (240, 359), False, 'import matplotlib\n'), ((5331, 5346), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)'], {}), '(2)\n', (5343, 5346), True, 'import matplotlib.pyplot as plt\n'), ((6585, 6600), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)'], {}), '(2)\n', (6597, 6600), True, 'import matplotlib.pyplot as plt\n'), ((7805, 7820), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)'], {}), '(1)\n', (7817, 7820), True, 'import matplotlib.pyplot as plt\n'), ((8476, 8490), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (8488, 8490), True, 'import matplotlib.pyplot as plt\n'), ((9134, 9148), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (9146, 9148), True, 'import matplotlib.pyplot as plt\n'), ((9793, 9807), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (9805, 9807), True, 'import matplotlib.pyplot as plt\n'), ((10507, 10577), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Assignment 4 solution generator"""'}), "(description='Assignment 4 solution generator')\n", (10530, 10577), False, 'import argparse\n'), ((1094, 1129), 'csv.reader', 'csv.reader', (['csv_file'], {'delimiter': '""","""'}), "(csv_file, delimiter=',')\n", (1104, 1129), False, 'import csv\n'), ((2097, 2216), 'numpy.sqrt', 'np.sqrt', (['((data[R_ZERO_INDEX][index] + 1.0j * omega * data[L_ZERO_INDEX][index]) / (\n G_zero + 1.0j * omega * C_zero))'], {}), '((data[R_ZERO_INDEX][index] + 1.0j * omega * data[L_ZERO_INDEX][\n index]) / (G_zero + 1.0j * omega * C_zero))\n', (2104, 2216), True, 'import numpy as np\n'), ((2231, 2346), 'numpy.sqrt', 'np.sqrt', (['((data[R_POS_INDEX][index] + 1.0j * omega * data[L_POS_INDEX][index]) / (\n G_pos + 1.0j * omega * C_pos))'], {}), '((data[R_POS_INDEX][index] + 1.0j * omega * data[L_POS_INDEX][index]\n ) / (G_pos + 1.0j * omega * C_pos))\n', (2238, 2346), True, 'import numpy as np\n'), ((3954, 4073), 'numpy.sqrt', 'np.sqrt', (['((data[R_ZERO_INDEX][index] + 1.0j * omega * data[L_ZERO_INDEX][index]) * (\n G_zero + 1.0j * omega * C_zero))'], {}), '((data[R_ZERO_INDEX][index] + 1.0j * omega * data[L_ZERO_INDEX][\n index]) * (G_zero + 1.0j * omega * C_zero))\n', (3961, 4073), True, 'import numpy as np\n'), ((4075, 4190), 'numpy.sqrt', 'np.sqrt', (['((data[R_POS_INDEX][index] + 1.0j * omega * data[L_POS_INDEX][index]) * (\n G_pos + 1.0j * omega * C_pos))'], {}), '((data[R_POS_INDEX][index] + 1.0j * omega * data[L_POS_INDEX][index]\n ) * (G_pos + 1.0j * omega * C_pos))\n', (4082, 4190), True, 'import numpy as np\n'), ((6030, 6068), 'matplotlib.ticker.FormatStrFormatter', 'tck.FormatStrFormatter', (['"""%1.1f $\\\\pi$"""'], {}), "('%1.1f $\\\\pi$')\n", (6052, 6068), True, 'import matplotlib.ticker as tck\n'), ((6103, 6134), 'matplotlib.ticker.MultipleLocator', 'tck.MultipleLocator', ([], {'base': '(1 / 5)'}), '(base=1 / 5)\n', (6122, 6134), True, 'import matplotlib.ticker as tck\n'), ((3100, 3131), 'numpy.absolute', 'np.absolute', (['impedance_zero_val'], {}), '(impedance_zero_val)\n', (3111, 3131), True, 'import numpy as np\n'), ((3176, 3204), 'numpy.angle', 'np.angle', (['impedance_zero_val'], {}), '(impedance_zero_val)\n', (3184, 3204), True, 'import numpy as np\n'), ((3252, 3282), 'numpy.absolute', 'np.absolute', (['impedance_pos_val'], {}), '(impedance_pos_val)\n', (3263, 3282), True, 'import numpy as np\n'), ((3326, 3353), 'numpy.angle', 'np.angle', (['impedance_pos_val'], {}), '(impedance_pos_val)\n', (3334, 3353), True, 'import numpy as np\n'), ((4643, 4662), 'numpy.real', 'np.real', (['gamma_zero'], {}), '(gamma_zero)\n', (4650, 4662), True, 'import numpy as np\n'), ((4695, 4713), 'numpy.real', 'np.real', (['gamma_pos'], {}), '(gamma_pos)\n', (4702, 4713), True, 'import numpy as np\n'), ((4814, 4833), 'numpy.imag', 'np.imag', (['gamma_zero'], {}), '(gamma_zero)\n', (4821, 4833), True, 'import numpy as np\n'), ((4860, 4878), 'numpy.imag', 'np.imag', (['gamma_pos'], {}), '(gamma_pos)\n', (4867, 4878), True, 'import numpy as np\n'), ((4284, 4316), 'numpy.exp', 'np.exp', (['(-1 * gamma_zero * length)'], {}), '(-1 * gamma_zero * length)\n', (4290, 4316), True, 'import numpy as np\n'), ((4449, 4480), 'numpy.exp', 'np.exp', (['(-1 * gamma_pos * length)'], {}), '(-1 * gamma_pos * length)\n', (4455, 4480), True, 'import numpy as np\n'), ((4361, 4380), 'numpy.imag', 'np.imag', (['gamma_zero'], {}), '(gamma_zero)\n', (4368, 4380), True, 'import numpy as np\n'), ((4524, 4542), 'numpy.imag', 'np.imag', (['gamma_pos'], {}), '(gamma_pos)\n', (4531, 4542), True, 'import numpy as np\n')] |
# coding=utf-8
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.base.build_environment import get_scm
from pants.base.exceptions import TaskError
from pants.goal.workspace import ScmWorkspace
from pants.scm.change_calculator import BuildGraphChangeCalculator
from pants.subsystem.subsystem import Subsystem
from pants.util.objects import datatype
# TODO: Remove this in 1.5.0dev0.
class _ChainedOptions(object):
def __init__(self, options_seq):
self._options_seq = options_seq
def __getattr__(self, attr):
for options in self._options_seq:
option_value = getattr(options, attr, None)
if option_value is not None:
return option_value
return None
class ChangedRequest(datatype('ChangedRequest',
['changes_since', 'diffspec', 'include_dependees', 'fast'])):
"""Parameters required to compute a changed file/target set."""
@classmethod
def from_options(cls, options):
"""Given an `Options` object, produce a `ChangedRequest`."""
return cls(options.changes_since,
options.diffspec,
options.include_dependees,
options.fast)
def is_actionable(self):
return bool(self.changes_since or self.diffspec)
class Changed(object):
"""A subsystem for global `changed` functionality.
This supports the "legacy" `changed`, `test-changed` and `compile-changed` goals as well as the
v2 engine style `--changed-*` argument target root replacements which can apply to any goal (e.g.
`./pants --changed-parent=HEAD~3 list` replaces `./pants --changed-parent=HEAD~3 changed`).
"""
class Factory(Subsystem):
options_scope = 'changed'
@classmethod
def register_options(cls, register):
register('--changes-since', '--parent', '--since',
help='Calculate changes since this tree-ish/scm ref (defaults to current HEAD/tip).')
register('--diffspec',
help='Calculate changes contained within given scm spec (commit range/sha/ref/etc).')
register('--include-dependees', choices=['none', 'direct', 'transitive'], default='none',
help='Include direct or transitive dependees of changed targets.')
register('--fast', type=bool,
help='Stop searching for owners once a source is mapped to at least one owning target.')
# TODO: Remove or reduce this in 1.5.0dev0 - we only need the subsystem's options scope going fwd.
@classmethod
def create(cls, alternate_options=None):
"""
:param Options alternate_options: An alternate `Options` object for overrides.
"""
options = cls.global_instance().get_options()
# N.B. This chaining is purely to support the `changed` tests until deprecation.
ordered_options = [option for option in (alternate_options, options) if option is not None]
# TODO: Kill this chaining (in favor of outright options replacement) as part of the `changed`
# task removal (post-deprecation cycle). See https://github.com/pantsbuild/pants/issues/3893
chained_options = _ChainedOptions(ordered_options)
changed_request = ChangedRequest.from_options(chained_options)
return Changed(changed_request)
def __init__(self, changed_request):
self._changed_request = changed_request
# TODO: Remove this in 1.5.0dev0 in favor of `TargetRoots` use of `EngineChangeCalculator`.
def change_calculator(self, build_graph, address_mapper, scm=None, workspace=None,
exclude_target_regexp=None):
"""Constructs and returns a BuildGraphChangeCalculator.
:param BuildGraph build_graph: A BuildGraph instance.
:param AddressMapper address_mapper: A AddressMapper instance.
:param Scm scm: The SCM instance. Defaults to discovery.
:param ScmWorkspace: The SCM workspace instance.
:param string exclude_target_regexp: The exclude target regexp.
"""
scm = scm or get_scm()
if scm is None:
raise TaskError('A `changed` goal or `--changed` option was specified, '
'but no SCM is available to satisfy the request.')
workspace = workspace or ScmWorkspace(scm)
return BuildGraphChangeCalculator(
scm,
workspace,
address_mapper,
build_graph,
self._changed_request.include_dependees,
fast=self._changed_request.fast,
changes_since=self._changed_request.changes_since,
diffspec=self._changed_request.diffspec,
exclude_target_regexp=exclude_target_regexp
)
| [
"pants.goal.workspace.ScmWorkspace",
"pants.util.objects.datatype",
"pants.base.exceptions.TaskError",
"pants.base.build_environment.get_scm",
"pants.scm.change_calculator.BuildGraphChangeCalculator"
] | [((954, 1044), 'pants.util.objects.datatype', 'datatype', (['"""ChangedRequest"""', "['changes_since', 'diffspec', 'include_dependees', 'fast']"], {}), "('ChangedRequest', ['changes_since', 'diffspec',\n 'include_dependees', 'fast'])\n", (962, 1044), False, 'from pants.util.objects import datatype\n'), ((4401, 4697), 'pants.scm.change_calculator.BuildGraphChangeCalculator', 'BuildGraphChangeCalculator', (['scm', 'workspace', 'address_mapper', 'build_graph', 'self._changed_request.include_dependees'], {'fast': 'self._changed_request.fast', 'changes_since': 'self._changed_request.changes_since', 'diffspec': 'self._changed_request.diffspec', 'exclude_target_regexp': 'exclude_target_regexp'}), '(scm, workspace, address_mapper, build_graph,\n self._changed_request.include_dependees, fast=self._changed_request.\n fast, changes_since=self._changed_request.changes_since, diffspec=self.\n _changed_request.diffspec, exclude_target_regexp=exclude_target_regexp)\n', (4427, 4697), False, 'from pants.scm.change_calculator import BuildGraphChangeCalculator\n'), ((4160, 4169), 'pants.base.build_environment.get_scm', 'get_scm', ([], {}), '()\n', (4167, 4169), False, 'from pants.base.build_environment import get_scm\n'), ((4202, 4326), 'pants.base.exceptions.TaskError', 'TaskError', (['"""A `changed` goal or `--changed` option was specified, but no SCM is available to satisfy the request."""'], {}), "(\n 'A `changed` goal or `--changed` option was specified, but no SCM is available to satisfy the request.'\n )\n", (4211, 4326), False, 'from pants.base.exceptions import TaskError\n'), ((4371, 4388), 'pants.goal.workspace.ScmWorkspace', 'ScmWorkspace', (['scm'], {}), '(scm)\n', (4383, 4388), False, 'from pants.goal.workspace import ScmWorkspace\n')] |
"""
eZmax API Definition (Full)
This API expose all the functionnalities for the eZmax and eZsign applications. # noqa: E501
The version of the OpenAPI document: 1.1.7
Contact: <EMAIL>
Generated by: https://openapi-generator.tech
"""
import unittest
import eZmaxApi
from eZmaxApi.api.global_customer_api import GlobalCustomerApi # noqa: E501
class TestGlobalCustomerApi(unittest.TestCase):
"""GlobalCustomerApi unit test stubs"""
def setUp(self):
self.api = GlobalCustomerApi() # noqa: E501
def tearDown(self):
pass
def test_global_customer_get_endpoint_v1(self):
"""Test case for global_customer_get_endpoint_v1
Get customer endpoint # noqa: E501
"""
pass
if __name__ == '__main__':
unittest.main()
| [
"unittest.main",
"eZmaxApi.api.global_customer_api.GlobalCustomerApi"
] | [((789, 804), 'unittest.main', 'unittest.main', ([], {}), '()\n', (802, 804), False, 'import unittest\n'), ((504, 523), 'eZmaxApi.api.global_customer_api.GlobalCustomerApi', 'GlobalCustomerApi', ([], {}), '()\n', (521, 523), False, 'from eZmaxApi.api.global_customer_api import GlobalCustomerApi\n')] |
import unittest
from cosymlib import file_io
from numpy import testing
from cosymlib.molecule.geometry import Geometry
import os
data_dir = os.path.join(os.path.dirname(__file__), 'data')
class TestSymgroupFchk(unittest.TestCase):
def setUp(self):
self._structure = file_io.read_generic_structure_file(data_dir + '/wfnsym/tih4_5d.fchk')
self._geometry = self._structure.geometry
def test_symmetry_measure(self):
# print(self._structure.geometry)
measure = self._geometry.get_symmetry_measure('C3', central_atom=1)
self.assertAlmostEqual(measure, 0)
class TestSymgroupCycles(unittest.TestCase):
def setUp(self):
self._geometry = Geometry(positions=[[ 0.506643354, -1.227657970, 0.000000000],
[ 1.303068499, 0.000000000, 0.000000000],
[ 0.506643354, 1.227657970, 0.000000000],
[-0.926250976, 0.939345948, 0.000000000],
[-0.926250976, -0.939345948, 0.000000000]],
# name='test',
symbols=['C', 'C', 'C', 'C', 'C'],
connectivity_thresh=1.5,
)
def test_symmetry_measure(self):
measure = self._geometry.get_symmetry_measure('C5')
self.assertAlmostEqual(measure, 0.8247502, places=6)
measure = self._geometry.get_symmetry_measure('C2')
self.assertAlmostEqual(measure, 0.0, places=6)
measure = self._geometry.get_symmetry_measure('C3')
self.assertAlmostEqual(measure, 33.482451, places=6)
#def test_symmetry_measure_permutation(self):
# measure = self._geometry.get_symmetry_measure('C5', fix_permutation=True)
# self.assertAlmostEqual(measure, 0.8247502, places=6)
def test_symmetry_nearest(self):
nearest = self._geometry.get_symmetry_nearest_structure('C5').get_positions()
# print(nearest)
reference = [[ 4.05078542e-01, -1.24670356e+00, 0.00000000e+00],
[ 1.31086170e+00, -1.33226763e-16, 0.00000000e+00],
[ 4.05078542e-01, 1.24670356e+00, 0.00000000e+00],
[-1.06050939e+00, 7.70505174e-01, 0.00000000e+00],
[-1.06050939e+00, -7.70505174e-01, 0.00000000e+00]]
testing.assert_array_almost_equal(nearest, reference, decimal=6)
| [
"os.path.dirname",
"numpy.testing.assert_array_almost_equal",
"cosymlib.molecule.geometry.Geometry",
"cosymlib.file_io.read_generic_structure_file"
] | [((155, 180), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (170, 180), False, 'import os\n'), ((283, 353), 'cosymlib.file_io.read_generic_structure_file', 'file_io.read_generic_structure_file', (["(data_dir + '/wfnsym/tih4_5d.fchk')"], {}), "(data_dir + '/wfnsym/tih4_5d.fchk')\n", (318, 353), False, 'from cosymlib import file_io\n'), ((697, 950), 'cosymlib.molecule.geometry.Geometry', 'Geometry', ([], {'positions': '[[0.506643354, -1.22765797, 0.0], [1.303068499, 0.0, 0.0], [0.506643354, \n 1.22765797, 0.0], [-0.926250976, 0.939345948, 0.0], [-0.926250976, -\n 0.939345948, 0.0]]', 'symbols': "['C', 'C', 'C', 'C', 'C']", 'connectivity_thresh': '(1.5)'}), "(positions=[[0.506643354, -1.22765797, 0.0], [1.303068499, 0.0, 0.0\n ], [0.506643354, 1.22765797, 0.0], [-0.926250976, 0.939345948, 0.0], [-\n 0.926250976, -0.939345948, 0.0]], symbols=['C', 'C', 'C', 'C', 'C'],\n connectivity_thresh=1.5)\n", (705, 950), False, 'from cosymlib.molecule.geometry import Geometry\n'), ((2444, 2508), 'numpy.testing.assert_array_almost_equal', 'testing.assert_array_almost_equal', (['nearest', 'reference'], {'decimal': '(6)'}), '(nearest, reference, decimal=6)\n', (2477, 2508), False, 'from numpy import testing\n')] |
# -*- coding: utf-8 -*-
"""Gymnasium implementation."""
# Django
from django.core.validators import RegexValidator
from django.db import models
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _ # noqa
class Gymnasium(models.Model):
"""Gymnasium model for the website."""
slug = models.SlugField(_('slug'), unique=True, max_length=128)
name = models.CharField(_('name'), max_length=128)
address = models.CharField(_('address'), max_length=255)
city = models.CharField(_('city'), max_length=255)
zip_code = models.IntegerField(_('zip code'))
phone = models.CharField(
_('phone number'),
max_length=10,
blank=True,
validators=[
# ^
# (?:(?:\+|00)33|0) # Dialing code
# \s*[1-9] # First number (from 1 to 9)
# (?:[\s.-]*\d{2}){4} # End of the phone number
# $
RegexValidator(regex=r"^(?:(?:\+|00)33|0)\s*[1-7,9](?:[\s.-]*\d{2}){4}$",
message=_("This is not a correct phone number"))
]
)
surface = models.SmallIntegerField(_('surface'), blank=True, null=True)
capacity = models.SmallIntegerField(_('capacity'), blank=True, null=True)
def __str__(self):
"""Representation of a Gymnasium as a string."""
return "Gymnasium {}".format(self.name)
class Meta:
verbose_name = _("gymnasium")
verbose_name_plural = _("gymnasiums")
ordering = ("name", "city")
def save(self, *args, **kwargs):
"""Override the save method in order to rewrite the slug field each time we save the object."""
self.slug = slugify(self.name)
super().save(*args, **kwargs)
def get_time_slots(self):
"""Return a list of all the time slots in the gymnasium."""
return self.time_slot_set.all() | [
"django.utils.text.slugify",
"django.utils.translation.ugettext_lazy"
] | [((352, 361), 'django.utils.translation.ugettext_lazy', '_', (['"""slug"""'], {}), "('slug')\n", (353, 361), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((420, 429), 'django.utils.translation.ugettext_lazy', '_', (['"""name"""'], {}), "('name')\n", (421, 429), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((478, 490), 'django.utils.translation.ugettext_lazy', '_', (['"""address"""'], {}), "('address')\n", (479, 490), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((536, 545), 'django.utils.translation.ugettext_lazy', '_', (['"""city"""'], {}), "('city')\n", (537, 545), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((598, 611), 'django.utils.translation.ugettext_lazy', '_', (['"""zip code"""'], {}), "('zip code')\n", (599, 611), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((651, 668), 'django.utils.translation.ugettext_lazy', '_', (['"""phone number"""'], {}), "('phone number')\n", (652, 668), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1173, 1185), 'django.utils.translation.ugettext_lazy', '_', (['"""surface"""'], {}), "('surface')\n", (1174, 1185), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1250, 1263), 'django.utils.translation.ugettext_lazy', '_', (['"""capacity"""'], {}), "('capacity')\n", (1251, 1263), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1457, 1471), 'django.utils.translation.ugettext_lazy', '_', (['"""gymnasium"""'], {}), "('gymnasium')\n", (1458, 1471), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1502, 1517), 'django.utils.translation.ugettext_lazy', '_', (['"""gymnasiums"""'], {}), "('gymnasiums')\n", (1503, 1517), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1716, 1734), 'django.utils.text.slugify', 'slugify', (['self.name'], {}), '(self.name)\n', (1723, 1734), False, 'from django.utils.text import slugify\n'), ((1077, 1116), 'django.utils.translation.ugettext_lazy', '_', (['"""This is not a correct phone number"""'], {}), "('This is not a correct phone number')\n", (1078, 1116), True, 'from django.utils.translation import ugettext_lazy as _\n')] |
#!/usr/bin/env python3
# coding: utf-8
# MIT License © https://github.com/scherma
# contact http_<EMAIL>4<EMAIL>
import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal
import tempfile, evtx_dates, db_calls, psycopg2, psycopg2.extras, sys, pcap_parser, yarahandler, magic, case_postprocess
import scapy.all as scapy
from lxml import etree
from io import StringIO, BytesIO
from PIL import Image
logger = logging.getLogger("antfarm.worker")
# Manages connection to VM and issuing of commands
class RunInstance():
def __init__( self,
cursor,
dbconn,
domuuid,
conf,
fname,
uuid,
submittime,
hashes,
victim_params,
ttl=240,
interactive=False,
reboots=0,
web=True,
banking=False,
collect_registries=False,
filespath = "suspects",
outdir = "output"
):
self.conf = conf
self.rootdir = os.path.join(conf.get('General', 'basedir'), self.conf.get('General', 'instancename'))
self.uuid = uuid
self.starttime = arrow.utcnow().timestamp
self.endtime = None
self.submittime = submittime
self.hashes = hashes
self.ttl = ttl
self.interactive = interactive
self.reboots = reboots
self.banking = banking
self.collect_registries = collect_registries
self.web = web
self.filespath = os.path.join(self.rootdir, filespath)
self.fname = self._suspect_exists(fname)
self.victim_params = victim_params
self.runcmds = []
self.rundir = self._make_outputdir(outdir)
self.imgdir = self._make_imgdir()
self.runlog = self._register_logger()
self.pcap_file = os.path.join(self.rundir, "capture.pcap")
#self.stop_capture = False
self.imgsequence = 0
self.cursor = cursor
self.dbconn = dbconn
self.domuuid = domuuid
self.yara_test()
self.vf = None
self.websockserver = None
def __del__(self):
self._unregister_logger()
self.remove_vnc()
@property
def rawfile(self):
return os.path.join(self.filespath, self.hashes["sha256"][0:2], self.hashes["sha256"])
@property
def downloadfile(self):
return os.path.join(self.filespath, 'downloads', str(self.domuuid), self.fname)
@property
def banking(self):
return int(self._banking)
@banking.setter
def banking(self, value):
self._banking = bool(value)
@property
def web(self):
return int(self._web)
@banking.setter
def web(self, value):
self._web = bool(value)
@property
def interactive(self):
return int(self._interactive)
@interactive.setter
def interactive(self, value):
self._interactive = bool(value)
def _dump_dict(self):
tformat = 'YYYY-MM-DD HH:mm:ss.SSSZ'
selfdict = {
"rootdir": self.rootdir,
"uuid": self.uuid,
"starttime": self.starttime,
"endtime": self.endtime,
"submittime": self.submittime,
"hashes": self.hashes,
"ttl": self.ttl,
"interactive": self.interactive,
"reboots": self.reboots,
"banking": self.banking,
"web": self.web,
"filespath": self.filespath,
"fname": self.fname,
"victim_params": self.victim_params,
"runcmds": self.runcmds,
"rundir": self.rundir,
"pcap_file": self.pcap_file
}
return selfdict
def _make_outputdir(self, outdir):
short = self.hashes["sha256"][0:2]
bdir = os.path.join(self.rootdir, outdir, short)
if not os.path.exists(bdir):
os.mkdir(bdir)
fdir = os.path.join(bdir, self.hashes["sha256"])
if not os.path.exists(fdir):
os.mkdir(fdir)
# rundir should not exist before the run - if it does, UUID is broken somehow!
rundir = os.path.join(fdir, self.uuid)
if not os.path.exists(rundir):
os.mkdir(rundir)
logger.debug("Created run instance directory {0}".format(rundir))
return rundir
def _make_imgdir(self):
imgshort = os.path.join(self.rootdir, 'www', 'public', 'images', 'cases', self.uuid[0:2])
if not os.path.exists(imgshort):
os.mkdir(imgshort)
logger.debug("Made images base dir {0}".format(imgshort))
imgdir = os.path.join(imgshort, self.uuid)
if not os.path.exists(imgdir):
os.mkdir(imgdir)
logger.debug("Made images final dir {0}".format(imgdir))
return imgdir
def _register_logger(self):
formatter = logging.Formatter(fmt='[%(asctime)s] %(levelname)s\t%(message)s', datefmt='%Y%m%d %H:%M:%S')
runlog = logging.FileHandler(os.path.join(self.rundir, 'run.log'))
RUN_NUM_LEVEL = getattr(logging, self.conf.get('General', 'runloglevel'))
runlog.setLevel(RUN_NUM_LEVEL)
runlog.setFormatter(formatter)
log_modules = [__name__, "pyvnc", "vmworker", "runinstance", "db_calls", "victimfiles", "yarahandler"]
for module in log_modules:
logging.getLogger(module).setLevel(RUN_NUM_LEVEL)
logger.addHandler(runlog)
return runlog
def _unregister_logger(self):
logger.removeHandler(self.runlog)
def _suspect_exists(self, fname):
open(self.rawfile).close()
logger.debug("Confirmed file '{0}' exists with sha256 '{1}'".format(fname, self.hashes["sha256"]))
return fname
def yara_test(self):
matches = yarahandler.testyara(self.conf, self.rawfile)
if matches:
logger.info("Found yara matches: {}".format(matches))
db_calls.yara_detection(matches, self.hashes["sha256"], self.cursor)
else:
logger.info("No yara matches found")
# make a screenshot
# https://www.linuxvoice.com/issues/003/LV3libvirt.pdf
def screenshot(self, dom, lv_conn):
imgpath = os.path.join(self.imgdir, "{0}.png".format(self.imgsequence))
thumbpath = os.path.join(self.imgdir, "{0}-thumb.png".format(self.imgsequence))
i = get_screen_image(dom, lv_conn)
i.save(imgpath)
i.thumbnail((400, 400))
i.save(thumbpath)
logger.debug("Took screenshot {0}".format(imgpath))
self.imgsequence += 1
def _sc_writer(self, stream, data, b):
b.write(data)
def case_update(self, status):
self.cursor.execute("""UPDATE "cases" SET status = %s WHERE uuid=%s""", (status, self.uuid))
self.dbconn.commit()
def get_pcap(self):
try:
folder = "/usr/local/unsafehex/{}/pcaps".format(self.conf.get("General", "instancename"))
def getmtime(name):
path = os.path.join(folder, name)
return os.path.getmtime(path)
pcaps = sorted(os.listdir(folder), key=getmtime, reverse=True)
to_read = []
start = arrow.get(self.starttime)
end = arrow.get(self.endtime)
hours_list = arrow.Arrow.range("hour", start, end)
for pcap_file in pcaps:
pf = os.path.join(folder, pcap_file)
if arrow.get(os.path.getmtime(pf)) > start:
to_read.append(pf)
logger.debug("Reading from pcaps: {}".format(to_read))
#for hour in hours_list:
# pcap_file = "{}.pcap".format(hour.format("HH"))
# to_read.append(pcap_file)
fl = "host {0} and not (host {1} and port 28080)".format(self.victim_params["ip"], self.conf.get("General", "gateway_ip"))
logger.debug("Reading pcapring with filter {}".format(fl))
logger.debug("Time parameters: {} :: {}".format(start, end))
written = 0
for pcap in to_read:
logger.debug("Reading {}".format(pcap))
packets = scapy.sniff(offline=pcap, filter=fl)
for packet in packets:
ptime = arrow.get(packet.time)
if ptime >= start and ptime <= end:
scapy.wrpcap(self.pcap_file, packet, append=True)
written += 1
logger.info("Wrote {} packets to file {}".format(written, self.pcap_file))
conversations = pcap_parser.conversations(self.pcap_file)
db_calls.insert_pcap_streams(conversations, self.uuid, self.cursor)
except Exception:
ex_type, ex, tb = sys.exc_info()
fname = os.path.split(tb.tb_frame.f_code.co_filename)[1]
lineno = tb.tb_lineno
logger.error("Exception {0} {1} in {2}, line {3} while processing pcap".format(ex_type, ex, fname, lineno))
def events_to_store(self, searchfiles, startdate, enddate):
events = {}
logger.debug("Searching suricata log files: {}".format(searchfiles))
for searchfile in searchfiles:
evctr = 0
if os.path.exists(searchfile):
with open(searchfile) as f:
for line in f:
d = json.loads(line.rstrip(' \t\r\n\0').lstrip(' \t\r\n\0'))
t = arrow.get(d["timestamp"])
# ensure only event types we can handle safely get looked at
if d["event_type"] in ["tls", "http", "dns", "alert"]:
# include everything from selected host
if ((d["src_ip"] == self.victim_params["ip"] or d["dest_ip"] == self.victim_params["ip"]) and
# that falls within the run time
(t >= startdate and t <= enddate) and not
# except where the target is the API service
(d["dest_ip"] == self.conf.get("General", "gateway_ip") and d["dest_port"] == 28080)):
if d["event_type"] != "alert" or (d["event_type"] == "alert" and d["alert"]["category"] != "Generic Protocol Command Decode"):
if d["event_type"] not in events:
events[d["event_type"]] = [d]
else:
events[d["event_type"]].append(d)
evctr += 1
logger.info("Identified {0} events to include from {1}".format(evctr, searchfile))
return events
def behaviour(self, dom, lv_conn):
try:
cstr = "{0}::{1}".format(self.victim_params["vnc"]["address"], self.victim_params["vnc"]["port"])
vncconn = pyvnc.Connector(cstr, self.victim_params["password"], (self.victim_params["display_x"], self.victim_params["display_y"]))
logger.debug("Initialised VNC connection")
click_after = arrow.now().format("YYYY-MM-DD HH:mm:ss")
for i in range(0,5):
vncconn.run_sample(self.victim_params["malware_pos_x"], self.victim_params["malware_pos_y"])
time.sleep(6)
if self.sample_has_run(click_after):
self.screenshot(dom, lv_conn)
break
logger.error("Didn't see a process creation. That's odd...")
#logger.info("VM prepped for suspect execution, starting behaviour sequence")
if self.interactive:
logger.info("Passing control to user")
else:
vncconn.basic()
logger.info("Basic behaviour complete")
self.screenshot(dom, lv_conn)
if self.banking:
vncconn.bank()
self.screenshot(dom, lv_conn)
logger.info("Banking happened")
if self.reboots:
vncconn.restart()
logger.info("System rebooted")
if self.web:
vncconn.web()
self.screenshot(dom, lv_conn)
logger.info("Web activity happened")
if self.reboots > 1:
vncconn.restart()
logger.info("System rebooted")
logger.info("Behaviour sequence complete")
vncconn.disconnect()
logger.debug("VNC disconnect issued")
except Exception as e:
ex_type, ex, tb = sys.exc_info()
fname = os.path.split(tb.tb_frame.f_code.co_filename)[1]
lineno = tb.tb_lineno
raise RuntimeError("Exception {0} {1} in {2}, line {3} while processing job, run not completed. Aborting.".format(ex_type, ex, fname, lineno))
def sample_has_run(self, click_after):
# for now let's just assume it did
return True
self.cursor.execute("""SELECT * FROM sysmon_evts WHERE uuid=%s AND eventid=1 AND timestamp > %s""", (self.uuid, click_after))
rows = self.cursor.fetchall()
# check if any processes have been started from Explorer
for row in rows:
if row["eventid"] == 1:
if row["eventdata"]["ParentImage"] == "C:\\Windows\\explorer.exe":
return True
return False
def do_run(self, dom, lv_conn):
logger.info("Started run sequence")
# prep the file for run
shutil.copy(self.rawfile, self.downloadfile)
logger.debug("File copied ready for download")
try:
dom.resume()
logger.debug("Resumed VM in preparation for run")
case_obtained = False
while not case_obtained:
self.cursor.execute("""SELECT status FROM cases WHERE uuid=%s""", (self.uuid,))
rows = self.cursor.fetchall()
if rows and rows[0]["status"] == "obtained":
break
else:
time.sleep(5)
logger.info("Suspect was delivered, starting behaviour sequence")
self.behaviour(dom, lv_conn)
# except block for debugging purposes - clean this up for production
except Exception as e:
ex_type, ex, tb = sys.exc_info()
fname = os.path.split(tb.tb_frame.f_code.co_filename)[1]
lineno = tb.tb_lineno
raise RuntimeError("Exception {0} {1} in {2}, line {3} while processing job, run not completed. Aborting.".format(ex_type, ex, fname, lineno))
finally:
#ssh.close()
os.remove(self.downloadfile)
logger.debug("Removed download file")
def targeted_files_list(self):
targeted_files = []
targeted_files.extend(db_calls.timestomped_files(self.uuid, self.cursor))
return targeted_files
def construct_record(self, victim_params):
dtstart = arrow.get(self.starttime)
dtend = arrow.get(self.endtime)
try:
logger.info("Obtaining new files from guest filesystem")
self.vf = victimfiles.VictimFiles(self.conf, self.victim_params["diskfile"], '/dev/sda2')
filesdict = self.vf.download_new_files(dtstart, self.rundir)
registriesdict = self.vf.download_modified_registries(dtstart, self.rundir, self.victim_params["username"], self.collect_registries)
targetedfilesdict = self.vf.download_specific_files(self.targeted_files_list(), self.rundir)
compileddict = {**filesdict, **registriesdict, **targetedfilesdict}
db_calls.insert_files(compileddict, self.uuid, self.cursor)
except Exception:
ex_type, ex, tb = sys.exc_info()
fname = os.path.split(tb.tb_frame.f_code.co_filename)[1]
lineno = tb.tb_lineno
logger.error("Exception {0} {1} in {2}, line {3} while processing filesystem output".format(ex_type, ex, fname, lineno))
finally:
try:
del(vf)
except Exception:
pass
try:
# record suricata events
eventlog = os.path.join(self.rundir, "eve.json")
with open(eventlog, 'w') as e:
files = self._suricata_logfiles
events = self.events_to_store(files, dtstart, dtend)
#e.write(json.dumps(events))
qty = {}
for evtype in events:
qty[evtype] = len(events[evtype])
if evtype == "dns":
db_calls.insert_dns(events[evtype], self.uuid, self.cursor)
if evtype == "http":
db_calls.insert_http(events[evtype], self.uuid, self.cursor)
if evtype == "alert":
db_calls.insert_alert(events[evtype], self.uuid, self.cursor)
if evtype == "tls":
db_calls.insert_tls(events[evtype], self.uuid, self.cursor)
logger.info("Wrote events to {0}: {1}".format(eventlog, str(qty)))
except Exception:
ex_type, ex, tb = sys.exc_info()
fname = os.path.split(tb.tb_frame.f_code.co_filename)[1]
lineno = tb.tb_lineno
logger.error("Exception {0} {1} in {2}, line {3} while processing job, Suricata data not written".format(ex_type, ex, fname, lineno))
try:
self.get_pcap()
except Exception:
ex_type, ex, tb = sys.exc_info()
fname = os.path.split(tb.tb_frame.f_code.co_filename)[1]
lineno = tb.tb_lineno
logger.error("Exception {0} {1} in {2}, line {3} while processing job, pcap processing failed".format(ex_type, ex, fname, lineno))
try:
pp = case_postprocess.Postprocessor(self.uuid, self.cursor)
pp.update_events()
except Exception:
ex_type, ex, tb = sys.exc_info()
fname = os.path.split(tb.tb_frame.f_code.co_filename)[1]
lineno = tb.tb_lineno
logger.error("Exception {0} {1} in {2}, line {3} while processing job, case postprocessing failed".format(ex_type, ex, fname, lineno))
@property
def _suricata_logfiles(self):
evefiles = sorted(glob.glob("/var/log/suricata/eve-*.json"), key=os.path.getmtime, reverse=True)
to_read = []
start = arrow.get(self.starttime)
end = arrow.get(self.endtime)
for evefile in evefiles:
evefiletime = arrow.get(evefile.split("-")[1].split(".")[0], "YYYYMMDDHHmmss")
if evefiletime < start:
to_read.insert(0, evefile)
break
else:
to_read.insert(0, evefile)
return to_read
def present_vnc(self):
lport = 6800 + (int(self.victim_params["vnc"]["port"]) - 5900)
dport = self.victim_params["vnc"]["port"]
self.vncthread = multiprocessing.Process(target=vncsocket, args=("127.0.0.1", lport, dport))
self.vncthread.start()
logger.info("Started websockify server on {} -> {}".format(lport, dport))
def remove_vnc(self):
if self.vncthread and isinstance(self.vncthread, multiprocessing.Process):
self.vncthread.terminate()
logger.info("Stopped websockify server")
def vncsocket(host, lport, dport):
logger.debug("Spinning up websocket process...")
server = websockify.WebSocketProxy(**{"target_host": host, "target_port": dport, "listen_port": lport})
server.start_server()
def get_screen_image(dom, lv_conn):
s = lv_conn.newStream()
# cause libvirt to take the screenshot
dom.screenshot(s, 0)
# copy the data into a buffer
buf = BytesIO()
s.recvAll(sc_writer, buf)
s.finish()
# write the buffer to file
buf.seek(0)
i = Image.open(buf)
return i
def sc_writer(stream, data, b):
b.write(data)
class StopCaptureException(RuntimeError):
def __init__(self, message, errors):
super(RuntimeError, self).__init__(message)
self.errors = errors
def __init__(self, message):
super(RuntimeError, self).__init__(message)
| [
"logging.getLogger",
"victimfiles.VictimFiles",
"db_calls.insert_http",
"multiprocessing.Process",
"io.BytesIO",
"time.sleep",
"sys.exc_info",
"case_postprocess.Postprocessor",
"websockify.WebSocketProxy",
"pyvnc.Connector",
"os.remove",
"os.path.exists",
"os.listdir",
"db_calls.insert_tls... | [((481, 516), 'logging.getLogger', 'logging.getLogger', (['"""antfarm.worker"""'], {}), "('antfarm.worker')\n", (498, 516), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((20219, 20317), 'websockify.WebSocketProxy', 'websockify.WebSocketProxy', ([], {}), "(**{'target_host': host, 'target_port': dport,\n 'listen_port': lport})\n", (20244, 20317), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((20537, 20546), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (20544, 20546), False, 'from io import StringIO, BytesIO\n'), ((20647, 20662), 'PIL.Image.open', 'Image.open', (['buf'], {}), '(buf)\n', (20657, 20662), False, 'from PIL import Image\n'), ((1730, 1767), 'os.path.join', 'os.path.join', (['self.rootdir', 'filespath'], {}), '(self.rootdir, filespath)\n', (1742, 1767), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((2050, 2091), 'os.path.join', 'os.path.join', (['self.rundir', '"""capture.pcap"""'], {}), "(self.rundir, 'capture.pcap')\n", (2062, 2091), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((2472, 2551), 'os.path.join', 'os.path.join', (['self.filespath', "self.hashes['sha256'][0:2]", "self.hashes['sha256']"], {}), "(self.filespath, self.hashes['sha256'][0:2], self.hashes['sha256'])\n", (2484, 2551), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((4082, 4123), 'os.path.join', 'os.path.join', (['self.rootdir', 'outdir', 'short'], {}), '(self.rootdir, outdir, short)\n', (4094, 4123), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((4203, 4244), 'os.path.join', 'os.path.join', (['bdir', "self.hashes['sha256']"], {}), "(bdir, self.hashes['sha256'])\n", (4215, 4244), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((4413, 4442), 'os.path.join', 'os.path.join', (['fdir', 'self.uuid'], {}), '(fdir, self.uuid)\n', (4425, 4442), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((4659, 4737), 'os.path.join', 'os.path.join', (['self.rootdir', '"""www"""', '"""public"""', '"""images"""', '"""cases"""', 'self.uuid[0:2]'], {}), "(self.rootdir, 'www', 'public', 'images', 'cases', self.uuid[0:2])\n", (4671, 4737), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((4897, 4930), 'os.path.join', 'os.path.join', (['imgshort', 'self.uuid'], {}), '(imgshort, self.uuid)\n', (4909, 4930), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((5147, 5244), 'logging.Formatter', 'logging.Formatter', ([], {'fmt': '"""[%(asctime)s] %(levelname)s\t%(message)s"""', 'datefmt': '"""%Y%m%d %H:%M:%S"""'}), "(fmt='[%(asctime)s] %(levelname)s\\t%(message)s', datefmt=\n '%Y%m%d %H:%M:%S')\n", (5164, 5244), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((6066, 6111), 'yarahandler.testyara', 'yarahandler.testyara', (['self.conf', 'self.rawfile'], {}), '(self.conf, self.rawfile)\n', (6086, 6111), False, 'import tempfile, evtx_dates, db_calls, psycopg2, psycopg2.extras, sys, pcap_parser, yarahandler, magic, case_postprocess\n'), ((14106, 14150), 'shutil.copy', 'shutil.copy', (['self.rawfile', 'self.downloadfile'], {}), '(self.rawfile, self.downloadfile)\n', (14117, 14150), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((15604, 15629), 'arrow.get', 'arrow.get', (['self.starttime'], {}), '(self.starttime)\n', (15613, 15629), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((15646, 15669), 'arrow.get', 'arrow.get', (['self.endtime'], {}), '(self.endtime)\n', (15655, 15669), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((19140, 19165), 'arrow.get', 'arrow.get', (['self.starttime'], {}), '(self.starttime)\n', (19149, 19165), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((19180, 19203), 'arrow.get', 'arrow.get', (['self.endtime'], {}), '(self.endtime)\n', (19189, 19203), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((19722, 19797), 'multiprocessing.Process', 'multiprocessing.Process', ([], {'target': 'vncsocket', 'args': "('127.0.0.1', lport, dport)"}), "(target=vncsocket, args=('127.0.0.1', lport, dport))\n", (19745, 19797), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((1386, 1400), 'arrow.utcnow', 'arrow.utcnow', ([], {}), '()\n', (1398, 1400), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((4139, 4159), 'os.path.exists', 'os.path.exists', (['bdir'], {}), '(bdir)\n', (4153, 4159), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((4173, 4187), 'os.mkdir', 'os.mkdir', (['bdir'], {}), '(bdir)\n', (4181, 4187), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((4260, 4280), 'os.path.exists', 'os.path.exists', (['fdir'], {}), '(fdir)\n', (4274, 4280), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((4294, 4308), 'os.mkdir', 'os.mkdir', (['fdir'], {}), '(fdir)\n', (4302, 4308), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((4458, 4480), 'os.path.exists', 'os.path.exists', (['rundir'], {}), '(rundir)\n', (4472, 4480), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((4494, 4510), 'os.mkdir', 'os.mkdir', (['rundir'], {}), '(rundir)\n', (4502, 4510), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((4753, 4777), 'os.path.exists', 'os.path.exists', (['imgshort'], {}), '(imgshort)\n', (4767, 4777), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((4791, 4809), 'os.mkdir', 'os.mkdir', (['imgshort'], {}), '(imgshort)\n', (4799, 4809), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((4946, 4968), 'os.path.exists', 'os.path.exists', (['imgdir'], {}), '(imgdir)\n', (4960, 4968), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((4982, 4998), 'os.mkdir', 'os.mkdir', (['imgdir'], {}), '(imgdir)\n', (4990, 4998), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((5277, 5313), 'os.path.join', 'os.path.join', (['self.rundir', '"""run.log"""'], {}), "(self.rundir, 'run.log')\n", (5289, 5313), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((6210, 6278), 'db_calls.yara_detection', 'db_calls.yara_detection', (['matches', "self.hashes['sha256']", 'self.cursor'], {}), "(matches, self.hashes['sha256'], self.cursor)\n", (6233, 6278), False, 'import tempfile, evtx_dates, db_calls, psycopg2, psycopg2.extras, sys, pcap_parser, yarahandler, magic, case_postprocess\n'), ((7531, 7556), 'arrow.get', 'arrow.get', (['self.starttime'], {}), '(self.starttime)\n', (7540, 7556), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((7575, 7598), 'arrow.get', 'arrow.get', (['self.endtime'], {}), '(self.endtime)\n', (7584, 7598), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((7637, 7674), 'arrow.Arrow.range', 'arrow.Arrow.range', (['"""hour"""', 'start', 'end'], {}), "('hour', start, end)\n", (7654, 7674), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((8988, 9029), 'pcap_parser.conversations', 'pcap_parser.conversations', (['self.pcap_file'], {}), '(self.pcap_file)\n', (9013, 9029), False, 'import tempfile, evtx_dates, db_calls, psycopg2, psycopg2.extras, sys, pcap_parser, yarahandler, magic, case_postprocess\n'), ((9042, 9109), 'db_calls.insert_pcap_streams', 'db_calls.insert_pcap_streams', (['conversations', 'self.uuid', 'self.cursor'], {}), '(conversations, self.uuid, self.cursor)\n', (9070, 9109), False, 'import tempfile, evtx_dates, db_calls, psycopg2, psycopg2.extras, sys, pcap_parser, yarahandler, magic, case_postprocess\n'), ((9659, 9685), 'os.path.exists', 'os.path.exists', (['searchfile'], {}), '(searchfile)\n', (9673, 9685), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((11388, 11514), 'pyvnc.Connector', 'pyvnc.Connector', (['cstr', "self.victim_params['password']", "(self.victim_params['display_x'], self.victim_params['display_y'])"], {}), "(cstr, self.victim_params['password'], (self.victim_params[\n 'display_x'], self.victim_params['display_y']))\n", (11403, 11514), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((15259, 15287), 'os.remove', 'os.remove', (['self.downloadfile'], {}), '(self.downloadfile)\n', (15268, 15287), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((15444, 15494), 'db_calls.timestomped_files', 'db_calls.timestomped_files', (['self.uuid', 'self.cursor'], {}), '(self.uuid, self.cursor)\n', (15470, 15494), False, 'import tempfile, evtx_dates, db_calls, psycopg2, psycopg2.extras, sys, pcap_parser, yarahandler, magic, case_postprocess\n'), ((15774, 15853), 'victimfiles.VictimFiles', 'victimfiles.VictimFiles', (['self.conf', "self.victim_params['diskfile']", '"""/dev/sda2"""'], {}), "(self.conf, self.victim_params['diskfile'], '/dev/sda2')\n", (15797, 15853), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((16269, 16328), 'db_calls.insert_files', 'db_calls.insert_files', (['compileddict', 'self.uuid', 'self.cursor'], {}), '(compileddict, self.uuid, self.cursor)\n', (16290, 16328), False, 'import tempfile, evtx_dates, db_calls, psycopg2, psycopg2.extras, sys, pcap_parser, yarahandler, magic, case_postprocess\n'), ((16851, 16888), 'os.path.join', 'os.path.join', (['self.rundir', '"""eve.json"""'], {}), "(self.rundir, 'eve.json')\n", (16863, 16888), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((18507, 18561), 'case_postprocess.Postprocessor', 'case_postprocess.Postprocessor', (['self.uuid', 'self.cursor'], {}), '(self.uuid, self.cursor)\n', (18537, 18561), False, 'import tempfile, evtx_dates, db_calls, psycopg2, psycopg2.extras, sys, pcap_parser, yarahandler, magic, case_postprocess\n'), ((19006, 19047), 'glob.glob', 'glob.glob', (['"""/var/log/suricata/eve-*.json"""'], {}), "('/var/log/suricata/eve-*.json')\n", (19015, 19047), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((7312, 7338), 'os.path.join', 'os.path.join', (['folder', 'name'], {}), '(folder, name)\n', (7324, 7338), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((7362, 7384), 'os.path.getmtime', 'os.path.getmtime', (['path'], {}), '(path)\n', (7378, 7384), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((7412, 7430), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (7422, 7430), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((7733, 7764), 'os.path.join', 'os.path.join', (['folder', 'pcap_file'], {}), '(folder, pcap_file)\n', (7745, 7764), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((8545, 8581), 'scapy.all.sniff', 'scapy.sniff', ([], {'offline': 'pcap', 'filter': 'fl'}), '(offline=pcap, filter=fl)\n', (8556, 8581), True, 'import scapy.all as scapy\n'), ((9175, 9189), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (9187, 9189), False, 'import tempfile, evtx_dates, db_calls, psycopg2, psycopg2.extras, sys, pcap_parser, yarahandler, magic, case_postprocess\n'), ((11792, 11805), 'time.sleep', 'time.sleep', (['(6)'], {}), '(6)\n', (11802, 11805), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((13163, 13177), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (13175, 13177), False, 'import tempfile, evtx_dates, db_calls, psycopg2, psycopg2.extras, sys, pcap_parser, yarahandler, magic, case_postprocess\n'), ((14932, 14946), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (14944, 14946), False, 'import tempfile, evtx_dates, db_calls, psycopg2, psycopg2.extras, sys, pcap_parser, yarahandler, magic, case_postprocess\n'), ((16398, 16412), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (16410, 16412), False, 'import tempfile, evtx_dates, db_calls, psycopg2, psycopg2.extras, sys, pcap_parser, yarahandler, magic, case_postprocess\n'), ((17852, 17866), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (17864, 17866), False, 'import tempfile, evtx_dates, db_calls, psycopg2, psycopg2.extras, sys, pcap_parser, yarahandler, magic, case_postprocess\n'), ((18215, 18229), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (18227, 18229), False, 'import tempfile, evtx_dates, db_calls, psycopg2, psycopg2.extras, sys, pcap_parser, yarahandler, magic, case_postprocess\n'), ((18649, 18663), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (18661, 18663), False, 'import tempfile, evtx_dates, db_calls, psycopg2, psycopg2.extras, sys, pcap_parser, yarahandler, magic, case_postprocess\n'), ((5633, 5658), 'logging.getLogger', 'logging.getLogger', (['module'], {}), '(module)\n', (5650, 5658), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((8649, 8671), 'arrow.get', 'arrow.get', (['packet.time'], {}), '(packet.time)\n', (8658, 8671), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((9210, 9255), 'os.path.split', 'os.path.split', (['tb.tb_frame.f_code.co_filename'], {}), '(tb.tb_frame.f_code.co_filename)\n', (9223, 9255), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((11592, 11603), 'arrow.now', 'arrow.now', ([], {}), '()\n', (11601, 11603), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((13198, 13243), 'os.path.split', 'os.path.split', (['tb.tb_frame.f_code.co_filename'], {}), '(tb.tb_frame.f_code.co_filename)\n', (13211, 13243), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((14648, 14661), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (14658, 14661), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((14967, 15012), 'os.path.split', 'os.path.split', (['tb.tb_frame.f_code.co_filename'], {}), '(tb.tb_frame.f_code.co_filename)\n', (14980, 15012), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((16433, 16478), 'os.path.split', 'os.path.split', (['tb.tb_frame.f_code.co_filename'], {}), '(tb.tb_frame.f_code.co_filename)\n', (16446, 16478), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((17887, 17932), 'os.path.split', 'os.path.split', (['tb.tb_frame.f_code.co_filename'], {}), '(tb.tb_frame.f_code.co_filename)\n', (17900, 17932), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((18250, 18295), 'os.path.split', 'os.path.split', (['tb.tb_frame.f_code.co_filename'], {}), '(tb.tb_frame.f_code.co_filename)\n', (18263, 18295), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((18684, 18729), 'os.path.split', 'os.path.split', (['tb.tb_frame.f_code.co_filename'], {}), '(tb.tb_frame.f_code.co_filename)\n', (18697, 18729), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((7794, 7814), 'os.path.getmtime', 'os.path.getmtime', (['pf'], {}), '(pf)\n', (7810, 7814), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((8752, 8801), 'scapy.all.wrpcap', 'scapy.wrpcap', (['self.pcap_file', 'packet'], {'append': '(True)'}), '(self.pcap_file, packet, append=True)\n', (8764, 8801), True, 'import scapy.all as scapy\n'), ((9879, 9904), 'arrow.get', 'arrow.get', (["d['timestamp']"], {}), "(d['timestamp'])\n", (9888, 9904), False, 'import logging, os, configparser, libvirt, json, arrow, pyvnc, shutil, time, victimfiles, glob, websockify, multiprocessing, signal\n'), ((17275, 17334), 'db_calls.insert_dns', 'db_calls.insert_dns', (['events[evtype]', 'self.uuid', 'self.cursor'], {}), '(events[evtype], self.uuid, self.cursor)\n', (17294, 17334), False, 'import tempfile, evtx_dates, db_calls, psycopg2, psycopg2.extras, sys, pcap_parser, yarahandler, magic, case_postprocess\n'), ((17400, 17460), 'db_calls.insert_http', 'db_calls.insert_http', (['events[evtype]', 'self.uuid', 'self.cursor'], {}), '(events[evtype], self.uuid, self.cursor)\n', (17420, 17460), False, 'import tempfile, evtx_dates, db_calls, psycopg2, psycopg2.extras, sys, pcap_parser, yarahandler, magic, case_postprocess\n'), ((17527, 17588), 'db_calls.insert_alert', 'db_calls.insert_alert', (['events[evtype]', 'self.uuid', 'self.cursor'], {}), '(events[evtype], self.uuid, self.cursor)\n', (17548, 17588), False, 'import tempfile, evtx_dates, db_calls, psycopg2, psycopg2.extras, sys, pcap_parser, yarahandler, magic, case_postprocess\n'), ((17653, 17712), 'db_calls.insert_tls', 'db_calls.insert_tls', (['events[evtype]', 'self.uuid', 'self.cursor'], {}), '(events[evtype], self.uuid, self.cursor)\n', (17672, 17712), False, 'import tempfile, evtx_dates, db_calls, psycopg2, psycopg2.extras, sys, pcap_parser, yarahandler, magic, case_postprocess\n')] |
import json
class TestListRepo:
def test_invalid(self, host):
result = host.run('stack list repo test')
assert result.rc == 255
assert result.stderr.startswith('error - ')
def test_args(self, host, add_repo):
# Add a second repo so we can make sure it is skipped
add_repo('test2', 'test2url')
# Run list repo with just the test box
result = host.run('stack list repo test output-format=json')
assert result.rc == 0
# Make sure we got data only for the test box
repo_data = json.loads(result.stdout)
assert len(repo_data) == 1
assert repo_data[0]['name'] == 'test'
# now get all of them
# assert both repos are in the list data
result = host.run('stack list repo output-format=json')
repo_data = json.loads(result.stdout)
assert len(repo_data) == 2
assert {'test', 'test2'} == {repo['name'] for repo in repo_data}
# now get all of them, by explicitly asking for them
# assert both repos are in the list data
result = host.run('stack list repo test test2 output-format=json')
new_repo_data = json.loads(result.stdout)
assert len(new_repo_data) == 2
assert {'test', 'test2'} == {repo['name'] for repo in new_repo_data}
def test_removed_not_listed(self, host, add_repo, revert_etc):
# Run list repo with just the test box
result = host.run('stack list repo test output-format=json')
assert result.rc == 0
# Make sure we got data only for the test box
repo_data = json.loads(result.stdout)
assert len(repo_data) == 1
assert repo_data[0]['name'] == 'test'
result = host.run('stack remove repo test')
assert result.rc == 0
# Run list repo again
result = host.run('stack list repo test output-format=json')
assert result.rc == 255
assert result.stderr.startswith('error - ')
def test_expanded_columns(self, host, host_os, add_repo):
# Run list repo with just the test box
result = host.run('stack list repo test expanded=true output-format=json')
assert result.rc == 0
assert json.loads(result.stdout) == [
{
"name": "test",
"alias": "test",
"url": "test_url",
"autorefresh": False,
"assumeyes": False,
"type": "rpm-md",
"is_mirrorlist": False,
"gpgcheck": False,
"gpgkey": None,
"os": host_os,
"pallet name": None
}
]
def test_add_repo_with_pallet(self, host, host_os, add_repo, create_pallet_isos, revert_export_stack_pallets, revert_pallet_hooks, revert_etc):
result = host.run(f'stack add pallet {create_pallet_isos}/minimal-1.0-sles12.x86_64.disk1.iso')
#result = host.run(f'stack add pallet /root/minimal-1.0-sles12.x86_64.disk1.iso')
assert result.rc == 0
result = host.run('stack list pallet minimal output-format=json')
assert result.rc == 0
pallet_data = json.loads(result.stdout)
assert len(pallet_data) == 1
# get pallet id, as well as the -'d name in the correct order
from stack.commands import DatabaseConnection, get_mysql_connection, Command
from stack.argument_processors.pallet import PalletArgProcessor
from operator import attrgetter
p = PalletArgProcessor()
p.db = DatabaseConnection(get_mysql_connection())
minimal_pallet = p.get_pallets(args=['minimal'], params=pallet_data[0])[0]
pallet_name = '-'.join(attrgetter('name', 'version', 'rel', 'os', 'arch')(minimal_pallet))
# now attach the test repo to the pallet
result = host.run(f'stack set repo test pallet={minimal_pallet.id}')
assert result.rc == 0
# now verify it is attached to that pallet
result = host.run('stack list repo test expanded=true output-format=json')
assert result.rc == 0
assert json.loads(result.stdout) == [
{
"name": "test",
"alias": "test",
"url": "test_url",
"autorefresh": False,
"assumeyes": False,
"type": "rpm-md",
"is_mirrorlist": False,
"gpgcheck": False,
"gpgkey": None,
"os": host_os,
"pallet name": pallet_name
}
]
# now verify that removing that pallet removes the repo as well
result = host.run('stack remove pallet minimal')
assert result.rc == 0
result = host.run('stack list repo')
assert result.rc == 0
assert result.stdout == ''
| [
"operator.attrgetter",
"stack.commands.get_mysql_connection",
"json.loads",
"stack.argument_processors.pallet.PalletArgProcessor"
] | [((499, 524), 'json.loads', 'json.loads', (['result.stdout'], {}), '(result.stdout)\n', (509, 524), False, 'import json\n'), ((734, 759), 'json.loads', 'json.loads', (['result.stdout'], {}), '(result.stdout)\n', (744, 759), False, 'import json\n'), ((1042, 1067), 'json.loads', 'json.loads', (['result.stdout'], {}), '(result.stdout)\n', (1052, 1067), False, 'import json\n'), ((1428, 1453), 'json.loads', 'json.loads', (['result.stdout'], {}), '(result.stdout)\n', (1438, 1453), False, 'import json\n'), ((2722, 2747), 'json.loads', 'json.loads', (['result.stdout'], {}), '(result.stdout)\n', (2732, 2747), False, 'import json\n'), ((3029, 3049), 'stack.argument_processors.pallet.PalletArgProcessor', 'PalletArgProcessor', ([], {}), '()\n', (3047, 3049), False, 'from stack.argument_processors.pallet import PalletArgProcessor\n'), ((1965, 1990), 'json.loads', 'json.loads', (['result.stdout'], {}), '(result.stdout)\n', (1975, 1990), False, 'import json\n'), ((3078, 3100), 'stack.commands.get_mysql_connection', 'get_mysql_connection', ([], {}), '()\n', (3098, 3100), False, 'from stack.commands import DatabaseConnection, get_mysql_connection, Command\n'), ((3567, 3592), 'json.loads', 'json.loads', (['result.stdout'], {}), '(result.stdout)\n', (3577, 3592), False, 'import json\n'), ((3204, 3254), 'operator.attrgetter', 'attrgetter', (['"""name"""', '"""version"""', '"""rel"""', '"""os"""', '"""arch"""'], {}), "('name', 'version', 'rel', 'os', 'arch')\n", (3214, 3254), False, 'from operator import attrgetter\n')] |
import matplotlib.pyplot as plt
import numpy as np
def plot_chains(chain, fileout=None, tracers=0, labels=None, delay=0, ymax=200000, thin=100, num_xticks=7, truths=None):
if chain.ndim < 3:
print("You must include a multiple chains")
return
n_chains, length, n_var = chain.shape
print(n_chains, length, n_var)
if (labels is not None) and (len(labels) != n_var):
print("You must provide the correct number of variable labels.")
return
if (truths is not None) and (len(truths) != n_var):
print("You must provide the correct number of truths.")
return
fig, ax = plt.subplots(int(n_var/2) + n_var%2, 2, figsize=(8, 0.8*n_var))
plt.subplots_adjust(left=0.09, bottom=0.07, right=0.96, top=0.96, hspace=0)
color = np.empty(n_chains, dtype=str)
color[:] = 'k'
alpha = 0.01 * np.ones(n_chains)
zorder = np.ones(n_chains)
if tracers > 0:
idx = np.random.choice(n_chains, tracers, replace=False)
color[idx] = 'r'
alpha[idx] = 1.0
zorder[idx] = 2.0
for i in range(n_var):
ix = int(i/2)
iy = i%2
for j in range(n_chains):
xvals = (np.arange(length)*thin - delay) / 1000.0
ax[ix,iy].plot(xvals, chain[j,:,i], color=color[j], alpha=alpha[j], rasterized=True, zorder=zorder[j])
if ymax is None: ymax = (length*thin-delay)
ax[ix,iy].set_xlim(-delay/1000.0, ymax/1000.0)
ax[ix,iy].set_xticks(np.linspace(-delay/1000.0,ymax/1000.0,num_xticks))
ax[ix,iy].set_xticklabels([])
# Add y-axis labels if provided by use
if labels is not None: ax[ix,iy].set_ylabel(labels[i])
if delay != 0: ax[ix,iy].axvline(0, color='k', linestyle='dashed', linewidth=2.0, zorder=9)
if truths is not None: ax[ix,iy].axhline(truths[i], color='C0', linestyle='dashed', linewidth=2.0, zorder=10)
# plt.tight_layout()
ax[-1,0].set_xticklabels(np.linspace(-delay/1000.0,ymax/1000.0,num_xticks).astype('i8').astype('U'))
ax[-1,1].set_xticklabels(np.linspace(-delay/1000.0,ymax/1000.0,num_xticks).astype('i8').astype('U'))
ax[-1,0].set_xlabel(r'Steps ($\times$1000)')
ax[-1,1].set_xlabel(r'Steps ($\times$1000)')
if fileout is None:
plt.show()
else:
plt.savefig(fileout, rasterized=True)
return
# from dart_board import plotting
# import numpy as np
# import pickle
# chains = pickle.load(open("../data/HMXB_chain.obj", "rb"))
# plotting.plot_chains(chains)
| [
"matplotlib.pyplot.savefig",
"numpy.ones",
"numpy.arange",
"numpy.random.choice",
"numpy.linspace",
"numpy.empty",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.show"
] | [((708, 783), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'left': '(0.09)', 'bottom': '(0.07)', 'right': '(0.96)', 'top': '(0.96)', 'hspace': '(0)'}), '(left=0.09, bottom=0.07, right=0.96, top=0.96, hspace=0)\n', (727, 783), True, 'import matplotlib.pyplot as plt\n'), ((798, 827), 'numpy.empty', 'np.empty', (['n_chains'], {'dtype': 'str'}), '(n_chains, dtype=str)\n', (806, 827), True, 'import numpy as np\n'), ((897, 914), 'numpy.ones', 'np.ones', (['n_chains'], {}), '(n_chains)\n', (904, 914), True, 'import numpy as np\n'), ((866, 883), 'numpy.ones', 'np.ones', (['n_chains'], {}), '(n_chains)\n', (873, 883), True, 'import numpy as np\n'), ((949, 999), 'numpy.random.choice', 'np.random.choice', (['n_chains', 'tracers'], {'replace': '(False)'}), '(n_chains, tracers, replace=False)\n', (965, 999), True, 'import numpy as np\n'), ((2285, 2295), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2293, 2295), True, 'import matplotlib.pyplot as plt\n'), ((2314, 2351), 'matplotlib.pyplot.savefig', 'plt.savefig', (['fileout'], {'rasterized': '(True)'}), '(fileout, rasterized=True)\n', (2325, 2351), True, 'import matplotlib.pyplot as plt\n'), ((1494, 1549), 'numpy.linspace', 'np.linspace', (['(-delay / 1000.0)', '(ymax / 1000.0)', 'num_xticks'], {}), '(-delay / 1000.0, ymax / 1000.0, num_xticks)\n', (1505, 1549), True, 'import numpy as np\n'), ((1200, 1217), 'numpy.arange', 'np.arange', (['length'], {}), '(length)\n', (1209, 1217), True, 'import numpy as np\n'), ((1972, 2027), 'numpy.linspace', 'np.linspace', (['(-delay / 1000.0)', '(ymax / 1000.0)', 'num_xticks'], {}), '(-delay / 1000.0, ymax / 1000.0, num_xticks)\n', (1983, 2027), True, 'import numpy as np\n'), ((2077, 2132), 'numpy.linspace', 'np.linspace', (['(-delay / 1000.0)', '(ymax / 1000.0)', 'num_xticks'], {}), '(-delay / 1000.0, ymax / 1000.0, num_xticks)\n', (2088, 2132), True, 'import numpy as np\n')] |
##
## Evaluation Script
##
import numpy as np
import time
from sample_model import Model
from data_loader import data_loader
from generator import Generator
def evaluate(label_indices = {'brick': 0, 'ball': 1, 'cylinder': 2},
channel_means = np.array([147.12697, 160.21092, 167.70029]),
data_path = '../data',
minibatch_size = 32,
num_batches_to_test = 10,
checkpoint_dir = 'tf_data/sample_model'):
print("1. Loading data")
data = data_loader(label_indices = label_indices,
channel_means = channel_means,
train_test_split = 0.5,
data_path = data_path)
print("2. Instantiating the model")
M = Model(mode = 'test')
#Evaluate on test images:
GT = Generator(data.test.X, data.test.y, minibatch_size = minibatch_size)
num_correct = 0
num_total = 0
print("3. Evaluating on test images")
for i in range(num_batches_to_test):
GT.generate()
yhat = M.predict(X = GT.X, checkpoint_dir = checkpoint_dir)
correct_predictions = (np.argmax(yhat, axis = 1) == np.argmax(GT.y, axis = 1))
num_correct += np.sum(correct_predictions)
num_total += len(correct_predictions)
accuracy = round(num_correct/num_total,4)
return accuracy
def calculate_score(accuracy):
score = 0
if accuracy >= 0.92:
score = 10
elif accuracy >= 0.9:
score = 9
elif accuracy >= 0.85:
score = 8
elif accuracy >= 0.8:
score = 7
elif accuracy >= 0.75:
score = 6
elif accuracy >= 0.70:
score = 5
else:
score = 4
return score
if __name__ == '__main__':
program_start = time.time()
accuracy = evaluate()
score = calculate_score(accuracy)
program_end = time.time()
total_time = round(program_end - program_start,2)
print()
print("Execution time (seconds) = ", total_time)
print('Accuracy = ' + str(accuracy))
print("Score = ", score)
print()
| [
"generator.Generator",
"sample_model.Model",
"data_loader.data_loader",
"numpy.argmax",
"numpy.array",
"numpy.sum",
"time.time"
] | [((258, 301), 'numpy.array', 'np.array', (['[147.12697, 160.21092, 167.70029]'], {}), '([147.12697, 160.21092, 167.70029])\n', (266, 301), True, 'import numpy as np\n'), ((513, 629), 'data_loader.data_loader', 'data_loader', ([], {'label_indices': 'label_indices', 'channel_means': 'channel_means', 'train_test_split': '(0.5)', 'data_path': 'data_path'}), '(label_indices=label_indices, channel_means=channel_means,\n train_test_split=0.5, data_path=data_path)\n', (524, 629), False, 'from data_loader import data_loader\n'), ((745, 763), 'sample_model.Model', 'Model', ([], {'mode': '"""test"""'}), "(mode='test')\n", (750, 763), False, 'from sample_model import Model\n'), ((806, 872), 'generator.Generator', 'Generator', (['data.test.X', 'data.test.y'], {'minibatch_size': 'minibatch_size'}), '(data.test.X, data.test.y, minibatch_size=minibatch_size)\n', (815, 872), False, 'from generator import Generator\n'), ((1755, 1766), 'time.time', 'time.time', ([], {}), '()\n', (1764, 1766), False, 'import time\n'), ((1849, 1860), 'time.time', 'time.time', ([], {}), '()\n', (1858, 1860), False, 'import time\n'), ((1206, 1233), 'numpy.sum', 'np.sum', (['correct_predictions'], {}), '(correct_predictions)\n', (1212, 1233), True, 'import numpy as np\n'), ((1127, 1150), 'numpy.argmax', 'np.argmax', (['yhat'], {'axis': '(1)'}), '(yhat, axis=1)\n', (1136, 1150), True, 'import numpy as np\n'), ((1156, 1179), 'numpy.argmax', 'np.argmax', (['GT.y'], {'axis': '(1)'}), '(GT.y, axis=1)\n', (1165, 1179), True, 'import numpy as np\n')] |
# -*- coding=utf-8 -*-
"""
# Copyright (c) 2020 PaddlePaddle 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.
"""
import math
import argparse
import numpy as np
import paddle.fluid as fluid
from utils import tdm_sampler_prepare, tdm_child_prepare, trace_var
from train_network import DnnLayerClassifierNet, InputTransNet
class TdmInferNet(object):
def __init__(self, args):
self.input_embed_size = args.query_emb_size
self.node_embed_size = args.node_emb_size
self.label_nums = 2 # label为正负两类
self.node_nums = args.node_nums
self.max_layers = args.layer_size
self.batch_size = args.batch_size
self.topK = args.topK # 最终召回多少个item
self.child_nums = args.child_nums # 若树为二叉树,则child_nums=2
self.layer_list = self.get_layer_list(args)
self.first_layer_idx = 0
self.first_layer_node = self.create_first_layer(args)
self.layer_classifier = DnnLayerClassifierNet(args)
self.input_trans_net = InputTransNet(args)
def input_data(self):
input_emb = fluid.data(
name="input_emb",
shape=[None, self.input_embed_size],
dtype="float32", )
# first_layer 与 first_layer_mask 对应着infer起始层的节点
first_layer = fluid.data(
name="first_layer_node",
shape=[None, 1],
dtype="int64",
lod_level=1, )
first_layer_mask = fluid.data(
name="first_layer_node_mask",
shape=[None, 1],
dtype="int64",
lod_level=1, )
inputs = [input_emb] + [first_layer] + [first_layer_mask]
return inputs
def get_layer_list(self, args):
"""get layer list from layer_list.txt"""
layer_list = []
with open(args.tree_layer_init_path, 'r') as fin:
for line in fin.readlines():
l = []
layer = (line.split('\n'))[0].split(',')
for node in layer:
if node:
l.append(node)
layer_list.append(l)
return layer_list
def create_first_layer(self, args):
"""decide which layer to start infer"""
first_layer_id = 0
for idx, layer_node in enumerate(args.layer_node_num_list):
if layer_node >= self.topK:
first_layer_id = idx
break
first_layer_node = self.layer_list[first_layer_id]
self.first_layer_idx = first_layer_id
return first_layer_node
def infer_net(self, inputs):
"""
infer的主要流程
infer的基本逻辑是:从上层开始(具体层idx由树结构及TopK值决定)
1、依次通过每一层分类器,得到当前层输入的指定节点的prob
2、根据prob值大小,取topK的节点,取这些节点的孩子节点作为下一层的输入
3、循环1、2步骤,遍历完所有层,得到每一层筛选结果的集合
4、将筛选结果集合中的叶子节点,拿出来再做一次topK,得到最终的召回输出
"""
input_emb = inputs[0]
current_layer_node = inputs[1]
current_layer_child_mask = inputs[2]
node_score = []
node_list = []
input_trans_emb = self.input_trans_net.input_fc_infer(input_emb)
for layer_idx in range(self.first_layer_idx, self.max_layers):
# 确定当前层的需要计算的节点数
if layer_idx == self.first_layer_idx:
current_layer_node_num = len(self.first_layer_node)
else:
current_layer_node_num = current_layer_node.shape[1] * \
current_layer_node.shape[2]
current_layer_node = fluid.layers.reshape(
current_layer_node, [-1, current_layer_node_num])
current_layer_child_mask = fluid.layers.reshape(
current_layer_child_mask, [-1, current_layer_node_num])
node_emb = fluid.embedding(
input=current_layer_node,
size=[self.node_nums, self.node_embed_size],
param_attr=fluid.ParamAttr(name="TDM_Tree_Emb"))
input_fc_out = self.input_trans_net.layer_fc_infer(input_trans_emb,
layer_idx)
# 过每一层的分类器
layer_classifier_res = self.layer_classifier.classifier_layer_infer(
input_fc_out, node_emb, layer_idx)
# 过最终的判别分类器
tdm_fc = fluid.layers.fc(
input=layer_classifier_res,
size=self.label_nums,
act=None,
num_flatten_dims=2,
param_attr=fluid.ParamAttr(name="tdm.cls_fc.weight"),
bias_attr=fluid.ParamAttr(name="tdm.cls_fc.bias"))
prob = fluid.layers.softmax(tdm_fc)
positive_prob = fluid.layers.slice(
prob, axes=[2], starts=[1], ends=[2])
prob_re = fluid.layers.reshape(positive_prob,
[-1, current_layer_node_num])
# 过滤掉padding产生的无效节点(node_id=0)
node_zero_mask = fluid.layers.cast(current_layer_node, 'bool')
node_zero_mask = fluid.layers.cast(node_zero_mask, 'float')
prob_re = prob_re * node_zero_mask
# 在当前层的分类结果中取topK,并将对应的score及node_id保存下来
k = self.topK
if current_layer_node_num < self.topK:
k = current_layer_node_num
_, topk_i = fluid.layers.topk(prob_re, k)
# index_sample op根据下标索引tensor对应位置的值
# 若paddle版本>2.0,调用方式为paddle.index_sample
top_node = fluid.contrib.layers.index_sample(current_layer_node,
topk_i)
prob_re_mask = prob_re * current_layer_child_mask # 过滤掉非叶子节点
topk_value = fluid.contrib.layers.index_sample(prob_re_mask, topk_i)
node_score.append(topk_value)
node_list.append(top_node)
# 取当前层topK结果的孩子节点,作为下一层的输入
if layer_idx < self.max_layers - 1:
# tdm_child op 根据输入返回其 child 及 child_mask
# 若child是叶子节点,则child_mask=1,否则为0
current_layer_node, current_layer_child_mask = \
fluid.contrib.layers.tdm_child(x=top_node,
node_nums=self.node_nums,
child_nums=self.child_nums,
param_attr=fluid.ParamAttr(
name="TDM_Tree_Info"),
dtype='int64')
total_node_score = fluid.layers.concat(node_score, axis=1)
total_node = fluid.layers.concat(node_list, axis=1)
# 考虑到树可能是不平衡的,计算所有层的叶子节点的topK
res_score, res_i = fluid.layers.topk(total_node_score, self.topK)
res_layer_node = fluid.contrib.layers.index_sample(total_node, res_i)
res_node = fluid.layers.reshape(res_layer_node, [-1, self.topK, 1])
# 利用Tree_info信息,将node_id转换为item_id
tree_info = fluid.default_main_program().global_block().var(
"TDM_Tree_Info")
res_node_emb = fluid.layers.gather_nd(tree_info, res_node)
res_item = fluid.layers.slice(
res_node_emb, axes=[2], starts=[0], ends=[1])
res_item_re = fluid.layers.reshape(res_item, [-1, self.topK])
return res_item_re
| [
"paddle.fluid.layers.concat",
"paddle.fluid.layers.topk",
"paddle.fluid.ParamAttr",
"paddle.fluid.data",
"paddle.fluid.layers.softmax",
"train_network.DnnLayerClassifierNet",
"paddle.fluid.contrib.layers.index_sample",
"paddle.fluid.layers.slice",
"paddle.fluid.layers.cast",
"paddle.fluid.default_... | [((1469, 1496), 'train_network.DnnLayerClassifierNet', 'DnnLayerClassifierNet', (['args'], {}), '(args)\n', (1490, 1496), False, 'from train_network import DnnLayerClassifierNet, InputTransNet\n'), ((1528, 1547), 'train_network.InputTransNet', 'InputTransNet', (['args'], {}), '(args)\n', (1541, 1547), False, 'from train_network import DnnLayerClassifierNet, InputTransNet\n'), ((1595, 1682), 'paddle.fluid.data', 'fluid.data', ([], {'name': '"""input_emb"""', 'shape': '[None, self.input_embed_size]', 'dtype': '"""float32"""'}), "(name='input_emb', shape=[None, self.input_embed_size], dtype=\n 'float32')\n", (1605, 1682), True, 'import paddle.fluid as fluid\n'), ((1796, 1881), 'paddle.fluid.data', 'fluid.data', ([], {'name': '"""first_layer_node"""', 'shape': '[None, 1]', 'dtype': '"""int64"""', 'lod_level': '(1)'}), "(name='first_layer_node', shape=[None, 1], dtype='int64', lod_level=1\n )\n", (1806, 1881), True, 'import paddle.fluid as fluid\n'), ((1956, 2045), 'paddle.fluid.data', 'fluid.data', ([], {'name': '"""first_layer_node_mask"""', 'shape': '[None, 1]', 'dtype': '"""int64"""', 'lod_level': '(1)'}), "(name='first_layer_node_mask', shape=[None, 1], dtype='int64',\n lod_level=1)\n", (1966, 2045), True, 'import paddle.fluid as fluid\n'), ((7022, 7061), 'paddle.fluid.layers.concat', 'fluid.layers.concat', (['node_score'], {'axis': '(1)'}), '(node_score, axis=1)\n', (7041, 7061), True, 'import paddle.fluid as fluid\n'), ((7083, 7121), 'paddle.fluid.layers.concat', 'fluid.layers.concat', (['node_list'], {'axis': '(1)'}), '(node_list, axis=1)\n', (7102, 7121), True, 'import paddle.fluid as fluid\n'), ((7188, 7234), 'paddle.fluid.layers.topk', 'fluid.layers.topk', (['total_node_score', 'self.topK'], {}), '(total_node_score, self.topK)\n', (7205, 7234), True, 'import paddle.fluid as fluid\n'), ((7260, 7312), 'paddle.fluid.contrib.layers.index_sample', 'fluid.contrib.layers.index_sample', (['total_node', 'res_i'], {}), '(total_node, res_i)\n', (7293, 7312), True, 'import paddle.fluid as fluid\n'), ((7332, 7388), 'paddle.fluid.layers.reshape', 'fluid.layers.reshape', (['res_layer_node', '[-1, self.topK, 1]'], {}), '(res_layer_node, [-1, self.topK, 1])\n', (7352, 7388), True, 'import paddle.fluid as fluid\n'), ((7554, 7597), 'paddle.fluid.layers.gather_nd', 'fluid.layers.gather_nd', (['tree_info', 'res_node'], {}), '(tree_info, res_node)\n', (7576, 7597), True, 'import paddle.fluid as fluid\n'), ((7618, 7682), 'paddle.fluid.layers.slice', 'fluid.layers.slice', (['res_node_emb'], {'axes': '[2]', 'starts': '[0]', 'ends': '[1]'}), '(res_node_emb, axes=[2], starts=[0], ends=[1])\n', (7636, 7682), True, 'import paddle.fluid as fluid\n'), ((7718, 7765), 'paddle.fluid.layers.reshape', 'fluid.layers.reshape', (['res_item', '[-1, self.topK]'], {}), '(res_item, [-1, self.topK])\n', (7738, 7765), True, 'import paddle.fluid as fluid\n'), ((3979, 4049), 'paddle.fluid.layers.reshape', 'fluid.layers.reshape', (['current_layer_node', '[-1, current_layer_node_num]'], {}), '(current_layer_node, [-1, current_layer_node_num])\n', (3999, 4049), True, 'import paddle.fluid as fluid\n'), ((4106, 4182), 'paddle.fluid.layers.reshape', 'fluid.layers.reshape', (['current_layer_child_mask', '[-1, current_layer_node_num]'], {}), '(current_layer_child_mask, [-1, current_layer_node_num])\n', (4126, 4182), True, 'import paddle.fluid as fluid\n'), ((5084, 5112), 'paddle.fluid.layers.softmax', 'fluid.layers.softmax', (['tdm_fc'], {}), '(tdm_fc)\n', (5104, 5112), True, 'import paddle.fluid as fluid\n'), ((5141, 5197), 'paddle.fluid.layers.slice', 'fluid.layers.slice', (['prob'], {'axes': '[2]', 'starts': '[1]', 'ends': '[2]'}), '(prob, axes=[2], starts=[1], ends=[2])\n', (5159, 5197), True, 'import paddle.fluid as fluid\n'), ((5237, 5302), 'paddle.fluid.layers.reshape', 'fluid.layers.reshape', (['positive_prob', '[-1, current_layer_node_num]'], {}), '(positive_prob, [-1, current_layer_node_num])\n', (5257, 5302), True, 'import paddle.fluid as fluid\n'), ((5419, 5464), 'paddle.fluid.layers.cast', 'fluid.layers.cast', (['current_layer_node', '"""bool"""'], {}), "(current_layer_node, 'bool')\n", (5436, 5464), True, 'import paddle.fluid as fluid\n'), ((5494, 5536), 'paddle.fluid.layers.cast', 'fluid.layers.cast', (['node_zero_mask', '"""float"""'], {}), "(node_zero_mask, 'float')\n", (5511, 5536), True, 'import paddle.fluid as fluid\n'), ((5782, 5811), 'paddle.fluid.layers.topk', 'fluid.layers.topk', (['prob_re', 'k'], {}), '(prob_re, k)\n', (5799, 5811), True, 'import paddle.fluid as fluid\n'), ((5937, 5998), 'paddle.fluid.contrib.layers.index_sample', 'fluid.contrib.layers.index_sample', (['current_layer_node', 'topk_i'], {}), '(current_layer_node, topk_i)\n', (5970, 5998), True, 'import paddle.fluid as fluid\n'), ((6155, 6210), 'paddle.fluid.contrib.layers.index_sample', 'fluid.contrib.layers.index_sample', (['prob_re_mask', 'topk_i'], {}), '(prob_re_mask, topk_i)\n', (6188, 6210), True, 'import paddle.fluid as fluid\n'), ((4371, 4407), 'paddle.fluid.ParamAttr', 'fluid.ParamAttr', ([], {'name': '"""TDM_Tree_Emb"""'}), "(name='TDM_Tree_Emb')\n", (4386, 4407), True, 'import paddle.fluid as fluid\n'), ((4954, 4995), 'paddle.fluid.ParamAttr', 'fluid.ParamAttr', ([], {'name': '"""tdm.cls_fc.weight"""'}), "(name='tdm.cls_fc.weight')\n", (4969, 4995), True, 'import paddle.fluid as fluid\n'), ((5023, 5062), 'paddle.fluid.ParamAttr', 'fluid.ParamAttr', ([], {'name': '"""tdm.cls_fc.bias"""'}), "(name='tdm.cls_fc.bias')\n", (5038, 5062), True, 'import paddle.fluid as fluid\n'), ((6833, 6870), 'paddle.fluid.ParamAttr', 'fluid.ParamAttr', ([], {'name': '"""TDM_Tree_Info"""'}), "(name='TDM_Tree_Info')\n", (6848, 6870), True, 'import paddle.fluid as fluid\n'), ((7453, 7481), 'paddle.fluid.default_main_program', 'fluid.default_main_program', ([], {}), '()\n', (7479, 7481), True, 'import paddle.fluid as fluid\n')] |
import requests
from requests import Response
class Client:
@staticmethod
def request(method: str, url: str, **kwargs) -> Response:
"""
Request method
method: method for the new Request object: GET, OPTIONS, HEAD, POST, PUT, PATCH, or DELETE. # noqa
url – URL for the new Request object.
**kwargs:
params – (optional) Dictionary, list of tuples or bytes to send in the query string for the Request. # noqa
json – (optional) A JSON serializable Python object to send in the body of the Request. # noqa
headers – (optional) Dictionary of HTTP Headers to send with the Request.
"""
return requests.request(method, url, **kwargs) | [
"requests.request"
] | [((688, 727), 'requests.request', 'requests.request', (['method', 'url'], {}), '(method, url, **kwargs)\n', (704, 727), False, 'import requests\n')] |
"""server URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
import interface.stats as stats
import interface.routes as route
import interface.pois as pois
urlpatterns = [
url(r'^stats/check/', stats.get_stats_from_id ),
url(r'^stats/update/', stats.post_stats_from_id),
url(r'^route/generate/', route.generate),
url(r'^route/return/', route.return_home),
url(r'^route/rate/', route.rate_route),
url(r'^poi/coords/', pois.get_coords),
url(r'^poi/types/', pois.get_types)
]
| [
"django.conf.urls.url"
] | [((789, 834), 'django.conf.urls.url', 'url', (['"""^stats/check/"""', 'stats.get_stats_from_id'], {}), "('^stats/check/', stats.get_stats_from_id)\n", (792, 834), False, 'from django.conf.urls import url\n'), ((842, 889), 'django.conf.urls.url', 'url', (['"""^stats/update/"""', 'stats.post_stats_from_id'], {}), "('^stats/update/', stats.post_stats_from_id)\n", (845, 889), False, 'from django.conf.urls import url\n'), ((896, 935), 'django.conf.urls.url', 'url', (['"""^route/generate/"""', 'route.generate'], {}), "('^route/generate/', route.generate)\n", (899, 935), False, 'from django.conf.urls import url\n'), ((942, 982), 'django.conf.urls.url', 'url', (['"""^route/return/"""', 'route.return_home'], {}), "('^route/return/', route.return_home)\n", (945, 982), False, 'from django.conf.urls import url\n'), ((989, 1026), 'django.conf.urls.url', 'url', (['"""^route/rate/"""', 'route.rate_route'], {}), "('^route/rate/', route.rate_route)\n", (992, 1026), False, 'from django.conf.urls import url\n'), ((1033, 1069), 'django.conf.urls.url', 'url', (['"""^poi/coords/"""', 'pois.get_coords'], {}), "('^poi/coords/', pois.get_coords)\n", (1036, 1069), False, 'from django.conf.urls import url\n'), ((1076, 1110), 'django.conf.urls.url', 'url', (['"""^poi/types/"""', 'pois.get_types'], {}), "('^poi/types/', pois.get_types)\n", (1079, 1110), False, 'from django.conf.urls import url\n')] |
import json
from ..connection import get_connection
class Metadata:
def __init__(self, database):
self.connection = get_connection(database).connection
# first list is default if nothing is specified (should be extended)
# list is ordered as [edge_name, node1_id, edge_node1_id, edge_node2_id, node2_id2
def get_metadata(self):
self.connection.execute("SELECT metadata FROM _meta")
metadata = json.loads(self.connection.fetchone()[0])
return metadata
def update_metadata(self, data):
self.connection.execute(f"UPDATE _meta SET metadata='{json.dumps(data)}'")
def get_default_join_info(self, node1, node2):
return self.get_metadata()[node1][node2][0]
def get_all_join_info(self, node1, node2):
return self.get_metadata()[node1][node2]
# {
# 'term_dict': {
# 'docs': [['term_doc', 'term_id', 'term_id', 'doc_id', 'doc_id']]
# },
# 'docs': {
# 'term_dict': [['term_doc', 'doc_id', 'doc_id', 'term_id', 'term_id']],
# 'entities': [['entity_doc', 'collection_id', 'doc_id', 'entity', 'entity']],
# 'authors': [['doc_author', 'collection_id', 'doc', 'author', 'author']]
# },
# 'entities': {
# 'docs': [['entity_doc', 'entity', 'entity', 'doc_id', 'collection_id']]
# },
# 'authors': {
# 'docs': [['doc_author', 'author', 'author', 'doc', 'collection_id']]
# }
# }
| [
"json.dumps"
] | [((604, 620), 'json.dumps', 'json.dumps', (['data'], {}), '(data)\n', (614, 620), False, 'import json\n')] |
import requests
from bs4 import BeautifulSoup
def getSummary(link):
#Get page response
response = requests.get(link)
#Parse the pgae
soup = BeautifulSoup(response.content,'html.parser')
#Find first paragraph
summary_p = soup.find('p')
#Get the first text
summary = summary_p.text[:40] + ' ...'
#Return the text
return summary
def crawl_page():
#Available urls
urls = ['https://www.in.gr/world/','https://www.in.gr/politics/','https://www.in.gr/economy/','https://www.in.gr/sports/','https://www.in.gr/culture/','https://www.in.gr/entertainment/','https://www.in.gr/tech/']
#Types of articles
content = ['global','politics','economy','sports','culture','entertainment','technology']
#Adding headers
headers = {
'User-agent':'Mozilla/5.0'
}
#Complete list of article data
data_list = list()
#For given urls
for index,url in enumerate(urls):
#User report
print(f'---- Scrapping from url:{url}')
#Get page response
response = requests.get(url, headers=headers)
#Parse the page
soup = BeautifulSoup(response.content,'html.parser')
#Find the article element
articles = soup.find_all('article')
#Loop through all articles
for article in articles:
#Title and url
info = article.find('a',{'href':True})
link = info['href']
title = info['title']
#Image
image_element = article.find('div',{'class':'absg'})
image = image_element['data-src']
#Summary
try:
sum_span = article.find('span',{'class':'article-dd'})
summary = sum_span.text
except AttributeError:
summary = getSummary(link)
#Time
time_elem = article.find('time')
time = time_elem['datetime']
#Complete data
article_data = {
'site':'in',
'type':content[index],
'title':title,
'link':link,
'image':image,
'summary':summary,
'date':time
}
#Add the article data to the complete list
data_list.append(article_data)
print(len(data_list))
if __name__ == '__main__':
crawl_page() | [
"bs4.BeautifulSoup",
"requests.get"
] | [((107, 125), 'requests.get', 'requests.get', (['link'], {}), '(link)\n', (119, 125), False, 'import requests\n'), ((157, 203), 'bs4.BeautifulSoup', 'BeautifulSoup', (['response.content', '"""html.parser"""'], {}), "(response.content, 'html.parser')\n", (170, 203), False, 'from bs4 import BeautifulSoup\n'), ((1049, 1083), 'requests.get', 'requests.get', (['url'], {'headers': 'headers'}), '(url, headers=headers)\n', (1061, 1083), False, 'import requests\n'), ((1124, 1170), 'bs4.BeautifulSoup', 'BeautifulSoup', (['response.content', '"""html.parser"""'], {}), "(response.content, 'html.parser')\n", (1137, 1170), False, 'from bs4 import BeautifulSoup\n')] |
import copy
from configuration.configuration import QuestionnaireConfiguration
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import F
from django.template.loader import render_to_string
from configuration.models import Configuration, Key, Value, Translation, \
Questiongroup, Category
class Edition:
"""
Base class for a new edition of a questionnaire configuration, providing a central interface for:
- Simple, explicit definition for changes in configuration
- Re-use of operations, with possibility of customizing them (callables)
- Changes can be tracked per question between editions
- Verbose display of changes before application
- Generic helper methods for help texts, release notes and such
"""
code = ''
edition = ''
hierarchy = [
'sections',
'categories',
'subcategories',
'questiongroups',
'questions'
]
hierarchy_modules = 'modules'
def __str__(self):
return f'{self.code}: Edition {self.edition}'
@property
def operations(self):
raise NotImplementedError('A list of operations is required.')
def __init__(
self, key: Key, value: Value, questiongroup: Questiongroup,
category: Category, configuration: Configuration,
translation: Translation):
"""
Load operations, and validate the required instance variables.
"""
self.key = key
self.value = value
self.questiongroup = questiongroup
self.category = category
self.configuration = configuration
self.translation = translation
self.validate_instance_variables()
def validate_instance_variables(self):
for required_variable in ['code', 'edition']:
if not getattr(self, required_variable):
raise NotImplementedError('Instance variable "%s" is required' % required_variable)
if self.code not in [code[0] for code in Configuration.CODE_CHOICES]:
raise AttributeError('Code %s is not a valid configuration code choice' % self.code)
def run_operations(self):
"""
Apply operations, as defined by self.operations
"""
data = self.get_base_configuration_data()
for _operation in self.operations:
data = _operation.migrate(**data)
self.save_object(**data)
def get_base_configuration_data(self):
"""
Get configuration data from the 'previous' version, which is the base for this edition.
"""
return self.configuration.objects.filter(
code=self.code
).exclude(
code=self.code, edition=self.edition
).latest(
'created'
).data
def save_object(self, **data) -> Configuration:
"""
Create or update the configuration with the modified data.
"""
try:
obj = self.configuration.objects.get(
edition=self.edition, code=self.code)
except self.configuration.DoesNotExist:
obj = self.configuration(edition=self.edition, code=self.code)
obj.data = data
# Validate the data before saving.
questionnaire_configuration = QuestionnaireConfiguration(
keyword=self.code, configuration_object=obj)
if questionnaire_configuration.configuration_error:
raise Exception('Configuration error: %s' %
questionnaire_configuration.configuration_error)
obj.save()
return obj
def get_release_notes(self):
for _operation in self.operations:
yield _operation.render()
def update_questionnaire_data(self, **data) -> dict:
"""
Gets called when creating a new version of a questionnaire in a new
edition. Calls each operation's "transform_questionnaire" method.
"""
for _operation in self.operations:
data = _operation.update_questionnaire_data(**data)
return data
@classmethod
def run_migration(cls, apps, schema_editor):
"""
Callable for the django migration file. Create an empty migration with:
```python manage.py makemigrations configuration --empty```
Add this tho the operations list:
operations = [
migrations.RunPython(<Subclass>.run_migration)
]
"""
if settings.IS_TEST_RUN:
# This needs discussion! What is expected of this migration in test mode?
return
# Models are loaded here, so they are available in the context of a migration.
model_names = ['Configuration', 'Key', 'Value', 'Translation']
kwargs = {}
for model in model_names:
kwargs[model.lower()] = apps.get_model('configuration', model)
cls(**kwargs).run_operations()
@property
def translation_key(self) -> str:
"""
Name of the current configuration, used as dict-key in the translation-data
(see Translation.get_translation)
"""
return f'{self.code}_{self.edition}'
def update_translation(self, update_pk: int, **data):
"""
Helper to replace texts (for choices, checkboxes, labels, etc.).
Create a new translation for this edition. Adds this configuration with
edition as a new key to the given (update_pk) translation object.
"""
obj = self.translation.objects.get(pk=update_pk)
obj.data.update({self.translation_key: data})
obj.save()
def create_new_translation(
self, translation_type, translation_keys: list=None,
**data) -> Translation:
"""
Create and return a new translation entry.
"""
if translation_keys:
data = {t: data for t in translation_keys}
else:
data = {self.translation_key: data}
translation, __ = self.translation.objects.get_or_create(
translation_type=translation_type, data=data)
return translation
def create_new_category(
self, keyword: str, translation: dict or int or None) -> Category:
if isinstance(translation, dict):
translation_obj = self.create_new_translation(
translation_type='category', **translation)
elif isinstance(translation, int):
translation_obj = self.translation.objects.get(pk=translation)
else:
translation_obj = None
category, __ = self.category.objects.get_or_create(
keyword=keyword, translation=translation_obj)
return category
def create_new_questiongroup(
self, keyword: str, translation: dict or int or None) -> Questiongroup:
if isinstance(translation, dict):
translation_obj = self.create_new_translation(
translation_type='questiongroup', **translation)
elif isinstance(translation, int):
translation_obj = self.translation.objects.get(pk=translation)
else:
translation_obj = None
configuration = {}
questiongroup, __ = self.questiongroup.objects.get_or_create(
keyword=keyword, translation=translation_obj,
configuration=configuration)
return questiongroup
def create_new_question(
self, keyword: str, translation: dict or int, question_type: str,
values: list=None, configuration: dict=None) -> Key:
"""
Create and return a new question (actually, in DB terms, a key), with a
translation.
"""
if isinstance(translation, dict):
translation_obj = self.create_new_translation(
translation_type='key', **translation)
else:
translation_obj = self.translation.objects.get(pk=translation)
configuration_data = configuration if configuration is not None else {}
configuration_data.update({'type': question_type})
try:
key = self.key.objects.get(keyword=keyword)
key.translation = translation_obj
key.configuration = configuration_data
key.save()
except ObjectDoesNotExist:
key = self.key.objects.create(
keyword=keyword,
translation=translation_obj,
configuration=configuration_data
)
if values is not None:
existing_values = key.values.all()
for new_value in values:
if new_value not in existing_values:
key.values.add(new_value)
return key
def create_new_value(
self, keyword: str, translation: dict or int, order_value: int=None,
configuration: dict=None, configuration_editions: list=None) -> Value:
"""
Create and return a new value, with a translation.
"""
if isinstance(translation, dict):
translation_obj = self.create_new_translation(
translation_type='value',
translation_keys=configuration_editions, **translation)
else:
translation_obj = self.translation.objects.get(pk=translation)
try:
value = self.value.objects.get(keyword=keyword)
value.translation = translation_obj
value.order_value = order_value
value.configuration = configuration
value.save()
except ObjectDoesNotExist:
value = self.value.objects.create(
keyword=keyword, translation=translation_obj,
order_value=order_value, configuration=configuration)
return value
def create_new_values_list(self, values_list: list) -> list:
"""Create and return a list of simple values."""
return [
self.create_new_value(
keyword=k,
translation={
'label': {
'en': l
}
})
for k, l in values_list
]
def add_new_value(
self, question_keyword: str, value: Value, order_value: int=None):
"""
Add a new value to an existing question.
"""
key = self.key.objects.get(keyword=question_keyword)
if order_value and not key.values.filter(pk=value.pk).exists():
# If order_value is provided and the value was not yet added to the
# question, update the ordering of the existing values.
key.values.filter(
order_value__gte=order_value
).update(
order_value=F('order_value') + 1
)
key.values.add(value)
def get_value(self, keyword: str) -> Value:
return self.value.objects.get(keyword=keyword)
def get_question(self, keyword: str) -> Key:
return self.key.objects.get(keyword=keyword)
def get_questiongroup(self, keyword: str) -> Questiongroup:
return self.questiongroup.objects.get(keyword=keyword)
def find_in_data(self, path: tuple, **data: dict) -> dict:
"""
Helper to find and return an element inside a configuration data dict.
Provide a path with keywords pointing to the desired element.
Drills down to the element assuming the following hierarchy of
configuration data:
"data": {
"sections": [
{
"keyword": "<section_keyword>",
"categories": [
{
"keyword": "<category_keyword>",
"subcategories": [
{
"keyword": "<subcategory_keyword>"
"questiongroups": [
{
"keyword": "<questiongroup_keyword>",
"questions": [
{
"keyword": "<question_keyword>"
}
]
}
]
}
]
}
]
}
],
"modules": [
"cca"
]
}
"""
for hierarchy_level, path_keyword in enumerate(path):
# Get the list of elements at the current hierarchy.
element_list = data[self.hierarchy[hierarchy_level]]
# Find the element by its keyword.
data = next((item for item in element_list
if item['keyword'] == path_keyword), None)
if data is None:
raise KeyError(
'No element with keyword %s found in list of %s' % (
path_keyword, self.hierarchy[hierarchy_level]))
return data
def update_config_data(self, path: tuple, updated, level=0, **data):
"""
Helper to update a portion of the nested configuration data dict.
"""
current_hierarchy = self.hierarchy[level]
# Make a copy of the current data, but reset the children.
new_data = copy.deepcopy(data)
new_data[current_hierarchy] = []
for element in data[current_hierarchy]:
if element['keyword'] != path[0]:
new_element = element
elif len(path) > 1:
new_element = self.update_config_data(
path=path[1:], updated=updated, level=level+1, **element)
else:
new_element = updated
new_data[current_hierarchy].append(new_element)
return new_data
def update_data(self, qg_keyword, q_keyword, updated, **data: dict) -> dict:
"""
Helper to update a question of the questionnaire data dict.
"""
questiongroup_data = data.get(qg_keyword, [])
if not questiongroup_data:
return data
updated_questiongroup_data = []
for qg_data in questiongroup_data:
if q_keyword in qg_data:
qg_data[q_keyword] = updated
updated_questiongroup_data.append(qg_data)
data[qg_keyword] = updated_questiongroup_data
return data
def add_new_module(self, updated, **data: dict) -> dict:
"""
Helper to add a module to the configuration
"""
# Modules data is fetched
module_data = data.get(self.hierarchy_modules, [])
if not module_data:
return data
# New module is appended
module_data.append(updated)
# Questionnaire configuration is updated with new module and returned
data[self.hierarchy_modules] = module_data
return data
def append_translation(self, update_pk: int, **data):
"""
Helper to append texts (for choices, checkboxes, labels, etc.).
"""
obj = self.translation.objects.get(pk=update_pk)
obj.data.update(data)
obj.save()
class Operation:
"""
Data structure for an 'operation' method.
Centralized wrapper for all operations, so they can be extended / modified
in a single class.
"""
default_template = 'configuration/partials/release_note.html'
def __init__(self, transform_configuration: callable, release_note: str, **kwargs):
"""
Args:
transform_configuration: callable for the update on the configuration data
release_note: string with release note
**kwargs:
transform_questionnaire: callable. Used to transform the
questionnaire data, e.g. for deleted/moved questions.
"""
self.transform_configuration = transform_configuration
self.release_note = release_note
self.template_name = kwargs.get('template_name', self.default_template)
self.transform_questionnaire = kwargs.get('transform_questionnaire')
def migrate(self, **data) -> dict:
return self.transform_configuration(**data)
def render(self) -> str:
return render_to_string(
template_name=self.template_name,
context={'note': self.release_note}
)
def update_questionnaire_data(self, **data):
if self.transform_questionnaire:
return self.transform_questionnaire(**data)
return data
| [
"configuration.configuration.QuestionnaireConfiguration",
"django.db.models.F",
"django.template.loader.render_to_string",
"copy.deepcopy"
] | [((3316, 3387), 'configuration.configuration.QuestionnaireConfiguration', 'QuestionnaireConfiguration', ([], {'keyword': 'self.code', 'configuration_object': 'obj'}), '(keyword=self.code, configuration_object=obj)\n', (3342, 3387), False, 'from configuration.configuration import QuestionnaireConfiguration\n'), ((13237, 13256), 'copy.deepcopy', 'copy.deepcopy', (['data'], {}), '(data)\n', (13250, 13256), False, 'import copy\n'), ((16161, 16253), 'django.template.loader.render_to_string', 'render_to_string', ([], {'template_name': 'self.template_name', 'context': "{'note': self.release_note}"}), "(template_name=self.template_name, context={'note': self.\n release_note})\n", (16177, 16253), False, 'from django.template.loader import render_to_string\n'), ((10745, 10761), 'django.db.models.F', 'F', (['"""order_value"""'], {}), "('order_value')\n", (10746, 10761), False, 'from django.db.models import F\n')] |
import matplotlib.pyplot as plt
import distance
from matplotlib import style
from clustering_algorithms.affinity_propagation import AffinityPropagation
from clustering_algorithms.custom_k_means import KMeans
from clustering_algorithms.custom_mean_shift import MeanShift
from clustering_algorithms.custom_mean_shift_string_edition import MeanShiftStringEdition
from clustering_algorithms.dbscan import DbScan
from prepare_data.format_sequences import format_sequences_from_student
from utils.e_mine import e_mine_find_common_scanpath
from utils.string_compare_algorithm import levenstein_sequence_similarity, is_string_similar, needleman_wunsch, \
needleman_wunsch_with_penalty
import numpy as np
# def initialize_2D_number_data_and_plot_them():
# number_data = np.array([[1, 2], [1.5, 1.8], [5, 8], [8, 8], [1, 0.6], [9, 11], [8, 2], [10, 2], [9, 3]])
# # plot data
# plt.scatter(number_data[:, 0], number_data[:, 1])
# plt.show()
# return number_data
#
#
# def test_k_means_with_numbers_then_plot_results():
# clf = KMeans(k=3)
# clf.fit(number_data)
#
# for centroid in clf.centroids:
# plt.scatter(clf.centroids[centroid][0], clf.centroids[centroid][1],
# marker="o", color="k", s=150, linewidths=5)
#
# for classification in clf.classifications:
# color = colors[classification]
# for featureset in clf.classifications[classification]:
# plt.scatter(featureset[0], featureset[1], marker="x", color=color,
# s=150, linewidths=5)
# plt.show()
#
#
# def test_mean_shift_with_numbers_then_plot_results():
# clf_ms = MeanShift()
# clf_ms.fit(number_data)
# plt.scatter(number_data[:, 0], number_data[:, 1], s=150)
# centroids = clf_ms.centroids
# for c in centroids:
# plt.scatter(centroids[c][0], centroids[c][1], color='k', marker="*", s=150)
# plt.show()
def initialize_string_sequences(student_name):
# print(format_sequences_from_student(student_name))
return format_sequences_from_student(student_name)
# return ["ACCAEF", "ACCEF", "AACF", "CCCEF", "CCAACCF", "CCACF"]
def print_description():
print("***************************************************")
print("NAME OF ALGORITHM")
print("- *CLUSTER REPRESENTER* [CLUSTER MEMBER, CLUSTER MEMBER, CLUSTER MEMBER]")
print("***************************************************")
def test_and_print_results_string_k_means_with_levenshtein_distance():
kmeans_alg = KMeans(k=3, distance_function=distance.levenshtein, find_average_function=e_mine_find_common_scanpath,
check_is_optimized_function=is_string_similar)
kmeans_alg.fit(string_data)
print_k_means_results(kmeans_alg, "Levenshtein")
def test_and_print_results_string_k_means_with_needleman_wunsch_distance():
kmeans_alg = KMeans(k=3, distance_function=needleman_wunsch, find_average_function=e_mine_find_common_scanpath,
check_is_optimized_function=is_string_similar)
kmeans_alg.fit(string_data)
print_k_means_results(kmeans_alg, "Needleman-Wunsch")
def test_and_print_results_string_k_means_with_needleman_wunsch_distance_with_extra_penalty_points():
kmeans_alg = KMeans(k=3, distance_function=needleman_wunsch_with_penalty,
find_average_function=e_mine_find_common_scanpath,
check_is_optimized_function=is_string_similar)
kmeans_alg.fit(string_data)
print_k_means_results(kmeans_alg, "Needleman-Wunsch with additional penalty")
def print_k_means_results(kmeans_alg, distance_algorithm):
centroid_cluster_map_kmeans = {}
for i in range(0, len(kmeans_alg.centroids)):
centroid_cluster_map_kmeans[kmeans_alg.centroids[i]] = kmeans_alg.classifications[i]
print()
print("K Means string edition with %s distance algorithm" % distance_algorithm)
for centroid in centroid_cluster_map_kmeans:
print(" - *%s* %s" % (centroid, centroid_cluster_map_kmeans[centroid]))
def test_and_print_results_string_mean_shift_with_levenshtein_distance():
mean_shift_string_edition = MeanShiftStringEdition()
mean_shift_string_edition.fit(string_data)
print_mean_shift_results(mean_shift_string_edition, "Levenshtein")
def test_and_print_results_string_mean_shift_with_needleman_wunsch_distance():
mean_shift_string_edition = MeanShiftStringEdition(distance_function=needleman_wunsch)
mean_shift_string_edition.fit(string_data)
print_mean_shift_results(mean_shift_string_edition, "Needleman-Wunsch")
def test_and_print_results_string_mean_shift_with_needleman_wunsch_distance_with_extra_penalty_points():
mean_shift_string_edition = MeanShiftStringEdition(distance_function=needleman_wunsch_with_penalty)
mean_shift_string_edition.fit(string_data)
print_mean_shift_results(mean_shift_string_edition, "Needleman-Wunsch with additional penalty")
def print_mean_shift_results(mean_shift_string_edition, distance_algorithm):
print()
print("Mean Shift string edition with %s distance algorithm" % distance_algorithm)
for centroid in mean_shift_string_edition.centroids:
print(" - *%s*" % mean_shift_string_edition.centroids[centroid])
def test_and_print_results_string_affinity_propagation_with_levenstein_distance():
data_as_array = np.asarray(string_data)
lev_similarity_scores = -1 * np.array(
[[distance.levenshtein(w1, w2) for w1 in data_as_array] for w2 in data_as_array])
affinity_propagation_alg = AffinityPropagation()
affinity_propagation_alg.fit(lev_similarity_scores)
print_affinity_propagation_results(affinity_propagation_alg, data_as_array, "Levenshtein")
def test_and_print_results_string_affinity_propagation_with_needleman_wunsch_distance():
data_as_array = np.asarray(string_data)
lev_similarity_scores = -1 * np.array(
[[needleman_wunsch(w1, w2) for w1 in data_as_array] for w2 in data_as_array])
affinity_propagation_alg = AffinityPropagation()
affinity_propagation_alg.fit(lev_similarity_scores)
print_affinity_propagation_results(affinity_propagation_alg, data_as_array, "Needleman-Wunsch")
def test_and_print_results_string_affinity_propagation_with_needleman_wunsch_distance_with_extra_penalty_points():
data_as_array = np.asarray(string_data)
lev_similarity_scores = -1 * np.array(
[[needleman_wunsch_with_penalty(w1, w2) for w1 in data_as_array] for w2 in data_as_array])
affinity_propagation_alg = AffinityPropagation()
affinity_propagation_alg.fit(lev_similarity_scores)
print_affinity_propagation_results(affinity_propagation_alg, data_as_array, "Needleman-Wunsch with additional penalty")
def print_affinity_propagation_results(affinity_propagation_alg, data_as_array, distance_algorithm):
print()
print('Affinity Propagation with %s distance algorithm' % distance_algorithm)
exemplar_features_map = affinity_propagation_alg.get_exemplars_and_their_features(data_as_array)
for exemplar in exemplar_features_map:
print(" - *%s* %s" % (exemplar, exemplar_features_map[exemplar]))
def test_and_print_results_string_db_scan_with_levenstein_distance():
def lev_metric(x, y):
i, j = int(x[0]), int(y[0]) # extract indices
return distance.levenshtein(string_data[i], string_data[j])
db_scan = DbScan()
db_scan.fit(lev_metric, string_data)
print_db_scan_results(db_scan, "Levenshtein")
def test_and_print_results_string_db_scan_with_needleman_wunsch_distance():
def lev_metric(x, y):
i, j = int(x[0]), int(y[0]) # extract indices
return needleman_wunsch(string_data[i], string_data[j])
db_scan = DbScan()
db_scan.fit(lev_metric, string_data)
print_db_scan_results(db_scan, "Needleman-Wunsch")
def test_and_print_results_string_db_scan_with_needleman_wunsch_distance_with_extra_penalty_points():
def lev_metric(x, y):
i, j = int(x[0]), int(y[0]) # extract indices
return needleman_wunsch_with_penalty(string_data[i], string_data[j])
db_scan = DbScan()
db_scan.fit(lev_metric, string_data)
print_db_scan_results(db_scan, "Needleman-Wunsch with additional penalty")
def print_db_scan_results(db_scan, distance_algorithm):
print()
print('DB Scan with %s distance algorithm' % distance_algorithm)
for cluster in db_scan.get_clusters():
cluster_representer = e_mine_find_common_scanpath(db_scan.get_clusters()[cluster])
print(" - *%s* %s" % (cluster_representer, db_scan.get_clusters()[cluster]))
'''
1# Initialize number collection and plot style
'''
# style.use('ggplot')
# number_data = initialize_2D_number_data_and_plot_them()
# colors = 10 * ["g", "r", "c", "b", "k"]
'''
Test classification algorithms with numbers
'''
# test_k_means_with_numbers_then_plot_results()
# test_mean_shift_with_numbers_then_plot_results()
'''
2# Initialize string collection and print description on printed form
'''
student_name = "student_1"
string_data = initialize_string_sequences(student_name)
print_description()
'''
Test classification algorithms with strings
'''
test_and_print_results_string_k_means_with_levenshtein_distance()
test_and_print_results_string_k_means_with_needleman_wunsch_distance()
test_and_print_results_string_k_means_with_needleman_wunsch_distance_with_extra_penalty_points()
test_and_print_results_string_mean_shift_with_levenshtein_distance()
test_and_print_results_string_mean_shift_with_needleman_wunsch_distance()
test_and_print_results_string_mean_shift_with_needleman_wunsch_distance_with_extra_penalty_points()
test_and_print_results_string_affinity_propagation_with_levenstein_distance()
test_and_print_results_string_affinity_propagation_with_needleman_wunsch_distance()
test_and_print_results_string_affinity_propagation_with_needleman_wunsch_distance_with_extra_penalty_points()
test_and_print_results_string_db_scan_with_levenstein_distance()
test_and_print_results_string_db_scan_with_needleman_wunsch_distance()
test_and_print_results_string_db_scan_with_needleman_wunsch_distance_with_extra_penalty_points() | [
"utils.string_compare_algorithm.needleman_wunsch_with_penalty",
"prepare_data.format_sequences.format_sequences_from_student",
"numpy.asarray",
"clustering_algorithms.affinity_propagation.AffinityPropagation",
"clustering_algorithms.custom_k_means.KMeans",
"distance.levenshtein",
"clustering_algorithms.... | [((2032, 2075), 'prepare_data.format_sequences.format_sequences_from_student', 'format_sequences_from_student', (['student_name'], {}), '(student_name)\n', (2061, 2075), False, 'from prepare_data.format_sequences import format_sequences_from_student\n'), ((2510, 2664), 'clustering_algorithms.custom_k_means.KMeans', 'KMeans', ([], {'k': '(3)', 'distance_function': 'distance.levenshtein', 'find_average_function': 'e_mine_find_common_scanpath', 'check_is_optimized_function': 'is_string_similar'}), '(k=3, distance_function=distance.levenshtein, find_average_function=\n e_mine_find_common_scanpath, check_is_optimized_function=is_string_similar)\n', (2516, 2664), False, 'from clustering_algorithms.custom_k_means import KMeans\n'), ((2864, 3014), 'clustering_algorithms.custom_k_means.KMeans', 'KMeans', ([], {'k': '(3)', 'distance_function': 'needleman_wunsch', 'find_average_function': 'e_mine_find_common_scanpath', 'check_is_optimized_function': 'is_string_similar'}), '(k=3, distance_function=needleman_wunsch, find_average_function=\n e_mine_find_common_scanpath, check_is_optimized_function=is_string_similar)\n', (2870, 3014), False, 'from clustering_algorithms.custom_k_means import KMeans\n'), ((3245, 3411), 'clustering_algorithms.custom_k_means.KMeans', 'KMeans', ([], {'k': '(3)', 'distance_function': 'needleman_wunsch_with_penalty', 'find_average_function': 'e_mine_find_common_scanpath', 'check_is_optimized_function': 'is_string_similar'}), '(k=3, distance_function=needleman_wunsch_with_penalty,\n find_average_function=e_mine_find_common_scanpath,\n check_is_optimized_function=is_string_similar)\n', (3251, 3411), False, 'from clustering_algorithms.custom_k_means import KMeans\n'), ((4140, 4164), 'clustering_algorithms.custom_mean_shift_string_edition.MeanShiftStringEdition', 'MeanShiftStringEdition', ([], {}), '()\n', (4162, 4164), False, 'from clustering_algorithms.custom_mean_shift_string_edition import MeanShiftStringEdition\n'), ((4397, 4455), 'clustering_algorithms.custom_mean_shift_string_edition.MeanShiftStringEdition', 'MeanShiftStringEdition', ([], {'distance_function': 'needleman_wunsch'}), '(distance_function=needleman_wunsch)\n', (4419, 4455), False, 'from clustering_algorithms.custom_mean_shift_string_edition import MeanShiftStringEdition\n'), ((4719, 4790), 'clustering_algorithms.custom_mean_shift_string_edition.MeanShiftStringEdition', 'MeanShiftStringEdition', ([], {'distance_function': 'needleman_wunsch_with_penalty'}), '(distance_function=needleman_wunsch_with_penalty)\n', (4741, 4790), False, 'from clustering_algorithms.custom_mean_shift_string_edition import MeanShiftStringEdition\n'), ((5352, 5375), 'numpy.asarray', 'np.asarray', (['string_data'], {}), '(string_data)\n', (5362, 5375), True, 'import numpy as np\n'), ((5540, 5561), 'clustering_algorithms.affinity_propagation.AffinityPropagation', 'AffinityPropagation', ([], {}), '()\n', (5559, 5561), False, 'from clustering_algorithms.affinity_propagation import AffinityPropagation\n'), ((5825, 5848), 'numpy.asarray', 'np.asarray', (['string_data'], {}), '(string_data)\n', (5835, 5848), True, 'import numpy as np\n'), ((6009, 6030), 'clustering_algorithms.affinity_propagation.AffinityPropagation', 'AffinityPropagation', ([], {}), '()\n', (6028, 6030), False, 'from clustering_algorithms.affinity_propagation import AffinityPropagation\n'), ((6325, 6348), 'numpy.asarray', 'np.asarray', (['string_data'], {}), '(string_data)\n', (6335, 6348), True, 'import numpy as np\n'), ((6522, 6543), 'clustering_algorithms.affinity_propagation.AffinityPropagation', 'AffinityPropagation', ([], {}), '()\n', (6541, 6543), False, 'from clustering_algorithms.affinity_propagation import AffinityPropagation\n'), ((7376, 7384), 'clustering_algorithms.dbscan.DbScan', 'DbScan', ([], {}), '()\n', (7382, 7384), False, 'from clustering_algorithms.dbscan import DbScan\n'), ((7714, 7722), 'clustering_algorithms.dbscan.DbScan', 'DbScan', ([], {}), '()\n', (7720, 7722), False, 'from clustering_algorithms.dbscan import DbScan\n'), ((8096, 8104), 'clustering_algorithms.dbscan.DbScan', 'DbScan', ([], {}), '()\n', (8102, 8104), False, 'from clustering_algorithms.dbscan import DbScan\n'), ((7308, 7360), 'distance.levenshtein', 'distance.levenshtein', (['string_data[i]', 'string_data[j]'], {}), '(string_data[i], string_data[j])\n', (7328, 7360), False, 'import distance\n'), ((7650, 7698), 'utils.string_compare_algorithm.needleman_wunsch', 'needleman_wunsch', (['string_data[i]', 'string_data[j]'], {}), '(string_data[i], string_data[j])\n', (7666, 7698), False, 'from utils.string_compare_algorithm import levenstein_sequence_similarity, is_string_similar, needleman_wunsch, needleman_wunsch_with_penalty\n'), ((8019, 8080), 'utils.string_compare_algorithm.needleman_wunsch_with_penalty', 'needleman_wunsch_with_penalty', (['string_data[i]', 'string_data[j]'], {}), '(string_data[i], string_data[j])\n', (8048, 8080), False, 'from utils.string_compare_algorithm import levenstein_sequence_similarity, is_string_similar, needleman_wunsch, needleman_wunsch_with_penalty\n'), ((5429, 5457), 'distance.levenshtein', 'distance.levenshtein', (['w1', 'w2'], {}), '(w1, w2)\n', (5449, 5457), False, 'import distance\n'), ((5902, 5926), 'utils.string_compare_algorithm.needleman_wunsch', 'needleman_wunsch', (['w1', 'w2'], {}), '(w1, w2)\n', (5918, 5926), False, 'from utils.string_compare_algorithm import levenstein_sequence_similarity, is_string_similar, needleman_wunsch, needleman_wunsch_with_penalty\n'), ((6402, 6439), 'utils.string_compare_algorithm.needleman_wunsch_with_penalty', 'needleman_wunsch_with_penalty', (['w1', 'w2'], {}), '(w1, w2)\n', (6431, 6439), False, 'from utils.string_compare_algorithm import levenstein_sequence_similarity, is_string_similar, needleman_wunsch, needleman_wunsch_with_penalty\n')] |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""Conversion between single-channel integer value to 3-channels color image.
Mostly used for semantic segmentation.
"""
from __future__ import annotations
import numpy as np
import torch
from multipledispatch import dispatch
from torch import Tensor
from onevision.cv.core import get_num_channels
from onevision.cv.core import to_channel_first
from onevision.type import TensorOrArray
__all__ = [
"integer_to_color",
"is_color_image",
]
# MARK: - Functional
def _integer_to_color(image: np.ndarray, colors: list) -> np.ndarray:
"""Convert the integer-encoded image to color image. Fill an image with
labels' colors.
Args:
image (np.ndarray):
An image in either one-hot or integer.
colors (list):
List of all colors.
Returns:
color (np.ndarray):
Colored image.
"""
if len(colors) <= 0:
raise ValueError(f"No colors are provided.")
# NOTE: Convert to channel-first
image = to_channel_first(image)
# NOTE: Squeeze dims to 2
if image.ndim == 3:
image = np.squeeze(image)
# NOTE: Draw color
r = np.zeros_like(image).astype(np.uint8)
g = np.zeros_like(image).astype(np.uint8)
b = np.zeros_like(image).astype(np.uint8)
for l in range(0, len(colors)):
idx = image == l
r[idx] = colors[l][0]
g[idx] = colors[l][1]
b[idx] = colors[l][2]
rgb = np.stack([r, g, b], axis=0)
return rgb
@dispatch(Tensor, list)
def integer_to_color(image: Tensor, colors: list) -> Tensor:
mask_np = image.numpy()
mask_np = integer_to_color(mask_np, colors)
color = torch.from_numpy(mask_np)
return color
@dispatch(np.ndarray, list)
def integer_to_color(image: np.ndarray, colors: list) -> np.ndarray:
# [C, H, W]
if image.ndim == 3:
return _integer_to_color(image, colors)
# [B, C, H, W]
if image.ndim == 4:
colors = [_integer_to_color(i, colors) for i in image]
colors = np.stack(colors).astype(np.uint8)
return colors
raise ValueError(f"`image.ndim` must be 3 or 4. But got: {image.ndim}.")
def is_color_image(image: TensorOrArray) -> bool:
"""Check if the given image is color encoded."""
if get_num_channels(image) in [3, 4]:
return True
return False
| [
"torch.from_numpy",
"numpy.squeeze",
"numpy.stack",
"multipledispatch.dispatch",
"onevision.cv.core.to_channel_first",
"numpy.zeros_like",
"onevision.cv.core.get_num_channels"
] | [((1527, 1549), 'multipledispatch.dispatch', 'dispatch', (['Tensor', 'list'], {}), '(Tensor, list)\n', (1535, 1549), False, 'from multipledispatch import dispatch\n'), ((1747, 1773), 'multipledispatch.dispatch', 'dispatch', (['np.ndarray', 'list'], {}), '(np.ndarray, list)\n', (1755, 1773), False, 'from multipledispatch import dispatch\n'), ((1037, 1060), 'onevision.cv.core.to_channel_first', 'to_channel_first', (['image'], {}), '(image)\n', (1053, 1060), False, 'from onevision.cv.core import to_channel_first\n'), ((1481, 1508), 'numpy.stack', 'np.stack', (['[r, g, b]'], {'axis': '(0)'}), '([r, g, b], axis=0)\n', (1489, 1508), True, 'import numpy as np\n'), ((1701, 1726), 'torch.from_numpy', 'torch.from_numpy', (['mask_np'], {}), '(mask_np)\n', (1717, 1726), False, 'import torch\n'), ((1136, 1153), 'numpy.squeeze', 'np.squeeze', (['image'], {}), '(image)\n', (1146, 1153), True, 'import numpy as np\n'), ((2309, 2332), 'onevision.cv.core.get_num_channels', 'get_num_channels', (['image'], {}), '(image)\n', (2325, 2332), False, 'from onevision.cv.core import get_num_channels\n'), ((1190, 1210), 'numpy.zeros_like', 'np.zeros_like', (['image'], {}), '(image)\n', (1203, 1210), True, 'import numpy as np\n'), ((1236, 1256), 'numpy.zeros_like', 'np.zeros_like', (['image'], {}), '(image)\n', (1249, 1256), True, 'import numpy as np\n'), ((1282, 1302), 'numpy.zeros_like', 'np.zeros_like', (['image'], {}), '(image)\n', (1295, 1302), True, 'import numpy as np\n'), ((2059, 2075), 'numpy.stack', 'np.stack', (['colors'], {}), '(colors)\n', (2067, 2075), True, 'import numpy as np\n')] |
from statistics import mean
import csv
from aalpy.SULs import DfaSUL, MealySUL, MooreSUL
from aalpy.learning_algs import run_Lstar
from aalpy.oracles import RandomWalkEqOracle
from aalpy.utils import generate_random_dfa, generate_random_mealy_machine, generate_random_moore_machine
num_states = 1000
alph_size = 5
repeat = 10
num_increases = 20
states = ['alph_size', alph_size]
times_dfa = ['dfa_pypy_rs']
times_mealy = ['mealy_pypy_rs']
times_moore = ['moore_pypyrs']
cex_processing = 'rs'
for i in range(num_increases):
print(i)
total_time_dfa = []
total_time_mealy = []
total_time_moore = []
for _ in range(repeat):
alphabet = list(range(alph_size))
dfa = generate_random_dfa(num_states, alphabet=alphabet, num_accepting_states=num_states // 2)
sul = DfaSUL(dfa)
# eq_oracle = StatePrefixEqOracle(alphabet, sul, walks_per_state=5, walk_len=40)
eq_oracle = RandomWalkEqOracle(alphabet, sul, num_steps=10000, reset_prob=0.09)
_, data = run_Lstar(alphabet, sul, eq_oracle, cex_processing=cex_processing, cache_and_non_det_check=False,
return_data=True, automaton_type='dfa')
total_time_dfa.append(data['learning_time'])
del dfa
del sul
del eq_oracle
mealy = generate_random_mealy_machine(num_states, input_alphabet=alphabet, output_alphabet=alphabet)
sul_mealy = MealySUL(mealy)
# eq_oracle = StatePrefixEqOracle(alphabet, sul_mealy, walks_per_state=5, walk_len=40)
eq_oracle = RandomWalkEqOracle(alphabet, sul_mealy, num_steps=10000, reset_prob=0.09)
_, data = run_Lstar(alphabet, sul_mealy, eq_oracle, cex_processing=cex_processing,
cache_and_non_det_check=False,
return_data=True, automaton_type='mealy')
total_time_mealy.append(data['learning_time'])
del mealy
del sul_mealy
del eq_oracle
moore = generate_random_moore_machine(num_states, input_alphabet=alphabet, output_alphabet=alphabet)
moore_sul = MooreSUL(moore)
# eq_oracle = StatePrefixEqOracle(alphabet, moore_sul, walks_per_state=5, walk_len=40)
eq_oracle = RandomWalkEqOracle(alphabet, moore_sul, num_steps=10000, reset_prob=0.09)
_, data = run_Lstar(alphabet, moore_sul, eq_oracle, cex_processing=cex_processing,
cache_and_non_det_check=False,
return_data=True, automaton_type='moore')
total_time_moore.append(data['learning_time'])
alph_size += 5
states.append(alph_size)
# save data and keep averages
times_dfa.append(round(mean(total_time_dfa), 4))
times_mealy.append(round(mean(total_time_mealy), 4))
times_moore.append(round(mean(total_time_moore), 4))
with open('increasing_alphabet_experiments.csv', 'w') as f:
wr = csv.writer(f, dialect='excel')
wr.writerow(states)
wr.writerow(times_dfa)
wr.writerow(times_mealy)
wr.writerow(times_moore)
| [
"aalpy.oracles.RandomWalkEqOracle",
"statistics.mean",
"aalpy.SULs.DfaSUL",
"csv.writer",
"aalpy.learning_algs.run_Lstar",
"aalpy.SULs.MealySUL",
"aalpy.utils.generate_random_dfa",
"aalpy.utils.generate_random_mealy_machine",
"aalpy.utils.generate_random_moore_machine",
"aalpy.SULs.MooreSUL"
] | [((2899, 2929), 'csv.writer', 'csv.writer', (['f'], {'dialect': '"""excel"""'}), "(f, dialect='excel')\n", (2909, 2929), False, 'import csv\n'), ((703, 796), 'aalpy.utils.generate_random_dfa', 'generate_random_dfa', (['num_states'], {'alphabet': 'alphabet', 'num_accepting_states': '(num_states // 2)'}), '(num_states, alphabet=alphabet, num_accepting_states=\n num_states // 2)\n', (722, 796), False, 'from aalpy.utils import generate_random_dfa, generate_random_mealy_machine, generate_random_moore_machine\n'), ((806, 817), 'aalpy.SULs.DfaSUL', 'DfaSUL', (['dfa'], {}), '(dfa)\n', (812, 817), False, 'from aalpy.SULs import DfaSUL, MealySUL, MooreSUL\n'), ((928, 995), 'aalpy.oracles.RandomWalkEqOracle', 'RandomWalkEqOracle', (['alphabet', 'sul'], {'num_steps': '(10000)', 'reset_prob': '(0.09)'}), '(alphabet, sul, num_steps=10000, reset_prob=0.09)\n', (946, 995), False, 'from aalpy.oracles import RandomWalkEqOracle\n'), ((1015, 1156), 'aalpy.learning_algs.run_Lstar', 'run_Lstar', (['alphabet', 'sul', 'eq_oracle'], {'cex_processing': 'cex_processing', 'cache_and_non_det_check': '(False)', 'return_data': '(True)', 'automaton_type': '"""dfa"""'}), "(alphabet, sul, eq_oracle, cex_processing=cex_processing,\n cache_and_non_det_check=False, return_data=True, automaton_type='dfa')\n", (1024, 1156), False, 'from aalpy.learning_algs import run_Lstar\n'), ((1306, 1402), 'aalpy.utils.generate_random_mealy_machine', 'generate_random_mealy_machine', (['num_states'], {'input_alphabet': 'alphabet', 'output_alphabet': 'alphabet'}), '(num_states, input_alphabet=alphabet,\n output_alphabet=alphabet)\n', (1335, 1402), False, 'from aalpy.utils import generate_random_dfa, generate_random_mealy_machine, generate_random_moore_machine\n'), ((1419, 1434), 'aalpy.SULs.MealySUL', 'MealySUL', (['mealy'], {}), '(mealy)\n', (1427, 1434), False, 'from aalpy.SULs import DfaSUL, MealySUL, MooreSUL\n'), ((1551, 1624), 'aalpy.oracles.RandomWalkEqOracle', 'RandomWalkEqOracle', (['alphabet', 'sul_mealy'], {'num_steps': '(10000)', 'reset_prob': '(0.09)'}), '(alphabet, sul_mealy, num_steps=10000, reset_prob=0.09)\n', (1569, 1624), False, 'from aalpy.oracles import RandomWalkEqOracle\n'), ((1644, 1793), 'aalpy.learning_algs.run_Lstar', 'run_Lstar', (['alphabet', 'sul_mealy', 'eq_oracle'], {'cex_processing': 'cex_processing', 'cache_and_non_det_check': '(False)', 'return_data': '(True)', 'automaton_type': '"""mealy"""'}), "(alphabet, sul_mealy, eq_oracle, cex_processing=cex_processing,\n cache_and_non_det_check=False, return_data=True, automaton_type='mealy')\n", (1653, 1793), False, 'from aalpy.learning_algs import run_Lstar\n'), ((1982, 2078), 'aalpy.utils.generate_random_moore_machine', 'generate_random_moore_machine', (['num_states'], {'input_alphabet': 'alphabet', 'output_alphabet': 'alphabet'}), '(num_states, input_alphabet=alphabet,\n output_alphabet=alphabet)\n', (2011, 2078), False, 'from aalpy.utils import generate_random_dfa, generate_random_mealy_machine, generate_random_moore_machine\n'), ((2095, 2110), 'aalpy.SULs.MooreSUL', 'MooreSUL', (['moore'], {}), '(moore)\n', (2103, 2110), False, 'from aalpy.SULs import DfaSUL, MealySUL, MooreSUL\n'), ((2227, 2300), 'aalpy.oracles.RandomWalkEqOracle', 'RandomWalkEqOracle', (['alphabet', 'moore_sul'], {'num_steps': '(10000)', 'reset_prob': '(0.09)'}), '(alphabet, moore_sul, num_steps=10000, reset_prob=0.09)\n', (2245, 2300), False, 'from aalpy.oracles import RandomWalkEqOracle\n'), ((2320, 2469), 'aalpy.learning_algs.run_Lstar', 'run_Lstar', (['alphabet', 'moore_sul', 'eq_oracle'], {'cex_processing': 'cex_processing', 'cache_and_non_det_check': '(False)', 'return_data': '(True)', 'automaton_type': '"""moore"""'}), "(alphabet, moore_sul, eq_oracle, cex_processing=cex_processing,\n cache_and_non_det_check=False, return_data=True, automaton_type='moore')\n", (2329, 2469), False, 'from aalpy.learning_algs import run_Lstar\n'), ((2689, 2709), 'statistics.mean', 'mean', (['total_time_dfa'], {}), '(total_time_dfa)\n', (2693, 2709), False, 'from statistics import mean\n'), ((2744, 2766), 'statistics.mean', 'mean', (['total_time_mealy'], {}), '(total_time_mealy)\n', (2748, 2766), False, 'from statistics import mean\n'), ((2801, 2823), 'statistics.mean', 'mean', (['total_time_moore'], {}), '(total_time_moore)\n', (2805, 2823), False, 'from statistics import mean\n')] |
#!/usr/bin/env python
import sys
from os.path import exists
import numpy as np
import pylab
import scipy.interpolate
def read_fortran(filename):
""" Reads Fortran style binary data and returns a numpy array.
"""
with open(filename, 'rb') as f:
# read size of record
f.seek(0)
n = np.fromfile(f, dtype='int32', count=1)[0]
# read contents of record
f.seek(4)
v = np.fromfile(f, dtype='float32')
return v[:-1]
def mesh2grid(v, x, z):
""" Interpolates from an unstructured coordinates (mesh) to a structured
coordinates (grid)
"""
lx = x.max() - x.min()
lz = z.max() - z.min()
nn = v.size
mesh = _stack(x, z)
nx = np.around(np.sqrt(nn*lx/lz))
nz = np.around(np.sqrt(nn*lz/lx))
dx = lx/nx
dz = lz/nz
# construct structured grid
x = np.linspace(x.min(), x.max(), nx)
z = np.linspace(z.min(), z.max(), nz)
X, Z = np.meshgrid(x, z)
grid = _stack(X.flatten(), Z.flatten())
# interpolate to structured grid
V = scipy.interpolate.griddata(mesh, v, grid, 'linear')
# workaround edge issues
if np.any(np.isnan(V)):
W = scipy.interpolate.griddata(mesh, v, grid, 'nearest')
for i in np.where(np.isnan(V)):
V[i] = W[i]
return np.reshape(V, (int(nz), int(nx))), x, z
def _stack(*args):
return np.column_stack(args)
if __name__ == '__main__':
""" Plots data on 2-D unstructured mesh
Modified from a script for specfem2d:
http://tigress-web.princeton.edu/~rmodrak/visualize/plot2d
Can be used to plot models or kernels created by inv.cu
SYNTAX
plot_model.py folder_name component_name||file_name (time_step)
e.g. ./plot_model.py output vx 1000
./plot_model.py output proc001000_vx.bin
./plot_model.py example/model/checker vs
"""
istr = ''
if len(sys.argv) > 3:
istr = str(sys.argv[3])
while len(istr) < 6:
istr = '0' + istr
else:
istr = '000000'
# parse command line arguments
x_coords_file = '%s/proc000000_x.bin' % sys.argv[1]
z_coords_file = '%s/proc000000_z.bin' % sys.argv[1]
# check that files actually exist
assert exists(x_coords_file)
assert exists(z_coords_file)
database_file = "%s/%s" % (sys.argv[1], sys.argv[2])
if not exists(database_file):
database_file = "%s/%s.bin" % (sys.argv[1], sys.argv[2])
if not exists(database_file):
database_file = "%s/proc%s_%s.bin" % (sys.argv[1], istr, sys.argv[2])
assert exists(database_file)
# read mesh coordinates
#try:
if True:
x = read_fortran(x_coords_file)
z = read_fortran(z_coords_file)
#except:
# raise Exception('Error reading mesh coordinates.')
# read database file
try:
v = read_fortran(database_file)
except:
raise Exception('Error reading database file: %s' % database_file)
# check mesh dimensions
assert x.shape == z.shape == v.shape, 'Inconsistent mesh dimensions.'
# interpolate to uniform rectangular grid
V, X, Z = mesh2grid(v, x, z)
# display figure
pylab.pcolor(X, Z, V)
locs = np.arange(X.min(), X.max() + 1, (X.max() - X.min()) / 5)
pylab.xticks(locs, map(lambda x: "%g" % x, locs / 1e3))
locs = np.arange(Z.min(), Z.max() + 1, (Z.max() - Z.min()) / 5)
pylab.yticks(locs, map(lambda x: "%g" % x, locs / 1e3))
pylab.colorbar()
pylab.xlabel('x / km')
pylab.ylabel('z / km')
pylab.gca().invert_yaxis()
pylab.show()
| [
"os.path.exists",
"numpy.fromfile",
"numpy.sqrt",
"pylab.gca",
"pylab.xlabel",
"numpy.column_stack",
"pylab.colorbar",
"numpy.isnan",
"numpy.meshgrid",
"pylab.pcolor",
"pylab.ylabel",
"pylab.show"
] | [((849, 866), 'numpy.meshgrid', 'np.meshgrid', (['x', 'z'], {}), '(x, z)\n', (860, 866), True, 'import numpy as np\n'), ((1239, 1260), 'numpy.column_stack', 'np.column_stack', (['args'], {}), '(args)\n', (1254, 1260), True, 'import numpy as np\n'), ((2029, 2050), 'os.path.exists', 'exists', (['x_coords_file'], {}), '(x_coords_file)\n', (2035, 2050), False, 'from os.path import exists\n'), ((2059, 2080), 'os.path.exists', 'exists', (['z_coords_file'], {}), '(z_coords_file)\n', (2065, 2080), False, 'from os.path import exists\n'), ((2338, 2359), 'os.path.exists', 'exists', (['database_file'], {}), '(database_file)\n', (2344, 2359), False, 'from os.path import exists\n'), ((2871, 2892), 'pylab.pcolor', 'pylab.pcolor', (['X', 'Z', 'V'], {}), '(X, Z, V)\n', (2883, 2892), False, 'import pylab\n'), ((3138, 3154), 'pylab.colorbar', 'pylab.colorbar', ([], {}), '()\n', (3152, 3154), False, 'import pylab\n'), ((3156, 3178), 'pylab.xlabel', 'pylab.xlabel', (['"""x / km"""'], {}), "('x / km')\n", (3168, 3178), False, 'import pylab\n'), ((3180, 3202), 'pylab.ylabel', 'pylab.ylabel', (['"""z / km"""'], {}), "('z / km')\n", (3192, 3202), False, 'import pylab\n'), ((3232, 3244), 'pylab.show', 'pylab.show', ([], {}), '()\n', (3242, 3244), False, 'import pylab\n'), ((382, 413), 'numpy.fromfile', 'np.fromfile', (['f'], {'dtype': '"""float32"""'}), "(f, dtype='float32')\n", (393, 413), True, 'import numpy as np\n'), ((655, 676), 'numpy.sqrt', 'np.sqrt', (['(nn * lx / lz)'], {}), '(nn * lx / lz)\n', (662, 676), True, 'import numpy as np\n'), ((690, 711), 'numpy.sqrt', 'np.sqrt', (['(nn * lz / lx)'], {}), '(nn * lz / lx)\n', (697, 711), True, 'import numpy as np\n'), ((1038, 1049), 'numpy.isnan', 'np.isnan', (['V'], {}), '(V)\n', (1046, 1049), True, 'import numpy as np\n'), ((2144, 2165), 'os.path.exists', 'exists', (['database_file'], {}), '(database_file)\n', (2150, 2165), False, 'from os.path import exists\n'), ((2234, 2255), 'os.path.exists', 'exists', (['database_file'], {}), '(database_file)\n', (2240, 2255), False, 'from os.path import exists\n'), ((293, 331), 'numpy.fromfile', 'np.fromfile', (['f'], {'dtype': '"""int32"""', 'count': '(1)'}), "(f, dtype='int32', count=1)\n", (304, 331), True, 'import numpy as np\n'), ((1131, 1142), 'numpy.isnan', 'np.isnan', (['V'], {}), '(V)\n', (1139, 1142), True, 'import numpy as np\n'), ((3204, 3215), 'pylab.gca', 'pylab.gca', ([], {}), '()\n', (3213, 3215), False, 'import pylab\n')] |
# with the TRACKBAR gui component
# we can perform some action my moving cursor
import cv2
import numpy as np
def funk(): # create one funciton # Now we are not adding any action in it . # just pass
pass
def main():
img1 = np.zeros((512,512,3) , np.uint8) # create a imgae of size 512 x512
windowName = 'openCV BGR color Palette' # give the name to window which will appear after the execution ofthis program
cv2.namedWindow(windowName) # putting it (name) into the command
# create just labels
# make a Trackbar (we can scroll and change the color manually upto range 0 -255)
# just create scroll label
cv2.createTrackbar('B',windowName , 0 , 255 , funk)
cv2.createTrackbar('G',windowName , 0 , 255 , funk)
cv2.createTrackbar('R',windowName , 0 , 255 , funk)
while(True):
cv2.imshow(windowName , img1) # display the image on the window which we have created earlier
#exit from the loop
if cv2.waitKey(20)>0: # enter the any key to close the window
break
# put/ decide the colors on the labels corresponding windowNmae
# when scroll will move then track position will also be changed ., so corresponding to that position these below commands will perform some action
blue = cv2.getTrackbarPos('B' , windowName)
green = cv2.getTrackbarPos('R' , windowName)
red = cv2. getTrackbarPos('G' , windowName)
img1[:]= [blue ,green , red] # correspoding to cordinates this image will be shown
print(blue , green , red)
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
| [
"cv2.imshow",
"numpy.zeros",
"cv2.waitKey",
"cv2.destroyAllWindows",
"cv2.getTrackbarPos",
"cv2.createTrackbar",
"cv2.namedWindow"
] | [((250, 283), 'numpy.zeros', 'np.zeros', (['(512, 512, 3)', 'np.uint8'], {}), '((512, 512, 3), np.uint8)\n', (258, 283), True, 'import numpy as np\n'), ((451, 478), 'cv2.namedWindow', 'cv2.namedWindow', (['windowName'], {}), '(windowName)\n', (466, 478), False, 'import cv2\n'), ((673, 722), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""B"""', 'windowName', '(0)', '(255)', 'funk'], {}), "('B', windowName, 0, 255, funk)\n", (691, 722), False, 'import cv2\n'), ((733, 782), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""G"""', 'windowName', '(0)', '(255)', 'funk'], {}), "('G', windowName, 0, 255, funk)\n", (751, 782), False, 'import cv2\n'), ((790, 839), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""R"""', 'windowName', '(0)', '(255)', 'funk'], {}), "('R', windowName, 0, 255, funk)\n", (808, 839), False, 'import cv2\n'), ((1636, 1659), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (1657, 1659), False, 'import cv2\n'), ((871, 899), 'cv2.imshow', 'cv2.imshow', (['windowName', 'img1'], {}), '(windowName, img1)\n', (881, 899), False, 'import cv2\n'), ((1338, 1373), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""B"""', 'windowName'], {}), "('B', windowName)\n", (1356, 1373), False, 'import cv2\n'), ((1398, 1433), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""R"""', 'windowName'], {}), "('R', windowName)\n", (1416, 1433), False, 'import cv2\n'), ((1450, 1485), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""G"""', 'windowName'], {}), "('G', windowName)\n", (1468, 1485), False, 'import cv2\n'), ((1007, 1022), 'cv2.waitKey', 'cv2.waitKey', (['(20)'], {}), '(20)\n', (1018, 1022), False, 'import cv2\n')] |
from nldi_el_serv.XSGen import XSGen
from nldi_el_serv.dem_query import query_dems_shape
import py3dep
from pynhd import NLDI
gagebasin = NLDI().get_basins("06721000").to_crs('epsg:3857')
gageloc = NLDI().getfeature_byid("nwissite", "USGS-06721000").to_crs('epsg:3857')
cid = gageloc.comid.values.astype(str)
print(cid, gageloc.comid.values.astype(int)[0])
# strmseg_basin = NLDI().getfeature_byid("comid", cid[0], basin=True).to_crs('epsg:3857')
strmseg_loc = NLDI().getfeature_byid("comid", cid[0]).to_crs('epsg:3857')
xs = XSGen(point=gageloc, cl_geom=strmseg_loc, ny=101, width=1000)
xs_line = xs.get_xs()
xs_line_geom = xs_line.to_crs('epsg:4326')
print(xs_line_geom)
bbox = xs_line_geom.geometry[0].envelope.bounds
print(bbox)
query = query_dems_shape(bbox)
print(query)
t1 = (xs_line.total_bounds) + ((-100., -100., 100., 100.))
dem = py3dep.get_map("DEM", tuple(t1), resolution=10, geo_crs="EPSG:3857", crs="epsg:3857")
tmp = 0
| [
"pynhd.NLDI",
"nldi_el_serv.dem_query.query_dems_shape",
"nldi_el_serv.XSGen.XSGen"
] | [((529, 590), 'nldi_el_serv.XSGen.XSGen', 'XSGen', ([], {'point': 'gageloc', 'cl_geom': 'strmseg_loc', 'ny': '(101)', 'width': '(1000)'}), '(point=gageloc, cl_geom=strmseg_loc, ny=101, width=1000)\n', (534, 590), False, 'from nldi_el_serv.XSGen import XSGen\n'), ((745, 767), 'nldi_el_serv.dem_query.query_dems_shape', 'query_dems_shape', (['bbox'], {}), '(bbox)\n', (761, 767), False, 'from nldi_el_serv.dem_query import query_dems_shape\n'), ((140, 146), 'pynhd.NLDI', 'NLDI', ([], {}), '()\n', (144, 146), False, 'from pynhd import NLDI\n'), ((200, 206), 'pynhd.NLDI', 'NLDI', ([], {}), '()\n', (204, 206), False, 'from pynhd import NLDI\n'), ((463, 469), 'pynhd.NLDI', 'NLDI', ([], {}), '()\n', (467, 469), False, 'from pynhd import NLDI\n')] |
# PyVot
# Copyright(c) Microsoft Corporation
# 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
#
# THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
# IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
# MERCHANTABLITY OR NON-INFRINGEMENT.
#
# See the Apache Version 2.0 License for specific language governing
# permissions and limitations under the License.
#
# This file must work in both Python 2 and 3 as-is (without applying 2to3)
#
import sys
# If setuptools available, we normally want to install dependencies. The --no-downloads flag
# allows the PTVS installer to prevent this, to avoid network-related failure cases
allow_downloads = True
no_downloads_flag = '--no-downloads'
if no_downloads_flag in sys.argv:
sys.argv.remove(no_downloads_flag)
allow_downloads = False
try:
from setuptools import setup, Distribution
use_setuptools = True
except ImportError:
from distutils.core import setup, Distribution
use_setuptools = False
running_python3 = sys.version_info.major > 2
# Sets __version__ as a global without importing xl's __init__. We might not have pywin32 yet.
with open(r'.\xl\version.py') as version_file:
exec(version_file.read(), globals())
class PyvotDistribution(Distribution):
def find_config_files(self):
configs = Distribution.find_config_files(self)
configs.append("setup.py3.cfg" if running_python3 else "setup.py2.cfg")
return configs
long_description = \
"""Pyvot connects familiar data-exploration and visualization tools in Excel with the powerful data analysis
and transformation capabilities of Python, with an emphasis on tabular data. It provides a minimal and Pythonic
interface to Excel, smoothing over the pain points in using the existing Excel object model as exposed via COM."""
setup_options = dict(
name="Pyvot",
version=__version__,
author="<NAME>",
author_email="<EMAIL>",
license="Apache License 2.0",
description="Pythonic interface for data exploration in Excel",
long_description=long_description,
download_url="http://pypi.python.org/pypi/Pyvot",
url="http://pytools.codeplex.com/wikipage?title=Pyvot",
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Win32 (MS Windows)',
'Operating System :: Microsoft :: Windows',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Office/Business :: Financial :: Spreadsheet',
'License :: OSI Approved :: Apache Software License'],
packages=['xl', 'xl._impl'],
distclass=PyvotDistribution
)
if running_python3:
use_2to3 = True
from distutils.command.build_py import build_py_2to3
setup_options.update(dict(
cmdclass={'build_py': build_py_2to3}
))
if use_setuptools:
setup_options.update(dict(
zip_safe=True
))
if use_setuptools and allow_downloads:
setup_options.update(dict(
setup_requires=["Sphinx"],
))
setup(**setup_options)
| [
"distutils.core.Distribution.find_config_files",
"sys.argv.remove",
"distutils.core.setup"
] | [((3384, 3406), 'distutils.core.setup', 'setup', ([], {}), '(**setup_options)\n', (3389, 3406), False, 'from distutils.core import setup, Distribution\n'), ((1052, 1086), 'sys.argv.remove', 'sys.argv.remove', (['no_downloads_flag'], {}), '(no_downloads_flag)\n', (1067, 1086), False, 'import sys\n'), ((1613, 1649), 'distutils.core.Distribution.find_config_files', 'Distribution.find_config_files', (['self'], {}), '(self)\n', (1643, 1649), False, 'from distutils.core import setup, Distribution\n')] |
from odoo import models, fields, api
from odoo.exceptions import ValidationError
class DemoOdooWizardTutorial(models.Model):
_name = 'demo.odoo.wizard.tutorial'
_description = 'Demo Odoo Wizard Tutorial'
name = fields.Char('Description', required=True)
partner_id = fields.Many2one('res.partner', string='Partner')
@api.multi
def action_context_demo(self):
# if self._context.get('context_data', False):
if self.env.context.get('context_data'):
raise ValidationError('have context data')
raise ValidationError('hello')
@api.multi
def action_button(self):
for record in self:
record.with_context(context_data=True).action_context_demo() | [
"odoo.fields.Many2one",
"odoo.fields.Char",
"odoo.exceptions.ValidationError"
] | [((225, 266), 'odoo.fields.Char', 'fields.Char', (['"""Description"""'], {'required': '(True)'}), "('Description', required=True)\n", (236, 266), False, 'from odoo import models, fields, api\n'), ((284, 332), 'odoo.fields.Many2one', 'fields.Many2one', (['"""res.partner"""'], {'string': '"""Partner"""'}), "('res.partner', string='Partner')\n", (299, 332), False, 'from odoo import models, fields, api\n'), ((557, 581), 'odoo.exceptions.ValidationError', 'ValidationError', (['"""hello"""'], {}), "('hello')\n", (572, 581), False, 'from odoo.exceptions import ValidationError\n'), ((506, 542), 'odoo.exceptions.ValidationError', 'ValidationError', (['"""have context data"""'], {}), "('have context data')\n", (521, 542), False, 'from odoo.exceptions import ValidationError\n')] |
from django.db import models
class PartnerCharity(models.Model):
slug_id = models.CharField(max_length=30, unique=True)
name = models.TextField(unique=True, verbose_name='Name (human readable)')
email = models.EmailField(help_text='Used to cc the charity on receipts')
xero_account_name = models.TextField(help_text='Exact text of incoming donation account in xero')
active = models.BooleanField(default=True)
thumbnail = models.FileField(blank=True, null=True)
order = models.IntegerField(null=True, blank=True)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = 'Partner charities'
| [
"django.db.models.EmailField",
"django.db.models.TextField",
"django.db.models.IntegerField",
"django.db.models.FileField",
"django.db.models.BooleanField",
"django.db.models.CharField"
] | [((81, 125), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)', 'unique': '(True)'}), '(max_length=30, unique=True)\n', (97, 125), False, 'from django.db import models\n'), ((137, 204), 'django.db.models.TextField', 'models.TextField', ([], {'unique': '(True)', 'verbose_name': '"""Name (human readable)"""'}), "(unique=True, verbose_name='Name (human readable)')\n", (153, 204), False, 'from django.db import models\n'), ((217, 282), 'django.db.models.EmailField', 'models.EmailField', ([], {'help_text': '"""Used to cc the charity on receipts"""'}), "(help_text='Used to cc the charity on receipts')\n", (234, 282), False, 'from django.db import models\n'), ((307, 384), 'django.db.models.TextField', 'models.TextField', ([], {'help_text': '"""Exact text of incoming donation account in xero"""'}), "(help_text='Exact text of incoming donation account in xero')\n", (323, 384), False, 'from django.db import models\n'), ((398, 431), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)'}), '(default=True)\n', (417, 431), False, 'from django.db import models\n'), ((448, 487), 'django.db.models.FileField', 'models.FileField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (464, 487), False, 'from django.db import models\n'), ((500, 542), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'null': '(True)', 'blank': '(True)'}), '(null=True, blank=True)\n', (519, 542), False, 'from django.db import models\n')] |
__all__ = ['LightGBMRegressorModel']
from mmlspark.lightgbm.LightGBMRegressor import LightGBMRegressor, LightGBMRegressionModel
from mmlspark.train import ComputeModelStatistics
from pyspark.ml.evaluation import RegressionEvaluator
from pyspark.sql import DataFrame
import pyspark.sql.functions as F
from python_data_utils.spark.ml.base import BinaryClassCVModel, Metrics, RegressionCVModel
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
class LightGBMRegressorModel(RegressionCVModel):
def __init__(
self, *, estimator=None, evaluator=None,
label_col: str = 'label', params_map=None):
estimator = LightGBMRegressor(
objective='regression_l1',
# earlyStoppingRound=3,
# validationIndicatorCol='is_val',
labelCol=label_col)\
if not estimator else estimator
assert isinstance(estimator, LightGBMRegressor)
evaluator = RegressionEvaluator(metricName='mae')\
if not evaluator else evaluator
super().__init__(estimator, evaluator)
self.params_map = {
'baggingFraction': [.8, .9, 1.],
'featureFraction': [.5, .75, 1.],
'lambdaL1': [.1, .2, .3],
'learningRate': [0.01, 0.1],
'maxDepth': [-1, 3, 12],
'numIterations': [200],
'numLeaves': [31]
} if not params_map else params_map
@Metrics.register('regression_metrics')
def regression_metrics(self, predictions: DataFrame):
return ComputeModelStatistics(
evaluationMetric='regression',
labelCol=self.estimator.getLabelCol(),
scoresCol=self.estimator.getPredictionCol())\
.transform(predictions)\
.toPandas().to_dict(orient='list')
@Metrics.register('feature_importances')
def feature_importances(self, predictions: DataFrame):
feat_importances = pd.DataFrame(sorted(zip(
self.best_model.stages[-1].getFeatureImportances()
, self.features)), columns=['Value', 'Feature'])
# plot feature importance
_, ax = plt.subplots(figsize=(20, 10))
ax = sns.barplot(
x="Value",
y="Feature",
ax=ax,
data=feat_importances.sort_values(
by="Value", ascending=False))
ax.set_title('LightGBM Features (avg over folds)')
plt.tight_layout()
return {'data': feat_importances, 'plot': ax}
@Metrics.register('residuals_plot')
def residuals_plot(self, predictions: DataFrame):
# plot residuals
predictions = predictions.withColumn(
'_resid', F.col(self.estimator.getPredictionCol())\
- F.col(self.estimator.getLabelCol()))
return predictions.select('_resid').toPandas().hist()
| [
"python_data_utils.spark.ml.base.Metrics.register",
"pyspark.ml.evaluation.RegressionEvaluator",
"matplotlib.pyplot.tight_layout",
"warnings.simplefilter",
"mmlspark.lightgbm.LightGBMRegressor.LightGBMRegressor",
"matplotlib.pyplot.subplots"
] | [((485, 547), 'warnings.simplefilter', 'warnings.simplefilter', ([], {'action': '"""ignore"""', 'category': 'FutureWarning'}), "(action='ignore', category=FutureWarning)\n", (506, 547), False, 'import warnings\n'), ((1522, 1560), 'python_data_utils.spark.ml.base.Metrics.register', 'Metrics.register', (['"""regression_metrics"""'], {}), "('regression_metrics')\n", (1538, 1560), False, 'from python_data_utils.spark.ml.base import BinaryClassCVModel, Metrics, RegressionCVModel\n'), ((1900, 1939), 'python_data_utils.spark.ml.base.Metrics.register', 'Metrics.register', (['"""feature_importances"""'], {}), "('feature_importances')\n", (1916, 1939), False, 'from python_data_utils.spark.ml.base import BinaryClassCVModel, Metrics, RegressionCVModel\n'), ((2590, 2624), 'python_data_utils.spark.ml.base.Metrics.register', 'Metrics.register', (['"""residuals_plot"""'], {}), "('residuals_plot')\n", (2606, 2624), False, 'from python_data_utils.spark.ml.base import BinaryClassCVModel, Metrics, RegressionCVModel\n'), ((2226, 2256), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(20, 10)'}), '(figsize=(20, 10))\n', (2238, 2256), True, 'import matplotlib.pyplot as plt\n'), ((2510, 2528), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2526, 2528), True, 'import matplotlib.pyplot as plt\n'), ((747, 811), 'mmlspark.lightgbm.LightGBMRegressor.LightGBMRegressor', 'LightGBMRegressor', ([], {'objective': '"""regression_l1"""', 'labelCol': 'label_col'}), "(objective='regression_l1', labelCol=label_col)\n", (764, 811), False, 'from mmlspark.lightgbm.LightGBMRegressor import LightGBMRegressor, LightGBMRegressionModel\n'), ((1041, 1078), 'pyspark.ml.evaluation.RegressionEvaluator', 'RegressionEvaluator', ([], {'metricName': '"""mae"""'}), "(metricName='mae')\n", (1060, 1078), False, 'from pyspark.ml.evaluation import RegressionEvaluator\n')] |
import argparse
import os
import sys
sys.path.append(os.environ['CI_SITE_CONFIG'])
import ci_site_config
import run
import common
parser = argparse.ArgumentParser()
parser.add_argument("--prov", help="core provider", choices=["psm2", "verbs", \
"tcp", "udp", "sockets", "shm"])
parser.add_argument("--util", help="utility provider", choices=["rxd", "rxm"])
parser.add_argument("--ofi_build_mode", help="specify the build configuration", \
choices = ["dbg", "dl"])
args = parser.parse_args()
args_core = args.prov
args_util = args.util
if (args.ofi_build_mode):
ofi_build_mode = args.ofi_build_mode
else:
ofi_build_mode='reg'
node = (os.environ['NODE_NAME']).split('-')[0]
hosts = [node]
# Note: Temporarily disabling all mpich testing
# due to mpich options issues which is causing
# multiple tests to fail.
#mpilist = ['impi', 'mpich', 'ompi']
mpilist = ['impi', 'ompi']
#this script is executed from /tmp
#this is done since some mpi tests
#look for a valid location before running
# the test on the secondary host(client)
# but jenkins only creates a valid path on
# the primary host (server/test node)
os.chdir('/tmp/')
if(args_core):
for host in ci_site_config.node_map[node]:
hosts.append(host)
if (args_util == None):
run.fi_info_test(args_core, hosts, ofi_build_mode)
run.fabtests(args_core, hosts, ofi_build_mode)
run.shmemtest(args_core, hosts, ofi_build_mode)
for mpi in mpilist:
run.intel_mpi_benchmark(args_core, hosts, mpi, ofi_build_mode)
run.mpistress_benchmark(args_core, hosts, mpi, ofi_build_mode)
run.osu_benchmark(args_core, hosts, mpi, ofi_build_mode)
else:
run.fi_info_test(args_core, hosts, ofi_build_mode, util=args_util)
run.fabtests(args_core, hosts, ofi_build_mode, util=args_util)
run.shmemtest(args_core, hosts, ofi_build_mode, util=args_util)
for mpi in mpilist:
run.intel_mpi_benchmark(args_core, hosts, mpi, ofi_build_mode, \
util=args_util,)
run.mpistress_benchmark(args_core, hosts, mpi, ofi_build_mode, \
util=args_util)
run.osu_benchmark(args_core, hosts, mpi, ofi_build_mode, \
util=args_util)
else:
print("Error : Specify a core provider to run tests")
| [
"run.fabtests",
"argparse.ArgumentParser",
"run.fi_info_test",
"os.chdir",
"run.shmemtest",
"run.mpistress_benchmark",
"run.osu_benchmark",
"run.intel_mpi_benchmark",
"sys.path.append"
] | [((37, 82), 'sys.path.append', 'sys.path.append', (["os.environ['CI_SITE_CONFIG']"], {}), "(os.environ['CI_SITE_CONFIG'])\n", (52, 82), False, 'import sys\n'), ((140, 165), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (163, 165), False, 'import argparse\n'), ((1166, 1183), 'os.chdir', 'os.chdir', (['"""/tmp/"""'], {}), "('/tmp/')\n", (1174, 1183), False, 'import os\n'), ((1311, 1361), 'run.fi_info_test', 'run.fi_info_test', (['args_core', 'hosts', 'ofi_build_mode'], {}), '(args_core, hosts, ofi_build_mode)\n', (1327, 1361), False, 'import run\n'), ((1370, 1416), 'run.fabtests', 'run.fabtests', (['args_core', 'hosts', 'ofi_build_mode'], {}), '(args_core, hosts, ofi_build_mode)\n', (1382, 1416), False, 'import run\n'), ((1425, 1472), 'run.shmemtest', 'run.shmemtest', (['args_core', 'hosts', 'ofi_build_mode'], {}), '(args_core, hosts, ofi_build_mode)\n', (1438, 1472), False, 'import run\n'), ((1743, 1809), 'run.fi_info_test', 'run.fi_info_test', (['args_core', 'hosts', 'ofi_build_mode'], {'util': 'args_util'}), '(args_core, hosts, ofi_build_mode, util=args_util)\n', (1759, 1809), False, 'import run\n'), ((1818, 1880), 'run.fabtests', 'run.fabtests', (['args_core', 'hosts', 'ofi_build_mode'], {'util': 'args_util'}), '(args_core, hosts, ofi_build_mode, util=args_util)\n', (1830, 1880), False, 'import run\n'), ((1889, 1952), 'run.shmemtest', 'run.shmemtest', (['args_core', 'hosts', 'ofi_build_mode'], {'util': 'args_util'}), '(args_core, hosts, ofi_build_mode, util=args_util)\n', (1902, 1952), False, 'import run\n'), ((1513, 1575), 'run.intel_mpi_benchmark', 'run.intel_mpi_benchmark', (['args_core', 'hosts', 'mpi', 'ofi_build_mode'], {}), '(args_core, hosts, mpi, ofi_build_mode)\n', (1536, 1575), False, 'import run\n'), ((1591, 1653), 'run.mpistress_benchmark', 'run.mpistress_benchmark', (['args_core', 'hosts', 'mpi', 'ofi_build_mode'], {}), '(args_core, hosts, mpi, ofi_build_mode)\n', (1614, 1653), False, 'import run\n'), ((1666, 1722), 'run.osu_benchmark', 'run.osu_benchmark', (['args_core', 'hosts', 'mpi', 'ofi_build_mode'], {}), '(args_core, hosts, mpi, ofi_build_mode)\n', (1683, 1722), False, 'import run\n'), ((1993, 2071), 'run.intel_mpi_benchmark', 'run.intel_mpi_benchmark', (['args_core', 'hosts', 'mpi', 'ofi_build_mode'], {'util': 'args_util'}), '(args_core, hosts, mpi, ofi_build_mode, util=args_util)\n', (2016, 2071), False, 'import run\n'), ((2127, 2205), 'run.mpistress_benchmark', 'run.mpistress_benchmark', (['args_core', 'hosts', 'mpi', 'ofi_build_mode'], {'util': 'args_util'}), '(args_core, hosts, mpi, ofi_build_mode, util=args_util)\n', (2150, 2205), False, 'import run\n'), ((2264, 2336), 'run.osu_benchmark', 'run.osu_benchmark', (['args_core', 'hosts', 'mpi', 'ofi_build_mode'], {'util': 'args_util'}), '(args_core, hosts, mpi, ofi_build_mode, util=args_util)\n', (2281, 2336), False, 'import run\n')] |
from wtforms import Form, BooleanField, IntegerField, StringField, PasswordField, validators
from wtforms.fields.html5 import EmailField
from src.common.database import db
from sqlalchemy import exc
class RunnerRegistrationForm(Form):
first_name = StringField('First name', [
validators.Length(min=2, max=25),
validators.DataRequired(message="Required")])
last_name = StringField('Last name', [
validators.Length(min=2, max=25)])
gender = StringField('Gender', [
validators.Length(min=2, max=6),
validators.data_required(message="Required. 'boy' or 'girl'")])
year = IntegerField('Year of birth', [
validators.NumberRange(min=1917, max=2017),
validators.data_required(message="Required. Please specify number between 1917 and 2017.")])
class ParticipantModel(db.Model):
__tablename__ = "participants"
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(80), nullable=False)
last_name = db.Column(db.String(80), nullable=False)
gender = db.Column(db.String(6), nullable=False)
year = db.Column(db.Integer, nullable=False)
startlist = db.relationship("StartlistModel",
back_populates='participants',
cascade="all, delete, delete-orphan")
__table_args__ = (db.UniqueConstraint('first_name', 'last_name', 'year'),)
def __init__(self, first_name, last_name, gender, year):
self.first_name = first_name
self.last_name = last_name
self.gender = gender
self.year = int(year)
def json(self):
return {
"first_name": self.first_name,
"last_name": self.last_name,
"gender": self.gender,
"year": self.year,
}
@classmethod
def find_by_year(cls, year):
# 'guery' is a SQLAlchemy query builder
# SELECT FROM items WHERE name=name LIMIT 1
# returned data gets converted into ItemModel object
return cls.query.filter_by(year=int(year))
@classmethod
def find_by_gender_and_year(cls, gender, year):
return cls.query.filter_by(gender=gender, year=year)
def save_to_db(self):
''' Function does update and insert to the DB (upserting)
'''
# SQLAlchemy can translate object into the row
try:
db.session.add(self)
db.session.commit()
except exc.IntegrityError as e:
db.session().rollback()
@classmethod
def get_participants_ordered(cls):
return db.session.query(ParticipantModel.id,
ParticipantModel.last_name,
ParticipantModel.first_name,
ParticipantModel.gender,
ParticipantModel.year).\
order_by(ParticipantModel.last_name).\
order_by(ParticipantModel.first_name).\
all()
@classmethod
def get_by_id(cls, participant_id):
return db.session.query(cls).filter_by(id=participant_id).one()
@staticmethod
def drop_table():
db.drop_all()
@classmethod
def list_all(cls):
return cls.query.all()
def delete_from_db(self):
db.session.delete(self)
db.session.commit()
@classmethod
def delete_all_rows(cls):
all_rows = cls.list_all()
for row in all_rows:
row.delete_from_db()
| [
"wtforms.validators.NumberRange",
"src.common.database.db.Column",
"src.common.database.db.session.commit",
"src.common.database.db.session.add",
"src.common.database.db.session",
"wtforms.validators.Length",
"src.common.database.db.relationship",
"src.common.database.db.UniqueConstraint",
"src.comm... | [((895, 934), 'src.common.database.db.Column', 'db.Column', (['db.Integer'], {'primary_key': '(True)'}), '(db.Integer, primary_key=True)\n', (904, 934), False, 'from src.common.database import db\n'), ((1114, 1151), 'src.common.database.db.Column', 'db.Column', (['db.Integer'], {'nullable': '(False)'}), '(db.Integer, nullable=False)\n', (1123, 1151), False, 'from src.common.database import db\n'), ((1169, 1276), 'src.common.database.db.relationship', 'db.relationship', (['"""StartlistModel"""'], {'back_populates': '"""participants"""', 'cascade': '"""all, delete, delete-orphan"""'}), "('StartlistModel', back_populates='participants', cascade=\n 'all, delete, delete-orphan')\n", (1184, 1276), False, 'from src.common.database import db\n'), ((962, 975), 'src.common.database.db.String', 'db.String', (['(80)'], {}), '(80)\n', (971, 975), False, 'from src.common.database import db\n'), ((1019, 1032), 'src.common.database.db.String', 'db.String', (['(80)'], {}), '(80)\n', (1028, 1032), False, 'from src.common.database import db\n'), ((1073, 1085), 'src.common.database.db.String', 'db.String', (['(6)'], {}), '(6)\n', (1082, 1085), False, 'from src.common.database import db\n'), ((1353, 1407), 'src.common.database.db.UniqueConstraint', 'db.UniqueConstraint', (['"""first_name"""', '"""last_name"""', '"""year"""'], {}), "('first_name', 'last_name', 'year')\n", (1372, 1407), False, 'from src.common.database import db\n'), ((3193, 3206), 'src.common.database.db.drop_all', 'db.drop_all', ([], {}), '()\n', (3204, 3206), False, 'from src.common.database import db\n'), ((3318, 3341), 'src.common.database.db.session.delete', 'db.session.delete', (['self'], {}), '(self)\n', (3335, 3341), False, 'from src.common.database import db\n'), ((3350, 3369), 'src.common.database.db.session.commit', 'db.session.commit', ([], {}), '()\n', (3367, 3369), False, 'from src.common.database import db\n'), ((291, 323), 'wtforms.validators.Length', 'validators.Length', ([], {'min': '(2)', 'max': '(25)'}), '(min=2, max=25)\n', (308, 323), False, 'from wtforms import Form, BooleanField, IntegerField, StringField, PasswordField, validators\n'), ((333, 376), 'wtforms.validators.DataRequired', 'validators.DataRequired', ([], {'message': '"""Required"""'}), "(message='Required')\n", (356, 376), False, 'from wtforms import Form, BooleanField, IntegerField, StringField, PasswordField, validators\n'), ((431, 463), 'wtforms.validators.Length', 'validators.Length', ([], {'min': '(2)', 'max': '(25)'}), '(min=2, max=25)\n', (448, 463), False, 'from wtforms import Form, BooleanField, IntegerField, StringField, PasswordField, validators\n'), ((512, 543), 'wtforms.validators.Length', 'validators.Length', ([], {'min': '(2)', 'max': '(6)'}), '(min=2, max=6)\n', (529, 543), False, 'from wtforms import Form, BooleanField, IntegerField, StringField, PasswordField, validators\n'), ((553, 614), 'wtforms.validators.data_required', 'validators.data_required', ([], {'message': '"""Required. \'boy\' or \'girl\'"""'}), '(message="Required. \'boy\' or \'girl\'")\n', (577, 614), False, 'from wtforms import Form, BooleanField, IntegerField, StringField, PasswordField, validators\n'), ((669, 711), 'wtforms.validators.NumberRange', 'validators.NumberRange', ([], {'min': '(1917)', 'max': '(2017)'}), '(min=1917, max=2017)\n', (691, 711), False, 'from wtforms import Form, BooleanField, IntegerField, StringField, PasswordField, validators\n'), ((721, 816), 'wtforms.validators.data_required', 'validators.data_required', ([], {'message': '"""Required. Please specify number between 1917 and 2017."""'}), "(message=\n 'Required. Please specify number between 1917 and 2017.')\n", (745, 816), False, 'from wtforms import Form, BooleanField, IntegerField, StringField, PasswordField, validators\n'), ((2406, 2426), 'src.common.database.db.session.add', 'db.session.add', (['self'], {}), '(self)\n', (2420, 2426), False, 'from src.common.database import db\n'), ((2439, 2458), 'src.common.database.db.session.commit', 'db.session.commit', ([], {}), '()\n', (2456, 2458), False, 'from src.common.database import db\n'), ((2512, 2524), 'src.common.database.db.session', 'db.session', ([], {}), '()\n', (2522, 2524), False, 'from src.common.database import db\n'), ((3087, 3108), 'src.common.database.db.session.query', 'db.session.query', (['cls'], {}), '(cls)\n', (3103, 3108), False, 'from src.common.database import db\n'), ((2608, 2759), 'src.common.database.db.session.query', 'db.session.query', (['ParticipantModel.id', 'ParticipantModel.last_name', 'ParticipantModel.first_name', 'ParticipantModel.gender', 'ParticipantModel.year'], {}), '(ParticipantModel.id, ParticipantModel.last_name,\n ParticipantModel.first_name, ParticipantModel.gender, ParticipantModel.year\n )\n', (2624, 2759), False, 'from src.common.database import db\n')] |
import fourparts as fp
import pandas as pd
file_name = 'chorale_F'
df = fp.midi_to_df('samples/' + file_name + '.mid', save=True)
chords = fp.PreProcessor(4).get_progression(df)
chord_progression = fp.ChordProgression(chords)
# gets pitch class sets
pitch_class_sets = chord_progression.get_pitch_class_sets()
pd.DataFrame(pitch_class_sets).to_csv(file_name + '_pitch_class_sets.csv')
# check parallels
result = chord_progression.check_parallels()
pd.DataFrame(result).to_csv(file_name + '_parallel_results.csv')
# demonstration for 2 parts
file_name = 'chorale_G_2parts'
df = fp.midi_to_df('samples/' + file_name + '.mid', save=True)
dyads = fp.PreProcessor(2).get_progression(df)
dyad_progression = fp.DyadProgression(dyads)
# gets intervals between each dyad
dyad_intervals = dyad_progression.get_harmonic_intervals()
pd.DataFrame(dyad_intervals).to_csv(file_name + '_dyad_intervals.csv')
| [
"fourparts.PreProcessor",
"fourparts.ChordProgression",
"fourparts.DyadProgression",
"pandas.DataFrame",
"fourparts.midi_to_df"
] | [((75, 132), 'fourparts.midi_to_df', 'fp.midi_to_df', (["('samples/' + file_name + '.mid')"], {'save': '(True)'}), "('samples/' + file_name + '.mid', save=True)\n", (88, 132), True, 'import fourparts as fp\n'), ((201, 228), 'fourparts.ChordProgression', 'fp.ChordProgression', (['chords'], {}), '(chords)\n', (220, 228), True, 'import fourparts as fp\n'), ((585, 642), 'fourparts.midi_to_df', 'fp.midi_to_df', (["('samples/' + file_name + '.mid')"], {'save': '(True)'}), "('samples/' + file_name + '.mid', save=True)\n", (598, 642), True, 'import fourparts as fp\n'), ((709, 734), 'fourparts.DyadProgression', 'fp.DyadProgression', (['dyads'], {}), '(dyads)\n', (727, 734), True, 'import fourparts as fp\n'), ((142, 160), 'fourparts.PreProcessor', 'fp.PreProcessor', (['(4)'], {}), '(4)\n', (157, 160), True, 'import fourparts as fp\n'), ((314, 344), 'pandas.DataFrame', 'pd.DataFrame', (['pitch_class_sets'], {}), '(pitch_class_sets)\n', (326, 344), True, 'import pandas as pd\n'), ((453, 473), 'pandas.DataFrame', 'pd.DataFrame', (['result'], {}), '(result)\n', (465, 473), True, 'import pandas as pd\n'), ((651, 669), 'fourparts.PreProcessor', 'fp.PreProcessor', (['(2)'], {}), '(2)\n', (666, 669), True, 'import fourparts as fp\n'), ((830, 858), 'pandas.DataFrame', 'pd.DataFrame', (['dyad_intervals'], {}), '(dyad_intervals)\n', (842, 858), True, 'import pandas as pd\n')] |
"""
Defines models
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Function
from torch.autograd import Variable
from torch.nn.utils.rnn import pack_padded_sequence
from torch.nn.utils.rnn import pad_packed_sequence
def init_weights(m):
if type(m) == nn.Linear or type(m) == nn.Conv2d:
torch.nn.init.xavier_uniform_(m.weight)
if m.bias is not None:
m.bias.data.fill_(0.01)
class Flatten(nn.Module):
def forward(self, input):
return input.view(input.size(0), -1)
class Model(nn.Module):
def __init__(self, opt):
super(Model, self).__init__()
self.acoustic_modality = opt.acoustic_modality
self.visual_modality = opt.visual_modality
self.lexical_modality = opt.lexical_modality
self.acoustic_feature_dim = opt.acoustic_feature_dim
self.visual_feature_dim = opt.visual_feature_dim
self.lexical_feature_dim = opt.lexical_feature_dim
self.conv_width_v = opt.conv_width_v
self.conv_width_a = opt.conv_width_a
self.kernel_size_v = opt.kernel_size_v
self.kernel_size_a = opt.kernel_size_a
self.max_pool_width = opt.max_pool_width
self.rnn_layer_num_v = opt.rnn_layer_num_v
self.rnn_layer_num_a = opt.rnn_layer_num_a
self.rnn_width = opt.rnn_width
self.linear_width_l = opt.linear_width_l
self.linear_width = opt.linear_width
self.dropout_rate = opt.dropout_rate
self.conv1d_v1 = nn.Conv1d( in_channels=opt.visual_feature_dim,
out_channels=self.conv_width_v,
kernel_size=self.kernel_size_v,
padding=self.kernel_size_v-1)
self.conv1d_v2 = nn.Conv1d( in_channels=self.conv_width_v,
out_channels=self.conv_width_v,
kernel_size=self.kernel_size_v,
padding=self.kernel_size_v-1)
self.conv1d_v3 = nn.Conv1d( in_channels=self.conv_width_v,
out_channels=self.conv_width_v,
kernel_size=self.kernel_size_v,
padding=self.kernel_size_v-1)
self.conv1d_a1 = nn.Conv1d( in_channels=opt.acoustic_feature_dim,
out_channels=self.conv_width_a,
kernel_size=self.kernel_size_a,
padding=self.kernel_size_a-1)
self.conv1d_a2 = nn.Conv1d( in_channels=self.conv_width_a,
out_channels=self.conv_width_a,
kernel_size=self.kernel_size_a,
padding=self.kernel_size_a-1)
self.conv1d_a3 = nn.Conv1d( in_channels=self.conv_width_a,
out_channels=self.conv_width_a,
kernel_size=self.kernel_size_a,
padding=self.kernel_size_a-1)
self.maxpool = nn.MaxPool1d(self.max_pool_width)
self.gru_v = nn.GRU(input_size=self.conv_width_v,
num_layers=self.rnn_layer_num_v,
hidden_size=self.rnn_width,
batch_first=True)
self.gru_a = nn.GRU(input_size=self.conv_width_a,
num_layers=self.rnn_layer_num_a,
hidden_size=self.rnn_width,
batch_first=True)
self.linear_l = nn.Linear(self.lexical_feature_dim, self.linear_width_l)
self.batchnorm_v = nn.BatchNorm1d(self.rnn_width)
self.batchnorm_a = nn.BatchNorm1d(self.rnn_width)
self.batchnorm_l = nn.BatchNorm1d(self.linear_width_l)
self.dropout = nn.Dropout(self.dropout_rate)
width = 0
if self.acoustic_modality:
width += self.rnn_width
if self.visual_modality:
width += self.rnn_width
if self.lexical_modality:
width += self.linear_width_l
self.linear_1 = nn.Linear(width, self.linear_width)
self.linear_2 = nn.Linear(self.linear_width, 3)
self.softmax = nn.Softmax(dim=1)
self.relu = nn.ReLU()
def forward_v(self, x_v):
x = x_v
x = torch.transpose(x, 1, 2)
x = self.relu(self.maxpool(self.conv1d_v1(x)))
x = self.relu(self.maxpool(self.conv1d_v2(x)))
x = self.relu(self.maxpool(self.conv1d_v3(x)))
x = torch.transpose(x, 1, 2)
x, _ = self.gru_v(x)
x = torch.transpose(x, 1, 2)
x = F.adaptive_avg_pool1d(x,1)[:, :, -1]
x = self.batchnorm_v(self.dropout(x))
return x
def forward_a(self, x_a):
x = x_a
x = torch.transpose(x, 1, 2)
x = self.relu(self.maxpool(self.conv1d_a1(x)))
x = self.relu(self.maxpool(self.conv1d_a2(x)))
x = self.relu(self.maxpool(self.conv1d_a3(x)))
x = torch.transpose(x, 1, 2)
x, _ = self.gru_a(x)
x = torch.transpose(x, 1, 2)
x = F.adaptive_avg_pool1d(x,1)[:, :, -1]
x = self.batchnorm_a(self.dropout(x))
return x
def forward_l(self, x_l):
x = x_l
x = self.relu(self.linear_l(x))
x = self.batchnorm_l(self.dropout(x))
return x
def encoder(self, x_v, x_a, x_l):
if self.visual_modality:
x_v = self.forward_v(x_v)
if self.acoustic_modality:
x_a = self.forward_a(x_a)
if self.lexical_modality:
x_l = self.forward_l(x_l)
if self.visual_modality:
if self.acoustic_modality:
if self.lexical_modality:
x = torch.cat((x_v, x_a, x_l), 1)
else:
x = torch.cat((x_v, x_a), 1)
else:
if self.lexical_modality:
x = torch.cat((x_v, x_l), 1)
else:
x = x_v
else:
if self.acoustic_modality:
if self.lexical_modality:
x = torch.cat((x_a, x_l), 1)
else:
x = x_a
else:
x = x_l
return x
def recognizer(self, x):
x = self.relu(self.linear_1(x))
x = self.linear_2(x)
return x
def forward(self, x_v, x_a, x_l):
x = self.encoder(x_v, x_a, x_l)
x = self.recognizer(x)
return x
| [
"torch.nn.MaxPool1d",
"torch.nn.ReLU",
"torch.nn.Dropout",
"torch.nn.Softmax",
"torch.nn.functional.adaptive_avg_pool1d",
"torch.nn.init.xavier_uniform_",
"torch.transpose",
"torch.nn.BatchNorm1d",
"torch.nn.Linear",
"torch.nn.Conv1d",
"torch.cat",
"torch.nn.GRU"
] | [((350, 389), 'torch.nn.init.xavier_uniform_', 'torch.nn.init.xavier_uniform_', (['m.weight'], {}), '(m.weight)\n', (379, 389), False, 'import torch\n'), ((1535, 1686), 'torch.nn.Conv1d', 'nn.Conv1d', ([], {'in_channels': 'opt.visual_feature_dim', 'out_channels': 'self.conv_width_v', 'kernel_size': 'self.kernel_size_v', 'padding': '(self.kernel_size_v - 1)'}), '(in_channels=opt.visual_feature_dim, out_channels=self.\n conv_width_v, kernel_size=self.kernel_size_v, padding=self.\n kernel_size_v - 1)\n', (1544, 1686), True, 'import torch.nn as nn\n'), ((1809, 1949), 'torch.nn.Conv1d', 'nn.Conv1d', ([], {'in_channels': 'self.conv_width_v', 'out_channels': 'self.conv_width_v', 'kernel_size': 'self.kernel_size_v', 'padding': '(self.kernel_size_v - 1)'}), '(in_channels=self.conv_width_v, out_channels=self.conv_width_v,\n kernel_size=self.kernel_size_v, padding=self.kernel_size_v - 1)\n', (1818, 1949), True, 'import torch.nn as nn\n'), ((2078, 2218), 'torch.nn.Conv1d', 'nn.Conv1d', ([], {'in_channels': 'self.conv_width_v', 'out_channels': 'self.conv_width_v', 'kernel_size': 'self.kernel_size_v', 'padding': '(self.kernel_size_v - 1)'}), '(in_channels=self.conv_width_v, out_channels=self.conv_width_v,\n kernel_size=self.kernel_size_v, padding=self.kernel_size_v - 1)\n', (2087, 2218), True, 'import torch.nn as nn\n'), ((2348, 2501), 'torch.nn.Conv1d', 'nn.Conv1d', ([], {'in_channels': 'opt.acoustic_feature_dim', 'out_channels': 'self.conv_width_a', 'kernel_size': 'self.kernel_size_a', 'padding': '(self.kernel_size_a - 1)'}), '(in_channels=opt.acoustic_feature_dim, out_channels=self.\n conv_width_a, kernel_size=self.kernel_size_a, padding=self.\n kernel_size_a - 1)\n', (2357, 2501), True, 'import torch.nn as nn\n'), ((2624, 2764), 'torch.nn.Conv1d', 'nn.Conv1d', ([], {'in_channels': 'self.conv_width_a', 'out_channels': 'self.conv_width_a', 'kernel_size': 'self.kernel_size_a', 'padding': '(self.kernel_size_a - 1)'}), '(in_channels=self.conv_width_a, out_channels=self.conv_width_a,\n kernel_size=self.kernel_size_a, padding=self.kernel_size_a - 1)\n', (2633, 2764), True, 'import torch.nn as nn\n'), ((2893, 3033), 'torch.nn.Conv1d', 'nn.Conv1d', ([], {'in_channels': 'self.conv_width_a', 'out_channels': 'self.conv_width_a', 'kernel_size': 'self.kernel_size_a', 'padding': '(self.kernel_size_a - 1)'}), '(in_channels=self.conv_width_a, out_channels=self.conv_width_a,\n kernel_size=self.kernel_size_a, padding=self.kernel_size_a - 1)\n', (2902, 3033), True, 'import torch.nn as nn\n'), ((3161, 3194), 'torch.nn.MaxPool1d', 'nn.MaxPool1d', (['self.max_pool_width'], {}), '(self.max_pool_width)\n', (3173, 3194), True, 'import torch.nn as nn\n'), ((3217, 3336), 'torch.nn.GRU', 'nn.GRU', ([], {'input_size': 'self.conv_width_v', 'num_layers': 'self.rnn_layer_num_v', 'hidden_size': 'self.rnn_width', 'batch_first': '(True)'}), '(input_size=self.conv_width_v, num_layers=self.rnn_layer_num_v,\n hidden_size=self.rnn_width, batch_first=True)\n', (3223, 3336), True, 'import torch.nn as nn\n'), ((3439, 3558), 'torch.nn.GRU', 'nn.GRU', ([], {'input_size': 'self.conv_width_a', 'num_layers': 'self.rnn_layer_num_a', 'hidden_size': 'self.rnn_width', 'batch_first': '(True)'}), '(input_size=self.conv_width_a, num_layers=self.rnn_layer_num_a,\n hidden_size=self.rnn_width, batch_first=True)\n', (3445, 3558), True, 'import torch.nn as nn\n'), ((3664, 3720), 'torch.nn.Linear', 'nn.Linear', (['self.lexical_feature_dim', 'self.linear_width_l'], {}), '(self.lexical_feature_dim, self.linear_width_l)\n', (3673, 3720), True, 'import torch.nn as nn\n'), ((3749, 3779), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['self.rnn_width'], {}), '(self.rnn_width)\n', (3763, 3779), True, 'import torch.nn as nn\n'), ((3807, 3837), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['self.rnn_width'], {}), '(self.rnn_width)\n', (3821, 3837), True, 'import torch.nn as nn\n'), ((3865, 3900), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['self.linear_width_l'], {}), '(self.linear_width_l)\n', (3879, 3900), True, 'import torch.nn as nn\n'), ((3924, 3953), 'torch.nn.Dropout', 'nn.Dropout', (['self.dropout_rate'], {}), '(self.dropout_rate)\n', (3934, 3953), True, 'import torch.nn as nn\n'), ((4212, 4247), 'torch.nn.Linear', 'nn.Linear', (['width', 'self.linear_width'], {}), '(width, self.linear_width)\n', (4221, 4247), True, 'import torch.nn as nn\n'), ((4272, 4303), 'torch.nn.Linear', 'nn.Linear', (['self.linear_width', '(3)'], {}), '(self.linear_width, 3)\n', (4281, 4303), True, 'import torch.nn as nn\n'), ((4327, 4344), 'torch.nn.Softmax', 'nn.Softmax', ([], {'dim': '(1)'}), '(dim=1)\n', (4337, 4344), True, 'import torch.nn as nn\n'), ((4366, 4375), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (4373, 4375), True, 'import torch.nn as nn\n'), ((4435, 4459), 'torch.transpose', 'torch.transpose', (['x', '(1)', '(2)'], {}), '(x, 1, 2)\n', (4450, 4459), False, 'import torch\n'), ((4637, 4661), 'torch.transpose', 'torch.transpose', (['x', '(1)', '(2)'], {}), '(x, 1, 2)\n', (4652, 4661), False, 'import torch\n'), ((4703, 4727), 'torch.transpose', 'torch.transpose', (['x', '(1)', '(2)'], {}), '(x, 1, 2)\n', (4718, 4727), False, 'import torch\n'), ((4900, 4924), 'torch.transpose', 'torch.transpose', (['x', '(1)', '(2)'], {}), '(x, 1, 2)\n', (4915, 4924), False, 'import torch\n'), ((5102, 5126), 'torch.transpose', 'torch.transpose', (['x', '(1)', '(2)'], {}), '(x, 1, 2)\n', (5117, 5126), False, 'import torch\n'), ((5168, 5192), 'torch.transpose', 'torch.transpose', (['x', '(1)', '(2)'], {}), '(x, 1, 2)\n', (5183, 5192), False, 'import torch\n'), ((4740, 4767), 'torch.nn.functional.adaptive_avg_pool1d', 'F.adaptive_avg_pool1d', (['x', '(1)'], {}), '(x, 1)\n', (4761, 4767), True, 'import torch.nn.functional as F\n'), ((5205, 5232), 'torch.nn.functional.adaptive_avg_pool1d', 'F.adaptive_avg_pool1d', (['x', '(1)'], {}), '(x, 1)\n', (5226, 5232), True, 'import torch.nn.functional as F\n'), ((5851, 5880), 'torch.cat', 'torch.cat', (['(x_v, x_a, x_l)', '(1)'], {}), '((x_v, x_a, x_l), 1)\n', (5860, 5880), False, 'import torch\n'), ((5927, 5951), 'torch.cat', 'torch.cat', (['(x_v, x_a)', '(1)'], {}), '((x_v, x_a), 1)\n', (5936, 5951), False, 'import torch\n'), ((6036, 6060), 'torch.cat', 'torch.cat', (['(x_v, x_l)', '(1)'], {}), '((x_v, x_l), 1)\n', (6045, 6060), False, 'import torch\n'), ((6230, 6254), 'torch.cat', 'torch.cat', (['(x_a, x_l)', '(1)'], {}), '((x_a, x_l), 1)\n', (6239, 6254), False, 'import torch\n')] |
# Time: O(n)
# Space: O(n)
# 1297 weekly contest 168 12/21/2019
# Given a string s, return the maximum number of ocurrences of any substring under the following rules:
#
# The number of unique characters in the substring must be less than or equal to maxLetters.
# The substring size must be between minSize and maxSize inclusive.
# Constraints:
#
# 1 <= s.length <= 10^5
# 1 <= maxLetters <= 26
# 1 <= minSize <= maxSize <= min(26, s.length)
import collections
# rolling hash (Rabin-Karp Algorithm)
class Solution(object):
def maxFreq(self, s, maxLetters, minSize, maxSize):
"""
:type s: str
:type maxLetters: int
:type minSize: int
:type maxSize: int
:rtype: int
"""
M, p = 10**9+7, 113
power, rolling_hash = pow(p, minSize-1, M), 0
left = 0
lookup, count = collections.defaultdict(int), collections.defaultdict(int)
for right in xrange(len(s)):
count[s[right]] += 1
if right-left+1 > minSize:
count[s[left]] -= 1
rolling_hash = (rolling_hash - ord(s[left])*power) % M
if count[s[left]] == 0:
count.pop(s[left])
left += 1
rolling_hash = (rolling_hash*p + ord(s[right])) % M
if right-left+1 == minSize and len(count) <= maxLetters:
lookup[rolling_hash] += 1
return max(lookup.values() or [0])
# Time: O(m * n), m = 26
# Space: O(m * n)
class Solution2(object):
def maxFreq2(self, s, maxLetters, minSize, maxSize):
"""
:type s: str
:type maxLetters: int
:type minSize: int
:type maxSize: int
:rtype: int
"""
lookup = {}
for right in xrange(minSize-1, len(s)):
word = s[right-minSize+1:right+1]
if word in lookup:
lookup[word] += 1
elif len(collections.Counter(word)) <= maxLetters:
lookup[word] = 1
return max(lookup.values() or [0])
# O(n*size) where size = maxSize-minSize+1
def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:
cnt=collections.defaultdict(int)
n=len(s)
st=0
ed=st+minSize
while st<n:
letters=set(s[st:ed])
while len(letters)<=maxLetters and ed-st<=maxSize and ed<=n:
cnt[s[st:ed]]+=1
ed+=1
if ed<n:
letters.add(s[ed])
st+=1
ed=st+minSize
return max(cnt.values()) if cnt else 0
def maxFreq_506140166(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:
cnt=collections.defaultdict(int)
n=len(s)
st=ed=0
while st<n:
letters=set()
while len(letters)<=maxLetters and ed-st<=maxSize and ed<=n:
if ed-st>=minSize:
cnt[s[st:ed]]+=1
if ed<n:
letters.add(s[ed])
ed+=1
st+=1
ed=st
return max(cnt.values()) if cnt else 0
# TLE: O(n*size) where size = maxSize-minSize+1
# TLE because no pruning, when letterCnts > maxLetters, we should stop. But the problem is we
# cannot maintain the count of unique letters if exit the current iteration early.
def maxFreq_ming(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:
sizes = maxSize-minSize+1
dp = [[0] * 26 for _ in range(sizes)] # letters for all valid sizes
letterCnts = [0]*(sizes) # count of unique letters for all valid sizes
subsCounter = collections.defaultdict(int)
ans = 0
for j, c in enumerate(s):
for i in range(len(dp)):
dp[i][ord(c)-ord('a')] += 1
if dp[i][ord(c)-ord('a')] == 1:
letterCnts[i] += 1
if sum(dp[i]) == minSize+i:
pos_to_discard = j+1-minSize-i
if letterCnts[i] <= maxLetters:
subs = s[pos_to_discard:j+1]
subsCounter[subs] += 1
ans = max(ans, subsCounter[subs])
dp[i][ord(s[pos_to_discard])-ord('a')] -= 1
if dp[i][ord(s[pos_to_discard])-ord('a')] == 0:
letterCnts[i] -= 1
return ans
print(Solution().maxFreq("babcbceccaaacddbdaedbadcddcbdbcbaaddbcabcccbacebda",1,1,1)) # 13
print(Solution().maxFreq("aababcaab", 2,3,4)) # 2
print(Solution().maxFreq("aaaa", 1,3,3)) #2
print(Solution().maxFreq("aabcabcab",2,2,3)) # 3
print(Solution().maxFreq("abcde",2,3,3)) # 0
| [
"collections.Counter",
"collections.defaultdict"
] | [((2196, 2224), 'collections.defaultdict', 'collections.defaultdict', (['int'], {}), '(int)\n', (2219, 2224), False, 'import collections\n'), ((2736, 2764), 'collections.defaultdict', 'collections.defaultdict', (['int'], {}), '(int)\n', (2759, 2764), False, 'import collections\n'), ((3715, 3743), 'collections.defaultdict', 'collections.defaultdict', (['int'], {}), '(int)\n', (3738, 3743), False, 'import collections\n'), ((860, 888), 'collections.defaultdict', 'collections.defaultdict', (['int'], {}), '(int)\n', (883, 888), False, 'import collections\n'), ((890, 918), 'collections.defaultdict', 'collections.defaultdict', (['int'], {}), '(int)\n', (913, 918), False, 'import collections\n'), ((1935, 1960), 'collections.Counter', 'collections.Counter', (['word'], {}), '(word)\n', (1954, 1960), False, 'import collections\n')] |
import copy
import logging
from api.models import Transaction, BonusTransaction, Order, Tag, OrderItem
from api.models.guest import Guest
from api.models.label import Label
from api.tests.data.guests import TestGuests
from api.tests.data.statuses import TestStatuses
from api.tests.data.users import TestUsers
from api.tests.utils.combined_test_case import CombinedTestCase
LOG = logging.getLogger(__name__)
class GuestViewTestCase(CombinedTestCase):
REFRESH_OBJECTS = [TestGuests]
def test_list(self):
self.login(TestUsers.RECEPTION_EXT)
self.perform_list_test('/guests', TestGuests.SAVED)
def test_list_ordered(self):
self.login(TestUsers.RECEPTION_EXT)
response = self.client.get('/guests?ordering=-code')
self.assertPksEqual(response.data, [TestGuests.SHEELAH, TestGuests.ROBY])
response = self.client.get('/guests?ordering=balance')
self.assertPksEqual(response.data, [TestGuests.SHEELAH, TestGuests.ROBY])
def test_list_search(self):
self.login(TestUsers.RECEPTION_EXT)
response = self.client.get('/guests?code=001')
self.assertEqual(response.status_code, 200)
self.assertPksEqual(response.data, [TestGuests.ROBY])
response = self.client.get('/guests?name=roby')
self.assertPksEqual(response.data, [TestGuests.ROBY])
response = self.client.get('/guests?mail=rbrush')
self.assertPksEqual(response.data, [TestGuests.ROBY])
response = self.client.get(f'/guests?status={TestStatuses.PAID.id}')
self.assertPksEqual(response.data, [TestGuests.ROBY])
response = self.client.get('/guests?status=null')
self.assertPksEqual(response.data, [])
url = '/guests?code=DEMO&name=el&mail=sohu.com'
expected_response = copy.deepcopy(self.RESPONSES[f'GET{url}'])
self.patch_json_ids(expected_response)
response = self.client.get(url)
self.assertPksEqual(response.data, [TestGuests.ROBY])
self.assertJSONEqual(response.content, expected_response)
url = f'/guests?card={TestGuests.ROBY.card}'
expected_response = copy.deepcopy(self.RESPONSES[f'GET{url}'])
self.patch_json_ids(expected_response)
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertJSONEqual(response.content, expected_response)
response = self.client.get('f/guests?card=notfound')
self.assertEqual(response.status_code, 404)
def test_create_min(self):
self.login(TestUsers.RECEPTION_EXT)
self.perform_create_test('/guests', TestGuests, '#min', '#min')
def test_create_max(self):
self.login(TestUsers.RECEPTION_EXT)
self.perform_create_test('/guests', TestGuests, '#max', '#max')
def test_update(self):
self.login(TestUsers.RECEPTION_EXT)
self.perform_update_test('/guests', TestGuests)
def test_patch_readonly(self):
self.login(TestUsers.ADMIN_EXT)
mutable_fields = {
'checked_in': "2019-12-31T22:01:00Z",
'code': '123',
'name': 'Jimmy',
'mail': '<EMAIL>',
'status': TestStatuses.PAID.id,
'card': '1212',
}
immutable_fields = {
'balance': '5.00',
'bonus': '3.00'
}
self.assertPatchReadonly(f'/guests/{TestGuests.ROBY.id}', mutable_fields, immutable_fields)
def test_list_create_update(self):
self.login(TestUsers.RECEPTION_EXT)
identifier = 'PATCH/guests/list_update'
expected_response = copy.deepcopy(self.RESPONSES[identifier])
request = self.REQUESTS[identifier]
response = self.client.patch('/guests/list_update', request)
self.assertEqual(response.status_code, 201)
self.patch_object_ids(expected_response, response.data)
self.assertValueEqual(
Guest.objects.all(),
[TestGuests.ROBY_LIST_PATCHED, TestGuests.SHEELAH, TestGuests.JOHANNA_MIN]
)
self.patch_json_ids(expected_response)
self.assertJSONEqual(response.content, expected_response)
def test_delete_all(self):
self.login(TestUsers.ADMIN_EXT)
response = self.client.delete('/guests/delete_all')
self.assertEqual(response.status_code, 204)
self.assertValueEqual(Guest.objects.all(), [])
self.assertValueEqual(Transaction.objects.all(), [])
self.assertValueEqual(BonusTransaction.objects.all(), [])
self.assertValueEqual(Order.objects.all(), [])
self.assertValueEqual(OrderItem.objects.all(), [])
self.assertValueEqual(Tag.objects.all(), [])
self.assertValueEqual(Label.objects.all(), [])
def test_permissions(self):
self.perform_permission_test(
'/guests',
list_users=[TestUsers.ADMIN_EXT, TestUsers.RECEPTION_EXT],
list_by_card_users=[TestUsers.ADMIN_EXT, TestUsers.TERMINAL_EXT, TestUsers.RECEPTION_EXT],
retrieve_users=[TestUsers.ADMIN_EXT, TestUsers.RECEPTION_EXT],
create_users=[TestUsers.ADMIN_EXT, TestUsers.RECEPTION_EXT],
update_users=[TestUsers.ADMIN_EXT, TestUsers.RECEPTION_EXT],
delete_users=[],
card_parameter='card',
card=TestGuests.ROBY.card,
detail_id=TestGuests.ROBY.id,
create_suffix='#max'
)
self.assertPermissions(
lambda: self.client.get(f'/guests?mail={TestGuests.ROBY.mail}'),
[TestUsers.ADMIN_EXT, TestUsers.RECEPTION_EXT]
)
self.assertPermissions(
lambda: self.client.patch('/guests/list_update', self.REQUESTS['PATCH/guests/list_update']),
[TestUsers.ADMIN_EXT, TestUsers.RECEPTION_EXT]
)
self.assertPermissions(
lambda: self.client.delete('/guests/delete_all'),
[TestUsers.ADMIN_EXT]
)
def test_constraints(self):
self.login(TestUsers.ADMIN_EXT)
# Empty card is allowed.
body = {**self.REQUESTS['POST/guests#max'], **{'card': None}}
response = self.client.post('/guests', body)
self.assertEqual(response.status_code, 201)
# Code has to be unique.
body = {**self.REQUESTS['POST/guests#max'], **{'code': TestGuests.ROBY.code, 'card': 'CARD1'}}
response = self.client.post('/guests', body)
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json()['code'][0], 'guest with this code already exists.')
# Card has to be unique.
body = {**self.REQUESTS['POST/guests#max'], **{'code': 'CODE1', 'card': TestGuests.ROBY.card}}
response = self.client.post('/guests', body)
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json()['card'][0], 'guest with this card already exists.')
def test_str(self):
LOG.debug(TestGuests.ROBY)
self.assertEqual(
str(TestGuests.ROBY),
f'Guest(id={TestGuests.ROBY.id},name="<NAME>",code="DEMO-00001")'
)
| [
"logging.getLogger",
"api.models.Transaction.objects.all",
"api.models.Order.objects.all",
"api.models.label.Label.objects.all",
"api.models.OrderItem.objects.all",
"copy.deepcopy",
"api.models.BonusTransaction.objects.all",
"api.models.Tag.objects.all",
"api.models.guest.Guest.objects.all"
] | [((382, 409), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (399, 409), False, 'import logging\n'), ((1806, 1848), 'copy.deepcopy', 'copy.deepcopy', (["self.RESPONSES[f'GET{url}']"], {}), "(self.RESPONSES[f'GET{url}'])\n", (1819, 1848), False, 'import copy\n'), ((2146, 2188), 'copy.deepcopy', 'copy.deepcopy', (["self.RESPONSES[f'GET{url}']"], {}), "(self.RESPONSES[f'GET{url}'])\n", (2159, 2188), False, 'import copy\n'), ((3613, 3654), 'copy.deepcopy', 'copy.deepcopy', (['self.RESPONSES[identifier]'], {}), '(self.RESPONSES[identifier])\n', (3626, 3654), False, 'import copy\n'), ((3928, 3947), 'api.models.guest.Guest.objects.all', 'Guest.objects.all', ([], {}), '()\n', (3945, 3947), False, 'from api.models.guest import Guest\n'), ((4373, 4392), 'api.models.guest.Guest.objects.all', 'Guest.objects.all', ([], {}), '()\n', (4390, 4392), False, 'from api.models.guest import Guest\n'), ((4428, 4453), 'api.models.Transaction.objects.all', 'Transaction.objects.all', ([], {}), '()\n', (4451, 4453), False, 'from api.models import Transaction, BonusTransaction, Order, Tag, OrderItem\n'), ((4489, 4519), 'api.models.BonusTransaction.objects.all', 'BonusTransaction.objects.all', ([], {}), '()\n', (4517, 4519), False, 'from api.models import Transaction, BonusTransaction, Order, Tag, OrderItem\n'), ((4555, 4574), 'api.models.Order.objects.all', 'Order.objects.all', ([], {}), '()\n', (4572, 4574), False, 'from api.models import Transaction, BonusTransaction, Order, Tag, OrderItem\n'), ((4610, 4633), 'api.models.OrderItem.objects.all', 'OrderItem.objects.all', ([], {}), '()\n', (4631, 4633), False, 'from api.models import Transaction, BonusTransaction, Order, Tag, OrderItem\n'), ((4669, 4686), 'api.models.Tag.objects.all', 'Tag.objects.all', ([], {}), '()\n', (4684, 4686), False, 'from api.models import Transaction, BonusTransaction, Order, Tag, OrderItem\n'), ((4722, 4741), 'api.models.label.Label.objects.all', 'Label.objects.all', ([], {}), '()\n', (4739, 4741), False, 'from api.models.label import Label\n')] |
import re
from typing import Any, Type, Tuple, Union, Iterable
from nonebot.typing import overrides
from nonebot.adapters import Message as BaseMessage
from nonebot.adapters import MessageSegment as BaseMessageSegment
from .utils import escape, unescape
from .api import Message as GuildMessage
from .api import MessageArk, MessageEmbed
class MessageSegment(BaseMessageSegment["Message"]):
@classmethod
@overrides(BaseMessageSegment)
def get_message_class(cls) -> Type["Message"]:
return Message
@staticmethod
def ark(ark: MessageArk) -> "Ark":
return Ark("ark", data={"ark": ark})
@staticmethod
def embed(embed: MessageEmbed) -> "Embed":
return Embed("embed", data={"embed": embed})
@staticmethod
def emoji(id: str) -> "Emoji":
return Emoji("emoji", data={"id": id})
@staticmethod
def image(url: str) -> "Attachment":
return Attachment("attachment", data={"url": url})
@staticmethod
def mention_user(user_id: int) -> "MentionUser":
return MentionUser("mention_user", {"user_id": str(user_id)})
@staticmethod
def mention_channel(channel_id: int) -> "MentionChannel":
return MentionChannel("mention_channel", {"channel_id": str(channel_id)})
@staticmethod
def text(content: str) -> "Text":
return Text("text", {"text": content})
@overrides(BaseMessageSegment)
def is_text(self) -> bool:
return self.type == "text"
class Text(MessageSegment):
@overrides(MessageSegment)
def __str__(self) -> str:
return escape(self.data["text"])
class Emoji(MessageSegment):
@overrides(MessageSegment)
def __str__(self) -> str:
return f"<emoji:{self.data['id']}>"
class MentionUser(MessageSegment):
@overrides(MessageSegment)
def __str__(self) -> str:
return f"<@{self.data['user_id']}>"
class MentionEveryone(MessageSegment):
@overrides(MessageSegment)
def __str__(self) -> str:
return "@everyone"
class MentionChannel(MessageSegment):
@overrides(MessageSegment)
def __str__(self) -> str:
return f"<#{self.data['channel_id']}>"
class Attachment(MessageSegment):
@overrides(MessageSegment)
def __str__(self) -> str:
return f"<attachment:{self.data['url']}>"
class Embed(MessageSegment):
@overrides(MessageSegment)
def __str__(self) -> str:
return f"<embed:{self.data['embed']}>"
class Ark(MessageSegment):
@overrides(MessageSegment)
def __str__(self) -> str:
return f"<ark:{self.data['ark']}>"
class Message(BaseMessage[MessageSegment]):
@classmethod
@overrides(BaseMessage)
def get_segment_class(cls) -> Type[MessageSegment]:
return MessageSegment
@overrides(BaseMessage)
def __add__(
self, other: Union[str, MessageSegment, Iterable[MessageSegment]]
) -> "Message":
return super(Message, self).__add__(
MessageSegment.text(other) if isinstance(other, str) else other
)
@overrides(BaseMessage)
def __radd__(
self, other: Union[str, MessageSegment, Iterable[MessageSegment]]
) -> "Message":
return super(Message, self).__radd__(
MessageSegment.text(other) if isinstance(other, str) else other
)
@staticmethod
@overrides(BaseMessage)
def _construct(msg: str) -> Iterable[MessageSegment]:
text_begin = 0
for embed in re.finditer(
r"\<(?P<type>(?:@|#|emoji:))!?(?P<id>\w+?)\>",
msg,
):
content = msg[text_begin : embed.pos + embed.start()]
if content:
yield Text("text", {"text": unescape(content)})
text_begin = embed.pos + embed.end()
if embed.group("type") == "@":
yield MentionUser("mention_user", {"user_id": embed.group("id")})
elif embed.group("type") == "#":
yield MentionChannel(
"mention_channel", {"channel_id": embed.group("id")}
)
else:
yield Emoji("emoji", {"id": embed.group("id")})
content = msg[text_begin:]
if content:
yield Text("text", {"text": unescape(msg[text_begin:])})
@classmethod
def from_guild_message(cls, message: GuildMessage) -> "Message":
msg = Message()
if message.content:
msg.extend(Message(message.content))
if message.attachments:
msg.extend(
Attachment("attachment", data={"url": seg.url})
for seg in message.attachments
if seg.url
)
if message.embeds:
msg.extend(Embed("embed", data={"embed": seg}) for seg in message.embeds)
if message.ark:
msg.append(Ark("ark", data={"ark": message.ark}))
return msg
def extract_content(self) -> str:
return "".join(
str(seg)
for seg in self
if seg.type
in ("text", "emoji", "mention_user", "mention_everyone", "mention_channel")
)
| [
"re.finditer",
"nonebot.typing.overrides"
] | [((417, 446), 'nonebot.typing.overrides', 'overrides', (['BaseMessageSegment'], {}), '(BaseMessageSegment)\n', (426, 446), False, 'from nonebot.typing import overrides\n'), ((1378, 1407), 'nonebot.typing.overrides', 'overrides', (['BaseMessageSegment'], {}), '(BaseMessageSegment)\n', (1387, 1407), False, 'from nonebot.typing import overrides\n'), ((1509, 1534), 'nonebot.typing.overrides', 'overrides', (['MessageSegment'], {}), '(MessageSegment)\n', (1518, 1534), False, 'from nonebot.typing import overrides\n'), ((1642, 1667), 'nonebot.typing.overrides', 'overrides', (['MessageSegment'], {}), '(MessageSegment)\n', (1651, 1667), False, 'from nonebot.typing import overrides\n'), ((1784, 1809), 'nonebot.typing.overrides', 'overrides', (['MessageSegment'], {}), '(MessageSegment)\n', (1793, 1809), False, 'from nonebot.typing import overrides\n'), ((1930, 1955), 'nonebot.typing.overrides', 'overrides', (['MessageSegment'], {}), '(MessageSegment)\n', (1939, 1955), False, 'from nonebot.typing import overrides\n'), ((2058, 2083), 'nonebot.typing.overrides', 'overrides', (['MessageSegment'], {}), '(MessageSegment)\n', (2067, 2083), False, 'from nonebot.typing import overrides\n'), ((2202, 2227), 'nonebot.typing.overrides', 'overrides', (['MessageSegment'], {}), '(MessageSegment)\n', (2211, 2227), False, 'from nonebot.typing import overrides\n'), ((2344, 2369), 'nonebot.typing.overrides', 'overrides', (['MessageSegment'], {}), '(MessageSegment)\n', (2353, 2369), False, 'from nonebot.typing import overrides\n'), ((2481, 2506), 'nonebot.typing.overrides', 'overrides', (['MessageSegment'], {}), '(MessageSegment)\n', (2490, 2506), False, 'from nonebot.typing import overrides\n'), ((2648, 2670), 'nonebot.typing.overrides', 'overrides', (['BaseMessage'], {}), '(BaseMessage)\n', (2657, 2670), False, 'from nonebot.typing import overrides\n'), ((2763, 2785), 'nonebot.typing.overrides', 'overrides', (['BaseMessage'], {}), '(BaseMessage)\n', (2772, 2785), False, 'from nonebot.typing import overrides\n'), ((3034, 3056), 'nonebot.typing.overrides', 'overrides', (['BaseMessage'], {}), '(BaseMessage)\n', (3043, 3056), False, 'from nonebot.typing import overrides\n'), ((3325, 3347), 'nonebot.typing.overrides', 'overrides', (['BaseMessage'], {}), '(BaseMessage)\n', (3334, 3347), False, 'from nonebot.typing import overrides\n'), ((3450, 3515), 're.finditer', 're.finditer', (['"""\\\\<(?P<type>(?:@|#|emoji:))!?(?P<id>\\\\w+?)\\\\>"""', 'msg'], {}), "('\\\\<(?P<type>(?:@|#|emoji:))!?(?P<id>\\\\w+?)\\\\>', msg)\n", (3461, 3515), False, 'import re\n')] |
# Future
from __future__ import annotations
# Standard Library
from collections.abc import Callable
from typing import Literal, TypeVar
# Packages
from discord.ext import commands
# Local
from cd import custom, exceptions
__all__ = (
"is_player_connected",
)
T = TypeVar("T")
def is_player_connected() -> Callable[[T], T]:
async def predicate(ctx: custom.Context) -> Literal[True]:
if not ctx.voice_client or not ctx.voice_client.is_connected():
raise exceptions.EmbedError(description="I'm not connected to any voice channels.")
return True
return commands.check(predicate)
| [
"discord.ext.commands.check",
"cd.exceptions.EmbedError",
"typing.TypeVar"
] | [((274, 286), 'typing.TypeVar', 'TypeVar', (['"""T"""'], {}), "('T')\n", (281, 286), False, 'from typing import Literal, TypeVar\n'), ((602, 627), 'discord.ext.commands.check', 'commands.check', (['predicate'], {}), '(predicate)\n', (616, 627), False, 'from discord.ext import commands\n'), ((491, 568), 'cd.exceptions.EmbedError', 'exceptions.EmbedError', ([], {'description': '"""I\'m not connected to any voice channels."""'}), '(description="I\'m not connected to any voice channels.")\n', (512, 568), False, 'from cd import custom, exceptions\n')] |
"""Base test for TalisMUD tests.
It creates an in-memory database for each test, so they run in independent
environments.
"""
import unittest
from pony.orm import db_session
from data.base import db
from data.properties import LazyPropertyDescriptor
# Bind to a temporary database
db.bind(provider="sqlite", filename=":memory:")
db.generate_mapping(create_tables=True)
class BaseTest(unittest.TestCase):
"""Base class for TalisMUD unittests."""
def setUp(self):
"""Called before each test method."""
db.create_tables()
db_session._enter()
def tearDown(self):
"""Called after the test method."""
# Reset lazy properties
for entity in db.entities.values():
for key in dir(entity):
value = getattr(entity, key)
if isinstance(value, LazyPropertyDescriptor):
value.memory.clear()
db_session.__exit__()
db.drop_all_tables(with_all_data=True)
| [
"data.base.db.entities.values",
"data.base.db.create_tables",
"data.base.db.drop_all_tables",
"data.base.db.generate_mapping",
"data.base.db.bind",
"pony.orm.db_session._enter",
"pony.orm.db_session.__exit__"
] | [((287, 334), 'data.base.db.bind', 'db.bind', ([], {'provider': '"""sqlite"""', 'filename': '""":memory:"""'}), "(provider='sqlite', filename=':memory:')\n", (294, 334), False, 'from data.base import db\n'), ((335, 374), 'data.base.db.generate_mapping', 'db.generate_mapping', ([], {'create_tables': '(True)'}), '(create_tables=True)\n', (354, 374), False, 'from data.base import db\n'), ((533, 551), 'data.base.db.create_tables', 'db.create_tables', ([], {}), '()\n', (549, 551), False, 'from data.base import db\n'), ((560, 579), 'pony.orm.db_session._enter', 'db_session._enter', ([], {}), '()\n', (577, 579), False, 'from pony.orm import db_session\n'), ((703, 723), 'data.base.db.entities.values', 'db.entities.values', ([], {}), '()\n', (721, 723), False, 'from data.base import db\n'), ((917, 938), 'pony.orm.db_session.__exit__', 'db_session.__exit__', ([], {}), '()\n', (936, 938), False, 'from pony.orm import db_session\n'), ((947, 985), 'data.base.db.drop_all_tables', 'db.drop_all_tables', ([], {'with_all_data': '(True)'}), '(with_all_data=True)\n', (965, 985), False, 'from data.base import db\n')] |
import requests
import sys
requests.put(f"http://localhost:9200/{sys.argv[1]}?pretty")
headers = {"Content-Type": "application/x-ndjson"}
data = open(sys.argv[2], "rb").read()
requests.post(
f"http://localhost:9200/{sys.argv[1]}/_bulk?pretty", headers=headers, data=data
)
| [
"requests.post",
"requests.put"
] | [((31, 90), 'requests.put', 'requests.put', (['f"""http://localhost:9200/{sys.argv[1]}?pretty"""'], {}), "(f'http://localhost:9200/{sys.argv[1]}?pretty')\n", (43, 90), False, 'import requests\n'), ((189, 288), 'requests.post', 'requests.post', (['f"""http://localhost:9200/{sys.argv[1]}/_bulk?pretty"""'], {'headers': 'headers', 'data': 'data'}), "(f'http://localhost:9200/{sys.argv[1]}/_bulk?pretty', headers=\n headers, data=data)\n", (202, 288), False, 'import requests\n')] |
import torch
import torch.nn.functional as F
from torch.optim import Adam
from torch.utils.data import DataLoader
import torchvision
from torchvision import transforms
from torchvision.models import resnet101
import pytorch_lightning as pl
from model.AEINet import ADDGenerator, MultilevelAttributesEncoder
from model.MultiScaleDiscriminator import MultiscaleDiscriminator
from model.loss import GANLoss, AEI_Loss
from dataset import *
class AEINet(pl.LightningModule):
def __init__(self, hp):
super(AEINet, self).__init__()
self.hp = hp
self.G = ADDGenerator(hp.arcface.vector_size)
self.E = MultilevelAttributesEncoder()
self.D = MultiscaleDiscriminator(3)
self.Z = resnet101(num_classes=256)
self.Z.load_state_dict(torch.load(hp.arcface.chkpt_path, map_location='cpu'))
self.Loss_GAN = GANLoss()
self.Loss_E_G = AEI_Loss()
def forward(self, target_img, source_img):
z_id = self.Z(F.interpolate(source_img, size=112, mode='bilinear'))
z_id = F.normalize(z_id)
z_id = z_id.detach()
feature_map = self.E(target_img)
output = self.G(z_id, feature_map)
output_z_id = self.Z(F.interpolate(output, size=112, mode='bilinear'))
output_z_id = F.normalize(output_z_id)
output_feature_map = self.E(output)
return output, z_id, output_z_id, feature_map, output_feature_map
def training_step(self, batch, batch_idx, optimizer_idx):
target_img, source_img, same = batch
if optimizer_idx == 0:
output, z_id, output_z_id, feature_map, output_feature_map = self(target_img, source_img)
self.generated_img = output
output_multi_scale_val = self.D(output)
loss_GAN = self.Loss_GAN(output_multi_scale_val, True, for_discriminator=False)
loss_E_G, loss_att, loss_id, loss_rec = self.Loss_E_G(target_img, output, feature_map, output_feature_map, z_id,
output_z_id, same)
loss_G = loss_E_G + loss_GAN
self.logger.experiment.add_scalar("Loss G", loss_G.item(), self.global_step)
self.logger.experiment.add_scalar("Attribute Loss", loss_att.item(), self.global_step)
self.logger.experiment.add_scalar("ID Loss", loss_id.item(), self.global_step)
self.logger.experiment.add_scalar("Reconstruction Loss", loss_rec.item(), self.global_step)
self.logger.experiment.add_scalar("GAN Loss", loss_GAN.item(), self.global_step)
return loss_G
else:
multi_scale_val = self.D(target_img)
output_multi_scale_val = self.D(self.generated_img.detach())
loss_D_fake = self.Loss_GAN(multi_scale_val, True)
loss_D_real = self.Loss_GAN(output_multi_scale_val, False)
loss_D = loss_D_fake + loss_D_real
self.logger.experiment.add_scalar("Loss D", loss_D.item(), self.global_step)
return loss_D
def validation_step(self, batch, batch_idx):
target_img, source_img, same = batch
output, z_id, output_z_id, feature_map, output_feature_map = self(target_img, source_img)
self.generated_img = output
output_multi_scale_val = self.D(output)
loss_GAN = self.Loss_GAN(output_multi_scale_val, True, for_discriminator=False)
loss_E_G, loss_att, loss_id, loss_rec = self.Loss_E_G(target_img, output, feature_map, output_feature_map,
z_id, output_z_id, same)
loss_G = loss_E_G + loss_GAN
return {"loss": loss_G, 'target': target_img[0].cpu(), 'source': source_img[0].cpu(), "output": output[0].cpu(), }
def validation_end(self, outputs):
loss = torch.stack([x["loss"] for x in outputs]).mean()
validation_image = []
for x in outputs:
validation_image = validation_image + [x['target'], x['source'], x["output"]]
validation_image = torchvision.utils.make_grid(validation_image, nrow=3)
self.logger.experiment.add_scalar("Validation Loss", loss.item(), self.global_step)
self.logger.experiment.add_image("Validation Image", validation_image, self.global_step)
return {"loss": loss, "image": validation_image, }
def configure_optimizers(self):
lr_g = self.hp.model.learning_rate_E_G
lr_d = self.hp.model.learning_rate_D
b1 = self.hp.model.beta1
b2 = self.hp.model.beta2
opt_g = torch.optim.Adam(list(self.G.parameters()) + list(self.E.parameters()), lr=lr_g, betas=(b1, b2))
opt_d = torch.optim.Adam(self.D.parameters(), lr=lr_d, betas=(b1, b2))
return [opt_g, opt_d], []
def train_dataloader(self):
# transforms.Resize((256, 256)),
# transforms.CenterCrop((256, 256)),
transform = transforms.Compose([
transforms.ToTensor(),
])
dataset = AEI_Dataset(self.hp.data.dataset_dir, transform=transform)
return DataLoader(dataset, batch_size=self.hp.model.batch_size, num_workers=self.hp.model.num_workers, shuffle=True, drop_last=True)
def val_dataloader(self):
transform = transforms.Compose([
transforms.Resize((256, 256)),
transforms.CenterCrop((256, 256)),
transforms.ToTensor(),
])
dataset = AEI_Val_Dataset(self.hp.data.valset_dir, transform=transform)
return DataLoader(dataset, batch_size=1, shuffle=False)
| [
"torchvision.transforms.CenterCrop",
"model.AEINet.ADDGenerator",
"model.loss.AEI_Loss",
"torch.load",
"torch.stack",
"torchvision.models.resnet101",
"torchvision.transforms.Resize",
"torch.nn.functional.normalize",
"model.AEINet.MultilevelAttributesEncoder",
"model.loss.GANLoss",
"model.MultiSc... | [((582, 618), 'model.AEINet.ADDGenerator', 'ADDGenerator', (['hp.arcface.vector_size'], {}), '(hp.arcface.vector_size)\n', (594, 618), False, 'from model.AEINet import ADDGenerator, MultilevelAttributesEncoder\n'), ((636, 665), 'model.AEINet.MultilevelAttributesEncoder', 'MultilevelAttributesEncoder', ([], {}), '()\n', (663, 665), False, 'from model.AEINet import ADDGenerator, MultilevelAttributesEncoder\n'), ((683, 709), 'model.MultiScaleDiscriminator.MultiscaleDiscriminator', 'MultiscaleDiscriminator', (['(3)'], {}), '(3)\n', (706, 709), False, 'from model.MultiScaleDiscriminator import MultiscaleDiscriminator\n'), ((728, 754), 'torchvision.models.resnet101', 'resnet101', ([], {'num_classes': '(256)'}), '(num_classes=256)\n', (737, 754), False, 'from torchvision.models import resnet101\n'), ((866, 875), 'model.loss.GANLoss', 'GANLoss', ([], {}), '()\n', (873, 875), False, 'from model.loss import GANLoss, AEI_Loss\n'), ((900, 910), 'model.loss.AEI_Loss', 'AEI_Loss', ([], {}), '()\n', (908, 910), False, 'from model.loss import GANLoss, AEI_Loss\n'), ((1051, 1068), 'torch.nn.functional.normalize', 'F.normalize', (['z_id'], {}), '(z_id)\n', (1062, 1068), True, 'import torch.nn.functional as F\n'), ((1286, 1310), 'torch.nn.functional.normalize', 'F.normalize', (['output_z_id'], {}), '(output_z_id)\n', (1297, 1310), True, 'import torch.nn.functional as F\n'), ((4053, 4106), 'torchvision.utils.make_grid', 'torchvision.utils.make_grid', (['validation_image'], {'nrow': '(3)'}), '(validation_image, nrow=3)\n', (4080, 4106), False, 'import torchvision\n'), ((5082, 5212), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset'], {'batch_size': 'self.hp.model.batch_size', 'num_workers': 'self.hp.model.num_workers', 'shuffle': '(True)', 'drop_last': '(True)'}), '(dataset, batch_size=self.hp.model.batch_size, num_workers=self.\n hp.model.num_workers, shuffle=True, drop_last=True)\n', (5092, 5212), False, 'from torch.utils.data import DataLoader\n'), ((5511, 5559), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset'], {'batch_size': '(1)', 'shuffle': '(False)'}), '(dataset, batch_size=1, shuffle=False)\n', (5521, 5559), False, 'from torch.utils.data import DataLoader\n'), ((786, 839), 'torch.load', 'torch.load', (['hp.arcface.chkpt_path'], {'map_location': '"""cpu"""'}), "(hp.arcface.chkpt_path, map_location='cpu')\n", (796, 839), False, 'import torch\n'), ((982, 1034), 'torch.nn.functional.interpolate', 'F.interpolate', (['source_img'], {'size': '(112)', 'mode': '"""bilinear"""'}), "(source_img, size=112, mode='bilinear')\n", (995, 1034), True, 'import torch.nn.functional as F\n'), ((1214, 1262), 'torch.nn.functional.interpolate', 'F.interpolate', (['output'], {'size': '(112)', 'mode': '"""bilinear"""'}), "(output, size=112, mode='bilinear')\n", (1227, 1262), True, 'import torch.nn.functional as F\n'), ((3831, 3872), 'torch.stack', 'torch.stack', (["[x['loss'] for x in outputs]"], {}), "([x['loss'] for x in outputs])\n", (3842, 3872), False, 'import torch\n'), ((4952, 4973), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (4971, 4973), False, 'from torchvision import transforms\n'), ((5292, 5321), 'torchvision.transforms.Resize', 'transforms.Resize', (['(256, 256)'], {}), '((256, 256))\n', (5309, 5321), False, 'from torchvision import transforms\n'), ((5335, 5368), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(256, 256)'], {}), '((256, 256))\n', (5356, 5368), False, 'from torchvision import transforms\n'), ((5382, 5403), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (5401, 5403), False, 'from torchvision import transforms\n')] |
from configs import cfg
from src.utils.record_log import _logger
import numpy as np
import tensorflow as tf
import scipy.stats as stats
class Evaluator(object):
def __init__(self, model):
self.model = model
self.global_step = model.global_step
## ---- summary----
self.build_summary()
self.writer = tf.summary.FileWriter(cfg.summary_dir)
def get_evaluation(self, sess, dataset_obj, global_step=None):
_logger.add()
_logger.add('getting evaluation result for %s' % dataset_obj.data_type)
logits_list, loss_list = [], []
target_score_list, predicted_score_list = [], []
for sample_batch, _, _, _ in dataset_obj.generate_batch_sample_iter():
feed_dict = self.model.get_feed_dict(sample_batch, 'dev')
logits, loss, predicted_score = sess.run([self.model.logits, self.model.loss,
self.model.predicted_score], feed_dict)
logits_list.append(np.argmax(logits, -1))
loss_list.append(loss)
predicted_score_list.append(predicted_score)
for sample in sample_batch:
target_score_list.append(sample['relatedness_score'])
logits_array = np.concatenate(logits_list, 0)
loss_value = np.mean(loss_list)
target_scores = np.array(target_score_list)
predicted_scores = np.concatenate(predicted_score_list, 0)
# pearson, spearman, mse
pearson_value = stats.pearsonr(target_scores, predicted_scores)[0]
spearman_value = stats.spearmanr(target_scores, predicted_scores)[0]
mse_value = np.mean((target_scores - predicted_scores) ** 2)
# todo: analysis
# analysis_save_dir = cfg.mkdir(cfg.answer_dir, 'gs_%d' % global_step or 0)
# OutputAnalysis.do_analysis(dataset_obj, logits_array, accu_array, analysis_save_dir,
# cfg.fine_grained)
if global_step is not None:
if dataset_obj.data_type == 'train':
summary_feed_dict = {
self.train_loss: loss_value,
self.train_pearson: pearson_value,
self.train_spearman: spearman_value,
self.train_mse: mse_value,
}
summary = sess.run(self.train_summaries, summary_feed_dict)
self.writer.add_summary(summary, global_step)
elif dataset_obj.data_type == 'dev':
summary_feed_dict = {
self.dev_loss: loss_value,
self.dev_pearson: pearson_value,
self.dev_spearman: spearman_value,
self.dev_mse: mse_value,
}
summary = sess.run(self.dev_summaries, summary_feed_dict)
self.writer.add_summary(summary, global_step)
else:
summary_feed_dict = {
self.test_loss: loss_value,
self.test_pearson: pearson_value,
self.test_spearman: spearman_value,
self.test_mse: mse_value,
}
summary = sess.run(self.test_summaries, summary_feed_dict)
self.writer.add_summary(summary, global_step)
return loss_value, (pearson_value, spearman_value, mse_value)
# --- internal use ------
def build_summary(self):
with tf.name_scope('train_summaries'):
self.train_loss = tf.placeholder(tf.float32, [], 'train_loss')
self.train_pearson = tf.placeholder(tf.float32, [], 'train_pearson')
self.train_spearman = tf.placeholder(tf.float32, [], 'train_spearman')
self.train_mse = tf.placeholder(tf.float32, [], 'train_mse')
tf.add_to_collection('train_summaries_collection', tf.summary.scalar('train_loss', self.train_loss))
tf.add_to_collection('train_summaries_collection', tf.summary.scalar('train_pearson', self.train_pearson))
tf.add_to_collection('train_summaries_collection', tf.summary.scalar('train_spearman', self.train_spearman))
tf.add_to_collection('train_summaries_collection', tf.summary.scalar('train_mse', self.train_mse))
self.train_summaries = tf.summary.merge_all('train_summaries_collection')
with tf.name_scope('dev_summaries'):
self.dev_loss = tf.placeholder(tf.float32, [], 'dev_loss')
self.dev_pearson = tf.placeholder(tf.float32, [], 'dev_pearson')
self.dev_spearman = tf.placeholder(tf.float32, [], 'dev_spearman')
self.dev_mse = tf.placeholder(tf.float32, [], 'dev_mse')
tf.add_to_collection('dev_summaries_collection', tf.summary.scalar('dev_loss',self.dev_loss))
tf.add_to_collection('dev_summaries_collection', tf.summary.scalar('dev_pearson', self.dev_pearson))
tf.add_to_collection('dev_summaries_collection', tf.summary.scalar('dev_spearman', self.dev_spearman))
tf.add_to_collection('dev_summaries_collection', tf.summary.scalar('dev_mse', self.dev_mse))
self.dev_summaries = tf.summary.merge_all('dev_summaries_collection')
with tf.name_scope('test_summaries'):
self.test_loss = tf.placeholder(tf.float32, [], 'test_loss')
self.test_pearson = tf.placeholder(tf.float32, [], 'test_pearson')
self.test_spearman = tf.placeholder(tf.float32, [], 'test_spearman')
self.test_mse = tf.placeholder(tf.float32, [], 'test_mse')
tf.add_to_collection('test_summaries_collection', tf.summary.scalar('test_loss',self.test_loss))
tf.add_to_collection('test_summaries_collection', tf.summary.scalar('test_pearson', self.test_pearson))
tf.add_to_collection('test_summaries_collection', tf.summary.scalar('test_spearman', self.test_spearman))
tf.add_to_collection('test_summaries_collection', tf.summary.scalar('test_mse', self.test_mse))
self.test_summaries = tf.summary.merge_all('test_summaries_collection')
| [
"src.utils.record_log._logger.add",
"numpy.mean",
"tensorflow.summary.merge_all",
"tensorflow.placeholder",
"numpy.argmax",
"tensorflow.summary.scalar",
"numpy.array",
"tensorflow.name_scope",
"numpy.concatenate",
"scipy.stats.pearsonr",
"scipy.stats.spearmanr",
"tensorflow.summary.FileWriter"... | [((346, 384), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['cfg.summary_dir'], {}), '(cfg.summary_dir)\n', (367, 384), True, 'import tensorflow as tf\n'), ((461, 474), 'src.utils.record_log._logger.add', '_logger.add', ([], {}), '()\n', (472, 474), False, 'from src.utils.record_log import _logger\n'), ((483, 554), 'src.utils.record_log._logger.add', '_logger.add', (["('getting evaluation result for %s' % dataset_obj.data_type)"], {}), "('getting evaluation result for %s' % dataset_obj.data_type)\n", (494, 554), False, 'from src.utils.record_log import _logger\n'), ((1256, 1286), 'numpy.concatenate', 'np.concatenate', (['logits_list', '(0)'], {}), '(logits_list, 0)\n', (1270, 1286), True, 'import numpy as np\n'), ((1308, 1326), 'numpy.mean', 'np.mean', (['loss_list'], {}), '(loss_list)\n', (1315, 1326), True, 'import numpy as np\n'), ((1351, 1378), 'numpy.array', 'np.array', (['target_score_list'], {}), '(target_score_list)\n', (1359, 1378), True, 'import numpy as np\n'), ((1406, 1445), 'numpy.concatenate', 'np.concatenate', (['predicted_score_list', '(0)'], {}), '(predicted_score_list, 0)\n', (1420, 1445), True, 'import numpy as np\n'), ((1651, 1699), 'numpy.mean', 'np.mean', (['((target_scores - predicted_scores) ** 2)'], {}), '((target_scores - predicted_scores) ** 2)\n', (1658, 1699), True, 'import numpy as np\n'), ((1503, 1550), 'scipy.stats.pearsonr', 'stats.pearsonr', (['target_scores', 'predicted_scores'], {}), '(target_scores, predicted_scores)\n', (1517, 1550), True, 'import scipy.stats as stats\n'), ((1579, 1627), 'scipy.stats.spearmanr', 'stats.spearmanr', (['target_scores', 'predicted_scores'], {}), '(target_scores, predicted_scores)\n', (1594, 1627), True, 'import scipy.stats as stats\n'), ((3449, 3481), 'tensorflow.name_scope', 'tf.name_scope', (['"""train_summaries"""'], {}), "('train_summaries')\n", (3462, 3481), True, 'import tensorflow as tf\n'), ((3513, 3557), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]', '"""train_loss"""'], {}), "(tf.float32, [], 'train_loss')\n", (3527, 3557), True, 'import tensorflow as tf\n'), ((3591, 3638), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]', '"""train_pearson"""'], {}), "(tf.float32, [], 'train_pearson')\n", (3605, 3638), True, 'import tensorflow as tf\n'), ((3673, 3721), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]', '"""train_spearman"""'], {}), "(tf.float32, [], 'train_spearman')\n", (3687, 3721), True, 'import tensorflow as tf\n'), ((3751, 3794), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]', '"""train_mse"""'], {}), "(tf.float32, [], 'train_mse')\n", (3765, 3794), True, 'import tensorflow as tf\n'), ((4294, 4344), 'tensorflow.summary.merge_all', 'tf.summary.merge_all', (['"""train_summaries_collection"""'], {}), "('train_summaries_collection')\n", (4314, 4344), True, 'import tensorflow as tf\n'), ((4359, 4389), 'tensorflow.name_scope', 'tf.name_scope', (['"""dev_summaries"""'], {}), "('dev_summaries')\n", (4372, 4389), True, 'import tensorflow as tf\n'), ((4419, 4461), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]', '"""dev_loss"""'], {}), "(tf.float32, [], 'dev_loss')\n", (4433, 4461), True, 'import tensorflow as tf\n'), ((4493, 4538), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]', '"""dev_pearson"""'], {}), "(tf.float32, [], 'dev_pearson')\n", (4507, 4538), True, 'import tensorflow as tf\n'), ((4571, 4617), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]', '"""dev_spearman"""'], {}), "(tf.float32, [], 'dev_spearman')\n", (4585, 4617), True, 'import tensorflow as tf\n'), ((4645, 4686), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]', '"""dev_mse"""'], {}), "(tf.float32, [], 'dev_mse')\n", (4659, 4686), True, 'import tensorflow as tf\n'), ((5159, 5207), 'tensorflow.summary.merge_all', 'tf.summary.merge_all', (['"""dev_summaries_collection"""'], {}), "('dev_summaries_collection')\n", (5179, 5207), True, 'import tensorflow as tf\n'), ((5222, 5253), 'tensorflow.name_scope', 'tf.name_scope', (['"""test_summaries"""'], {}), "('test_summaries')\n", (5235, 5253), True, 'import tensorflow as tf\n'), ((5284, 5327), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]', '"""test_loss"""'], {}), "(tf.float32, [], 'test_loss')\n", (5298, 5327), True, 'import tensorflow as tf\n'), ((5360, 5406), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]', '"""test_pearson"""'], {}), "(tf.float32, [], 'test_pearson')\n", (5374, 5406), True, 'import tensorflow as tf\n'), ((5440, 5487), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]', '"""test_spearman"""'], {}), "(tf.float32, [], 'test_spearman')\n", (5454, 5487), True, 'import tensorflow as tf\n'), ((5516, 5558), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]', '"""test_mse"""'], {}), "(tf.float32, [], 'test_mse')\n", (5530, 5558), True, 'import tensorflow as tf\n'), ((6044, 6093), 'tensorflow.summary.merge_all', 'tf.summary.merge_all', (['"""test_summaries_collection"""'], {}), "('test_summaries_collection')\n", (6064, 6093), True, 'import tensorflow as tf\n'), ((1006, 1027), 'numpy.argmax', 'np.argmax', (['logits', '(-1)'], {}), '(logits, -1)\n', (1015, 1027), True, 'import numpy as np\n'), ((3858, 3906), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""train_loss"""', 'self.train_loss'], {}), "('train_loss', self.train_loss)\n", (3875, 3906), True, 'import tensorflow as tf\n'), ((3971, 4025), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""train_pearson"""', 'self.train_pearson'], {}), "('train_pearson', self.train_pearson)\n", (3988, 4025), True, 'import tensorflow as tf\n'), ((4090, 4146), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""train_spearman"""', 'self.train_spearman'], {}), "('train_spearman', self.train_spearman)\n", (4107, 4146), True, 'import tensorflow as tf\n'), ((4211, 4257), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""train_mse"""', 'self.train_mse'], {}), "('train_mse', self.train_mse)\n", (4228, 4257), True, 'import tensorflow as tf\n'), ((4748, 4792), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""dev_loss"""', 'self.dev_loss'], {}), "('dev_loss', self.dev_loss)\n", (4765, 4792), True, 'import tensorflow as tf\n'), ((4854, 4904), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""dev_pearson"""', 'self.dev_pearson'], {}), "('dev_pearson', self.dev_pearson)\n", (4871, 4904), True, 'import tensorflow as tf\n'), ((4967, 5019), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""dev_spearman"""', 'self.dev_spearman'], {}), "('dev_spearman', self.dev_spearman)\n", (4984, 5019), True, 'import tensorflow as tf\n'), ((5082, 5124), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""dev_mse"""', 'self.dev_mse'], {}), "('dev_mse', self.dev_mse)\n", (5099, 5124), True, 'import tensorflow as tf\n'), ((5621, 5667), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""test_loss"""', 'self.test_loss'], {}), "('test_loss', self.test_loss)\n", (5638, 5667), True, 'import tensorflow as tf\n'), ((5730, 5782), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""test_pearson"""', 'self.test_pearson'], {}), "('test_pearson', self.test_pearson)\n", (5747, 5782), True, 'import tensorflow as tf\n'), ((5846, 5900), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""test_spearman"""', 'self.test_spearman'], {}), "('test_spearman', self.test_spearman)\n", (5863, 5900), True, 'import tensorflow as tf\n'), ((5964, 6008), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""test_mse"""', 'self.test_mse'], {}), "('test_mse', self.test_mse)\n", (5981, 6008), True, 'import tensorflow as tf\n')] |
import RPi.GPIO as GPIO
import connexion
if __name__ == '__main__':
app = connexion.App('a-pi-api')
app.add_api('v0/spec.yml')
app.run(host='0.0.0.0', port=80)
| [
"connexion.App"
] | [((76, 101), 'connexion.App', 'connexion.App', (['"""a-pi-api"""'], {}), "('a-pi-api')\n", (89, 101), False, 'import connexion\n')] |
#coding=utf-8
import matplotlib
matplotlib.use("Agg")
import tensorflow as tf
import argparse
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D,MaxPooling2D,UpSampling2D,BatchNormalization,Reshape,Permute,Activation
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.callbacks import ModelCheckpoint
from sklearn.preprocessing import LabelEncoder
from PIL import Image
import matplotlib.pyplot as plt
import cv2
import random
import os
from tqdm import tqdm
seed = 7
np.random.seed(seed)
#设置图像大小
img_w = 32
img_h = 32
#分类
n_label=6
classes=[0.0,17.0,34.0,51.0,68.0,255.0]
labelencoder = LabelEncoder()
labelencoder.fit(classes)
#训练批次和每次数据量
EPOCHS = 5
BS = 32
#图像最大值
divisor=255.0
#图像根路径
filepath ='C:\\Users\Administrator\Desktop\Project\src\\'
#读取图片
def load_img(path, grayscale=False):
if grayscale:
img = cv2.imread(path,cv2.IMREAD_GRAYSCALE)
else:
img = cv2.imread(path)
img = np.array(img,dtype="float") / divisor
return img
#获取训练数据和测试数据地址
def get_train_val(val_rate = 0.25):
train_url = []
train_set = []
val_set = []
for pic in os.listdir(filepath + 'train'):
train_url.append(pic)
random.shuffle(train_url)
total_num = len(train_url)
val_num = int(val_rate * total_num)
for i in range(len(train_url)):
if i < val_num:
val_set.append(train_url[i])
else:
train_set.append(train_url[i])
return train_set,val_set
# 生成训练数据
def generateData(batch_size,data=[]):
while True:
train_data = []
train_label = []
batch = 0
for i in (range(len(data))):
url = data[i]
batch += 1
img = load_img(filepath + 'train/' + url)
img = img_to_array(img)
train_data.append(img)
label = load_img(filepath + 'label/' + url, grayscale=True)
label = img_to_array(label).reshape((img_w * img_h,))
train_label.append(label)
if batch % batch_size==0:
train_data = np.array(train_data)
train_label = np.array(train_label).flatten() #拍平
train_label = labelencoder.transform(train_label)
train_label = to_categorical(train_label, num_classes=n_label) #编码输出便签
train_label = train_label.reshape((batch_size,img_w,img_h,n_label))
yield (train_data,train_label)
train_data = []
train_label = []
batch = 0
#生成测试的数据
def generateValidData(batch_size,data=[]):
while True:
valid_data = []
valid_label = []
batch = 0
for i in (range(len(data))):
url = data[i]
batch += 1
img = load_img(filepath + 'train/' + url)
img = img_to_array(img)
valid_data.append(img)
label = load_img(filepath + 'label/' + url, grayscale=True)
label = img_to_array(label).reshape((img_w * img_h,))
valid_label.append(label)
if batch % batch_size==0:
valid_data = np.array(valid_data)
valid_label = np.array(valid_label).flatten()
valid_label = labelencoder.transform(valid_label)
valid_label = to_categorical(valid_label, num_classes=n_label)
valid_label = valid_label.reshape((batch_size,img_w,img_h,n_label))
yield (valid_data,valid_label)
valid_data = []
valid_label = []
batch = 0
#定义模型-网络模型
def SegNet():
model = Sequential()
#encoder
model.add(Conv2D(64,(3,3),strides=(1,1),input_shape=(img_w,img_h,3),padding='same',activation='relu',data_format='channels_last'))
model.add(BatchNormalization())
model.add(Conv2D(64,(3,3),strides=(1,1),padding='same',activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2)))
#(128,128)
model.add(Conv2D(128, (3, 3), strides=(1, 1), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(Conv2D(128, (3, 3), strides=(1, 1), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2)))
#(64,64)
model.add(Conv2D(256, (3, 3), strides=(1, 1), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(Conv2D(256, (3, 3), strides=(1, 1), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(Conv2D(256, (3, 3), strides=(1, 1), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
#(32,32)
model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
#(16,16)
model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
#(8,8)
#decoder
model.add(UpSampling2D(size=(2,2)))
#(16,16)
model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(UpSampling2D(size=(2, 2)))
#(32,32)
model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(UpSampling2D(size=(2, 2)))
#(64,64)
model.add(Conv2D(256, (3, 3), strides=(1, 1), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(Conv2D(256, (3, 3), strides=(1, 1), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(Conv2D(256, (3, 3), strides=(1, 1), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(UpSampling2D(size=(2, 2)))
#(128,128)
model.add(Conv2D(128, (3, 3), strides=(1, 1), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(Conv2D(128, (3, 3), strides=(1, 1), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(UpSampling2D(size=(2, 2)))
#(256,256)
model.add(Conv2D(64, (3, 3), strides=(1, 1), input_shape=(img_w, img_h,3), padding='same', activation='relu',data_format='channels_last'))
model.add(BatchNormalization())
model.add(Conv2D(64, (3, 3), strides=(1, 1), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(Conv2D(n_label, (1, 1), strides=(1, 1), padding='same'))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy',optimizer='sgd',metrics=['accuracy'])
model.summary()
return model
#开始训练
def train(args):
model = SegNet()
modelcheck = ModelCheckpoint(args['model'],monitor='val_acc',save_best_only=True,mode='max')
callable = [modelcheck,tf.keras.callbacks.TensorBoard(log_dir='.')]
train_set,val_set = get_train_val()
train_numb = len(train_set)
valid_numb = len(val_set)
print ("the number of train data is",train_numb)
print ("the number of val data is",valid_numb)
H = model.fit(x=generateData(BS,train_set),steps_per_epoch=(train_numb//BS),epochs=EPOCHS,verbose=2,
validation_data=generateValidData(BS,val_set),validation_steps=(valid_numb//BS),callbacks=callable)
# plot the training loss and accuracy
plt.style.use("ggplot")
plt.figure()
N = EPOCHS
plt.plot(np.arange(0, N), H.history["loss"], label="train_loss")
plt.plot(np.arange(0, N), H.history["val_loss"], label="val_loss")
plt.plot(np.arange(0, N), H.history["acc"], label="train_acc")
plt.plot(np.arange(0, N), H.history["val_acc"], label="val_acc")
plt.title("Training Loss and Accuracy on SegNet Satellite Seg")
plt.xlabel("Epoch #")
plt.ylabel("Loss/Accuracy")
plt.legend(loc="lower left")
plt.savefig(args["plot"])
#获取参数
def args_parse():
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-a", "--augment", help="using data augment or not",
action="store_true", default=False)
ap.add_argument("-m", "--model", required=False,default="segnet.h5",
help="path to output model")
ap.add_argument("-p", "--plot", type=str, default="plot.png",
help="path to output accuracy/loss plot")
args = vars(ap.parse_args())
return args
#运行程序
if __name__=='__main__':
args = args_parse()
train(args)
print("完成")
#predict()
| [
"sklearn.preprocessing.LabelEncoder",
"matplotlib.pyplot.ylabel",
"tensorflow.keras.layers.BatchNormalization",
"numpy.array",
"numpy.arange",
"os.listdir",
"tensorflow.keras.layers.Conv2D",
"argparse.ArgumentParser",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.style.use",
"numpy.random.seed"... | [((34, 55), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (48, 55), False, 'import matplotlib\n'), ((650, 670), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (664, 670), True, 'import numpy as np\n'), ((785, 799), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (797, 799), False, 'from sklearn.preprocessing import LabelEncoder\n'), ((1318, 1348), 'os.listdir', 'os.listdir', (["(filepath + 'train')"], {}), "(filepath + 'train')\n", (1328, 1348), False, 'import os\n'), ((1386, 1411), 'random.shuffle', 'random.shuffle', (['train_url'], {}), '(train_url)\n', (1400, 1411), False, 'import random\n'), ((3970, 3982), 'tensorflow.keras.models.Sequential', 'Sequential', ([], {}), '()\n', (3980, 3982), False, 'from tensorflow.keras.models import Sequential\n'), ((8382, 8469), 'tensorflow.keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', (["args['model']"], {'monitor': '"""val_acc"""', 'save_best_only': '(True)', 'mode': '"""max"""'}), "(args['model'], monitor='val_acc', save_best_only=True, mode\n ='max')\n", (8397, 8469), False, 'from tensorflow.keras.callbacks import ModelCheckpoint\n'), ((9031, 9054), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (9044, 9054), True, 'import matplotlib.pyplot as plt\n'), ((9060, 9072), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (9070, 9072), True, 'import matplotlib.pyplot as plt\n'), ((9374, 9437), 'matplotlib.pyplot.title', 'plt.title', (['"""Training Loss and Accuracy on SegNet Satellite Seg"""'], {}), "('Training Loss and Accuracy on SegNet Satellite Seg')\n", (9383, 9437), True, 'import matplotlib.pyplot as plt\n'), ((9443, 9464), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epoch #"""'], {}), "('Epoch #')\n", (9453, 9464), True, 'import matplotlib.pyplot as plt\n'), ((9470, 9497), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Loss/Accuracy"""'], {}), "('Loss/Accuracy')\n", (9480, 9497), True, 'import matplotlib.pyplot as plt\n'), ((9503, 9531), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower left"""'}), "(loc='lower left')\n", (9513, 9531), True, 'import matplotlib.pyplot as plt\n'), ((9537, 9562), 'matplotlib.pyplot.savefig', 'plt.savefig', (["args['plot']"], {}), "(args['plot'])\n", (9548, 9562), True, 'import matplotlib.pyplot as plt\n'), ((9661, 9686), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (9684, 9686), False, 'import argparse\n'), ((1034, 1072), 'cv2.imread', 'cv2.imread', (['path', 'cv2.IMREAD_GRAYSCALE'], {}), '(path, cv2.IMREAD_GRAYSCALE)\n', (1044, 1072), False, 'import cv2\n'), ((1098, 1114), 'cv2.imread', 'cv2.imread', (['path'], {}), '(path)\n', (1108, 1114), False, 'import cv2\n'), ((4016, 4150), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(64)', '(3, 3)'], {'strides': '(1, 1)', 'input_shape': '(img_w, img_h, 3)', 'padding': '"""same"""', 'activation': '"""relu"""', 'data_format': '"""channels_last"""'}), "(64, (3, 3), strides=(1, 1), input_shape=(img_w, img_h, 3), padding=\n 'same', activation='relu', data_format='channels_last')\n", (4022, 4150), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4152, 4172), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (4170, 4172), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4191, 4260), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(64)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(64, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (4197, 4260), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4273, 4293), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (4291, 4293), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4312, 4342), 'tensorflow.keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (4324, 4342), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4378, 4448), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(128)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(128, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (4384, 4448), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4467, 4487), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (4485, 4487), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4506, 4576), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(128)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(128, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (4512, 4576), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4595, 4615), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (4613, 4615), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4634, 4664), 'tensorflow.keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (4646, 4664), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4696, 4766), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(256)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(256, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (4702, 4766), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4785, 4805), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (4803, 4805), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4824, 4894), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(256)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(256, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (4830, 4894), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4913, 4933), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (4931, 4933), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4952, 5022), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(256)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(256, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (4958, 5022), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5041, 5061), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (5059, 5061), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5080, 5110), 'tensorflow.keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (5092, 5110), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5145, 5215), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(512)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(512, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (5151, 5215), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5234, 5254), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (5252, 5254), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5273, 5343), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(512)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(512, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (5279, 5343), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5362, 5382), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (5380, 5382), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5401, 5471), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(512)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(512, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (5407, 5471), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5490, 5510), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (5508, 5510), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5529, 5559), 'tensorflow.keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (5541, 5559), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5594, 5664), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(512)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(512, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (5600, 5664), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5683, 5703), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (5701, 5703), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5722, 5792), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(512)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(512, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (5728, 5792), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5811, 5831), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (5829, 5831), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5850, 5920), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(512)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(512, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (5856, 5920), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5939, 5959), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (5957, 5959), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5978, 6008), 'tensorflow.keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (5990, 6008), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6057, 6082), 'tensorflow.keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)'}), '(size=(2, 2))\n', (6069, 6082), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6116, 6186), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(512)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(512, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (6122, 6186), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6205, 6225), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (6223, 6225), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6244, 6314), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(512)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(512, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (6250, 6314), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6333, 6353), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (6351, 6353), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6372, 6442), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(512)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(512, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (6378, 6442), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6461, 6481), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (6479, 6481), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6500, 6525), 'tensorflow.keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)'}), '(size=(2, 2))\n', (6512, 6525), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6560, 6630), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(512)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(512, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (6566, 6630), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6649, 6669), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (6667, 6669), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6688, 6758), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(512)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(512, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (6694, 6758), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6777, 6797), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (6795, 6797), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6816, 6886), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(512)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(512, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (6822, 6886), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6905, 6925), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (6923, 6925), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6944, 6969), 'tensorflow.keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)'}), '(size=(2, 2))\n', (6956, 6969), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7004, 7074), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(256)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(256, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (7010, 7074), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7093, 7113), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (7111, 7113), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7132, 7202), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(256)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(256, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (7138, 7202), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7221, 7241), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (7239, 7241), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7260, 7330), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(256)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(256, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (7266, 7330), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7349, 7369), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (7367, 7369), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7388, 7413), 'tensorflow.keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)'}), '(size=(2, 2))\n', (7400, 7413), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7450, 7520), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(128)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(128, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (7456, 7520), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7539, 7559), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (7557, 7559), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7578, 7648), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(128)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(128, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (7584, 7648), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7667, 7687), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (7685, 7687), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7706, 7731), 'tensorflow.keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)'}), '(size=(2, 2))\n', (7718, 7731), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7768, 7902), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(64)', '(3, 3)'], {'strides': '(1, 1)', 'input_shape': '(img_w, img_h, 3)', 'padding': '"""same"""', 'activation': '"""relu"""', 'data_format': '"""channels_last"""'}), "(64, (3, 3), strides=(1, 1), input_shape=(img_w, img_h, 3), padding=\n 'same', activation='relu', data_format='channels_last')\n", (7774, 7902), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7912, 7932), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (7930, 7932), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7951, 8020), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(64)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(64, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (7957, 8020), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((8039, 8059), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (8057, 8059), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((8078, 8133), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['n_label', '(1, 1)'], {'strides': '(1, 1)', 'padding': '"""same"""'}), "(n_label, (1, 1), strides=(1, 1), padding='same')\n", (8084, 8133), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((8152, 8173), 'tensorflow.keras.layers.Activation', 'Activation', (['"""softmax"""'], {}), "('softmax')\n", (8162, 8173), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((8490, 8533), 'tensorflow.keras.callbacks.TensorBoard', 'tf.keras.callbacks.TensorBoard', ([], {'log_dir': '"""."""'}), "(log_dir='.')\n", (8520, 8533), True, 'import tensorflow as tf\n'), ((9103, 9118), 'numpy.arange', 'np.arange', (['(0)', 'N'], {}), '(0, N)\n', (9112, 9118), True, 'import numpy as np\n'), ((9173, 9188), 'numpy.arange', 'np.arange', (['(0)', 'N'], {}), '(0, N)\n', (9182, 9188), True, 'import numpy as np\n'), ((9245, 9260), 'numpy.arange', 'np.arange', (['(0)', 'N'], {}), '(0, N)\n', (9254, 9260), True, 'import numpy as np\n'), ((9313, 9328), 'numpy.arange', 'np.arange', (['(0)', 'N'], {}), '(0, N)\n', (9322, 9328), True, 'import numpy as np\n'), ((1130, 1158), 'numpy.array', 'np.array', (['img'], {'dtype': '"""float"""'}), "(img, dtype='float')\n", (1138, 1158), True, 'import numpy as np\n'), ((1990, 2007), 'tensorflow.keras.preprocessing.image.img_to_array', 'img_to_array', (['img'], {}), '(img)\n', (2002, 2007), False, 'from tensorflow.keras.preprocessing.image import img_to_array\n'), ((3128, 3145), 'tensorflow.keras.preprocessing.image.img_to_array', 'img_to_array', (['img'], {}), '(img)\n', (3140, 3145), False, 'from tensorflow.keras.preprocessing.image import img_to_array\n'), ((2300, 2320), 'numpy.array', 'np.array', (['train_data'], {}), '(train_data)\n', (2308, 2320), True, 'import numpy as np\n'), ((2495, 2543), 'tensorflow.keras.utils.to_categorical', 'to_categorical', (['train_label'], {'num_classes': 'n_label'}), '(train_label, num_classes=n_label)\n', (2509, 2543), False, 'from tensorflow.keras.utils import to_categorical\n'), ((3440, 3460), 'numpy.array', 'np.array', (['valid_data'], {}), '(valid_data)\n', (3448, 3460), True, 'import numpy as np\n'), ((3628, 3676), 'tensorflow.keras.utils.to_categorical', 'to_categorical', (['valid_label'], {'num_classes': 'n_label'}), '(valid_label, num_classes=n_label)\n', (3642, 3676), False, 'from tensorflow.keras.utils import to_categorical\n'), ((2141, 2160), 'tensorflow.keras.preprocessing.image.img_to_array', 'img_to_array', (['label'], {}), '(label)\n', (2153, 2160), False, 'from tensorflow.keras.preprocessing.image import img_to_array\n'), ((3280, 3299), 'tensorflow.keras.preprocessing.image.img_to_array', 'img_to_array', (['label'], {}), '(label)\n', (3292, 3299), False, 'from tensorflow.keras.preprocessing.image import img_to_array\n'), ((2354, 2375), 'numpy.array', 'np.array', (['train_label'], {}), '(train_label)\n', (2362, 2375), True, 'import numpy as np\n'), ((3494, 3515), 'numpy.array', 'np.array', (['valid_label'], {}), '(valid_label)\n', (3502, 3515), True, 'import numpy as np\n')] |
from . import utils
import os
import scanpy as sc
import scprep
import tempfile
URL = "https://ndownloader.figshare.com/files/25555751"
@utils.loader
def load_human_blood_nestorowa2016(test=False):
"""Download Nesterova data from Figshare."""
if test:
# load full data first, cached if available
adata = load_human_blood_nestorowa2016(test=False)
# Subsample data
adata = adata[:, :500].copy()
utils.filter_genes_cells(adata)
sc.pp.subsample(adata, n_obs=500)
# Note: could also use 200-500 HVGs rather than 200 random genes
# Ensure there are no cells or genes with 0 counts
utils.filter_genes_cells(adata)
return adata
else:
with tempfile.TemporaryDirectory() as tempdir:
filepath = os.path.join(tempdir, "human_blood_nestorowa2016.h5ad")
scprep.io.download.download_url(URL, filepath)
adata = sc.read(filepath)
# Ensure there are no cells or genes with 0 counts
utils.filter_genes_cells(adata)
return adata
| [
"tempfile.TemporaryDirectory",
"scanpy.read",
"scanpy.pp.subsample",
"os.path.join",
"scprep.io.download.download_url"
] | [((488, 521), 'scanpy.pp.subsample', 'sc.pp.subsample', (['adata'], {'n_obs': '(500)'}), '(adata, n_obs=500)\n', (503, 521), True, 'import scanpy as sc\n'), ((741, 770), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (768, 770), False, 'import tempfile\n'), ((806, 861), 'os.path.join', 'os.path.join', (['tempdir', '"""human_blood_nestorowa2016.h5ad"""'], {}), "(tempdir, 'human_blood_nestorowa2016.h5ad')\n", (818, 861), False, 'import os\n'), ((874, 920), 'scprep.io.download.download_url', 'scprep.io.download.download_url', (['URL', 'filepath'], {}), '(URL, filepath)\n', (905, 920), False, 'import scprep\n'), ((941, 958), 'scanpy.read', 'sc.read', (['filepath'], {}), '(filepath)\n', (948, 958), True, 'import scanpy as sc\n')] |
from minidoc import svg
from minidoc import tst
from efdir import fs
import shutil
import os
def creat_one_svg(k,v,i=None,**kwargs):
if("dst_dir" in kwargs):
dst_dir = kwargs['dst_dir']
else:
dst_dir = "./images"
screen_size = svg.get_screen_size(v,**kwargs)
kwargs['screen_size'] = screen_size
cmds_str = svg.cmds_arr2str(v,**kwargs)
output_path = svg.creat_svg(cmds_str,**kwargs)
#name = tst.get_svg_name(k) + "." + str(i) + ".svg"
name = tst.get_svg_name(k) + ".svg"
dst = os.path.join(dst_dir,name)
shutil.move(output_path,dst)
return(dst)
#still_frames
#rownums
#colnums
def creat_svgs(kl,vl,**kwargs):
if("dst_dir" in kwargs):
dst_dir = kwargs['dst_dir']
else:
dst_dir = "./images"
fs.mkdir(dst_dir)
arr = []
for i in range(kl.__len__()):
k = kl[i]
v = vl[i]
dst = creat_one_svg(k,v,i=i,**kwargs)
arr.append(dst)
return(arr)
####
####
| [
"minidoc.tst.get_svg_name",
"minidoc.svg.cmds_arr2str",
"shutil.move",
"minidoc.svg.get_screen_size",
"os.path.join",
"efdir.fs.mkdir",
"minidoc.svg.creat_svg"
] | [((256, 288), 'minidoc.svg.get_screen_size', 'svg.get_screen_size', (['v'], {}), '(v, **kwargs)\n', (275, 288), False, 'from minidoc import svg\n'), ((343, 372), 'minidoc.svg.cmds_arr2str', 'svg.cmds_arr2str', (['v'], {}), '(v, **kwargs)\n', (359, 372), False, 'from minidoc import svg\n'), ((390, 423), 'minidoc.svg.creat_svg', 'svg.creat_svg', (['cmds_str'], {}), '(cmds_str, **kwargs)\n', (403, 423), False, 'from minidoc import svg\n'), ((529, 556), 'os.path.join', 'os.path.join', (['dst_dir', 'name'], {}), '(dst_dir, name)\n', (541, 556), False, 'import os\n'), ((560, 589), 'shutil.move', 'shutil.move', (['output_path', 'dst'], {}), '(output_path, dst)\n', (571, 589), False, 'import shutil\n'), ((780, 797), 'efdir.fs.mkdir', 'fs.mkdir', (['dst_dir'], {}), '(dst_dir)\n', (788, 797), False, 'from efdir import fs\n'), ((490, 509), 'minidoc.tst.get_svg_name', 'tst.get_svg_name', (['k'], {}), '(k)\n', (506, 509), False, 'from minidoc import tst\n')] |
# Generated by Django 3.0.7 on 2020-07-19 03:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0007_auto_20200614_0254'),
]
operations = [
migrations.AddField(
model_name='touristspot',
name='photo',
field=models.ImageField(blank=True, null=True, upload_to='core'),
),
]
| [
"django.db.models.ImageField"
] | [((335, 393), 'django.db.models.ImageField', 'models.ImageField', ([], {'blank': '(True)', 'null': '(True)', 'upload_to': '"""core"""'}), "(blank=True, null=True, upload_to='core')\n", (352, 393), False, 'from django.db import migrations, models\n')] |
#!/usr/bin/env python
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test some MITAB specific translation issues.
# Author: <NAME>, <even dot rouault at mines dash paris dot org>
#
###############################################################################
# Copyright (c) 2010, <NAME> <even dot rouault at mines-paris dot org>
#
# 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 sys
sys.path.append( '../pymod' )
import gdaltest
from osgeo import osr
###############################################################################
# Test the osr.SpatialReference.ImportFromMICoordSys() function.
#
def osr_micoordsys_1():
srs = osr.SpatialReference()
srs.ImportFromMICoordSys('Earth Projection 3, 62, "m", -117.474542888889, 33.7644620277778, 33.9036340277778, 33.6252900277778, 0, 0')
if abs(srs.GetProjParm(osr.SRS_PP_STANDARD_PARALLEL_1)-33.9036340277778)>0.0000005 \
or abs(srs.GetProjParm(osr.SRS_PP_STANDARD_PARALLEL_2)-33.6252900277778)>0.0000005 \
or abs(srs.GetProjParm(osr.SRS_PP_LATITUDE_OF_ORIGIN)-33.7644620277778)>0.0000005 \
or abs(srs.GetProjParm(osr.SRS_PP_CENTRAL_MERIDIAN)-(-117.474542888889))>0.0000005 \
or abs(srs.GetProjParm(osr.SRS_PP_FALSE_EASTING)-0.0)>0.0000005 \
or abs(srs.GetProjParm(osr.SRS_PP_FALSE_NORTHING)-0.0)>0.0000005:
print(srs.ExportToPrettyWkt())
gdaltest.post_reason('Can not export Lambert Conformal Conic projection.')
return 'fail'
return 'success'
###############################################################################
# Test the osr.SpatialReference.ExportToMICoordSys() function.
#
def osr_micoordsys_2():
srs = osr.SpatialReference()
srs.ImportFromWkt("""PROJCS["unnamed",GEOGCS["NAD27",\
DATUM["North_American_Datum_1927",\
SPHEROID["Clarke 1866",6378206.4,294.9786982139006,\
AUTHORITY["EPSG","7008"]],AUTHORITY["EPSG","6267"]],\
PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433],\
AUTHORITY["EPSG","4267"]],PROJECTION["Lambert_Conformal_Conic_2SP"],\
PARAMETER["standard_parallel_1",33.90363402777778],\
PARAMETER["standard_parallel_2",33.62529002777778],\
PARAMETER["latitude_of_origin",33.76446202777777],\
PARAMETER["central_meridian",-117.4745428888889],\
PARAMETER["false_easting",0],PARAMETER["false_northing",0],\
UNIT["metre",1,AUTHORITY["EPSG","9001"]]]""")
proj = srs.ExportToMICoordSys()
if proj != 'Earth Projection 3, 62, "m", -117.474542888889, 33.7644620277778, 33.9036340277778, 33.6252900277778, 0, 0':
print(proj)
gdaltest.post_reason('Can not import Lambert Conformal Conic projection.')
return 'fail'
return 'success'
###############################################################################
# Test EPSG:3857
#
def osr_micoordsys_3():
srs = osr.SpatialReference()
srs.ImportFromEPSG(3857)
proj = srs.ExportToMICoordSys()
if proj != 'Earth Projection 10, 157, "m", 0':
gdaltest.post_reason('failure')
print(proj)
return 'fail'
srs = osr.SpatialReference()
srs.ImportFromMICoordSys('Earth Projection 10, 157, "m", 0')
wkt = srs.ExportToWkt()
if wkt.find('EXTENSION["PROJ4"') < 0:
gdaltest.post_reason('failure')
print(wkt)
return 'fail'
# Transform again to MITAB (we no longer have the EPSG code, so we rely on PROJ4 extension node)
proj = srs.ExportToMICoordSys()
if proj != 'Earth Projection 10, 157, "m", 0':
gdaltest.post_reason('failure')
print(proj)
return 'fail'
return 'success'
gdaltest_list = [
osr_micoordsys_1,
osr_micoordsys_2,
osr_micoordsys_3 ]
if __name__ == '__main__':
gdaltest.setup_run( 'osr_micoordsys' )
gdaltest.run_tests( gdaltest_list )
gdaltest.summarize()
| [
"osgeo.osr.SpatialReference",
"gdaltest.run_tests",
"gdaltest.summarize",
"gdaltest.setup_run",
"gdaltest.post_reason",
"sys.path.append"
] | [((1570, 1597), 'sys.path.append', 'sys.path.append', (['"""../pymod"""'], {}), "('../pymod')\n", (1585, 1597), False, 'import sys\n'), ((1823, 1845), 'osgeo.osr.SpatialReference', 'osr.SpatialReference', ([], {}), '()\n', (1843, 1845), False, 'from osgeo import osr\n'), ((2844, 2866), 'osgeo.osr.SpatialReference', 'osr.SpatialReference', ([], {}), '()\n', (2864, 2866), False, 'from osgeo import osr\n'), ((4003, 4025), 'osgeo.osr.SpatialReference', 'osr.SpatialReference', ([], {}), '()\n', (4023, 4025), False, 'from osgeo import osr\n'), ((4237, 4259), 'osgeo.osr.SpatialReference', 'osr.SpatialReference', ([], {}), '()\n', (4257, 4259), False, 'from osgeo import osr\n'), ((4891, 4927), 'gdaltest.setup_run', 'gdaltest.setup_run', (['"""osr_micoordsys"""'], {}), "('osr_micoordsys')\n", (4909, 4927), False, 'import gdaltest\n'), ((4935, 4968), 'gdaltest.run_tests', 'gdaltest.run_tests', (['gdaltest_list'], {}), '(gdaltest_list)\n', (4953, 4968), False, 'import gdaltest\n'), ((4976, 4996), 'gdaltest.summarize', 'gdaltest.summarize', ([], {}), '()\n', (4994, 4996), False, 'import gdaltest\n'), ((2543, 2617), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""Can not export Lambert Conformal Conic projection."""'], {}), "('Can not export Lambert Conformal Conic projection.')\n", (2563, 2617), False, 'import gdaltest\n'), ((3748, 3822), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""Can not import Lambert Conformal Conic projection."""'], {}), "('Can not import Lambert Conformal Conic projection.')\n", (3768, 3822), False, 'import gdaltest\n'), ((4152, 4183), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""failure"""'], {}), "('failure')\n", (4172, 4183), False, 'import gdaltest\n'), ((4403, 4434), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""failure"""'], {}), "('failure')\n", (4423, 4434), False, 'import gdaltest\n'), ((4674, 4705), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""failure"""'], {}), "('failure')\n", (4694, 4705), False, 'import gdaltest\n')] |
# -*- coding: utf-8 -*-
import math
from typing import Tuple, Union
import numpy as np
from .cutting_plane import CUTStatus
Arr = Union[np.ndarray]
class ell_stable:
"""Ellipsoid Search Space
ell_stable = {x | (x − xc)' Q^−1 (x − xc) ≤ κ}
Returns:
[type] -- [description]
"""
# __slots__ = ('_n', '_c1', '_kappa', '_rho', '_sigma', '_delta', '_tsq',
# '_xc', '_Q', 'use_parallel_cut', 'no_defer_trick')
def __init__(self, val: Union[Arr, float], x: Arr):
"""Construct a new ell_stable object
Arguments:
val (Union[Arr, float]): [description]
x (Arr): [description]
"""
self.use_parallel_cut = True
self.no_defer_trick = False
self._n = n = len(x)
self._nSq = float(n * n)
self._nPlus1 = float(n + 1)
self._nMinus1 = float(n - 1)
self._halfN = float(n) / 2.0
self._halfNplus1 = self._nPlus1 / 2.0
self._halfNminus1 = self._nMinus1 / 2.0
self._c1 = self._nSq / (self._nSq - 1)
self._c2 = 2.0 / self._nPlus1
self._c3 = float(n) / self._nPlus1
self._xc = x
self._kappa = 1.0
if np.isscalar(val):
self._Q = np.eye(n)
if self.no_defer_trick:
self._Q *= val
else:
self._kappa = val
else:
self._Q = np.diag(val)
def copy(self):
"""[summary]
Returns:
ell_stable: [description]
"""
E = ell_stable(self._kappa, self.xc)
E._Q = self._Q.copy()
# E._c1 = self._c1
E.use_parallel_cut = self.use_parallel_cut
E.no_defer_trick = self.no_defer_trick
return E
@property
def xc(self):
"""copy the whole array anyway
Returns:
[type]: [description]
"""
return self._xc
@xc.setter
def xc(self, x: Arr):
"""Set the xc object
Arguments:
x ([type]): [description]
"""
self._xc = x
# @property
# def use_parallel_cut(self) -> bool:
# """[summary]
# Returns:
# bool: [description]
# """
# return self._use_parallel_cut
# @use_parallel_cut.setter
# def use_parallel_cut(self, b: bool):
# """[summary]
# Arguments:
# b (bool): [description]
# """
# self._use_parallel_cut = b
# Reference: Gill, Murray, and Wright, "Practical Optimization", p43.
# Author: <NAME> (<EMAIL>)
def update(self, cut) -> Tuple[int, float]:
g, beta = cut
# calculate inv(L)*g: (n-1)*n/2 multiplications
invLg = g.copy() # initially
for i in range(1, self._n):
for j in range(i):
self._Q[i, j] = self._Q[j, i] * invLg[j]
# keep for rank-one update
invLg[i] -= self._Q[i, j]
# calculate inv(D)*inv(L)*g: n
invDinvLg = invLg.copy() # initially
for i in range(self._n):
invDinvLg[i] *= self._Q[i, i]
# calculate omega: n
gQg = invDinvLg * invLg
omega = sum(gQg)
self._tsq = self._kappa * omega
status = self._calc_ll(beta)
if status != CUTStatus.success:
return status, self._tsq
# calculate Q*g = inv(L')*inv(D)*inv(L)*g : (n-1)*n/2
Qg = invDinvLg.copy() # initially
for i in range(self._n - 1, 0, -1):
for j in range(i, self._n):
Qg[i - 1] -= self._Q[i, j] * Qg[j] # ???
# calculate xc: n
self._xc -= (self._rho / omega) * Qg
# rank-one update: 3*n + (n-1)*n/2
# r = self._sigma / omega
mu = self._sigma / (1.0 - self._sigma)
oldt = omega / mu # initially
m = self._n - 1
for j in range(m):
# p=sqrt(k)*vv(j)
# p = invLg[j]
# mup = mu * p
t = oldt + gQg[j]
# self._Q[j, j] /= t # update invD
beta2 = invDinvLg[j] / t
self._Q[j, j] *= oldt / t # update invD
for k in range(j + 1, self._n):
# v(k) -= p * self._Q[j, k]
self._Q[j, k] += beta2 * self._Q[k, j]
oldt = t
# p = invLg(n1)
# mup = mu * p
t = oldt + gQg[m]
self._Q[m, m] *= oldt / t # update invD
self._kappa *= self._delta
# if (self.no_defer_trick)
# {
# self._Q *= self._kappa
# self._kappa = 1.
# }
return status, self._tsq
def _calc_ll(self, beta) -> CUTStatus:
"""parallel or deep cut
Arguments:
beta ([type]): [description]
Returns:
int: [description]
"""
if np.isscalar(beta):
return self._calc_dc(beta)
if len(beta) < 2: # unlikely
return self._calc_dc(beta[0])
return self._calc_ll_core(beta[0], beta[1])
def _calc_ll_core(self, b0: float, b1: float) -> CUTStatus:
"""Calculate new ellipsoid under Parallel Cut
g' (x − xc) + β0 ≤ 0
g' (x − xc) + β1 ≥ 0
Arguments:
b0 (float): [description]
b1 (float): [description]
Returns:
int: [description]
"""
b1sqn = b1 * (b1 / self._tsq)
t1n = 1 - b1sqn
if t1n < 0 or not self.use_parallel_cut:
return self._calc_dc(b0)
bdiff = b1 - b0
if bdiff < 0:
return CUTStatus.nosoln # no sol'n
if b0 == 0:
self._calc_ll_cc(b1, b1sqn)
return CUTStatus.success
b0b1n = b0 * (b1 / self._tsq)
if self._n * b0b1n < -1: # unlikely
return CUTStatus.noeffect # no effect
# parallel cut
t0n = 1.0 - b0 * (b0 / self._tsq)
# t1 = self._tsq - b1sq
bsum = b0 + b1
bsumn = bsum / self._tsq
bav = bsum / 2.0
tempn = self._halfN * bsumn * bdiff
xi = math.sqrt(t0n * t1n + tempn * tempn)
self._sigma = self._c3 + (1.0 - b0b1n - xi) / (bsumn * bav * self._nPlus1)
self._rho = self._sigma * bav
self._delta = self._c1 * ((t0n + t1n) / 2 + xi / self._n)
return CUTStatus.success
def _calc_ll_cc(self, b1: float, b1sqn: float):
"""Calculate new ellipsoid under Parallel Cut, one of them is central
g' (x − xc) ≤ 0
g' (x − xc) + β1 ≥ 0
Arguments:
b1 (float): [description]
b1sq (float): [description]
"""
n = self._n
xi = math.sqrt(1 - b1sqn + (self._halfN * b1sqn) ** 2)
self._sigma = self._c3 + self._c2 * (1.0 - xi) / b1sqn
self._rho = self._sigma * b1 / 2.0
self._delta = self._c1 * (1.0 - b1sqn / 2.0 + xi / n)
def _calc_dc(self, beta: float) -> CUTStatus:
"""Calculate new ellipsoid under Deep Cut
g' (x − xc) + β ≤ 0
Arguments:
beta (float): [description]
Returns:
int: [description]
"""
try:
tau = math.sqrt(self._tsq)
except ValueError:
print("Warning: tsq is negative: {}".format(self._tsq))
self._tsq = 0.0
tau = 0.0
bdiff = tau - beta
if bdiff < 0.0:
return CUTStatus.nosoln # no sol'n
if beta == 0.0:
self._calc_cc(tau)
return CUTStatus.success
n = self._n
gamma = tau + n * beta
if gamma < 0.0:
return CUTStatus.noeffect # no effect, unlikely
self._mu = (bdiff / gamma) * self._halfNminus1
self._rho = gamma / self._nPlus1
self._sigma = 2.0 * self._rho / (tau + beta)
self._delta = self._c1 * (1.0 - beta * (beta / self._tsq))
return CUTStatus.success
def _calc_cc(self, tau: float):
"""Calculate new ellipsoid under Central Cut
Arguments:
tau (float): [description]
"""
self._mu = self._halfNminus1
self._sigma = self._c2
self._rho = tau / self._nPlus1
self._delta = self._c1
| [
"numpy.eye",
"math.sqrt",
"numpy.isscalar",
"numpy.diag"
] | [((1213, 1229), 'numpy.isscalar', 'np.isscalar', (['val'], {}), '(val)\n', (1224, 1229), True, 'import numpy as np\n'), ((4841, 4858), 'numpy.isscalar', 'np.isscalar', (['beta'], {}), '(beta)\n', (4852, 4858), True, 'import numpy as np\n'), ((6096, 6132), 'math.sqrt', 'math.sqrt', (['(t0n * t1n + tempn * tempn)'], {}), '(t0n * t1n + tempn * tempn)\n', (6105, 6132), False, 'import math\n'), ((6701, 6750), 'math.sqrt', 'math.sqrt', (['(1 - b1sqn + (self._halfN * b1sqn) ** 2)'], {}), '(1 - b1sqn + (self._halfN * b1sqn) ** 2)\n', (6710, 6750), False, 'import math\n'), ((1253, 1262), 'numpy.eye', 'np.eye', (['n'], {}), '(n)\n', (1259, 1262), True, 'import numpy as np\n'), ((1418, 1430), 'numpy.diag', 'np.diag', (['val'], {}), '(val)\n', (1425, 1430), True, 'import numpy as np\n'), ((7211, 7231), 'math.sqrt', 'math.sqrt', (['self._tsq'], {}), '(self._tsq)\n', (7220, 7231), False, 'import math\n')] |
from flask_wtf import FlaskForm
from wtforms import PasswordField, StringField, SubmitField
from wtforms.validators import DataRequired
#
# Purpose: This from will be used to collect the information for the user logging
# and logging out.
#
# Fields:
# Password: <PASSWORD>
# Username: This contains the name that a user has chosen to represent them
# Submit: This is the field that the user uses to signal that everything has been
# filled out.
#
# Returns:
# All the material that the user filled out (bassically all the fields but filled
# out).
#
class LoginForm(FlaskForm):
"""
Form for users to login
"""
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
submit = SubmitField('Login')
| [
"wtforms.validators.DataRequired",
"wtforms.SubmitField"
] | [((811, 831), 'wtforms.SubmitField', 'SubmitField', (['"""Login"""'], {}), "('Login')\n", (822, 831), False, 'from wtforms import PasswordField, StringField, SubmitField\n'), ((711, 725), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (723, 725), False, 'from wtforms.validators import DataRequired\n'), ((781, 795), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (793, 795), False, 'from wtforms.validators import DataRequired\n')] |
import time
from netmiko.base_connection import BaseConnection
class F5TmshSSH(BaseConnection):
def session_preparation(self):
"""Prepare the session after the connection has been established."""
self._test_channel_read()
self.set_base_prompt()
self.tmsh_mode()
self.set_base_prompt()
self._config_mode = False
cmd = 'run /util bash -c "stty cols 255"'
self.set_terminal_width(command=cmd, pattern="run")
self.disable_paging(
command="modify cli preference pager disabled display-threshold 0"
)
self.clear_buffer()
def tmsh_mode(self, delay_factor=1):
"""tmsh command is equivalent to config command on F5."""
delay_factor = self.select_delay_factor(delay_factor)
self.clear_buffer()
command = f"{self.RETURN}tmsh{self.RETURN}"
self.write_channel(command)
time.sleep(1 * delay_factor)
self.clear_buffer()
return None
def check_config_mode(self, check_string="", pattern=""):
"""Checks if the device is in configuration mode or not."""
return True
def config_mode(self, config_command=""):
"""No config mode for F5 devices."""
return ""
def exit_config_mode(self, exit_config=""):
"""No config mode for F5 devices."""
return ""
| [
"time.sleep"
] | [((915, 943), 'time.sleep', 'time.sleep', (['(1 * delay_factor)'], {}), '(1 * delay_factor)\n', (925, 943), False, 'import time\n')] |
from .. import global_vars as g
from ..window import Window
import numpy as np
from ..roi import makeROI
class TestSettings():
def test_random_roi_color(self):
initial = g.settings['roi_color']
g.settings['roi_color'] = 'random'
w1 = Window(np.random.random([10, 10, 10]))
roi1 = makeROI('rectangle', [[1, 1], [3, 3]])
roi2 = makeROI('rectangle', [[2, 2], [3, 3]])
assert roi1.pen.color().name() != roi2.pen.color().name(), 'Random ROI color is the same. This could be a random chance. Run repeatedly.'
g.settings['roi_color'] = '#00ff00'
roi3 = makeROI('rectangle', [[3, 3], [3, 3]])
assert roi3.pen.color().name() == "#00ff00", 'ROI color set. all rois are same color'
g.settings['roi_color'] = initial
def test_multitrace(self):
initial = g.settings['multipleTraceWindows']
g.settings['multipleTraceWindows'] = False
w1 = Window(np.random.random([10, 10, 10]))
roi1 = makeROI('rectangle', [[1, 1], [3, 3]])
roi1.plot()
roi2 = makeROI('rectangle', [[2, 2], [3, 3]])
roi2.plot()
assert roi1.traceWindow == roi2.traceWindow, 'Traces not plotted together.'
g.settings['multipleTraceWindows'] = True
roi3 = makeROI('rectangle', [[3, 3], [3, 3]])
roi3.plot()
assert roi3.traceWindow != roi1.traceWindow, 'Multiple trace windows'
g.settings['multipleTraceWindows'] = initial
| [
"numpy.random.random"
] | [((250, 280), 'numpy.random.random', 'np.random.random', (['[10, 10, 10]'], {}), '([10, 10, 10])\n', (266, 280), True, 'import numpy as np\n'), ((868, 898), 'numpy.random.random', 'np.random.random', (['[10, 10, 10]'], {}), '([10, 10, 10])\n', (884, 898), True, 'import numpy as np\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# collect a set of trip_id s at all stops in a GTFS file over the selected week of the service period starting at serviceweekstartdate
# filter stops near trainstations based on input txt file - stopsneartrainstop_post_edit
# merge sets of trips at stops near each trainstation to count trips per hour and per day
#
#
import transitanalystisrael_config as cfg
import process_date
import trip_ids_at_stops_merge_near_trainstops_perday_v3
import stopswtrainstopidsandtpdperline_v1
import time
#
print("Local current time :", time.asctime( time.localtime(time.time()) ))
#
processdate = process_date.get_date_now()
trip_ids_at_stops_merge_near_trainstops_perday_v3.main(processdate, cfg.gtfspath, cfg.gtfsdirbase, cfg.processedpath, processdate)
stopswtrainstopidsandtpdperline_v1.main(processdate, cfg.processedpath)
print("Local current time :", time.asctime( time.localtime(time.time()) )) | [
"stopswtrainstopidsandtpdperline_v1.main",
"process_date.get_date_now",
"time.time",
"trip_ids_at_stops_merge_near_trainstops_perday_v3.main"
] | [((633, 660), 'process_date.get_date_now', 'process_date.get_date_now', ([], {}), '()\n', (658, 660), False, 'import process_date\n'), ((662, 797), 'trip_ids_at_stops_merge_near_trainstops_perday_v3.main', 'trip_ids_at_stops_merge_near_trainstops_perday_v3.main', (['processdate', 'cfg.gtfspath', 'cfg.gtfsdirbase', 'cfg.processedpath', 'processdate'], {}), '(processdate, cfg.\n gtfspath, cfg.gtfsdirbase, cfg.processedpath, processdate)\n', (716, 797), False, 'import trip_ids_at_stops_merge_near_trainstops_perday_v3\n'), ((793, 864), 'stopswtrainstopidsandtpdperline_v1.main', 'stopswtrainstopidsandtpdperline_v1.main', (['processdate', 'cfg.processedpath'], {}), '(processdate, cfg.processedpath)\n', (832, 864), False, 'import stopswtrainstopidsandtpdperline_v1\n'), ((601, 612), 'time.time', 'time.time', ([], {}), '()\n', (610, 612), False, 'import time\n'), ((925, 936), 'time.time', 'time.time', ([], {}), '()\n', (934, 936), False, 'import time\n')] |
"""
NCL_bar_2.py
===============
This script illustrates the following concepts:
- Drawing bars instead of curves in an XY plot
- Changing the aspect ratio of a bar plot
- Drawing filled bars up or down based on a Y reference value
- Setting the minimum/maximum value of the Y axis in a bar plot
- Using named colors to indicate a fill color
- Creating array of dates to use as x-axis tick labels
- Creating a main title
See following URLs to see the reproduced NCL plot & script:
- Original NCL script: https://www.ncl.ucar.edu/Applications/Scripts/bar_2.ncl
- Original NCL plot: https://www.ncl.ucar.edu/Applications/Images/bar_2_lg.png
"""
import geocat.datafiles as gdf
import matplotlib.pyplot as plt
###############################################################################
# Import packages:
import numpy as np
import xarray as xr
from geocat.viz import util as gvutil
###############################################################################
# Read in data:
# Open a netCDF data file using xarray default engine and load the data into xarrays
ds = xr.open_dataset(gdf.get("netcdf_files/soi.nc"))
dsoik = ds.DSOI_KET
date = ds.date
num_months = np.shape(date)[0]
# Dates in the file are represented by year and month (YYYYMM)
# representing them fractionally will make ploting the data easier
# This produces the same results as NCL's yyyymm_to_yyyyfrac() function
date_frac = np.empty_like(date)
for n in np.arange(0, num_months, 1):
yyyy = int(date[n] / 100)
mon = (date[n] / 100 - yyyy) * 100
date_frac[n] = yyyy + (mon - 1) / 12
###############################################################################
# Plot
# Generate figure (set its size (width, height) in inches) and axes
plt.figure(figsize=(12, 6))
ax = plt.axes()
# Create a list of colors based on the color bar values
colors = ['red' if (value > 0) else 'blue' for value in dsoik[::8]]
plt.bar(date_frac[::8],
dsoik[::8],
align='edge',
edgecolor='black',
color=colors,
width=8 / 12,
linewidth=.6)
# Use geocat.viz.util convenience function to add minor and major tick lines
gvutil.add_major_minor_ticks(ax,
x_minor_per_major=4,
y_minor_per_major=5,
labelsize=20)
# Use geocat.viz.util convenience function to set axes parameters
gvutil.set_axes_limits_and_ticks(ax,
ylim=(-3, 3),
yticks=np.linspace(-3, 3, 7),
yticklabels=np.linspace(-3, 3, 7),
xlim=(date_frac[40], date_frac[-16]),
xticks=np.linspace(1900, 1980, 5))
# Use geocat.viz.util convenience function to set titles and labels
gvutil.set_titles_and_labels(ax,
maintitle="Darwin Southern Oscillation Index",
ylabel='Anomalies',
maintitlefontsize=28,
labelfontsize=20)
plt.show()
| [
"geocat.datafiles.get",
"geocat.viz.util.add_major_minor_ticks",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.axes",
"numpy.empty_like",
"numpy.linspace",
"numpy.shape",
"geocat.viz.util.set_titles_and_labels",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((1430, 1449), 'numpy.empty_like', 'np.empty_like', (['date'], {}), '(date)\n', (1443, 1449), True, 'import numpy as np\n'), ((1459, 1486), 'numpy.arange', 'np.arange', (['(0)', 'num_months', '(1)'], {}), '(0, num_months, 1)\n', (1468, 1486), True, 'import numpy as np\n'), ((1755, 1782), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 6)'}), '(figsize=(12, 6))\n', (1765, 1782), True, 'import matplotlib.pyplot as plt\n'), ((1788, 1798), 'matplotlib.pyplot.axes', 'plt.axes', ([], {}), '()\n', (1796, 1798), True, 'import matplotlib.pyplot as plt\n'), ((1924, 2040), 'matplotlib.pyplot.bar', 'plt.bar', (['date_frac[::8]', 'dsoik[::8]'], {'align': '"""edge"""', 'edgecolor': '"""black"""', 'color': 'colors', 'width': '(8 / 12)', 'linewidth': '(0.6)'}), "(date_frac[::8], dsoik[::8], align='edge', edgecolor='black', color=\n colors, width=8 / 12, linewidth=0.6)\n", (1931, 2040), True, 'import matplotlib.pyplot as plt\n'), ((2161, 2253), 'geocat.viz.util.add_major_minor_ticks', 'gvutil.add_major_minor_ticks', (['ax'], {'x_minor_per_major': '(4)', 'y_minor_per_major': '(5)', 'labelsize': '(20)'}), '(ax, x_minor_per_major=4, y_minor_per_major=5,\n labelsize=20)\n', (2189, 2253), True, 'from geocat.viz import util as gvutil\n'), ((2827, 2975), 'geocat.viz.util.set_titles_and_labels', 'gvutil.set_titles_and_labels', (['ax'], {'maintitle': '"""Darwin Southern Oscillation Index"""', 'ylabel': '"""Anomalies"""', 'maintitlefontsize': '(28)', 'labelfontsize': '(20)'}), "(ax, maintitle=\n 'Darwin Southern Oscillation Index', ylabel='Anomalies',\n maintitlefontsize=28, labelfontsize=20)\n", (2855, 2975), True, 'from geocat.viz import util as gvutil\n'), ((3084, 3094), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3092, 3094), True, 'import matplotlib.pyplot as plt\n'), ((1117, 1147), 'geocat.datafiles.get', 'gdf.get', (['"""netcdf_files/soi.nc"""'], {}), "('netcdf_files/soi.nc')\n", (1124, 1147), True, 'import geocat.datafiles as gdf\n'), ((1197, 1211), 'numpy.shape', 'np.shape', (['date'], {}), '(date)\n', (1205, 1211), True, 'import numpy as np\n'), ((2528, 2549), 'numpy.linspace', 'np.linspace', (['(-3)', '(3)', '(7)'], {}), '(-3, 3, 7)\n', (2539, 2549), True, 'import numpy as np\n'), ((2596, 2617), 'numpy.linspace', 'np.linspace', (['(-3)', '(3)', '(7)'], {}), '(-3, 3, 7)\n', (2607, 2617), True, 'import numpy as np\n'), ((2730, 2756), 'numpy.linspace', 'np.linspace', (['(1900)', '(1980)', '(5)'], {}), '(1900, 1980, 5)\n', (2741, 2756), True, 'import numpy as np\n')] |
#
# 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.
"""Test that the driver can build tests effectively."""
import os
import unittest
from gabbi import driver
TESTS_DIR = 'test_gabbits'
class DriverTest(unittest.TestCase):
def setUp(self):
super(DriverTest, self).setUp()
self.loader = unittest.defaultTestLoader
self.test_dir = os.path.join(os.path.dirname(__file__), TESTS_DIR)
def test_driver_loads_three_tests(self):
suite = driver.build_tests(self.test_dir, self.loader,
host='localhost', port=8001)
self.assertEqual(1, len(suite._tests),
'top level suite contains one suite')
self.assertEqual(3, len(suite._tests[0]._tests),
'contained suite contains three tests')
the_one_test = suite._tests[0]._tests[0]
self.assertEqual('test_driver_sample_one',
the_one_test.__class__.__name__,
'test class name maps')
self.assertEqual('one',
the_one_test.test_data['name'])
self.assertEqual('/', the_one_test.test_data['url'])
def test_driver_prefix(self):
suite = driver.build_tests(self.test_dir, self.loader,
host='localhost', port=8001,
prefix='/mountpoint')
the_one_test = suite._tests[0]._tests[0]
the_two_test = suite._tests[0]._tests[1]
self.assertEqual('/mountpoint', the_one_test.prefix)
self.assertEqual('/mountpoint', the_two_test.prefix)
def test_build_requires_host_or_intercept(self):
with self.assertRaises(AssertionError):
driver.build_tests(self.test_dir, self.loader)
def test_build_with_url_provides_host(self):
"""This confirms that url provides the required host."""
suite = driver.build_tests(self.test_dir, self.loader,
url='https://foo.example.com')
first_test = suite._tests[0]._tests[0]
full_url = first_test._parse_url(first_test.test_data['url'])
ssl = first_test.test_data['ssl']
self.assertEqual('https://foo.example.com/', full_url)
self.assertTrue(ssl)
def test_build_require_ssl(self):
suite = driver.build_tests(self.test_dir, self.loader,
host='localhost',
require_ssl=True)
first_test = suite._tests[0]._tests[0]
full_url = first_test._parse_url(first_test.test_data['url'])
self.assertEqual('https://localhost:8001/', full_url)
suite = driver.build_tests(self.test_dir, self.loader,
host='localhost',
require_ssl=False)
first_test = suite._tests[0]._tests[0]
full_url = first_test._parse_url(first_test.test_data['url'])
self.assertEqual('http://localhost:8001/', full_url)
def test_build_url_target(self):
suite = driver.build_tests(self.test_dir, self.loader,
host='localhost', port='999',
url='https://example.com:1024/theend')
first_test = suite._tests[0]._tests[0]
full_url = first_test._parse_url(first_test.test_data['url'])
self.assertEqual('https://example.com:1024/theend/', full_url)
def test_build_url_target_forced_ssl(self):
suite = driver.build_tests(self.test_dir, self.loader,
host='localhost', port='999',
url='http://example.com:1024/theend',
require_ssl=True)
first_test = suite._tests[0]._tests[0]
full_url = first_test._parse_url(first_test.test_data['url'])
self.assertEqual('https://example.com:1024/theend/', full_url)
def test_build_url_use_prior_test(self):
suite = driver.build_tests(self.test_dir, self.loader,
host='localhost',
use_prior_test=True)
for test in suite._tests[0]._tests:
if test.test_data['name'] != 'use_prior_false':
expected_use_prior = True
else:
expected_use_prior = False
self.assertEqual(expected_use_prior,
test.test_data['use_prior_test'])
suite = driver.build_tests(self.test_dir, self.loader,
host='localhost',
use_prior_test=False)
for test in suite._tests[0]._tests:
self.assertEqual(False, test.test_data['use_prior_test'])
| [
"os.path.dirname",
"gabbi.driver.build_tests"
] | [((972, 1047), 'gabbi.driver.build_tests', 'driver.build_tests', (['self.test_dir', 'self.loader'], {'host': '"""localhost"""', 'port': '(8001)'}), "(self.test_dir, self.loader, host='localhost', port=8001)\n", (990, 1047), False, 'from gabbi import driver\n'), ((1723, 1824), 'gabbi.driver.build_tests', 'driver.build_tests', (['self.test_dir', 'self.loader'], {'host': '"""localhost"""', 'port': '(8001)', 'prefix': '"""/mountpoint"""'}), "(self.test_dir, self.loader, host='localhost', port=8001,\n prefix='/mountpoint')\n", (1741, 1824), False, 'from gabbi import driver\n'), ((2403, 2480), 'gabbi.driver.build_tests', 'driver.build_tests', (['self.test_dir', 'self.loader'], {'url': '"""https://foo.example.com"""'}), "(self.test_dir, self.loader, url='https://foo.example.com')\n", (2421, 2480), False, 'from gabbi import driver\n'), ((2822, 2908), 'gabbi.driver.build_tests', 'driver.build_tests', (['self.test_dir', 'self.loader'], {'host': '"""localhost"""', 'require_ssl': '(True)'}), "(self.test_dir, self.loader, host='localhost',\n require_ssl=True)\n", (2840, 2908), False, 'from gabbi import driver\n'), ((3171, 3258), 'gabbi.driver.build_tests', 'driver.build_tests', (['self.test_dir', 'self.loader'], {'host': '"""localhost"""', 'require_ssl': '(False)'}), "(self.test_dir, self.loader, host='localhost',\n require_ssl=False)\n", (3189, 3258), False, 'from gabbi import driver\n'), ((3557, 3676), 'gabbi.driver.build_tests', 'driver.build_tests', (['self.test_dir', 'self.loader'], {'host': '"""localhost"""', 'port': '"""999"""', 'url': '"""https://example.com:1024/theend"""'}), "(self.test_dir, self.loader, host='localhost', port='999',\n url='https://example.com:1024/theend')\n", (3575, 3676), False, 'from gabbi import driver\n'), ((3996, 4132), 'gabbi.driver.build_tests', 'driver.build_tests', (['self.test_dir', 'self.loader'], {'host': '"""localhost"""', 'port': '"""999"""', 'url': '"""http://example.com:1024/theend"""', 'require_ssl': '(True)'}), "(self.test_dir, self.loader, host='localhost', port='999',\n url='http://example.com:1024/theend', require_ssl=True)\n", (4014, 4132), False, 'from gabbi import driver\n'), ((4484, 4573), 'gabbi.driver.build_tests', 'driver.build_tests', (['self.test_dir', 'self.loader'], {'host': '"""localhost"""', 'use_prior_test': '(True)'}), "(self.test_dir, self.loader, host='localhost',\n use_prior_test=True)\n", (4502, 4573), False, 'from gabbi import driver\n'), ((4977, 5067), 'gabbi.driver.build_tests', 'driver.build_tests', (['self.test_dir', 'self.loader'], {'host': '"""localhost"""', 'use_prior_test': '(False)'}), "(self.test_dir, self.loader, host='localhost',\n use_prior_test=False)\n", (4995, 5067), False, 'from gabbi import driver\n'), ((872, 897), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (887, 897), False, 'import os\n'), ((2225, 2271), 'gabbi.driver.build_tests', 'driver.build_tests', (['self.test_dir', 'self.loader'], {}), '(self.test_dir, self.loader)\n', (2243, 2271), False, 'from gabbi import driver\n')] |
#!/pxrpythonsubst
#
# Copyright 2018 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
import os
import unittest
from maya import cmds
from maya import standalone
from maya.api import OpenMaya as OM
from pxr import Gf, Usd, UsdSkel, Vt
class testUsdExportSkeleton(unittest.TestCase):
@classmethod
def setUpClass(cls):
standalone.initialize('usd')
cmds.file(os.path.abspath('UsdExportSkeleton.ma'), open=True,
force=True)
cmds.loadPlugin('pxrUsd', quiet=True)
@classmethod
def tearDownClass(cls):
standalone.uninitialize()
def _AssertMatricesClose(self, gfm1, gfm2):
for i in xrange(0, 4):
for j in xrange(0, 4):
self.assertAlmostEqual(gfm1[i][j], gfm2[i][j], places=3)
def testSkeletonTopology(self):
"""Tests that the joint topology is correct."""
usdFile = os.path.abspath('UsdExportSkeleton.usda')
cmds.usdExport(mergeTransformAndShape=True, file=usdFile,
shadingMode='none')
stage = Usd.Stage.Open(usdFile)
skeleton = UsdSkel.Skeleton.Get(stage, '/skeleton_Hip')
self.assertTrue(skeleton)
joints = skeleton.GetJointsAttr().Get()
self.assertEqual(joints, Vt.TokenArray([
"Hip",
"Hip/Spine",
"Hip/Spine/Neck",
"Hip/Spine/Neck/Head",
"Hip/Spine/Neck/LArm",
"Hip/Spine/Neck/LArm/LHand",
# note: skips ExtraJoints because it's not a joint
"Hip/Spine/Neck/LArm/LHand/ExtraJoints/ExtraJoint1",
"Hip/Spine/Neck/LArm/LHand/ExtraJoints/ExtraJoint1/ExtraJoint2",
"Hip/Spine/Neck/RArm",
"Hip/Spine/Neck/RArm/RHand",
"Hip/RLeg",
"Hip/RLeg/RFoot",
"Hip/LLeg",
"Hip/LLeg/LFoot"
]))
def testSkelTransformDecomposition(self):
"""
Tests that the decomposed transform values, when recomposed, recreate
the correct Maya transformation matrix.
"""
usdFile = os.path.abspath('UsdExportSkeleton.usda')
cmds.usdExport(mergeTransformAndShape=True, file=usdFile,
shadingMode='none', frameRange=[1, 30])
stage = Usd.Stage.Open(usdFile)
anim = UsdSkel.PackedJointAnimation.Get(stage,
'/skeleton_Hip/Animation')
self.assertEqual(anim.GetJointsAttr().Get()[8],
"Hip/Spine/Neck/RArm")
animT = anim.GetTranslationsAttr()
animR = anim.GetRotationsAttr()
animS = anim.GetScalesAttr()
selList = OM.MSelectionList()
selList.add("RArm")
rArmDagPath = selList.getDagPath(0)
fnTransform = OM.MFnTransform(rArmDagPath)
for i in xrange(1, 31):
cmds.currentTime(i, edit=True)
mayaXf = fnTransform.transformation().asMatrix()
usdT = animT.Get(i)[8]
usdR = animR.Get(i)[8]
usdS = animS.Get(i)[8]
usdXf = UsdSkel.MakeTransform(usdT, usdR, usdS)
self._AssertMatricesClose(usdXf, Gf.Matrix4d(*mayaXf))
if __name__ == '__main__':
unittest.main(verbosity=2)
| [
"pxr.UsdSkel.Skeleton.Get",
"maya.api.OpenMaya.MFnTransform",
"maya.standalone.initialize",
"maya.cmds.currentTime",
"maya.api.OpenMaya.MSelectionList",
"pxr.UsdSkel.MakeTransform",
"maya.cmds.usdExport",
"pxr.UsdSkel.PackedJointAnimation.Get",
"pxr.Usd.Stage.Open",
"maya.cmds.loadPlugin",
"unit... | [((4135, 4161), 'unittest.main', 'unittest.main', ([], {'verbosity': '(2)'}), '(verbosity=2)\n', (4148, 4161), False, 'import unittest\n'), ((1331, 1359), 'maya.standalone.initialize', 'standalone.initialize', (['"""usd"""'], {}), "('usd')\n", (1352, 1359), False, 'from maya import standalone\n'), ((1464, 1501), 'maya.cmds.loadPlugin', 'cmds.loadPlugin', (['"""pxrUsd"""'], {'quiet': '(True)'}), "('pxrUsd', quiet=True)\n", (1479, 1501), False, 'from maya import cmds\n'), ((1556, 1581), 'maya.standalone.uninitialize', 'standalone.uninitialize', ([], {}), '()\n', (1579, 1581), False, 'from maya import standalone\n'), ((1881, 1922), 'os.path.abspath', 'os.path.abspath', (['"""UsdExportSkeleton.usda"""'], {}), "('UsdExportSkeleton.usda')\n", (1896, 1922), False, 'import os\n'), ((1931, 2008), 'maya.cmds.usdExport', 'cmds.usdExport', ([], {'mergeTransformAndShape': '(True)', 'file': 'usdFile', 'shadingMode': '"""none"""'}), "(mergeTransformAndShape=True, file=usdFile, shadingMode='none')\n", (1945, 2008), False, 'from maya import cmds\n'), ((2037, 2060), 'pxr.Usd.Stage.Open', 'Usd.Stage.Open', (['usdFile'], {}), '(usdFile)\n', (2051, 2060), False, 'from pxr import Gf, Usd, UsdSkel, Vt\n'), ((2081, 2125), 'pxr.UsdSkel.Skeleton.Get', 'UsdSkel.Skeleton.Get', (['stage', '"""/skeleton_Hip"""'], {}), "(stage, '/skeleton_Hip')\n", (2101, 2125), False, 'from pxr import Gf, Usd, UsdSkel, Vt\n'), ((3058, 3099), 'os.path.abspath', 'os.path.abspath', (['"""UsdExportSkeleton.usda"""'], {}), "('UsdExportSkeleton.usda')\n", (3073, 3099), False, 'import os\n'), ((3108, 3210), 'maya.cmds.usdExport', 'cmds.usdExport', ([], {'mergeTransformAndShape': '(True)', 'file': 'usdFile', 'shadingMode': '"""none"""', 'frameRange': '[1, 30]'}), "(mergeTransformAndShape=True, file=usdFile, shadingMode=\n 'none', frameRange=[1, 30])\n", (3122, 3210), False, 'from maya import cmds\n'), ((3234, 3257), 'pxr.Usd.Stage.Open', 'Usd.Stage.Open', (['usdFile'], {}), '(usdFile)\n', (3248, 3257), False, 'from pxr import Gf, Usd, UsdSkel, Vt\n'), ((3273, 3339), 'pxr.UsdSkel.PackedJointAnimation.Get', 'UsdSkel.PackedJointAnimation.Get', (['stage', '"""/skeleton_Hip/Animation"""'], {}), "(stage, '/skeleton_Hip/Animation')\n", (3305, 3339), False, 'from pxr import Gf, Usd, UsdSkel, Vt\n'), ((3590, 3609), 'maya.api.OpenMaya.MSelectionList', 'OM.MSelectionList', ([], {}), '()\n', (3607, 3609), True, 'from maya.api import OpenMaya as OM\n'), ((3704, 3732), 'maya.api.OpenMaya.MFnTransform', 'OM.MFnTransform', (['rArmDagPath'], {}), '(rArmDagPath)\n', (3719, 3732), True, 'from maya.api import OpenMaya as OM\n'), ((1379, 1418), 'os.path.abspath', 'os.path.abspath', (['"""UsdExportSkeleton.ma"""'], {}), "('UsdExportSkeleton.ma')\n", (1394, 1418), False, 'import os\n'), ((2242, 2620), 'pxr.Vt.TokenArray', 'Vt.TokenArray', (["['Hip', 'Hip/Spine', 'Hip/Spine/Neck', 'Hip/Spine/Neck/Head',\n 'Hip/Spine/Neck/LArm', 'Hip/Spine/Neck/LArm/LHand',\n 'Hip/Spine/Neck/LArm/LHand/ExtraJoints/ExtraJoint1',\n 'Hip/Spine/Neck/LArm/LHand/ExtraJoints/ExtraJoint1/ExtraJoint2',\n 'Hip/Spine/Neck/RArm', 'Hip/Spine/Neck/RArm/RHand', 'Hip/RLeg',\n 'Hip/RLeg/RFoot', 'Hip/LLeg', 'Hip/LLeg/LFoot']"], {}), "(['Hip', 'Hip/Spine', 'Hip/Spine/Neck', 'Hip/Spine/Neck/Head',\n 'Hip/Spine/Neck/LArm', 'Hip/Spine/Neck/LArm/LHand',\n 'Hip/Spine/Neck/LArm/LHand/ExtraJoints/ExtraJoint1',\n 'Hip/Spine/Neck/LArm/LHand/ExtraJoints/ExtraJoint1/ExtraJoint2',\n 'Hip/Spine/Neck/RArm', 'Hip/Spine/Neck/RArm/RHand', 'Hip/RLeg',\n 'Hip/RLeg/RFoot', 'Hip/LLeg', 'Hip/LLeg/LFoot'])\n", (2255, 2620), False, 'from pxr import Gf, Usd, UsdSkel, Vt\n'), ((3778, 3808), 'maya.cmds.currentTime', 'cmds.currentTime', (['i'], {'edit': '(True)'}), '(i, edit=True)\n', (3794, 3808), False, 'from maya import cmds\n'), ((3996, 4035), 'pxr.UsdSkel.MakeTransform', 'UsdSkel.MakeTransform', (['usdT', 'usdR', 'usdS'], {}), '(usdT, usdR, usdS)\n', (4017, 4035), False, 'from pxr import Gf, Usd, UsdSkel, Vt\n'), ((4081, 4101), 'pxr.Gf.Matrix4d', 'Gf.Matrix4d', (['*mayaXf'], {}), '(*mayaXf)\n', (4092, 4101), False, 'from pxr import Gf, Usd, UsdSkel, Vt\n')] |
""" Support matrices generation.
radmtx module contains two class objects: sender and receiver, representing
the ray sender and receiver in the rfluxmtx operation. sender object is can
be instantiated as a surface, a list of points, or a view, and these are
typical forms of a sender. Similarly, a receiver object can be instantiated as
a surface, sky, or suns.
"""
from __future__ import annotations
import os
import copy
import subprocess as sp
import tempfile as tf
import logging
from frads import makesky
from frads import radgeom
from frads import radutil, util
from typing import Optional
logger = logging.getLogger('frads.radmtx')
class Sender:
"""Sender object for matrix generation with the following attributes:
Attributes:
form(str): types of sender, {surface(s)|view(v)|points(p)}
sender(str): the sender object
xres(int): sender x dimension
yres(int): sender y dimension
"""
def __init__(self, *, form: str, sender: bytes,
xres: Optional[int], yres: Optional[int]):
"""Instantiate the instance.
Args:
form(str): Sender as (s, v, p) for surface, view, and points;
path(str): sender file path;
sender(str): content of the sender file;
xres(int): x resolution of the image;
yres(int): y resoluation or line count if form is pts;
"""
self.form = form
self.sender = sender
self.xres = xres
self.yres = yres
logger.debug("Sender: %s", sender)
@classmethod
def as_surface(cls, *, prim_list: list, basis: str,
offset=None, left=None):
"""
Construct a sender from a surface.
Args:
prim_list(list): a list of primitives
basis(str): sender sampling basis
offset(float): move the sender surface in its normal direction
left(bool): Use left-hand rule instead for matrix generation
Returns:
A sender object (Sender)
"""
prim_str = prepare_surface(prims=prim_list, basis=basis, offset=offset,
left=left, source=None, out=None)
return cls(form='s', sender=prim_str.encode(), xres=None, yres=None)
@classmethod
def as_view(cls, *, vu_dict: dict, ray_cnt: int, xres: int, yres: int) -> Sender:
"""
Construct a sender from a view.
Args:
vu_dict: a dictionary containing view parameters;
ray_cnt: ray count;
xres, yres: image resolution
c2c: Set to True to trim the fisheye corner rays.
Returns:
A sender object
"""
if None in (xres, yres):
raise ValueError("Need to specify resolution")
vcmd = f"vwrays {radutil.opt2str(vu_dict)} -x {xres} -y {yres} -d"
res_eval = util.spcheckout(vcmd.split()).decode().split()
xres, yres = int(res_eval[1]), int(res_eval[3])
logger.info("Changed resolution to %s %s", xres, yres)
cmd = f"vwrays -ff -x {xres} -y {yres} "
if ray_cnt > 1:
vu_dict['c'] = ray_cnt
vu_dict['pj'] = 0.7 # placeholder
logger.debug("Ray count is %s", ray_cnt)
cmd += radutil.opt2str(vu_dict)
if vu_dict['vt'] == 'a':
cmd += "|" + Sender.crop2circle(ray_cnt, xres)
vrays = sp.run(cmd, shell=True, check=True, stdout=sp.PIPE).stdout
return cls(form='v', sender=vrays, xres=xres, yres=yres)
@classmethod
def as_pts(cls, *, pts_list: list, ray_cnt=1) -> Sender:
"""Construct a sender from a list of points.
Args:
pts_list(list): a list of list of float
ray_cnt(int): sender ray count
Returns:
A sender object
"""
if pts_list is None:
raise ValueError("pts_list is None")
if not all(isinstance(item, list) for item in pts_list):
raise ValueError("All grid points has to be lists.")
pts_list = [i for i in pts_list for _ in range(ray_cnt)]
grid_str = os.linesep.join(
[' '.join(map(str, li)) for li in pts_list]) + os.linesep
return cls(form='p', sender=grid_str.encode(), xres=None, yres=len(pts_list))
@staticmethod
def crop2circle(ray_cnt: int, xres: int) -> str:
"""Flush the corner rays from a fisheye view
Args:
ray_cnt: ray count;
xres: resolution of the square image;
Returns:
Command to generate cropped rays
"""
cmd = "rcalc -if6 -of "
cmd += f'-e "DIM:{xres};CNT:{ray_cnt}" '
cmd += '-e "pn=(recno-1)/CNT+.5" '
cmd += '-e "frac(x):x-floor(x)" '
cmd += '-e "xpos=frac(pn/DIM);ypos=pn/(DIM*DIM)" '
cmd += '-e "incir=if(.25-(xpos-.5)*(xpos-.5)-(ypos-.5)*(ypos-.5),1,0)" '
cmd += ' -e "$1=$1;$2=$2;$3=$3;$4=$4*incir;$5=$5*incir;$6=$6*incir"'
if os.name == "posix":
cmd = cmd.replace('"', "'")
return cmd
class Receiver:
"""Receiver object for matrix generation."""
def __init__(self, receiver: str, basis: str, modifier=None) -> None:
"""Instantiate the receiver object.
Args:
receiver(str): receiver string which can be appended to one another
basis(str): receiver basis, usually kf, r4, r6;
modifier(str): modifiers to the receiver objects;
"""
self.receiver = receiver
self.basis = basis
self.modifier = modifier
logger.debug("Receivers: %s", receiver)
def __add__(self, other: Receiver) -> Receiver:
self.receiver += '\n' + other.receiver
return self
@classmethod
def as_sun(cls, *, basis, smx_path, window_normals, full_mod=False) -> Receiver:
"""Instantiate a sun receiver object.
Args:
basis: receiver sampling basis {kf | r1 | sc25...}
smx_path: sky/sun matrix file path
window_paths: window file paths
Returns:
A sun receiver object
"""
gensun = makesky.Gensun(int(basis[-1]))
if (smx_path is None) and (window_normals is None):
str_repr = gensun.gen_full()
return cls(receiver=str_repr, basis=basis, modifier=gensun.mod_str)
str_repr, mod_str = gensun.gen_cull(smx_path=smx_path, window_normals=window_normals)
if full_mod:
return cls(receiver=str_repr, basis=basis, modifier=gensun.mod_str)
return cls(receiver=str_repr, basis=basis, modifier=mod_str)
@classmethod
def as_sky(cls, basis) -> Receiver:
"""Instantiate a sky receiver object.
Args:
basis: receiver sampling basis {kf | r1 | sc25...}
Returns:
A sky receiver object
"""
assert basis.startswith('r'), 'Sky basis need to be Treganza/Reinhart'
sky_str = makesky.basis_glow(basis)
logger.debug(sky_str)
return cls(receiver=sky_str, basis=basis)
@classmethod
def as_surface(cls, prim_list: list, basis: str, out: str,
offset=None, left=False, source='glow') -> Receiver:
"""Instantiate a surface receiver object.
Args:
prim_list: list of primitives(dict)
basis: receiver sampling basis {kf | r1 | sc25...}
out: output path
offset: offset the surface in its normal direction
left: use instead left-hand rule for matrix generation
source: light source for receiver object {glow|light}
Returns:
A surface receiver object
"""
rcvr_str = prepare_surface(prims=prim_list, basis=basis, offset=offset,
left=left, source=source, out=out)
return cls(receiver=rcvr_str, basis=basis)
def prepare_surface(*, prims, basis, left, offset, source, out) -> str:
"""Prepare the sender or receiver surface, adding appropriate tags.
Args:
prims(list): list of primitives
basis(str): sampling basis
left(bool): use instead the left-hand rule
offset(float): offset surface in its normal direction
source(str): surface light source for receiver
out: output path
Returns:
The receiver as string
"""
if basis is None:
raise ValueError('Sampling basis cannot be None')
upvector = str(radutil.up_vector(prims)).replace(' ', ',')
upvector = "-" + upvector if left else upvector
modifier_set = {p.modifier for p in prims}
if len(modifier_set) != 1:
logger.warning("Primitives don't share modifier")
src_mod = f"rflx{prims[0].modifier}"
header = f'#@rfluxmtx h={basis} u={upvector}\n'
if out is not None:
header += f'#@rfluxmtx o="{out}"\n\n'
if source is not None:
source_line = f"void {source} {src_mod}\n0\n0\n4 1 1 1 0\n\n"
header += source_line
modifiers = [p.modifier for p in prims]
content = ''
for prim in prims:
if prim.identifier in modifiers:
_identifier = 'discarded'
else:
_identifier = prim.identifier
_modifier = src_mod
if offset is not None:
poly = radutil.parse_polygon(prim.real_arg)
offset_vec = poly.normal().scale(offset)
moved_pts = [pt + offset_vec for pt in poly.vertices]
_real_args = radgeom.Polygon(moved_pts).to_real()
else:
_real_args = prim.real_arg
new_prim = radutil.Primitive(
_modifier, prim.ptype, _identifier, prim.str_arg, _real_args)
content += str(new_prim) + '\n'
return header + content
def rfluxmtx(*, sender, receiver, env, opt=None, out=None):
"""Calling rfluxmtx to generate the matrices.
Args:
sender: Sender object
receiver: Receiver object
env: model environment, basically anything that's not the
sender or receiver
opt: option string
out: output path
Returns:
return the stdout of the command
"""
if None in (sender, receiver):
raise ValueError("Sender/Receiver object is None")
opt = '' if opt is None else opt
with tf.TemporaryDirectory() as tempd:
receiver_path = os.path.join(tempd, 'receiver')
with open(receiver_path, 'w') as wtr:
wtr.write(receiver.receiver)
if isinstance(env[0], dict):
env_path = os.path.join(tempd, 'env')
with open(env_path, 'w') as wtr:
[wtr.write(str(prim)) for prim in env]
env_paths = [env_path]
else:
env_paths = env
cmd = ['rfluxmtx'] + opt.split()
stdin = None
if sender.form == 's':
sender_path = os.path.join(tempd, 'sender')
with open(sender_path, 'wb') as wtr:
wtr.write(sender.sender)
cmd.extend([sender_path, receiver_path])
elif sender.form == 'p':
cmd.extend(['-I+', '-faa', '-y', str(sender.yres), '-', receiver_path])
stdin = sender.sender
elif sender.form == 'v':
cmd.extend(["-ffc", "-x", str(sender.xres), "-y", str(sender.yres), "-ld-"])
if out is not None:
util.mkdir_p(out)
out = os.path.join(out, '%04d.hdr')
cmd.extend(["-o", out])
cmd.extend(['-', receiver_path])
stdin = sender.sender
cmd.extend(env_paths)
return util.spcheckout(cmd, inp=stdin)
def rcvr_oct(receiver, env, oct_path):
"""Generate an octree of the environment and the receiver.
Args:
receiver: receiver object
env: environment file paths
oct_path: Path to write the octree to
"""
with tf.TemporaryDirectory() as tempd:
receiver_path = os.path.join(tempd, 'rcvr_path')
with open(receiver_path, 'w') as wtr:
wtr.write(receiver.receiver)
ocmd = ['oconv', '-f'] + env + [receiver_path]
octree = util.spcheckout(ocmd)
with open(oct_path, 'wb') as wtr:
wtr.write(octree)
def rcontrib(*, sender, modifier: str, octree, out, opt) -> None:
"""Calling rcontrib to generate the matrices.
Args:
sender: Sender object
modifier: modifier str listing the receivers in octree
octree: the octree that includes the environment and the receiver
opt: option string
out: output path
Returns:
None
"""
lopt = opt.split()
lopt.append('-fo+')
with tf.TemporaryDirectory() as tempd:
modifier_path = os.path.join(tempd, 'modifier')
with open(modifier_path, 'w') as wtr:
wtr.write(modifier)
cmd = ['rcontrib'] + lopt
stdin = sender.sender
if sender.form == 'p':
cmd += ['-I+', '-faf', '-y', str(sender.yres)]
elif sender.form == 'v':
util.mkdir_p(out)
out = os.path.join(out, '%04d.hdr')
cmd += ['-ffc', '-x', str(sender.xres), '-y', str(sender.yres)]
cmd += ['-o', out, '-M', modifier_path, octree]
util.spcheckout(cmd, inp=stdin)
| [
"logging.getLogger",
"frads.radutil.Primitive",
"tempfile.TemporaryDirectory",
"frads.radgeom.Polygon",
"subprocess.run",
"frads.makesky.basis_glow",
"frads.radutil.opt2str",
"os.path.join",
"frads.util.spcheckout",
"frads.radutil.parse_polygon",
"frads.radutil.up_vector",
"frads.util.mkdir_p"... | [((608, 641), 'logging.getLogger', 'logging.getLogger', (['"""frads.radmtx"""'], {}), "('frads.radmtx')\n", (625, 641), False, 'import logging\n'), ((3273, 3297), 'frads.radutil.opt2str', 'radutil.opt2str', (['vu_dict'], {}), '(vu_dict)\n', (3288, 3297), False, 'from frads import radutil, util\n'), ((6958, 6983), 'frads.makesky.basis_glow', 'makesky.basis_glow', (['basis'], {}), '(basis)\n', (6976, 6983), False, 'from frads import makesky\n'), ((9570, 9649), 'frads.radutil.Primitive', 'radutil.Primitive', (['_modifier', 'prim.ptype', '_identifier', 'prim.str_arg', '_real_args'], {}), '(_modifier, prim.ptype, _identifier, prim.str_arg, _real_args)\n', (9587, 9649), False, 'from frads import radutil, util\n'), ((10271, 10294), 'tempfile.TemporaryDirectory', 'tf.TemporaryDirectory', ([], {}), '()\n', (10292, 10294), True, 'import tempfile as tf\n'), ((10329, 10360), 'os.path.join', 'os.path.join', (['tempd', '"""receiver"""'], {}), "(tempd, 'receiver')\n", (10341, 10360), False, 'import os\n'), ((11559, 11590), 'frads.util.spcheckout', 'util.spcheckout', (['cmd'], {'inp': 'stdin'}), '(cmd, inp=stdin)\n', (11574, 11590), False, 'from frads import radutil, util\n'), ((11839, 11862), 'tempfile.TemporaryDirectory', 'tf.TemporaryDirectory', ([], {}), '()\n', (11860, 11862), True, 'import tempfile as tf\n'), ((11897, 11929), 'os.path.join', 'os.path.join', (['tempd', '"""rcvr_path"""'], {}), "(tempd, 'rcvr_path')\n", (11909, 11929), False, 'import os\n'), ((12089, 12110), 'frads.util.spcheckout', 'util.spcheckout', (['ocmd'], {}), '(ocmd)\n', (12104, 12110), False, 'from frads import radutil, util\n'), ((12623, 12646), 'tempfile.TemporaryDirectory', 'tf.TemporaryDirectory', ([], {}), '()\n', (12644, 12646), True, 'import tempfile as tf\n'), ((12681, 12712), 'os.path.join', 'os.path.join', (['tempd', '"""modifier"""'], {}), "(tempd, 'modifier')\n", (12693, 12712), False, 'import os\n'), ((13196, 13227), 'frads.util.spcheckout', 'util.spcheckout', (['cmd'], {'inp': 'stdin'}), '(cmd, inp=stdin)\n', (13211, 13227), False, 'from frads import radutil, util\n'), ((3406, 3457), 'subprocess.run', 'sp.run', (['cmd'], {'shell': '(True)', 'check': '(True)', 'stdout': 'sp.PIPE'}), '(cmd, shell=True, check=True, stdout=sp.PIPE)\n', (3412, 3457), True, 'import subprocess as sp\n'), ((9280, 9316), 'frads.radutil.parse_polygon', 'radutil.parse_polygon', (['prim.real_arg'], {}), '(prim.real_arg)\n', (9301, 9316), False, 'from frads import radutil, util\n'), ((10508, 10534), 'os.path.join', 'os.path.join', (['tempd', '"""env"""'], {}), "(tempd, 'env')\n", (10520, 10534), False, 'import os\n'), ((10831, 10860), 'os.path.join', 'os.path.join', (['tempd', '"""sender"""'], {}), "(tempd, 'sender')\n", (10843, 10860), False, 'import os\n'), ((2819, 2843), 'frads.radutil.opt2str', 'radutil.opt2str', (['vu_dict'], {}), '(vu_dict)\n', (2834, 2843), False, 'from frads import radutil, util\n'), ((8461, 8485), 'frads.radutil.up_vector', 'radutil.up_vector', (['prims'], {}), '(prims)\n', (8478, 8485), False, 'from frads import radutil, util\n'), ((12990, 13007), 'frads.util.mkdir_p', 'util.mkdir_p', (['out'], {}), '(out)\n', (13002, 13007), False, 'from frads import radutil, util\n'), ((13026, 13055), 'os.path.join', 'os.path.join', (['out', '"""%04d.hdr"""'], {}), "(out, '%04d.hdr')\n", (13038, 13055), False, 'import os\n'), ((9461, 9487), 'frads.radgeom.Polygon', 'radgeom.Polygon', (['moved_pts'], {}), '(moved_pts)\n', (9476, 9487), False, 'from frads import radgeom\n'), ((11325, 11342), 'frads.util.mkdir_p', 'util.mkdir_p', (['out'], {}), '(out)\n', (11337, 11342), False, 'from frads import radutil, util\n'), ((11365, 11394), 'os.path.join', 'os.path.join', (['out', '"""%04d.hdr"""'], {}), "(out, '%04d.hdr')\n", (11377, 11394), False, 'import os\n')] |