content
stringlengths
0
894k
type
stringclasses
2 values
import os import pickle from tqdm import tqdm from config import data_file, thchs30_folder # split in ['train', 'test', 'dev'] def get_thchs30_data(split): print('loading {} samples...'.format(split)) data_dir = os.path.join(thchs30_folder, 'data') wave_dir = os.path.join(thchs30_folder, split) samples = [] for file in tqdm(os.listdir(wave_dir)): file_path = os.path.join(wave_dir, file) if file_path.endswith('.wav'): text_path = os.path.join(data_dir, file + '.trn') with open(text_path, 'r', encoding='utf-8') as f: text = f.readlines()[1].strip() samples.append({'audiopath': file_path, 'text': text}) return samples def main(): data = dict() data['train'] = get_thchs30_data('train') data['dev'] = get_thchs30_data('dev') data['test'] = get_thchs30_data('test') with open(data_file, 'wb') as file: pickle.dump(data, file) print('num_train: ' + str(len(data['train']))) print('num_dev: ' + str(len(data['dev']))) print('num_test: ' + str(len(data['test']))) if __name__ == "__main__": main()
python
#!/bin/env python2 import cairo import os.path this = os.path.dirname(__file__) def millimeters_to_poscript_points(mm): inches = mm / 25.4 return inches * 72 def css_px_to_poscript_points(px): inches = px / 96. return inches * 72 cairo.PDFSurface(os.path.join(this, "A4_one_empty_page.pdf"), millimeters_to_poscript_points(210), millimeters_to_poscript_points(297)) png = cairo.ImageSurface.create_from_png(os.path.join(this, "pattern_4x4.png")) pattern = cairo.SurfacePattern(png) pattern.set_filter(cairo.FILTER_NEAREST) out = cairo.PDFSurface(os.path.join(this, "pattern_4x4.pdf"), css_px_to_poscript_points(4), css_px_to_poscript_points(4)) ctx = cairo.Context(out) ctx.set_source(pattern) ctx.paint()
python
import numpy as np from torch.utils.data import Subset from sklearn.model_selection import train_test_split def split_data(dataset,splits=(0.8,0.2),seed=None): assert np.sum(splits) == 1 assert (len(splits)==2) | (len(splits)==3) if len(splits) == 2: train_idx, test_idx, _, _ = train_test_split(range(len(dataset)), dataset.Y, stratify=dataset.Y, test_size=splits[1], random_state=seed) return Subset(dataset,train_idx), Subset(dataset,test_idx) else: train_idx, test_idx, _, _ = train_test_split(range(len(dataset)), dataset.Y, stratify=dataset.Y, test_size=(splits[1]+splits[2]), random_state=seed) test_idx, val_idx, _, _ = train_test_split(test_idx, dataset.Y[test_idx], stratify=dataset.Y[test_idx], test_size=splits[2]/(splits[1] + splits[2]), random_state=seed) return Subset(dataset,train_idx), Subset(dataset,test_idx), Subset(dataset,val_idx)
python
from __future__ import print_function # ---------------------------------------------------------------- # Copyright 2016 Cisco Systems # # 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. # ------------------------------------------------------------------ # ---------------------------------------------------------------- # Utility functions to create and return a Session from optparse import OptionParser, IndentedHelpFormatter from ydk.providers import NetconfServiceProvider import logging class HelpFormatterWithLineBreaks(IndentedHelpFormatter): def format_description(self, description): result = "" if description is not None: description_paragraphs = description.split("\n") for paragraph in description_paragraphs: result += self._format_text(paragraph) + "\n" return result def init_logging(): """ Initialize the logging infra and add a handler """ logger = logging.getLogger('ydk') # logger.setLevel(logging.INFO) # create file handler fh = logging.FileHandler('sample.log') fh.setLevel(logging.DEBUG) # create a console logger too ch = logging.StreamHandler() ch.setLevel(logging.INFO) # add the handlers to the logger formatter = logging.Formatter(("%(asctime)s - %(name)s - %(levelname)s - %(message)s")) ch.setFormatter(formatter) fh.setFormatter(formatter) logger.addHandler(fh) logger.addHandler(ch) def establish_session(): usage = """%prog [-h | --help] [options] """ parser = OptionParser(usage, formatter=HelpFormatterWithLineBreaks()) parser.add_option("-v", "--version", dest="version", help="Force NETCONF version 1.0 or 1.1") parser.add_option("-u", "--user", dest="username", default="admin") parser.add_option("-p", "--password", dest="password", default="admin") parser.add_option("--proto", dest="proto", default="ssh", help="Transport protocol to use, one of ssh or tcp") parser.add_option("--host", dest="host", default="localhost", help="NETCONF agent hostname") parser.add_option("--port", dest="port", default=830, type="int", help="NETCONF agent SSH port") (o, args) = parser.parse_args() print('Establishing connection with device %s:%d using %s...'%(o.host, o.port, o.proto)) ne = NetconfServiceProvider(address=o.host, port=o.port, username=o.username, password=o.password, protocol=o.proto) print('Connection established') return ne
python
import torch import torch.nn as nn import torch.nn.functional as F class Matching(nn.Module): def __init__(self, vis_dim, lang_dim, jemb_dim, jemb_drop_out): super(Matching, self).__init__() self.vis_emb_fc = nn.Sequential(nn.Linear(vis_dim, jemb_dim), nn.BatchNorm1d(jemb_dim), nn.ReLU(), nn.Dropout(jemb_drop_out), nn.Linear(jemb_dim, jemb_dim), nn.BatchNorm1d(jemb_dim)) self.lang_emb_fc = nn.Sequential(nn.Linear(lang_dim, jemb_dim), nn.BatchNorm1d(jemb_dim), nn.ReLU(), nn.Dropout(jemb_drop_out), nn.Linear(jemb_dim, jemb_dim), nn.BatchNorm1d(jemb_dim)) def forward(self, visual_input, lang_input): assert visual_input.size(0) == lang_input.size(0) visual_feat = visual_input.view((visual_input.size(0) * visual_input.size(1), -1)) lang_feat = lang_input visual_emb = self.vis_emb_fc(visual_feat) lang_emb = self.lang_emb_fc(lang_feat) # l2-normalize visual_emb_normalized = F.normalize(visual_emb, p=2, dim=1) lang_emb_normalized = F.normalize(lang_emb, p=2, dim=1) block_visual_emb_normalized = visual_emb_normalized.view((visual_input.size(0), visual_input.size(1), -1)) block_lang_emb_normalized = lang_emb_normalized.unsqueeze(1).expand((visual_input.size(0), visual_input.size(1), lang_emb_normalized.size(1))) cossim = torch.sum(block_lang_emb_normalized * block_visual_emb_normalized, 2) return cossim
python
import torch import torch.nn as nn class LeNet(torch.nn.Module): """This is improved version of LeNet """ def __init__(self): super(LeNet, self).__init__() self.network = nn.Sequential(nn.Conv2d(1, 6, kernel_size=5, padding=2), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(6, 16, kernel_size=5), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2), nn.Flatten(), nn.Linear(400, 120), nn.ReLU(), nn.Dropout(p=0.5), nn.Linear(120, 84), nn.ReLU(), nn.Dropout(p=0.5), nn.Linear(84, 10)) def forward(self, x): result = self.network(x) return result
python
# -*- test-case-name: twisted.positioning.test -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ The Twisted positioning framework. @since: 14.0 """
python
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack.package import * class Libpam(AutotoolsPackage): """Example PAM module demonstrating two-factor authentication for logging into servers via SSH, OpenVPN, etc""" homepage = "https://github.com/google/google-authenticator-libpam" url = "https://github.com/google/google-authenticator-libpam/archive/1.09.tar.gz" version('1.09', sha256='ab1d7983413dc2f11de2efa903e5c326af8cb9ea37765dacb39949417f7cd037') version('1.08', sha256='6f6d7530261ba9e2ece84214f1445857d488b7851c28a58356b49f2d9fd36290') version('1.07', sha256='104a158e013585e20287f8d33935e93c711b96281e6dda621a5c19575d0b0405') depends_on('autoconf', type='build') depends_on('automake', type='build') depends_on('libtool', type='build') depends_on('m4', type='build') depends_on('linux-pam') def autoreconf(self, spec, prefix): bash = which('bash') bash('./bootstrap.sh')
python
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from __future__ import division from __future__ import print_function import filecmp import os from absl import logging import tensorflow.compat.v2 as tf from tensorflow_examples.lite.model_maker.core import compat from tensorflow_examples.lite.model_maker.core import test_util from tensorflow_examples.lite.model_maker.core.data_util import object_detector_dataloader from tensorflow_examples.lite.model_maker.core.export_format import ExportFormat from tensorflow_examples.lite.model_maker.core.export_format import QuantizationType from tensorflow_examples.lite.model_maker.core.task import model_spec from tensorflow_examples.lite.model_maker.core.task import object_detector class ObjectDetectorTest(tf.test.TestCase): def testEfficientDetLite0(self): # Gets model specification. spec = model_spec.get('efficientdet_lite0') # Prepare data. images_dir, annotations_dir, label_map = test_util.create_pascal_voc( self.get_temp_dir()) data = object_detector_dataloader.DataLoader.from_pascal_voc( images_dir, annotations_dir, label_map) # Train the model. task = object_detector.create(data, spec, batch_size=1, epochs=1) self.assertEqual(spec.config.num_classes, 2) # Evaluate trained model metrics = task.evaluate(data) self.assertIsInstance(metrics, dict) self.assertGreaterEqual(metrics['AP'], 0) # Export the model to saved model. output_path = os.path.join(self.get_temp_dir(), 'saved_model') task.export(self.get_temp_dir(), export_format=ExportFormat.SAVED_MODEL) self.assertTrue(os.path.isdir(output_path)) self.assertNotEqual(len(os.listdir(output_path)), 0) # Export the model to TFLite model. output_path = os.path.join(self.get_temp_dir(), 'float.tflite') task.export( self.get_temp_dir(), tflite_filename='float.tflite', quantization_type=QuantizationType.FP32, export_format=ExportFormat.TFLITE, with_metadata=True, export_metadata_json_file=True) # Checks the sizes of the float32 TFLite model files in bytes. model_size = 13476379 self.assertNear(os.path.getsize(output_path), model_size, 50000) json_output_file = os.path.join(self.get_temp_dir(), 'float.json') self.assertTrue(os.path.isfile(json_output_file)) self.assertGreater(os.path.getsize(json_output_file), 0) expected_json_file = test_util.get_test_data_path( 'efficientdet_lite0_metadata.json') self.assertTrue(filecmp.cmp(json_output_file, expected_json_file)) # Evaluate the TFLite model. task.evaluate_tflite(output_path, data) self.assertIsInstance(metrics, dict) self.assertGreaterEqual(metrics['AP'], 0) # Export the model to quantized TFLite model. # TODO(b/175173304): Skips the test for stable tensorflow 2.4 for now since # it fails. Will revert this change after TF upgrade. if tf.__version__.startswith('2.4'): return # Not include QuantizationType.FP32 here since we have already tested it # above together with metadata file test. types = (QuantizationType.INT8, QuantizationType.FP16, QuantizationType.DYNAMIC) # The sizes of the TFLite model files in bytes. model_sizes = (4439987, 6840331, 4289875) for quantization_type, model_size in zip(types, model_sizes): filename = quantization_type.name.lower() + '.tflite' output_path = os.path.join(self.get_temp_dir(), filename) if quantization_type == QuantizationType.INT8: representative_data = data else: representative_data = None task.export( self.get_temp_dir(), quantization_type=quantization_type, tflite_filename=filename, representative_data=representative_data, export_format=ExportFormat.TFLITE) self.assertNear(os.path.getsize(output_path), model_size, 100) if __name__ == '__main__': logging.set_verbosity(logging.ERROR) # Load compressed models from tensorflow_hub os.environ['TFHUB_MODEL_LOAD_FORMAT'] = 'COMPRESSED' compat.setup_tf_behavior(tf_version=2) tf.test.main()
python
''' This code loads the results and prepares Fig8a. (c) Efrat Shimron, UC Berkeley, 2021 ''' import os import matplotlib.pyplot as plt import numpy as np R = 4 pad_ratio_vec = np.array([1, 2]) print('============================================================================== ') print(' crime impact estimation ') print('=============================================================================== ') pad_ratio_test = np.array([1]) samp_type = 'weak' method_str = 'DL' # data_type = 'pathology_1' data_type = 'pathology_2' zones_vec = np.array([1, 2]) # np.array([1,2]) # load results results_dir = data_type + f'_results_R{R}/' gold_filename = results_dir + 'gold_dict.npy' rec_filename = results_dir + method_str + '_dict.npy' gold_container = np.load(gold_filename, allow_pickle=True) rec_container = np.load(rec_filename, allow_pickle=True) # display results per training pad ratio for pad_i, pad_ratio in enumerate(pad_ratio_vec): # training pad ratio; the test pad ratio was always 2 pad_ratio_str = int(pad_ratio_vec[pad_i]) rec_gold_rotated = gold_container.item()[(pad_ratio, samp_type)] rec_rotated = rec_container.item()[(pad_ratio, samp_type)] if pad_i == 0: cmax = np.max([np.abs(rec_gold_rotated), np.abs(rec_rotated)]) # display full-FOV rec fig = plt.figure() plt.imshow(rec_rotated, cmap="gray") # plt.axis('off') plt.clim(0, cmax) plt.title(f'rec - train pad {pad_ratio_str}') plt.show() # display zoomed-in images for z_i in range(zones_vec.shape[0]): zone_str = f'zone_{zones_vec[z_i]}' figs_folder = f'Fig8a_R{R}' + data_type + '_' + zone_str if not os.path.exists(figs_folder): os.makedirs(figs_folder) if data_type == 'pathology_1': if zones_vec[z_i] == 1: # prepare zoomed-in figures for the paper # zoom-in coordinates for pathology 1 x1 = 335 x2 = 380 y1 = 210 y2 = 300 # scale the zoom-in coordinates to fit changing image size x1s = int(x1 * pad_ratio_test) x2s = int(x2 * pad_ratio_test) y1s = int(y1 * pad_ratio_test) y2s = int(y2 * pad_ratio_test) elif zones_vec[z_i] == 2: x1 = 325 x2 = 370 y1 = 70 y2 = 160 # scale the zoom-in coordinates to fit changing image size x1s = int(x1 * pad_ratio_test) x2s = int(x2 * pad_ratio_test) y1s = int(y1 * pad_ratio_test) y2s = int(y2 * pad_ratio_test) elif data_type == 'pathology_2': if zones_vec[z_i] == 1: x1 = 310 x2 = 350 y1 = 200 y2 = 280 # scale the zoom-in coordinates to fit changing image size x1s = int(x1 * pad_ratio_test) x2s = int(x2 * pad_ratio_test) y1s = int(y1 * pad_ratio_test) y2s = int(y2 * pad_ratio_test) elif zones_vec[z_i] == 2: x1 = 310 x2 = 360 y1 = 90 y2 = 190 # scale the zoom-in coordinates to fit changing image size x1s = int(x1 * pad_ratio_test) x2s = int(x2 * pad_ratio_test) y1s = int(y1 * pad_ratio_test) y2s = int(y2 * pad_ratio_test) # rec zoomed - png fig = plt.figure() plt.imshow(rec_rotated[x1s:x2s, y1s:y2s], cmap="gray") plt.axis('off') plt.clim(0, cmax) plt.title( f'{method_str} train on pad {pad_ratio_str} & test on {str(int(pad_ratio_test))} - zone {zones_vec[z_i]}') plt.show() figname = figs_folder + f'/{method_str}_training_pad_x{pad_ratio_str}_{samp_type}_VD_zone_{zones_vec[z_i]}_zoomed' fig.savefig(figname, dpi=1000) # rec zoomed - eps figure fig = plt.figure() plt.imshow(rec_rotated[x1s:x2s, y1s:y2s], cmap="gray") plt.axis('off') plt.clim(0, cmax) plt.title( f'{method_str} train on pad {pad_ratio_str} & test on {str(int(pad_ratio_test))} - zone {zones_vec[z_i]}') plt.show() figname = figs_folder + f'/{method_str}_training_pad_x{pad_ratio_str}_{samp_type}_VD_zone_{zones_vec[z_i]}_zoomed.eps' fig.savefig(figname, format='eps', dpi=1000)
python
from django.core.urlresolvers import reverse from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.core.paginator import Paginator from go.base import utils from go.base.tests.helpers import GoDjangoTestCase, DjangoVumiApiHelper from go.vumitools.api import VumiApi, VumiUserApi from go.vumitools.conversation.definition import ConversationDefinitionBase from go.conversation.view_definition import ConversationViewDefinitionBase class TestAuthentication(GoDjangoTestCase): def setUp(self): self.vumi_helper = self.add_helper(DjangoVumiApiHelper()) self.user = self.vumi_helper.make_django_user().get_django_user() def test_user_account_created(self): """test that we have a user account""" self.assertEqual('[email protected]', self.user.userprofile.get_user_account().username) def test_redirect_to_login(self): """test the authentication mechanism""" response = self.client.get(reverse('conversations:index')) self.assertRedirects(response, '%s?next=%s' % ( reverse('auth_login'), reverse('conversations:index'))) def test_login(self): self.client.login(username=self.user.email, password='password') response = self.client.get(reverse('conversations:index')) self.assertContains(response, 'Dashboard') def test_logged_out(self): """test logout & redirect after logout""" self.client.login(username=self.user.email, password='password') response = self.client.get(reverse('auth_logout')) response = self.client.get(reverse('conversations:index')) self.assertRedirects(response, '%s?next=%s' % ( reverse('auth_login'), reverse('conversations:index'))) class FakeTemplateToken(object): def __init__(self, contents): self.contents = contents class TestUtils(GoDjangoTestCase): def setUp(self): self.vumi_helper = self.add_helper(DjangoVumiApiHelper()) self.user = self.vumi_helper.make_django_user().get_django_user() def test_vumi_api_for_user(self): user_api = utils.vumi_api_for_user(self.user) self.assertTrue(isinstance(user_api, VumiUserApi)) self.assertEqual(user_api.user_account_key, self.user.get_profile().user_account) def test_vumi_api(self): vumi_api = utils.vumi_api() self.assertTrue(isinstance(vumi_api, VumiApi)) def test_padded_queryset(self): short_list = get_user_model().objects.all()[:1] padded_list = utils.padded_queryset(short_list) expected_list = list(short_list) + [None, None, None, None, None] self.assertEqual(padded_list, expected_list) def test_padded_queryset_limiting(self): long_list = Permission.objects.all() self.assertTrue(long_list.count() > 6) padded_list = utils.padded_queryset(long_list) self.assertEqual(len(padded_list), 6) def test_page_range_window(self): paginator = Paginator(range(100), 5) self.assertEqual(utils.page_range_window(paginator.page(1), 5), [1, 2, 3, 4, 5, 6, 7, 8, 9]) self.assertEqual(utils.page_range_window(paginator.page(5), 5), [1, 2, 3, 4, 5, 6, 7, 8, 9]) self.assertEqual(utils.page_range_window(paginator.page(9), 5), [5, 6, 7, 8, 9, 10, 11, 12, 13]) self.assertEqual(utils.page_range_window(paginator.page(20), 5), [12, 13, 14, 15, 16, 17, 18, 19, 20]) paginator = Paginator(range(3), 5) self.assertEqual(utils.page_range_window(paginator.page(1), 5), [1]) paginator = Paginator(range(3), 3) self.assertEqual(utils.page_range_window(paginator.page(1), 5), [1]) paginator = Paginator(range(4), 3) self.assertEqual(utils.page_range_window(paginator.page(1), 5), [1, 2]) def test_get_conversation_view_definition(self): view_def = utils.get_conversation_view_definition('bulk_message', None) conv_def = view_def._conv_def self.assertTrue(isinstance(view_def, ConversationViewDefinitionBase)) self.assertTrue(isinstance(conv_def, ConversationDefinitionBase)) self.assertEqual('bulk_message', conv_def.conversation_type)
python
import py from pypy.translator.cli.test.runtest import compile_function from pypy.translator.oosupport.test_template.backendopt import BaseTestOptimizedSwitch class TestOptimizedSwitch(BaseTestOptimizedSwitch): def getcompiled(self, fn, annotation): return compile_function(fn, annotation, backendopt=True)
python
""" Low level *Skype for Linux* interface implemented using *XWindows messaging*. Uses direct *Xlib* calls through *ctypes* module. This module handles the options that you can pass to `Skype.__init__` for Linux machines when the transport is set to *X11*. No further options are currently supported. Warning PyGTK framework users ============================= The multithreaded architecture of Skype4Py requires a special treatment if the Xlib transport is combined with PyGTK GUI framework. The following code has to be called at the top of your script, before PyGTK is even imported. .. python:: from Skype4Py.api.posix_x11 import threads_init threads_init() This function enables multithreading support in Xlib and GDK. If not done here, this is enabled for Xlib library when the `Skype` object is instantiated. If your script imports the PyGTK module, doing this so late may lead to a segmentation fault when the GUI is shown on the screen. A remedy is to enable the multithreading support before PyGTK is imported by calling the ``threads_init`` function. """ __docformat__ = 'restructuredtext en' import sys import threading import os from ctypes import * from ctypes.util import find_library import time import logging from Skype4Py.api import Command, SkypeAPIBase, \ timeout2float, finalize_opts from Skype4Py.enums import * from Skype4Py.errors import SkypeAPIError __all__ = ['SkypeAPI', 'threads_init'] # The Xlib Programming Manual: # ============================ # http://tronche.com/gui/x/xlib/ # some Xlib constants PropertyChangeMask = 0x400000 PropertyNotify = 28 ClientMessage = 33 PropertyNewValue = 0 PropertyDelete = 1 # some Xlib types c_ulong_p = POINTER(c_ulong) DisplayP = c_void_p Atom = c_ulong AtomP = c_ulong_p XID = c_ulong Window = XID Bool = c_int Status = c_int Time = c_ulong c_int_p = POINTER(c_int) # should the structures be aligned to 8 bytes? align = (sizeof(c_long) == 8 and sizeof(c_int) == 4) # some Xlib structures class XClientMessageEvent(Structure): if align: _fields_ = [('type', c_int), ('pad0', c_int), ('serial', c_ulong), ('send_event', Bool), ('pad1', c_int), ('display', DisplayP), ('window', Window), ('message_type', Atom), ('format', c_int), ('pad2', c_int), ('data', c_char * 20)] else: _fields_ = [('type', c_int), ('serial', c_ulong), ('send_event', Bool), ('display', DisplayP), ('window', Window), ('message_type', Atom), ('format', c_int), ('data', c_char * 20)] class XPropertyEvent(Structure): if align: _fields_ = [('type', c_int), ('pad0', c_int), ('serial', c_ulong), ('send_event', Bool), ('pad1', c_int), ('display', DisplayP), ('window', Window), ('atom', Atom), ('time', Time), ('state', c_int), ('pad2', c_int)] else: _fields_ = [('type', c_int), ('serial', c_ulong), ('send_event', Bool), ('display', DisplayP), ('window', Window), ('atom', Atom), ('time', Time), ('state', c_int)] class XErrorEvent(Structure): if align: _fields_ = [('type', c_int), ('pad0', c_int), ('display', DisplayP), ('resourceid', XID), ('serial', c_ulong), ('error_code', c_ubyte), ('request_code', c_ubyte), ('minor_code', c_ubyte)] else: _fields_ = [('type', c_int), ('display', DisplayP), ('resourceid', XID), ('serial', c_ulong), ('error_code', c_ubyte), ('request_code', c_ubyte), ('minor_code', c_ubyte)] class XEvent(Union): if align: _fields_ = [('type', c_int), ('xclient', XClientMessageEvent), ('xproperty', XPropertyEvent), ('xerror', XErrorEvent), ('pad', c_long * 24)] else: _fields_ = [('type', c_int), ('xclient', XClientMessageEvent), ('xproperty', XPropertyEvent), ('xerror', XErrorEvent), ('pad', c_long * 24)] XEventP = POINTER(XEvent) if getattr(sys, 'skype4py_setup', False): # we get here if we're building docs; to let the module import without # exceptions, we emulate the X11 library using a class: class X(object): def __getattr__(self, name): return self def __setattr__(self, name, value): pass def __call__(self, *args, **kwargs): pass x11 = X() else: # load X11 library (Xlib) libpath = find_library('X11') if not libpath: raise ImportError('Could not find X11 library') x11 = cdll.LoadLibrary(libpath) del libpath # setup Xlib function prototypes x11.XCloseDisplay.argtypes = (DisplayP,) x11.XCloseDisplay.restype = None x11.XCreateSimpleWindow.argtypes = (DisplayP, Window, c_int, c_int, c_uint, c_uint, c_uint, c_ulong, c_ulong) x11.XCreateSimpleWindow.restype = Window x11.XDefaultRootWindow.argtypes = (DisplayP,) x11.XDefaultRootWindow.restype = Window x11.XDeleteProperty.argtypes = (DisplayP, Window, Atom) x11.XDeleteProperty.restype = None x11.XDestroyWindow.argtypes = (DisplayP, Window) x11.XDestroyWindow.restype = None x11.XFree.argtypes = (c_void_p,) x11.XFree.restype = None x11.XGetAtomName.argtypes = (DisplayP, Atom) x11.XGetAtomName.restype = c_void_p x11.XGetErrorText.argtypes = (DisplayP, c_int, c_char_p, c_int) x11.XGetErrorText.restype = None x11.XGetWindowProperty.argtypes = (DisplayP, Window, Atom, c_long, c_long, Bool, Atom, AtomP, c_int_p, c_ulong_p, c_ulong_p, POINTER(POINTER(Window))) x11.XGetWindowProperty.restype = c_int x11.XInitThreads.argtypes = () x11.XInitThreads.restype = Status x11.XInternAtom.argtypes = (DisplayP, c_char_p, Bool) x11.XInternAtom.restype = Atom x11.XNextEvent.argtypes = (DisplayP, XEventP) x11.XNextEvent.restype = None x11.XOpenDisplay.argtypes = (c_char_p,) x11.XOpenDisplay.restype = DisplayP x11.XPending.argtypes = (DisplayP,) x11.XPending.restype = c_int x11.XSelectInput.argtypes = (DisplayP, Window, c_long) x11.XSelectInput.restype = None x11.XSendEvent.argtypes = (DisplayP, Window, Bool, c_long, XEventP) x11.XSendEvent.restype = Status x11.XLockDisplay.argtypes = (DisplayP,) x11.XLockDisplay.restype = None x11.XUnlockDisplay.argtypes = (DisplayP,) x11.XUnlockDisplay.restype = None def threads_init(gtk=True): """Enables multithreading support in Xlib and PyGTK. See the module docstring for more info. :Parameters: gtk : bool May be set to False to skip the PyGTK module. """ # enable X11 multithreading x11.XInitThreads() if gtk: from gtk.gdk import threads_init threads_init() class SkypeAPI(SkypeAPIBase): def __init__(self, opts): self.logger = logging.getLogger('Skype4Py.api.posix_x11.SkypeAPI') SkypeAPIBase.__init__(self) finalize_opts(opts) # initialize threads if not done already by the user threads_init(gtk=False) # init Xlib display self.disp = x11.XOpenDisplay(None) if not self.disp: raise SkypeAPIError('Could not open XDisplay') self.win_root = x11.XDefaultRootWindow(self.disp) self.win_self = x11.XCreateSimpleWindow(self.disp, self.win_root, 100, 100, 100, 100, 1, 0, 0) x11.XSelectInput(self.disp, self.win_root, PropertyChangeMask) self.win_skype = self.get_skype() ctrl = 'SKYPECONTROLAPI_MESSAGE' self.atom_msg = x11.XInternAtom(self.disp, ctrl, False) self.atom_msg_begin = x11.XInternAtom(self.disp, ctrl + '_BEGIN', False) self.loop_event = threading.Event() self.loop_timeout = 0.0001 self.loop_break = False def __del__(self): if x11: if hasattr(self, 'disp'): if hasattr(self, 'win_self'): x11.XDestroyWindow(self.disp, self.win_self) x11.XCloseDisplay(self.disp) def run(self): self.logger.info('thread started') # main loop event = XEvent() data = '' while not self.loop_break and x11: while x11.XPending(self.disp): self.loop_timeout = 0.0001 x11.XNextEvent(self.disp, byref(event)) # events we get here are already prefiltered by the predicate function if event.type == ClientMessage: if event.xclient.format == 8: if event.xclient.message_type == self.atom_msg_begin: data = str(event.xclient.data) elif event.xclient.message_type == self.atom_msg: if data != '': data += str(event.xclient.data) else: self.logger.warning('Middle of Skype X11 message received with no beginning!') else: continue if len(event.xclient.data) != 20 and data: self.notify(data.decode('utf-8')) data = '' elif event.type == PropertyNotify: namep = x11.XGetAtomName(self.disp, event.xproperty.atom) is_inst = (c_char_p(namep).value == '_SKYPE_INSTANCE') x11.XFree(namep) if is_inst: if event.xproperty.state == PropertyNewValue: self.win_skype = self.get_skype() # changing attachment status can cause an event handler to be fired, in # turn it could try to call Attach() and doing this immediately seems to # confuse Skype (command '#0 NAME xxx' returns '#0 CONNSTATUS OFFLINE' :D); # to fix this, we give Skype some time to initialize itself time.sleep(1.0) self.set_attachment_status(apiAttachAvailable) elif event.xproperty.state == PropertyDelete: self.win_skype = None self.set_attachment_status(apiAttachNotAvailable) self.loop_event.wait(self.loop_timeout) if self.loop_event.isSet(): self.loop_timeout = 0.0001 elif self.loop_timeout < 1.0: self.loop_timeout *= 2 self.loop_event.clear() self.logger.info('thread finished') def get_skype(self): """Returns Skype window ID or None if Skype not running.""" skype_inst = x11.XInternAtom(self.disp, '_SKYPE_INSTANCE', True) if not skype_inst: return type_ret = Atom() format_ret = c_int() nitems_ret = c_ulong() bytes_after_ret = c_ulong() winp = pointer(Window()) fail = x11.XGetWindowProperty(self.disp, self.win_root, skype_inst, 0, 1, False, 33, byref(type_ret), byref(format_ret), byref(nitems_ret), byref(bytes_after_ret), byref(winp)) if not fail and format_ret.value == 32 and nitems_ret.value == 1: return winp.contents.value def close(self): self.loop_break = True self.loop_event.set() while self.isAlive(): time.sleep(0.01) SkypeAPIBase.close(self) def set_friendly_name(self, friendly_name): SkypeAPIBase.set_friendly_name(self, friendly_name) if self.attachment_status == apiAttachSuccess: # reattach with the new name self.set_attachment_status(apiAttachUnknown) self.attach() def attach(self, timeout, wait=True): if self.attachment_status == apiAttachSuccess: return self.acquire() try: if not self.isAlive(): try: self.start() except AssertionError: raise SkypeAPIError('Skype API closed') try: self.wait = True t = threading.Timer(timeout2float(timeout), lambda: setattr(self, 'wait', False)) if wait: t.start() while self.wait: self.win_skype = self.get_skype() if self.win_skype is not None: break else: time.sleep(1.0) else: raise SkypeAPIError('Skype attach timeout') finally: t.cancel() command = Command('NAME %s' % self.friendly_name, '', True, timeout) self.release() try: self.send_command(command, True) finally: self.acquire() if command.Reply != 'OK': self.win_skype = None self.set_attachment_status(apiAttachRefused) return self.set_attachment_status(apiAttachSuccess) finally: self.release() command = Command('PROTOCOL %s' % self.protocol, Blocking=True) self.send_command(command, True) self.protocol = int(command.Reply.rsplit(None, 1)[-1]) def is_running(self): return (self.get_skype() is not None) def startup(self, minimized, nosplash): # options are not supported as of Skype 1.4 Beta for Linux if not self.is_running(): if os.fork() == 0: # we're the child os.setsid() os.execlp('skype', 'skype') def shutdown(self): from signal import SIGINT fh = os.popen('ps -o %p --no-heading -C skype') pid = fh.readline().strip() fh.close() if pid: os.kill(int(pid), SIGINT) # Skype sometimes doesn't delete the '_SKYPE_INSTANCE' property skype_inst = x11.XInternAtom(self.disp, '_SKYPE_INSTANCE', True) if skype_inst: x11.XDeleteProperty(self.disp, self.win_root, skype_inst) self.win_skype = None self.set_attachment_status(apiAttachNotAvailable) def send_command(self, command, force=False): if self.attachment_status != apiAttachSuccess and not force: self.attach(command.Timeout) self.push_command(command) self.notifier.sending_command(command) cmd = u'#%d %s' % (command.Id, command.Command) self.logger.debug('sending %s', repr(cmd)) if command.Blocking: command._event = bevent = threading.Event() else: command._timer = timer = threading.Timer(command.timeout2float(), self.pop_command, (command.Id,)) event = XEvent() event.xclient.type = ClientMessage event.xclient.display = self.disp event.xclient.window = self.win_self event.xclient.message_type = self.atom_msg_begin event.xclient.format = 8 cmd = cmd.encode('utf-8') + '\x00' for i in xrange(0, len(cmd), 20): event.xclient.data = cmd[i:i + 20] x11.XSendEvent(self.disp, self.win_skype, False, 0, byref(event)) event.xclient.message_type = self.atom_msg self.loop_event.set() if command.Blocking: bevent.wait(command.timeout2float()) if not bevent.isSet(): raise SkypeAPIError('Skype command timeout') else: timer.start() def notify(self, cmd): self.logger.debug('received %s', repr(cmd)) # Called by main loop for all received Skype commands. if cmd.startswith(u'#'): p = cmd.find(u' ') command = self.pop_command(int(cmd[1:p])) if command is not None: command.Reply = cmd[p + 1:] if command.Blocking: command._event.set() else: command._timer.cancel() self.notifier.reply_received(command) else: self.notifier.notification_received(cmd[p + 1:]) else: self.notifier.notification_received(cmd)
python
#! /usr/bin/env python3 # encoding: UTF-8 # # Python Workshop - Conditionals etc #2 # # We'll later cover learn what happens here import random # # Guess a number # Find a random number between 0 and 100 inclusive target = random.randint(0, 100) # TODO: # Write a while loop that repeatedly asks the user to guess the `target`. # If the number is not the same as the target, write whether it is smaller # or larger, and try again. Otherwise, stop the loop.
python
#! /usr/bin/env python import cyvcf2 import argparse import sys from collections import defaultdict, Counter import pandas as pd import signal import numpy as np from shutil import copyfile import pyfaidx from random import choice from pyliftover import LiftOver from Bio.Seq import reverse_complement from mutyper import ancestor def setup_ancestor(args): """utility for initializing an Ancestor object for use in different ' 'subroutines""" return ancestor.Ancestor(args.fasta, k=args.k, target=args.target, strand_file=args.strand_file, key_function=lambda x: x.split(args.sep)[args.chrom_pos], read_ahead=10000, sequence_always_upper=(not args.strict)) def ancestral_fasta(args): """subroutine for ancestor subcommand """ # single chromosome fasta file for reference genome ref = pyfaidx.Fasta(args.reference, read_ahead=10000) # make a copy to build our ancestor for this chromosome copyfile(args.reference, args.output) anc = pyfaidx.Fasta(args.output, read_ahead=10000, mutable=True) # reference genome for outgroup species (all chromosomes) out = pyfaidx.Fasta(args.outgroup, read_ahead=10000) # outgroup to reference alignment chain file lo = LiftOver(args.chain) # snps database for the same chromosome vcf = cyvcf2.VCF(args.vcf) # change regions outside of callability mask to all N bases if args.bed: if args.bed == '-': bed = sys.stdin else: bed = open(args.bed, 'r') last_end = 0 for line in bed: chrom, start, end = line.rstrip().split('\t')[:3] start = int(start) anc[chrom][last_end:start] = 'N' * (start - last_end) last_end = int(end) anc[chrom][last_end: len(anc[chrom])] = 'N' * (len(anc[chrom]) - last_end) for variant in vcf: # change variants that are not biallelic SNPs to N bases if not (variant.is_snp and len(variant.ALT) == 1): anc[chrom][variant.start: variant.end] = 'N' * (variant.end - variant.start) else: out_coords = lo.convert_coordinate(variant.CHROM, variant.start) # change ambiguously aligning sites to N bases if out_coords is None or len(out_coords) != 1: anc[chrom][variant.start] = 'N' else: if variant.REF != ref[chrom][variant.start].seq.upper(): raise ValueError(f'variant reference allele {variant.REF} ' f'mismatches reference sequence ' f'{ref[chrom][variant.start]}') out_chromosome, out_position, out_strand = out_coords[0][:3] out_allele = out[out_chromosome][out_position].seq # if negative strand, take reverse complement base if out_strand == '-': out_allele = reverse_complement(out_allele) # and finally, polarize if out_allele.upper() == variant.ALT[0]: anc[chrom][variant.start] = out_allele elif out_allele.upper() != variant.REF: # triallelic anc[chrom][variant.start] = 'N' def variants(args): """subroutine for variants subcommand """ ancestor = setup_ancestor(args) vcf = cyvcf2.VCF(args.vcf) vcf.add_info_to_header({'ID': 'mutation_type', 'Description': f'ancestral {args.k}-mer mutation ' 'type', 'Type': 'Character', 'Number': '1'}) vcf_writer = cyvcf2.Writer('-', vcf) vcf_writer.write_header() for variant in vcf: # biallelic snps only if not (variant.is_snp and len(variant.ALT) == 1): continue # mutation type as ancestral kmer and derived kmer anc_kmer, der_kmer = ancestor.mutation_type(variant.CHROM, variant.start, variant.REF, variant.ALT[0]) if anc_kmer is None or der_kmer is None: continue mutation_type = f'{anc_kmer}>{der_kmer}' variant.INFO['mutation_type'] = mutation_type # ancestral allele AA = ancestor[variant.CHROM][variant.start].seq # polarize genotypes (and associated INFO) if alternative allele is # ancestral if variant.ALT[0] == AA: variant.INFO['AC'] = variant.INFO['AN'] - variant.INFO['AC'] variant.INFO['AF'] = variant.INFO['AC'] / variant.INFO['AN'] # cyvcf2 docs say we need to reassign genotypes like this for the # change to propagate (can't just update indexwise) if variant.ploidy == 2: # diploid variant.genotypes = [[int(not gt[0]), int(not gt[1]), gt[2]] for gt in variant.genotypes] elif variant.ploidy == 1: # haploid variant.genotypes = [[int(not gt[0]), gt[1]] for gt in variant.genotypes] else: raise ValueError(f"invalid ploidy {variant.ploidy}") elif not variant.REF == AA: raise ValueError(f'ancestral allele {AA} is not equal to ' f'reference {variant.REF} or alternative ' f'{variant.ALT[0]}') # set REF to ancestral allele and ALT to derived allele variant.REF = anc_kmer[ancestor.target] variant.ALT = der_kmer[ancestor.target] vcf_writer.write_record(variant) # this line required to exit on a SIGTERM in a pipe, e.g. from head signal.signal(signal.SIGPIPE, signal.SIG_DFL) def targets(args): """subroutine for targets subcommand """ ancestor = setup_ancestor(args) if args.bed == '-': args.bed = sys.stdin sizes = ancestor.targets(args.bed) try: for kmer in sorted(sizes): print(f'{kmer}\t{sizes[kmer]}') except BrokenPipeError: pass def spectra(args): """subroutine for spectra subcommand """ vcf = cyvcf2.VCF(args.vcf, gts012=True) if args.population: spectra_data = Counter() for variant in vcf: spectra_data[variant.INFO['mutation_type']] += 1 spectra = pd.DataFrame(spectra_data, ['population']).reindex(sorted(spectra_data), axis='columns') try: print(spectra.to_csv(sep='\t', index=False)) except BrokenPipeError: pass else: spectra_data = defaultdict(lambda: np.zeros_like(vcf.samples, dtype=int)) if args.randomize: for variant in vcf: random_haplotype = choice([x for x, y in enumerate(variant.gt_types) for _ in range(y)]) spectra_data[variant.INFO['mutation_type']][random_haplotype] += 1. else: for variant in vcf: if variant.ploidy == 1: # haploid ALT are coded as 2 (homozygous ALT) variant.gt_types[variant.gt_types == 2] = 1 spectra_data[variant.INFO['mutation_type']] += variant.gt_types spectra = pd.DataFrame(spectra_data, vcf.samples).reindex(sorted(spectra_data), axis='columns') try: print(spectra.to_csv(sep='\t', index=True, index_label='sample')) except BrokenPipeError: pass def ksfs(args): """subroutine for ksfs subcommand """ vcf = cyvcf2.VCF(args.vcf) ksfs_data = defaultdict(lambda: Counter()) AN = None for variant in vcf: # AN must be the same for all sites (no missing genotypes) if AN is not None and variant.INFO['AN'] != AN: raise ValueError(f'different AN {variant.INFO["AN"]} and {AN}' ' indicates missing genotypes') AN = variant.INFO['AN'] ksfs_data[variant.INFO['mutation_type']][variant.INFO['AC']] += 1 # exclude fixed sites AC=0, AC=AN index = range(1, AN) for mutation_type in sorted(ksfs_data): ksfs_data[mutation_type] = [ksfs_data[mutation_type][ac] for ac in index] ksfs = pd.DataFrame(ksfs_data, index).reindex(sorted(ksfs_data), axis='columns') try: print(ksfs.to_csv(sep='\t', index=True, index_label='sample_frequency')) except BrokenPipeError: pass def get_parser(): parser = argparse.ArgumentParser( description='mutyper: ancestral kmer mutation types for variant data') subparsers = parser.add_subparsers( title='subcommands', description='specify one of these', required=True, help='additional help available for each subcommand') parser_ancestor = subparsers.add_parser( 'ancestor', description='create an ancestral FASTA file, using an ' 'outgroup alignment, and a database of SNPs ' 'with a callability mask') parser_variants = subparsers.add_parser( 'variants', description='adds mutation_type to VCF/BCF INFO, polarizes' ' REF/ALT/AC according to ancestral/derived ' 'states, and stream to stdout') parser_targets = subparsers.add_parser( 'targets', description='compute 𝑘-mer target sizes and stream to ' 'stdout') parser_spectra = subparsers.add_parser( 'spectra', description='compute mutation spectra for each sample in ' 'VCF/BCF with mutation_type data and stream to' ' stdout') parser_ksfs = subparsers.add_parser( 'ksfs', description='compute sample frequency spectrum for each ' 'mutation type from a VCF/BCF file with ' 'mutation_type data (i.e. output from variants ' 'subcommand ) and stream to stdout') # arguments that require FASTA input for sub_parser in (parser_variants, parser_targets): sub_parser.add_argument('fasta', type=str, help='path to ancestral FASTA') sub_parser.add_argument('--k', type=int, default=3, help='k-mer context size (default 3)') sub_parser.add_argument('--target', type=int, default=None, help='0-based mutation target position in kmer' ' (default middle)') sub_parser.add_argument('--sep', type=str, default=':', help='field delimiter in FASTA headers ' '(default ":")') sub_parser.add_argument('--chrom_pos', type=int, default=0, help='0-based chromosome field position in ' 'FASTA headers (default 0)') sub_parser.add_argument('--strand_file', type=str, default=None, help='path to bed file with regions where ' 'reverse strand defines mutation ' 'context, e.g. direction of replication ' 'or transcription (default collapse ' 'reverse complements)') sub_parser.add_argument('--strict', action='store_true', help='only uppercase nucleotides in FASTA ' 'considered ancestrally identified') # subcommands that require VCF input for sub_parser in (parser_ancestor, parser_variants, parser_spectra, parser_ksfs): sub_parser.add_argument('vcf', type=str, help='VCF/BCF file, usually for a single ' 'chromosome ("-" for stdin)') # subcommands that take BED input for sub_parser in (parser_ancestor, parser_targets): sub_parser.add_argument('--bed', type=str, default=None, help='path to BED file mask ("-" for stdin)') # arguments specific to ancestor subcommand parser_ancestor.add_argument('reference', type=str, help='path to reference FASTA for one ' 'chromosome') parser_ancestor.add_argument('outgroup', type=str, help='path to outgroup genome FASTA') parser_ancestor.add_argument('chain', type=str, help='path to alignment chain file ' '(reference to outgroup)') parser_ancestor.add_argument('output', type=str, help='path for output ancestral FASTA for ' 'this chromosome') parser_ancestor.set_defaults(func=ancestral_fasta) # arguments specific to variants subcommand parser_variants.set_defaults(func=variants) # arguments specific to targets subcommand parser_targets.set_defaults(func=targets) # arguments specific to spectra subcommand parser_spectra.add_argument('--population', action='store_true', help='population-wise spectrum, instead of ' 'individual') parser_spectra.add_argument('--randomize', action='store_true', help='randomly assign mutation to a single ' 'haplotype') parser_spectra.set_defaults(func=spectra) # arguments specific to ksfs subcommand parser_ksfs.set_defaults(func=ksfs) return parser def main(arg_list=None): args = get_parser().parse_args(arg_list) args.func(args)
python
############################################################################### # $Id$ # $Author$ # # Routines to create the inquisitor plots. # ############################################################################### # system import import threading import string import os # enstore imports import Trace import e_errors import enstore_files import enstore_plots import enstore_functions import enstore_functions2 import enstore_constants import accounting_query import configuration_client LOGFILE_DIR = "logfile_dir" XFER_SIZE = "xfer-size" class InquisitorPlots: def open_db_connection(self): if not self.acc_db: # open a connection to the accounting db, the data is there acc = self.config_d.get(enstore_constants.ACCOUNTING_SERVER, {}) if acc: self.acc_db = accounting_query.accountingQuery(host = acc.get('dbhost', "localhost"), port = acc.get('dbport', 5432), dbname= acc.get('dbname', ""), user = acc.get('dbuser', "enstore")) def close_db_connection(self): if self.acc_db: self.acc_db.close() self.acc_db = None # create the htl file with the inquisitor plot information def make_plot_html_page(self): for plotfile_t in self.plotfile_l: if len(plotfile_t) > 2: plotfile = plotfile_t[0] html_dir = plotfile_t[1] links_l = plotfile_t[2:] else: (plotfile, html_dir) = plotfile_t links_l = None nav_link = "" plotfile.open() # get the list of stamps and jpg files (jpgs, stamps, pss) = enstore_plots.find_jpg_files(html_dir) plotfile.write(jpgs, stamps, pss, self.mount_label, links_l) plotfile.close() plotfile.install() # figure out how much information to get out of the db # if start_time specified : do start_time -> latest # if stop_time specified : do 30 days ago -> stop_time # if start_time and stop_time are specified : # do start_time -> stop_time def make_time_query(self, column): time_q = "%s to_char(%s, 'YYYY-MM-DD') %s"%(accounting_query.WHERE, column, accounting_query.GREATER) if not self.start_time: # only use the last 30 days self.start_time = self.acc_db.days_ago(30) time_q = "%s '%s'"%(time_q, self.start_time) if self.stop_time: time_q = "%s %s %s %s '%s'"%(time_q, accounting_query.AND, column, accounting_query.LESS, self.stop_time) return time_q # make the mount plots (mounts per hour and mount latency) def mount_plot(self, prefix): self.open_db_connection() # get the config file so we can not plot null mover data config = enstore_functions.get_config_dict() if config: config = config.configdict else: config = {} # get the mount information out of the accounting db. it is in # the tape_mounts table db_table = "tape_mounts" start_col = "start" finish_col = "finish" type_col = "type" table = "tape_mounts" time_q = self.make_time_query(start_col) # only need mount requests time_q = "%s %s state%s'M'"%(time_q, accounting_query.AND, accounting_query.EQUALS) # get the total mounts/day. the results are in a list # where each element looks like - # {'start': '2003-03-27', 'total': '345'} query = "select to_char(start , 'YYYY-MM-DD') as %s, count(*) as total from %s %s group by to_char(start, 'YYYY-MM-DD') order by to_char(start, 'YYYY-MM-DD')"%(start_col, table, time_q) total_mounts = self.acc_db.query(query) # get the mounts for each drive type. first get a list of the drive # types query = "select distinct %s from %s"%(type_col, table) drive_types = self.acc_db.query(query) total_mounts_type = {} # for each drive type get a list of the mounts/day # the results are in a dict which holds a list where each element # looks like - # {'start': '2003-03-27 00:05:55', 'latency': '00:00:25'} for type_d in drive_types.dictresult(): aType = type_d[type_col] query = "select to_char(start , 'YYYY-MM-DD') as %s, count(*) as total from %s %s %s %s='%s' group by to_char(start, 'YYYY-MM-DD') order by to_char(start, 'YYYY-MM-DD')"%(start_col, table, time_q, accounting_query.AND, type_col, aType) total_mounts_type[aType] = self.acc_db.query(query).dictresult() # only do the plotting if we have some data if total_mounts: # now save any new mount count data for the continuing total # count. and create the overall total mount plot mpdfile = enstore_plots.MpdDataFile(self.output_dir, self.mount_label) mpdfile.open() total_mounts_l = total_mounts.dictresult() mpdfile.plot(total_mounts_l) mpdfile.close() mpdfile.install(self.html_dir) mmpdfile = enstore_plots.MpdMonthDataFile(self.output_dir, self.mount_label) mmpdfile.open() mmpdfile.plot(total_mounts_l, total_mounts_type) mmpdfile.close() mmpdfile.install(self.html_dir) mmpdfile.cleanup(self.keep, self.keep_dir) # close db connection self.close_db_connection() # make the total transfers per unit of time and the bytes moved per day # plot def encp_plot(self, prefix): ofn = self.output_dir+"/bytes_moved.txt" # open connection to db. self.open_db_connection() # Dmitry: # Kludge: this seems like the only way I can get storage groups efficiently # res=self.acc_db.query("select distinct(storage_group) from encp_xfer_average_by_storage_group") storage_groups = [] for row in res.getresult(): if not row: continue storage_groups.append(row[0]) # always add /dev/null to the end of the list of files to search thru # so that grep always has > 1 file and will always print the name of # the file at the beginning of the line. do not count any null moves. encpfile = enstore_files.EnEncpDataFile("%s* /dev/null"%(prefix,), ofn, "-e %s"%(Trace.MSG_ENCP_XFER,), self.logfile_dir, "| grep -v %s"%(enstore_constants.NULL_DRIVER,)) # only extract the information from the newly created file that is # within the requested timeframe. encpfile.open('r') os.system("cp %s %s_1"%(encpfile.file_name,encpfile.file_name,)) encpfile.read_and_parse(self.start_time, self.stop_time, prefix, self.media_changer) encpfile.close() encpfile.cleanup(self.keep, self.keep_dir) # # This is a test, this is a test. I am testing retrieval of data from DB. I replaces encpfile.data -> self.data # self.data=[] self.start_time = self.acc_db.days_ago(30) encp_q = "select to_char(date,'YYYY-MM-DD:hh24:mi:ss'), size, rw, mover, drive_id, storage_group from encp_xfer where date > '%s' and driver != '%s'"%(self.start_time,enstore_constants.NULL_DRIVER,) res=self.acc_db.query(encp_q) for row in res.getresult(): if not row: continue self.data.append([row[0],row[1],row[2],row[3],row[4],row[5]]) # only do the plotting if we have some data if self.data: # overall bytes/per/day count bpdfile = enstore_plots.BpdDataFile(self.output_dir) bpdfile.open() bpdfile.plot(self.data) bpdfile.close() bpdfile.install(self.html_dir) mbpdfile = enstore_plots.BpdMonthDataFile(self.output_dir) mbpdfile.open() mbpdfile.plot(bpdfile.write_ctr) mbpdfile.close() mbpdfile.install(self.html_dir) xferfile = enstore_plots.XferDataFile(self.output_dir, mbpdfile.ptsfile) xferfile.open() xferfile.plot(self.data) xferfile.close() xferfile.install(self.html_dir) xferfile.cleanup(self.keep, self.keep_dir) # # check if there are other storage groups # if (len(storage_groups)>1) : for sg in storage_groups: xferfile = enstore_plots.XferDataFile(self.output_dir, mbpdfile.ptsfile,sg) xferfile.open() xferfile.plot(self.data) xferfile.close() xferfile.install(self.html_dir+"/"+XFER_SIZE) # Kludge (Dmitry) xferfile.cleanup(self.keep, self.keep_dir) # delete any extraneous files. do it here because the xfer file # plotting needs the bpd data file bpdfile.cleanup(self.keep, self.keep_dir) mbpdfile.cleanup(self.keep, self.keep_dir) self.close_db_connection() # make the plot showing queue movement for different storage groups plot def sg_plot(self, prefix): ofn = self.output_dir+"/sg_lmq.txt" # open connection to db. self.open_db_connection() # always add /dev/null to the end of the list of files to search thru # so that grep always has > 1 file and will always print the name of # the file at the beginning of the line. sgfile = enstore_files.EnSgDataFile("%s* /dev/null"%(prefix,), ofn, "-e %s"%(Trace.MSG_ADD_TO_LMQ,), self.logfile_dir) # only extract the information from the newly created file that is # within the requested timeframe. sgfile.open('r') sgfile.timed_read(self.start_time, self.stop_time, prefix) # now pull out the info we are going to plot from the lines sgfile.parse_data(prefix) sgfile.close() sgfile.cleanup(self.keep, self.keep_dir) # only do the plotting if we have some data if sgfile.data: sgplot = enstore_plots.SgDataFile(self.output_dir) sgplot.open() sgplot.plot(sgfile.data) sgplot.close() sgplot.install(self.html_dir) # delete any extraneous files. do it here because the xfer file # plotting needs the bpd data file sgplot.cleanup(self.keep, self.keep_dir) # close db connection self.close_db_connection() def get_bpd_files(self): # # Dmitry is hacking below, getting info from config server # *I assume that config server and points are on the same node!!!!* # servers=self.config_d.get('known_config_servers',[]) nodes_and_dirs={} for server in servers: if (server == 'status') : continue server_name,server_port = servers.get(server) # # access config server to get locatin of web directory # csc = configuration_client.ConfigurationClient((server_name, server_port)) inq_d = csc.get(enstore_constants.INQUISITOR, {}) nodes_and_dirs[server_name.split('.')[0]]=inq_d.get("html_file","/fnal/ups/prd/www_pages/enstore") files_l = [] pts_file_only = "%s%s"%(enstore_constants.BPD_FILE, enstore_plots.PTS) this_node = enstore_functions2.strip_node(os.uname()[1]) for node in nodes_and_dirs.keys(): destination_directory = nodes_and_dirs.get(node) pts_file = "%s/%s"%(destination_directory, pts_file_only) if enstore_functions2.ping(node) == enstore_constants.IS_ALIVE: new_file = "/tmp/%s.%s"%(pts_file_only, node) if node == this_node: rtn = os.system("cp %s %s"%(pts_file, new_file)) else: rtn = enstore_functions2.get_remote_file(node, pts_file, new_file) if rtn == 0: files_l.append((new_file, node)) else: Trace.log(e_errors.WARNING, "could not copy %s from %s for total bytes plot"%(pts_file,node)) else: Trace.log(e_errors.WARNING, "could not ping, %s from %s for total bytes plot"%(pts_file,node)) return files_l def fill_in_bpd_d(self, bpdfile, data_d, node): if bpdfile.lines: for line in bpdfile.lines: fields = string.split(string.strip(line)) # this is the date if not data_d.has_key(fields[0]): data_d[fields[0]] = {} if len(fields) > 2: # we have data , need date, total, ctr, writes data_d[fields[0]][node] = {enstore_plots.TOTAL : float(fields[1]), enstore_plots.CTR : enstore_plots.get_ctr(fields), enstore_plots.WRITES : float(fields[3])} else: data_d[fields[0]][node] = {enstore_plots.TOTAL : 0.0, enstore_plots.CTR : 0L, enstore_plots.WRITES : 0.0} def read_bpd_data(self, files_l): data_d = {} for filename, node in files_l: bpdfile = enstore_files.EnstoreBpdFile(filename) bpdfile.open('r') # only extract the info that is within the requested time frame bpdfile.timed_read(self.start_time, self.stop_time) bpdfile.close() # now fill in the data dictionary with the data self.fill_in_bpd_d(bpdfile, data_d, node) return data_d def total_bytes_plot(self): # we need to copy the enplot_bpd.pts files from all the nodes that are not # our own. files_l = self.get_bpd_files() # for each file we have, open it and read the requested data data_d = self.read_bpd_data(files_l) # now write out the data and plot it if data_d: tbpdfile = enstore_plots.TotalBpdDataFile(self.output_dir) tbpdfile.open() tbpdfile.plot(data_d) tbpdfile.close() tbpdfile.install(self.html_dir) tbpdfile.cleanup(self.keep, self.keep_dir) # make all the plots def plot(self, encp, mount, sg, total_bytes): ld = {} self.acc_db = None # find out where the log files are located if self.logfile_dir is None: ld = self.config_d.get("log_server") self.logfile_dir = ld["log_file_path"] if self.output_dir is None: self.output_dir = self.logfile_dir # get the list of alternate log files. we may need to grep these instead of the # normal ones if not ld: ld = self.config_d.get("log_server") alt_logs = ld.get("msg_type_logs", {}) if encp: enstore_functions.inqTrace(enstore_constants.PLOTTING, "Creating inq transfer plots") alt_key = string.strip(Trace.MSG_ENCP_XFER) self.encp_plot(alt_logs.get(alt_key, enstore_constants.LOG_PREFIX)) if mount: enstore_functions.inqTrace(enstore_constants.PLOTTING, "Creating inq mount plots") alt_key = string.strip(Trace.MSG_MC_LOAD_REQ) self.mount_plot(alt_logs.get(alt_key, enstore_constants.LOG_PREFIX)) if sg: enstore_functions.inqTrace(enstore_constants.PLOTTING, "Creating inq storage group plots") alt_key = string.strip(Trace.MSG_ADD_TO_LMQ) self.sg_plot(alt_logs.get(alt_key, enstore_constants.LOG_PREFIX)) if total_bytes: enstore_functions.inqTrace(enstore_constants.PLOTTING, "Creating inq total bytes summary plot") self.total_bytes_plot() # update the inquisitor plots web page if not self.no_plot_html: Trace.trace(11, "Creating the inq plot web page") self.make_plot_html_page()
python
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) import pytest from .. import Backend from . import AVAILABLE_BACKENDS @pytest.mark.parametrize('key', AVAILABLE_BACKENDS) def test_Dummy(key): be = Backend(key) d0 = be.Dummy() d1 = be.Dummy() assert d0 == d0 assert d0 != d1
python
# Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang # Mingshuang Luo) # # See ../../../../LICENSE for clarification regarding multiple authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This file displays duration statistics of utterances in a manifest. You can use the displayed value to choose minimum/maximum duration to remove short and long utterances during the training. See the function `remove_short_and_long_utt()` in ../../../librispeech/ASR/transducer/train.py for usage. """ from lhotse import load_manifest_lazy def main(): paths = [ "./data/fbank/alimeeting_cuts_train.jsonl.gz", "./data/fbank/alimeeting_cuts_eval.jsonl.gz", "./data/fbank/alimeeting_cuts_test.jsonl.gz", ] for path in paths: print(f"Starting display the statistics for {path}") cuts = load_manifest_lazy(path) cuts.describe() if __name__ == "__main__": main() """ Starting display the statistics for ./data/fbank/alimeeting_cuts_train.jsonl.gz Cuts count: 559092 Total duration (hours): 424.6 Speech duration (hours): 424.6 (100.0%) *** Duration statistics (seconds): mean 2.7 std 3.0 min 0.0 25% 0.7 50% 1.7 75% 3.6 99% 13.6 99.5% 14.7 99.9% 16.2 max 284.3 Starting display the statistics for ./data/fbank/alimeeting_cuts_eval.jsonl.gz Cuts count: 6457 Total duration (hours): 4.9 Speech duration (hours): 4.9 (100.0%) *** Duration statistics (seconds): mean 2.7 std 3.1 min 0.1 25% 0.6 50% 1.6 75% 3.5 99% 13.6 99.5% 14.1 99.9% 14.7 max 15.8 Starting display the statistics for ./data/fbank/alimeeting_cuts_test.jsonl.gz Cuts count: 16358 Total duration (hours): 12.5 Speech duration (hours): 12.5 (100.0%) *** Duration statistics (seconds): mean 2.7 std 2.9 min 0.1 25% 0.7 50% 1.7 75% 3.5 99% 13.7 99.5% 14.2 99.9% 14.8 max 15.7 """
python
import time import cv2 import numpy as np import tflite_runtime.interpreter as tflite def _inference(interpreter, input_details, input_data): '''Inference (internal function) TensorFlow Lite inference the inference result can be get to use interpreter.get_tensor Arguments: - interpreter: tflite.Interpreter - input_details: result of tflite.Interpreter.get_input_details() - input_data: input inference data Returns: - duration: inference time [ms] ''' start_time = time.time() interpreter.set_tensor(input_details[0]['index'], input_data) interpreter.invoke() stop_time = time.time() duration = (stop_time - start_time) * 1000 return duration def object_detection(model_file, class_label, image, max_detection=-1, thresh=0.3): '''Object Detection Arguments: - model_file: file path of tflite - class_label: list of class name - image: image data(ndarray, HxWxC) - max_detection: max boxes to draw on image (if -1 set then draw all boxes, but thresh is more priority) - thresh: minimum score threshold to draw boxes Returns: - ret_image: return image - duration: inference time [ms] ''' # load model file interpreter = tflite.Interpreter(model_path=model_file) input_details = interpreter.get_input_details() # print(input_details) # image preprocessing org_img_shape = image.shape input_type = input_details[0]['name'] if (input_type == 'normalized_input_image_tensor'): input_image = (((image / 255.) - 0.5) * 2).astype(np.float32) input_image = np.expand_dims(input_image, axis=0) interpreter.resize_tensor_input(input_details[0]['index'], (1, image.shape[0], image.shape[1], 3)) elif (input_type == 'serving_default_images:0'): input_img_shape = (input_details[0]['shape'][1], input_details[0]['shape'][2]) input_image = cv2.resize(image, input_img_shape) input_image = np.expand_dims(input_image, axis=0) interpreter.allocate_tensors() # inference duration = _inference(interpreter, input_details, input_image) # draw bounding box output_details = interpreter.get_output_details() # StatefulPartitionedCall:0 count # StatefulPartitionedCall:1 scores # StatefulPartitionedCall:2 classes # StatefulPartitionedCall:3 boxes result = {} for output_detail in output_details: if (output_detail['name'] == 'StatefulPartitionedCall:0'): result['count'] = interpreter.get_tensor(output_detail['index']) elif (output_detail['name'] == 'StatefulPartitionedCall:1'): result['scores'] = interpreter.get_tensor(output_detail['index']) elif (output_detail['name'] == 'StatefulPartitionedCall:2'): result['classes'] = interpreter.get_tensor(output_detail['index']) elif (output_detail['name'] == 'StatefulPartitionedCall:3'): result['boxes'] = interpreter.get_tensor(output_detail['index']) elif (output_detail['name'] == 'raw_outputs/box_encodings'): result['boxes'] = interpreter.get_tensor(output_detail['index']) elif (output_detail['name'] == 'raw_outputs/class_predictions'): result_tmp = interpreter.get_tensor(output_detail['index']) result_exp = np.exp(result_tmp) result['scores'] = result_exp.max(axis=2) / result_exp.sum(axis=2) result['classes'] = result_tmp.argmax(axis=2) # print(result['scores'].shape) # print(result['classes'].shape) # print(result['boxes'].shape) ret_image = image for i, (score_, class_, box_) in enumerate(zip(result['scores'][0], result['classes'][0], result['boxes'][0])): if (score_ >= thresh): print(f'{i}, score={score_}, class={class_}, box={box_}') ymin, xmin, ymax, xmax = box_ ymin = int(ymin * org_img_shape[0]) xmin = int(xmin * org_img_shape[1]) ymax = int(ymax * org_img_shape[0]) xmax = int(xmax * org_img_shape[1]) color = [255, 0, 0] cv2.rectangle(image, (xmin, ymin), (xmax, ymax), color, 2) y = ymin - 15 if ((ymin - 15) > 15) else ymin + 15 if class_label is None: label = f'class: {int(class_)}' else: label = f'{class_label[int(class_)]}' cv2.putText(image, label, (xmin, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2) # return return ret_image, duration
python
# Copyright 2020-present NAVER Corp. Under BSD 3-clause license import subprocess import sys import os.path as path from typing import List, Optional def run_python_command(local_path: str, args: List[str], python_binary: Optional[str] = None, notbash = True): """ run a python subprocess :param local_path: path where you expect the file to be :type local_path: str :param args: the arguments of the python process :type args: List[str] :param python_binary: path to the python binary, optional, when None, the .py file is called directly :type python_binary: Optional[str] :raises ValueError: subprocess crashed """ if python_binary is None and notbash: if path.isfile(local_path): compute_image_pairs_bin = path.normpath(local_path) else: # maybe the script was installed through pip compute_image_pairs_bin = path.basename(local_path) args.insert(0, compute_image_pairs_bin) use_shell = sys.platform.startswith("win") sub_process = subprocess.Popen(args, shell=use_shell) sub_process.wait() if sub_process.returncode != 0: raise ValueError('\nSubprocess Error (Return code:' f' {sub_process.returncode} )')
python
import numpy from numpy.testing import * from prettyplotting import * from algopy.utpm import * # STEP 0: setting parameters and general problem definition ############################################################ # Np = number of parameters p # Nq = number of control variables q # Nm = number of measurements # P = number of vectorized operations at once (SPMD) D,Nq,Np,Nm = 2,1,11,30 P = Np q = UTPM(numpy.zeros((D,P,Nq))) q0 = 1. q.data[0,:,0] = q0 p = UTPM(numpy.zeros((D,P,Np))) p0 = numpy.random.rand(Np) p.data[0,:,:] = p0 p.data[1,:,:] = numpy.eye(P) B = UTPM(numpy.zeros((D,P,Nm, Np))) B0 = numpy.random.rand(Nm,Np) B.data[0,:] = B0 # STEP 1: compute push forward ############################################################ G = UTPM.dot(B, p) F = G * q[0] J = F.FtoJT().T Q,R = UTPM.qr(J) Id = numpy.eye(Np) Rinv = UTPM.solve(R,Id) C = UTPM.dot(Rinv,Rinv.T) l,U = UTPM.eigh(C) arg = UTPM.argmax(l) # check correctness of the push forward tmp1 = q0**-2* numpy.linalg.inv(numpy.dot(B0.T,B0)) l0, U0 = numpy.linalg.eigh( tmp1 ) assert_array_almost_equal( J.data[0,0], B0) assert_array_almost_equal( C.data[0,0], tmp1) assert_array_almost_equal(l.data[0,0], l0) assert_array_almost_equal(U.data[0,0], U0) # STEP 2: compute pullback ############################################################ lbar = UTPM(numpy.zeros(l.data.shape)) lbar.data[0,0, arg] = 1. Ubar = UTPM(numpy.zeros(U.data.shape)) Cbar = UTPM.pb_eigh(lbar, Ubar, C, l, U) Rinvbar, RinvTbar = UTPM.pb_dot(Cbar, Rinv, Rinv.T, C) Rinvbar += RinvTbar.T Rbar, Idbar = UTPM.pb_solve(Rinvbar, R, Id, Rinv) Qbar = UTPM(numpy.zeros(Q.data.shape)) Jbar = UTPM.pb_qr(Qbar, Rbar, J, Q, R) Fbar = Jbar.T.JTtoF() qbars = UTPM.dot(G.T,Fbar) # accumulate over the different directions qbar = UTPM(numpy.zeros((D,1))) qbar.data[:,0] = numpy.sum( qbars.data[:,:], axis=1) ############################################# # compare with analytical solution ############################################# c = numpy.max(numpy.linalg.eig( numpy.linalg.inv(numpy.dot(B0.T, B0)))[0]) dPhidq = - 2* c * q0**-3 assert_almost_equal( dPhidq, qbar.data[1,0]) print('symbolical - UTPM pullback = %e'%( numpy.abs(dPhidq - qbar.data[1,0])))
python
#!/usr/bin/python3 # -*- coding: utf-8 -*- """Day 2 of AdventOfCode.com: iterating over arrays doing simple arithmetic""" import os from numpy import product def present_wrap_area(dimensions): """ :param dimensions: list of 3 floats: length, width and height :return: area of wrapping """ wrap_area = 0 sides = list() for i in range(0, 3): for j in range(i+1, 3): sides.append(dimensions[i] * dimensions[j]) for i in range(0, len(sides)): wrap_area += 2 * sides[i] wrap_area += min(sides) return wrap_area def present_ribbon_length(dimensions): """ :param dimensions: list of 3 floats: length, width and height :return: length of ribbon """ ribbon_length = product(dimensions) sorted_dims = sorted(dimensions) ribbon_length += 2 * (sorted_dims[0]+sorted_dims[1]) return ribbon_length def presents(sets_of_dimensions): """Calculates total parameters for all presents :param sets_of_dimensions: list of lists of 3 floats: length, width and height :return: """ return sum([present_wrap_area(dimensions) for dimensions in sets_of_dimensions]), \ sum([present_ribbon_length(dimensions) for dimensions in sets_of_dimensions]) sets_of_dims = list() with open(os.path.dirname(os.path.realpath('__file__')) + "/input/day2.txt", "r") as datafile: for line in datafile: sets_of_dims.append([float(s) for s in line.rstrip("\n").split("x")]) print(presents(sets_of_dims))
python
# Copy from web_set_price.py of Trading Stock Thailand # Objective : Create Program to store financial data of company # From set.or.th # sk 2018-12-05 import urllib from bs4 import BeautifulSoup import numpy as np import pandas as pd from os.path import join, exists from os import remove, makedirs import urllib2 #sk #DIR_SEC_CSV = "sec_set_price" DIR_DATA_CSV = "data" # sk # Example url # https://www.set.or.th/set/historicaltrading.do? # symbol=BBL&page=2&language=en&country=US&type=trading # sk # https://www.set.or.th/set/companyfinance.do? # symbol=PTT&type=[balance,income,cashflow]& # language=en&country=US # def getTableData(symbol, page=1): # if page > 3: # page = 3 # limit at 3 def getTableData(cat, tick, typ, pg): #url_string = "https://www.set.or.th/set/historicaltrading.do?symbol={0}".format(symbol) #url_string += '&page={0}&language=en&country=US&type=trading'.format(page-1) url_string = "https://www.set.or.th/set/" url_string += cat + ".do?&language=en&country=us" url_string += "&symbol=" + tick url_string += "&type=" + typ if pg == 0: url_string += "" else: url_string += "&page=" + pg #page = urllib.request.urlopen(url_string).read() page = urllib2.urlopen(urllib2.Request(url_string)).read() soup = BeautifulSoup(page, 'lxml') # table_element = soup.find('table', class_='table table-hover table-info') table_element = soup.find('div', class_='table-responsive') # return table_element, url_string return table_element def createDataFrame(table_element): row_list =[] head_list = [] if table_element is None: return None tr_list = table_element.findAll('tr') for tr in tr_list: th_list = tr.findAll('th') if th_list is not None: for th in th_list: head_list.append(th.find(text=True)) td_list = tr.findAll('td') for td in td_list: row_list = np.append(row_list, td.find(text=True)) num_col = len(head_list) total_col = int(len(row_list)/num_col) row_list = np.reshape(row_list, (total_col, num_col) ) df=pd.DataFrame(columns = head_list, data = row_list) return df def create_all_data(symbol, total_page=1): # get stock data from set.or.th web (total page) df = None for p in range(1, total_page+1): table_element, url_string = getTableData(symbol, page=p) print(url_string) df_temp = createDataFrame(table_element) if df is None: df = df_temp else: df = df.append(df_temp) return df # def writeCSVFile(df, symbol, output_path=DIR_SEC_CSV, include_index = False): def writeCSVFile(df, symbol, output_path=DIR_DATA_CSV, include_index = False): csv_file = "{}.csv".format(join(output_path, symbol)) df.to_csv(csv_file, index = include_index) # def removeOldFile(symbol, output_path=DIR_SEC_CSV): def removeOldFile(symbol, output_path=DIR_DATA_CSV): csv_file = "{}.csv".format(join(output_path, symbol)) if exists(output_path) == False: makedirs(output_path) if exists(csv_file): remove(csv_file) if __name__ == "__main__" : # table_element, url_string = getTableData("PTT") # tr_list = table_element.findAll('tr') # print(tr_list[0:2]) table_element = getTableData("companyfinance", "PTT", "cashflow", 0) # symbol_list = ['AOT', 'BBL'] # for symbol in symbol_list: # df = create_all_data(symbol, total_page = 2) # print('\n********* %s **********' % symbol) # print(df.tail()) symbol_list = ['PTT'] for symbol in symbol_list: df = create_all_data(symbol) # save csv files (all stock data) # removeOldFile(symbol) # clear old files # writeCSVFile(df, symbol)
python
import nltk import json import argparse from collections import Counter def build_word2id(seq_path, min_word_count): """Creates word2id dictionary. Args: seq_path: String; text file path min_word_count: Integer; minimum word count threshold Returns: word2id: Dictionary; word-to-id dictionary """ sequences = open(seq_path).readlines() num_seqs = len(sequences) counter = Counter() for i, sequence in enumerate(sequences): tokens = nltk.tokenize.word_tokenize(sequence.lower()) counter.update(tokens) if i % 1000 == 0: print("[{}/{}] Tokenized the sequences.".format(i, num_seqs)) # create a dictionary and add special tokens word2id = {} word2id['<pad>'] = 0 word2id['<start>'] = 1 word2id['<end>'] = 2 word2id['<unk>'] = 3 # if word frequency is less than 'min_word_count', then the word is discarded words = [word for word, count in counter.items() if count >= min_word_count] # add the words to the word2id dictionary for i, word in enumerate(words): word2id[word] = i + 4 return word2id def main(config): # build word2id dictionaries for source and target sequences src_word2id = build_word2id(config.src_path, config.min_word_count) trg_word2id = build_word2id(config.trg_path, config.min_word_count) # save word2id dictionaries with open(config.src_word2id_path, 'w') as f: json.dump(src_word2id, f) with open(config.trg_word2id_path, 'w') as f: json.dump(trg_word2id, f) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--src_path', type=str, default='./data/src_train.txt') parser.add_argument('--trg_path', type=str, default='./data/trg_train.txt') parser.add_argument('--src_word2id_path', type=str, default='./data/src_word2id.json') parser.add_argument('--trg_word2id_path', type=str, default='./data/trg_word2id.json') parser.add_argument('--min_word_count', type=int, default=1) config = parser.parse_args() print (config) main(config)
python
# -*- coding:utf-8 -*- # Python 字典类型转换为JSON对象 data1 = { 'no': 1, 'name':'Runoob', 'url':'http://www.runoob.com' } # 对数据进行编码 import json json_str = json.dumps(data1) print("Python原始数据:", repr(data1)) print("JSON对象:", json_str) # 将JSON对象转换为Python字典 # 对数据进行解码 data2 = json.loads(json_str) print("data2['name']:", data2['name']) print("data2['url']:", data2['url'])
python
import re def checkIP(IP): regex='^([2][0-5][0-5]|[1]{0,1}[0-9]{1,2})\.([2][0-5][0-5]|[1]{0,1}[0-9]{1,2})\.([2][0-5][0-5]|[1]{0,1}[0-9]{1,2})\.([2][0-5][0-5]|[1]{0,1}[0-9]{1,2}$)' return re.match(regex,IP) def checkIP2(n): return n<=255 a=['123.4.2.222', '0.0.0.0', '14.123.444.2', '1.1.1.1'] print "***** CHECK USING REGEX *****" for IP in a: print IP, if checkIP(IP): print "VALID" else: print "INVALID" print "" print "***** CHECK USING OCTECT VALIDITY *****" for IP in a: print IP,"VALID" if all([checkIP2(int(n)) for n in IP.split('.')]) else "INVALID" checking valid email #([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+)\.([a-zA-Z]{2,4})
python
#!/usr/bin/env python import wx import pcbnew import os import time from .kifind_plugin_gui import kifind_gui from .kifind_plugin_action import FindAll, DoSelect, __version__ class KiFindDialog(kifind_gui): """Class that gathers all the Gui control""" def __ShowAll(self, do_tracks, do_mm): self.list_result.DeleteAllItems() vias = FindAll(self.board, do_tracks, do_mm) for key, value in vias.items(): #print("Adding " + key) self.list_result.Append([key, value]) def __init__(self, board): """Init the brand new instance""" super(KiFindDialog, self).__init__(None) self.do_tracks = True self.do_mm = True self.index = 0 self.board = board self.list_result.InsertColumn(0, "Value") self.list_result.InsertColumn(1, "Number") self.SetTitle("KiFind (ver.{})".format(__version__)) self.Bind(wx.EVT_CLOSE, self.onCloseWindow) self.but_cancel.Bind(wx.EVT_BUTTON, self.onCloseWindow) self.but_show.Bind(wx.EVT_BUTTON, self.onProcessAction) self.Bind(wx.EVT_RADIOBUTTON, self.onProcessMirror) self.list_result.Bind(wx.EVT_LIST_ITEM_SELECTED, self.onSelected) #self.m_bitmap_help.SetBitmap(wx.Bitmap( os.path.join(os.path.dirname(os.path.realpath(__file__)), "rcs", "teardrops-help.png") ) ) self.SetMinSize(self.GetSize()) self.__ShowAll(self.do_tracks, self.do_mm) def onProcessMirror(self, event): rb = event.GetEventObject() if rb == self.radio_tracks: self.do_tracks = True elif rb == self.radio_vias: self.do_tracks = False elif rb == self.radio_mm: self.do_mm = True elif rb == self.radio_mils: self.do_mm = False self.__ShowAll(self.do_tracks, self.do_mm) #print("Value: " + str(self.mirror_type)) #print("Clicked: " + rb.GetLabel()) def onProcessAction(self, event): try: # Executes the requested action #index = self.list_result.GetNextItem(0, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED) #print("Choosen: " + self.list_result.GetItemText(self.index)) num = DoSelect(self.board, self.do_tracks, self.do_mm, self.list_result.GetItemText(self.index)) pcbnew.UpdateUserInterface() s = ["vias", "tracks"][self.do_tracks] pcbnew.Refresh() wx.MessageBox("Ready!\n\nProcessed: {} {}".format(num, s)) except Exception as ex: wx.MessageBox("Error: {}".format(ex)) self.EndModal(wx.ID_OK) def onSelected(self, event): #self.index = event.GetSelection() self.index = self.list_result.GetFirstSelected() #print("Selected: " + self.list_result.GetItemText(self.index)) #DoSelect(self.board, do_tracks, self.list_result.GetItemText(index)) def onCloseWindow(self, event): self.EndModal(wx.ID_OK) def InitKiFindDialog(board): # Launch the dialog tg = KiFindDialog(board) tg.ShowModal() tg.Destroy() if __name__ == '__main__': InitKiFindDialog(pcbnew.GetBoard())
python
from app import app from selenium import webdriver from selenium.webdriver.common.keys import Keys import pandas as pd import time import json from flask import jsonify @app.route('/') @app.route('/home', methods=['GET']) def home(): navegador = webdriver.Chrome() pessoas = ["Brain+Lag", "Why", "Dankpot7", "Romance+Dawn", "Dreadway", "Cinza+Falso", "Shallan+Davar"] #pessoas = ["Brain+Lag", "Why"] elos = [] dados = [] win_rate = [] campeoes = [] for nome in pessoas: campeao = [] # Entra no perfil da pessoa navegador.get(f"https://br.op.gg/summoner/userName={nome}") # Atualiza o perfil #navegador.find_element_by_xpath('//*[@id="SummonerRefreshButton"]').click() time.sleep(1) # Pega os dados elo = navegador.find_element_by_xpath('//*[@id="SummonerLayoutContent"]/div[2]/div[1]/div[2]/div/div[2]').text dado = navegador.find_element_by_xpath('//*[@id="SummonerLayoutContent"]/div[2]/div[1]/div[2]/div/div[3]').text win = navegador.find_element_by_xpath('//*[@id="SummonerLayoutContent"]/div[2]/div[1]/div[2]/div/div[4]').text # Campeões jogados for i in range(1,11): campeao.append(navegador.find_element_by_xpath(f'//*[@id="SummonerLayoutContent"]/div[2]/div[2]/div/div[2]/div[3]/div[{i}]/div/div[1]/div[2]/div[4]/a').text) navegador.find_element_by_xpath('//*[@id="SummonerLayoutContent"]/div[2]/div[2]/div/div[2]/div[4]/a').click() time.sleep(2) for i in range(1,11): campeao.append(navegador.find_element_by_xpath(f'//*[@id="SummonerLayoutContent"]/div[2]/div[2]/div/div[2]/div[4]/div[{i}]/div/div[1]/div[2]/div[4]/a').text) elos.append(elo) dados.append(dado) win_rate.append(win) campeoes.append(campeao) pdls = [] vitorias_derrotas = [] taxa = [] nomes = [] for i in range(len(dados)): pdl = dados[i][:2] pdls.append(pdl) v_d = dados[i][6:] vitorias_derrotas.append(v_d) tx = win_rate[i][8:] taxa.append(tx) nm = pessoas[i].replace("+", " ") nomes.append(nm) dataframe = pd.DataFrame() dataframe["Invocador"] = nomes dataframe["Elo"] = elos dataframe["PLDs"] = pdls dataframe["Partidas"] = vitorias_derrotas dataframe["WinRate"] = taxa dataframe["Campeões"] = campeoes dataframe = dataframe.sort_values("WinRate", ascending=False) dataframe = dataframe.reset_index(drop=True) dataframe.to_json(f"{nomes[0]}.json") dick = dataframe.to_dict() return jsonify(dick)
python
# Copyright (c) 2019 Horizon Robotics. 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 torch import torch.nn as nn import alf from alf.data_structures import LossInfo, StepType from alf.utils import tensor_utils, value_ops from alf.utils.summary_utils import safe_mean_hist_summary @alf.configurable class OneStepQRLoss(nn.Module): """Temporal difference loss.""" def __init__(self, gamma=0.99, sum_over_quantiles=True, debug_summaries=False, name="OneStepQRLoss"): r""" Args: gamma (float|list[float]): A discount factor for future rewards. For multi-dim reward, this can also be a list of discounts, each discount applies to a reward dim. td_errors_loss_fn (Callable): A function for computing the TD errors loss. This function takes as input the target and the estimated Q values and returns the loss for each element of the batch. sum_over_quantiles (bool): Whether to sum over the quantiles debug_summaries (bool): True if debug summaries should be created. name (str): The name of this loss. """ super().__init__() self._name = name self._gamma = torch.tensor(gamma) self._debug_summaries = debug_summaries self._sum_over_quantiles = sum_over_quantiles @property def gamma(self): """Return the :math:`\gamma` value for discounting future rewards. Returns: Tensor: a rank-0 or rank-1 (multi-dim reward) floating tensor. """ return self._gamma.clone() def forward(self, info, value, target_value): """Calculate the loss. The first dimension of all the tensors is time dimension and the second dimesion is the batch dimension. Args: info (namedtuple): experience collected from ``unroll()`` or a replay buffer. All tensors are time-major. ``info`` should contain the following fields: - reward: - step_type: - discount: value (torch.Tensor): the time-major tensor for the value at each time step. The loss is between this and the calculated return. target_value (torch.Tensor): the time-major tensor for the value at each time step. This is used to calculate return. ``target_value`` can be same as ``value``. Returns: LossInfo: with the ``extra`` field same as ``loss``. """ if info.reward.ndim == 3: # [T, B, D] or [T, B, 1] discounts = info.discount.unsqueeze(-1) * self._gamma else: # [T, B] discounts = info.discount * self._gamma target_value_shape = target_value.shape rewards = info.reward.unsqueeze(-1).expand(target_value_shape) step_types = info.step_type.unsqueeze(-1).expand(target_value_shape) discounts = discounts.unsqueeze(-1).expand(target_value_shape) returns = value_ops.one_step_discounted_return( rewards=rewards, values=target_value, step_types=step_types, discounts=discounts) value = value[:-1] # Get the cummulative prob assert value.ndim == 3, value.shape n_quantiles = value.shape[-1] # Cumulative probabilities to calculate quantiles. cum_prob = (torch.arange( n_quantiles, device=value.device, dtype=torch.float ) + 0.5) / n_quantiles # For QR-DQN, current_quantiles have a shape # (T, B, n_quantiles), and make cum_prob # broadcastable to # (T, B, n_quantiles, n_target_quantiles) cum_prob = cum_prob.view(1, 1, -1, 1) # (T, B, n_quantiles, n_target_quantiles) element_wise_delta = returns.detach().unsqueeze(-2) - value.unsqueeze(-1) abs_element_wise_delta = torch.abs(element_wise_delta) huber_loss = torch.where( abs_element_wise_delta > 1, abs_element_wise_delta - 0.5, element_wise_delta ** 2 * 0.5 ) loss = torch.abs(cum_prob - (element_wise_delta.detach() < 0).float()) * huber_loss if self._sum_over_quantiles: loss = loss.sum(dim=-2).mean(dim=-1) else: loss = loss.mean(dim=-2).mean(dim=-1) # The shape of the loss expected by Algorith.update_with_gradient is # [T, B], so we need to augment it with additional zeros. loss = tensor_utils.tensor_extend_zero(loss) if self._debug_summaries and alf.summary.should_record_summaries(): mask = step_types[:-1] != StepType.LAST with alf.summary.scope(self._name): def _summarize(v, r, td, suffix): alf.summary.scalar( "explained_variance_of_return_by_value" + suffix, tensor_utils.explained_variance(v, r, mask)) safe_mean_hist_summary('values' + suffix, v, mask) safe_mean_hist_summary('returns' + suffix, r, mask) safe_mean_hist_summary("td_error" + suffix, td, mask) for i in range(value.shape[-2]): for j in range(value.shape[-1]): suffix = f'/{i}-{j}' _summarize( value[..., i, j], returns[..., i, j], element_wise_delta[..., i, j], suffix) return LossInfo(loss=loss, extra=loss)
python
from profiles.models import * from django.contrib import admin admin.site.register(FriendGroup) admin.site.register(UserProfile)
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db.models.query import QuerySet class CategoryQuerySet(QuerySet): def by_author(self, user): return self.filter(author=user)
python
seq = input() a = [(int(seq[i]) + int(seq[i+1]))/2.0 for i in range(len(seq)-1)] print(a)
python
####################################################################### # Tests for applications.py module ####################################################################### from auto_process_ngs.applications import * import unittest try: from cStringIO import StringIO except ImportError: # cStringIO not available in Python3 from io import StringIO class TestBcl2Fastq(unittest.TestCase): def test_configure_bcl_to_fastq(self): """Construct 'configureBclToFastq.pl' command lines """ self.assertEqual(bcl2fastq.configureBclToFastq( 'Data/Intensities/Basecalls', 'SampleSheet.csv').command_line, ['configureBclToFastq.pl', '--input-dir','Data/Intensities/Basecalls', '--output-dir','Unaligned', '--sample-sheet','SampleSheet.csv', '--fastq-cluster-count','-1']) self.assertEqual(bcl2fastq.configureBclToFastq( 'Data/Intensities/Basecalls', 'SampleSheet.csv', output_dir='run/bcl2fastq').command_line, ['configureBclToFastq.pl', '--input-dir','Data/Intensities/Basecalls', '--output-dir','run/bcl2fastq', '--sample-sheet','SampleSheet.csv', '--fastq-cluster-count','-1']) self.assertEqual(bcl2fastq.configureBclToFastq( 'Data/Intensities/Basecalls', 'SampleSheet.csv', output_dir='run/bcl2fastq', ignore_missing_bcl=True).command_line, ['configureBclToFastq.pl', '--input-dir','Data/Intensities/Basecalls', '--output-dir','run/bcl2fastq', '--sample-sheet','SampleSheet.csv', '--fastq-cluster-count','-1', '--ignore-missing-bcl']) self.assertEqual(bcl2fastq.configureBclToFastq( 'Data/Intensities/Basecalls', 'SampleSheet.csv', configureBclToFastq_exe= "/opt/bin/configureBclToFastq.pl").command_line, ['/opt/bin/configureBclToFastq.pl', '--input-dir','Data/Intensities/Basecalls', '--output-dir','Unaligned', '--sample-sheet','SampleSheet.csv', '--fastq-cluster-count','-1']) def test_bcl2fastq(self): """Construct 'bcl2fastq' command lines for bcl2fastq v2.* """ self.assertEqual(bcl2fastq.bcl2fastq2( '/runs/150107_NB123000_0001_ABCX', 'SampleSheet.csv').command_line, ['bcl2fastq', '--runfolder-dir','/runs/150107_NB123000_0001_ABCX', '--output-dir','Unaligned', '--sample-sheet','SampleSheet.csv']) self.assertEqual(bcl2fastq.bcl2fastq2( '/runs/150107_NB123000_0001_ABCX', 'SampleSheet.csv', output_dir='run/bcl2fastq').command_line, ['bcl2fastq', '--runfolder-dir','/runs/150107_NB123000_0001_ABCX', '--output-dir','run/bcl2fastq', '--sample-sheet','SampleSheet.csv']) self.assertEqual(bcl2fastq.bcl2fastq2( '/runs/150107_NB123000_0001_ABCX', 'SampleSheet.csv', output_dir='run/bcl2fastq', ignore_missing_bcl=True).command_line, ['bcl2fastq', '--runfolder-dir','/runs/150107_NB123000_0001_ABCX', '--output-dir','run/bcl2fastq', '--sample-sheet','SampleSheet.csv', '--ignore-missing-bcls']) self.assertEqual(bcl2fastq.bcl2fastq2( '/runs/150107_NB123000_0001_ABCX', 'SampleSheet.csv', output_dir='run/bcl2fastq', mismatches=1, no_lane_splitting=True).command_line, ['bcl2fastq', '--runfolder-dir','/runs/150107_NB123000_0001_ABCX', '--output-dir','run/bcl2fastq', '--sample-sheet','SampleSheet.csv', '--barcode-mismatches','1', '--no-lane-splitting']) self.assertEqual(bcl2fastq.bcl2fastq2( '/runs/150107_NB123000_0001_ABCX', 'SampleSheet.csv', bcl2fastq_exe='/opt/bin/bcl2fastq').command_line, ['/opt/bin/bcl2fastq', '--runfolder-dir','/runs/150107_NB123000_0001_ABCX', '--output-dir','Unaligned', '--sample-sheet','SampleSheet.csv']) class TestGeneral(unittest.TestCase): def test_rsync(self): """Construct 'rsync' command lines """ self.assertEqual(general.rsync('from','to').command_line, ['rsync','-av','from','to']) self.assertEqual(general.rsync('from','[email protected]:to').command_line, ['rsync','-av','-e','ssh','from','[email protected]:to']) def test_make(self): """Construct 'make' command lines """ self.assertEqual(general.make(makefile='makefile', working_dir='Unaligned', nprocessors='12').command_line, ['make', '-C','Unaligned', '-j','12', '-f','makefile']) def test_ssh_cmd(self): """Construct 'ssh' command lines """ self.assertEqual(general.ssh_command('user','example.com',('ls','-l')).command_line, ['ssh','[email protected]','ls','-l']) def test_scp(self): """Construct 'scp' command lines """ self.assertEqual( general.scp('user','example.com','my_file','remotedir').command_line, ['scp','my_file','[email protected]:remotedir']) def test_scp_recursive(self): """Construct 'scp -r' command lines """ self.assertEqual( general.scp('user','example.com','my_dir','remotedir', recursive=True).command_line, ['scp','-r','my_dir','[email protected]:remotedir'])
python
#!/usr/bin/env python # # This examples show how to use accessors to associate scalar data to mesh elements, # and how to read and write those data from/to mesh files using ViennaGrid's readers # and writers. from __future__ import print_function # In this example, we will illustrate how to read and write scalar data from and to # mesh files using accessors and the VTK reader and writer, respectively. # # We will start defining a domain of triangles in the cartesian 2D space and will # create some vertices and cells (triangles) in it. Then we will store the surface # of the cells using accessors. Finally, we will write the mesh and the scalar data # to a VTK file and we will read it again from the mesh file, just to illustrate # how to read and write data stored using accessors. from viennagrid import Domain, Point, Segmentation from viennagrid import config from viennagrid import io from viennagrid import accessors from viennagrid.algorithms import surface # Create an empty domain domain = Domain(config.triangular_2d) # Add vertices to the domain. These vertices will then be used to define # cells. domain.make_vertex(Point(0, 0)) # Vertex with ID #0 domain.make_vertex(Point(1, 0)) # Vertex with ID #1 domain.make_vertex(Point(2, 0)) # Vertex with ID #2 domain.make_vertex(Point(2, 1)) # Vertex with ID #3 domain.make_vertex(Point(1, 1)) # Vertex with ID #4 domain.make_vertex(Point(0, 1)) # Vertex with ID #5 # Create a segmentation of the domain segmentation = Segmentation(domain) # Create 2 segments in the segmentation of the domain seg0 = segmentation.make_segment() seg1 = segmentation.make_segment() # Create 2 cells in the first segment. Since the domain is a triangular domain, # cells are triangles and three vertices must be specified to create a cell. seg0.make_cell(domain.vertices[0], domain.vertices[1], domain.vertices[5]) seg0.make_cell(domain.vertices[1], domain.vertices[4], domain.vertices[5]) # Create 2 cells in the second segment. This time, we will use variable to # make the code shorter. seg1.make_cell(domain.vertices[1], domain.vertices[2], domain.vertices[4]) seg1.make_cell(domain.vertices[3], domain.vertices[2], domain.vertices[4]) # Create a new accessor for the cells of the domain and save for each cell # its surface. cell_surface_accessor = accessors.Accessor(accessors.CELL_ACCESSOR, config.triangular_2d) # For each cell of the domain, we calculate its surface and store the surface # of the cell using the accessor. To do that, we call the 'set_value' method # of the accessor specifying the cell and the value that we want to assign to # the cell. for cell in domain.cells: cell_surface_accessor.set_value(cell, surface(cell)) # Now we want to read the value corresponding to each cell stored in the accessor. # Since the cells that have a value stored in the accessor are all the cells of the # domain, we simply iterate over the cells of the domain and get the value stored # in the accessor for that cell using the 'get_value' method of the accessor. for i, cell in enumerate(domain.cells): value = cell_surface_accessor.get_value(cell) print('Cell #%(i)d has surface %(value)f' % locals()) # Next, we want to write the mesh and the scalar data to a VTK file. To do that, # we must provide each accessor with a name for the data stored in it, preferrably # a descriptive name of what the data mean. # # Since we have stored the surface of the cells, we will call the data 'surface'. # Then, we create a dictionary associating the quantity name to the accessor that # stores that given quantity. Since we only have one accessor to save, this dictionary # will have only one key. accessors = {'surface': cell_surface_accessor} # Now we call the VTK write as in the I/O tutorial, but we also specify the dictionary # that contains all accessors that should be written to the file. io.write_vtk('tri2d_mesh_with_surface_data_no_segment', domain, accessors) # If you want to save the segmentation information, too, you must call the writer as # explained in the I/O tutorial, also specifying the segmentation: io.write_vtk('tri2d_mesh_with_surface_data', domain, segmentation, accessors)
python
########## Single softmax layer NN build for digit recognition ################### ############ Import modules ################# import mnistdata import tensorflow as tf tf.set_random_seed(0) # Download images and labels into mnist.test (10K images+labels) and mnist.train (60K images+labels) mnist = mnistdata.read_data_sets("data", one_hot=True, reshape=False) ########### Define input, label, training parameters (weight and bias) ################ # input X: 28 * 28 gray-scale pixels X = tf.placeholder(dtype=tf.float32, shape=[None, 28, 28, 1], name='input_digits_2D') # label Y_: the expected label Y_ = tf.placeholder(dtype=tf.float32, shape=[None, 10], name='truth_label') # weights matrix W[28*28, 10] W = tf.Variable(initial_value=tf.zeros([28*28, 10])) # bias b[10] b = tf.Variable(initial_value=tf.zeros([10])) ########### Define model, expected output, loss function and training method ########### ## flatten the 28*28 image into 1 single line of pixels XX = tf.reshape(X, shape=[-1, 28*28]) # the softmax model Y = tf.nn.softmax(tf.matmul(XX, W) + b) # loss function cross_entropy = - tf.reduce_sum(Y_ * tf.log(Y)) # optimizer set up: GradientDecent(mini-batch), learning rate is 0.005 train_step = tf.train.GradientDescentOptimizer(learning_rate=0.005).minimize(loss = cross_entropy) # accuracy of the prediction correct_prediction = tf.equal(tf.argmax(Y, 1), tf.argmax(Y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) ######################################################################################### ########################### set up training process #################### ## initilization init = tf.global_variables_initializer() # sess = tf.Session() sess.run(init) ## batch training actions definition ## def do_training(i): batch_X, batch_Y = mnist.train.next_batch(100) # get batch-size data ##### print training accuracy and loss ############ train_a, train_c = sess.run([accuracy, cross_entropy], feed_dict={X: batch_X, Y_:batch_Y}) print("training " + str(i) + ": accuracy: " + str(train_a) + " loss: " + str(train_c)) ##### print testing accuracy and loss ############## test_a, test_c = sess.run([accuracy, cross_entropy], feed_dict={X: mnist.test.images, Y_:mnist.test.labels}) print("testing " + str(i) + ": ********* epoch " + str(i * 100 // mnist.train.images.shape[0] + 1) + " ********* test accuracy:" + str(test_a) + " test loss: " + str(test_c)) ##### backpropagation training ######## sess.run(train_step, feed_dict={X:batch_X, Y_:batch_Y}) with sess: iterations = 1000 for i in range(iterations): do_training(i) print("#############final performance on testing data###############") test_a, test_c = sess.run([accuracy, cross_entropy], feed_dict={X: mnist.test.images, Y_: mnist.test.labels}) print("accuracy:" + str(test_a) + " loss: " + str(test_c)) ##### print testing accuracy and loss ##############
python
import os os.environ['DJANGO_COLORS'] = 'nocolor' from django.core.management import call_command from django.db import connection from django.apps import apps from io import StringIO commands = StringIO() cursor = connection.cursor() for app in apps.get_app_configs(): call_command('sqlsequencereset', app.label, stdout=commands) cursor.execute(commands.getvalue())
python
import discord import os import keep_alive from discord.ext import commands client = commands.Bot(command_prefix=':', self_bot=True, help_command=None) @client.event async def on_ready(): # Playing # await client.change_presence(activity=discord.Game(name="a game")) # Streaming # await bot.change_presence(activity=discord.Streaming(name="a Stream", url="http://your-url-here.com/")) # Listening # await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="a song")) # Watching await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="The world burn")) keep_alive.keep_alive() client.run(os.getenv("TOKEN"), bot=False)
python
""" globals.py File that holds some important static dictionary look-up tables, and some useful functions used repeatedly in the codebase. """ import numpy as np import pandas as pd from scipy.special import logit """ get_prec_df Reads in the precinct df given the state and the year. NOTE: also adds in normalized candidate cfscores @param: state, year, bool value of whether want CD or not """ def get_prec_df(state, year, add_cd=False, alt=False): if year == None: return None if state == 'ne': state_lst = ['tx', 'ny'] else: state_lst = [state] prec_df_lst = [] for state in state_lst: precdir = '../data/%s_data/data/%s_%s' % (state, state, year) if alt: precfile = '%s/precline_%s_alt_%s.csv' % (precdir, state, year) else: precfile = '%s/precline_%s_house_%s.csv' % (precdir, state, year) prec_df = pd.read_csv(precfile) # add in normalized candidate cfscores # [-2, 2] --> [0, 1] --> logit() --> [-inf, +inf] prec_df['cf_score_0'] = prec_df['cf_score_0'].astype(float) prec_df['cf_score_1'] = prec_df['cf_score_1'].astype(float) prec_df['cf_norm_0'] = logit(((prec_df['cf_score_0'] + 2) / 4.0)) prec_df['cf_norm_1'] = logit(((prec_df['cf_score_1'] + 2) / 4.0)) if add_cd: prec_cd_file = '%s/%s_%s_prec_cd.csv' % (precdir, state, year) prec_df = pd.merge(prec_df, pd.read_csv(prec_cd_file), how='left', on='geoid') prec_df['state'] = state prec_df['geoid'] = prec_df['geoid'].astype('str') prec_df_lst.append(prec_df) return pd.concat(prec_df_lst) next_year_dict = { '2006': '2008', '2008': '2010', '2010': None } alt_exists_dict = { 'tx': { '2006': True, '2008': True, '2010': False, }, 'ny': { '2006': True, '2008': True, '2010': True, }, 'oh': { '2006': True, '2008': True, '2010': True, } } state_name_dict = { 'tx': 'Texas', 'ny': 'New York', 'oh': 'Ohio' } # maps both kinds of state names to the lowercase way we like state_cces_dict = { 'Texas': 'tx', 'New York': 'ny', 'Ohio': 'oh', 'TX': 'tx', 'NY': 'ny', 'OH': 'oh' } state_code_dict = { 'tx': 48, 'ny': 36, 'oh': 39 } # dictionaries that have hard-coded the string to integer values of CCES survey cces_ideology_dict = { 'very liberal': 1, 'liberal': 2, 'moderate': 3, 'conservative': 4, 'very conservative': 5, 'not sure': -1, 'skipped': -1, 'not asked': -1 } cces_self_p_dict = { 'Very Liberal': 1, 'Liberal': 2, 'Somewhat Liberal': 3, 'Middle of the Road': 4, 'Somewhat Conservative': 5, 'Conservative': 6, 'Very Conservative': 7, 'Not Sure': -1, 'Skipped': -1, 'Not Asked': -1, np.nan: -1 }
python
# Definition of dictionary europe = {'spain':'madrid', 'france':'paris', 'germany':'bonn', 'norway':'oslo', 'italy':'rome', 'poland':'warsaw', 'australia':'vienna' } # Update capital of germany europe['germany'] = 'berlin' # Remove australia del(europe['australia']) # Print europe print(europe)
python
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"f1score": "00_utils.ipynb", "df_preproc": "00_utils.ipynb", "load_data": "00_utils.ipynb", "TestModel": "00_utils.ipynb", "transform": "00_utils.ipynb", "windows_fast": "00_utils.ipynb", "AnomalyDetection": "01_binet.ipynb"} modules = ["utils.py", "binet.py"] doc_url = "https://{user}.github.io/anomaly/" git_url = "https://github.com/{user}/anomaly/tree/{branch}/" def custom_doc_links(name): return None
python
from __future__ import absolute_import from collections import OrderedDict import logging from tabulate import tabulate from numpy import asarray from numpy import sqrt from numpy import ones from numpy_sugar.linalg import economic_svd from ...tool.kinship import gower_normalization from ...tool.normalize import stdnorm from limix_inference.lmm import SlowLMM from limix_inference.mean import LinearMean from limix_inference.cov import LinearCov from limix_inference.cov import SumCov class InputInfo(object): def __init__(self): self.background_markers_user_provided = None self.nconst_background_markers = None self.covariates_user_provided = None self.nconst_markers = None self.kinship_rank = None self.candidate_nmarkers = None self.phenotype_info = None self.background_nmarkers = None self.effective_X = None self.effective_G = None self.effective_K = None self.S = None self.Q = None def __str__(self): t = [] t += self.phenotype_info.get_info() if self.background_markers_user_provided: t.append(['Background data', 'provided via markers']) t.append(['# background markers', self.background_nmarkers]) t.append([ '# const background markers', self.nconst_background_markers ]) else: t.append(['Background data', 'provided via Kinship matrix']) t.append(['Kinship diagonal mean', self.kinship_diagonal_mean]) if self.covariates_user_provided: t.append(['Covariates', 'provided by user']) else: t.append(['Covariates', 'a single column of ones']) t.append(['Kinship rank', self.kinship_rank]) t.append(['# candidate markers', self.candidate_nmarkers]) return tabulate(t, tablefmt='plain') def tuple_it(GK): r = [] for GKi in GK: if isinstance(GKi, tuple): r.append(GKi) else: r.append((GKi, False)) return tuple(r) def normalize_covariance_list(GK): if not isinstance(GK, (list, tuple, dict)): GK = (GK, ) GK = tuple_it(GK) if not isinstance(GK, dict): GK = [('K%d' % i, GK[i]) for i in range(len(GK))] GK = OrderedDict(GK) return GK def preprocess(GK, covariates, input_info): logger = logging.getLogger(__name__) input_info.covariates_user_provided = covariates is not None for (name, GKi) in iter(GK.items()): if GKi[1]: logger.info('Covariace matrix normalization on %s.', name) K = asarray(GKi[0], dtype=float) K = gower_normalization(K) GK[name] = (K, True) else: logger.info('Genetic markers normalization on %s.', name) G = asarray(GKi[0], dtype=float) G = stdnorm(G, 0) G /= sqrt(G.shape[1]) GK[name] = (G, False) input_info.effective_GK = GK def normal_decomposition(y, GK, covariates=None, progress=True): logger = logging.getLogger(__name__) logger.info('Normal variance decomposition scan has started.') y = asarray(y, dtype=float) ii = InputInfo() # ii.phenotype_info = NormalPhenotypeInfo(y) GK = normalize_covariance_list(GK) preprocess(GK, covariates, ii) vd = NormalVarDec( y, ii.effective_GK, covariates=covariates, progress=progress) vd.learn() # genetic_preprocess(X, G, K, covariates, ii) # # lrt = NormalLRT(y, ii.Q[0], ii.Q[1], ii.S[0], covariates=covariates, # progress=progress) # lrt.candidate_markers = ii.effective_X # lrt.pvals() # return lrt return vd def _offset_covariate(covariates, n): return ones((n, 1)) if covariates is None else covariates class VarDec(object): def __init__(self, K, covariates=None, progress=True): self._logger = logging.getLogger(__name__) self._progress = progress self._X = None self._K = K n = list(K.items())[0][1][0].shape[0] self._covariates = _offset_covariate(covariates, n) def learn(self): self._logger.info('Variance decomposition computation: has started.') self._learn(progress=False) class NormalVarDec(VarDec): def __init__(self, y, K, covariates=None, progress=True): super(NormalVarDec, self).__init__( K, covariates=covariates, progress=progress) self._y = y mean = LinearMean(self._covariates.shape[1]) mean.set_data(self._covariates) covs = [] for Ki in iter(K.items()): c = LinearCov() if Ki[1][1]: G = economic_svd(Ki[1][0]) else: G = Ki[1][0] c.set_data((G, G)) covs.append(c) cov = SumCov(covs) self._lmm = SlowLMM(y, mean, cov) def _learn(self, progress): self._lmm.feed().maximize()
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : Eric Winn # @Email : [email protected] # @Time : 19-9-3 上午7:19 # @Version : 1.0 # @File : __init__.py # @Software : PyCharm
python
from typing import Optional from django.urls import reverse from django.views.generic import CreateView from django.http import Http404 from django.utils.functional import cached_property from task.forms import TaskCreateForm from ..models import Member from ..querysets import get_user_teams, get_team_with_members from ..forms import TeamCreateForm, MemberCreateForm class TeamView(CreateView): template_name = "team/team.html" form_class = TeamCreateForm def get_success_url(self) -> str: return reverse("team") def get_context_data(self, **kwargs): kwargs['object_list'] = get_user_teams(self.request.user.pk) return super().get_context_data(**kwargs) def post(self, request, *args, **kwargs): if request.method == 'POST': post = request.POST.copy() post.update({"creator": request.user}) request.POST = post return super().post(request, *args, **kwargs) class TeamManagementView(CreateView): template_name = "team/management.html" def get_form_class(self): if self.request.method == 'POST': if 'add_member' in self.request.POST: return MemberCreateForm return TaskCreateForm def __get_team_id(self) -> int: """Return team id that exists in url kwargs""" return self.kwargs.get('id', None) def __validate_post_team_id(self) -> bool: """ Validate entered team id in form are equal to team id in url kwargs """ team_id = self.__get_team_id() return self.request.POST.get("team", [None])[0] == str(team_id) def get_success_url(self) -> str: team = self.__get_team_id() if team is None: return reverse("team") return reverse("team-management", kwargs={"id": team}) def get_context_data(self, **kwargs): """ Sets `object` context to team object that exists in url. if team not found, `Http404` will be raised """ obj = get_team_with_members( team_id=self.kwargs.get("id") ) if obj is None: raise Http404() kwargs['object'] = obj return super().get_context_data(**kwargs) @cached_property def _member_object(self) -> Optional[Member]: """Returns member instance of request.user""" return Member.objects.filter( user=self.request.user, team_id=self.__get_team_id() ).first() def has_permissions(self): """ Checks that user has permission to access to this page or not """ member = self._member_object return member and member.rank > Member.RankChoices.NORMAL def post(self, request, *args, **kwargs): if not self.has_permissions() or not self.__validate_post_team_id(): raise Http404() return super().post(request, *args, **kwargs) def get(self, request, *args, **kwargs): if not self._member_object: raise Http404() if not self.has_permissions(): pass # Should be redirected to tasks page return super().get(request, *args, **kwargs)
python
from PyQt5.QtCore import * from PyQt5.QtWidgets import * from common.config import Config, workstation_methods from panel.common.CommonWidgets import * class WorkstationConfiguration(QWidget): def __init__(self, workstation_name, workstation_type): super(WorkstationConfiguration, self).__init__() self.workstation_name = workstation_name self.workstation_type = workstation_type self.resize(QSize(1600, 500)) self.create_widgets() self.item_count = 0 self._configuration = {} self.networks_available = [] self.basic_actions() def create_widgets(self): # Labels self.name_label = QLabel("Workstation name") self.distribution_label = QLabel("Distribution") self.release_label = QLabel("Release") self.network_name_label = QLabel("Network name") self.network_interface_label = QLabel("Network interface") self.network_ip_label = QLabel("IP address") self.network_subnet_label = QLabel("Subnet") self.gateway_label = QLabel("Gateway") self.camera_label = QCheckBox("Camera") # Line Edits self.name_value = QLabel(self.workstation_name) self.distribution_value = QLineEdit() self.distribution_value.setText("ubuntu") self.release_value = QLineEdit() self.release_value.setText("bionic") self.network_value = QComboBox() self.interface_value = QLineEdit() self.interface_value.setText("eth1") self.ip_value = QLineEdit() self.ip_value.setText("10.122.0.") self.subnet_value = QLineEdit() self.subnet_value.setText("24") self.gateway_value = QLineEdit() self.gateway_value.setText("10.122.0.1") # Group box self.group_box = QGroupBox(self) self.group_box.setTitle(self.workstation_name + ' physic configuration') # Grid layout self.grid_layout = QGridLayout() # Workstation name self.grid_layout.addWidget(self.name_label, 0, 0) self.grid_layout.addWidget(self.name_value, 0, 1) # Distribution name self.grid_layout.addWidget(self.distribution_label, 0, 3) self.grid_layout.addWidget(self.distribution_value, 0, 4) # Release name self.grid_layout.addWidget(self.release_label, 0, 6) self.grid_layout.addWidget(self.release_value, 0, 7) # Network name self.grid_layout.addWidget(self.network_name_label, 1, 0) self.grid_layout.addWidget(self.network_value, 1, 1) # Interface name self.grid_layout.addWidget(self.network_interface_label, 1, 3) self.grid_layout.addWidget(self.interface_value, 1, 4) # IP address self.grid_layout.addWidget(self.network_ip_label, 1, 6) self.grid_layout.addWidget(self.ip_value, 1, 7) # Subnet self.grid_layout.addWidget(self.network_subnet_label, 2, 0) self.grid_layout.addWidget(self.subnet_value, 2, 1) # Gateway self.grid_layout.addWidget(self.gateway_label, 2, 3) self.grid_layout.addWidget(self.gateway_value, 2, 4) #Camera self.grid_layout.addWidget(self.camera_label, 2, 6, 1, 2) self.group_box.setLayout(self.grid_layout) def update_networks_list(self, networks_list): # Get current network name former_network = self.network_value.currentText() # Clean combo box self.network_value.clear() self.network_value.addItem("") # Recreate networks list for network in networks_list: # item network is a dict self.network_value.addItem(network["name"]) self.network_value.addItem("lxdbr0") # If selected network has not been removed, set index to combo box former_index = self.network_value.findText(former_network) self.network_value.setCurrentIndex(former_index) self.networks_available = networks_list def set_configuration(self, config): """ Set data stored in config to widgets available in view :param config: Parameters to be set :type config: dict :return: None """ self.name_value.setText(config["hostname"]) self.distribution_value.setText(config["distribution"]) self.release_value.setText(config["release"]) network_index = self.network_value.findText(config["networks"][0]["name"]) self.network_value.setCurrentIndex(network_index) self.interface_value.setText(config["networks"][0]["interface"]) self.ip_value.setText(config["networks"][0]["ip_v4"]) self.subnet_value.setText(config["networks"][0]["subnet"]) self.gateway_value.setText(config["gateway"]) self.camera_label.setChecked(config["camera"] in ["true"]) def get_current_configuration(self): """ Read data entered in editable fields :return: Currently set configuration :rtype: dict """ self._configuration = { "hostname": self.name_value.text(), "distribution": self.distribution_value.text(), "release": self.release_value.text(), "network_name": self.network_value.currentText(), "network_interface": self.interface_value.text(), "ip_address": self.ip_value.text(), "subnet": self.subnet_value.text(), "gateway": self.gateway_value.text(), "camera": str(self.camera_label.isChecked()).lower() } return self._configuration def basic_actions(self): """ Connects signals to dedicated functions """ self.network_value.currentTextChanged.connect(self.update_network_values) @pyqtSlot() def update_network_values(self): """ Regarding selected network, set values to widgets """ # Find selected network current_network_name = self.network_value.currentText() if current_network_name not in ["", "lxdbr0"]: current_network = next(network for network in self.networks_available if network["name"] == current_network_name) base_ip = ".".join(current_network["ip_v4"].split(".")[0:-1]) subnet = current_network["subnet"] gateway = ".".join([base_ip, "1"]) # Then, set values to required widgets current_ip = self.ip_value.text().split(".")[-1] self.ip_value.setText(base_ip + "." + current_ip) self.subnet_value.setText(subnet) self.gateway_value.setText(gateway) if "interface" in current_network.keys(): self.interface_value.setText(current_network["interface"]) if current_network_name in ["lxdbr0"]: self.ip_value.setText("default_ip_on_lxdbr0") self.subnet_value.setText("24") self.gateway_value.setText("default_gateway_on_lxdbr0") self.interface_value.setText("") def check_values(self): """ Check if entered values are as expected :return: Collection of bool related to value checking :rtype: dict """ dist = True if self.distribution_value.text() in ["ubuntu", "debian"] else False network = True if self.network_value.currentText() not in [""] else False split_ip = self.ip_value.text().split(".") ip = True if split_ip[-1] not in [""] else False gateway = True if split_ip[-1] not in [""] else False assertion = { "distribution": dist, # if wrong distribution set "network": network, # if wrong network name set "ip": ip, # if ip address is incomplete, "gateway": gateway # if gateway is incomplete } return assertion class WorkstationActions(QWidget): def __init__(self, workstation_name, workstation_type): super(WorkstationActions, self).__init__() self.workstation_name = workstation_name self.workstation_type = workstation_type self._workstations_actions = {} self.users_available = [] self.retrieve_workstations_actions() self.create_widgets() self.set_layout() self.create_actions_list(self.workstation_type) self.basic_actions() # Counters self.item_count = 0 # for actions self.parameter_count = 0 # for arguments # Dictionary to store set actions self._actions_list = [] def retrieve_workstations_actions(self): """ Loads functions defined in logic_actions scripts """ self._workstations_actions["workstation"] = [] _workstations = [w for w in Config.get_available_workstations() if w not in ["workstation"]] # For each type of workstation, get dedicated actions and utils actions for workstation in _workstations: self._workstations_actions[workstation] = workstation_methods[workstation]() self._workstations_actions[workstation] += workstation_methods["utils"]() self._workstations_actions["workstation"] += self._workstations_actions[workstation] # common_actions = [actions.items() for workstation, actions in self._workstations_actions.items()] self._workstations_actions["workstation"] += Config.get_workstations_methods() self._workstations_actions["workstation"] += workstation_methods["utils"]() def basic_actions(self): """ Connects signals to dedicated functions """ # Actions self.actions_apply.clicked.connect(self.add_action) self.remove_button.clicked.connect(self.remove_action) # Parameters self.add_param_button.clicked.connect(self.add_parameter) self.remove_param_button.clicked.connect(self.remove_parameter) # Table actions self.reset_button.clicked.connect(self.reset_tables) self.default_button.clicked.connect(self.default_configuration) self.up_button.clicked.connect(self.item_up) self.down_button.clicked.connect(self.item_down) self.apply_parameters.clicked.connect(self.update_parameter_table) # Qt signals self.actions_table.itemSelectionChanged.connect(self.generate_parameter_table) @pyqtSlot() def add_action(self): """ Add an element to the actions table widget """ try: act = self.actions_table.currentRow() name = self.actions_list.currentText() if name not in [""]: d_actions = {"name": self.actions_list.currentText()} else: return self._actions_list.append(d_actions) # self._actions_arg.append(self.actions_args.text()) self.generate_action_table() except: print("No item selected") @pyqtSlot() def remove_action(self): """ Remove an element from actions table widget """ try: item_index = self.actions_table.currentRow() self._actions_list.pop(item_index) self.generate_action_table() except: print("No item selected") def generate_action_table(self): """ Generates actions table using data stored in _actions_list """ # Create item to add action to QTableWidget self.item_count = 0 self.actions_table.clear() self.actions_table.setRowCount(0) self.actions_table.setHorizontalHeaderLabels(["Actions"]) for index in range(len(self._actions_list)): action_label = QTableWidgetItem(self._actions_list[index]["name"]) # action_arg = QTableWidgetItem(self._actions_arg[index]) self.actions_table.insertRow(self.item_count) self.actions_table.setItem(self.item_count, 0, action_label) # self.actions_table.setItem(self.item_count, 1, action_arg) self.item_count += 1 @pyqtSlot() def add_parameter(self): """ Add an empty line to parameters table widget """ # Get action name try: param_name = QComboBox() param_name.setEditable(True) param_name.addItem("") action_name = self.actions_table.item(self.actions_table.currentRow(), 0).text() for elt in Config.get_authorized_values(action_name): param_name.addItem(elt) parameter_value = QLineEdit("") self.complex_actions_table.insertRow(self.parameter_count) # Add widgets to each line of parameters table self.complex_actions_table.setCellWidget(self.parameter_count, 0, param_name) self.complex_actions_table.setCellWidget(self.parameter_count, 1, parameter_value) self.parameter_count += 1 except: pass @pyqtSlot() def remove_parameter(self): """ Removes selected element from parameters table """ try: # Get selected action index action_index = self.actions_table.currentRow() # Get selected parameter name parameter = self.complex_actions_table.cellWidget(self.complex_actions_table.currentRow(), 0).currentText() self.complex_actions_table.removeRow(self.complex_actions_table.currentRow()) # Remove selected parameter from _actions_list (containing configuration) if parameter in self._actions_list[action_index]["args"].keys(): self._actions_list[action_index]["args"].pop(parameter) self.generate_parameter_table() except: pass @pyqtSlot() def update_parameter_table(self): """ Set up current action configuration as new configuration """ d_args = {} try: # Get current action index and name action_index = self.actions_table.currentRow() action_name = self.actions_table.item(action_index, 0).text() # Get data in parameters table and set it in d_args for index in range(self.complex_actions_table.rowCount()): param_name = self.complex_actions_table.cellWidget(index, 0).currentText() try: param_value = self.complex_actions_table.cellWidget(index, 1).get_configuration() except: param_value = self.complex_actions_table.cellWidget(index, 1).text() ########################################################################## # Get availables users ########################################################################## if param_name in ["create_sim_user"]: self.users_available.append(param_value) d_args[param_name] = param_value # once d_args if filled with all parameters, it is stored in an object used in json file generation d_complete = { "name": action_name, "args": d_args } self._actions_list[action_index] = d_complete self.generate_parameter_table() except: pass @pyqtSlot() def generate_parameter_table(self): """ Updates parameter table view """ # Clear table self.parameter_count = 0 self.complex_actions_table.clear() self.complex_actions_table.setRowCount(0) self.complex_actions_table.setHorizontalHeaderLabels(["Parameters", "Values"]) try: # Get action index action_index = self.actions_table.currentRow() self.parameter_count = 0 # Show values for action, argument in self._actions_list[action_index]["args"].items(): param_name = QComboBox() param_name.setEditable(True) param_name.addItem("") for elt in Config.get_authorized_values(self._actions_list[action_index]["name"]): param_name.addItem(elt) param_name.setCurrentText(action) if type(argument) not in [dict, list]: parameter_value = QTextEdit(argument) elif type(argument) is list: parameter_value = ListArgumentWidget(argument) parameter_value.set_configuration() elif type(argument) is dict: parameter_value = DictArgumentWidget(argument) parameter_value.set_configuration() else: parameter_value = QTextEdit("Must be checked in json file") self.complex_actions_table.insertRow(self.parameter_count) self.complex_actions_table.setCellWidget(self.parameter_count, 0, param_name) self.complex_actions_table.setCellWidget(self.parameter_count, 1, parameter_value) self.parameter_count += 1 except: pass @pyqtSlot() def reset_tables(self): """ Clears all values set in QTableWidgets :return: None """ self.actions_table.clear() self.actions_table.setRowCount(0) self.actions_table.setHorizontalHeaderLabels(["Actions"]) self.complex_actions_table.clear() self.complex_actions_table.setRowCount(0) self.complex_actions_table.setHorizontalHeaderLabels(["Parameters", "Values"]) self._actions_list = [] @pyqtSlot() def default_configuration(self): pass @pyqtSlot() def item_up(self): """ Change actions table order :return: None """ try: current_index = self.actions_table.currentRow() if current_index == 0: return if current_index >= 1: self._actions_list[current_index - 1], self._actions_list[current_index] = self._actions_list[current_index], self._actions_list[current_index - 1] self.generate_action_table() self.generate_parameter_table() except: pass @pyqtSlot() def item_down(self): """ Change actions table order :return: None """ try: current_index = self.actions_table.currentRow() if current_index == self.actions_table.rowCount(): return if current_index <= self.actions_table.rowCount() - 1: self._actions_list[current_index + 1], self._actions_list[current_index] = self._actions_list[current_index], self._actions_list[current_index + 1] self.generate_action_table() self.generate_parameter_table() except: pass def create_actions_list(self, workstation_type): """ Loads functions defined in logic_actions scripts and set up in available actions :param workstation_type: Current workstation type :type workstation_type: str :return: None """ if workstation_type in self._workstations_actions.keys(): # Concatenate specific workstation actions and common actions available_actions = list(set(self._workstations_actions[workstation_type])) else: available_actions = list(set(self._workstations_actions["workstation"])) # Set availables actions to QComboBox self.actions_list.addItems(available_actions) def create_widgets(self): # Selecting actions to add self.actions_label = QLabel("Actions: ") self.actions_list = QComboBox() # Box containing available actions self.actions_list.addItem("") self.actions_list.setEditable(True) self.actions_apply = QPushButton("Add action") # Then, a table is needed to show applied functions self.actions_table = QTableWidget() self.actions_table.insertColumn(0) self.actions_table.setColumnWidth(0, 450) self.actions_table.setHorizontalHeaderLabels(["Actions"]) # Then another table is required for more complex actions self.complex_actions_table = QTableWidget() self.complex_actions_table.insertColumn(0) self.complex_actions_table.setColumnWidth(0, 300) self.complex_actions_table.insertColumn(1) self.complex_actions_table.setColumnWidth(1, 600) self.complex_actions_table.setHorizontalHeaderLabels(["Parameters", "Values"]) # With button actions self.up_button = QPushButton("Up") self.down_button = QPushButton("Down") self.remove_button = QPushButton("Remove action") self.default_button = QPushButton("Default configuration") self.reset_button = QPushButton("Reset configuration") self.add_param_button = QPushButton("+") self.remove_param_button = QPushButton("-") self.apply_parameters = QPushButton("Update configuration") def set_layout(self): # Main layout self.main_layout = QVBoxLayout(self) # Header self.header = QGroupBox("logic configuration") logic_layout = QHBoxLayout() #Config actions actions = QGroupBox() actions.setMaximumWidth(800) actions_layout = QGridLayout() actions_layout.addWidget(self.actions_label, 0, 0) actions_layout.addWidget(self.actions_list, 0, 1, 1, 2) actions_layout.addWidget(self.actions_apply, 1, 0) actions_layout.addWidget(self.remove_button, 1, 1) actions_layout.addWidget(self.up_button, 3, 2) actions_layout.addWidget(self.down_button, 4, 2) actions_layout.addWidget(self.reset_button, 8, 2) actions_layout.addWidget(self.actions_table, 3, 0, 6, 2) actions.setLayout(actions_layout) args = QGroupBox() args_layout = QGridLayout() args_layout.addWidget(self.add_param_button, 0, 0) args_layout.addWidget(self.remove_param_button, 0, 1) args_layout.addWidget(self.complex_actions_table, 1, 0, 6, 2) args_layout.addWidget(self.apply_parameters, 8, 0, 1, 2) args.setLayout(args_layout) logic_layout.addWidget(actions) logic_layout.addWidget(args) self.header.setLayout(logic_layout) self.main_layout.addWidget(self.header) def set_configuration(self, d_actions): """ Set data loaded by reading json file to class object :param d_actions: Values loaded :type d_actions: dict :return: """ self._actions_list = d_actions self.generate_action_table() def get_current_actions(self): """ Get data available in interface :return: Formatted data :rtype: dict """ return {self.workstation_name: self._actions_list} def get_available_users(self): """ Get configured users available :return: List of users :rtype: list """ return self.users_available def check_values(self): pass
python
""" Digital Communications Function Module Copyright (c) March 2017, Mark Wickert All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. """ from matplotlib import pylab from matplotlib import mlab import numpy as np from numpy import fft import matplotlib.pyplot as plt from scipy import signal from scipy.special import erfc from sys import exit from .sigsys import upsample from .sigsys import downsample from .sigsys import NRZ_bits from .sigsys import NRZ_bits2 from .sigsys import PN_gen from .sigsys import m_seq from .sigsys import cpx_AWGN from .sigsys import CIC def farrow_resample(x, fs_old, fs_new): """ Parameters ---------- x : Input list representing a signal vector needing resampling. fs_old : Starting/old sampling frequency. fs_new : New sampling frequency. Returns ------- y : List representing the signal vector resampled at the new frequency. Notes ----- A cubic interpolator using a Farrow structure is used resample the input data at a new sampling rate that may be an irrational multiple of the input sampling rate. Time alignment can be found for a integer value M, found with the following: .. math:: f_{s,out} = f_{s,in} (M - 1) / M The filter coefficients used here and a more comprehensive listing can be found in H. Meyr, M. Moeneclaey, & S. Fechtel, "Digital Communication Receivers," Wiley, 1998, Chapter 9, pp. 521-523. Another good paper on variable interpolators is: L. Erup, F. Gardner, & R. Harris, "Interpolation in Digital Modems--Part II: Implementation and Performance," IEEE Comm. Trans., June 1993, pp. 998-1008. A founding paper on the subject of interpolators is: C. W. Farrow, "A Continuously variable Digital Delay Element," Proceedings of the IEEE Intern. Symp. on Circuits Syst., pp. 2641-2645, June 1988. Mark Wickert April 2003, recoded to Python November 2013 Examples -------- The following example uses a QPSK signal with rc pulse shaping, and time alignment at M = 15. >>> import matplotlib.pyplot as plt >>> from numpy import arange >>> from sk_dsp_comm import digitalcom as dc >>> Ns = 8 >>> Rs = 1. >>> fsin = Ns*Rs >>> Tsin = 1 / fsin >>> N = 200 >>> ts = 1 >>> x, b, data = dc.MPSK_bb(N+12, Ns, 4, 'rc') >>> x = x[12*Ns:] >>> xxI = x.real >>> M = 15 >>> fsout = fsin * (M-1) / M >>> Tsout = 1. / fsout >>> xI = dc.farrow_resample(xxI, fsin, fsin) >>> tx = arange(0, len(xI)) / fsin >>> yI = dc.farrow_resample(xxI, fsin, fsout) >>> ty = arange(0, len(yI)) / fsout >>> plt.plot(tx - Tsin, xI) >>> plt.plot(tx[ts::Ns] - Tsin, xI[ts::Ns], 'r.') >>> plt.plot(ty[ts::Ns] - Tsout, yI[ts::Ns], 'g.') >>> plt.title(r'Impact of Asynchronous Sampling') >>> plt.ylabel(r'Real Signal Amplitude') >>> plt.xlabel(r'Symbol Rate Normalized Time') >>> plt.xlim([0, 20]) >>> plt.grid() >>> plt.show() """ #Cubic interpolator over 4 samples. #The base point receives a two sample delay. v3 = signal.lfilter([1/6., -1/2., 1/2., -1/6.],[1],x) v2 = signal.lfilter([0, 1/2., -1, 1/2.],[1],x) v1 = signal.lfilter([-1/6., 1, -1/2., -1/3.],[1],x) v0 = signal.lfilter([0, 0, 1],[1],x) Ts_old = 1/float(fs_old) Ts_new = 1/float(fs_new) T_end = Ts_old*(len(x)-3) t_new = np.arange(0,T_end+Ts_old,Ts_new) if x.dtype == np.dtype('complex128') or x.dtype == np.dtype('complex64'): y = np.zeros(len(t_new)) + 1j*np.zeros(len(t_new)) else: y = np.zeros(len(t_new)) for n in range(len(t_new)): n_old = int(np.floor(n*Ts_new/Ts_old)) mu = (n*Ts_new - n_old*Ts_old)/Ts_old # Combine outputs y[n] = ((v3[n_old+1]*mu + v2[n_old+1])*mu + v1[n_old+1])*mu + v0[n_old+1] return y def eye_plot(x,L,S=0): """ Eye pattern plot of a baseband digital communications waveform. The signal must be real, but can be multivalued in terms of the underlying modulation scheme. Used for BPSK eye plots in the Case Study article. Parameters ---------- x : ndarray of the real input data vector/array L : display length in samples (usually two symbols) S : start index Returns ------- None : A plot window opens containing the eye plot Notes ----- Increase S to eliminate filter transients. Examples -------- 1000 bits at 10 samples per bit with 'rc' shaping. >>> import matplotlib.pyplot as plt >>> from sk_dsp_comm import digitalcom as dc >>> x,b, data = dc.NRZ_bits(1000,10,'rc') >>> dc.eye_plot(x,20,60) >>> plt.show() """ plt.figure(figsize=(6,4)) idx = np.arange(0,L+1) plt.plot(idx,x[S:S+L+1],'b') k_max = int((len(x) - S)/L)-1 for k in range(1,k_max): plt.plot(idx,x[S+k*L:S+L+1+k*L],'b') plt.grid() plt.xlabel('Time Index - n') plt.ylabel('Amplitude') plt.title('Eye Plot') return 0 def scatter(x,Ns,start): """ Sample a baseband digital communications waveform at the symbol spacing. Parameters ---------- x : ndarray of the input digital comm signal Ns : number of samples per symbol (bit) start : the array index to start the sampling Returns ------- xI : ndarray of the real part of x following sampling xQ : ndarray of the imaginary part of x following sampling Notes ----- Normally the signal is complex, so the scatter plot contains clusters at point in the complex plane. For a binary signal such as BPSK, the point centers are nominally +/-1 on the real axis. Start is used to eliminate transients from the FIR pulse shaping filters from appearing in the scatter plot. Examples -------- >>> import matplotlib.pyplot as plt >>> from sk_dsp_comm import digitalcom as dc >>> x,b, data = dc.NRZ_bits(1000,10,'rc') Add some noise so points are now scattered about +/-1. >>> y = dc.cpx_AWGN(x,20,10) >>> yI,yQ = dc.scatter(y,10,60) >>> plt.plot(yI,yQ,'.') >>> plt.grid() >>> plt.xlabel('In-Phase') >>> plt.ylabel('Quadrature') >>> plt.axis('equal') >>> plt.show() """ xI = np.real(x[start::Ns]) xQ = np.imag(x[start::Ns]) return xI, xQ def strips(x,Nx,fig_size=(6,4)): """ Plots the contents of real ndarray x as a vertical stacking of strips, each of length Nx. The default figure size is (6,4) inches. The yaxis tick labels are the starting index of each strip. The red dashed lines correspond to zero amplitude in each strip. strips(x,Nx,my_figsize=(6,4)) Mark Wickert April 2014 """ plt.figure(figsize=fig_size) #ax = fig.add_subplot(111) N = len(x) Mx = int(np.ceil(N/float(Nx))) x_max = np.max(np.abs(x)) for kk in range(Mx): plt.plot(np.array([0,Nx]),-kk*Nx*np.array([1,1]),'r-.') plt.plot(x[kk*Nx:(kk+1)*Nx]/x_max*0.4*Nx-kk*Nx,'b') plt.axis([0,Nx,-Nx*(Mx-0.5),Nx*0.5]) plt.yticks(np.arange(0,-Nx*Mx,-Nx),np.arange(0,Nx*Mx,Nx)) plt.xlabel('Index') plt.ylabel('Strip Amplitude and Starting Index') return 0 def bit_errors(tx_data,rx_data,Ncorr = 1024,Ntransient = 0): """ Count bit errors between a transmitted and received BPSK signal. Time delay between streams is detected as well as ambiquity resolution due to carrier phase lock offsets of :math:`k*\\pi`, k=0,1. The ndarray tx_data is Tx 0/1 bits as real numbers I. The ndarray rx_data is Rx 0/1 bits as real numbers I. Note: Ncorr needs to be even """ # Remove Ntransient symbols and level shift to {-1,+1} tx_data = 2*tx_data[Ntransient:]-1 rx_data = 2*rx_data[Ntransient:]-1 # Correlate the first Ncorr symbols at four possible phase rotations R0 = np.fft.ifft(np.fft.fft(rx_data,Ncorr)* np.conj(np.fft.fft(tx_data,Ncorr))) R1 = np.fft.ifft(np.fft.fft(-1*rx_data,Ncorr)* np.conj(np.fft.fft(tx_data,Ncorr))) #Place the zero lag value in the center of the array R0 = np.fft.fftshift(R0) R1 = np.fft.fftshift(R1) R0max = np.max(R0.real) R1max = np.max(R1.real) R = np.array([R0max,R1max]) Rmax = np.max(R) kphase_max = np.where(R == Rmax)[0] kmax = kphase_max[0] # Correlation lag value is zero at the center of the array if kmax == 0: lagmax = np.where(R0.real == Rmax)[0] - Ncorr/2 elif kmax == 1: lagmax = np.where(R1.real == Rmax)[0] - Ncorr/2 taumax = lagmax[0] print('kmax = %d, taumax = %d' % (kmax, taumax)) # Count bit and symbol errors over the entire input ndarrays # Begin by making tx and rx length equal and apply phase rotation to rx if taumax < 0: tx_data = tx_data[int(-taumax):] tx_data = tx_data[:min(len(tx_data),len(rx_data))] rx_data = (-1)**kmax*rx_data[:len(tx_data)] else: rx_data = (-1)**kmax * rx_data[int(taumax):] rx_data = rx_data[:min(len(tx_data),len(rx_data))] tx_data = tx_data[:len(rx_data)] # Convert to 0's and 1's Bit_count = len(tx_data) tx_I = np.int16((tx_data.real + 1)/2) rx_I = np.int16((rx_data.real + 1)/2) Bit_errors = tx_I ^ rx_I return Bit_count,np.sum(Bit_errors) def QAM_bb(N_symb,Ns,mod_type='16qam',pulse='rect',alpha=0.35): """ QAM_BB_TX: A complex baseband transmitter x,b,tx_data = QAM_bb(K,Ns,M) //////////// Inputs ////////////////////////////////////////////////// N_symb = the number of symbols to process Ns = number of samples per symbol mod_type = modulation type: qpsk, 16qam, 64qam, or 256qam alpha = squareroot raised codine pulse shape bandwidth factor. For DOCSIS alpha = 0.12 to 0.18. In general alpha can range over 0 < alpha < 1. SRC = pulse shape: 0-> rect, 1-> SRC //////////// Outputs ///////////////////////////////////////////////// x = complex baseband digital modulation b = transmitter shaping filter, rectangle or SRC tx_data = xI+1j*xQ = inphase symbol sequence + 1j*quadrature symbol sequence Mark Wickert November 2014 """ # Filter the impulse train waveform with a square root raised # cosine pulse shape designed as follows: # Design the filter to be of duration 12 symbols and # fix the excess bandwidth factor at alpha = 0.35 # If SRC = 0 use a simple rectangle pulse shape if pulse.lower() == 'src': b = sqrt_rc_imp(Ns,alpha,6) elif pulse.lower() == 'rc': b = rc_imp(Ns,alpha,6) elif pulse.lower() == 'rect': b = np.ones(int(Ns)) #alt. rect. pulse shape else: raise ValueError('pulse shape must be src, rc, or rect') if mod_type.lower() == 'qpsk': M = 2 # bits per symbol elif mod_type.lower() == '16qam': M = 4 elif mod_type.lower() == '64qam': M = 8 elif mod_type.lower() == '256qam': M = 16 else: raise ValueError('Unknown mod_type') # Create random symbols for the I & Q channels xI = np.random.randint(0,M,N_symb) xI = 2*xI - (M-1) xQ = np.random.randint(0,M,N_symb) xQ = 2*xQ - (M-1) # Employ differential encoding to counter phase ambiquities # Create a zero padded (interpolated by Ns) symbol sequence. # This prepares the symbol sequence for arbitrary pulse shaping. symbI = np.hstack((xI.reshape(N_symb,1),np.zeros((N_symb,int(Ns)-1)))) symbI = symbI.flatten() symbQ = np.hstack((xQ.reshape(N_symb,1),np.zeros((N_symb,int(Ns)-1)))) symbQ = symbQ.flatten() symb = symbI + 1j*symbQ if M > 2: symb /= (M-1) # The impulse train waveform contains one pulse per Ns (or Ts) samples # imp_train = [ones(K,1) zeros(K,Ns-1)]'; # imp_train = reshape(imp_train,Ns*K,1); # Filter the impulse train signal x = signal.lfilter(b,1,symb) x = x.flatten() # out is a 1D vector # Scale shaping filter to have unity DC gain b = b/sum(b) return x, b, xI+1j*xQ def QAM_SEP(tx_data,rx_data,mod_type,Ncorr = 1024,Ntransient = 0,SEP_disp=True): """ Nsymb, Nerr, SEP_hat = QAM_symb_errors(tx_data,rx_data,mod_type,Ncorr = 1024,Ntransient = 0) Count symbol errors between a transmitted and received QAM signal. The received symbols are assumed to be soft values on a unit square. Time delay between streams is detected. The ndarray tx_data is Tx complex symbols. The ndarray rx_data is Rx complex symbols. Note: Ncorr needs to be even """ #Remove Ntransient symbols and makes lengths equal tx_data = tx_data[Ntransient:] rx_data = rx_data[Ntransient:] Nmin = min([len(tx_data),len(rx_data)]) tx_data = tx_data[:Nmin] rx_data = rx_data[:Nmin] # Perform level translation and quantize the soft symbol values if mod_type.lower() == 'qpsk': M = 2 # bits per symbol elif mod_type.lower() == '16qam': M = 4 elif mod_type.lower() == '64qam': M = 8 elif mod_type.lower() == '256qam': M = 16 else: raise ValueError('Unknown mod_type') rx_data = np.rint((M-1)*(rx_data + (1+1j))/2.) # Fix-up edge points real part s1r = np.nonzero(np.ravel(rx_data.real > M - 1))[0] s2r = np.nonzero(np.ravel(rx_data.real < 0))[0] rx_data.real[s1r] = (M - 1)*np.ones(len(s1r)) rx_data.real[s2r] = np.zeros(len(s2r)) # Fix-up edge points imag part s1i = np.nonzero(np.ravel(rx_data.imag > M - 1))[0] s2i = np.nonzero(np.ravel(rx_data.imag < 0))[0] rx_data.imag[s1i] = (M - 1)*np.ones(len(s1i)) rx_data.imag[s2i] = np.zeros(len(s2i)) rx_data = 2*rx_data - (M - 1)*(1 + 1j) #Correlate the first Ncorr symbols at four possible phase rotations R0,lags = xcorr(rx_data,tx_data,Ncorr) R1,lags = xcorr(rx_data*(1j)**1,tx_data,Ncorr) R2,lags = xcorr(rx_data*(1j)**2,tx_data,Ncorr) R3,lags = xcorr(rx_data*(1j)**3,tx_data,Ncorr) #Place the zero lag value in the center of the array R0max = np.max(R0.real) R1max = np.max(R1.real) R2max = np.max(R2.real) R3max = np.max(R3.real) R = np.array([R0max,R1max,R2max,R3max]) Rmax = np.max(R) kphase_max = np.where(R == Rmax)[0] kmax = kphase_max[0] #Find correlation lag value is zero at the center of the array if kmax == 0: lagmax = lags[np.where(R0.real == Rmax)[0]] elif kmax == 1: lagmax = lags[np.where(R1.real == Rmax)[0]] elif kmax == 2: lagmax = lags[np.where(R2.real == Rmax)[0]] elif kmax == 3: lagmax = lags[np.where(R3.real == Rmax)[0]] taumax = lagmax[0] if SEP_disp: print('Phase ambiquity = (1j)**%d, taumax = %d' % (kmax, taumax)) #Count symbol errors over the entire input ndarrays #Begin by making tx and rx length equal and apply #phase rotation to rx_data if taumax < 0: tx_data = tx_data[-taumax:] tx_data = tx_data[:min(len(tx_data),len(rx_data))] rx_data = (1j)**kmax*rx_data[:len(tx_data)] else: rx_data = (1j)**kmax*rx_data[taumax:] rx_data = rx_data[:min(len(tx_data),len(rx_data))] tx_data = tx_data[:len(rx_data)] #Convert QAM symbol difference to symbol errors errors = np.int16(abs(rx_data-tx_data)) # Detect symbols errors # Could decode bit errors from symbol index difference idx = np.nonzero(np.ravel(errors != 0))[0] if SEP_disp: print('Symbols = %d, Errors %d, SEP = %1.2e' \ % (len(errors), len(idx), len(idx)/float(len(errors)))) return len(errors), len(idx), len(idx)/float(len(errors)) def GMSK_bb(N_bits, Ns, MSK = 0,BT = 0.35): """ MSK/GMSK Complex Baseband Modulation x,data = gmsk(N_bits, Ns, BT = 0.35, MSK = 0) Parameters ---------- N_bits : number of symbols processed Ns : the number of samples per bit MSK : 0 for no shaping which is standard MSK, MSK <> 0 --> GMSK is generated. BT : premodulation Bb*T product which sets the bandwidth of the Gaussian lowpass filter Mark Wickert Python version November 2014 """ x, b, data = NRZ_bits(N_bits,Ns) # pulse length 2*M*Ns M = 4 n = np.arange(-M*Ns,M*Ns+1) p = np.exp(-2*np.pi**2*BT**2/np.log(2)*(n/float(Ns))**2); p = p/np.sum(p); # Gaussian pulse shape if MSK not zero if MSK != 0: x = signal.lfilter(p,1,x) y = np.exp(1j*np.pi/2*np.cumsum(x)/Ns) return y, data def MPSK_bb(N_symb,Ns,M,pulse='rect',alpha = 0.25,MM=6): """ Generate a complex baseband MPSK signal with pulse shaping. Parameters ---------- N_symb : number of MPSK symbols to produce Ns : the number of samples per bit, M : MPSK modulation order, e.g., 4, 8, 16, ... pulse_type : 'rect' , 'rc', 'src' (default 'rect') alpha : excess bandwidth factor(default 0.25) MM : single sided pulse duration (default = 6) Returns ------- x : ndarray of the MPSK signal values b : ndarray of the pulse shape data : ndarray of the underlying data bits Notes ----- Pulse shapes include 'rect' (rectangular), 'rc' (raised cosine), 'src' (root raised cosine). The actual pulse length is 2*M+1 samples. This function is used by BPSK_tx in the Case Study article. Examples -------- >>> from sk_dsp_comm import digitalcom as dc >>> import scipy.signal as signal >>> import matplotlib.pyplot as plt >>> x,b,data = dc.MPSK_bb(500,10,8,'src',0.35) >>> # Matched filter received signal x >>> y = signal.lfilter(b,1,x) >>> plt.plot(y.real[12*10:],y.imag[12*10:]) >>> plt.xlabel('In-Phase') >>> plt.ylabel('Quadrature') >>> plt.axis('equal') >>> # Sample once per symbol >>> plt.plot(y.real[12*10::10],y.imag[12*10::10],'r.') >>> plt.show() """ data = np.random.randint(0,M,N_symb) xs = np.exp(1j*2*np.pi/M*data) x = np.hstack((xs.reshape(N_symb,1),np.zeros((N_symb,int(Ns)-1)))) x =x.flatten() if pulse.lower() == 'rect': b = np.ones(int(Ns)) elif pulse.lower() == 'rc': b = rc_imp(Ns,alpha,MM) elif pulse.lower() == 'src': b = sqrt_rc_imp(Ns,alpha,MM) else: raise ValueError('pulse type must be rec, rc, or src') x = signal.lfilter(b,1,x) if M == 4: x = x*np.exp(1j*np.pi/4); # For QPSK points in quadrants return x,b/float(Ns),data def QPSK_rx(fc,N_symb,Rs,EsN0=100,fs=125,lfsr_len=10,phase=0,pulse='src'): """ This function generates """ Ns = int(np.round(fs/Rs)) print('Ns = ', Ns) print('Rs = ', fs/float(Ns)) print('EsN0 = ', EsN0, 'dB') print('phase = ', phase, 'degrees') print('pulse = ', pulse) x, b, data = QPSK_bb(N_symb,Ns,lfsr_len,pulse) # Add AWGN to x x = cpx_AWGN(x,EsN0,Ns) n = np.arange(len(x)) xc = x*np.exp(1j*2*np.pi*fc/float(fs)*n) * np.exp(1j*phase) return xc, b, data def QPSK_tx(fc,N_symb,Rs,fs=125,lfsr_len=10,pulse='src'): """ """ Ns = int(np.round(fs/Rs)) print('Ns = ', Ns) print('Rs = ', fs/float(Ns)) print('pulse = ', pulse) x, b, data = QPSK_bb(N_symb,Ns,lfsr_len,pulse) n = np.arange(len(x)) xc = x*np.exp(1j*2*np.pi*fc/float(fs)*n) return xc, b, data def QPSK_bb(N_symb,Ns,lfsr_len=5,pulse='src',alpha=0.25,M=6): """ """ if lfsr_len > 0: # LFSR data data = PN_gen(2*N_symb,lfsr_len) dataI = data[0::2] dataQ = data[1::2] xI, b = NRZ_bits2(dataI,Ns,pulse,alpha,M) xQ, b = NRZ_bits2(dataQ,Ns,pulse,alpha,M) else: # Random data data = np.zeros(2*N_symb) xI, b, data[0::2] = NRZ_bits(N_symb,Ns,pulse,alpha,M) xQ, b, data[1::2] = NRZ_bits(N_symb,Ns,pulse,alpha,M) #print('P_I: ',np.var(xI), 'P_Q: ',np.var(xQ)) x = (xI + 1j*xQ)/np.sqrt(2.) return x, b, data def QPSK_BEP(tx_data,rx_data,Ncorr = 1024,Ntransient = 0): """ Count bit errors between a transmitted and received QPSK signal. Time delay between streams is detected as well as ambiquity resolution due to carrier phase lock offsets of :math:`k*\\frac{\\pi}{4}`, k=0,1,2,3. The ndarray sdata is Tx +/-1 symbols as complex numbers I + j*Q. The ndarray data is Rx +/-1 symbols as complex numbers I + j*Q. Note: Ncorr needs to be even """ #Remove Ntransient symbols tx_data = tx_data[Ntransient:] rx_data = rx_data[Ntransient:] #Correlate the first Ncorr symbols at four possible phase rotations R0 = np.fft.ifft(np.fft.fft(rx_data,Ncorr)* np.conj(np.fft.fft(tx_data,Ncorr))) R1 = np.fft.ifft(np.fft.fft(1j*rx_data,Ncorr)* np.conj(np.fft.fft(tx_data,Ncorr))) R2 = np.fft.ifft(np.fft.fft(-1*rx_data,Ncorr)* np.conj(np.fft.fft(tx_data,Ncorr))) R3 = np.fft.ifft(np.fft.fft(-1j*rx_data,Ncorr)* np.conj(np.fft.fft(tx_data,Ncorr))) #Place the zero lag value in the center of the array R0 = np.fft.fftshift(R0) R1 = np.fft.fftshift(R1) R2 = np.fft.fftshift(R2) R3 = np.fft.fftshift(R3) R0max = np.max(R0.real) R1max = np.max(R1.real) R2max = np.max(R2.real) R3max = np.max(R3.real) R = np.array([R0max,R1max,R2max,R3max]) Rmax = np.max(R) kphase_max = np.where(R == Rmax)[0] kmax = kphase_max[0] #Correlation lag value is zero at the center of the array if kmax == 0: lagmax = np.where(R0.real == Rmax)[0] - Ncorr/2 elif kmax == 1: lagmax = np.where(R1.real == Rmax)[0] - Ncorr/2 elif kmax == 2: lagmax = np.where(R2.real == Rmax)[0] - Ncorr/2 elif kmax == 3: lagmax = np.where(R3.real == Rmax)[0] - Ncorr/2 taumax = lagmax[0] print('kmax = %d, taumax = %d' % (kmax, taumax)) # Count bit and symbol errors over the entire input ndarrays # Begin by making tx and rx length equal and apply phase rotation to rx if taumax < 0: tx_data = tx_data[-taumax:] tx_data = tx_data[:min(len(tx_data),len(rx_data))] rx_data = 1j**kmax*rx_data[:len(tx_data)] else: rx_data = 1j**kmax*rx_data[taumax:] rx_data = rx_data[:min(len(tx_data),len(rx_data))] tx_data = tx_data[:len(rx_data)] #Convert to 0's and 1's S_count = len(tx_data) tx_I = np.int16((tx_data.real + 1)/2) tx_Q = np.int16((tx_data.imag + 1)/2) rx_I = np.int16((rx_data.real + 1)/2) rx_Q = np.int16((rx_data.imag + 1)/2) I_errors = tx_I ^ rx_I Q_errors = tx_Q ^ rx_Q #A symbol errors occurs when I or Q or both are in error S_errors = I_errors | Q_errors #return 0 return S_count,np.sum(I_errors),np.sum(Q_errors),np.sum(S_errors) def BPSK_BEP(tx_data,rx_data,Ncorr = 1024,Ntransient = 0): """ Count bit errors between a transmitted and received BPSK signal. Time delay between streams is detected as well as ambiquity resolution due to carrier phase lock offsets of :math:`k*\\pi`, k=0,1. The ndarray tx_data is Tx +/-1 symbols as real numbers I. The ndarray rx_data is Rx +/-1 symbols as real numbers I. Note: Ncorr needs to be even """ #Remove Ntransient symbols tx_data = tx_data[Ntransient:] rx_data = rx_data[Ntransient:] #Correlate the first Ncorr symbols at four possible phase rotations R0 = np.fft.ifft(np.fft.fft(rx_data,Ncorr)* np.conj(np.fft.fft(tx_data,Ncorr))) R1 = np.fft.ifft(np.fft.fft(-1*rx_data,Ncorr)* np.conj(np.fft.fft(tx_data,Ncorr))) #Place the zero lag value in the center of the array R0 = np.fft.fftshift(R0) R1 = np.fft.fftshift(R1) R0max = np.max(R0.real) R1max = np.max(R1.real) R = np.array([R0max,R1max]) Rmax = np.max(R) kphase_max = np.where(R == Rmax)[0] kmax = kphase_max[0] #Correlation lag value is zero at the center of the array if kmax == 0: lagmax = np.where(R0.real == Rmax)[0] - Ncorr/2 elif kmax == 1: lagmax = np.where(R1.real == Rmax)[0] - Ncorr/2 taumax = int(lagmax[0]) print('kmax = %d, taumax = %d' % (kmax, taumax)) #return R0,R1,R2,R3 #Count bit and symbol errors over the entire input ndarrays #Begin by making tx and rx length equal and apply phase rotation to rx if taumax < 0: tx_data = tx_data[-taumax:] tx_data = tx_data[:min(len(tx_data),len(rx_data))] rx_data = (-1)**kmax*rx_data[:len(tx_data)] else: rx_data = (-1)**kmax*rx_data[taumax:] rx_data = rx_data[:min(len(tx_data),len(rx_data))] tx_data = tx_data[:len(rx_data)] #Convert to 0's and 1's S_count = len(tx_data) tx_I = np.int16((tx_data.real + 1)/2) rx_I = np.int16((rx_data.real + 1)/2) I_errors = tx_I ^ rx_I #Symbol errors and bit errors are equivalent S_errors = I_errors #return tx_data, rx_data return S_count,np.sum(S_errors) def BPSK_tx(N_bits,Ns,ach_fc=2.0,ach_lvl_dB=-100,pulse='rect',alpha = 0.25,M=6): """ Generates biphase shift keyed (BPSK) transmitter with adjacent channel interference. Generates three BPSK signals with rectangular or square root raised cosine (SRC) pulse shaping of duration N_bits and Ns samples per bit. The desired signal is centered on f = 0, which the adjacent channel signals to the left and right are also generated at dB level relative to the desired signal. Used in the digital communications Case Study supplement. Parameters ---------- N_bits : the number of bits to simulate Ns : the number of samples per bit ach_fc : the frequency offset of the adjacent channel signals (default 2.0) ach_lvl_dB : the level of the adjacent channel signals in dB (default -100) pulse : the pulse shape 'rect' or 'src' alpha : square root raised cosine pulse shape factor (default = 0.25) M : square root raised cosine pulse truncation factor (default = 6) Returns ------- x : ndarray of the composite signal x0 + ach_lvl*(x1p + x1m) b : the transmit pulse shape data0 : the data bits used to form the desired signal; used for error checking Notes ----- Examples -------- >>> x,b,data0 = BPSK_tx(1000,10,'src') """ x0,b,data0 = NRZ_bits(N_bits,Ns,pulse,alpha,M) x1p,b,data1p = NRZ_bits(N_bits,Ns,pulse,alpha,M) x1m,b,data1m = NRZ_bits(N_bits,Ns,pulse,alpha,M) n = np.arange(len(x0)) x1p = x1p*np.exp(1j*2*np.pi*ach_fc/float(Ns)*n) x1m = x1m*np.exp(-1j*2*np.pi*ach_fc/float(Ns)*n) ach_lvl = 10**(ach_lvl_dB/20.) return x0 + ach_lvl*(x1p + x1m), b, data0 def rc_imp(Ns,alpha,M=6): """ A truncated raised cosine pulse used in digital communications. The pulse shaping factor :math:`0 < \\alpha < 1` is required as well as the truncation factor M which sets the pulse duration to be :math:`2*M*T_{symbol}`. Parameters ---------- Ns : number of samples per symbol alpha : excess bandwidth factor on (0, 1), e.g., 0.35 M : equals RC one-sided symbol truncation factor Returns ------- b : ndarray containing the pulse shape See Also -------- sqrt_rc_imp Notes ----- The pulse shape b is typically used as the FIR filter coefficients when forming a pulse shaped digital communications waveform. Examples -------- Ten samples per symbol and :math:`\\alpha = 0.35`. >>> import matplotlib.pyplot as plt >>> from sk_dsp_comm.digitalcom import rc_imp >>> from numpy import arange >>> b = rc_imp(10,0.35) >>> n = arange(-10*6,10*6+1) >>> plt.stem(n,b) >>> plt.show() """ # Design the filter n = np.arange(-M*Ns,M*Ns+1) b = np.zeros(len(n)) a = alpha Ns *= 1.0 for i in range(len(n)): if (1 - 4*(a*n[i]/Ns)**2) == 0: b[i] = np.pi/4*np.sinc(1/(2.*a)) else: b[i] = np.sinc(n[i]/Ns)*np.cos(np.pi*a*n[i]/Ns)/(1 - 4*(a*n[i]/Ns)**2) return b def sqrt_rc_imp(Ns,alpha,M=6): """ A truncated square root raised cosine pulse used in digital communications. The pulse shaping factor :math:`0 < \\alpha < 1` is required as well as the truncation factor M which sets the pulse duration to be :math:`2*M*T_{symbol}`. Parameters ---------- Ns : number of samples per symbol alpha : excess bandwidth factor on (0, 1), e.g., 0.35 M : equals RC one-sided symbol truncation factor Returns ------- b : ndarray containing the pulse shape Notes ----- The pulse shape b is typically used as the FIR filter coefficients when forming a pulse shaped digital communications waveform. When square root raised cosine (SRC) pulse is used to generate Tx signals and at the receiver used as a matched filter (receiver FIR filter), the received signal is now raised cosine shaped, thus having zero intersymbol interference and the optimum removal of additive white noise if present at the receiver input. Examples -------- Ten samples per symbol and :math:`\\alpha = 0.35`. >>> import matplotlib.pyplot as plt >>> from numpy import arange >>> from sk_dsp_comm.digitalcom import sqrt_rc_imp >>> b = sqrt_rc_imp(10,0.35) >>> n = arange(-10*6,10*6+1) >>> plt.stem(n,b) >>> plt.show() """ # Design the filter n = np.arange(-M*Ns,M*Ns+1) b = np.zeros(len(n)) Ns *= 1.0 a = alpha for i in range(len(n)): if abs(1 - 16*a**2*(n[i]/Ns)**2) <= np.finfo(np.float).eps/2: b[i] = 1/2.*((1+a)*np.sin((1+a)*np.pi/(4.*a))-(1-a)*np.cos((1-a)*np.pi/(4.*a))+(4*a)/np.pi*np.sin((1-a)*np.pi/(4.*a))) else: b[i] = 4*a/(np.pi*(1 - 16*a**2*(n[i]/Ns)**2)) b[i] = b[i]*(np.cos((1+a)*np.pi*n[i]/Ns) + np.sinc((1-a)*n[i]/Ns)*(1-a)*np.pi/(4.*a)) return b def RZ_bits(N_bits,Ns,pulse='rect',alpha = 0.25,M=6): """ Generate return-to-zero (RZ) data bits with pulse shaping. A baseband digital data signal using +/-1 amplitude signal values and including pulse shaping. Parameters ---------- N_bits : number of RZ {0,1} data bits to produce Ns : the number of samples per bit, pulse_type : 'rect' , 'rc', 'src' (default 'rect') alpha : excess bandwidth factor(default 0.25) M : single sided pulse duration (default = 6) Returns ------- x : ndarray of the RZ signal values b : ndarray of the pulse shape data : ndarray of the underlying data bits Notes ----- Pulse shapes include 'rect' (rectangular), 'rc' (raised cosine), 'src' (root raised cosine). The actual pulse length is 2*M+1 samples. This function is used by BPSK_tx in the Case Study article. Examples -------- >>> import matplotlib.pyplot as plt >>> from numpy import arange >>> from sk_dsp_comm.digitalcom import RZ_bits >>> x,b,data = RZ_bits(100,10) >>> t = arange(len(x)) >>> plt.plot(t,x) >>> plt.ylim([-0.01, 1.01]) >>> plt.show() """ data = np.random.randint(0,2,N_bits) x = np.hstack((data.reshape(N_bits,1),np.zeros((N_bits,int(Ns)-1)))) x =x.flatten() if pulse.lower() == 'rect': b = np.ones(int(Ns)) elif pulse.lower() == 'rc': b = rc_imp(Ns,alpha,M) elif pulse.lower() == 'src': b = sqrt_rc_imp(Ns,alpha,M) else: print('pulse type must be rec, rc, or src') x = signal.lfilter(b,1,x) return x,b/float(Ns),data def my_psd(x,NFFT=2**10,Fs=1): """ A local version of NumPy's PSD function that returns the plot arrays. A mlab.psd wrapper function that returns two ndarrays; makes no attempt to auto plot anything. Parameters ---------- x : ndarray input signal NFFT : a power of two, e.g., 2**10 = 1024 Fs : the sampling rate in Hz Returns ------- Px : ndarray of the power spectrum estimate f : ndarray of frequency values Notes ----- This function makes it easier to overlay spectrum plots because you have better control over the axis scaling than when using psd() in the autoscale mode. Examples -------- >>> import matplotlib.pyplot as plt >>> from sk_dsp_comm import digitalcom as dc >>> from numpy import log10 >>> x,b, data = dc.NRZ_bits(10000,10) >>> Px,f = dc.my_psd(x,2**10,10) >>> plt.plot(f, 10*log10(Px)) >>> plt.show() """ Px,f = pylab.mlab.psd(x,NFFT,Fs) return Px.flatten(), f def time_delay(x,D,N=4): """ A time varying time delay which takes advantage of the Farrow structure for cubic interpolation: y = time_delay(x,D,N = 3) Note that D is an array of the same length as the input signal x. This allows you to make the delay a function of time. If you want a constant delay just use D*zeros(len(x)). The minimum delay allowable is one sample or D = 1.0. This is due to the causal system nature of the Farrow structure. A founding paper on the subject of interpolators is: C. W. Farrow, "A Continuously variable Digital Delay Element," Proceedings of the IEEE Intern. Symp. on Circuits Syst., pp. 2641-2645, June 1988. Mark Wickert, February 2014 """ if type(D) == float or type(D) == int: #Make sure D stays with in the tapped delay line bounds if int(np.fix(D)) < 1: print('D has integer part less than one') exit(1) if int(np.fix(D)) > N-2: print('D has integer part greater than N - 2') exit(1) # Filter 4-tap input with four Farrow FIR filters # Since the time delay is a constant, the LTI filter # function from scipy.signal is convenient. D_frac = D - np.fix(D) Nd = int(np.fix(D)) b = np.zeros(Nd + 4) # Load Lagrange coefficients into the last four FIR taps b[Nd] = -(D_frac-1)*(D_frac-2)*(D_frac-3)/6. b[Nd + 1] = D_frac*(D_frac-2)*(D_frac-3)/2. b[Nd + 2] = -D_frac*(D_frac-1)*(D_frac-3)/2. b[Nd + 3] = D_frac*(D_frac-1)*(D_frac-2)/6. # Do all of the filtering in one step for this special case # of a fixed delay. y = signal.lfilter(b,[1],x) else: # Make sure D stays with in the tapped delay line bounds if np.fix(np.min(D)) < 1: print('D has integer part less than one') exit(1) if np.fix(np.max(D)) > N-2: print('D has integer part greater than N - 2') exit(1) y = np.zeros(len(x)) X = np.zeros(N+1) # Farrow filter tap weights W3 = np.array([[1./6, -1./2, 1./2, -1./6]]) W2 = np.array([[0, 1./2, -1., 1./2]]) W1 = np.array([[-1./6, 1., -1./2, -1./3]]) W0 = np.array([[0, 0, 1., 0]]) for k in range(len(x)): Nd = int(np.fix(D[k])) mu = 1 - (D[k]-np.fix(D[k])) # Form a row vector of signal samples, present and past values X = np.hstack((np.array(x[k]), X[:-1])) # Filter 4-tap input with four Farrow FIR filters # Here numpy dot(A,B) performs the matrix multiply # since the filter has time-varying coefficients v3 = np.dot(W3,np.array(X[Nd-1:Nd+3]).T) v2 = np.dot(W2,np.array(X[Nd-1:Nd+3]).T) v1 = np.dot(W1,np.array(X[Nd-1:Nd+3]).T) v0 = np.dot(W0,np.array(X[Nd-1:Nd+3]).T) #Combine sub-filter outputs using mu = 1 - d y[k] = ((v3[0]*mu + v2[0])*mu + v1[0])*mu + v0[0] return y def xcorr(x1,x2,Nlags): """ r12, k = xcorr(x1,x2,Nlags), r12 and k are ndarray's Compute the energy normalized cross correlation between the sequences x1 and x2. If x1 = x2 the cross correlation is the autocorrelation. The number of lags sets how many lags to return centered about zero """ K = 2*(int(np.floor(len(x1)/2))) X1 = fft.fft(x1[:K]) X2 = fft.fft(x2[:K]) E1 = sum(abs(x1[:K])**2) E2 = sum(abs(x2[:K])**2) r12 = np.fft.ifft(X1*np.conj(X2))/np.sqrt(E1*E2) k = np.arange(K) - int(np.floor(K/2)) r12 = np.fft.fftshift(r12) idx = np.nonzero(np.ravel(abs(k) <= Nlags)) return r12[idx], k[idx] def Q_fctn(x): """ Gaussian Q-function """ return 1./2*erfc(x/np.sqrt(2.)) def PCM_encode(x,N_bits): """ x_bits = PCM_encode(x,N_bits) ///////////////////////////////////////////////////////////// x = signal samples to be PCM encoded N_bits = bit precision of PCM samples x_bits = encoded serial bit stream of 0/1 values. MSB first. ///////////////////////////////////////////////////////////// Mark Wickert, Mark 2015 """ xq = np.int16(np.rint(x*2**(N_bits-1))) x_bits = np.zeros((N_bits,len(xq))) for k, xk in enumerate(xq): x_bits[:,k] = tobin(xk,N_bits) # Reshape into a serial bit stream x_bits = np.reshape(x_bits,(1,len(x)*N_bits),'F') return np.int16(x_bits.flatten()) # A helper function for PCM_encode def tobin(data, width): """ """ data_str = bin(data & (2**width-1))[2:].zfill(width) return [int(x) for x in tuple(data_str)] def PCM_decode(x_bits,N_bits): """ xhat = PCM_decode(x_bits,N_bits) ///////////////////////////////////////////////////////////// x_bits = serial bit stream of 0/1 values. The length of x_bits must be a multiple of N_bits N_bits = bit precision of PCM samples xhat = decoded PCM signal samples ///////////////////////////////////////////////////////////// Mark Wickert, March 2015 """ N_samples = len(x_bits)//N_bits # Convert serial bit stream into parallel words with each # column holdingthe N_bits binary sample value xrs_bits = x_bits.copy() xrs_bits = np.reshape(xrs_bits,(N_bits,N_samples),'F') # Convert N_bits binary words into signed integer values xq = np.zeros(N_samples) w = 2**np.arange(N_bits-1,-1,-1) # binary weights for bin # to dec conversion for k in range(N_samples): xq[k] = np.dot(xrs_bits[:,k],w) - xrs_bits[0,k]*2**N_bits return xq/2**(N_bits-1) def AWGN_chan(x_bits,EBN0_dB): """ Parameters ---------- x_bits : serial bit stream of 0/1 values. EBNO_dB : Energy per bit to noise power density ratio in dB of the serial bit stream sent through the AWGN channel. Frequently we equate EBN0 to SNR in link budget calculations Returns ------- y_bits : Received serial bit stream following hard decisions. This bit will have bit errors. To check the estimated bit error probability use :func:`BPSK_BEP` or simply >> Pe_est = sum(xor(x_bits,y_bits))/length(x_bits); Mark Wickert, March 2015 """ x_bits = 2*x_bits - 1 # convert from 0/1 to -1/1 signal values var_noise = 10**(-EBN0_dB/10)/2; y_bits = x_bits + np.sqrt(var_noise)*np.random.randn(np.size(x_bits)) # Make hard decisions y_bits = np.sign(y_bits) # -1/+1 signal values y_bits = (y_bits+1)/2 # convert back to 0/1 binary values return y_bits def mux_pilot_blocks(IQ_data, Np): """ Parameters ---------- IQ_data : a 2D array of input QAM symbols with the columns representing the NF carrier frequencies and each row the QAM symbols used to form an OFDM symbol Np : the period of the pilot blocks; e.g., a pilot block is inserted every Np OFDM symbols (Np-1 OFDM data symbols of width Nf are inserted in between the pilot blocks. Returns ------- IQ_datap : IQ_data with pilot blocks inserted See Also -------- OFDM_tx Notes ----- A helper function called by :func:`OFDM_tx` that inserts pilot block for use in channel estimation when a delay spread channel is present. """ N_OFDM = IQ_data.shape[0] Npb = N_OFDM // (Np - 1) N_OFDM_rem = N_OFDM - Npb * (Np - 1) Nf = IQ_data.shape[1] IQ_datap = np.zeros((N_OFDM + Npb + 1, Nf), dtype=np.complex128) pilots = np.ones(Nf) # The pilot symbol is simply 1 + j0 for k in range(Npb): IQ_datap[Np * k:Np * (k + 1), :] = np.vstack((pilots, IQ_data[(Np - 1) * k:(Np - 1) * (k + 1), :])) IQ_datap[Np * Npb:Np * (Npb + N_OFDM_rem), :] = np.vstack((pilots, IQ_data[(Np - 1) * Npb:, :])) return IQ_datap def OFDM_tx(IQ_data, Nf, N, Np=0, cp=False, Ncp=0): """ Parameters ---------- IQ_data : +/-1, +/-3, etc complex QAM symbol sample inputs Nf : number of filled carriers, must be even and Nf < N N : total number of carriers; generally a power 2, e.g., 64, 1024, etc Np : Period of pilot code blocks; 0 <=> no pilots cp : False/True <=> bypass cp insertion entirely if False Ncp : the length of the cyclic prefix Returns ------- x_out : complex baseband OFDM waveform output after P/S and CP insertion See Also -------- OFDM_rx Examples -------- >>> import matplotlib.pyplot as plt >>> from sk_dsp_comm import digitalcom as dc >>> x1,b1,IQ_data1 = dc.QAM_bb(50000,1,'16qam') >>> x_out = dc.OFDM_tx(IQ_data1,32,64) >>> plt.psd(x_out,2**10,1); >>> plt.xlabel(r'Normalized Frequency ($\omega/(2\pi)=f/f_s$)') >>> plt.ylim([-40,0]) >>> plt.xlim([-.5,.5]) >>> plt.show() """ N_symb = len(IQ_data) N_OFDM = N_symb // Nf IQ_data = IQ_data[:N_OFDM * Nf] IQ_s2p = np.reshape(IQ_data, (N_OFDM, Nf)) # carrier symbols by column print(IQ_s2p.shape) if Np > 0: IQ_s2p = mux_pilot_blocks(IQ_s2p, Np) N_OFDM = IQ_s2p.shape[0] print(IQ_s2p.shape) if cp: x_out = np.zeros(N_OFDM * (N + Ncp), dtype=np.complex128) else: x_out = np.zeros(N_OFDM * N, dtype=np.complex128) for k in range(N_OFDM): buff = np.zeros(N, dtype=np.complex128) for n in range(-Nf // 2, Nf // 2 + 1): if n == 0: # Modulate carrier f = 0 buff[0] = 0 # This can be a pilot carrier elif n > 0: # Modulate carriers f = 1:Nf/2 buff[n] = IQ_s2p[k, n - 1] else: # Modulate carriers f = -Nf/2:-1 buff[N + n] = IQ_s2p[k, Nf + n] if cp: # With cyclic prefix x_out_buff = fft.ifft(buff) x_out[k * (N + Ncp):(k + 1) * (N + Ncp)] = np.concatenate((x_out_buff[N - Ncp:], x_out_buff)) else: # No cyclic prefix included x_out[k * N:(k + 1) * N] = fft.ifft(buff) return x_out def chan_est_equalize(z, Np, alpha, Ht=None): """ This is a helper function for :func:`OFDM_rx` to unpack pilot blocks from from the entire set of received OFDM symbols (the Nf of N filled carriers only); then estimate the channel array H recursively, and finally apply H_hat to Y, i.e., X_hat = Y/H_hat carrier-by-carrier. Note if Np = -1, then H_hat = H, the true channel. Parameters ---------- z : Input N_OFDM x Nf 2D array containing pilot blocks and OFDM data symbols. Np : The pilot block period; if -1 use the known channel impulse response input to ht. alpha : The forgetting factor used to recursively estimate H_hat Ht : The theoretical channel frquency response to allow ideal equalization provided Ncp is adequate. Returns ------- zz_out : The input z with the pilot blocks removed and one-tap equalization applied to each of the Nf carriers. H : The channel estimate in the frequency domain; an array of length Nf; will return Ht if provided as an input. Examples -------- >>> from sk_dsp_comm.digitalcom import chan_est_equalize >>> zz_out,H = chan_est_eq(z,Nf,Np,alpha,Ht=None) """ N_OFDM = z.shape[0] Nf = z.shape[1] Npb = N_OFDM // Np N_part = N_OFDM - Npb * Np - 1 zz_out = np.zeros_like(z) Hmatrix = np.zeros((N_OFDM, Nf), dtype=np.complex128) k_fill = 0 k_pilot = 0 for k in range(N_OFDM): if np.mod(k, Np) == 0: # Process pilot blocks if k == 0: H = z[k, :] else: H = alpha * H + (1 - alpha) * z[k, :] Hmatrix[k_pilot, :] = H k_pilot += 1 else: # process data blocks if isinstance(type(None), type(Ht)): zz_out[k_fill, :] = z[k, :] / H # apply equalizer else: zz_out[k_fill, :] = z[k, :] / Ht # apply ideal equalizer k_fill += 1 zz_out = zz_out[:k_fill, :] # Trim to # of OFDM data symbols Hmatrix = Hmatrix[:k_pilot, :] # Trim to # of OFDM pilot symbols if k_pilot > 0: # Plot a few magnitude and phase channel estimates chan_idx = np.arange(0, Nf // 2, 4) plt.subplot(211) for i in chan_idx: plt.plot(np.abs(Hmatrix[:, i])) plt.title('Channel Estimates H[k] Over Selected Carrier Indices') plt.xlabel('Channel Estimate Update Index') plt.ylabel('|H[k]|') plt.grid(); plt.subplot(212) for i in chan_idx: plt.plot(np.angle(Hmatrix[:, i])) plt.xlabel('Channel Estimate Update Index') plt.ylabel('angle[H[k] (rad)') plt.grid(); plt.tight_layout() return zz_out, H def OFDM_rx(x, Nf, N, Np=0, cp=False, Ncp=0, alpha=0.95, ht=None): """ Parameters ---------- x : Received complex baseband OFDM signal Nf : Number of filled carriers, must be even and Nf < N N : Total number of carriers; generally a power 2, e.g., 64, 1024, etc Np : Period of pilot code blocks; 0 <=> no pilots; -1 <=> use the ht impulse response input to equalize the OFDM symbols; note equalization still requires Ncp > 0 to work on a delay spread channel. cp : False/True <=> if False assume no CP is present Ncp : The length of the cyclic prefix alpha : The filter forgetting factor in the channel estimator. Typically alpha is 0.9 to 0.99. nt : Input the known theoretical channel impulse response Returns ------- z_out : Recovered complex baseband QAM symbols as a serial stream; as appropriate channel estimation has been applied. H : channel estimate (in the frequency domain at each subcarrier) See Also -------- OFDM_tx Examples -------- >>> import matplotlib.pyplot as plt >>> from sk_dsp_comm import digitalcom as dc >>> from scipy import signal >>> from numpy import array >>> hc = array([1.0, 0.1, -0.05, 0.15, 0.2, 0.05]) # impulse response spanning five symbols >>> # Quick example using the above channel with no cyclic prefix >>> x1,b1,IQ_data1 = dc.QAM_bb(50000,1,'16qam') >>> x_out = dc.OFDM_tx(IQ_data1,32,64,0,True,0) >>> c_out = signal.lfilter(hc,1,x_out) # Apply channel distortion >>> r_out = dc.cpx_AWGN(c_out,100,64/32) # Es/N0 = 100 dB >>> z_out,H = dc.OFDM_rx(r_out,32,64,-1,True,0,alpha=0.95,ht=hc) >>> plt.plot(z_out[200:].real,z_out[200:].imag,'.') >>> plt.xlabel('In-Phase') >>> plt.ylabel('Quadrature') >>> plt.axis('equal') >>> plt.grid() >>> plt.show() Another example with noise using a 10 symbol cyclic prefix and channel estimation: >>> x_out = dc.OFDM_tx(IQ_data1,32,64,100,True,10) >>> c_out = signal.lfilter(hc,1,x_out) # Apply channel distortion >>> r_out = dc.cpx_AWGN(c_out,25,64/32) # Es/N0 = 25 dB >>> z_out,H = dc.OFDM_rx(r_out,32,64,100,True,10,alpha=0.95,ht=hc); >>> plt.figure() # if channel estimation is turned on need this >>> plt.plot(z_out[-2000:].real,z_out[-2000:].imag,'.') # allow settling time >>> plt.xlabel('In-Phase') >>> plt.ylabel('Quadrature') >>> plt.axis('equal') >>> plt.grid() >>> plt.show() """ N_symb = len(x) // (N + Ncp) y_out = np.zeros(N_symb * N, dtype=np.complex128) for k in range(N_symb): if cp: # Remove the cyclic prefix buff = x[k * (N + Ncp) + Ncp:(k + 1) * (N + Ncp)] else: buff = x[k * N:(k + 1) * N] y_out[k * N:(k + 1) * N] = fft.fft(buff) # Demultiplex into Nf parallel streams from N total, including # the pilot blocks which contain channel information z_out = np.reshape(y_out, (N_symb, N)) z_out = np.hstack((z_out[:, 1:Nf // 2 + 1], z_out[:, N - Nf // 2:N])) if Np > 0: if isinstance(type(None), type(ht)): z_out, H = chan_est_equalize(z_out, Np, alpha) else: Ht = fft.fft(ht, N) Hht = np.hstack((Ht[1:Nf // 2 + 1], Ht[N - Nf // 2:])) z_out, H = chan_est_equalize(z_out, Np, alpha, Hht) elif Np == -1: # Ideal equalization using hc Ht = fft.fft(ht, N) H = np.hstack((Ht[1:Nf // 2 + 1], Ht[N - Nf // 2:])) for k in range(N_symb): z_out[k, :] /= H else: H = np.ones(Nf) # Multiplex into original serial symbol stream return z_out.flatten(), H
python
def validMountainArray(arr): N = len(arr) i = 0 while i + 1 < N and arr[i] < arr[i+1]: i += 1 if i == 0 or i == N-1: return False while i + 1 < N and arr[i] > arr [i+1]: i += 1 return i == N-1 arr = [2,1] x = validMountainArray(arr) print(x) arr1 = [3,5,5] x = validMountainArray(arr1) print(x) arr2 = [0,3,2,1] x = validMountainArray(arr2) print(x)
python
from django.http import HttpResponse from django.shortcuts import render from rest_framework.generics import ( CreateAPIView, DestroyAPIView, ListAPIView, UpdateAPIView, RetrieveAPIView ) from posts.models import Post from .serializers import ( PostCreateSerializer, PostListSerializer, PostDetailSerializer ) class PostCreateAPIView(CreateAPIView): queryset = Post.objects.all() serializer_class = PostDetailSerializer class PostDetailAPIView(RetrieveAPIView): queryset = Post.objects.all() serializer_class = PostDetailSerializer lookup_field = 'slug' class PostUpdateAPIView(UpdateAPIView): queryset = Post.objects.all() serializer_class = PostDetailSerializer lookup_field = 'slug' class PostDeleteAPIView(DestroyAPIView): queryset = Post.objects.all() serializer_class = PostDetailSerializer lookup_field = 'slug' class PostListAPIView (ListAPIView): queryset = Post.objects.all() serializer_class = PostListSerializer
python
import bayesnewton import objax import numpy as np import matplotlib.pyplot as plt import time # load graviational wave data data = np.loadtxt('../data/ligo.txt') # https://www.gw-openscience.org/events/GW150914/ np.random.seed(12345) x = data[:, 0] y = data[:, 1] x_test = x y_test = y x_plot = x var_f = 1.0 # GP variance len_f = 0.1 # GP lengthscale var_y = 0.01 # observation noise kern = bayesnewton.kernels.Matern12(variance=var_f, lengthscale=len_f) lik = bayesnewton.likelihoods.Gaussian(variance=var_y) # , fix_variance=True) model = bayesnewton.models.MarkovVariationalGP(kernel=kern, likelihood=lik, X=x, Y=y) lr_adam = 0.1 lr_newton = 1 iters = 100 opt_hypers = objax.optimizer.Adam(model.vars()) energy = objax.GradValues(model.energy, model.vars()) inf_args = { "power": 0.5, # the EP power } @objax.Function.with_vars(model.vars() + opt_hypers.vars()) def train_op(): model.inference(lr=lr_newton, **inf_args) # perform inference and update variational params dE, E = energy(**inf_args) # compute energy and its gradients w.r.t. hypers opt_hypers(lr_adam, dE) return E train_op = objax.Jit(train_op) t0 = time.time() for i in range(1, iters + 1): loss = train_op() print('iter %2d, energy: %1.4f' % (i, loss[0])) t1 = time.time() print('optimisation time: %2.2f secs' % (t1-t0)) t0 = time.time() posterior_mean, posterior_var = model.predict_y(X=x_plot) nlpd = model.negative_log_predictive_density(X=x_test, Y=y_test) t1 = time.time() print('prediction time: %2.2f secs' % (t1-t0)) print('nlpd: %2.3f' % nlpd) lb = posterior_mean - 1.96 * posterior_var ** 0.5 ub = posterior_mean + 1.96 * posterior_var ** 0.5 print('plotting ...') plt.figure(1, figsize=(12, 5)) plt.clf() plt.plot(x, y, 'k.', label='training observations') plt.plot(x_test, y_test, 'r.', alpha=0.4, label='test observations') plt.plot(x_plot, posterior_mean, 'b', label='posterior mean') # plt.plot(x_plot, posterior_samples.T, 'b', alpha=0.2) plt.fill_between(x_plot, lb, ub, color='b', alpha=0.05, label='95% confidence') plt.xlim([x_plot[0], x_plot[-1]]) if hasattr(model, 'Z'): plt.plot(model.Z.value[:, 0], -2 * np.ones_like(model.Z.value[:, 0]), 'b^', markersize=5) # plt.xlim([x_test[0], x_test[-1]]) # plt.ylim([-2, 5]) plt.legend() plt.title('GP regression') plt.xlabel('$X$') plt.show()
python
import numpy as np import tinkerbell.app.plot as tbapl import tinkerbell.app.rcparams as tbarc from matplotlib import pyplot as plt fname_img = 'img/time_stage_lstm.png' def xy_from_npy(fname): data = np.load(fname) return (data[0], data[1]) xmax = tbarc.rcparams['shale.lstm_stage.xmax'] y0 = tbarc.rcparams['shale.lstm.y0_mean'] xdisc_train = tbarc.rcparams['shale.lstm_stage.xdisc_mean'] xdisc_pred = xdisc_train + xmax*tbarc.rcparams['shale.lstm_stage.xdisc_mult'] y0_pred = tbarc.rcparams['shale.lstm.y0_mean']*tbarc.rcparams['shale.lstm.y0_mult'] xlim = (-5, xmax*1.025) ylim = (-2, y0*1.1) lims = (xlim, ylim) fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row') training_xy = xy_from_npy(tbarc.rcparams['shale.lstm_stage.fnamentraindata']) tbapl.render(ax1, [training_xy], styles=['p'], lim=lims) ax1.set_title('Training') inputy0_xy = ((0), (y0_pred)) inputxdisc_xy = ((xdisc_pred), (0)) tbapl.render(ax2, [inputy0_xy, inputxdisc_xy], styles=['iy', 'ix'], lim=lims) ax2.set_title('Query') prediction_xy = xy_from_npy(tbarc.rcparams['shale.lstm_stage.fnamenpreddata']) tbapl.render(ax3, [inputy0_xy, inputxdisc_xy, prediction_xy], styles=['iy', 'ix', 'l'], lim=lims) ax3.set_title('Prediction') blind_xy = xy_from_npy(tbarc.rcparams['shale.lstm_stage.fnamenblinddata']) tbapl.render(ax4, [prediction_xy, blind_xy], styles=['l', 'p'], lim=lims) ax4.set_title('Prediction vs. reference') fig.set_size_inches(14, 9) plt.savefig(fname_img, dpi=300) plt.show()
python
# ----------* CHALLENGE 74 *---------- # Enter a list of ten colours. Ask the user for a starting number between 0 and 4 # and an end number between 5 and 9. Display the list for those colours # between the start and end numbers the user input. list_colours = ["red", "blue", "green", "yellow", "orange", "purple", "brown", "cyan", "pink", "burgundy", "olive"] first_index = int(input("Enter a number between 0 and 4: ")) last_index = int(input("Enter a number between 5 and 9: ")) print(list_colours[first_index:last_index+1])
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('contenttypes', '0001_initial'), ] operations = [ migrations.CreateModel( name='Permission', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('codename', models.CharField(max_length=100, verbose_name='codename')), ('object_id', models.PositiveIntegerField()), ('approved', models.BooleanField(default=False, help_text='Designates whether the permission has been approved and treated as active. Unselect this instead of deleting permissions.', verbose_name='approved')), ('date_requested', models.DateTimeField(default=datetime.datetime.now, verbose_name='date requested')), ('date_approved', models.DateTimeField(null=True, verbose_name='date approved', blank=True)), ('content_type', models.ForeignKey(related_name='row_permissions', to='contenttypes.ContentType')), ('creator', models.ForeignKey(related_name='created_permissions', blank=True, to=settings.AUTH_USER_MODEL, null=True)), ('group', models.ForeignKey(blank=True, to='auth.Group', null=True)), ('user', models.ForeignKey(related_name='granted_permissions', blank=True, to=settings.AUTH_USER_MODEL, null=True)), ], options={ 'verbose_name': 'permission', 'verbose_name_plural': 'permissions', 'permissions': (('change_foreign_permissions', 'Can change foreign permissions'), ('delete_foreign_permissions', 'Can delete foreign permissions'), ('approve_permission_requests', 'Can approve permission requests')), }, bases=(models.Model,), ), migrations.AlterUniqueTogether( name='permission', unique_together=set([('codename', 'object_id', 'content_type', 'user', 'group')]), ), ]
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Classical Heisenberg model Monte Carlo simulator """ import json import os import shutil import time import numpy as np from kent_distribution.kent_distribution import kent2 from skdylib.spherical_coordinates import sph_urand, xyz2sph from thermalspin.heisenberg_system import HeisenbergSystem SNAPSHOTS_ARRAY_INITIAL_DIMENSION = int(3e4) class HeisenbergSimulation: """ Handler of the HeisenbergSystem simulation. It run the simulation and collect the results. """ def __init__(self, hsys: HeisenbergSystem, take_states_snapshots=False): """ :param hsys: system to be evolved """ self.system = hsys self.steps_counter = 0 self.snapshots_counter = 0 self.snapshots_array_dimension = SNAPSHOTS_ARRAY_INITIAL_DIMENSION if take_states_snapshots: self.snapshots = np.zeros( shape=(SNAPSHOTS_ARRAY_INITIAL_DIMENSION, self.system.nx, self.system.ny, self.system.nz, 2)) else: self.snapshots = None self.snapshots_t = np.zeros(shape=SNAPSHOTS_ARRAY_INITIAL_DIMENSION) self.snapshots_e = np.zeros(shape=SNAPSHOTS_ARRAY_INITIAL_DIMENSION) self.snapshots_m = np.zeros(shape=(SNAPSHOTS_ARRAY_INITIAL_DIMENSION, 3)) self.snapshots_J = np.zeros(shape=SNAPSHOTS_ARRAY_INITIAL_DIMENSION) self.snapshots_T = np.zeros(shape=SNAPSHOTS_ARRAY_INITIAL_DIMENSION) self.snapshots_Hz = np.zeros(shape=SNAPSHOTS_ARRAY_INITIAL_DIMENSION) self.take_snapshot() def run(self, nsteps): """ Evolve the system for a given number of steps :param nsteps: The number of steps """ self.steps_counter += nsteps for t in range(1, nsteps + 1): self.system.step() def take_snapshot(self): """" Take a snapshot of the system, parameters and results """ # First check if the snapshots array needs reshape if self.snapshots_counter == self.snapshots_array_dimension: if self.snapshots is not None: self.snapshots.resize((self.snapshots_counter + SNAPSHOTS_ARRAY_INITIAL_DIMENSION, self.system.nx, self.system.ny, self.system.nz, 2)) else: self.snapshots = None self.snapshots_t.resize(self.snapshots_counter + SNAPSHOTS_ARRAY_INITIAL_DIMENSION) self.snapshots_e.resize(self.snapshots_counter + SNAPSHOTS_ARRAY_INITIAL_DIMENSION) self.snapshots_m.resize((self.snapshots_counter + SNAPSHOTS_ARRAY_INITIAL_DIMENSION, 3)) self.snapshots_J.resize(self.snapshots_counter + SNAPSHOTS_ARRAY_INITIAL_DIMENSION) self.snapshots_T.resize(self.snapshots_counter + SNAPSHOTS_ARRAY_INITIAL_DIMENSION) self.snapshots_Hz.resize(self.snapshots_counter + SNAPSHOTS_ARRAY_INITIAL_DIMENSION) # Then takes a snapshot if self.snapshots is not None: self.snapshots[self.snapshots_counter, :, :, :, :] = self.system.state.copy() self.snapshots_t[self.snapshots_counter] = self.steps_counter self.snapshots_e[self.snapshots_counter] = self.system.energy self.snapshots_m[self.snapshots_counter, :] = self.system.magnetization self.snapshots_J[self.snapshots_counter] = self.system.J self.snapshots_T[self.snapshots_counter] = self.system.T self.snapshots_Hz[self.snapshots_counter] = self.system.Hz self.snapshots_counter += 1 def run_with_snapshots(self, steps_number, delta_snapshots, verbose=False): """ Evolve the system while taking snapshots :param steps_number: Number of steps to be computed :param delta_snapshots: Distance between snapshots """ if steps_number % delta_snapshots != 0: raise Exception("steps_number must be multiple of delta_snapshots") nsnapshots = int(steps_number / delta_snapshots) for t in range(0, nsnapshots): self.run(delta_snapshots) self.take_snapshot() if verbose: print(f"Step number {self.steps_counter}", end="\r") # Functions for initialization and saving to disk the results of a simulation def init_simulation_aligned(simdir, nx, ny, nz, params, theta_0=None, phi_0=None): """ Generate a lattice of spins aligned toward an axis :param simdir: Directory of the simulation :param nx: Number of x cells :param ny: Number of y cells :param nz: Number of z cells :param params: parameters of the simulation :param phi_0: :param theta_0: """ shutil.rmtree(simdir, ignore_errors=True) state = np.ones(shape=(nx, ny, nz, 2)) state[:, :, :, 0] = state[:, :, :, 0] * theta_0 state[:, :, :, 1] = state[:, :, :, 1] * phi_0 os.makedirs(simdir) params_file = open(simdir + "params.json", "w") json.dump(params, params_file, indent=2) np.save(simdir + "state.npy", state) def init_simulation_tilted(simdir, nx, ny, nz, params): """ Generate a lattice of spins aligned toward tan axis if specified, random if not :param simdir: Directory of the simulation :param nx: Number of x cells :param ny: Number of y cells :param nz: Number of z cells :param params: parameters of the simulation """ shutil.rmtree(simdir, ignore_errors=True) state = np.ones(shape=(nx, ny, nz, 2)) gamma1 = np.array([0, 0, 1], dtype=np.float) gamma2 = np.array([0, 1, 0], dtype=np.float) gamma3 = np.array([1, 0, 0], dtype=np.float) kent = kent2(gamma1, gamma2, gamma3, kappa=20, beta=0) for i, j, k in np.ndindex((nx, ny, nz)): state[i, j, k, :] = xyz2sph(kent.rvs()) os.makedirs(simdir) params_file = open(simdir + "params.json", "w") json.dump(params, params_file, indent=2) np.save(simdir + "state.npy", state) def init_simulation_random(simdir, nx, ny, nz, params): """ Generate a lattice of spins aligned toward tan axis if specified, random if not :param simdir: Directory of the simulation :param nx: Number of x cells :param ny: Number of y cells :param nz: Number of z cells :param params: parameters of the simulation """ shutil.rmtree(simdir, ignore_errors=True) state = np.zeros(shape=(nx, ny, nz, 2)) for i, j, k in np.ndindex(nx, ny, nz): theta_r, phi_r = sph_urand() state[i, j, k, 0] = theta_r state[i, j, k, 1] = phi_r os.makedirs(simdir) params_file = open(simdir + "params.json", "w") json.dump(params, params_file, indent=2) np.save(simdir + "state.npy", state) def run_simulation(simulation_directory, verbose=True): """ Run a simulation and save to disk the results :param simulation_directory: the directory of the simulation :param verbose: print step numbers in real time """ if os.path.isfile(simulation_directory + "params.json"): params_file = open(simulation_directory + "params.json", "r") params = json.load(params_file) else: raise Exception("Missing params.json file") if os.path.isfile(simulation_directory + "state.npy"): state = np.load(simulation_directory + "state.npy") else: raise Exception("Missing state.npy file") param_J = np.array(params["param_J"]) param_Hz = np.array(params["param_Hz"]) param_T = np.array(params["param_T"]) steps_number = params["steps_number"] delta_snapshots = params["delta_snapshots"] save_snapshots = params["save_snapshots"] sys = HeisenbergSystem(state, param_J[0], param_Hz[0], param_T[0]) hsim = HeisenbergSimulation(sys, take_states_snapshots=save_snapshots) for i in range(param_T.shape[0]): T_str = "{0:.3f}".format(param_T[i]) Hz_str = "{0:.3f}".format(param_Hz[i]) print(f"Simulation stage: {i}\n" f"Temperature: {T_str}\n" f"Hz: {Hz_str}\n" f"Steps number: {steps_number}\n" f"Delta snapshots: {delta_snapshots}\n") hsim.system.J = param_J[i] hsim.system.T = param_T[i] hsim.system.Hz = param_Hz[i] start_time = time.time() hsim.run_with_snapshots(steps_number, delta_snapshots, verbose=verbose) end_time = time.time() run_time = end_time - start_time run_time_str = "{0:.2f}".format(run_time) print(f"Stage completed in {run_time_str} seconds\n") print("Saving results ...", end="") start = time.time() # Save the last state np.save(simulation_directory + "state.npy", hsim.system.state) # Collect the results of the simulation new_results = np.zeros(shape=(hsim.snapshots_counter, 4)) new_results[:, 0] = hsim.snapshots_e[:hsim.snapshots_counter] new_results[:, 1:4] = hsim.snapshots_m[:hsim.snapshots_counter] # Collect the snapshots and params new_snapshots_params = np.zeros(shape=(hsim.snapshots_counter, 4)) new_snapshots_params[:, 0] = hsim.snapshots_t[:hsim.snapshots_counter] new_snapshots_params[:, 1] = hsim.snapshots_J[:hsim.snapshots_counter] new_snapshots_params[:, 2] = hsim.snapshots_Hz[:hsim.snapshots_counter] new_snapshots_params[:, 3] = hsim.snapshots_T[:hsim.snapshots_counter] # If old data is found, append the new one if os.path.isfile(simulation_directory + "snapshots_params.npy") and os.path.isfile( simulation_directory + "results.npy"): old_results = np.load(simulation_directory + "results.npy") results = np.concatenate((old_results, new_results[1:])) old_snapshots_params = np.load(simulation_directory + "snapshots_params.npy") last_t = old_snapshots_params[-1, 0] new_snapshots_params[:, 0] += last_t snapshots_params = np.concatenate((old_snapshots_params, new_snapshots_params[1:])) else: snapshots_params = new_snapshots_params results = new_results # Save all np.save(simulation_directory + "snapshots_params.npy", snapshots_params) np.save(simulation_directory + "results.npy", results) if save_snapshots: new_snapshots = hsim.snapshots[:hsim.snapshots_counter] if os.path.isfile(simulation_directory + "snapshots.npy"): old_snapshots = np.load(simulation_directory + "snapshots.npy") snapshots = np.concatenate((old_snapshots, new_snapshots[1:])) else: snapshots = new_snapshots np.save(simulation_directory + "snapshots.npy", snapshots) end = time.time() saving_time = end - start saving_time_str = "{0:.6f}".format(saving_time) print(f"done in {saving_time_str} seconds.")
python
# -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'employees.ui' ## ## Created by: Qt User Interface Compiler version 5.15.1 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! ################################################################################ from PySide2.QtCore import QSize, QLocale, QMetaObject, QCoreApplication, QDate from PySide2.QtGui import Qt, QFont, QIcon from PySide2.QtWidgets import QSizePolicy, QSpacerItem, QLabel, QGridLayout, QPushButton, QComboBox, QDateEdit, QFormLayout, QLineEdit, QTabWidget, QWidget class Ui_Form(object): def setupUi(self, Form): if not Form.objectName(): Form.setObjectName(u"Form") Form.resize(580, 400) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(Form.sizePolicy().hasHeightForWidth()) Form.setSizePolicy(sizePolicy) Form.setMinimumSize(QSize(580, 400)) Form.setMaximumSize(QSize(580, 400)) font = QFont() font.setFamily(u"Comic Sans MS") font.setPointSize(10) Form.setFont(font) icon = QIcon() icon.addFile(u":/newPrefix/images/python.ico", QSize(), QIcon.Normal, QIcon.Off) Form.setWindowIcon(icon) Form.setLocale(QLocale(QLocale.Russian, QLocale.Russia)) self.gridLayout_5 = QGridLayout(Form) self.gridLayout_5.setObjectName(u"gridLayout_5") self.tabWidget = QTabWidget(Form) self.tabWidget.setObjectName(u"tabWidget") sizePolicy.setHeightForWidth(self.tabWidget.sizePolicy().hasHeightForWidth()) self.tabWidget.setSizePolicy(sizePolicy) self.tabWidget.setMinimumSize(QSize(560, 380)) self.tab = QWidget() self.tab.setObjectName(u"tab") self.gridLayout_4 = QGridLayout(self.tab) self.gridLayout_4.setObjectName(u"gridLayout_4") self.label_5 = QLabel(self.tab) self.label_5.setObjectName(u"label_5") font1 = QFont() font1.setFamily(u"Comic Sans MS") font1.setPointSize(12) self.label_5.setFont(font1) self.label_5.setAlignment(Qt.AlignCenter) self.gridLayout_4.addWidget(self.label_5, 0, 0, 1, 2) self.verticalSpacer_2 = QSpacerItem(20, 25, QSizePolicy.Minimum, QSizePolicy.Fixed) self.gridLayout_4.addItem(self.verticalSpacer_2, 1, 1, 1, 1) self.gridLayout_3 = QGridLayout() self.gridLayout_3.setObjectName(u"gridLayout_3") self.horizontalSpacer_2 = QSpacerItem(55, 20, QSizePolicy.Fixed, QSizePolicy.Minimum) self.gridLayout_3.addItem(self.horizontalSpacer_2, 0, 0, 1, 1) self.gridLayout = QGridLayout() self.gridLayout.setObjectName(u"gridLayout") self.label = QLabel(self.tab) self.label.setObjectName(u"label") self.gridLayout.addWidget(self.label, 0, 0, 1, 1) self.lineEdit = QLineEdit(self.tab) self.lineEdit.setObjectName(u"lineEdit") self.lineEdit.setMinimumSize(QSize(150, 30)) self.gridLayout.addWidget(self.lineEdit, 1, 0, 1, 1) self.gridLayout_3.addLayout(self.gridLayout, 0, 1, 1, 1) self.horizontalSpacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout_3.addItem(self.horizontalSpacer, 0, 2, 1, 1) self.gridLayout_2 = QGridLayout() self.gridLayout_2.setObjectName(u"gridLayout_2") self.label_4 = QLabel(self.tab) self.label_4.setObjectName(u"label_4") self.gridLayout_2.addWidget(self.label_4, 0, 0, 1, 1) self.dateEdit = QDateEdit(self.tab) self.dateEdit.setObjectName(u"dateEdit") self.dateEdit.setMinimumSize(QSize(150, 30)) self.dateEdit.setCalendarPopup(True) self.dateEdit.setTimeSpec(Qt.LocalTime) self.dateEdit.setDate(QDate(2020, 10, 1)) self.gridLayout_2.addWidget(self.dateEdit, 1, 0, 1, 1) self.gridLayout_3.addLayout(self.gridLayout_2, 0, 3, 1, 1) self.horizontalSpacer_3 = QSpacerItem(75, 20, QSizePolicy.Fixed, QSizePolicy.Minimum) self.gridLayout_3.addItem(self.horizontalSpacer_3, 0, 4, 1, 1) self.formLayout = QFormLayout() self.formLayout.setObjectName(u"formLayout") self.label_2 = QLabel(self.tab) self.label_2.setObjectName(u"label_2") self.formLayout.setWidget(0, QFormLayout.LabelRole, self.label_2) self.lineEdit_2 = QLineEdit(self.tab) self.lineEdit_2.setObjectName(u"lineEdit_2") self.lineEdit_2.setMinimumSize(QSize(150, 30)) self.formLayout.setWidget(1, QFormLayout.LabelRole, self.lineEdit_2) self.gridLayout_3.addLayout(self.formLayout, 1, 1, 1, 1) self.formLayout_2 = QFormLayout() self.formLayout_2.setObjectName(u"formLayout_2") self.label_3 = QLabel(self.tab) self.label_3.setObjectName(u"label_3") self.formLayout_2.setWidget(0, QFormLayout.LabelRole, self.label_3) self.lineEdit_3 = QLineEdit(self.tab) self.lineEdit_3.setObjectName(u"lineEdit_3") self.lineEdit_3.setMinimumSize(QSize(150, 30)) self.formLayout_2.setWidget(1, QFormLayout.LabelRole, self.lineEdit_3) self.gridLayout_3.addLayout(self.formLayout_2, 2, 1, 1, 1) self.gridLayout_4.addLayout(self.gridLayout_3, 2, 0, 1, 2) self.verticalSpacer = QSpacerItem(15, 25, QSizePolicy.Minimum, QSizePolicy.Fixed) self.gridLayout_4.addItem(self.verticalSpacer, 3, 1, 1, 1) self.horizontalSpacer_4 = QSpacerItem(310, 20, QSizePolicy.Fixed, QSizePolicy.Minimum) self.gridLayout_4.addItem(self.horizontalSpacer_4, 4, 0, 1, 1) self.pushButton = QPushButton(self.tab) self.pushButton.setObjectName(u"pushButton") self.gridLayout_4.addWidget(self.pushButton, 4, 1, 1, 1) self.tabWidget.addTab(self.tab, "") self.tab_2 = QWidget() self.tab_2.setObjectName(u"tab_2") self.gridLayout_9 = QGridLayout(self.tab_2) self.gridLayout_9.setObjectName(u"gridLayout_9") self.gridLayout_6 = QGridLayout() self.gridLayout_6.setObjectName(u"gridLayout_6") self.horizontalSpacer_7 = QSpacerItem(75, 20, QSizePolicy.Fixed, QSizePolicy.Minimum) self.gridLayout_6.addItem(self.horizontalSpacer_7, 0, 4, 1, 1) self.gridLayout_8 = QGridLayout() self.gridLayout_8.setObjectName(u"gridLayout_8") self.label_7 = QLabel(self.tab_2) self.label_7.setObjectName(u"label_7") self.gridLayout_8.addWidget(self.label_7, 0, 0, 1, 1) self.dateEdit_2 = QDateEdit(self.tab_2) self.dateEdit_2.setObjectName(u"dateEdit_2") self.dateEdit_2.setMinimumSize(QSize(150, 30)) self.dateEdit_2.setReadOnly(True) self.dateEdit_2.setCalendarPopup(True) self.dateEdit_2.setTimeSpec(Qt.LocalTime) self.dateEdit_2.setDate(QDate(2020, 10, 1)) self.gridLayout_8.addWidget(self.dateEdit_2, 1, 0, 1, 1) self.gridLayout_6.addLayout(self.gridLayout_8, 0, 3, 1, 1) self.formLayout_4 = QFormLayout() self.formLayout_4.setObjectName(u"formLayout_4") self.label_9 = QLabel(self.tab_2) self.label_9.setObjectName(u"label_9") self.formLayout_4.setWidget(0, QFormLayout.LabelRole, self.label_9) self.lineEdit_6 = QLineEdit(self.tab_2) self.lineEdit_6.setObjectName(u"lineEdit_6") self.lineEdit_6.setMinimumSize(QSize(150, 30)) self.lineEdit_6.setReadOnly(True) self.formLayout_4.setWidget(1, QFormLayout.LabelRole, self.lineEdit_6) self.gridLayout_6.addLayout(self.formLayout_4, 2, 1, 1, 1) self.horizontalSpacer_6 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout_6.addItem(self.horizontalSpacer_6, 0, 2, 1, 1) self.gridLayout_7 = QGridLayout() self.gridLayout_7.setObjectName(u"gridLayout_7") self.label_6 = QLabel(self.tab_2) self.label_6.setObjectName(u"label_6") self.gridLayout_7.addWidget(self.label_6, 0, 0, 1, 1) self.lineEdit_4 = QLineEdit(self.tab_2) self.lineEdit_4.setObjectName(u"lineEdit_4") self.lineEdit_4.setMinimumSize(QSize(150, 30)) self.lineEdit_4.setReadOnly(True) self.gridLayout_7.addWidget(self.lineEdit_4, 1, 0, 1, 1) self.gridLayout_6.addLayout(self.gridLayout_7, 0, 1, 1, 1) self.horizontalSpacer_5 = QSpacerItem(60, 20, QSizePolicy.Fixed, QSizePolicy.Minimum) self.gridLayout_6.addItem(self.horizontalSpacer_5, 0, 0, 1, 1) self.formLayout_3 = QFormLayout() self.formLayout_3.setObjectName(u"formLayout_3") self.label_8 = QLabel(self.tab_2) self.label_8.setObjectName(u"label_8") self.formLayout_3.setWidget(0, QFormLayout.LabelRole, self.label_8) self.lineEdit_5 = QLineEdit(self.tab_2) self.lineEdit_5.setObjectName(u"lineEdit_5") self.lineEdit_5.setMinimumSize(QSize(150, 30)) self.lineEdit_5.setReadOnly(True) self.formLayout_3.setWidget(1, QFormLayout.LabelRole, self.lineEdit_5) self.gridLayout_6.addLayout(self.formLayout_3, 1, 1, 1, 1) self.formLayout_6 = QFormLayout() self.formLayout_6.setObjectName(u"formLayout_6") self.label_12 = QLabel(self.tab_2) self.label_12.setObjectName(u"label_12") self.formLayout_6.setWidget(0, QFormLayout.LabelRole, self.label_12) self.lineEdit_7 = QLineEdit(self.tab_2) self.lineEdit_7.setObjectName(u"lineEdit_7") self.lineEdit_7.setMinimumSize(QSize(150, 30)) self.lineEdit_7.setReadOnly(True) self.formLayout_6.setWidget(1, QFormLayout.LabelRole, self.lineEdit_7) self.gridLayout_6.addLayout(self.formLayout_6, 1, 3, 1, 1) self.gridLayout_9.addLayout(self.gridLayout_6, 4, 0, 1, 2) self.formLayout_5 = QFormLayout() self.formLayout_5.setObjectName(u"formLayout_5") self.label_11 = QLabel(self.tab_2) self.label_11.setObjectName(u"label_11") self.label_11.setFont(font1) self.label_11.setAlignment(Qt.AlignCenter) self.formLayout_5.setWidget(0, QFormLayout.LabelRole, self.label_11) self.comboBox = QComboBox(self.tab_2) self.comboBox.setObjectName(u"comboBox") self.formLayout_5.setWidget(0, QFormLayout.FieldRole, self.comboBox) self.gridLayout_9.addLayout(self.formLayout_5, 0, 0, 1, 2) self.verticalSpacer_4 = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Fixed) self.gridLayout_9.addItem(self.verticalSpacer_4, 5, 1, 1, 1) self.verticalSpacer_3 = QSpacerItem(20, 25, QSizePolicy.Minimum, QSizePolicy.Fixed) self.gridLayout_9.addItem(self.verticalSpacer_3, 1, 0, 1, 1) self.label_10 = QLabel(self.tab_2) self.label_10.setObjectName(u"label_10") self.label_10.setFont(font1) self.label_10.setAlignment(Qt.AlignCenter) self.gridLayout_9.addWidget(self.label_10, 2, 0, 1, 2) self.tabWidget.addTab(self.tab_2, "") self.gridLayout_5.addWidget(self.tabWidget, 0, 0, 1, 1) self.retranslateUi(Form) self.tabWidget.setCurrentIndex(1) QMetaObject.connectSlotsByName(Form) # setupUi def retranslateUi(self, Form): Form.setWindowTitle(QCoreApplication.translate("Form", u"\u0421\u043e\u0442\u0440\u0443\u0434\u043d\u0438\u043a\u0438", None)) self.label_5.setText(QCoreApplication.translate("Form", u"\u0415\u0441\u043b\u0438 \u0443 \u0440\u0430\u0431\u043e\u0442\u043d\u0438\u043a\u0430 \u043d\u0435\u0442 \u043e\u0442\u0447\u0435\u0441\u0442\u0432\u0430, \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e \u043e\u0441\u0442\u0430\u0432\u0438\u0442\u044c \u043f\u043e\u043b\u0435 \u043f\u0443\u0441\u0442\u044b\u043c", None)) self.label.setText(QCoreApplication.translate("Form", u"\u0424\u0430\u043c\u0438\u043b\u0438\u044f", None)) self.lineEdit.setText("") self.label_4.setText(QCoreApplication.translate("Form", u"\u0414\u0430\u0442\u0430 \u043f\u0440\u0438\u0435\u043c\u0430 \u043d\u0430 \u0440\u0430\u0431\u043e\u0442\u0443", None)) self.dateEdit.setDisplayFormat(QCoreApplication.translate("Form", u"d/M/yyyy", None)) self.label_2.setText(QCoreApplication.translate("Form", u"\u0418\u043c\u044f", None)) self.lineEdit_2.setText("") self.label_3.setText(QCoreApplication.translate("Form", u"\u041e\u0442\u0447\u0435\u0441\u0442\u0432\u043e (\u0435\u0441\u043b\u0438 \u0438\u043c\u0435\u0435\u0442\u0441\u044f)", None)) self.lineEdit_3.setText("") self.pushButton.setText(QCoreApplication.translate("Form", u"\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c", None)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), QCoreApplication.translate("Form", u"\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u0441\u043e\u0442\u0440\u0443\u0434\u043d\u0438\u043a\u0430", None)) self.label_7.setText(QCoreApplication.translate("Form", u"\u0414\u0430\u0442\u0430 \u043f\u0440\u0438\u0435\u043c\u0430 \u043d\u0430 \u0440\u0430\u0431\u043e\u0442\u0443", None)) self.dateEdit_2.setDisplayFormat(QCoreApplication.translate("Form", u"d/M/yyyy", None)) self.label_9.setText(QCoreApplication.translate("Form", u"\u041e\u0442\u0447\u0435\u0441\u0442\u0432\u043e (\u0435\u0441\u043b\u0438 \u0438\u043c\u0435\u0435\u0442\u0441\u044f)", None)) self.lineEdit_6.setText("") self.label_6.setText(QCoreApplication.translate("Form", u"\u0424\u0430\u043c\u0438\u043b\u0438\u044f", None)) self.lineEdit_4.setText("") self.label_8.setText(QCoreApplication.translate("Form", u"\u0418\u043c\u044f", None)) self.lineEdit_5.setText("") self.label_12.setText(QCoreApplication.translate("Form", u"\u0418\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440 \u0432 \u0431\u0430\u0437\u0435", None)) self.lineEdit_7.setText("") self.label_11.setText(QCoreApplication.translate("Form", u"\u0412\u044b\u0431\u0435\u0440\u0438\u0442\u0435 \u0441\u043e\u0442\u0440\u0443\u0434\u043d\u0438\u043a\u0430 \u0438\u0437 \u0441\u043f\u0438\u0441\u043a\u0430:", None)) self.label_10.setText(QCoreApplication.translate("Form", u"\u0415\u0441\u043b\u0438 \u0443 \u0440\u0430\u0431\u043e\u0442\u043d\u0438\u043a\u0430 \u043d\u0435\u0442 \u043e\u0442\u0447\u0435\u0441\u0442\u0432\u0430, \u0432 \u043f\u043e\u043b\u0435 \u0431\u0443\u0434\u0435\u0442 \u0441\u0438\u043c\u0432\u043e\u043b -", None)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), QCoreApplication.translate("Form", u"\u0418\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044f \u043e \u0441\u043e\u0442\u0440\u0443\u0434\u043d\u0438\u043a\u0430\u0445", None)) # retranslateUi
python
import pygame, sys, noise, math from pygame.locals import * from random import randint, random pygame.init() try: windowSize = int(input("Enter size of window in pixels (e.g. 400): ")) except: # Give default size of 400px if invalid value entered windowSize = 400 windowSurface = pygame.display.set_mode((windowSize, windowSize), 0, 32) pygame.display.set_caption("Terrain generation (valley)") green = (0, 200, 0) beach_sand = (251, 255, 101) desert_sand = (255, 255, 51) white = (255, 255, 255) grey = (100, 100, 100) blue = (0, 100, 200) scale = 100 octaves = 6 persistence = 0.5 lacunarity = 2.0 pixelArray = pygame.PixelArray(windowSurface) seed1 = 0 seed2 = 0 def getDistanceFromCentre(y): return abs(y-(windowSize/2))/(windowSize/2) def generateTerrain(): global seed1, seed2 seed1 = randint(0, 100) seed2 = randint(0, 100) print("Generating terrain with seeds " + str(seed1) + " and " + str(seed2)) heightMap = [] temperatureMap = [] for y in range(windowSize): heightMap.append([]) temperatureMap.append([]) for x in range(windowSize): heightMap[y].append(noise.pnoise2(y/scale, x/scale, octaves=octaves, persistence=persistence, lacunarity=lacunarity, repeatx = windowSize, repeaty = windowSize, base=seed1)) temperatureMap[y].append(noise.pnoise2(y/scale, x/scale, octaves=octaves, persistence=persistence, lacunarity=lacunarity, repeatx = windowSize, repeaty = windowSize, base=seed2)) land = heightMap[y][x]+getDistanceFromCentre(y) # For any value smaller than 0.12, fill up with water. if land < 0.5: pixelArray[x, y] = (0, (getDistanceFromCentre(y)-heightMap[y][x]*2+1)*90, 255) # For values within interval (0.12, 0.16), fill up with sand. elif land < 0.56: pixelArray[x, y] = beach_sand elif land < 0.7: pixelArray[x, y] = green elif land < 0.8: pixelArray[x, y] = grey else: pixelArray[x, y] = white temperature = temperatureMap[y][x]-getDistanceFromCentre(y)*1.1 if temperature < -1: pixelArray[x, y] = white pygame.display.update() generateTerrain() while True: for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_r: windowSurface.fill(white) generateTerrain() if event.key == K_s: print("Saving map as image...") pygame.image.save(windowSurface, "map_valley_" + str(seed1) + "_" + str(seed2) + ".bmp") if event.type == QUIT: pygame.quit() sys.exit()
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created by Anand Sivaramakrishnan [email protected] 2018 12 28 This file is licensed under the Creative Commons Attribution-Share Alike license versions 3.0 or higher, see http://creativecommons.org/licenses/by-sa/3.0/ Python 3 matrixDFT.perform(): (also matrixDFT.inverse():) Parameters ---------- plane : 2D ndarray 2D array (either real or complex) representing the input image plane or pupil plane to transform. nlamD : float or 2-tuple of floats (nlamDY, nlamDX) Size of desired output region in lambda / D units, assuming that the pupil fills the input array (corresponds to 'm' in Soummer et al. 2007 4.2). This is in units of the spatial frequency that is just Nyquist sampled by the input array.) If given as a tuple, interpreted as (nlamDY, nlamDX). npix : int or 2-tuple of ints (npixY, npixX) Number of pixels per side side of destination plane array (corresponds to 'N_B' in Soummer et al. 2007 4.2). This will be the # of pixels in the image plane for a forward transformation, in the pupil plane for an inverse. If given as a tuple, interpreted as (npixY, npixX). """ ### Libraries/modules import os, sys import astropy.io.fits as fits import numpy as np import poppy.matrixDFT as matrixDFT import utils PUPIL = "pupil" IMAGE = "image" # This will set up default printing of numpy to 3 dec places, scientific notation #np.set_printoptions(precision=3, threshold=None, edgeitems=None, linewidth=None, # suppress=None, nanstr=None, infstr=None, formatter={'float': '{: 0.3e}'.format} ) def create_input_datafiles(rfn=None): """ Pupil and image data, true (zero mean) phase map (rad) No de-tilting of the thase done. Didactic case, no input parameters: create the pupil & monochromatic image on appropriate pixel scales. Pupil and image arrays of same size, ready to FT into each other losslessly. For real data you'll need to worry about adjusting sizes to satify this sampling relation between the two planes. For finite bandwidth data image simulation will loop over wavelengths. For coarsely sampled pixels image simulation will need to use finer sampling and rebin to detector pixel sizes. [email protected] Jan 2019 """ pupil0 = utils.makedisk(250, radius=50) # D=100 pix, array 250 pix pupil1 = (pupil0 - utils.makedisk(250, radius=15, ctr=(125.0,75.0)))*pupil0 pupil2 = (pupil1 - utils.makedisk(250, radius=15, ctr=(90.0,90.0)))*pupil0 pupil3 = (pupil2 - utils.makedisk(250, radius=15, ctr=(75.0,125.0)))*pupil0 fits.writeto(rfn+"0__input_pup.fits", pupil0, overwrite=True) fits.writeto(rfn+"1__input_pup.fits", pupil1, overwrite=True) fits.writeto(rfn+"2__input_pup.fits", pupil2, overwrite=True) fits.writeto(rfn+"3__input_pup.fits", pupil3, overwrite=True) for pnum in (0,1,2,3): pupil = fits.getdata(rfn+"{:1d}__input_pup.fits".format(pnum)) offctrbump=(pupil.shape[0]/2.0+30,pupil.shape[1]/2.0+20.0) # off-center bump ctrbump=(pupil.shape[0]/2.0,pupil.shape[1]/2.0) # central bump #quarter wave phase bump, off center phase = (2.0*np.pi/4.0) * utils.makegauss(pupil.shape[0], ctr=offctrbump, sigma=10.0) * pupil phase = de_mean(phase, pupil) # zero mean phase - doesn't change image fits.writeto(rfn+"{:1d}__input_truepha.fits".format(pnum), phase, overwrite=True) mft = matrixDFT.MatrixFourierTransform() imagefield = mft.perform(pupil * np.exp(1j*phase), pupil.shape[0], pupil.shape[0]) image = (imagefield*imagefield.conj()).real fits.writeto(rfn+"{:1d}__input_img.fits".format(pnum), image/image.sum(), overwrite=True) del mft def data_input(pupfn=None, imgfn=None, truephasefn=None, rfn=None): """ Get pupil and image data, No de-tilting of the thase done. Returns pupil and image arrays of samesize, ready to FT into each other correctly. For real data you'll need to worry about adjusting sizes to satify this sampling relation between the two planes. For finite bandwidth data image simulation will loop over wavelengths. For coarsely sampled pixels image simulation will need to use finer sampling and rebin to detector pixel sizes. [email protected] Jan 2019 """ pupil = fits.getdata(rfn+pupfn) image = fits.getdata(rfn+imgfn) truephase =fits.getdata(rfn+truephasefn) return pupil, image/image.sum(), truephase def arraystats(phase): return "mean {:+.4e} sigma {:+.4e} max {:+.4e} min {:+.4e} ".format( phase.mean(), phase.std(), phase.max(), phase.min()) def phase_changes(pupil, interior, phase_old, phase_new, gain): """ pupil: binary pupil array (grey edges OK) interior: one pixel clear of pupil edge, 0/1 array phase_old, phase_new: phase arrays to compare after de-meaning, de-tilting gain: the damping factor applied to the correction returns b - a phase difference array, standard dev of this phase difference, and the damped next phase to use interior unused here because we did not measure tilts of wavefronts """ dphase = (phase_new - phase_old) * pupil newphase = (phase_old + gain*dphase) * pupil # next iteration's pupil phase newphase = de_mean(newphase, pupil) return dphase, dphase[np.where(np.greater(pupil,0))].std(), newphase def de_mean(a, pupil): """ remove the mean where there is live pupil (0/1) """ return (a - a[np.where(pupil==1)].mean()) * pupil def meantilt(a, support): """ a: array like an OPD which you want to measure the mean tilt of. support_idx: indices array of region over which to take the mean of the tilts returns: (2-tuple) the mean tilt over the index array, in ["a" units] per pixel TBD: for really accurate work you should take the pixels either side and calculate the 'unbiased' tilt over the interior. In this 2018 version I changed tilt signs so higher value of array at higher index is positive tilt Remove tilt with phasea[pupil_idx] -= ta[0]*pupil_idx[0] - ta[1] * pupil_idx[1] ?? (untested) """ support_idx = np.where(support==1) xt,yt = (np.zeros(a.shape), np.zeros(a.shape)) xt[:-1,:] = a[1:,:] - a[:-1,:] yt[:,:-1] = a[:,1:] - a[:,:-1] print("\tMean tilt vector = {:.4e}, {:.4e}".format(xt[support_idx].mean(), yt[support_idx].mean())) return xt[support_idx].mean(), yt[support_idx].mean() # pure python x,y def interior(pup): """ The interior of a pupil, one pixel either side is clear of the pupil edge Used to calculate average tilt over the pupil Only works for unapodized (grey edge pixels OK) mA,mB = meantilt(opd, np.where(insideNRM()==1)) print "mA,mB %8.1e %8.1e rad/pix // " % (mA, mB), """ support = np.where(np.equal(pup, 1), 1, 0) support[1:,:] = support[1:,:] * support[:-1, :] #clip_loY ds9 support[:-1,:] = support[:-1,:] * support[1:, :] #clip_hiY ds9 support[:,1:] = support[:,1:] * support[:,:-1] #clip_loX ds9 support[1:,:] = support[1:,:] * support[:-1, :] #clip_loY ds9 return support.astype(np.uint8) def powerfunc(carr): return ((carr*carr.conj()).real).sum() class GerchbergSaxton: """ Does a Gerchberg Saxton in focus phase retrieval example case without noise Uses lossless transforms both ways (like an fft but a dft is used for didactic clarity) Usage: import GerchbergSaxton as GS # create or obtain pupil with obstructions, apodizations pupilfn = None # creates pupil initphase = None # First guess at pupil phase array (radians wavefront) or None damp=0.3, # pupil phase correction damping, dimensionless, <= 1 # UNUSED for clean didactc demonstration # read in or obtain intensity data from in-focus image # this data is on the sama angular scale as a lossless dft # of the pupil array, for simplicity. Trim it appropriately # ahead of time if necessary. imagefn = None # creates image with a gaussian phase bump aber # Save the first 5 iterations, then every 10th iteration # eg 1 2 3 4 5 10 20... history = (5,10) # rms phase change threshold for convergence (radians wavefront) threshold = 0.1 # context: Marechal approx gives Strehl 99% for phase rms 0.1 # max number of iterations (phase, image, back to next phase) maxiter = 30 # output file(s) root name fileroot = "GSdir/gstest" input files names will be appended to the fileroot # read in or obtain first guess of the wavefront phase in pupil gs = GS.GerchbergSaxton(pupilfn=pupilfn, imagefn=imagefn, truephasefn=truephasefn, outputtag="2", # kluge to match the numbered files for 4 didactic cases... initphase=phase, # initial guess, rad damp=damp, # pupil phase iteration damping, dimensionless, < 1 or None (uses 1) history=history, # record of which iterations you want to save for inspection later threshold=threshold, # stop iterating when wavefront rms <= this, rad maxiter=maxiter, # stop iterating after these number of iterations fileroot=fileroot, # file name root for history verbose=True, ) gs.gsloop() ### gerchbergsaxton.py files | File name for Example 1 | Description |--------------------------:|-------------------------------------------------------------------------| | gs1__input_img.fits | Image intensity file (unit power) | gs1__input_pup.fits | Pupil constraint file | gs1__input_truepha.fits | Phase used to create image | gs1__errorint.fits | Input image - final image | gs1__errorpha.fits | Input phase - measured phase | gs1_imgint.fits | Cube of image intensities | gs1_pupint.fits | Cube of pupil intensities | gs1_puppha.fits | Cube of pupil phases """ def __init__(self, pupilfn=None, imagefn=None, truephasefn=None, outputtag=0, initphase=None, damp=None, history=None, threshold=0.1, # Strehl 99% ~ 1 - threshold^2 maxiter=None, fileroot=None, verbose=True): """ Assumes square arrays, equal sized arrays for pupil, image Iterations are pupil - to image - to pupil """ # Requested attributes: self.damp = damp self.history = history self.threshold = threshold self.maxiter = maxiter self.fileroot = fileroot self.verbose = verbose self.pupil, self.image, self.truephase = data_input(pupilfn, imagefn, truephasefn, self.fileroot) self.tag = outputtag # Now for derived attributes: if initphase is None: self.initphase = self.pupil*0.0 # initial phase guess else: self.initphase = initphase self.phase = self.initphase.copy() self.pupilpower = (self.pupil*self.pupil).sum() self.mft = matrixDFT.MatrixFourierTransform() self.npix = self.pupil.shape[0] # size of the arrays # create interior of an unapodized pupil, for calculating mean tilts self.interior = interior(self.pupil) # Create initial guess at wavefront self.plane = PUPIL self.wavefront = self.pupil * np.exp(1j * self.phase) # List of phases to track evolution of GS self.iter = 0 # running count self.savediters = [-1,] # self.pupilintensities = [self.pupil,] # self.pupilphases = [self.initphase,] # self.imageintensities = [self.image,] # print("\nmaxiter {:d} convergence if sigma < {:.2e}\n".format(self.maxiter, self.threshold)) print("\nExample {:s} beginning\n".format(self.tag)) def apply_pupil_constraint(self, ): """ Replace absolute value of wavefront by pupil values, preserve the current phase """ if self.plane == PUPIL: # this new phase estimate comes from the image plane tranformed to this pupil nextphase = np.angle(self.wavefront) * self.pupil # check to see how the guess at the wavefront is changing... if self.verbose: fits.writeto(self.fileroot+self.tag+"__interior.fits", self.interior, overwrite=True) if self.verbose: fits.writeto(self.fileroot+self.tag+"__nextphase.fits", nextphase, overwrite=True) self.phasedelta, phasedeltarms, dampednextphase = phase_changes(self.pupil, self.interior, self.phase, nextphase, self.damp) print("\t{:3d}: Delta Phase stats: {:s} ".format(self.iter, arraystats(self.phasedelta[np.where(self.pupil==1)]))) # update wavefront with the new phase estimate self.wavefront = self.pupil * np.exp(1j*dampednextphase) self.phase = dampednextphase return phasedeltarms else: sys.exit(" gerchbergsaxton.apply_pupil_constraint(): being used in the wrong plane") def apply_image_constraint(self, ): """ Replace absolute value of wavefront by sqrt(image), preserve the current phase """ if self.plane == IMAGE: self.imagephase = np.angle(self.wavefront) self.wavefront = np.sqrt(self.image) * np.exp(1j*self.imagephase) if self.verbose: print("\timage power {:.4e}".format(powerfunc(self.wavefront))) return None else: sys.exit(" gerchbergsaxton.apply_image_constraint(): being used in the wrong plane") def propagate_wavefront(self, ): """ Apply the appropriate transform to go to the next conjugate plane. """ if self.plane == PUPIL: if self.verbose: print(" in pupil, going to image ") self.wavefront = self.mft.perform(self.wavefront, self.npix, self.npix) self.wavefront_image = self.wavefront self.plane = IMAGE elif self.plane == IMAGE: if self.verbose: print(" in image, going to pupil ") wavefront = self.mft.inverse(self.wavefront, self.npix, self.npix) power = (wavefront * wavefront.conj()).real.sum() self.wavefront = wavefront/np.sqrt(power) # preserve input total pupil power self.wavefront_pupil = self.wavefront self.plane = PUPIL else: sys.exit("GerchbergSaxton.propagate_wavefront() is confused: Neither pupil nor image plane") return None def iterate(self): """ iterate once, pupil to image then back to pupil, save data for the record if needed, then apply pupil constraint again """ if self.verbose: print("\niter:{:3d}".format(self.iter)) self.propagate_wavefront() # pupil to image self.save_iteration() self.apply_image_constraint() self.propagate_wavefront() # image to pupil self.save_iteration() self.iter += 1 rmsphasechange = self.apply_pupil_constraint() return rmsphasechange def save_iteration(self): """ keep a record of phases, intensities, etc. pupil phases whole plane incl. outside pupil support pupil phases only on pupil support image intensities whole plane """ if self.iter in range(history[0]) or self.iter%history[1]==0: if self.plane == PUPIL: pupilintensity = (self.wavefront*self.wavefront.conj()).real pupilintensity = pupilintensity/pupilintensity.sum()*self.pupilpower # preserve input total pupil power # should we instead preserve power over pupil?? # near convergence these two should be # very close towards the end. Just saying. # But this is a prob density function-like # array, so preserving total power is the # commonsense thing to do. self.pupilintensities.append(pupilintensity) self.pupilphases.append(self.pupil*np.angle(self.wavefront)) if self.plane == IMAGE: imageintensity = (self.wavefront*self.wavefront.conj()).real self.imageintensities.append(imageintensity/imageintensity.sum()) # preserve unit image power self.savediters.append(self.iter) def gswrite(self): """ save to disk for inspection """ # add the final iteration planes which may (or may not) be saved: # TBD - fancy bookkeeping to not save this if the GS loop ended on a 'save_iteration' cycle. # Right now there's a small chance that the last-but-one and last slices will be identical. # Not a big deal - they should be pretty close anyway as we converge.s # final pupil intensity added to list pupilintensity = (self.wavefront_pupil*self.wavefront_pupil.conj()).real pupilintensity = pupilintensity/pupilintensity.sum()*self.pupilpower self.pupilintensities.append(pupilintensity) # final pupil phase added to list self.pupilphases.append(np.angle(self.wavefront_pupil)*self.pupil) # final image intensity added to list imageintensity = (self.wavefront_image*self.wavefront_image.conj()).real self.imageintensities.append(imageintensity/imageintensity.sum()) # preserve unit image power # Now save the sequence of iterations... fits.writeto(self.fileroot+self.tag+"_pupint.fits", np.array(tuple(self.pupilintensities)), overwrite=True) fits.writeto(self.fileroot+self.tag+"_puppha.fits", np.array(tuple(self.pupilphases)), overwrite=True) fits.writeto(self.fileroot+self.tag+"_imgint.fits", np.array(tuple(self.imageintensities)), overwrite=True) # Errors compared to input values: phase_meas_error = de_mean(self.truephase - self.pupilphases[-1], self.pupil) img_meas_error = self.image - self.imageintensities[-1] print(" Init Phase stats: {:s} ".format(arraystats(self.truephase[np.where(self.pupil==1)]))) print(" Final Phase stats: {:s} ".format(arraystats(self.pupilphases[-1][np.where(self.pupil==1)]))) print("") print("Init - Final Phase stats: {:s} ".format(arraystats(phase_meas_error[np.where(self.pupil==1)]))) print(" Image diff stats: {:s} ".format(arraystats(img_meas_error))) print("") print("\tAll phases in radians, images total power unity, pupil power constrained to imput value") print("\nExample number {:s} ended\n".format(self.tag)) fits.writeto(gs.fileroot+self.tag+"__errorpha.fits", phase_meas_error, overwrite=True) fits.writeto(gs.fileroot+self.tag+"__errorint.fits", img_meas_error, overwrite=True) def gsloop(self): """ The main GS loop. """ for iloop in range(self.maxiter + 1): if self.iterate() < self.threshold: print("\n\tgsloop terminated at iter {}. Threshold sigma is {:.2e} radian \n".format(self.iter, self.threshold)) break self.gswrite() if __name__ == "__main__": # create or obtain pupil with obstructions, apodizations #pupilfn = None # creates pupil files, hardcoded single choice of pupill used initphase = None # First guess at pupil phase array (radians wavefront) or None damp = 1.0 # pupil phase correction damping, dimensionless, <= 1 # UNUSED for clean didactc demonstration # read in or obtain intensity data from in-focus image # this data is on the sama angular scale as a lossless dft # of the pupil array, for simplicity. Trim it appropriately # ahead of time if necessary. imagefn = None # creates image with a gaussian phase bump aber # Save the first 9 iterations, then every 10th iteration # eg 1 2 3 ... 9 10 20 30... history = (9,10) # rms phase change standard deviation threshold for convergence (radians wavefront) threshold = 1.0e-5 # radians # max number of iterations (phase, image, back to next phase) maxiter = 101 fileroot = "GSdir/gs" dirname = fileroot.split("/")[0] print(dirname) if not os.path.exists(dirname): os.makedirs(dirname) print("Created output directory ", dirname) create_input_datafiles(rfn=fileroot) # hardcoded file names for pupil image and true phase files # These names are used in GS.pupilfn, GS.imagefn, GS.truephasefn # A convenient output tag is inserted in the output file names of GS. for pnum in [0,1,2,3]: gs = GerchbergSaxton(pupilfn="{:d}__input_pup.fits".format(pnum), imagefn="{:d}__input_img.fits".format(pnum), truephasefn="{:d}__input_truepha.fits".format(pnum), outputtag="{:d}".format(pnum), # tags output files with prepended character(s) initphase=None, # initial guess, rad damp=damp, # pupil phase iteration damping, dimensionless, <= 1 or None (uses 1) history=history, # record of which iterations you want to save for inspection later threshold=threshold, # stop iterating when wavefront rms <= this, rad maxiter=maxiter, # stop iterating after these number of iterations fileroot=fileroot, # file name root for history verbose=False, ) gs.gsloop()
python
import os from django.db import models from django.urls import reverse from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from .hooks import hookset from .managers import PublishedPageManager class Page(models.Model): STATUS_CHOICES = ( (1, _("Draft")), (2, _("Public")), ) title = models.CharField(max_length=100) path = models.CharField(max_length=100, unique=True) body = models.TextField() body_html = models.TextField(blank=True, editable=False) status = models.IntegerField(choices=STATUS_CHOICES, default=2) publish_date = models.DateTimeField(default=timezone.now) created = models.DateTimeField(editable=False, default=timezone.now) updated = models.DateTimeField(editable=False, default=timezone.now) published = PublishedPageManager() def __str__(self): return self.title def get_absolute_url(self): return reverse("pinax_pages:pages_page", args=[self.path]) @property def is_community(self): return self.path.lower().startswith("community/") def save(self, *args, **kwargs): self.updated = timezone.now() self.body_html = hookset.parse_content(self.body) super(Page, self).save(*args, **kwargs) self.pagehistory_set.create( title=self.title, path=self.path, body=self.body, body_html=self.body_html, status=self.status, publish_date=self.publish_date ) def clean_fields(self, exclude=None): super(Page, self).clean_fields(exclude) hookset.validate_path(self.path) class PageHistory(models.Model): page = models.ForeignKey(Page, on_delete=models.CASCADE, editable=False) title = models.CharField(max_length=100, editable=False) path = models.CharField(max_length=100, editable=False) body = models.TextField(editable=False) body_html = models.TextField(blank=True, editable=False) status = models.IntegerField(default=2, editable=False) publish_date = models.DateTimeField(default=timezone.now, editable=False) created = models.DateTimeField(editable=False, default=timezone.now) def __str__(self): return "{} - {}".format(self.title, self.created) def generate_filename(instance, filename): return filename class File(models.Model): file = models.FileField(upload_to=generate_filename) created = models.DateTimeField(default=timezone.now) def download_url(self): return reverse("pinax_pages:file_download", args=[self.pk, os.path.basename(self.file.name).lower()])
python
#!/usr/bin/env python """ Bookizer ========== Bookizer get's an almost uncertain number of CSV files and converts them into a big CSV/ODS/XLS/XLSX file """ import sys from setuptools import setup if sys.version_info.major < 3: raise RuntimeError( 'Bookizer does not support Python 2.x anymore. ' 'Please use Python 3 or do magic.') setup()
python
# # SDK-Blueprint module # Code written by Cataldo Calò ([email protected]) and Mirco Manzoni ([email protected]) # # Copyright 2018-19 Politecnico di Milano # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # # This is being developed for the DITAS Project: https://www.ditas-project.eu/ # import argparse import os import requests import shutil from repo import repo from blueprint.blueprint import Blueprint from blueprint import blueprint as bp from distutils.dir_util import copy_tree import json __author__ = "Cataldo Calò, Mirco Manzoni" __credits__ = ["Cataldo Calò", "Mirco Manzoni"] __status__ = "Development" TMP_DIR = 'tmp' VDC_TEMPLATE = 'vdc_template' DAL_TEMPLATE = 'dal_template' VDC = 'VDC' DAL = 'DAL' VDC_TEMPLATE_COMMIT = 'VDC template commit' DAL_TEMPLATE_COMMIT = 'DAL template commit' BLUEPRINT_COMMIT = 'Blueprint commit' PUBLISH_ID = 'blueprint_id' def generate_blueprint(vdc_repo, vdc_path, dal_paths, update, push): # Do something print('Creating blueprint...') blueprint = Blueprint(vdc_path, dal_paths, update) blueprint.add_is_tags() blueprint.add_is_flow() blueprint.add_is_testing_output_data() blueprint.add_is_methods_input() blueprint.add_cookbook() blueprint.add_exposed_api() blueprint.add_is_data_sources() blueprint.add_data_management() blueprint.save() print('Blueprint created') if push: print('Pushing blueprint into VDC repository...') repo.commit_and_push_all_changes(vdc_repo, BLUEPRINT_COMMIT) print('Push complete') def extract_repo_name(url): # Extract the name of the repository from URL return os.path.basename(os.path.normpath(url)) def prepare_repo_folder(repo_name): # Create a subfolder in TMP_DIR with the name of the repo repo_path = os.path.join(os.getcwd(), TMP_DIR, repo_name) # If the subfolder already exists, delete it if os.path.exists(repo_path) and os.path.isdir(repo_path): shutil.rmtree(repo_path) return repo_path def clone_repos(vdc_url, dal_urls): print('clone_repos function, URLs: ', vdc_url, ', ', dal_urls) print('Cloning VDC repository at ' + vdc_url + '...') # Clone VDC repo and extract info to generate Blueprint repo_name = extract_repo_name(vdc_url) vdc_repo_path = prepare_repo_folder(repo_name) vdc_repo = repo.clone_repo(vdc_url, vdc_repo_path) dal_repo_paths = [] # Clone each DAL repo and merge information to blueprint for dal_url in dal_urls: # if the DAL URL is the same as VDC, prepare_repo_folder could cause some troubles # Just skip this step if dal_url != vdc_url: print('Cloning DAL repository at ' + dal_url + '...') repo_name = extract_repo_name(dal_url) dal_repo_path = prepare_repo_folder(repo_name) repo.clone_repo(dal_url, dal_repo_path) dal_repo_paths.append(dal_repo_path) else: print('DAL URL is the same as VDC: skipping cloning step...') dal_repo_paths.append(vdc_repo_path) return vdc_repo, vdc_repo_path, dal_repo_paths def handler_create(args): dal_urls = [args.VDC_URL] if args.DAL_URL: dal_urls = args.DAL_URL vdc_repo, vdc_repo_path, dal_repo_paths = clone_repos(args.VDC_URL, dal_urls) generate_blueprint(vdc_repo, vdc_repo_path, dal_repo_paths, False, args.push) def handler_update(args): dal_urls = [args.VDC_URL] if args.DAL_URL: dal_urls = args.DAL_URL vdc_repo, vdc_repo_path, dal_repo_paths = clone_repos(args.VDC_URL, dal_urls) generate_blueprint(vdc_repo, vdc_repo_path, dal_repo_paths, True, args.push) def handler_repo_init(args): if args.name: repo_name = args.name # This will create a repo in the org DITAS-Project. DO NOT SPAM resp = repo.create_ditas_repo(repo_name) # TODO: delete next line when testing is complete and uncomment the previous one #resp = repo.create_personal_repo(repo_name) print(resp['html_url']) repo_url = resp['html_url'] # Setup a local folder to track the remote repository repo_path = prepare_repo_folder(repo_name) remote_repo = repo.clone_repo(https_url=repo_url, path=repo_path, new_repo=True) # Use the default VDC template for the new repository if args.type == VDC: from_directory = os.path.join(os.getcwd(), VDC_TEMPLATE) commit_msg = VDC_TEMPLATE_COMMIT elif args.type == DAL: from_directory = os.path.join(os.getcwd(), DAL_TEMPLATE) commit_msg = DAL_TEMPLATE_COMMIT copy_tree(from_directory, repo_path) # Commit and push the new structure repo.commit_and_push_all_changes(remote_repo, commit_msg) def handler_publish(args): if not os.path.exists(args.file): print("File does not exist!") return body = bp.get_dict_from_file(args.file) api_endpoint = args.server + '/blueprints' print("Trying to make a POST to: ", api_endpoint) r = requests.post(url=api_endpoint, data=json.dumps(body), headers={'Content-Type': 'application/json'}, auth=repo.get_iccs_crendetials()) if r.ok: print("Blueprint published successfully.") print('The ID of the published blueprint is ' + json.loads(r.content)[PUBLISH_ID][0]) else: print(r.status_code) print(r.content) def handler_invokedue(args): if not os.path.exists(args.file): print("File does not exist!") return body = bp.get_dict_from_file(args.file) #api_endpoint = args.server + '/v1/datautility' #for debug only, remove once DUE-SDK API are standardized api_endpoint = args.server + '/ditas-project/DataUtilityEvaluator/1.0/datautility' print("Trying to invoke DUE-SDK at: ", api_endpoint) r = requests.post(url=api_endpoint, data=json.dumps(body), headers={'Content-Type': 'application/json'}) if r.ok: print("Data utility values updated successfully.") with open(args.file, 'w') as outfile: json.dump(json.loads(r.content), outfile, indent=4) else: print(r.status_code) print(r.content) def handler_unpublish(args): api_endpoint = args.server + '/blueprints/' + args.blueprint print("Trying to make a DELETE to: ", api_endpoint) r = requests.delete(url=api_endpoint, auth=repo.get_iccs_crendetials()) if r.ok: print("Blueprint unpublished successfully.") else: print(r.status_code) def handler_std_metrics(args): print("args: ", args) # Metrics are computed only for VDC if not args.local: vdc_repo, vdc_repo_path, _ = clone_repos(args.VDC, []) else: vdc_repo_path = os.path.join(os.getcwd(), TMP_DIR, args.VDC) bp.generate_api_metrics_files(vdc_repo_path) if __name__ == "__main__": parser = argparse.ArgumentParser( description='''DITAS SDK-Blueprint Generator.''') subparsers = parser.add_subparsers(help='Sub-command to create or update a blueprint, or to setup a new repository') # Create the parser for the "create" command parser_create = subparsers.add_parser('create', help='Generate a new blueprint. An already existing blueprint ' 'is overwritten.') parser_create.add_argument('VDC_URL', type=str, help='VDC repository URL') parser_create.add_argument('DAL_URL', type=str, nargs='*', help='List of DAL repositories URLs. Assumed same URL ' 'as VDC repository if not provided') parser_create.add_argument('-p', dest='push', action='store_true', required=False, help='Push new generated blueprint' ' into VDC repository') #parser_create.add_argument('-e', type=str, default='bla', help='Use this option to automatically set two URLs as ' # 'example') parser_create.set_defaults(func=handler_create) # Create the parser for the "update" command parser_update = subparsers.add_parser('update', help='Update an existing blueprint. Only the parts specified in the ' 'configuration files of the repositories will be overwritten.') parser_update.add_argument('VDC_URL', type=str, help='VDC repository URL') parser_update.add_argument('DAL_URL', type=str, nargs='*', help='List of DAL repositories URLs. Assumed same URL ' 'as VDC repository if not provided') parser_update.add_argument('-p', dest='push', action='store_true', required=False, help='Push new generated blueprint into VDC repository') parser_update.set_defaults(func=handler_update) # Create the parser for the "repo-init" command parser_repo_init = subparsers.add_parser('repo-init', help='Create a new GitHub repository with the default ' 'structure.') parser_repo_init.add_argument('type', choices=[VDC, DAL], help="Type of repository to create") parser_repo_init.add_argument('name', type=str, help='Repository name') parser_repo_init.set_defaults(func=handler_repo_init) # Create the parser for the "std-metrics" command parser_std_metrics = subparsers.add_parser('std-metrics', help='Create a json file for each API method with the ' 'default data metrics. The path is specified by ' 'the attribute "data-management" of the VDC ' 'configuration file.') parser_std_metrics.add_argument('VDC', type=str, help='VDC repository URL or directory name if already downloaded.') parser_std_metrics.add_argument('-l', dest='local', action='store_true', required=False, help='Specifies if the VDC repository has been already downloaded, i.e. the ' 'provided argument is the name of repository') parser_std_metrics.set_defaults(func=handler_std_metrics) # Create the parser for the "compute-du" command parser_publish = subparsers.add_parser(name='compute-du', help="Invokes DUE-SDK to compute data utility.") parser_publish.add_argument('file', type=str, help='Path to blueprint file to be updated.') parser_publish.add_argument('-server', type=str, default='https://localhost:8080', help='URL of the DUE-SDK.' 'For example: https://example.com:8080') parser_publish.set_defaults(func=handler_invokedue) # Create the parser for the "publish" command parser_publish = subparsers.add_parser(name='publish', help="Publish blueprint to ICCS repository.") parser_publish.add_argument('file', type=str, help='Path to blueprint file to be published.') parser_publish.add_argument('-server', type=str, default='https://localhost:8080', help='Hostname of the ICCS repository, including protocol. ' 'For example: https://example.com:8080') parser_publish.add_argument('-basename', type=str, default='http', help='') parser_publish.set_defaults(func=handler_publish) # Create the parser for the "unpublish" command parser_unpublish = subparsers.add_parser(name='unpublish', help="Unpublish blueprint from ICCS repository.") parser_unpublish.add_argument('blueprint', type=str, help='Blueprint ID to be unpublished.') parser_unpublish.add_argument('-server', type=str, default='https://localhost:8080', help='Hostname of the ICCS repository, including protocol. ' 'For example: https://example.com:8080') parser_unpublish.add_argument('-basename', type=str, default='http', help='') parser_unpublish.set_defaults(func=handler_unpublish) args = parser.parse_args() args.func(args) #print(args)
python
from office365.sharepoint.ui.applicationpages.client_people_picker import \ ClientPeoplePickerWebServiceInterface, ClientPeoplePickerQueryParameters from tests import test_user_principal_name from tests.sharepoint.sharepoint_case import SPTestCase class TestSPPeoplePicker(SPTestCase): @classmethod def setUpClass(cls): super(TestSPPeoplePicker, cls).setUpClass() def test1_get_search_results(self): params = ClientPeoplePickerQueryParameters(test_user_principal_name) result = ClientPeoplePickerWebServiceInterface.client_people_picker_resolve_user(self.client, params) self.client.execute_query() self.assertIsNotNone(result.value) #def test2_get_search_results(self): # result = ClientPeoplePickerWebServiceInterface.get_picker_entity_information(self.client, # test_user_principal_name) # self.client.execute_query() # self.assertIsNotNone(result.value) # def test2_get_search_results(self): # result = ClientPeoplePickerWebServiceInterface.get_search_results(self.client, "mdoe") # self.client.execute_query() # self.assertIsNotNone(result.value)
python
"""Build indexing using extracted features """ import numpy as np import os, os.path import pickle import scipy.spatial from scipy.spatial.distance import pdist, squareform """Build index Given feature matrix feature_mat, k is the number of nearest neighbors to choose """ def build_index(feature_mat, k): sample_count_ = feature_mat.shap(0) index = np.zeros((sample_count_, k), dtype=numpy.int) for idx in range(sample_count_): feature = feature_mat[idx, ...] dist =
python
import sys import os import random import math import bpy import numpy as np from os import getenv from os import remove from os.path import join, dirname, realpath, exists from mathutils import Matrix, Vector, Quaternion, Euler from glob import glob from random import choice from pickle import load from bpy_extras.object_utils import world_to_camera_view as world2cam sys.path.insert(0, ".") def mkdir_safe(directory): try: os.makedirs(directory) except FileExistsError: pass def setState0(): for ob in bpy.data.objects.values(): ob.select=False bpy.context.scene.objects.active = None sorted_parts = ['hips','leftUpLeg','rightUpLeg','spine','leftLeg','rightLeg', 'spine1','leftFoot','rightFoot','spine2','leftToeBase','rightToeBase', 'neck','leftShoulder','rightShoulder','head','leftArm','rightArm', 'leftForeArm','rightForeArm','leftHand','rightHand','leftHandIndex1' ,'rightHandIndex1'] # order part_match = {'root':'root', 'bone_00':'Pelvis', 'bone_01':'L_Hip', 'bone_02':'R_Hip', 'bone_03':'Spine1', 'bone_04':'L_Knee', 'bone_05':'R_Knee', 'bone_06':'Spine2', 'bone_07':'L_Ankle', 'bone_08':'R_Ankle', 'bone_09':'Spine3', 'bone_10':'L_Foot', 'bone_11':'R_Foot', 'bone_12':'Neck', 'bone_13':'L_Collar', 'bone_14':'R_Collar', 'bone_15':'Head', 'bone_16':'L_Shoulder', 'bone_17':'R_Shoulder', 'bone_18':'L_Elbow', 'bone_19':'R_Elbow', 'bone_20':'L_Wrist', 'bone_21':'R_Wrist', 'bone_22':'L_Hand', 'bone_23':'R_Hand'} part2num = {part:(ipart+1) for ipart,part in enumerate(sorted_parts)} # create one material per part as defined in a pickle with the segmentation # this is useful to render the segmentation in a material pass def create_segmentation(ob, params): materials = {} vgroups = {} with open('pkl/segm_per_v_overlap.pkl', 'rb') as f: vsegm = load(f) bpy.ops.object.material_slot_remove() parts = sorted(vsegm.keys()) for part in parts: vs = vsegm[part] vgroups[part] = ob.vertex_groups.new(part) vgroups[part].add(vs, 1.0, 'ADD') bpy.ops.object.vertex_group_set_active(group=part) materials[part] = bpy.data.materials['Material'].copy() materials[part].pass_index = part2num[part] bpy.ops.object.material_slot_add() ob.material_slots[-1].material = materials[part] bpy.ops.object.mode_set(mode='EDIT') bpy.ops.mesh.select_all(action='DESELECT') bpy.ops.object.vertex_group_select() bpy.ops.object.material_slot_assign() bpy.ops.object.mode_set(mode='OBJECT') return(materials) # create the different passes that we render def create_composite_nodes(tree, params, img=None, idx=0): res_paths = {k:join(params['tmp_path'], '%05d_%s'%(idx, k)) for k in params['output_types'] if params['output_types'][k]} # clear default nodes for n in tree.nodes: tree.nodes.remove(n) # create node for foreground image layers = tree.nodes.new('CompositorNodeRLayers') layers.location = -300, 400 # create node for background image bg_im = tree.nodes.new('CompositorNodeImage') bg_im.location = -300, 30 if img is not None: bg_im.image = img if(params['output_types']['vblur']): # create node for computing vector blur (approximate motion blur) vblur = tree.nodes.new('CompositorNodeVecBlur') vblur.factor = params['vblur_factor'] vblur.location = 240, 400 # create node for saving output of vector blurred image vblur_out = tree.nodes.new('CompositorNodeOutputFile') vblur_out.format.file_format = 'PNG' vblur_out.base_path = res_paths['vblur'] vblur_out.location = 460, 460 # create node for mixing foreground and background images mix = tree.nodes.new('CompositorNodeMixRGB') mix.location = 40, 30 mix.use_alpha = True # create node for the final output composite_out = tree.nodes.new('CompositorNodeComposite') composite_out.location = 240, 30 # create node for saving depth if(params['output_types']['depth']): depth_out = tree.nodes.new('CompositorNodeOutputFile') depth_out.location = 40, 700 depth_out.format.file_format = 'OPEN_EXR' depth_out.base_path = res_paths['depth'] # create node for saving normals if(params['output_types']['normal']): normal_out = tree.nodes.new('CompositorNodeOutputFile') normal_out.location = 40, 600 normal_out.format.file_format = 'OPEN_EXR' normal_out.base_path = res_paths['normal'] # create node for saving foreground image if(params['output_types']['fg']): fg_out = tree.nodes.new('CompositorNodeOutputFile') fg_out.location = 170, 600 fg_out.format.file_format = 'PNG' fg_out.base_path = res_paths['fg'] # create node for saving ground truth flow if(params['output_types']['gtflow']): gtflow_out = tree.nodes.new('CompositorNodeOutputFile') gtflow_out.location = 40, 500 gtflow_out.format.file_format = 'OPEN_EXR' gtflow_out.base_path = res_paths['gtflow'] # create node for saving segmentation if(params['output_types']['segm']): segm_out = tree.nodes.new('CompositorNodeOutputFile') segm_out.location = 40, 400 segm_out.format.file_format = 'OPEN_EXR' segm_out.base_path = res_paths['segm'] # merge fg and bg images tree.links.new(bg_im.outputs[0], mix.inputs[1]) tree.links.new(layers.outputs['Image'], mix.inputs[2]) if(params['output_types']['vblur']): tree.links.new(mix.outputs[0], vblur.inputs[0]) # apply vector blur on the bg+fg image, tree.links.new(layers.outputs['Z'], vblur.inputs[1]) # using depth, tree.links.new(layers.outputs['Speed'], vblur.inputs[2]) # and flow. tree.links.new(vblur.outputs[0], vblur_out.inputs[0]) # save vblurred output tree.links.new(mix.outputs[0], composite_out.inputs[0]) # bg+fg image if(params['output_types']['fg']): tree.links.new(layers.outputs['Image'], fg_out.inputs[0]) # save fg if(params['output_types']['depth']): tree.links.new(layers.outputs['Z'], depth_out.inputs[0]) # save depth if(params['output_types']['normal']): tree.links.new(layers.outputs['Normal'], normal_out.inputs[0]) # save normal if(params['output_types']['gtflow']): tree.links.new(layers.outputs['Speed'], gtflow_out.inputs[0]) # save ground truth flow if(params['output_types']['segm']): tree.links.new(layers.outputs['IndexMA'], segm_out.inputs[0]) # save segmentation return(res_paths) # creation of the spherical harmonics material, using an OSL script def create_sh_material(tree, sh_path, img=None): # clear default nodes for n in tree.nodes: tree.nodes.remove(n) uv = tree.nodes.new('ShaderNodeTexCoord') uv.location = -800, 400 uv_xform = tree.nodes.new('ShaderNodeVectorMath') uv_xform.location = -600, 400 uv_xform.inputs[1].default_value = (0, 0, 1) uv_xform.operation = 'AVERAGE' uv_im = tree.nodes.new('ShaderNodeTexImage') uv_im.location = -400, 400 if img is not None: uv_im.image = img rgb = tree.nodes.new('ShaderNodeRGB') rgb.location = -400, 200 script = tree.nodes.new('ShaderNodeScript') script.location = -230, 400 script.mode = 'EXTERNAL' script.filepath = sh_path #'spher_harm/sh.osl' #using the same file from multiple jobs causes white texture script.update() # the emission node makes it independent of the scene lighting emission = tree.nodes.new('ShaderNodeEmission') emission.location = -60, 400 mat_out = tree.nodes.new('ShaderNodeOutputMaterial') mat_out.location = 110, 400 tree.links.new(uv.outputs[2], uv_im.inputs[0]) tree.links.new(uv_im.outputs[0], script.inputs[0]) tree.links.new(script.outputs[0], emission.inputs[0]) tree.links.new(emission.outputs[0], mat_out.inputs[0]) # computes rotation matrix through Rodrigues formula as in cv2.Rodrigues def Rodrigues(rotvec): theta = np.linalg.norm(rotvec) r = (rotvec/theta).reshape(3, 1) if theta > 0. else rotvec cost = np.cos(theta) mat = np.asarray([[0, -r[2], r[1]], [r[2], 0, -r[0]], [-r[1], r[0], 0]]) return(cost*np.eye(3) + (1-cost)*r.dot(r.T) + np.sin(theta)*mat) def init_scene(scene, params, gender='female'): # load fbx model bpy.ops.import_scene.fbx(filepath=join(params['smpl_data_folder'], 'basicModel_%s_lbs_10_207_0_v1.0.2.fbx' % gender[0]), axis_forward='Y', axis_up='Z', global_scale=100) obname = '%s_avg' % gender[0] ob = bpy.data.objects[obname] ob.data.use_auto_smooth = False # autosmooth creates artifacts # assign the existing spherical harmonics material ob.active_material = bpy.data.materials['Material'] # delete the default cube (which held the material) bpy.ops.object.select_all(action='DESELECT') bpy.data.objects['Cube'].select = True bpy.ops.object.delete(use_global=False) # set camera properties and initial position bpy.ops.object.select_all(action='DESELECT') cam_ob = bpy.data.objects['Camera'] scn = bpy.context.scene scn.objects.active = cam_ob cam_ob.matrix_world = Matrix(((0., 0., 1, params['camera_distance']), (1., 0., 0., 0.), (0., 1., 0., 1.), (0.0, 0.0, 0.0, 1.0))) cam_ob.data.angle = math.radians(40) cam_ob.data.lens = 60 cam_ob.data.clip_start = 0.1 cam_ob.data.sensor_width = 32 # setup an empty object in the center which will be the parent of the Camera # this allows to easily rotate an object around the origin scn.cycles.film_transparent = True scn.render.layers["RenderLayer"].use_pass_vector = True scn.render.layers["RenderLayer"].use_pass_normal = True scene.render.layers['RenderLayer'].use_pass_emit = True scene.render.layers['RenderLayer'].use_pass_emit = True scene.render.layers['RenderLayer'].use_pass_material_index = True # set render size scn.render.resolution_x = params['resy'] scn.render.resolution_y = params['resx'] scn.render.resolution_percentage = 100 scn.render.image_settings.file_format = 'PNG' # clear existing animation data ob.data.shape_keys.animation_data_clear() arm_ob = bpy.data.objects['Armature'] arm_ob.animation_data_clear() return(ob, obname, arm_ob, cam_ob) # transformation between pose and blendshapes def rodrigues2bshapes(pose): rod_rots = np.asarray(pose).reshape(24, 3) mat_rots = [Rodrigues(rod_rot) for rod_rot in rod_rots] bshapes = np.concatenate([(mat_rot - np.eye(3)).ravel() for mat_rot in mat_rots[1:]]) return(mat_rots, bshapes) # apply trans pose and shape to character def apply_trans_pose_shape(trans, pose, shape, ob, arm_ob, obname, scene, cam_ob, frame=None): # transform pose into rotation matrices (for pose) and pose blendshapes mrots, bsh = rodrigues2bshapes(pose) # set the location of the first bone to the translation parameter arm_ob.pose.bones[obname+'_Pelvis'].location = trans if frame is not None: arm_ob.pose.bones[obname+'_root'].keyframe_insert('location', frame=frame) # set the pose of each bone to the quaternion specified by pose for ibone, mrot in enumerate(mrots): bone = arm_ob.pose.bones[obname+'_'+part_match['bone_%02d' % ibone]] bone.rotation_quaternion = Matrix(mrot).to_quaternion() if frame is not None: bone.keyframe_insert('rotation_quaternion', frame=frame) bone.keyframe_insert('location', frame=frame) # apply pose blendshapes for ibshape, bshape in enumerate(bsh): ob.data.shape_keys.key_blocks['Pose%03d' % ibshape].value = bshape if frame is not None: ob.data.shape_keys.key_blocks['Pose%03d' % ibshape].keyframe_insert('value', index=-1, frame=frame) # apply shape blendshapes for ibshape, shape_elem in enumerate(shape): ob.data.shape_keys.key_blocks['Shape%03d' % ibshape].value = shape_elem if frame is not None: ob.data.shape_keys.key_blocks['Shape%03d' % ibshape].keyframe_insert('value', index=-1, frame=frame) def get_bone_locs(obname, arm_ob, scene, cam_ob): n_bones = 24 render_scale = scene.render.resolution_percentage / 100 render_size = (int(scene.render.resolution_x * render_scale), int(scene.render.resolution_y * render_scale)) bone_locations_2d = np.empty((n_bones, 2)) bone_locations_3d = np.empty((n_bones, 3), dtype='float32') # obtain the coordinates of each bone head in image space for ibone in range(n_bones): bone = arm_ob.pose.bones[obname+'_'+part_match['bone_%02d' % ibone]] co_2d = world2cam(scene, cam_ob, arm_ob.matrix_world * bone.head) co_3d = arm_ob.matrix_world * bone.head bone_locations_3d[ibone] = (co_3d.x, co_3d.y, co_3d.z) bone_locations_2d[ibone] = (round(co_2d.x * render_size[0]), round(co_2d.y * render_size[1])) return(bone_locations_2d, bone_locations_3d) # reset the joint positions of the character according to its new shape def reset_joint_positions(orig_trans, shape, ob, arm_ob, obname, scene, cam_ob, reg_ivs, joint_reg): # since the regression is sparse, only the relevant vertex # elements (joint_reg) and their indices (reg_ivs) are loaded reg_vs = np.empty((len(reg_ivs), 3)) # empty array to hold vertices to regress from # zero the pose and trans to obtain joint positions in zero pose apply_trans_pose_shape(orig_trans, np.zeros(72), shape, ob, arm_ob, obname, scene, cam_ob) # obtain a mesh after applying modifiers bpy.ops.wm.memory_statistics() # me holds the vertices after applying the shape blendshapes me = ob.to_mesh(scene, True, 'PREVIEW') # fill the regressor vertices matrix for iiv, iv in enumerate(reg_ivs): reg_vs[iiv] = me.vertices[iv].co bpy.data.meshes.remove(me) # regress joint positions in rest pose joint_xyz = joint_reg.dot(reg_vs) # adapt joint positions in rest pose arm_ob.hide = False bpy.ops.object.mode_set(mode='EDIT') arm_ob.hide = True for ibone in range(24): bb = arm_ob.data.edit_bones[obname+'_'+part_match['bone_%02d' % ibone]] bboffset = bb.tail - bb.head bb.head = joint_xyz[ibone] bb.tail = bb.head + bboffset bpy.ops.object.mode_set(mode='OBJECT') return(shape) # load poses and shapes def load_body_data(smpl_data, ob, obname, gender='female', idx=0): # load MoSHed data from CMU Mocap (only the given idx is loaded) # create a dictionary with key the sequence name and values the pose and trans cmu_keys = [] for seq in smpl_data.files: if seq.startswith('pose_'): cmu_keys.append(seq.replace('pose_', '')) name = sorted(cmu_keys)[idx % len(cmu_keys)] cmu_parms = {} for seq in smpl_data.files: if seq == ('pose_' + name): cmu_parms[seq.replace('pose_', '')] = {'poses':smpl_data[seq], 'trans':smpl_data[seq.replace('pose_','trans_')]} # compute the number of shape blendshapes in the model n_sh_bshapes = len([k for k in ob.data.shape_keys.key_blocks.keys() if k.startswith('Shape')]) # load all SMPL shapes fshapes = smpl_data['%sshapes' % gender][:, :n_sh_bshapes] return(cmu_parms, fshapes, name) import time start_time = None def log_message(message): elapsed_time = time.time() - start_time print("[%.2f s] %s" % (elapsed_time, message)) def main(): # time logging global start_time start_time = time.time() import argparse # parse commandline arguments log_message(sys.argv) parser = argparse.ArgumentParser(description='Generate synth dataset images.') parser.add_argument('--idx', type=int, help='idx of the requested sequence') parser.add_argument('--ishape', type=int, help='requested cut, according to the stride') parser.add_argument('--stride', type=int, help='stride amount, default 50') args = parser.parse_args(sys.argv[sys.argv.index("--") + 1:]) idx = args.idx ishape = args.ishape stride = args.stride log_message("input idx: %d" % idx) log_message("input ishape: %d" % ishape) log_message("input stride: %d" % stride) if idx == None: exit(1) if ishape == None: exit(1) if stride == None: log_message("WARNING: stride not specified, using default value 50") stride = 50 # import idx info (name, split) idx_info = load(open("pkl/idx_info.pickle", 'rb')) idx_info = [x for x in idx_info if x['name'][:4] != 'h36m'] # get runpass (runpass, idx) = divmod(idx, len(idx_info)) log_message("runpass: %d" % runpass) log_message("output idx: %d" % idx) idx_info = idx_info[idx] log_message("sequence: %s" % idx_info['name']) log_message("nb_frames: %f" % idx_info['nb_frames']) log_message("use_split: %s" % idx_info['use_split']) # import configuration log_message("Importing configuration") import config params = config.load_file('config', 'SYNTH_DATA') smpl_data_folder = params['smpl_data_folder'] smpl_data_filename = params['smpl_data_filename'] bg_path = params['bg_path'] resy = params['resy'] resx = params['resx'] clothing_option = params['clothing_option'] # grey, nongrey or all tmp_path = params['tmp_path'] output_path = params['output_path'] output_types = params['output_types'] stepsize = params['stepsize'] clipsize = params['clipsize'] openexr_py2_path = params['openexr_py2_path'] # compute number of cuts nb_ishape = max(1, int(np.ceil((idx_info['nb_frames'] - (clipsize - stride))/stride))) log_message("Max ishape: %d" % (nb_ishape - 1)) if ishape == None: exit(1) assert(ishape < nb_ishape) # name is set given idx name = idx_info['name'] output_path = join(output_path, 'run%d' % runpass, name.replace(" ", "")) params['output_path'] = output_path tmp_path = join(tmp_path, 'run%d_%s_c%04d' % (runpass, name.replace(" ", ""), (ishape + 1))) params['tmp_path'] = tmp_path # check if already computed # + clean up existing tmp folders if any if exists(tmp_path) and tmp_path != "" and tmp_path != "/": os.system('rm -rf %s' % tmp_path) rgb_vid_filename = "%s_c%04d.mp4" % (join(output_path, name.replace(' ', '')), (ishape + 1)) #if os.path.isfile(rgb_vid_filename): # log_message("ALREADY COMPUTED - existing: %s" % rgb_vid_filename) # return 0 # create tmp directory if not exists(tmp_path): mkdir_safe(tmp_path) # >> don't use random generator before this point << # initialize RNG with seeds from sequence id import hashlib s = "synth_data:%d:%d:%d" % (idx, runpass,ishape) seed_number = int(hashlib.sha1(s.encode('utf-8')).hexdigest(), 16) % (10 ** 8) log_message("GENERATED SEED %d from string '%s'" % (seed_number, s)) random.seed(seed_number) np.random.seed(seed_number) if(output_types['vblur']): vblur_factor = np.random.normal(0.5, 0.5) params['vblur_factor'] = vblur_factor log_message("Setup Blender") # create copy-spher.harm. directory if not exists sh_dir = join(tmp_path, 'spher_harm') if not exists(sh_dir): mkdir_safe(sh_dir) sh_dst = join(sh_dir, 'sh_%02d_%05d.osl' % (runpass, idx)) os.system('cp spher_harm/sh.osl %s' % sh_dst) genders = {0: 'female', 1: 'male'} # pick random gender gender = choice(genders) scene = bpy.data.scenes['Scene'] scene.render.engine = 'CYCLES' bpy.data.materials['Material'].use_nodes = True scene.cycles.shading_system = True scene.use_nodes = True log_message("Listing background images") bg_names = join(bg_path, '%s_img.txt' % idx_info['use_split']) nh_txt_paths = [] with open(bg_names) as f: for line in f: nh_txt_paths.append(join(bg_path, line)) # grab clothing names log_message("clothing: %s" % clothing_option) with open( join(smpl_data_folder, 'textures', '%s_%s.txt' % ( gender, idx_info['use_split'] ) ) ) as f: txt_paths = f.read().splitlines() # if using only one source of clothing if clothing_option == 'nongrey': txt_paths = [k for k in txt_paths if 'nongrey' in k] elif clothing_option == 'grey': txt_paths = [k for k in txt_paths if 'nongrey' not in k] # random clothing texture cloth_img_name = choice(txt_paths) cloth_img_name = join(smpl_data_folder, cloth_img_name) cloth_img = bpy.data.images.load(cloth_img_name) # random background bg_img_name = choice(nh_txt_paths)[:-1] bg_img = bpy.data.images.load(bg_img_name) log_message("Loading parts segmentation") beta_stds = np.load(join(smpl_data_folder, ('%s_beta_stds.npy' % gender))) log_message("Building materials tree") mat_tree = bpy.data.materials['Material'].node_tree create_sh_material(mat_tree, sh_dst, cloth_img) res_paths = create_composite_nodes(scene.node_tree, params, img=bg_img, idx=idx) log_message("Loading smpl data") smpl_data = np.load(join(smpl_data_folder, smpl_data_filename)) log_message("Initializing scene") camera_distance = np.random.normal(8.0, 1) params['camera_distance'] = camera_distance ob, obname, arm_ob, cam_ob = init_scene(scene, params, gender) setState0() ob.select = True bpy.context.scene.objects.active = ob segmented_materials = True #True: 0-24, False: expected to have 0-1 bg/fg log_message("Creating materials segmentation") # create material segmentation if segmented_materials: materials = create_segmentation(ob, params) prob_dressed = {'leftLeg':.5, 'leftArm':.9, 'leftHandIndex1':.01, 'rightShoulder':.8, 'rightHand':.01, 'neck':.01, 'rightToeBase':.9, 'leftShoulder':.8, 'leftToeBase':.9, 'rightForeArm':.5, 'leftHand':.01, 'spine':.9, 'leftFoot':.9, 'leftUpLeg':.9, 'rightUpLeg':.9, 'rightFoot':.9, 'head':.01, 'leftForeArm':.5, 'rightArm':.5, 'spine1':.9, 'hips':.9, 'rightHandIndex1':.01, 'spine2':.9, 'rightLeg':.5} else: materials = {'FullBody': bpy.data.materials['Material']} prob_dressed = {'FullBody': .6} orig_pelvis_loc = (arm_ob.matrix_world.copy() * arm_ob.pose.bones[obname+'_Pelvis'].head.copy()) - Vector((-1., 1., 1.)) orig_cam_loc = cam_ob.location.copy() # unblocking both the pose and the blendshape limits for k in ob.data.shape_keys.key_blocks.keys(): bpy.data.shape_keys["Key"].key_blocks[k].slider_min = -10 bpy.data.shape_keys["Key"].key_blocks[k].slider_max = 10 log_message("Loading body data") cmu_parms, fshapes, name = load_body_data(smpl_data, ob, obname, idx=idx, gender=gender) log_message("Loaded body data for %s" % name) nb_fshapes = len(fshapes) if idx_info['use_split'] == 'train': fshapes = fshapes[:int(nb_fshapes*0.8)] elif idx_info['use_split'] == 'test': fshapes = fshapes[int(nb_fshapes*0.8):] # pick random real body shape shape = choice(fshapes) #+random_shape(.5) can add noise #shape = random_shape(3.) # random body shape # example shapes #shape = np.zeros(10) #average #shape = np.array([ 2.25176191, -3.7883464 , 0.46747496, 3.89178988, 2.20098416, 0.26102114, -3.07428093, 0.55708514, -3.94442258, -2.88552087]) #fat #shape = np.array([-2.26781107, 0.88158132, -0.93788176, -0.23480508, 1.17088298, 1.55550789, 0.44383225, 0.37688275, -0.27983086, 1.77102953]) #thin #shape = np.array([ 0.00404852, 0.8084637 , 0.32332591, -1.33163664, 1.05008727, 1.60955275, 0.22372946, -0.10738459, 0.89456312, -1.22231216]) #short #shape = np.array([ 3.63453289, 1.20836171, 3.15674431, -0.78646793, -1.93847355, -0.32129994, -0.97771656, 0.94531640, 0.52825811, -0.99324327]) #tall ndofs = 10 scene.objects.active = arm_ob orig_trans = np.asarray(arm_ob.pose.bones[obname+'_Pelvis'].location).copy() # create output directory if not exists(output_path): mkdir_safe(output_path) # spherical harmonics material needs a script to be loaded and compiled scs = [] for mname, material in materials.items(): scs.append(material.node_tree.nodes['Script']) scs[-1].filepath = sh_dst scs[-1].update() rgb_dirname = name.replace(" ", "") + '_c%04d.mp4' % (ishape + 1) rgb_path = join(tmp_path, rgb_dirname) data = cmu_parms[name] fbegin = ishape*stepsize*stride fend = min(ishape*stepsize*stride + stepsize*clipsize, len(data['poses'])) log_message("Computing how many frames to allocate") N = len(data['poses'][fbegin:fend:stepsize]) log_message("Allocating %d frames in mat file" % N) # force recomputation of joint angles unless shape is all zeros curr_shape = np.zeros_like(shape) nframes = len(data['poses'][::stepsize]) matfile_info = join(output_path, name.replace(" ", "") + "_c%04d_info.mat" % (ishape+1)) log_message('Working on %s' % matfile_info) # allocate dict_info = {} dict_info['bg'] = np.zeros((N,), dtype=np.object) # background image path dict_info['camLoc'] = np.empty(3) # (1, 3) dict_info['clipNo'] = ishape +1 dict_info['cloth'] = np.zeros((N,), dtype=np.object) # clothing texture image path dict_info['gender'] = np.empty(N, dtype='uint8') # 0 for male, 1 for female dict_info['joints2D'] = np.empty((2, 24, N), dtype='float32') # 2D joint positions in pixel space dict_info['joints3D'] = np.empty((3, 24, N), dtype='float32') # 3D joint positions in world coordinates dict_info['light'] = np.empty((9, N), dtype='float32') dict_info['pose'] = np.empty((data['poses'][0].size, N), dtype='float32') # joint angles from SMPL (CMU) dict_info['sequence'] = name.replace(" ", "") + "_c%04d" % (ishape + 1) dict_info['shape'] = np.empty((ndofs, N), dtype='float32') dict_info['zrot'] = np.empty(N, dtype='float32') dict_info['camDist'] = camera_distance dict_info['stride'] = stride if name.replace(" ", "").startswith('h36m'): dict_info['source'] = 'h36m' else: dict_info['source'] = 'cmu' if(output_types['vblur']): dict_info['vblur_factor'] = np.empty(N, dtype='float32') # for each clipsize'th frame in the sequence get_real_frame = lambda ifr: ifr random_zrot = 0 reset_loc = False batch_it = 0 curr_shape = reset_joint_positions(orig_trans, shape, ob, arm_ob, obname, scene, cam_ob, smpl_data['regression_verts'], smpl_data['joint_regressor']) random_zrot = 2*np.pi*np.random.rand() arm_ob.animation_data_clear() cam_ob.animation_data_clear() arm_ob.rotation_euler.x -= math.pi / 2 # create a keyframe animation with pose, translation, blendshapes and camera motion # LOOP TO CREATE 3D ANIMATION for seq_frame, (pose, trans) in enumerate(zip(data['poses'][fbegin:fend:stepsize], data['trans'][fbegin:fend:stepsize])): iframe = seq_frame scene.frame_set(get_real_frame(seq_frame)) # apply the translation, pose and shape to the character apply_trans_pose_shape(Vector(trans), pose, shape, ob, arm_ob, obname, scene, cam_ob, get_real_frame(seq_frame)) dict_info['shape'][:, iframe] = shape[:ndofs] dict_info['pose'][:, iframe] = pose dict_info['gender'][iframe] = list(genders)[list(genders.values()).index(gender)] if(output_types['vblur']): dict_info['vblur_factor'][iframe] = vblur_factor arm_ob.pose.bones[obname+'_root'].rotation_quaternion = Quaternion(Euler((0, 0, random_zrot), 'XYZ')) arm_ob.pose.bones[obname+'_root'].keyframe_insert('rotation_quaternion', frame=get_real_frame(seq_frame)) dict_info['zrot'][iframe] = random_zrot scene.update() # Bodies centered only in each minibatch of clipsize frames if seq_frame == 0 or reset_loc: reset_loc = False new_pelvis_loc = arm_ob.matrix_world.copy() * arm_ob.pose.bones[obname+'_Pelvis'].head.copy() rotated_orig = Vector([orig_pelvis_loc.copy()[0], orig_pelvis_loc.copy()[2], -orig_pelvis_loc.copy()[1]]) cam_ob.location = orig_cam_loc.copy() + (new_pelvis_loc.copy() - rotated_orig.copy()) cam_ob.keyframe_insert('location', frame=get_real_frame(seq_frame)) dict_info['camLoc'] = np.array(cam_ob.location) scene.node_tree.nodes['Image'].image = bg_img for part, material in materials.items(): material.node_tree.nodes['Vector Math'].inputs[1].default_value[:2] = (0, 0) # random light sh_coeffs = .7 * (2 * np.random.rand(9) - 1) sh_coeffs[0] = .5 + .9 * np.random.rand() # Ambient light (first coeff) needs a minimum is ambient. Rest is uniformly distributed, higher means brighter. sh_coeffs[1] = -.7 * np.random.rand() for ish, coeff in enumerate(sh_coeffs): for sc in scs: sc.inputs[ish+1].default_value = coeff # iterate over the keyframes and render # LOOP TO RENDER for seq_frame, (pose, trans) in enumerate(zip(data['poses'][fbegin:fend:stepsize], data['trans'][fbegin:fend:stepsize])): scene.frame_set(get_real_frame(seq_frame)) iframe = seq_frame dict_info['bg'][iframe] = bg_img_name dict_info['cloth'][iframe] = cloth_img_name dict_info['light'][:, iframe] = sh_coeffs scene.render.use_antialiasing = False scene.render.filepath = join(rgb_path, 'Image%04d.png' % get_real_frame(seq_frame)) log_message("Rendering frame %d" % seq_frame) # disable render output logfile = '/dev/null' open(logfile, 'a').close() old = os.dup(1) sys.stdout.flush() os.close(1) os.open(logfile, os.O_WRONLY) # Render bpy.ops.render.render(write_still=True) # disable output redirection os.close(1) os.dup(old) os.close(old) # NOTE: # ideally, pixels should be readable from a viewer node, but I get only zeros # --> https://ammous88.wordpress.com/2015/01/16/blender-access-render-results-pixels-directly-from-python-2/ # len(np.asarray(bpy.data.images['Render Result'].pixels) is 0 # Therefore we write them to temporary files and read with OpenEXR library (available for python2) in main_part2.py # Alternatively, if you don't want to use OpenEXR library, the following commented code does loading with Blender functions, but it can cause memory leak. # If you want to use it, copy necessary lines from main_part2.py such as definitions of dict_normal, matfile_normal... #for k, folder in res_paths.items(): # if not k== 'vblur' and not k=='fg': # path = join(folder, 'Image%04d.exr' % get_real_frame(seq_frame)) # render_img = bpy.data.images.load(path) # # render_img.pixels size is width * height * 4 (rgba) # arr = np.array(render_img.pixels[:]).reshape(resx, resy, 4)[::-1,:, :] # images are vertically flipped # if k == 'normal':# 3 channels, original order # mat = arr[:,:, :3] # dict_normal['normal_%d' % (iframe + 1)] = mat.astype(np.float32, copy=False) # elif k == 'gtflow': # mat = arr[:,:, 1:3] # dict_gtflow['gtflow_%d' % (iframe + 1)] = mat.astype(np.float32, copy=False) # elif k == 'depth': # mat = arr[:,:, 0] # dict_depth['depth_%d' % (iframe + 1)] = mat.astype(np.float32, copy=False) # elif k == 'segm': # mat = arr[:,:,0] # dict_segm['segm_%d' % (iframe + 1)] = mat.astype(np.uint8, copy=False) # # # remove the image to release memory, object handles, etc. # render_img.user_clear() # bpy.data.images.remove(render_img) # bone locations should be saved after rendering so that the bones are updated bone_locs_2D, bone_locs_3D = get_bone_locs(obname, arm_ob, scene, cam_ob) dict_info['joints2D'][:, :, iframe] = np.transpose(bone_locs_2D) dict_info['joints3D'][:, :, iframe] = np.transpose(bone_locs_3D) reset_loc = (bone_locs_2D.max(axis=-1) > 256).any() or (bone_locs_2D.min(axis=0) < 0).any() arm_ob.pose.bones[obname+'_root'].rotation_quaternion = Quaternion((1, 0, 0, 0)) # save a .blend file for debugging: # bpy.ops.wm.save_as_mainfile(filepath=join(tmp_path, 'pre.blend')) # save RGB data with ffmpeg (if you don't have h264 codec, you can replace with another one and control the quality with something like -q:v 3) cmd_ffmpeg = 'ffmpeg -y -r 30 -i ''%s'' -c:v h264 -pix_fmt yuv420p -crf 23 ''%s_c%04d.mp4''' % (join(rgb_path, 'Image%04d.png'), join(output_path, name.replace(' ', '')), (ishape + 1)) log_message("Generating RGB video (%s)" % cmd_ffmpeg) os.system(cmd_ffmpeg) if(output_types['vblur']): cmd_ffmpeg_vblur = 'ffmpeg -y -r 30 -i ''%s'' -c:v h264 -pix_fmt yuv420p -crf 23 -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" ''%s_c%04d.mp4''' % (join(res_paths['vblur'], 'Image%04d.png'), join(output_path, name.replace(' ', '')+'_vblur'), (ishape + 1)) log_message("Generating vblur video (%s)" % cmd_ffmpeg_vblur) os.system(cmd_ffmpeg_vblur) if(output_types['fg']): cmd_ffmpeg_fg = 'ffmpeg -y -r 30 -i ''%s'' -c:v h264 -pix_fmt yuv420p -crf 23 ''%s_c%04d.mp4''' % (join(res_paths['fg'], 'Image%04d.png'), join(output_path, name.replace(' ', '')+'_fg'), (ishape + 1)) log_message("Generating fg video (%s)" % cmd_ffmpeg_fg) os.system(cmd_ffmpeg_fg) cmd_tar = 'tar -czvf %s/%s.tar.gz -C %s %s' % (output_path, rgb_dirname, tmp_path, rgb_dirname) log_message("Tarballing the images (%s)" % cmd_tar) os.system(cmd_tar) # save annotation excluding png/exr data to _info.mat file import scipy.io scipy.io.savemat(matfile_info, dict_info, do_compression=True) if __name__ == '__main__': main()
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 21 17:08:55 2020 @author: anon """ import subprocess import numpy as np import h5py clear = np.zeros((100000, 2)) noisy = np.zeros((100000, 2)) for i in range(1, len(clear)): clear[i] = clear[i-1] + np.array([1.,1.]) noisy[i] = clear[i] + np.random.normal(scale=20., size=2) with h5py.File('../data/input.h5', 'w') as h5f: h5f.create_dataset('clear', data=clear) h5f.create_dataset('noisy', data=noisy) #Run kf aplication here subprocess.call(['../projects/bin/Debug/hdf5_test']) with h5py.File('../data/output.h5', 'r') as h5f: kf_out = h5f['kf_out'][:]
python
import sys from pyramid.config import Configurator from pyramid.i18n import get_localizer, TranslationStringFactory from pyramid.threadlocal import get_current_request def add_renderer_globals(event): request = event.get('request') if request is None: request = get_current_request() event['_'] = request.translate event['gettext'] = request.translate event['ngettext'] = request.pluralize event['localizer'] = request.localizer def configure_i18n(config: Configurator, default_domain: str): config.add_subscriber(add_renderer_globals, 'pyramid.events.BeforeRender') config.add_subscriber(add_renderer_globals, 'tet.viewlet.IBeforeViewletRender') config.registry.tsf = tsf = TranslationStringFactory(default_domain) def translate(request): localizer = request.localizer def auto_translate(string, *, domain=default_domain, mapping=None, context=None): if isinstance(string, str): string = tsf(string, context=context) return localizer.translate(string, domain=domain, mapping=mapping) return auto_translate def pluralize(request): localizer = request.localizer def auto_pluralize(singular, plural, n, *, domain=default_domain, mapping=None, context=None): if isinstance(singular, str): singular = tsf(singular, context=context) return localizer.pluralize(singular, plural, n, domain=domain, mapping=mapping) return auto_pluralize config.add_request_method(translate, property=True, reify=True) config.add_request_method(pluralize, property=True, reify=True) config.add_request_method(get_localizer, name='localize', property=True, reify=True) def includeme(config: Configurator): default_domain = config.get_settings().get('default_i18n_domain', config.package.__name__) configure_i18n(config, default_domain)
python
Given a binary array nums, return the maximum number of consecutive 1's in the array. Example 1: Input: nums = [1,1,0,1,1,1] Output: 3 Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. Example 2: Input: nums = [1,0,1,1,0,1] Output: 2 class Solution: def findMaxConsecutiveOnes(self, nums: List[int]) -> int: sum = 0 lst= [] for i in range(len(nums)): if nums[i] != 0: sum += 1 if nums[i] == len(nums)-1: lst.append(sum) else: lst.append(sum) sum = 0 lst.append(sum) print(lst) return max(lst)
python
#!/usr/bin/env python3 # for now assuming the 'derived' repo is just checked out import fire, yaml, git, os, shutil, sys, pathlib, subprocess, unidiff, time, logging from neotermcolor import colored def bold_yellow(text): return colored(text, color='yellow', attrs='bold') conf_file = ".differant.yml" def dirdiff(directory: str): "Either a function to diff directories, or a city in Wales, close to Dirham and Dirwick." f = open(f'{directory}/{conf_file}', 'r') conf = yaml.safe_load(f) f.close() upstream = directory + '-upstream' derived = directory + '-derived' if not os.path.isdir(upstream): repo = git.Repo.clone_from(conf['upstream'], upstream, depth=1, branch=conf['tag']) else: print(f"Skipping clone, upstream directory {upstream} exists.") if not os.path.isdir(derived): shutil.copytree(directory, derived) else: print(f"Skipping copy, derived directory {derived} exists.") for path in [conf_file, '.git']: shutil.rmtree(upstream+'/'+path, ignore_errors=True) shutil.rmtree(derived+'/'+path, ignore_errors=True) for i in conf['ignores']: what, why = i['what'], i['why'] # this is only applicable to Linux! if os.path.isabs(what) or what.find('..') != -1: print(f'Nice try. Ignoring directory {what}, please do not use absolute paths and parent folders.') continue print(f"Removing {what}, reason: {why}") shutil.rmtree(upstream+'/'+what, ignore_errors=True) shutil.rmtree(derived+'/'+what, ignore_errors=True) # let's diff the dirs now, and parse this into a Python patchset object result = subprocess.run(f"git diff --no-index {upstream} {derived}".split(' '), stdout=subprocess.PIPE) result_output = result.stdout.decode('utf-8') patchset = unidiff.PatchSet(result_output) refactors = conf.get('refactors', [])#['refactors'] known = conf.get('known_changes', [])#['known_changes'] if 'known'or [] # create empty arrays to store associated patches for r in refactors: r['patches'] = [] for k in known: k['patches'] = [] remaining = [] for p in patchset: p.only_refactors = False p.empty = False p.known = None if p.added == 0 and p.removed == 0: p.empty = True else: check_if_refactor(p, refactors) check_if_known(p, known, directory) if not p.known and not p.empty and not p.only_refactors: remaining.append(p) #print("Patch which only includes known refactors.") #p.refactors = [dict(x) for x in p.refactors] def get_size(patch): return patch.added + patch.removed known_patches = [p for p in patchset if p.known] refactor_only_patches = [p for p in patchset if p.only_refactors] empty_patches = [p for p in patchset if p.empty] l = sorted(remaining, key=get_size, reverse=True) print("\n".join([str(p) for p in l])) print(f"{len(known_patches)} known patches.") print(f"{len(refactor_only_patches)} refactor only patches.") print(f"{len(empty_patches)} empty_patches.") print(f"{len(remaining)} patches remain.") from fnmatch import fnmatch def check_if_known(patch, known, directory): for k in known: for f in k['files']: src = patch.source_file[2:].replace(directory+'-upstream/', '') tgt = patch.target_file[2:].replace(directory+'-derived/', '') if fnmatch(src, f) or fnmatch(tgt, f): k['patches'].append(patch) patch.known = k['change'] return True return False def check_if_refactor(patch, refactors): for hunk in patch: added = "".join([str(x)[1:] for x in hunk if x.line_type == unidiff.LINE_TYPE_ADDED]) removed = "".join([str(x)[1:] for x in hunk if x.line_type == unidiff.LINE_TYPE_REMOVED]) after_refactor = removed for r in refactors: was_added = False r_from, r_to = r['from'], r['to'] if after_refactor.find(r_from) != -1: r['patches'].append(patch) after_refactor = after_refactor.replace(r_from, r_to) if added == after_refactor: pass # print("Lines equal after applying refactors.") else: return False patch.only_refactors = True return True from watchdog.events import FileSystemEventHandler from watchdog.observers import Observer class DiffingHandler(FileSystemEventHandler): def __init__(self, directory): self.directory = directory def on_modified(self, event): if event.src_path == f"{self.directory}/{conf_file}": print(bold_yellow(f'Change in {conf_file} detected, rerunning dirdiff again!')) dirdiff(self.directory) print(bold_yellow('Continuing to watch for changes...')) def watch(directory: str, override: bool = False, interactive: bool = False): if not shutil.rmtree.avoids_symlink_attacks: print("Sorry, but your system is susceptible to symlink attacks. Consider switching. Exiting.") sys.exit(1) directory = directory.rstrip('/') abspath = os.path.abspath(directory) if abspath in pathlib.Path(os.getcwd()).parents or abspath == os.getcwd(): print("Please do not call dirdiff from inside of the target directory.") sys.exit(1) upstream = directory + '-upstream' derived = directory + '-derived' if override == True: shutil.rmtree(upstream) shutil.rmtree(derived) print(bold_yellow('Running dirdiff.')) dirdiff(directory) if interactive: print(f'Starting to watch {bold_yellow(directory+"/"+conf_file)} for changes...') observer = Observer() observer.schedule(DiffingHandler(directory), path=directory, recursive=True) observer.start() try: while True: time.sleep(1) finally: observer.stop() observer.join() if __name__ == "__main__": fire.Fire(watch)
python
from __future__ import print_function import os from importlib import import_module def split_path(path): decomposed_path = [] while 1: head, tail = os.path.split(path) if head == path: # sentinel for absolute paths decomposed_path.insert(0, head) break elif tail == path: # sentinel for relative paths decomposed_path.insert(0, tail) break else: path = head decomposed_path.insert(0, tail) if not decomposed_path[-1]: decomposed_path = decomposed_path[:-1] return decomposed_path def split_migration_path(migration_path): from django.db.migrations.loader import MIGRATIONS_MODULE_NAME decomposed_path = split_path(migration_path) for i, p in enumerate(decomposed_path): if p == MIGRATIONS_MODULE_NAME: return decomposed_path[i - 1], os.path.splitext(decomposed_path[i + 1])[0] def clean_bytes_to_str(byte_input): return byte_input.decode("utf-8").strip() def get_migration_abspath(app_label, migration_name): from django.db.migrations.loader import MigrationLoader module_name, _ = MigrationLoader.migrations_module(app_label) migration_path = "{}.{}".format(module_name, migration_name) migration_module = import_module(migration_path) migration_file = migration_module.__file__ if migration_file.endswith(".pyc"): migration_file = migration_file[:-1] return migration_file
python
import pytest from constructure.constructors import RDKitConstructor from constructure.scaffolds import SCAFFOLDS @pytest.mark.parametrize("scaffold", SCAFFOLDS.values()) def test_default_scaffolds(scaffold): # Make sure the number of R groups in the `smiles` pattern matches the `r_groups` # attributes. assert RDKitConstructor.n_replaceable_groups(scaffold) == len(scaffold.r_groups) assert {*scaffold.r_groups} == {i + 1 for i in range(len(scaffold.r_groups))}
python
from capturewrap.builders import CaptureWrapBuilder from capturewrap.models import CaptureResult
python
import flask from hacktech import auth_utils from hacktech import app_year import hacktech.modules.judging.helpers as judging_helpers from hacktech.modules.applications.helpers import allowed_file from werkzeug.utils import secure_filename import os import PyPDF2 def get_waiver_status(user_id, waiver_type): query = """ SELECT {0}_status FROM {0} where user_id = %s""".format(waiver_type) with flask.g.pymysql_db.cursor() as cursor: cursor.execute(query, user_id) res = cursor.fetchone() key = "{0}_status".format(waiver_type) return "Not Submitted" if res == None else res[key] def get_full_name(uid): query = "SELECT first_name, last_name FROM members WHERE user_id = %s" with flask.g.pymysql_db.cursor() as cursor: cursor.execute(query, uid) res = cursor.fetchone() if res is None: return ("", "") return (res['first_name'], res['last_name']) def save_info(email, waiver_file, app_folder, waiver_type): uid = auth_utils.get_user_id(email) first_name, last_name = get_full_name(uid) waiver_file_name = last_name + "_" + first_name + "_" + str(uid) + ".pdf" waiver_root_path = os.path.join(flask.current_app.root_path, flask.current_app.config[app_folder]) waiver_path = os.path.join(waiver_root_path, waiver_file_name) print(waiver_file, allowed_file(waiver_file)) if waiver_file and allowed_file(waiver_file): if os.path.exists(waiver_path): os.remove(waiver_path) waiver_file.save(waiver_path) query = "INSERT INTO {0}(user_id, {0}_path, {0}_status, submitted_time) VALUES (%s, %s, 'Submitted', NOW()) ON DUPLICATE KEY UPDATE {0}_status = 'Submitted', submitted_time = NOW()".format( waiver_type) with flask.g.pymysql_db.cursor() as cursor: cursor.execute(query, [uid, waiver_file_name]) return waiver_path return ""
python
from bflib import dice, units from bflib.items import coins, listing from bflib.items.ammunition.common import ShortbowArrow, LongbowArrow from bflib.items.weapons.ranged.base import RangedWeapon from bflib.rangeset import RangeSet from bflib.sizes import Size @listing.register_type class Bow(RangedWeapon): pass @listing.register_item class Shortbow(Bow): name = "Shortbow" melee_damage = dice.D2(1) ranged_range = RangeSet(units.Feet(50), units.Feet(100), units.Feet(150)) ranged_damage = None ranged_ammunition_type = ShortbowArrow price = coins.Gold(2) size = Size.Small weight = units.Pound(1) @listing.register_item class Longbow(Bow): name = "Longbow" melee_damage = dice.D2(1) ranged_range = RangeSet(units.Feet(70), units.Feet(140), units.Feet(210)) ranged_damage = None ranged_ammunition_type = LongbowArrow price = coins.Silver(2) size = Size.Large weight = units.Pound(3)
python
# Authors: Guillaume Favelier <[email protected]> # # License: Simplified BSD from ...fixes import nullcontext from ._pyvista import _Renderer as _PyVistaRenderer from ._pyvista import \ _close_all, _set_3d_view, _set_3d_title # noqa: F401 analysis:ignore class _Renderer(_PyVistaRenderer): def __init__(self, *args, **kwargs): kwargs["notebook"] = True super().__init__(*args, **kwargs) def show(self): from IPython.display import display self.figure.display = self.plotter.show(use_ipyvtk=True, return_viewer=True) self.figure.display.layout.width = None # unlock the fixed layout display(self.figure.display) return self.scene() _testing_context = nullcontext
python
import matplotlib.pyplot as plt import numpy as np tolerance = 1e-1 radius = np.pi # missile 1 x_m1, y_m1 = -np.pi, 0 v_m1 = 5 # missile 2 x_m2, y_m2 = 0, np.pi v_m2 = v_m1 # missile 3 x_m3, y_m3 = np.pi, 0 v_m3 = v_m1 # missile 4 x_m4, y_m4 = 0, -np.pi v_m4 = v_m1 plt.figure(figsize=(10, 10), dpi=80) plt.title(" missile flight simulator ", fontsize=40) plt.xlim(-4, 4) plt.ylim(-4, 4) #plt.xticks([]) #plt.yticks([]) # set spines ax = plt.gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data', 0)) ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data', 0)) plt.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']) plt.yticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']) plt.annotate('missile start point', xy=(x_m1, y_m1), xycoords='data', xytext=(+15, +15), textcoords='offset points', fontsize=12, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) # alpha labels for label in ax.get_xticklabels() + ax.get_yticklabels(): label.set_fontsize(16) label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65)) class ob(object): """docstring for ob""" def __init__(self, x, y): self.x = x self.y = y class missile(ob): """docstring for missile""" def __init__(self, x, y): super(missile, self).__init__(x, y) def forward(self, v, target): """docstring for forward""" if self.x < target.x: alpha = np.arctan((target.y - self.y) / (target.x - self.x)) elif self.x > target.x: alpha = np.pi + np.arctan((target.y - self.y) / (target.x - self.x)) elif self.x == target.x and self.y < target.y: alpha = np.pi / 2 else: alpha = -np.pi / 2 self.x = self.x + v * 0.01 * np.cos(alpha) self.y = self.y + v * 0.01 * np.sin(alpha) return self.x, self.y def distance(self, target): """docstring for distance""" return np.sqrt((self.x - target.x) ** 2 + (self.y - target.y) ** 2) class target(ob): """docstring for target""" def __init__(self, x, y): super(target, self).__init__(x, y) def newposition(self, x, y): """docstring for newposition""" self.x = x self.y = y m1 = missile(x_m1, y_m1) m2 = missile(x_m2, y_m2) m3 = missile(x_m3, y_m3) m4 = missile(x_m4, y_m4) while True: if m1.distance(m2) < tolerance or m1.distance(m3) < tolerance or m1.distance(m4) < tolerance: print "collision" plt.plot(x_m1, y_m1, 'o') plt.annotate('crash point', xy=(x_m1, y_m1), xycoords='data', xytext=(+15, +15), textcoords='offset points', fontsize=12, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) plt.pause(0.1) plt.show() break elif m3.distance(m2) < tolerance or m3.distance(m4) < tolerance: print "collision" plt.plot(x_m3, y_m3, 'o') plt.annotate('crash point', xy=(x_m3, y_m3), xycoords='data', xytext=(+15, +15), textcoords='offset points', fontsize=12, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) plt.pause(0.1) plt.show break x_m1, y_m1 = m1.forward(v_m1, m2) x_m2, y_m2 = m2.forward(v_m2, m3) x_m3, y_m3 = m3.forward(v_m3, m4) x_m4, y_m4 = m4.forward(v_m4, m1) #print alpha, beta plt.plot(x_m1, y_m1, 'bx', alpha=.5) plt.plot(x_m2, y_m2, 'k*', alpha=.5) plt.plot(x_m3, y_m3, 'r.', alpha=.5) plt.plot(x_m4, y_m4, 'gp', alpha=.5) plt.legend(("missile1", "missile2", "missile3", "missile4"), loc="upper left", prop={'size': 12}) plt.pause(0.1)
python
import framebuf gc.collect() import time gc.collect() import machine gc.collect() import neopixel gc.collect() import network gc.collect() import urequests gc.collect() import utime gc.collect() from machine import RTC, I2C, Pin #from ssd1306 import SSD1306_I2C import sh1106 #Oled gc.collect() import freesans20 # letter 20 gc.collect() import icons8x8 gc.collect() import writer # escribe letra y grafico gc.collect() n = 64 # 8x8=64 p = 14 # pin d1 np = neopixel.NeoPixel(machine.Pin(p), n) #Delay for showing image delay = 15 #Clear the screen def clear(): for i in range(64): np[i] = (0x00, 0x00, 0x00) np.write() clear() # display cool guy for values in icons8x8.cool: np[values] = (255, 255, 0) np[16]= (0x99,0x99,0x99) np[21]= (0x99,0x99,0x99) np.write() sleep(7) def load_image(filename): with open(filename, 'rb') as f: f.readline() f.readline() width, height = [int(v) for v in f.readline().split()] data = bytearray(f.read()) return framebuf.FrameBuffer(data, width, height, framebuf.MONO_HLSB) # SSD1106 OLED display print("Connecting to wifi...") display = sh1106.SH1106_I2C(128, 64, I2C(scl=Pin(5), sda=Pin(4), freq=400000)) #display.fill(1) #importa font y grafico .pbm font_writer = writer.Writer(display, freesans20) temperature_pbm = load_image('temperature.pbm') #humidity_pbm = load_image('humidity.pbm') #display en Oled display.fill(0) display.text("Connecting", 0, 5) display.text(" to wifi...", 0, 15) display.show() time.sleep_ms(3000) # Espera 3 segundos #Setup WiFi sta = network.WLAN(network.STA_IF) sta.active(True) sta.connect("LIZCANO", "Paris2006") print(sta.isconnected()) #display(3) display.fill(0) display.text("Connected !!!", 0, 5) display.text(" to wifi...", 0, 15) display.show() # wifi connected print("IP:", sta.ifconfig()[0], "\n") display.text(" IP: ", 0, 35) display.text(" " + str(sta.ifconfig()[0]), 0, 45) display.show() # clock data url = "http://worldtimeapi.org/api/timezone/America/Bogota" # see http://worldtimeapi.org/timezones web_query_delay = 60000 # interval time of web JSON query retry_delay = 3000 # interval time of retry after a failed Web query # internal real time clock rtc = RTC() # set timer update_time = utime.ticks_ms() - web_query_delay #setup the button button = machine.Pin(13, machine.Pin.IN, machine.Pin.PULL_UP) # Confirma OK clear() for values in icons8x8.ok1: np[values] = (20, 200, 20) np.write() for values in icons8x8.ok2: np[values] = (20, 50, 20) np.write() sleep(8) clear() # clear ok display.fill(0) display.show() # apaga oled while True: print(button.value()) if button.value() == 0: # clock loop while button.value() == 0: # True: # if lose wifi connection, reboot ESP8266 if not sta.isconnected(): machine.reset() # query and get web JSON every web_query_delay ms if utime.ticks_ms() - update_time >= web_query_delay: # HTTP GET data response = urequests.get("http://worldtimeapi.org/api/timezone/America/Bogota") if response.status_code == 200: # query success print("JSON response:\n", response.text) # parse JSON parsed = response.json() datetime_str = str(parsed["datetime"]) year = int(datetime_str[0:4]) month = int(datetime_str[5:7]) day = int(datetime_str[8:10]) hour = int(datetime_str[11:13]) minute = int(datetime_str[14:16]) second = int(datetime_str[17:19]) subsecond = int(round(int(datetime_str[20:26]) / 10000)) # update internal RTC rtc.datetime((year, month, day, 0, hour, minute, second, subsecond)) update_time = utime.ticks_ms() print("RTC updated\n") else: # query failed, retry retry_delay ms later update_time = utime.ticks_ms() - web_query_delay + retry_delay # generate formated date/time strings from internal RTC date_str = "{1:02d}/{2:02d}/{0:4d}".format(*rtc.datetime()) time_str = "{4:02d}:{5:02d}:{6:02d}".format(*rtc.datetime()) # update SSD1306 OLED display display.fill(0) #display.text("WebClock", 0, 5) textlen_h = font_writer.stringlen(time_str) textlen_d = font_writer.stringlen(date_str) font_writer.set_textpos((128 - textlen_h) // 2, 10) font_writer.printstring(time_str) #font_writer.set_textpos((128 - textlen_d) // 2, 50) #font_writer.printstring(date_str) display.text(date_str, 25, 55) #display.text(time_str, 0, 45) display.show() utime.sleep(0.1) if button.value() == 1: r = urequests.get("http://api.openweathermap.org/data/2.5/weather?q=Cajica,CO&appid=a2200cf760d109aeb26996d0188b06c9&units=metric").json() weather = r["weather"][0]["main"] weather2 = r["weather"][0]["description"] temp = r["main"]["temp"] print(weather) print(weather2) print(temp) display.fill(0) # apaga oled display.show() # apaga oled if weather == "Clear": for values in icons8x8.sun0: np[values] = (0x4c, 0x99, 0x00) np.write() sleep(1) for values in icons8x8.sun1: np[values] = (0x4c, 0x99, 0x00) np.write() sleep(1) for values in icons8x8.sun2: np[values] = (0x4c, 0x99, 0x00) np.write() sleep(0.2) sleep(delay) # cool guy clear() # clear neopixel for values in icons8x8.cool: np[values] = (255, 255, 0) np.write() np[16]= (0x99,0x99,0x99) np[21]= (0x99,0x99,0x99) sleep(0.3) np.write() np[16]= (0,0,0) np[21]= (0,0,0) sleep(0.3) np[16]= (0x99,0x99,0x99) np[21]= (0x99,0x99,0x99) sleep(0.3) np.write() sleep(delay) display.fill(0) # apaga oled display.show() # apaga oled clear() # clear neopixel elif weather2 == "few clouds": display.text("Outside: ", 0, 10) display.text(weather2, 0, 20) display.text("Temperature: " + str(temp), 0, 40) #display.text(str(temp), 35, 35) #display.text(" to wifi...", 0, 15) display.show() for values in icons8x8.fewclouds1: np[values] = (0x99, 0x99, 0x99) np.write() for values in icons8x8.fewclouds2: np[values] = (0x25, 0x25, 0x25) np.write() for values in icons8x8.fewclouds3: np[values] = (250,140,0) np.write() sleep(0.5) for values in icons8x8.fewclouds4: np[values] = (250, 250, 0) np.write() sleep(0.2) sleep(delay) display.fill(0) # apaga oled display.show() # apaga oled clear() # clear neopixel elif weather2 == "scattered clouds": display.text("Outside: ", 0, 10) display.text(weather2, 0, 20) display.text("Temperature: " + str(temp), 0, 40) #display.text(str(temp), 35, 35) #display.text(" to wifi...", 0, 15) display.show() for values in icons8x8.fewclouds1: np[values] = (0x99, 0x99, 0x99) np.write() for values in icons8x8.fewclouds2: np[values] = (0x25, 0x25, 0x25) np.write() for values in icons8x8.fewclouds3: np[values] = (250,140,0) np.write() sleep(0.5) for values in icons8x8.fewclouds4: np[values] = (250, 250, 0) np.write() sleep(0.2) sleep(delay) display.fill(0) # apaga oled display.show() # apaga oled clear() # clear neopixel elif weather2 == "broken clouds": display.text("Outside: ", 0, 10) display.text(weather2, 0, 20) display.text("Temperature: " + str(temp), 0, 40) #display.text(str(temp), 35, 35) #display.text(" to wifi...", 0, 15) display.show() for values in icons8x8.cloudy: np[values] = (0x99, 0x99, 0x99) np.write() sleep(delay) display.fill(0) # apaga oled display.show() # apaga oled clear() # clear neopixel elif weather == "Rain": display.text("Outside: ", 0, 10) display.text(weather2, 0, 20) display.text("Temperature: " + str(temp), 0, 40) for values in icons8x8.cloudy: np[values] = (0x55, 0x55, 0x55) np.write() sleep(1) for values in icons8x8.rain: np[values] = (0x00, 0x00, 0x99) np.write() sleep(delay) display.fill(0) # apaga oled display.show() # apaga oled clear() elif weather == "Thunderstorm": display.text("Outside: ", 0, 10) display.text(weather2, 0, 20) display.text("Temperature: " + str(temp), 0, 40) for values in icons8x8.cloudy: np[values] = (0x55, 0x55, 0x55) np.write() sleep(1) for values in icons8x8.lightning1: np[values] = (250, 250, 0x00) np.write() for values in icons8x8.lightning2: np[values] = (250, 153, 0) np.write() sleep(delay) display.fill(0) # apaga oled display.show() # apaga oled clear() elif weather == "Snow": display.text("Outside: ", 0, 10) display.text(weather2, 0, 20) display.text("Temperature: " + str(temp), 0, 40) for values in icons8x8.snow_ice: np[values] = (0x00, 0x00, 0x99) np.write() sleep(delay) display.fill(0) # apaga oled display.show() # apaga oled clear() sleep(1)
python
# Import modules import datetime import spiceypy import numpy as np import pandas as pd # Load the SPICE kernels via a meta file spiceypy.furnsh('kernel_meta.txt') # We want to compute miscellaneous positions w.r.t. the centre of # the Sun for a certain time interval. # First, we set an initial time in UTC. INIT_TIME_UTC = datetime.datetime(year=2000, month=1, day=1, \ hour=0, minute=0, second=0) # Add a number of days; you can play around with the datetime variables; but # leave it as it is for the first try, since other computations and comments # are based on this value. DELTA_DAYS = 10000 END_TIME_UTC = INIT_TIME_UTC + datetime.timedelta(days=DELTA_DAYS) # Convert the datetime objects now to strings INIT_TIME_UTC_STR = INIT_TIME_UTC.strftime('%Y-%m-%dT%H:%M:%S') END_TIME_UTC_STR = END_TIME_UTC.strftime('%Y-%m-%dT%H:%M:%S') # Print the starting and end times print('Init time in UTC: %s' % INIT_TIME_UTC_STR) print('End time in UTC: %s\n' % END_TIME_UTC_STR) # Convert to Ephemeris Time (ET) using the SPICE function utc2et INIT_TIME_ET = spiceypy.utc2et(INIT_TIME_UTC_STR) END_TIME_ET = spiceypy.utc2et(END_TIME_UTC_STR) # Create a numpy array that covers a time interval in delta = 1 day step TIME_INTERVAL_ET = np.linspace(INIT_TIME_ET, END_TIME_ET, DELTA_DAYS) #%% # Using km is not intuitive. AU would scale it too severely. Since we compute # the Solar System Barycentre (SSB) w.r.t. the Sun; and since we expect it to # be close to the Sun, we scale the x, y, z component w.r.t the radius of the # Sun. We extract the Sun radii (x, y, z components of the Sun ellipsoid) and # use the x component _, RADII_SUN = spiceypy.bodvcd(bodyid=10, item='RADII', maxn=3) RADIUS_SUN = RADII_SUN[0] #%% # All our computed parameters, positions etc. shall be stored in a pandas # dataframe. First, we create an empty one SOLAR_SYSTEM_DF = pd.DataFrame() # Set the column ET that stores all ETs SOLAR_SYSTEM_DF.loc[:, 'ET'] = TIME_INTERVAL_ET # The column UTC transforms all ETs back to a UTC format. The function # spicepy.et2datetime is NOT an official part of SPICE (there you can find # et2utc). # However this function returns immediately a datetime object SOLAR_SYSTEM_DF.loc[:, 'UTC'] = \ SOLAR_SYSTEM_DF['ET'].apply(lambda x: spiceypy.et2datetime(et=x).date()) # Here, the position of the SSB, as seen from the Sun, is computed. Since # spicepy.spkgps returns the position and the corresponding light time, # we add the index [0] to obtain only the position array SOLAR_SYSTEM_DF.loc[:, 'POS_SSB_WRT_SUN'] = \ SOLAR_SYSTEM_DF['ET'].apply(lambda x: spiceypy.spkgps(targ=0, \ et=x, \ ref='ECLIPJ2000', \ obs=10)[0]) # Now the SSB position vector is scaled with the Sun's radius SOLAR_SYSTEM_DF.loc[:, 'POS_SSB_WRT_SUN_SCALED'] = \ SOLAR_SYSTEM_DF['POS_SSB_WRT_SUN'].apply(lambda x: x / RADIUS_SUN) # Finally the distance between the Sun and the SSB is computed. The length # (norm) of the vector needs to be determined with the SPICE function vnorm(). # numpy provides an identical function in: numpy.linalg.norm() SOLAR_SYSTEM_DF.loc[:, 'SSB_WRT_SUN_SCALED_DIST'] = \ SOLAR_SYSTEM_DF['POS_SSB_WRT_SUN_SCALED'].apply(lambda x: \ spiceypy.vnorm(x)) #%% # Import the matplotlib library from matplotlib import pyplot as plt # Set a figure FIG, AX = plt.subplots(figsize=(12, 8)) # Plot the distance between the Sun and the SSB AX.plot(SOLAR_SYSTEM_DF['UTC'], SOLAR_SYSTEM_DF['SSB_WRT_SUN_SCALED_DIST'], \ color='tab:blue') # Set a label for the x and y axis and color the y ticks accordingly AX.set_xlabel('Date in UTC') AX.set_ylabel('SSB Dist. in Sun Radii', color='tab:blue') AX.tick_params(axis='y', labelcolor='tab:blue') # Set limits for the x and y axis AX.set_xlim(min(SOLAR_SYSTEM_DF['UTC']), max(SOLAR_SYSTEM_DF['UTC'])) AX.set_ylim(0, 2) # Set a grid AX.grid(axis='x', linestyle='dashed', alpha=0.5) # Saving the figure in high quality plt.savefig('SSB2SUN_DISTANCE.png', dpi=300) #%% # Additionally, we want to compute the position vector of all outer gas # giants. We define a dictionary with a planet's barycentre abbreviation and # corresponding NAIF ID code NAIF_ID_DICT = {'JUP': 5, \ 'SAT': 6, \ 'URA': 7, \ 'NEP': 8} # Iterate through the dictionary and compute the position vector for each # planet as seen from the Sun. Further, compute the phase angle between the # SSB and the planet as seen from the Sun for planets_name_key in NAIF_ID_DICT: # Define the pandas dataframe column for each planet (position and phase # angle). Each '%s' substring is replaced with the planets name as # indicated after the "%" planet_pos_col = 'POS_%s_WRT_SUN' % planets_name_key planet_angle_col = 'PHASE_ANGLE_SUN_%s2SSB' % planets_name_key # Get the corresponding NAIF ID of the planet's barycentre planet_id = NAIF_ID_DICT[planets_name_key] # Compute the planet's position as seen from the Sun. SOLAR_SYSTEM_DF.loc[:, planet_pos_col] = \ SOLAR_SYSTEM_DF['ET'].apply(lambda x: \ spiceypy.spkgps(targ=planet_id, \ et=x, \ ref='ECLIPJ2000', \ obs=10)[0]) # Compute the phase angle between the SSB and the planet as seen from the # Sun. Since we apply a lambda function on all columns we need to set # axis=1, otherwise we get an error! SOLAR_SYSTEM_DF.loc[:, planet_angle_col] = \ SOLAR_SYSTEM_DF.apply(lambda x: \ np.degrees(spiceypy.vsep(x[planet_pos_col], \ x['POS_SSB_WRT_SUN'])),\ axis=1) #%% # Let's verify the function vsep and compute the phase angle between the SSB # and Jupiter as seen from the Sun (we use the very first array entries). # Define a lambda function the computes the angle between two vectors COMP_ANGLE = lambda vec1, vec2: np.arccos(np.dot(vec1, vec2) \ / (np.linalg.norm(vec1) \ * np.linalg.norm(vec2))) print('Phase angle between the SSB and Jupiter as seen from the Sun (first ' \ 'array entry, lambda function): %s' % \ np.degrees(COMP_ANGLE(SOLAR_SYSTEM_DF['POS_SSB_WRT_SUN'].iloc[0], \ SOLAR_SYSTEM_DF['POS_JUP_WRT_SUN'].iloc[0]))) print('Phase angle between the SSB and Jupiter as seen from the Sun (first ' \ 'array entry, SPICE vsep function): %s' % \ np.degrees(spiceypy.vsep(SOLAR_SYSTEM_DF['POS_SSB_WRT_SUN'].iloc[0], \ SOLAR_SYSTEM_DF['POS_JUP_WRT_SUN'].iloc[0]))) #%% # Create a 4 axes plot where all 4 plots are vertically aligned and share the # x axis (date in UTC) FIG, (AX1, AX2, AX3, AX4) = plt.subplots(4, 1, sharex=True, figsize=(8, 20)) # We iterate through the planets (from Jupiter to Neptune) and plot the # phase angle between the planet and the SSB, as seen from the Sun, in each # axis individually for ax_f, planet_abr, planet_name in zip([AX1, AX2, AX3, AX4], \ ['JUP', 'SAT', 'URA', 'NEP'], \ ['Jupiter', 'Saturn', 'Uranus', \ 'Neptune']): # First, we set the planet's name as the sub plot title (instead of # setting a legend) ax_f.set_title(planet_name, color='tab:orange') # The distance between the SSB and the Sun is plotted. ax_f.plot(SOLAR_SYSTEM_DF['UTC'], \ SOLAR_SYSTEM_DF['SSB_WRT_SUN_SCALED_DIST'], \ color='tab:blue') # A y label is set and the color of labels and ticks are adjusted for # better visibility ax_f.set_ylabel('SSB Dist. in Sun Radii', color='tab:blue') ax_f.tick_params(axis='y', labelcolor='tab:blue') # Set x (based on the min and max date) and y limits (the SSB has varying # distances between 0 and 2 Sun Radii) ax_f.set_xlim(min(SOLAR_SYSTEM_DF['UTC']), max(SOLAR_SYSTEM_DF['UTC'])) ax_f.set_ylim(0, 2) # We add now the phase angle values and copy the x axis for this purpose ax_f_add = ax_f.twinx() # Plot the phase angle between the SSB and planet as seen from the Sun ax_f_add.plot(SOLAR_SYSTEM_DF['UTC'], \ SOLAR_SYSTEM_DF['PHASE_ANGLE_SUN_%s2SSB' % planet_abr], \ color='tab:orange', \ linestyle='-') # Set the y label's name and color accordingly ax_f_add.set_ylabel('Planet ph. ang. in deg', color='tab:orange') ax_f_add.tick_params(axis='y', labelcolor='tab:orange') # Invert the y axis and set the limits. We invert the axis so that a # possible anti-correlation (large phase angle corresponds to a smaller # distance between the Sun's centre and the SSB) becomes more obvious ax_f_add.invert_yaxis() ax_f_add.set_ylim(180, 0) # Set a grid (only date) ax_f.grid(axis='x', linestyle='dashed', alpha=0.5) # Finally we set the x label ... AX4.set_xlabel('Date in UTC') # ... tight the figures a bit ... FIG.tight_layout() # ... reduce the distance between the axes ... plt.subplots_adjust(hspace=0.2) # ... and save the figure in high quality plt.savefig('PLANETS_SUN_SSB_PHASE_ANGLE.png', dpi=300)
python
r''' Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' import struct from nogotofail.mitm.util.tls import types def parse_tls(message, throw_on_incomplete=False): """Try and parse a TLS record. If the message is fragmented over multiple TLS records this will return one TLS record with the defragmented payload Arguments: message -- wire representation of a TLS message. throw_on_incomplete -- throw a TlsRecordIncompleteError or TlsMessageFragmentedError if message is not complete, otherwise return None Returns (nogotofail.mitm.util.tls.TlsRecord, remaining_message) if message consumed or None, message if parsing was unsuccessful """ extra_fragment_data = "" original_message = message try: while message: try: record, size = types.TlsRecord.from_stream(message, previous_fragment_data=extra_fragment_data) return record, message[size:] except types.TlsMessageFragmentedError as e: # If we're fragmented try and keep parsing extra_fragment_data += e.fragment_data message = message[e.data_consumed:] # If we're fragmented but out of data error out if not message: if throw_on_incomplete: raise e else: return None, original_message except (IndexError, ValueError, struct.error): return None, original_message except types.TlsRecordIncompleteError as e: if throw_on_incomplete: raise e else: return None, original_message return None, original_message
python
from __future__ import annotations from typing import List from dataclasses import dataclass from ..model import Pos @dataclass class SingleCandidate: pos: Pos number: int reason: str = 'unkown' def __str__(self): return f'{self.pos.idx}, {self.number}' @dataclass class MultiCandidate: pos: List[int] number: List[int] reason: str = 'unkown' def __str__(self): return f'{self.pos}, {self.number}' class AppendDict: def __init__(self): self.dict = dict() def append(self, key, value): if key in self.dict: self.dict[key].append(value) else: self.dict[key] = [value] def items(self): return self.dict.items() def __getitem__(self, key): if key in self.dict: return self.dict[key] else: return set() def __setitem__(self, key, value): if key in self.dict: self.dict[key].add(value) else: self.dict[key] = set((value,)) def __str__(self): return str(self.dict)
python
""" Gui for image_dialog Author: Gerd Duscher """ # -*- coding: utf-8 -*- from PyQt5 import QtCore, QtGui, QtWidgets from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as Canvas from matplotlib.figure import Figure from pyTEMlib.microscope import microscope class MySICanvas(Canvas): def __init__(self, parent, width=10, height=10, dpi=100): self.figure = Figure(figsize=(width, height), dpi=dpi) self.figure.subplots_adjust(bottom=.2) Canvas.__init__(self, self.figure) self.setParent(parent) Canvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) Canvas.updateGeometry(self) class UiDialog(object): def __init__(self, dialog, parent=None): dialog.setObjectName('Image Info') dialog.resize(371, 184) valid_float = QtGui.QDoubleValidator() # valid_int = QtGui.QIntValidator() self.histogram = MySICanvas(parent, width=10, height=10, dpi=70) # Defining a plot instance (axes) and assigning a variable to it self.histogram.axes = self.histogram.figure.add_subplot(1, 1, 1) self.TEM = [] self.TEM = microscope.get_available_microscope_names() plot_layout = QtWidgets.QGridLayout() # Adding histogram plot_layout.addWidget(self.histogram, 0, 0) # making a single widget out of histogram histogram_plot = QtWidgets.QWidget() histogram_plot.setLayout(plot_layout) layout = self.layout = QtWidgets.QGridLayout() self.layout.setVerticalSpacing(2) self.separator1 = QtWidgets.QLabel() self.separator1.setAutoFillBackground(True) palette = self.separator1.palette() palette.setColor(self.separator1.backgroundRole(), QtCore.Qt.blue) palette.setColor(self.separator1.foregroundRole(), QtCore.Qt.white) self.separator1.setAlignment(QtCore.Qt.AlignCenter) self.separator1.setMaximumHeight(50) self.separator1.setPalette(palette) ###################################################################### self.separator1.setText("Microscope") layout.addWidget(self.separator1, 0, 0, 1, 3) row = 0 layout.addWidget(self.separator1, row, 0, 1, 4) row += 1 self.TEMList = QtWidgets.QComboBox() self.TEMList.setEditable(False) self.TEMList.addItems(self.TEM) self.layout.addWidget(self.TEMList, row, 1) row += 1 self.convLabel = QtWidgets.QLabel("Conv. Angle") self.convEdit = QtWidgets.QLineEdit(" 100.0") self.convEdit.setValidator(valid_float) self.convUnit = QtWidgets.QLabel("mrad") self.layout.addWidget(self.convLabel, row, 0) self.layout.addWidget(self.convEdit, row, 1) self.layout.addWidget(self.convUnit, row, 2) row += 1 self.E0Label = QtWidgets.QLabel("Acc. Voltage") self.E0Edit = QtWidgets.QLineEdit(" 100.0") self.E0Edit.setValidator(valid_float) self.E0Unit = QtWidgets.QLabel("kV") self.layout.addWidget(self.E0Label, row, 0) self.layout.addWidget(self.E0Edit, row, 1) self.layout.addWidget(self.E0Unit, row, 2) self.separator2 = QtWidgets.QLabel() self.separator2.setAutoFillBackground(True) self.separator2.setAlignment(QtCore.Qt.AlignCenter) self.separator2.setMaximumHeight(50) self.separator2.setPalette(palette) row += 1 ###################################################################### self.separator2.setText("Image") layout.addWidget(self.separator2, row, 0, 1, 4) ###################################################################### row += 1 self.sizeLabel = QtWidgets.QLabel("Size") self.sizeEdit = QtWidgets.QLineEdit(" 1 x 1") self.sizeEdit.setValidator(valid_float) self.sizeUnit = QtWidgets.QLabel("px") self.layout.addWidget(self.sizeLabel, row, 0) self.layout.addWidget(self.sizeEdit, row, 1) self.layout.addWidget(self.sizeUnit, row, 2) row += 1 self.timeLabel = QtWidgets.QLabel("Exp. Time") self.timeEdit = QtWidgets.QLineEdit(" 100.0") self.timeEdit.setValidator(valid_float) self.timeUnit = QtWidgets.QLabel("s") self.layout.addWidget(self.timeLabel, row, 0) self.layout.addWidget(self.timeEdit, row, 1) self.layout.addWidget(self.timeUnit, row, 2) self.separator3 = QtWidgets.QLabel(dialog) self.separator3.setAutoFillBackground(True) self.separator3.setAlignment(QtCore.Qt.AlignCenter) self.separator3.setMaximumHeight(50) self.separator3.setPalette(palette) row += 1 ###################################################################### self.separator3.setText("Histogram") self.layout.addWidget(self.separator3, row, 0, 1, 4) ###################################################################### row += 1 layout.addWidget(histogram_plot, row, 0, 1, 3) dialog.setLayout(layout)
python
import os import neuralbody.utils.geometry as geometry import numpy as np import torch import torch.nn as nn from torch.nn.parameter import Parameter class SMPL(nn.Module): def __init__(self, data_root, gender='neutral', spec='', beta=None): super(SMPL, self).__init__() file_path = os.path.join( data_root, 'SMPL{}_{}.npy'.format(spec, gender)) data = np.load(file_path, allow_pickle=True).item() mu_ = data['v_template'] n_betas_ = data['shapedirs'].shape[-1] shapedirs_ = np.reshape(data['shapedirs'], [-1, n_betas_]).T if isinstance(data['J_regressor'], np.ndarray): joint_reg_ = data['J_regressor'].T else: joint_reg_ = data['J_regressor'].T.todense() kin_parents_ = data['kintree_table'][0].astype(np.int32) blendW_ = data['weights'] f_ = torch.tensor(data['f'].astype(np.int32), dtype=torch.long) vbyf_ = geometry.vertex_by_face(f_) self.n_J = joint_reg_.shape[1] self.n_V = mu_.shape[0] mu_ = torch.tensor(mu_, dtype=torch.float32) J_regressor = torch.tensor(joint_reg_, dtype=torch.float32) shapedirs_ = torch.tensor(shapedirs_, dtype=torch.float32) if beta is not None: v_res = torch.matmul(beta, shapedirs_) v_res = v_res.reshape(-1, self.n_V, 3)[0] mu_ = mu_ + v_res J = torch.matmul(J_regressor.T, mu_) self.register_buffer('shapedirs', shapedirs_) self.register_buffer('J_regressor', J_regressor) self.register_buffer('kin_parents', torch.tensor( kin_parents_, dtype=torch.long)) self.register_buffer('f', f_) self.register_buffer('vbyf', vbyf_.to_dense()) self.register_buffer('blendW', torch.tensor( blendW_, dtype=torch.float32)) self.register_buffer('J', J) self.register_parameter('v', Parameter(mu_)) def forward(self, theta, beta=None, h2w=None, inverse=False): if beta is None: v_shaped = self.v.expand([theta.shape[0], self.n_V, 3]) J = self.J.expand([theta.shape[0], self.n_J, 3]) else: v_res = torch.matmul(beta, self.shapedirs) v_res = v_res.reshape(-1, self.n_V, 3) v_shaped = v_res + self.v Jx = torch.matmul(v_shaped[..., 0], self.J_regressor) Jy = torch.matmul(v_shaped[..., 1], self.J_regressor) Jz = torch.matmul(v_shaped[..., 2], self.J_regressor) J = torch.stack([Jx, Jy, Jz], dim=-1) v = geometry.lbs(v_shaped, self.blendW, theta, J, self.kin_parents, inverse) if h2w is not None: h2w_R = h2w[..., :3, :3] h2w_T = h2w[..., :3, 3:] v = torch.bmm(h2w_R, v.transpose(-1, -2)) + h2w_T v = v.transpose(-1, -2) return v, v_shaped
python
# Problem Description:-https://leetcode.com/problems/longest-palindromic-substring/ class Solution: def helper(self, s, left, right): while left>=0 and right<len(s) and (s[left]==s[right]): left-=1 right+=1 return s[left+1:right] def longestPalindrome(self, s: str) -> str: ans = "" for i in range(len(s)): odd_pos = self.helper(s, i, i) even_pos = self.helper(s, i, i+1) ans = max(even_pos, odd_pos, ans, key=len) return ans
python
from builtins import range from .base import MLClassifierBase import copy import numpy as np class RepeatClassifier(MLClassifierBase): """Simple classifier for handling cases where """ def __init__(self): super(RepeatClassifier, self).__init__() def fit(self, X, y): self.value_to_repeat = copy.copy(y.tocsr[0, :]) self.return_value = np.full(y) return self def predict(self, X): return np.array([np.copy(self.value_to_repeat) for x in range(len(X))])
python
import cv2 import numpy as np import matplotlib.pyplot as plt #from matplotlib import pyplot as plt from tkinter import filedialog from tkinter import * root = Tk() root.withdraw() root.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("all files",".*"),("jpg files",".jpg"))) img = cv2.imread(root.filename,0) root.destroy() """ cv2.imshow("Ventana de imagen seleccionada",img) cv2.waitKey(0) """ ######Equalizado adaptado clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)) cl = clahe.apply(img) cv2.imshow("Ventana de imagen ",cl) cv2.imwrite('clk.png',cl) #####Equalizacion equ = cv2.equalizeHist(img) res = np.hstack((img,equ)) #stacking images side-by-side cv2.imshow("Ventana de imagen seleccionada",res) ######Highpass kernel=np.array([[-1,-1,-1],[-1,-8,-1],[-1,-1,-1]]) dst = cv2.filter2D(equ,-1,kernel) ####Rotation and SCALE rows,cols = equ.shape M = cv2.getRotationMatrix2D((cols/2,rows/2),-15,1) Rotada = cv2.warpAffine(equ,M,(cols,rows)) cv2.imshow("Ventana de imagen rotada",dst) cv2.waitKey(0) """ dst2 = cv2.filter2D(cl,-1,kernel) cv2.imshow("Ventana",dst2) """ ##############
python
import numpy as np from gym.spaces import Box from gym.spaces import Discrete import copy from rlkit.envs.wrappers import ProxyEnv class ParticleEnv(ProxyEnv): def __init__( self, env, ): ProxyEnv.__init__(self, env) self.num_agent = self._wrapped_env.n self.action_space = self._wrapped_env.action_space[0] obs_dim = self._wrapped_env.observation_space[0].low.size for observation_space_i in self._wrapped_env.observation_space: if observation_space_i.low.size > obs_dim: obs_dim = observation_space_i.low.size self.observation_space = Box(low=-np.inf, high=+np.inf, shape=(obs_dim,), dtype=np.float32) self.obs_dim = obs_dim def step(self, action_n): action_n = copy.deepcopy(action_n) obs_n_list, reward_n, done_n_list, info_n = self._wrapped_env.step(action_n) obs_n = self.convert_obs(obs_n_list) done_n = self.convert_done(done_n_list) return obs_n, np.array(reward_n), done_n, {} def reset(self): obs_n_list = self._wrapped_env.reset() obs_n = self.convert_obs(obs_n_list) return obs_n def convert_obs(self, obs_n_list): obs_n = np.zeros((self.num_agent,self.obs_dim)) for i,j in enumerate(obs_n_list): obs_n[i][0:len(j)] = j return obs_n def convert_done(self, done_n_list): done = (np.array(done_n_list).sum() > 0) # one done all one done_n = np.array([done]*len(done_n_list)) return done_n def __str__(self): return "ParticleEnv: %s" % self._wrapped_env
python
# ================================================================== # Copyright (c) 2007,2008,2009 Metaweb Technologies, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # THIS SOFTWARE IS PROVIDED BY METAWEB TECHNOLOGIES AND CONTRIBUTORS # ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL METAWEB # TECHNOLOGIES OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ==================================================================== # # # wrap all the nastiness needed for a general mql inspect query # # import os, sys, re null = None true = True false = False inspect_query = { 'name': null, 'type': [], '/type/reflect/any_master': [{ 'optional':true, 'id': null, 'name': null, 'link': { 'master_property': { 'id': null, 'schema': null } } }], '/type/reflect/any_reverse': [{ 'optional':true, 'id': null, 'name': null, 'link': { 'master_property': { 'id':null, 'schema': null, 'expected_type': null, 'reverse_property': { 'id': null, 'schema': null, 'optional': true } } } }], '/type/reflect/any_value': [{ 'optional':true, 'value': null, 'link': { 'master_property': { 'id':null, 'schema': null, 'expected_type': null }, } }], 't:/type/reflect/any_value': [{ 'optional':true, 'type': '/type/text', 'value': null, 'lang': null, 'link': { 'master_property': { 'id':null, 'schema': null }, } }], '/type/object/creator': [{ 'optional':true, 'id':null, 'name':null }], '/type/object/timestamp': [{ 'optional':true, 'value': null, }], '/type/object/key': [{ 'optional':true, 'value': null, 'namespace': null }], '/type/namespace/keys': [{ 'optional':true, 'value': null, 'namespace': null }] } def transform_result(result): proptypes = {} props = {} # copy a property from a /type/reflect clause def pushtype(propdesc, prop): tid = propdesc['schema'] propid = propdesc['id'] if isinstance(prop, dict): prop = dict(prop) if 'link' in prop: prop.pop('link') if tid not in proptypes: proptypes[tid] = {} if propid not in proptypes[tid]: proptypes[tid][propid] = [] if propid not in props: props[propid] = [] props[propid].append(prop) # copy a property that isn't enumerated by /type/reflect def pushprop(propid): ps = result[propid] if ps is None: return # hack to infer the schema from id, not always reliable! schema = re.sub(r'/[^/]+$', '', propid) keyprop = dict(id=propid, schema=schema) for p in ps: pushtype(keyprop, p) ps = result['/type/reflect/any_master'] or [] for p in ps: propdesc = p.link.master_property pushtype(propdesc, p) # non-text non-key values ps = result['/type/reflect/any_value'] or [] for p in ps: propdesc = p.link.master_property # /type/text values are queried specially # so that we can get the lang, so ignore # them here. if propdesc.expected_type == '/type/text': continue pushtype(propdesc, p) # text values ps = result['t:/type/reflect/any_value'] or [] for p in ps: propdesc = p.link.master_property pushtype(propdesc, p) pushprop('/type/object/creator') pushprop('/type/object/timestamp') pushprop('/type/object/key') pushprop('/type/namespace/keys') # now the reverse properties ps = result['/type/reflect/any_reverse'] or [] for prop in ps: propdesc = prop.link.master_property.reverse_property # synthetic property descriptor for the reverse of # a property with no reverse descriptor. # note the bogus id starting with '-'. if propdesc is None: # schema = prop.link.master_property.expected_type # if schema is None: # schema = 'other' schema = 'other' propdesc = dict(id='-' + prop.link.master_property.id, schema=schema) pushtype(propdesc, prop) #return proptypes return props def inspect_object(mss, id): q = dict(inspect_query) q['id'] = id r = mss.mqlread(q) if r is None: return None return transform_result(r)
python
import numpy as np import deepdish as dd from scipy.signal import welch def interaction_band_pow(epochs, config): """Get the band power (psd) of the interaction forces/moments. Parameters ---------- subject : string subject ID e.g. 7707. trial : string trial e.g. HighFine, AdaptFine. Returns ------- band_pow : array An array of band_pow of each epoch of data. freqs : array An array of frequencies in power spectral density. """ data = epochs.get_data() band_pow = [] for i in range(epochs.__len__()): # Last row in smooth force freqs, power = welch(data[i, -1, :], fs=128, nperseg=64, nfft=128, detrend=False) band_pow.append(power) psds = np.sqrt(np.array(band_pow) * 128 / 2) return psds, freqs def instability_index(subject, trial, config): """Calculate instability index of the subject and trial. Parameters ---------- subject : string subject ID e.g. 7707. trial : string trial e.g. HighFine, AdaptFine. config : yaml file The configuration file Returns ------- ins_index : array An array of instability index calculated at each epochs. """ # signature of data: x(n_epochs, 3 channels, frequencies: 0-128 Hz) read_path = config['interim_data']['robot_epoch_path'] epochs = dd.io.load(read_path, group='/' + subject + '/robot/' + trial) data, freqs = interaction_band_pow(epochs, config) # Get frequency index between 3 Hz and 12 Hz f_critical_max = (freqs > 2.35) & (freqs <= 10.0) f_min_max = (freqs > 0.25) & (freqs <= 10.0) num = data[:, f_critical_max].sum(axis=-1) den = data[:, f_min_max].sum(axis=-1) ir_index = num / den return ir_index
python
''' Priority Queue implementation using binary heaps https://www.youtube.com/watch?v=eVq8CmoC1x8&list=PLDV1Zeh2NRsB6SWUrDFW2RmDotAfPbeHu&index=17 This code is done without using reverse mapping - takes O(n) time for remove_elem(elem) Can be improved by implementing it - https://www.youtube.com/watch?v=eVq8CmoC1x8&list=PLDV1Zeh2NRsB6SWUrDFW2RmDotAfPbeHu&index=17 ''' class BinaryHeap: # Initializing binary heap # Construct a priority queue using heapify in O(n) time, a great explanation can be found at: # http://www.cs.umd.edu/~meesh/351/mount/lectures/lect14-heapsort-analysis-part.pdf def __init__(self, elems = []): self.heap = elems self.heapsize = len(elems) # Heapify process for i in range(max(0, self.heapsize //2 -1), -1, -1): self.sink(i) # Returns true/false depending on if the priority queue is empty def is_empty(self): return len(self.heap) == 0 # Clears everything inside the heap, O(n) def clear(self): self.heap = [] self.heapsize = 0 # Return the size of the heap def size(self): return self.heapsize # Returns the value of the element with the lowest # priority in this priority queue. If the priority # queue is empty null is returned. def peek(self): if self.is_empty(): return None return self.heap[0] # Removes the root of the heap, O(log(n)) def pool(self): return self.remove_at(0) # Test if an element is in heap, O(n) def contains(self, elem): return self.heap.index(elem) != -1 # Adds an element to the priority queue, the # element must not be null, O(log(n)) def add(self, elem): if elem == None: raise ValueError("Null cant be added") self.heap.append(elem) self.heapsize += 1 self.swim(self.heapsize-1) # Perform bottom up node swim, O(log(n)) def swim(self, ind): # parent of heap 0 indexed parent = (ind-1)//2 while(ind > 0 and self.heap[ind] < self.heap[parent]): self.heap[ind], self.heap[parent] = self.heap[parent], self.heap[ind] ind = parent parent = (ind-1)//2 # Top down node sink, O(log(n)) def sink(self, ind): left = ind * 2 + 1 right = ind * 2 + 2 small = left while True: if right < self.heapsize and self.heap[right] < self.heap[left]: small = right # check if child is out of heap bounds or we cant sink anymore if left < self.heapsize and self.heap[ind] < self.heap[small]: break # sinking one step self.heap[ind], self.heap[small] = self.heap[small], self.heap[ind] ind = small # Removes a particular element in the heap, O(n) def remove_elem(self, elem): # Linear searching for elem O(n) i = self.heap.index(elem) return self.remove_at(i) # Removes a node at particular index, O(log(n)) def remove_at(self, ind): if ind > self.heapsize: return -1 last_index = self.heapsize - 1 # Swap ind value with last index and delete last index self.heap[ind], self.heap[last_index] = self.heap[last_index], self.heap[ind] removed_data = self.heap.pop() # If we must delete last element if ind == last_index: return removed_data # Try swimming to top self.swim(ind) # If no changes in swim, do sink if ind == self.heap[ind]: self.sink(ind) return removed_data # Recursively checks if this heap is a min heap # This method is just for testing purposes to make # sure the heap invariant is still being maintained # Called this method with k=0 to start at the root def is_min_heap(self, ind): left = 2 * ind + 1 right = 2 * ind + 2 if left < self.heapsize and self.heap[left] < self.heap[ind]: return False if right < self.heapsize and self.heap[right] < self.heap[ind]: return False return self.is_min_heap(left) and self.is_min_heap(right)
python
""" hyperopt search spaces for each prediction method """ import numpy as np from hyperopt import hp from hyperopt.pyll.base import scope from src.jobs.models import Job from src.predictive_model.classification.models import CLASSIFICATION_RANDOM_FOREST, CLASSIFICATION_KNN, \ CLASSIFICATION_XGBOOST, CLASSIFICATION_MULTINOMIAL_NAIVE_BAYES, CLASSIFICATION_DECISION_TREE, \ CLASSIFICATION_ADAPTIVE_TREE, \ CLASSIFICATION_HOEFFDING_TREE, CLASSIFICATION_SGDC, CLASSIFICATION_PERCEPTRON, CLASSIFICATION_NN from src.predictive_model.regression.models import REGRESSION_RANDOM_FOREST, REGRESSION_XGBOOST, REGRESSION_LASSO, \ REGRESSION_LINEAR, REGRESSION_NN from src.predictive_model.time_series_prediction.models import TIME_SERIES_PREDICTION_RNN def _get_space(job: Job) -> dict: """Returns the specific space for the used machine learning algorithm for the given job configuration :param job: :return: """ method_conf_name = "{}.{}".format(job.predictive_model.predictive_model, job.predictive_model.prediction_method) return HYPEROPT_SPACE_MAP[method_conf_name]() def _classification_random_forest() -> dict: """Returns the random forest prediction classification method :return: """ return { 'n_estimators': hp.choice('n_estimators', np.arange(150, 1000, dtype=int)), 'max_depth': scope.int(hp.quniform('max_depth', 4, 30, 1)), 'max_features': hp.choice('max_features', ['sqrt', 'log2', 'auto', None]), 'warm_start': True } def _classification_knn() -> dict: """Returns the KNN prediction classification method :return: """ return { 'n_neighbors': hp.choice('n_neighbors', np.arange(1, 20, dtype=int)), 'weights': hp.choice('weights', ['uniform', 'distance']), } def _classification_decision_tree() -> dict: """Returns the decision tree prediction classification method :return: """ return { 'max_depth': scope.int(hp.quniform('max_depth', 4, 30, 1)), 'min_samples_split': hp.choice('min_samples_split', np.arange(2, 10, dtype=int)), 'min_samples_leaf': hp.choice('min_samples_leaf', np.arange(1, 10, dtype=int)), } def _classification_xgboost() -> dict: """Returns the XGBoost prediction classification method :return: """ return { 'n_estimators': hp.choice('n_estimators', np.arange(150, 1000, dtype=int)), 'max_depth': scope.int(hp.quniform('max_depth', 3, 30, 1)), } def _classification_incremental_naive_bayes() -> dict: """Returns the incremental naive bayes prediction classification method :return: """ return { 'alpha': hp.uniform('alpha', 0, 10), 'fit_prior': True } def _classification_incremental_adaptive_tree() -> dict: """Returns the incremental adaptive tree prediction classification method :return: """ return { 'grace_period': hp.uniform('grace_period', 1, 5), 'split_criterion': hp.choice('split_criterion', ['gini', 'info_gain']), 'split_confidence': hp.uniform('split_confidence', .0000005, .000001), 'tie_threshold': hp.uniform('tie_threshold', .1, .6), # 'binary_split': hp.choice('binary_split', [ True, False ]), # 'stop_mem_management': hp.choice('stop_mem_management', [ True, False ]), 'remove_poor_atts': hp.choice('remove_poor_atts', [True, False]), # 'no_preprune': hp.choice('no_preprune', [ True, False ]), 'leaf_prediction': hp.choice('leaf_prediction', ['mc', 'nb', 'nba']), 'nb_threshold': hp.uniform('nb_threshold', 0.2, 0.6) } def _classification_incremental_hoeffding_tree() -> dict: """Returns the incremental hoeffding tree prediction classification method :return: """ return { 'grace_period': hp.uniform('grace_period', 3, 8), 'split_criterion': hp.choice('split_criterion', ['gini', 'info_gain']), 'split_confidence': hp.uniform('split_confidence', .0000005, .0000009), 'tie_threshold': hp.uniform('tie_threshold', .4, .8), # 'binary_split': hp.choice('binary_split', [ True, False ]), # 'stop_mem_management': hp.choice('stop_mem_management', [ True, False ]), 'remove_poor_atts': hp.choice('remove_poor_atts', [True, False]), # 'no_preprune': hp.choice('no_preprune', [ True, False ]), 'leaf_prediction': hp.choice('leaf_prediction', ['mc', 'nb', 'nba']), 'nb_threshold': hp.uniform('nb_threshold', 0.1, 0.5) } def _classification_incremental_sgd_classifier() -> dict: """Returns the incremental sgd classifier prediction classification method :return: """ return { 'loss': hp.choice('loss', ['hinge', 'log', 'modified_huber', 'squared_hinge', 'perceptron', 'squared_loss', 'huber', 'epsilon_insensitive', 'squared_epsilon_insensitive']), 'penalty': hp.choice('penalty', [None, 'l1', 'l2', 'elasticnet']), 'alpha': hp.uniform('alpha', 0.0001, 0.5), 'l1_ratio': hp.uniform('l1_ratio', 0.15, 1.0), 'fit_intercept': hp.choice('fit_intercept', [True, False]), 'tol': hp.uniform('tol', 1e-3, 0.5), 'epsilon': hp.uniform('epsilon', 1e-3, 0.5), 'learning_rate': hp.choice('learning_rate', ['constant', 'optimal', 'invscaling', 'adaptive']), 'eta0': scope.int(hp.quniform('eta0', 4, 30, 1)), 'power_t': hp.uniform('power_t', 0.3, 0.7), # 'early_stopping': hp.choice('early_stopping', [True, False]), #needs to be false with partial_fit 'n_iter_no_change': scope.int(hp.quniform('n_iter_no_change', 5, 30, 5)), 'validation_fraction': 0.1, 'average': hp.choice('average', [True, False]) } def _classification_incremental_perceptron() -> dict: """Returns the incremental perceptron prediction classification method :return: """ return { 'penalty': hp.choice('penalty', [None, 'l1', 'l2', 'elasticnet']), 'alpha': hp.uniform('alpha', 0.0001, 0.5), 'fit_intercept': hp.choice('fit_intercept', [True, False]), 'tol': hp.uniform('tol', 1e-3, 0.5), 'shuffle': hp.choice('shuffle', [True, False]), 'eta0': scope.int(hp.quniform('eta0', 4, 30, 1)), # 'early_stopping': hp.choice('early_stopping', [True, False]), #needs to be false with partial_fit 'validation_fraction': 0.1, 'n_iter_no_change': scope.int(hp.quniform('n_iter_no_change', 5, 30, 5)) } def _classification_nn() -> dict: """Returns the NN prediction classification method :return: """ return { 'hidden_layers': hp.quniform('hidden_layers', 1, 10, 1), 'hidden_units': hp.quniform('hidden_units', 1, 100, 1), 'activation_function': hp.choice('activation_function', ['sigmoid', 'tanh', 'relu']), 'epochs': hp.quniform('epochs', 1, 50, 1), 'dropout_rate': hp.uniform('dropout_rate', 0, 1) } def _regression_random_forest() -> dict: """Returns the random forest prediction regression method :return: """ return { 'n_estimators': hp.choice('n_estimators', np.arange(150, 1000, dtype=int)), 'max_features': hp.choice('max_features', ['sqrt', 'log2', 'auto', None]), 'max_depth': scope.int(hp.quniform('max_depth', 4, 30, 1)), } def _regression_lasso() -> dict: """Returns the lasso prediction regression method :return: """ return { 'alpha': hp.uniform('alpha', 0.01, 2.0), 'fit_intercept': hp.choice('fit_intercept', [True, False]), 'normalize': hp.choice('normalize', [True, False]) } def _regression_linear() -> dict: """Returns the linear prediction regression method :return: """ return { 'fit_intercept': hp.choice('fit_intercept', [True, False]), 'normalize': hp.choice('normalize', [True, False]) } def _regression_xgboost() -> dict: """Returns the XGBoost prediction regression method :return: """ return { 'max_depth': scope.int(hp.quniform('max_depth', 3, 100, 1)), 'n_estimators': hp.choice('n_estimators', np.arange(150, 1000, dtype=int)), } def _regression_nn() -> dict: """Returns the NN prediction regression method :return: """ return { 'hidden_layers': hp.quniform('hidden_layers', 1, 10, 1), 'hidden_units': hp.quniform('hidden_units', 1, 100, 1), 'activation_function': hp.choice('activation_function', ['sigmoid', 'tanh', 'relu']), 'epochs': hp.quniform('epochs', 1, 50, 1), 'dropout_rate': hp.uniform('dropout_rate', 0, 1) } def _time_series_prediction_rnn() -> dict: """TODO: complete commit description :return: """ raise NotImplementedError HYPEROPT_SPACE_MAP = { CLASSIFICATION_RANDOM_FOREST: _classification_random_forest, CLASSIFICATION_KNN: _classification_knn, CLASSIFICATION_XGBOOST: _classification_xgboost, CLASSIFICATION_DECISION_TREE: _classification_decision_tree, CLASSIFICATION_MULTINOMIAL_NAIVE_BAYES: _classification_incremental_naive_bayes, CLASSIFICATION_ADAPTIVE_TREE: _classification_incremental_adaptive_tree, CLASSIFICATION_HOEFFDING_TREE: _classification_incremental_hoeffding_tree, CLASSIFICATION_SGDC: _classification_incremental_sgd_classifier, CLASSIFICATION_PERCEPTRON: _classification_incremental_perceptron, CLASSIFICATION_NN: _classification_nn, REGRESSION_RANDOM_FOREST: _regression_random_forest, REGRESSION_XGBOOST: _regression_xgboost, REGRESSION_LASSO: _regression_lasso, REGRESSION_LINEAR: _regression_linear, REGRESSION_NN: _regression_nn, TIME_SERIES_PREDICTION_RNN: _time_series_prediction_rnn }
python
import logging from datetime import date from flask import request, render_template, jsonify, redirect, url_for from weight import app from weight.db import SessionScope from weight.forms import WeightForm from weight.db.queries import ( add_weight_data, edit_weight_data, delete_weight_data, get_weights_data, get_weight_data, ) logging.basicConfig(filename='weight.log', level=logging.DEBUG) logger = logging.getLogger(__name__) @app.route('/', methods=['GET']) def get_weight(): logger.info('start get weight') with SessionScope() as session: weights = get_weights_data(session) dates = [] weight_data_old = [] weight_data_new = [] for item in weights: dates.append(item.date.strftime('%Y-%m-%d')) weight_data_old.append(item.old_weight) weight_data_new.append(item.new_weight) logger.info('return render template') return render_template('weight/index.html', weights=weights, weight_data_old=weight_data_old, dates=dates, weight_data_new=weight_data_new) @app.route('/get_weight_data') def get_data_weight(): logger.info('start get weight data') with SessionScope() as session: weights = get_weights_data(session) dates = [] weight_data_old = [] weight_data_new = [] for item in weights: dates.append(item.date.isoformat()) weight_data_old.append(item.old_weight) weight_data_new.append(item.new_weight) weight_data_old = { 'x': dates, 'y': weight_data_old, 'mode': 'lines+markers', 'name': 'old weight', } weight_data_new = { 'x': dates, 'y': weight_data_new, 'mode': 'lines+markers', 'name': 'new weight', } logger.info('return jsonify') return jsonify({ 'old_weight': weight_data_old, 'new_weight': weight_data_new, }) @app.route('/add_weight', methods=['GET', 'POST']) def add_weight(): logger.info('start add weight') form = WeightForm() if form.validate_on_submit(): with SessionScope() as session: add_weight_data(request.form, session) return redirect(url_for('get_weight', _external=True)) else: logger.info('in else') form.date.data = date.today() logger.info('return render template') return render_template('weight/add_weight.html', form=form, change='add') @app.route('/edit_weight/<id>', methods=['GET', 'POST']) def edit_weight(id): form = WeightForm() if form.validate_on_submit(): with SessionScope() as session: edit_weight_data(request.form, session, id) return redirect(url_for('get_weight', _external=True)) else: with SessionScope() as session: weight_data = get_weight_data(session, id) form.date.data = weight_data.date form.old_weight.data = weight_data.old_weight form.new_weight.data = weight_data.new_weight return render_template('weight/add_weight.html', form=form, change='edit')
python
## 旋转数组 # 方法一: 暴力法, 循环嵌套 时间:O(k*n) 空间:O(1) # class Solution: # def rotate(self, nums: List[int], k: int) -> None: # n = len(nums) - 1 # j = 0 # while j < k: # i = n # temp = nums[n] # while i > 0: # nums[i] = nums[i-1] # i -= 1 # nums[0] = temp # j += 1 ################################################################# # 方法二:拆分对调 时间:O(n) 空间:O(n) # class Solution: # def rotate(self, nums: List[int], k: int) -> None: # split_index = len(nums) - k # front_arr = nums[:split_index] # after_arr = nums[split_index:] # for i, num in enumerate(after_arr + front_arr): # nums[i] = num ################################################################# # 方法三: 反转法 时间:O(n) 空间:O(1) class Solution: def rotate(self, nums: List[int], k: int) -> None: k %= len(nums) self.reversal(nums, 0, len(nums)-1) self.reversal(nums, 0, k-1) self.reversal(nums, k, len(nums)-1) def reversal(self, nums: List[int], start: int, end: int) -> None: while start < end: nums[start], nums[end] = nums[end], nums[start] start += 1 end -= 1
python
import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix def plot_matrix(clf, X_test, y_test): plt.clf() plt.imshow(confusion_matrix(clf.predict(X_test), y_test), interpolation='nearest', cmap=plt.cm.Blues) plt.colorbar() plt.xlabel("true label") plt.ylabel("predicted label") plt.show()
python
import subprocess class ShellCommandExecuter: def __init__(self, current_working_directory, args): self.current_working_directory = current_working_directory self.args = args def execute_for_output(self): process = subprocess.run(self.args, stdout=subprocess.PIPE, cwd=self.current_working_directory) return process.stdout.decode('utf-8').strip() def execute_for_return_code(self): return subprocess.call(self.args, cwd=self.current_working_directory)
python
#Addition of a new dot. import numpy as np import plotly.express as px import plotly.graph_objects as go #Initial state. Base dataset. ##def __init__ visualizer(self): ##Falta que lo clasifique. def add_dot(sepal_width, sepal_length, color): df = px.data.iris() newDyc = {"sepal_width": sepal_width, "sepal_length": sepal_length, "species": color} df = df.append(newDyc, ignore_index=True) newFig = px.scatter(df, x="sepal_width", y="sepal_length", color="species") newFig.show() # KNN.fit(X, Y) #KNN.askNewData() if __name__ == "__main__": df = px.data.iris() speciesDyc = {"setosa": 0, "versicolor": 1, "virginica": 2} X = df["sepal_width", "sepal_length"].values Y = df["species"].apply(speciesDyc.get).values print(np.isnan(Y).sum() == 0) df = df[["sepal_width", "sepal_length", "species"]] fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species") fig.show() fig.show()
python
import codecs import csv import sys import pickle import os try: from . import config_wv from . import pre_util except: sys.path.append("/Users/tdong/git/lg-flask/tasks/lgutil/pre_processing_wv/config_wv") import config_wv import pre_util def get_all_lines(fname, encoding='utf8'): with codecs.open(fname, "r", encoding) as fd: return fd.readlines() def get_all_rows_from_csv(csvfn, encoding='utf-8'): with open(csvfn, 'r') as fb: reader = csv.reader(fb) return list(reader) def load_pickle(picklefname): psize = os.path.getsize(picklefname) if psize > 0: with open(picklefname, 'rb') as hp: return pickle.load(hp) else: return {} def dump_pickle(picklefname, dic): with open(picklefname, 'wb') as hp: pickle.dump(dic, hp) def create_bible_raw_snts(fname, encoding='utf8'): sntLst = [] for rowLst in get_all_rows_from_csv(fname, encoding=encoding): sntLst.append(rowLst[3]) sntLst.append('\n') path, name = os.path.splitext(fname) newfile = path+'.lst' with open(newfile, 'w') as fd: fd.writelines(sntLst) if __name__ == "__main__": create_bible_raw_snts(config_wv.DeBibleCsv, encoding='ISO-8859-1')
python
# Print out 2 to the 65536 power # (try doing the same thing in the JS console and see what it outputs) bignum = 2 ** 65536 print(bignum)
python
from .cifar import CIFAR10NoisyLabels, CIFAR100NoisyLabels __all__ = ('CIFAR10NoisyLabels', 'CIFAR100NoisyLabels')
python
dict1 = dict(One = 1, Two = 2, Three = 3, Four = 4, Five = 5) print(dict1['Four']) dict1['Three'] = 3.1 print(dict1) del dict1['Two'] print(dict1)
python
from __future__ import annotations import pandas as pd import numpy as np from typing import List, Union, TYPE_CHECKING from whyqd.base import BaseSchemaAction if TYPE_CHECKING: from ..models import ColumnModel, ModifierModel, FieldModel class Action(BaseSchemaAction): """ Create a new field by iterating over a list of fields and picking the oldest value in the list. Script:: "ORDER_OLD > 'destination_field' < ['source_column' + 'source_column_date', 'source_column' + 'source_column_date', etc.]" Where `+` links two columns together, explicitly declaring that the date in `source_column_date` is used to assign the order to the values in `source_column`. Unlike the ORDER ACTION, ORDER_OLD takes its ordering from this date assignment. """ def __init__(self) -> None: super().__init__() self.name = "ORDER_OLD" self.title = "Order by oldest" self.description = "Use sparse data from a list of fields to populate a new field order by the oldest value. Field-pairs required, with the first containing the values, and the second the dates for comparison, linked by a '+' modifier (e.g. A+dA, B+dB, C+dC, values with the oldest associated date will have precedence over other values)." self.structure = ["field", "modifier", "field"] @property def modifiers(self) -> List[ModifierModel]: """ Describes the modifiers for order by oldest. Returns ------- List of ModifierModel ModifierModel representation of the modifiers. """ return [{"name": "+", "title": "Links"}] def transform( self, df: pd.DataFrame, destination: Union[FieldModel, ColumnModel], source: List[Union[ColumnModel, ModifierModel]], ) -> pd.DataFrame: """Create a new field by iterating over a list of fields and picking the oldest value in the list. Parameters ---------- df: DataFrame Working data to be transformed destination: FieldModel or ColumnModel, default None Destination column for the result of the Action. source: list of ColumnModel and / or ModifierModel List of source columns and modifiers for the action. Returns ------- Dataframe Containing the implementation of the Action """ base_date = None # Requires sets of 3 terms: field, +, date_field term_set = len(self.structure) for data, modifier, date in self.core.chunks(source, term_set): if modifier.name != "+": raise ValueError(f"Field `{source}` has invalid ORDER_BY_OLD script. Please review.") if not base_date: # Start the comparison on the next round df.rename(index=str, columns={data.name: destination.name}, inplace=True) base_date = date.name if data.name == date.name: # Just comparing date columns base_date = destination.name df.loc[:, base_date] = df.loc[:, base_date].apply( lambda x: pd.to_datetime(self.wrangle.parse_dates(x), errors="coerce") ) continue # np.where date is <> base_date and don't replace value with null # logic: if test_date not null & base_date <> test_date # False if (test_date == nan) | (base_date == nan) | base_date >< test_date # Therefore we need to test again for the alternatives df.loc[:, date.name] = df.loc[:, date.name].apply( lambda x: pd.to_datetime(self.wrangle.parse_dates(x), errors="coerce") ) df.loc[:, destination.name] = np.where( df[date.name].isnull() | (df[base_date] < df[date.name]), np.where(df[destination.name].notnull(), df[destination.name], df[data.name]), np.where(df[data.name].notnull(), df[data.name], df[destination.name]), ) if base_date != destination.name: df.loc[:, base_date] = np.where( df[date.name].isnull() | (df[base_date] < df[date.name]), np.where(df[base_date].notnull(), df[base_date], df[date.name]), np.where(df[date.name].notnull(), df[date.name], df[base_date]), ) return df
python
from zipfile import ZipFile import os class ExtractFiles: def __init__(self): self.ends_with = '.zip' self._backup_dir = r"C:\dev\integratedSystem\all_images" def handler_files(self, file_name): if file_name.endswith(self.ends_with): return self.extract_zips(file_name) else: return file_name def extract_zips(self, file_name): file_path = os.path.join(self._backup_dir, file_name) with ZipFile(file_path, 'r') as zip_ref: # Extract all the contents of zip file in current directory return zip_ref.namelist()[0]
python
import sys import mechanics.colors as colors from tcod import image_load from tcod import console from loader_functions.initialize_new_game import get_constants, get_game_variables from loader_functions.data_loaders import load_game, save_game from mechanics.menus import main_menu, messsage_box from mechanics.game_states import GameStates from mechanics.render_functions import render_all, clear_all from mechanics.entity import Entity from mechanics.input_handlers import handle_main_menu, handle_keys, handle_mouse from mechanics.game_messages import Message from mechanics.death_functions import kill_monster, kill_player from mechanics.entity import get_blocking_entities_at_location from mechanics.map_utils import next_floor def main(): constants = get_constants() sys.path.append("..") tdl.set_font('images/arial10x10.png', greyscale=True, altLayout=True) root_console = tdl.init( constants['SCREEN_WIDTH'], constants['SCREEN_HEIGHT'], constants['WINDOW_TITLE']) con = console.Console(constants['SCREEN_WIDTH'], constants['SCREEN_HEIGHT']) panel = console.Console(constants['SCREEN_WIDTH'], constants['PANEL_HEIGHT']) player = None entities = [] game_map = None message_log = None game_state = None show_main_menu = True show_load_error_message = False main_menu_background_image = image_load('images/menu_background.png') while not tdl.event.is_window_closed(): for event in tdl.event.get(): if event.type == 'KEYDOWN': user_input = event break else: user_input = None if show_main_menu: main_menu(con, root_console, main_menu_background_image, constants['SCREEN_WIDTH'], constants['SCREEN_HEIGHT']) if show_load_error_message: messsage_box(con, root_console, 'Jogo salvo nao encontrado!', 50, constants['SCREEN_WIDTH'], constants['SCREEN_HEIGHT']) tdl.flush() action = handle_main_menu(user_input) new_game = action.get('new_game') load_saved_game = action.get('load_game') exit_game = action.get('exit') if show_load_error_message and (new_game or load_saved_game or exit_game): show_load_error_message = False elif new_game: player, entities, game_map, message_log, game_state = get_game_variables( constants) game_state = GameStates.PLAYERS_TURN show_main_menu = False elif load_saved_game: try: player, entities, game_map, message_log, game_state = load_game() show_main_menu = False except FileNotFoundError: show_load_error_message = True elif exit_game: break else: root_console.clear() con.clear() panel.clear() play_game(player, entities, game_map, message_log, game_state, root_console, con, panel, constants) show_main_menu = True def play_game(player, entities, game_map, message_log, game_state, root_console, con, panel, constants): sys.path.append("..") tdl.set_font('images/arial10x10.png', greyscale=True, altLayout=True) fov_recompute = True mouse_coordinates = (0, 0) previous_game_state = game_state targeting_item = None while not tdl.event.is_window_closed(): if fov_recompute: game_map.compute_fov(player.x, player.y, fov=constants['FOV_ALGORITHM'], radius=constants['FOV_RADIUS'], light_walls=constants['FOV_LIGHT_WALLS']) render_all(con, panel, entities, player, game_map, fov_recompute, root_console, message_log, constants['SCREEN_WIDTH'], constants['SCREEN_HEIGHT'], constants['BAR_WIDTH'], constants['PANEL_HEIGHT'], constants['PANEL_Y'], mouse_coordinates, constants['Colors'], game_state) tdl.flush() clear_all(con, entities) fov_recompute = False for event in tdl.event.get(): if event.type == 'KEYDOWN': user_input = event break elif event.type == 'MOUSEMOTION': mouse_coordinates = event.cell elif event.type == 'MOUSEDOWN': user_mouse_input = event break else: user_input = None user_mouse_input = None if not (user_input or user_mouse_input): continue action = handle_keys(user_input, game_state) mouse_action = handle_mouse(user_mouse_input) move = action.get('move') pickup = action.get('pickup') show_inventory = action.get('show_inventory') drop_inventory = action.get('drop_inventory') inventory_index = action.get('inventory_index') take_stairs = action.get('take_stairs') level_up = action.get('level_up') show_character_screen = action.get('show_character_screen') exit = action.get('exit') fullscreen = action.get('fullscreen') left_click = mouse_action.get('left_click') right_click = mouse_action.get('right_click') player_turn_results = [] if move and game_state == GameStates.PLAYERS_TURN: dx, dy = move destination_x = player.x + dx destination_y = player.y + dy # NOCLIP AQUI if game_map.walkable[destination_x, destination_y]: target = get_blocking_entities_at_location( entities, destination_x, destination_y) if target: attack_results = player.fighter.attack(target) player_turn_results.extend(attack_results) else: player.move(dx, dy) fov_recompute = True game_state = GameStates.ENEMY_TURN elif pickup and game_state == GameStates.PLAYERS_TURN: for entity in entities: if (entity.item) and (entity.x == player.x and entity.y == player.y): pickup_results = player.inventory.add_item(entity) player_turn_results.extend(pickup_results) break else: message_log.add_message( Message('Nao ha nada aqui para ser pegado', colors.yellow)) if show_inventory: previous_game_state = game_state game_state = GameStates.SHOW_INVENTORY if drop_inventory: previous_game_state = game_state game_state = GameStates.DROP_INVENTORY if inventory_index is not None and previous_game_state != GameStates.PLAYER_DEAD and inventory_index < len(player.inventory.items): item = player.inventory.items[inventory_index] if game_state == GameStates.SHOW_INVENTORY: player_turn_results.extend(player.inventory.use( item, entities=entities, game_map=game_map)) elif game_state == GameStates.DROP_INVENTORY: player_turn_results.extend(player.inventory.drop_item(item)) if take_stairs and game_state == GameStates.PLAYERS_TURN: for entity in entities: if entity.stairs and entity.x == player.x and entity.y == player.y: game_map, entities = next_floor( player, message_log, entity.stairs.floor, constants) fov_recompute = True con.clear() break else: message_log.add_message( Message('Nao ha uma escadaria aqui.', colors.yellow)) if level_up: if level_up == 'hp': player.fighter.base_max_hp += 20 player.fighter.hp += 20 elif level_up == 'str': player.fighter.base_power += 1 elif level_up == 'def': player.fighter.base_defense += 1 game_state = previous_game_state if show_character_screen: previous_game_state = game_state game_state = GameStates.CHARACTER_SCREEN if game_state == GameStates.TARGETING: if left_click: target_x, target_y = left_click item_use_results = player.inventory.use( targeting_item, entities=entities, game_map=game_map, target_x=target_x, target_y=target_y) player_turn_results.extend(item_use_results) elif right_click: player_turn_results.append({'targeting_cancelled': True}) if exit: if game_state in (GameStates.SHOW_INVENTORY, GameStates.DROP_INVENTORY, GameStates.CHARACTER_SCREEN): game_state = previous_game_state elif game_state == GameStates.TARGETING: player_turn_results.append({'targeting_cancelled': True}) else: save_game(player, entities, game_map, message_log, game_state) return True if fullscreen: tdl.set_fullscreen(not tdl.get_fullscreen()) for player_turn_result in player_turn_results: message = player_turn_result.get('message') dead_entity = player_turn_result.get('dead') item_added = player_turn_result.get('item_added') item_consumed = player_turn_result.get('consumed') item_dropped = player_turn_result.get('item_dropped') equip = player_turn_result.get('equip') targeting = player_turn_result.get('targeting') targeting_cancelled = player_turn_result.get('targeting_cancelled') xp = player_turn_result.get('xp') if message: message_log.add_message(message) if dead_entity: if dead_entity == player: messsage, game_state = kill_player(dead_entity) else: message = kill_monster(dead_entity) message_log.add_message(message) if item_added: entities.remove(item_added) game_state = GameStates.ENEMY_TURN if item_consumed: game_state = GameStates.ENEMY_TURN if item_dropped: entities.append(item_dropped) game_state = GameStates.ENEMY_TURN if equip: equip_results = player.equipment.toggle_equip(equip) for equip_result in equip_results: equipped = equip_result.get('equipped') dequipped = equip_result.get('dequipped') if equipped: message_log.add_message( Message('Voce equipou o(a) {0}'.format(equipped.name))) if dequipped: message_log.add_message( Message('Voce desequipou o(a) {0}'.format(dequipped.name))) game_state = GameStates.ENEMY_TURN if targeting: previous_game_state = GameStates.PLAYERS_TURN game_state = GameStates.TARGETING targeting_item = targeting message_log.add_message(targeting_item.item.targeting_message) if targeting_cancelled: game_state = previous_game_state message_log.add_message(Message('Cancelado')) if xp: leveled_up = player.level.add_xp(xp) message_log.add_message( Message('Voce ganhou {0} pontos de experiencia.'.format(xp))) if leveled_up: message_log.add_message(Message( 'Suas habilidades de batalha melhoraram! Voce atingiu o nivel {0}'.format( player.level.current_level) + '!', colors.yellow)) previous_game_state = game_state game_state = GameStates.LEVEL_UP if game_state == GameStates.ENEMY_TURN: for entity in entities: if entity.ai: enemy_turn_results = entity.ai.take_turn( player, game_map, entities) for enemy_turn_result in enemy_turn_results: message = enemy_turn_result.get('message') dead_entity = enemy_turn_result.get('dead') if message: message_log.add_message(message) if dead_entity: if dead_entity == player: message, game_state = kill_player(dead_entity) else: message = kill_monster(dead_entity) message_log.add_message(message) if game_state == GameStates.PLAYER_DEAD: break else: game_state = GameStates.PLAYERS_TURN if __name__ == '__main__': main()
python
#!/usr/bin/python # Classification (U) """Program: main.py Description: Unit testing of main in daemon_rmq_2_isse.py. Usage: test/unit/daemon_rmq_2_isse/main.py Arguments: """ # Libraries and Global Variables # Standard import sys import os if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest # Third-party import mock # Local sys.path.append(os.getcwd()) import daemon_rmq_2_isse import lib.gen_libs as gen_libs import version __version__ = version.__version__ class UnitTest(unittest.TestCase): """Class: UnitTest Description: Class which is a representation of a unit testing. Methods: test_start_daemon -> Test main function with daemon start option. test_stop_daemon -> Test main function with daemon stop option. test_restart_daemon -> Test main function with daemon restart option. test_invalid_daemon -> Test main function with invalid option. test_arg_require_false -> Test main function with arg_require false. test_arg_require_true -> Test main function with arg_require true. """ @mock.patch("daemon_rmq_2_isse.arg_parser") @mock.patch("daemon_rmq_2_isse.Rmq2IsseDaemon.start") def test_start_daemon(self, mock_daemon, mock_arg): """Function: test_start_daemon Description: Test main function with daemon start option. Arguments: """ args = {"-a": "start", "-c": "rabbitmq"} mock_arg.arg_parse2.return_value = args mock_arg.arg_require.return_value = False mock_daemon.return_value = True self.assertRaises(SystemExit, daemon_rmq_2_isse.main) @mock.patch("daemon_rmq_2_isse.arg_parser") @mock.patch("daemon_rmq_2_isse.Rmq2IsseDaemon.stop") def test_stop_daemon(self, mock_daemon, mock_arg): """Function: test_stop_daemon Description: Test main function with daemon stop option. Arguments: """ args = {"-a": "stop", "-c": "rabbitmq"} mock_arg.arg_parse2.return_value = args mock_arg.arg_require.return_value = False mock_daemon.return_value = True self.assertRaises(SystemExit, daemon_rmq_2_isse.main) @mock.patch("daemon_rmq_2_isse.arg_parser") @mock.patch("daemon_rmq_2_isse.Rmq2IsseDaemon.restart") def test_restart_daemon(self, mock_daemon, mock_arg): """Function: test_restart_daemon Description: Test main function with daemon restart option. Arguments: """ args = {"-a": "restart", "-c": "rabbitmq"} mock_arg.arg_parse2.return_value = args mock_arg.arg_require.return_value = False mock_daemon.return_value = True self.assertRaises(SystemExit, daemon_rmq_2_isse.main) @mock.patch("daemon_rmq_2_isse.arg_parser") def test_invalid_daemon(self, mock_arg): """Function: test_invalid_daemon Description: Test main function with invalid option. Arguments: """ args = {"-a": "nostart", "-c": "rabbitmq"} mock_arg.arg_parse2.return_value = args mock_arg.arg_require.return_value = False with gen_libs.no_std_out(): self.assertRaises(SystemExit, daemon_rmq_2_isse.main) @mock.patch("daemon_rmq_2_isse.arg_parser") @mock.patch("daemon_rmq_2_isse.Rmq2IsseDaemon.start") def test_arg_require_false(self, mock_daemon, mock_arg): """Function: test_arg_require_false Description: Test main function with arg_require false. Arguments: """ args = {"-a": "start", "-c": "rabbitmq"} mock_arg.arg_parse2.return_value = args mock_arg.arg_require.return_value = False mock_daemon.return_value = True self.assertRaises(SystemExit, daemon_rmq_2_isse.main) @mock.patch("daemon_rmq_2_isse.arg_parser") def test_arg_require_true(self, mock_arg): """Function: test_arg_require_true Description: Test main function with arg_require true. Arguments: """ args = {"-a": "start", "-c": "rabbitmq"} mock_arg.arg_parse2.return_value = args mock_arg.arg_require.return_value = True with gen_libs.no_std_out(): self.assertRaises(SystemExit, daemon_rmq_2_isse.main) if __name__ == "__main__": unittest.main()
python
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license" file accompanying this file. This file 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 logging from typing import List, Optional import numpy as np import torch from torch.utils.data import DataLoader from gluonts.core.component import validated from gluonts.dataset.common import Dataset from gluonts.dataset.field_names import FieldName from gluonts.model.estimator import Estimator from gluonts.model.psagan._dataload import Data from gluonts.model.psagan._model import ( ProDiscriminator, ProGenDiscrim, ProGenerator, ProGeneratorInference, ) from gluonts.model.psagan._trainer import Trainer from gluonts.time_feature import time_features_from_frequency_str from gluonts.torch.model.predictor import PyTorchPredictor from gluonts.transform import ( AddAgeFeature, AddObservedValuesIndicator, AddPositionalEncoding, AddTimeFeatures, AsNumpyArray, Chain, ExpectedNumInstanceSampler, InstanceSplitter, RemoveFields, SetField, TestSplitSampler, VstackFeatures, ) logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s %(message)s", datefmt="[%Y-%m-%d %H:%M:%S]", ) logger = logging.getLogger(__name__) class syntheticEstimator(Estimator): @validated() def __init__( self, trainer: Trainer, freq: str, batch_size: int, num_batches_per_epoch: int, target_len: int, nb_features: int, ks_conv: int, key_features: int, value_features: int, ks_value: int, ks_query: int, ks_key: int, path_to_pretrain: str = None, use_feat_dynamic_real: bool = False, use_feat_static_cat: bool = True, use_feat_static_real: bool = False, num_workers: int = 0, device: str = "cpu", scaling: str = "local", cardinality: Optional[List[int]] = None, embedding_dim: int = 10, self_attention: bool = True, channel_nb: int = 32, pos_enc_dimension: int = 10, context_length: int = 0, exclude_index: list = None, ): super().__init__() self.trainer = trainer self.freq = freq self.batch_size = batch_size self.num_batches_per_epoch = num_batches_per_epoch self.target_len = target_len self.nb_features = nb_features self.ks_conv = ks_conv self.key_features = key_features self.value_features = value_features self.ks_value = ks_value self.ks_query = ks_query self.ks_key = ks_key self.use_feat_dynamic_real = use_feat_dynamic_real self.use_feat_static_cat = use_feat_static_cat self.use_feat_static_real = use_feat_static_real self.num_workers = num_workers self.channel_nb = channel_nb assert device == "cpu" or device == "gpu" self.device = torch.device("cuda" if device == "gpu" else "cpu") self.path_to_pretrain = path_to_pretrain assert ( scaling == "local" or scaling == "global" or scaling == "NoScale" ), "scaling has to be \ local or global. If it is local, then the whole time series will be\ mix-max scaled. If it is local, then each subseries of length \ target_len will be min-max scaled independenty. If is is NoScale\ then no scaling is applied to the dataset." self.scaling = scaling self.cardinality = cardinality self.embedding_dim = embedding_dim self.self_attention = self_attention self.pos_enc_dimension = pos_enc_dimension self.context_length = context_length assert context_length <= target_len if exclude_index is None: self.exclude_index = [] else: self.exclude_index = exclude_index def create_transformation( self, instance_splitter: bool = False, train=True ): time_features = time_features_from_frequency_str(self.freq) remove_field_names = [FieldName.FEAT_DYNAMIC_CAT] if not self.use_feat_static_real: remove_field_names.append(FieldName.FEAT_STATIC_REAL) if not self.use_feat_dynamic_real: remove_field_names.append(FieldName.FEAT_DYNAMIC_REAL) transformation = Chain( [RemoveFields(field_names=remove_field_names)] + ( [SetField(output_field=FieldName.FEAT_STATIC_CAT, value=[0.0])] if not self.use_feat_static_cat else [] ) + ( [ SetField( output_field=FieldName.FEAT_STATIC_REAL, value=[0.0] ) ] if not self.use_feat_static_real else [] ) + [ AddObservedValuesIndicator( target_field=FieldName.TARGET, output_field=FieldName.OBSERVED_VALUES, ), AsNumpyArray( field=FieldName.FEAT_STATIC_CAT, expected_ndim=1, dtype=np.float32, ), AddTimeFeatures( start_field=FieldName.START, target_field=FieldName.TARGET, output_field=FieldName.FEAT_TIME, time_features=time_features, pred_length=self.target_len, ), ] + ( [ AddPositionalEncoding( start_field=FieldName.START, target_field=FieldName.TARGET, output_field=FieldName.POS_ENCODING, pos_enc_dimension=self.pos_enc_dimension, ), VstackFeatures( output_field=FieldName.FEAT_TIME, input_fields=[ FieldName.FEAT_TIME, FieldName.POS_ENCODING, ], ), ] if self.pos_enc_dimension > 0 else [] ) + [ AddAgeFeature( target_field=FieldName.TARGET, output_field=FieldName.FEAT_AGE, pred_length=self.target_len, log_scale=True, dtype=np.float32, ), VstackFeatures( output_field=FieldName.FEAT_TIME, input_fields=[FieldName.FEAT_TIME, FieldName.FEAT_AGE] + ( [FieldName.FEAT_DYNAMIC_REAL] if self.use_feat_dynamic_real else [] ), ), ] + ( [ InstanceSplitter( target_field=FieldName.TARGET, is_pad_field=FieldName.IS_PAD, start_field=FieldName.START, forecast_start_field=FieldName.FORECAST_START, instance_sampler=ExpectedNumInstanceSampler( num_instances=1, min_future=self.target_len, ) if train else TestSplitSampler(min_past=self.target_len,), past_length=self.target_len, future_length=self.target_len, time_series_fields=[ FieldName.FEAT_TIME, FieldName.OBSERVED_VALUES, ], ) ] if instance_splitter else [] ), ) return transformation def _str2bool(self, v): return not (v.lower() in ("false")) def create_training_network(self): gen = ProGenerator( target_len=self.target_len, nb_features=self.nb_features, ks_conv=self.ks_conv, key_features=self.key_features, value_features=self.value_features, ks_value=self.ks_value, ks_query=self.ks_query, ks_key=self.ks_key, scaling=self.scaling, device=self.device.type, cardinality=self.cardinality, embedding_dim=self.embedding_dim, self_attention=self.self_attention, channel_nb=self.channel_nb, context_length=self.context_length, ) discrim = ProDiscriminator( target_len=self.target_len, nb_features=self.nb_features, ks_conv=self.ks_conv, key_features=self.key_features, value_features=self.value_features, ks_value=self.ks_value, ks_query=self.ks_query, ks_key=self.ks_key, cardinality=self.cardinality, embedding_dim=self.embedding_dim, self_attention=self.self_attention, channel_nb=self.channel_nb, ) network = ProGenDiscrim(discriminator=discrim, generator=gen) if self._str2bool(self.path_to_pretrain): network.load_state_dict( torch.load( self.path_to_pretrain, map_location=torch.device("cpu") )["generator_model_state_dict"] ) logger.info("Pre trained has been loaded") else: logger.info("No pre trained model has been loaded") return network def train( self, training_data: Dataset, validation_data: Optional[Dataset] = None ): transformation = self.create_transformation() ds = Data( training_data, transformation, self.num_batches_per_epoch, self.target_len, self.batch_size, device=self.device, scaling=self.scaling, context_length=self.context_length, exclude_index=self.exclude_index, ) dataloader = DataLoader(ds, batch_size=self.batch_size) net = self.create_training_network() logger.info( f"Batch Size : {self.batch_size},\ Number of Epochs : {self.trainer.num_epochs},\ Learning rate Generator : {self.trainer.lr_generator},\ Learning rate Discriminator : {self.trainer.lr_discriminator},\ Betas Generator : {self.trainer.betas_generator},\ Betas Discriminator : {self.trainer.betas_discriminator},\ Momment Loss : {self.trainer.momment_loss},\ Loss version : {self.trainer.use_loss},\ Pre-Trained Generator : {self.path_to_pretrain},\ Number epoch to fade in layer : {self.trainer.nb_epoch_fade_in_new_layer},\ Target length : {self.target_len},\ Kernel size : {self.ks_conv},\ Key features : {self.key_features},\ Value features : {self.value_features},\ Kernel size value : {self.ks_value},\ Kernel size query : {self.ks_query},\ Kernel size key : {self.ks_key},\ Scaling : {self.scaling},\ Cardinality : {self.cardinality},\ embedding_dim : {self.embedding_dim}\ channel nb: {self.channel_nb}\ positional encoding: {self.pos_enc_dimension}" ) self.trained_net = self.trainer(data_loader=dataloader, network=net) predictor = PyTorchPredictor( prediction_length=self.target_len, input_names=["past_target", "future_time_feat", "feat_static_cat"], batch_size=self.batch_size, freq=self.freq, prediction_net=ProGeneratorInference(self.trained_net.generator), input_transform=self.create_transformation( instance_splitter=True, train=False ), device="cpu", ) return predictor
python