id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
1789443
class Matrix: def __init__(self, matrix_string = ""): # Creo una lista de listas a partir del matrix_string; e es cada elemento de matrix_string.splitlines # (ej:'9 8 7'), e.split() es una lista hecha de cada iteracion de e (ej: [9,8,7]) self.matrix_List = [[int(num) for num in e.split()] for e in matrix_string.splitlines()] def row(self, index): # Debido a la forma en la que construi la matriz, solo es cuestion de regresar el item de la lista # de listas que corresponde a index # retorno una lista de la row creada de los elementos del item que corresponde a la row del index # para no mantener relacion con matrix_list return (self.matrix_List.copy())[index-1] def column(self, index): # List comprehension que te regresa la columna que corresponde al indice; La idea es recorrer las rows # y acceder a la columna respectiva desde la lista del row return [i[index-1] for i in self.matrix_List] ########### myMatrix = Matrix("1 2 3\n4 5 6\n 7 8 9") print(myMatrix.row(1)) print(myMatrix.column(1))
StarcoderdataPython
3281226
from django.utils.deprecation import MiddlewareMixin class MultipleProxyMiddleware(MiddlewareMixin): FORWARDED_FOR_FIELDS = [ 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED_HOST', 'HTTP_X_FORWARDED_SERVER', ] def process_request(self, request): """ Rewrites the proxy headers so that only the most recent proxy is used. """ for field in self.FORWARDED_FOR_FIELDS: if field in request.META: if ',' in request.META[field]: parts = request.META[field].split(',') request.META[field] = parts[-1].strip()
StarcoderdataPython
5016416
import sys sys.path.append('.') import unittest import numpy as np ### Custom Imports from environment.custom.knapsack.env import Knapsack from environment.custom.knapsack.backpack import Backpack, EOS_BACKPACK, NORMAL_BACKPACK from environment.custom.knapsack.item import Item class TestKnapsackEnv(unittest.TestCase): def test_constructor(self): env = Knapsack('knapsack', { "batch_size": 2, "num_items": 2, "num_backpacks": 1, "min_item_value": 3, "max_item_value": 4, "min_item_weight": 5, "max_item_weight": 6, "min_backpack_capacity": 7, "max_backpack_capacity": 8 }) self.assertEqual(env.batch_size, 2) self.assertEqual(env.num_items, 2) self.assertEqual(env.num_backpacks, 1) self.assertEqual(env.min_item_value, 3) self.assertEqual(env.max_item_value, 4) self.assertEqual(env.min_item_weight, 5) self.assertEqual(env.max_item_weight, 6) self.assertEqual(env.min_backpack_capacity, 7) self.assertEqual(env.max_backpack_capacity, 8) self.assertEqual(env.tensor_size, 4) # 2 Items + 1 Backpack + 1 EOS Backpack self.assertEqual(len(env.problem_list), 2) def test_generate_fn(self): env = Knapsack('knapsack', { "batch_size": 2, "num_items": 2, "num_backpacks": 2, "min_item_value": 3, "max_item_value": 3, "min_item_weight": 5, "max_item_weight": 5, "min_backpack_capacity": 10, "max_backpack_capacity": 10 }) prob_list = env.generate() self.assertEqual(len(prob_list), 2) sub_prob_1 = prob_list[0] self.assertEqual(len(sub_prob_1['backpacks']), 3) # 2 normal + 1 EOS backpack self.assertEqual(len(sub_prob_1['items']), 2) # 2 normal + 1 EOS backpack def test_state_fn(self): env = Knapsack('knapsack', { "batch_size": 2, "num_items": 2, "num_backpacks": 2, "min_item_value": 3, "max_item_value": 3, "min_item_weight": 5, "max_item_weight": 5, "min_backpack_capacity": 10, "max_backpack_capacity": 10 }) actual_state, _, _ = env.state() # Should be: # 2 -> batch size # 5 -> 1 EOS backpack + 2 normal backpacks + 2 items # 2 -> features self.assertEqual(actual_state.shape, (2,5,2)) expected_state = [ [ [0, 0], # EOS Backpack [10, 0], # Backpack 1 [10, 0], # Backpack 2 [5, 3], # Item 0 [5, 3] # Item 1 ], [ [0, 0], # EOS Backpack [10, 0], # Backpack 1 [10, 0], # Backpack 2 [5, 3], # Item 0 [5, 3] # Item 1 ] ] self.assertTrue(np.all(actual_state == expected_state)) def test_compute_masks_fn(self): env = Knapsack('knapsack', { "batch_size": 2, "num_items": 2, "num_backpacks": 2, "min_item_value": 3, "max_item_value": 3, "min_item_weight": 5, "max_item_weight": 5, "min_backpack_capacity": 10, "max_backpack_capacity": 10 }) actual_backpacks_masks, actual_items_masks = env.compute_masks() # Test masks shape self.assertEqual(actual_backpacks_masks.shape, (2,5)) self.assertEqual(actual_items_masks.shape, (2,5)) # Test the actual values of backpack mask expected_backpacks_masks = [ [0, 0, 0, 1, 1], [0, 0, 0, 1, 1] ] self.assertTrue(np.all(actual_backpacks_masks == expected_backpacks_masks)) # Test the actual values of backpack mask expected_item_masks = [ [1, 1, 1, 0, 0], [1, 1, 1, 0, 0] ] self.assertTrue(np.all(actual_items_masks == expected_item_masks)) def test_step_fn(self): env = Knapsack('knapsack', { "batch_size": 2, "num_items": 2, "num_backpacks": 2, "min_item_value": 3, "max_item_value": 3, "min_item_weight": 5, "max_item_weight": 5, "min_backpack_capacity": 10, "max_backpack_capacity": 10 }) action = [ [1, 3], # Problem 0: Place item 0 (index 3) at backpack 1 (index 1) [2, 4] # Problem 1: Place item 1 (index 4) at backpack 2 (index 2) ] actual_state, actual_rewards, actual_dones, info = env.step(action) # Test data shapes self.assertEqual(actual_state.shape, (2,5,2)) self.assertEqual(actual_rewards.shape, (2,1)) self.assertEqual(actual_dones.shape, (2,1)) self.assertEqual(info['backpack_net_mask'].shape, (2,5)) self.assertEqual(info['item_net_mask'].shape, (2,5)) self.assertEqual(info['num_items_to_place'], 2) expected_state = [ [ [0, 0], # [10, 3], # Backpack's value is equal to the selected item [10, 0], # [5, 3], # Item selected [5, 3] # ], [ [0, 0], # [10, 0], # [10, 3], # Backpack's value is equal to the selected item [5, 3], # [5, 3] # Item selected ] ] self.assertTrue(np.all(actual_state == expected_state)) expected_rewards = [ [3], [3] ] self.assertTrue(np.all(actual_rewards == expected_rewards)) expected_dones = [ [False], [False] ] self.assertTrue(np.all(actual_dones == expected_dones)) # Test the actual values of backpack mask expected_backpacks_masks = [ [0, 0, 0, 1, 1], [0, 0, 0, 1, 1] ] self.assertTrue(np.all(info['backpack_net_mask'] == expected_backpacks_masks)) # Test the actual values of backpack mask expected_item_masks = [ [1, 1, 1, 1, 0], [1, 1, 1, 0, 1] ] self.assertTrue(np.all(info['item_net_mask'] == expected_item_masks)) def test_multiple_steps_fn(self): env = Knapsack('knapsack', { "batch_size": 2, "num_items": 2, "num_backpacks": 2, "min_item_value": 3, "max_item_value": 3, "min_item_weight": 5, "max_item_weight": 5, "min_backpack_capacity": 10, "max_backpack_capacity": 10 }) action_list = np.array([ # 1 Step [ [1, 3], # Problem 0: Place item 0 (index 3) at backpack 1 (index 1) [2, 4] # Problem 1: Place item 1 (index 4) at backpack 2 (index 2) ], # 2 Step [ [2, 4], # Problem 0: Place item 0 (index 3) at EOS backpack (index 0) [0, 3] # Problem 1: Place item 1 (index 4) at EOS backpack (index 0) ] ]) actual_state, actual_rewards, actual_dones, info = env.multiple_steps(action_list) # Test data shapes self.assertEqual(actual_state.shape, (2,5,2)) self.assertEqual(actual_rewards.shape, (2,2)) self.assertEqual(actual_dones.shape, (2,2)) self.assertEqual(info['backpack_net_mask'].shape, (2,5)) self.assertEqual(info['item_net_mask'].shape, (2,5)) self.assertEqual(info['num_items_to_place'], 2) expected_state = [ [ [0, 0], # [10, 3], # Step 1: Backpack's value is equal to the selected item [10, 3], # Step 2: Backpack's value is equal to the selected item [5, 3], # Step 1: Item selected [5, 3] # Step 2: Item selected ], [ [0, 0], # Step 2: Backpack's value is equal to the selected item [10, 0], # [10, 3], # Step 1: Backpack's value is equal to the selected item [5, 3], # Step 2: Item selected [5, 3] # Step 1: Item selected ] ] self.assertTrue(np.all(actual_state == expected_state)) expected_rewards = [ [ 3.0, # Prob 1: Step 1 3.0 # Prob 1: Step 2 ], [ 3.0, # Prob 2: Step 1 0 # Prob 2: Step 1 ] ] self.assertTrue(np.all(actual_rewards == expected_rewards)) expected_dones = [ [ 0, # Prob 1: Step 1: Not Done -> 1 is still pending 1 # Prob 1: Step 2: Done -> All items are placed ], [ 0, # Prob 1: Step 1: Not Done -> 1 is still pending 1 # Prob 1: Step 2: Done -> All items are placed ] ] self.assertTrue(np.all(actual_dones == expected_dones)) # Test the actual values of backpack mask expected_backpacks_masks = [ [0, 0, 0, 1, 1], [0, 0, 0, 1, 1] ] self.assertTrue(np.all(info['backpack_net_mask'] == expected_backpacks_masks)) # Test the actual values of backpack mask expected_item_masks = [ [1, 1, 1, 1, 1], [1, 1, 1, 1, 1] ] self.assertTrue(np.all(info['item_net_mask'] == expected_item_masks))
StarcoderdataPython
3533190
import os, psutil, sys, time from library.city import * from library.database import * from multiprocessing import Process from IPython import embed from time import sleep from random import randint GLOBAL_THREADS = 3 def general_scraping(total_threads, thread_number): for city in City.select().where(City.finished == False): if city.id%total_threads != thread_number : continue else : name = city.name.decode('unicode_escape') link = city.link.decode('unicode_escape') sys.stdout.write("\nCrawling("+ str(thread_number) +") : " + name.encode('utf-8') + ", " + link.encode('utf-8') + "\n") if city.pages == 1 : city.finished = True city.save() for page in range(city.pages_crawled + 1, city.pages + 1): sys.stdout.write(str(page)+"#"+ str(thread_number)) y = ScrapeCityBasePage(city, city.link + "?pages" + str(page)) class MyProcessAbstraction(object): def __init__(self, parent_pid): self._child = None self._parent = psutil.Process(pid=parent_pid) def run_child(self, total_threads, thread_number): print("---- Starting Child: %i of %i ----" % (thread_number, total_threads)) # self._child = psutil.Popen(self._cmd) self._child_pid = os.getpid() self.thread_number = thread_number self.total_threads = total_threads self._child = psutil.Process(pid=self._child_pid) sys.stdout.write('---- Parent : '+str(self._parent.pid)+' ## Child : '+str(self._child_pid)) log_str = '(' + str(thread_number) + ' / ' + str(total_threads) + ') ----' try: sys.stdout.write("---- Inside Try " + log_str + " ----" + str(self._parent.status())) while self._parent.status() == psutil.STATUS_SLEEPING: sys.stdout.write("---- Inside While " + log_str) sys.stdout = open('/var/log/zomato_scraper_'+str(thread_number)+'_log.txt', 'a+') general_scraping(total_threads, thread_number) sleep(1) break sys.stdout.write("---- FINISHED Thread " + log_str) except psutil.NoSuchProcess: sys.stdout.write("---- Inside Except " + log_str) pass finally: sys.stdout.write("---- Terminating child PID %s (%i / %i)----\n" % (self._child.pid, self.thread_number, self.total_threads)) sys.exit() self._child.terminate() if __name__ == "__main__": parent = os.getpid() total_threads = GLOBAL_THREADS # main_thread_num = randint(0, total_threads-1) for thread_number in range(0,total_threads): child = MyProcessAbstraction(parent) child_proc = Process(target=child.run_child, args=(total_threads, thread_number)) child_proc.daemon = True child_proc.start() # general_scraping(total_threads, 0) sleep(3600) sys.stdout.write('---- Hourly finish of MAIN PROCESS ----' + "\n") error
StarcoderdataPython
3346055
<filename>Python/src/modules/Database/database.py import sqlite3 class DB: def __init__(self): self.__connection = sqlite3.connect("./database/database.db") self.__cursor = self.__connection.cursor() def getPriceByID(self, code:str) -> int: return int(((self.__cursor.execute('SELECT price FROM Products WHERE id=:code', {"code":code})).fetchall()[0])[0])
StarcoderdataPython
197340
<filename>qf_lib/common/enums/matplotlib_location.py # Copyright 2016-present CERN – European Organization for Nuclear Research # # 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 enum import Enum class Location(Enum): BEST = 0 UPPER_RIGHT = 1 UPPER_LEFT = 2 LOWER_LEFT = 3 LOWER_RIGHT = 4 RIGHT = 5 CENTER_LEFT = 6 CENTER_RIGHT = 7 LOWER_CENTER = 8 UPPER_CENTER = 9 CENTER = 10 def __init__(self, code): self.code = code class AxisLocation(Enum): """ Custom location for legend placements. In axis lengths for placement. e.g (1,0) = (x=1, y=0) = BOTTOM_RIGHT """ LOWER_RIGHT = (1, 0) LOWER_LEFT = (0, 0) UPPER_RIGHT = (1, 1) UPPER_LEFT = (0, 1)
StarcoderdataPython
6616410
<reponame>codeclimate-testing/falcon from testing_helpers import wrap @wrap def store_slice(): x = range(100) x[10:20] = range(50, 60) return x def test_store_slice(): store_slice() @wrap def store_slice1(): x = range(100) x[10:] = range(50, 60) return x def test_store_slice1(): store_slice1() @wrap def store_slice2(): x = range(100) x[:10] = range(50, 60) return x def test_store_slice2(): store_slice2() @wrap def store_slice3(): x = range(100) x[:] = range(50, 60) return x def test_store_slice3(): store_slice3() @wrap def load_slice0(): x = range(100) y = x[10:20] return y def test_load_slice0(): load_slice0() @wrap def load_slice1(): x = range(100) y = x[10:] return y def test_load_slice1(): load_slice1() @wrap def load_slice2(): x = range(100) y = x[:10] return y def test_load_slice2(): load_slice2() @wrap def load_slice3(): x = range(100) y = x[:] return y def test_load_slice3(): load_slice3() @wrap def load_slice4(): x = range(100) y = x[1::-1] return y def test_load_slice4(): load_slice4()
StarcoderdataPython
3456813
<filename>test.py #!/usr/bin/python from scheduler import scheduler import json scheduler = scheduler.Scheduler() class MyScheduler(object): @scheduler.on("new") def onNew(body): print "state: new received {}".format(body) scheduler.moveTo("running", json.dumps(body)) @scheduler.on("running") def onNew(body): print "state: running received {}".format(body) scheduler.moveTo("completed", json.dumps(body)) @scheduler.on("completed") def onNew(body): print "state: completed received {}".format(body) def initialize(self): payload = {"name": "<NAME>"} scheduler.moveTo("new", json.dumps(payload)) scheduler.intialize() myscheduler = MyScheduler() myscheduler.initialize() scheduler.run()
StarcoderdataPython
6495130
<reponame>naotohori/cafysis ATOM_MASS = { "H": 1.00797, "C": 12.0107, "N": 14.0067, "O": 15.9994, "Na": 22.98977, "Mg": 24.305, "P": 30.97376, "S": 32.06, "Cl": 35.453, "K": 39.0983, "Ca": 40.08, "Mn": 54.9380, "Fe": 55.847, "Cu": 63.546, "Zn": 65.38, "Br": 79.904, "Ag": 107.868, "I": 126.9045, }
StarcoderdataPython
5197407
def counting_triangles(V):
StarcoderdataPython
6422108
import ast import gzip from typing import Callable, Dict, Tuple, Union class JuliaExternalModulePlugins: def visit_gzipopen(t_self, node: ast.Call, vargs: list[str]): JuliaExternalModulePlugins._generic_gzip_visit(t_self) if vargs: return f"GZip.open({', '.join(vargs)})" # elif len(vargs) == 2: # return f"GZip.open({vargs[0]}, gzmode = {vargs[1]})" # elif len(vargs) == 3: # return f"GZip.open({vargs[0]}, gzmode = {vargs[1]}, buf_size = {vargs[2]})" return "GZip.open" def visit_gzipcompress(t_self, node: ast.Call, vargs: list[str]): JuliaExternalModulePlugins._generic_gzip_visit(t_self) return f"#Unsupported\nGZip.compress" def visit_gzipdecompress(t_self, node: ast.Call, vargs: list[str]): JuliaExternalModulePlugins._generic_gzip_visit(t_self) return f"#Unsupported\nGZip.decompress" def visit_gzipBadGzipFile(t_self, node: ast.Call, vargs: list[str]): JuliaExternalModulePlugins._generic_gzip_visit(t_self) # TODO: Temporary f"GZError(-1, \"gzopen failed\")" def _generic_gzip_visit(t_self): t_self._usings.add("GZip") FuncType = Union[Callable, str] FUNC_DISPATCH_TABLE: Dict[FuncType, Tuple[Callable, bool]] = { gzip.open: (JuliaExternalModulePlugins.visit_gzipopen, True), gzip.compress: (JuliaExternalModulePlugins.visit_gzipcompress, True), gzip.decompress: (JuliaExternalModulePlugins.visit_gzipdecompress, True), gzip.BadGzipFile: (JuliaExternalModulePlugins.visit_gzipBadGzipFile, True), } IGNORED_MODULE_SET = set([ "gzip" ])
StarcoderdataPython
11390759
# Copyright 2020 MONAI Consortium # 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. """ A collection of dictionary-based wrappers around the "vanilla" transforms for intensity adjustment defined in :py:class:`monai.transforms.intensity.array`. Class names are ended with 'd' to denote dictionary-based transforms. """ from typing import Hashable, Union, Optional import numpy as np from monai.transforms.compose import MapTransform, Randomizable from monai.transforms.intensity.array import ( NormalizeIntensity, ScaleIntensityRange, ThresholdIntensity, AdjustContrast, ShiftIntensity, ScaleIntensity, ) class RandGaussianNoised(Randomizable, MapTransform): """Dictionary-based version :py:class:`monai.transforms.RandGaussianNoise`. Add Gaussian noise to image. This transform assumes all the expected fields have same shape. Args: keys (hashable items): keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` prob (float): Probability to add Gaussian noise. mean (float or array of floats): Mean or “centre” of the distribution. std (float): Standard deviation (spread) of distribution. """ def __init__(self, keys: Hashable, prob: float = 0.1, mean=0.0, std: float = 0.1): super().__init__(keys) self.prob = prob self.mean = mean self.std = std self._do_transform = False self._noise = None def randomize(self, im_shape): self._do_transform = self.R.random() < self.prob self._noise = self.R.normal(self.mean, self.R.uniform(0, self.std), size=im_shape) def __call__(self, data): d = dict(data) image_shape = d[self.keys[0]].shape # image shape from the first data key self.randomize(image_shape) if not self._do_transform: return d for key in self.keys: d[key] = d[key] + self._noise.astype(d[key].dtype) return d class ShiftIntensityd(MapTransform): """ dictionary-based wrapper of :py:class:`monai.transforms.ShiftIntensity`. """ def __init__(self, keys: Hashable, offset: Union[int, float]): """ Args: keys (hashable items): keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` offset (int or float): offset value to shift the intensity of image. """ super().__init__(keys) self.shifter = ShiftIntensity(offset) def __call__(self, data): d = dict(data) for key in self.keys: d[key] = self.shifter(d[key]) return d class RandShiftIntensityd(Randomizable, MapTransform): """ dictionary-based version :py:class:`monai.transforms.RandShiftIntensity`. """ def __init__(self, keys: Hashable, offsets, prob: float = 0.1): """ Args: keys (hashable items): keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` offsets(int, float, tuple or list): offset range to randomly shift. if single number, offset value is picked from (-offsets, offsets). prob (float): probability of rotating. (Default 0.1, with 10% probability it returns a rotated array.) """ super().__init__(keys) self.offsets = (-offsets, offsets) if not isinstance(offsets, (list, tuple)) else offsets assert len(self.offsets) == 2, "offsets should be a number or pair of numbers." self.prob = prob self._do_transform = False def randomize(self): self._offset = self.R.uniform(low=self.offsets[0], high=self.offsets[1]) self._do_transform = self.R.random() < self.prob def __call__(self, data): d = dict(data) self.randomize() if not self._do_transform: return d shifter = ShiftIntensity(self._offset) for key in self.keys: d[key] = shifter(d[key]) return d class ScaleIntensityd(MapTransform): """ dictionary-based wrapper of :py:class:`monai.transforms.ScaleIntensity`. Scale the intensity of input image to the given value range (minv, maxv). If `minv` and `maxv` not provided, use `factor` to scale image by ``v = v * (1 + factor)``. """ def __init__( self, keys: Hashable, minv: Union[int, float] = 0.0, maxv: Union[int, float] = 1.0, factor: Optional[float] = None, ): """ Args: keys (hashable items): keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` minv (int or float): minimum value of output data. maxv (int or float): maximum value of output data. factor (float): factor scale by ``v = v * (1 + factor)``. """ super().__init__(keys) self.scaler = ScaleIntensity(minv, maxv, factor) def __call__(self, data): d = dict(data) for key in self.keys: d[key] = self.scaler(d[key]) return d class RandScaleIntensityd(Randomizable, MapTransform): """ dictionary-based version :py:class:`monai.transforms.RandScaleIntensity`. """ def __init__(self, keys: Hashable, factors, prob: float = 0.1): """ Args: keys (hashable items): keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` factors(float, tuple or list): factor range to randomly scale by ``v = v * (1 + factor)``. if single number, factor value is picked from (-factors, factors). prob (float): probability of rotating. (Default 0.1, with 10% probability it returns a rotated array.) """ super().__init__(keys) self.factors = (-factors, factors) if not isinstance(factors, (list, tuple)) else factors assert len(self.factors) == 2, "factors should be a number or pair of numbers." self.prob = prob self._do_transform = False def randomize(self): self.factor = self.R.uniform(low=self.factors[0], high=self.factors[1]) self._do_transform = self.R.random() < self.prob def __call__(self, data): d = dict(data) self.randomize() if not self._do_transform: return d scaler = ScaleIntensity(minv=None, maxv=None, factor=self.factor) for key in self.keys: d[key] = scaler(d[key]) return d class NormalizeIntensityd(MapTransform): """ dictionary-based wrapper of :py:class:`monai.transforms.NormalizeIntensity`. This transform can normalize only non-zero values or entire image, and can also calculate mean and std on each channel separately. Args: keys (hashable items): keys of the corresponding items to be transformed. See also: monai.transforms.MapTransform subtrahend (ndarray): the amount to subtract by (usually the mean) divisor (ndarray): the amount to divide by (usually the standard deviation) nonzero (bool): whether only normalize non-zero values. channel_wise (bool): if using calculated mean and std, calculate on each channel separately or calculate on the entire image directly. """ def __init__( self, keys: Hashable, subtrahend: Optional[np.ndarray] = None, divisor: Optional[np.ndarray] = None, nonzero: bool = False, channel_wise: bool = False, ): super().__init__(keys) self.normalizer = NormalizeIntensity(subtrahend, divisor, nonzero, channel_wise) def __call__(self, data): d = dict(data) for key in self.keys: d[key] = self.normalizer(d[key]) return d class ThresholdIntensityd(MapTransform): """ Dictionary-based wrapper of :py:class:`monai.transforms.ThresholdIntensity`. Args: keys (hashable items): keys of the corresponding items to be transformed. See also: monai.transforms.MapTransform threshold (float or int): the threshold to filter intensity values. above (bool): filter values above the threshold or below the threshold, default is True. cval (float or int): value to fill the remaining parts of the image, default is 0. """ def __init__(self, keys: Hashable, threshold: Union[int, float], above: bool = True, cval: Union[int, float] = 0): super().__init__(keys) self.filter = ThresholdIntensity(threshold, above, cval) def __call__(self, data): d = dict(data) for key in self.keys: d[key] = self.filter(d[key]) return d class ScaleIntensityRanged(MapTransform): """ Dictionary-based wrapper of :py:class:`monai.transforms.ScaleIntensityRange`. Args: keys (hashable items): keys of the corresponding items to be transformed. See also: monai.transforms.MapTransform a_min (int or float): intensity original range min. a_max (int or float): intensity original range max. b_min (int or float): intensity target range min. b_max (int or float): intensity target range max. clip (bool): whether to perform clip after scaling. """ def __init__( self, keys: Hashable, a_min: Union[int, float], a_max: Union[int, float], b_min: Union[int, float], b_max: Union[int, float], clip: bool = False, ): super().__init__(keys) self.scaler = ScaleIntensityRange(a_min, a_max, b_min, b_max, clip) def __call__(self, data): d = dict(data) for key in self.keys: d[key] = self.scaler(d[key]) return d class AdjustContrastd(MapTransform): """ Dictionary-based wrapper of :py:class:`monai.transforms.AdjustContrast`. Changes image intensity by gamma. Each pixel/voxel intensity is updated as: `x = ((x - min) / intensity_range) ^ gamma * intensity_range + min` Args: gamma (float): gamma value to adjust the contrast as function. """ def __init__(self, keys: Hashable, gamma: Union[int, float]): super().__init__(keys) self.adjuster = AdjustContrast(gamma) def __call__(self, data): d = dict(data) for key in self.keys: d[key] = self.adjuster(d[key]) return d class RandAdjustContrastd(Randomizable, MapTransform): """ Dictionary-based version :py:class:`monai.transforms.RandAdjustContrast`. Randomly changes image intensity by gamma. Each pixel/voxel intensity is updated as: `x = ((x - min) / intensity_range) ^ gamma * intensity_range + min` Args: keys (hashable items): keys of the corresponding items to be transformed. See also: monai.transforms.MapTransform prob (float): Probability of adjustment. gamma (tuple of float or float): Range of gamma values. If single number, value is picked from (0.5, gamma), default is (0.5, 4.5). """ def __init__(self, keys, prob=0.1, gamma=(0.5, 4.5)): super().__init__(keys) self.prob = prob if not isinstance(gamma, (tuple, list)): assert gamma > 0.5, "if gamma is single number, must greater than 0.5 and value is picked from (0.5, gamma)" self.gamma = (0.5, gamma) else: self.gamma = gamma assert len(self.gamma) == 2, "gamma should be a number or pair of numbers." self._do_transform = False self.gamma_value = None def randomize(self): self._do_transform = self.R.random_sample() < self.prob self.gamma_value = self.R.uniform(low=self.gamma[0], high=self.gamma[1]) def __call__(self, data): d = dict(data) self.randomize() if not self._do_transform: return d adjuster = AdjustContrast(self.gamma_value) for key in self.keys: d[key] = adjuster(d[key]) return d RandGaussianNoiseD = RandGaussianNoiseDict = RandGaussianNoised ShiftIntensityD = ShiftIntensityDict = ShiftIntensityd RandShiftIntensityD = RandShiftIntensityDict = RandShiftIntensityd ScaleIntensityD = ScaleIntensityDict = ScaleIntensityd RandScaleIntensityD = RandScaleIntensityDict = RandScaleIntensityd NormalizeIntensityD = NormalizeIntensityDict = NormalizeIntensityd ThresholdIntensityD = ThresholdIntensityDict = ThresholdIntensityd ScaleIntensityRangeD = ScaleIntensityRangeDict = ScaleIntensityRanged AdjustContrastD = AdjustContrastDict = AdjustContrastd RandAdjustContrastD = RandAdjustContrastDict = RandAdjustContrastd
StarcoderdataPython
3410703
<reponame>IoT-BA/project_noe-backend # -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-10-05 22:58 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0059_lorawanrawpoint_node'), ] operations = [ migrations.CreateModel( name='LoRaApplication', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=128)), ('AppEUI', models.CharField(max_length=128)), ('api_key', models.CharField(blank=True, max_length=256, null=True)), ], ), ]
StarcoderdataPython
6637961
# For deployment, change this to the hostname or IP address # of your server ALLOWED_HOSTS=['127.0.0.1'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'af_db.db' } } # This is for django-debug-toolbar which is an optional # development tool INTERNAL_IPS = ('127.0.0.1',) # Add optional dependencies DEBUG_APPS = ('debug_toolbar',) DEBUG = True TEMPLATE_DEBUG = DEBUG
StarcoderdataPython
5185780
from sklearn.ensemble import GradientBoostingRegressor from sklearn.datasets import load_boston from sklearn.utils import shuffle from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split import numpy as np from typing import Tuple def divide_datos( xdata: np.array, y: np.array ) -> Tuple[np.array, np.array, np.array, np.array]: """Toma un conjunto de datos `xdata` y sus etiquetas `y` y regresa un nuevo conjunto de datos dividido en etrenamiento y prueba. Arguments: xdata {np.array} -- Conjunto de datos y {np.array} -- Etiquetas del conjunto de datos Returns: Tuple[np.array, np.array, np.array, np.array] -- Conjunto de datos para entrenamiento, sus etiquetas y prueba con sus respectivas etiquetas. """ xtrain, xtest, ytrain, ytest = train_test_split(xdata, y, test_size=0.2) return xtrain, xtest, ytrain, ytest def ajuste_y_predice( xtrain: np.array, ytrain: np.array, xtest: np.array, ytest: np.array ) -> float: """Toma conjuntos de datos de prueba y entrenamiento, con sus respectivas etiquetas y realiza una regresión mediante el método de Boosting Trees Arguments: xtrain {np.array} -- Datos de entrenamiento ytrain {np.array} -- Etiquetas de entrenamiento xtest {np.array} -- Datos de prueba ytest {np.array} -- Etiquetas de prueba Returns: float -- Error cuadrático medio sobre el conjunto de prueba """ params = { "n_estimators": 500, "max_depth": 4, "min_samples_split": 2, "learning_rate": 0.01, "loss": "ls", } clf = GradientBoostingRegressor(**params) clf.fit(xtrain, ytrain) mse = mean_squared_error(ytest, clf.predict(xtest)) return mse if __name__ == "__main__": boston = load_boston() x_data, y = boston.data, boston.target xtrain, xtest, ytrain, ytest = divide_datos(x_data, y) resultado = ajuste_y_predice(xtrain, ytrain, xtest, ytest) print(f"MSE del ajuste: {resultado}")
StarcoderdataPython
1958388
""" PyPages ------- Do pagination in python like a charm. Links ````` * `documentation <https://github.com/fengsp/pypages>`_ * `development version <http://github.com/fengsp/pypages/zipball/master#egg=pypages-dev>`_ """ from setuptools import setup setup( name='PyPages', version='0.1', url='https://github.com/fengsp/pypages', license='BSD', author='<NAME>', author_email='<EMAIL>', description='Python Pagination for Humans', long_description=__doc__, py_modules=['pypages'], zip_safe=False, platforms='any', classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
StarcoderdataPython
12855481
import numpy as np from .cnn import CNN from .kviews import KViews from .. import const class EndToEnd(): def __init__( self, bg_model: CNN, rs_model: KViews ) -> None: self.name = 'EndToEnd' self.bg_model = bg_model self.rs_model = rs_model def metadata(self): return self.bg_model.metadata() + self.rs_model.metadata() def predict(self, image: np.ndarray) -> np.ndarray: # first find background preds = self.bg_model.predict(image) # cuticle detected, so use rs_model if preds.any() == const.BG_LABEL_MAP['cuticle']: idx = np.where(preds == 1) rs_preds = self.rs_model.predict(image[idx]) # remap (0, 1) to (1, 2) mp = {0: 1, 1: 2} rs_preds = np.array([mp[i] for i in rs_preds]) preds[idx] = rs_preds return preds
StarcoderdataPython
4950267
<filename>src/electionguardFlaskApi/election_controller.py from typing import List import pickle import os from electionguard.ballot import PlaintextBallot, CiphertextBallot from electionguardFlaskApi.election import * # Define filenames for data storage METADATA = '/metadata.obj' CONTEXT = '/context.obj' ENCRYPTER = '/encrypter.obj' BALLOT_BOX = '/ballot_box.obj' STORE = '/store.obj' BALLOTS_ENCRYPTED = '/ballots_encrypted.obj' KEYPAIR = '/keypair.obj' """ ElectionController mainly handles loading and storing of data and then calling the desired function in election.py with this data. I don't know if it makes sense to make ElectionController a class. I did it this way to make it more obvious that the flask app only calls functions from the controller. """ class ElectionController: # Path where all the election data gets stored. Default: ./data/ path: str def __init__(self, path: str) -> None: self.path = path print("Initialized Controller") def create_election(self, election_id: str) -> dict: election_path: str = self.path + election_id if os.path.isdir(election_path): return { 'success': 0, 'msg': 'Election already exists' } os.makedirs(election_path) (metadata, context, encrypter, ballot_box, store, keypair) = create() ballots_encrypted: List = [] # TODO: Close opened files... Maybe automate storing things with pickle pickle.dump(metadata, open(election_path + METADATA, 'wb')) pickle.dump(context, open(election_path + CONTEXT, 'wb')) pickle.dump(encrypter, open(election_path + ENCRYPTER, 'wb')) pickle.dump(ballot_box, open(election_path + BALLOT_BOX, 'wb')) pickle.dump(store, open(election_path + STORE, 'wb')) pickle.dump(ballots_encrypted, open(election_path + BALLOTS_ENCRYPTED, 'wb')) pickle.dump(keypair, open(election_path + KEYPAIR, 'wb')) return { 'success': 1, 'msg': 'Election created' } def encrypt_ballot(self, election_id: str, data: dict) -> dict: election_path: str = self.path + election_id encrypter = pickle.load(open(election_path + ENCRYPTER, 'rb')) ballots_encrypted = pickle.load(open(election_path + BALLOTS_ENCRYPTED, 'rb')) encrypted_ballot: CiphertextBallot = encrypt(data['ballot'], encrypter) ballots_encrypted.append(encrypted_ballot) pickle.dump(ballots_encrypted, open(election_path + BALLOTS_ENCRYPTED, 'wb')) return { 'success': 1, 'msg': 'Ballot was encrypted and stored', 'ballotTracker': encrypted_ballot.get_tracker_code() } def cast_spoil_ballot(self, election_id: str, data: dict, do_cast: bool) -> dict: election_path: str = self.path + election_id ballots_encrypted = pickle.load(open(election_path + BALLOTS_ENCRYPTED, 'rb')) ballot_box = pickle.load(open(election_path + BALLOT_BOX, 'rb')) store = pickle.load(open(election_path + STORE, 'rb')) metadata = pickle.load(open(election_path + METADATA, 'rb')) context = pickle.load(open(election_path + CONTEXT, 'rb')) (res, store_new) = cast_spoil(data['ballotId'], do_cast, ballots_encrypted, store, metadata, context) pickle.dump(store_new, open(election_path + STORE, 'wb')) msg_end = 'cast' if do_cast else 'spoiled' if res: return { 'success': 1, 'msg': f'Ballot successfully {msg_end}' } else: return { 'success': 0, 'msg': f'Ballot could not be {msg_end}' } def create_tally(self, election_id: str): election_path: str = self.path + election_id store = pickle.load(open(election_path + STORE, 'rb')) metadata = pickle.load(open(election_path + METADATA, 'rb')) context = pickle.load(open(election_path + CONTEXT, 'rb')) keypair = pickle.load(open(election_path + KEYPAIR, 'rb')) res = tally(store, metadata, context, keypair) if res: return { 'success': 1, 'msg': 'Tallied ballots and decrypted result', 'decryptedTally': res } else: return { 'success': 0 }
StarcoderdataPython
1931068
from datetime import datetime from .base import ServiceBase from wafec.fi.hypothesis.models import * from .test_service import TestService from wafec.fi.hypothesis.exceptions import NotFoundException from sqlalchemy import and_ class ParameterService(ServiceBase): def __init__(self): ServiceBase.__init__(self) self.test_service = TestService() def create_service_if_not_exists(self, service): service_instance = self.db_session.query(FITestParameterService).filter_by(service_name=service).one_or_none() if not service_instance: service_instance = FITestParameterService() service_instance.service_name = service self.db_session.add(service_instance) return service_instance def create_context_if_not_exists(self, context): context_instance = self.db_session.query(FITestParameterContext).filter_by(context_label=context).one_or_none() if not context_instance: context_instance = FITestParameterContext() context_instance.context_label = context self.db_session.add(context_instance) return context_instance def create(self, name, service, context): test_last = self.test_service.get_last_test() if not test_last: raise NotFoundException('No test found') parameter_instance = None service_instance = self.db_session.query(FITestParameterService).filter_by(service_name=service).one_or_none() context_instance = self.db_session.query(FITestParameterContext).filter_by(context_label=context).one_or_none() if service_instance and context_instance: parameter_instance = self.db_session.query(FITestParameter).filter( and_(FITestParameter.name == name, FITestParameter.test_id == test_last.id, FITestParameter.test_parameter_service_id == service_instance.id, FITestParameter.test_parameter_context_id == context_instance.id)).one_or_none() if not parameter_instance: if not service_instance: service_instance = self.create_service_if_not_exists(service) if not context_instance: context_instance = self.create_context_if_not_exists(context) parameter_instance = FITestParameter() parameter_instance.name = name parameter_instance.test = test_last parameter_instance.test_parameter_service = service_instance parameter_instance.test_parameter_context = context_instance parameter_instance.created_at = datetime.now() parameter_instance.updated_at = datetime.now() parameter_instance.updated_count = 1 self.db_session.add(parameter_instance) else: updated_count = parameter_instance.updated_count if parameter_instance.updated_count else 1 parameter_instance.updated_count = updated_count + 1 parameter_instance.updated_at = datetime.now() return parameter_instance
StarcoderdataPython
6669152
from __future__ import absolute_import import tensorflow as tf from .core import DecomonLayer import tensorflow.keras.backend as K from tensorflow.keras.backend import bias_add, conv2d import numpy as np from tensorflow.keras.constraints import NonNeg from tensorflow.keras import initializers # from tensorflow.python.keras.engine.base_layer import InputSpec from tensorflow.keras.layers import ( Conv2D, Dense, Activation, Flatten, Reshape, Dot, Input, BatchNormalization, Dropout, Lambda, InputSpec, InputLayer ) try: from keras.layers.merge import _Merge as Merge except ModuleNotFoundError: from tensorflow.python.keras.layers.merge import _Merge as Merge from decomon.layers import activations from decomon.layers.utils import NonPos, ClipAlpha, MultipleConstraint, Project_initializer_pos, Project_initializer_neg, ClipAlphaAndSumtoOne from tensorflow.python.keras.utils import conv_utils from tensorflow.python.keras.utils.generic_utils import to_list from decomon.layers.utils import get_upper, get_lower, sort from .maxpooling import DecomonMaxPooling2D from .decomon_reshape import DecomonReshape, DecomonPermute from .decomon_merge_layers import ( DecomonConcatenate, DecomonAverage, DecomonAdd, DecomonMinimum, DecomonMaximum, DecomonSubtract, to_monotonic_merge, ) from .utils import grad_descent from .core import F_FORWARD, F_IBP, F_HYBRID, DEEL_LIP, Ball import warnings import inspect try: from .deel_lip import DecomonGroupSort, DecomonGroupSort2 except ModuleNotFoundError: pass class DecomonConv2D(Conv2D, DecomonLayer): """ Forward LiRPA implementation of Conv2d layers. See Keras official documentation for further details on the Conv2d operator """ def __init__(self, filters, kernel_size, mode=F_HYBRID.name, **kwargs): activation = kwargs["activation"] if "activation" in kwargs: kwargs["activation"] = None super(DecomonConv2D, self).__init__(filters=filters, kernel_size=kernel_size, mode=mode, **kwargs) self.kernel_constraint_pos_ = NonNeg() self.kernel_constraint_neg_ = NonPos() self.kernel_pos = None self.kernel_neg = None self.kernel = None self.kernel_constraints_pos = None self.kernel_constraints_neg = None self.activation = activations.get(activation) self.bias = None self.w_ = None if self.mode == F_HYBRID.name: self.input_spec = [ #InputSpec(min_ndim=4), # y InputSpec(min_ndim=2), # z InputSpec(min_ndim=4), # u InputSpec(min_ndim=4), # wu InputSpec(min_ndim=4), # bu InputSpec(min_ndim=4), # l InputSpec(min_ndim=4), # wl InputSpec(min_ndim=4), # bl ] elif self.mode == F_IBP.name: self.input_spec = [ #InputSpec(min_ndim=4), # y #InputSpec(min_ndim=2), # z InputSpec(min_ndim=4), # u InputSpec(min_ndim=4), # l ] elif self.mode == F_FORWARD.name: self.input_spec = [ #InputSpec(min_ndim=4), # y InputSpec(min_ndim=2), # z InputSpec(min_ndim=4), # wu InputSpec(min_ndim=4), # bu InputSpec(min_ndim=4), # wl InputSpec(min_ndim=4), # bl ] if self.dc_decomp: self.input_spec += [InputSpec(min_ndim=4), InputSpec(min_ndim=4)] self.diag_op = Lambda(lambda x: tf.linalg.diag(x)) def build(self, input_shape): """ :param input_shape: :return: """ assert len(input_shape) == self.nb_tensors if self.data_format == "channels_first": channel_axis = 1 else: channel_axis = -1 if input_shape[0][channel_axis] is None: raise ValueError("The channel dimension of the inputs " "should be defined. Found `None`.") input_dim = input_shape[-1][channel_axis] kernel_shape = self.kernel_size + (input_dim, self.filters) if not self.shared: self.kernel = self.add_weight( shape=kernel_shape, initializer=self.kernel_initializer, name="kernel_all", regularizer=self.kernel_regularizer, constraint=self.kernel_constraint, ) if self.use_bias: self.bias = self.add_weight( shape=(self.filters,), initializer=self.bias_initializer, name="bias_pos", regularizer=self.bias_regularizer, constraint=self.bias_constraint, ) else: self.bias = None if self.finetune and self.mode == F_HYBRID.name: # create extra parameters that can be optimized n_in_ = input_shape[-1][1:] self.n_in_ = [e for e in n_in_] nb_comp = int(np.prod(to_list(self.kernel_size))*self.filters/np.prod(to_list(self.strides))) self.n_comp = nb_comp self.alpha_ = self.add_weight( shape=[nb_comp]+n_in_, initializer="ones", name="alpha_f", regularizer=None, constraint=ClipAlpha(), ) self.gamma_ = self.add_weight( shape=nb_comp+n_in_, initializer="ones", name="gamma_f", regularizer=None, constraint=ClipAlpha(), ) n_out_ = self.compute_output_shape(input_shape)[-1][1:] self.n_out_ = [e for e in n_out_] self.alpha_out = self.add_weight( shape=[nb_comp]+self.n_out_, initializer="ones", name="alpha_f", regularizer=None, constraint=ClipAlphaAndSumtoOne(), ) self.gamma_out = self.add_weight( shape=[nb_comp] + self.n_out_, initializer="ones", name="alpha_f", regularizer=None, constraint=ClipAlphaAndSumtoOne(), # list of constraints ? ) self.built = True def get_backward_weights(self, inputs, flatten=True): #if self.w_ is None: z_value = K.cast(0.0, K.floatx()) o_value = K.cast(1., K.floatx()) b_u = inputs[-1] n_in = np.prod(b_u.shape[1:]) id_ = self.diag_op(z_value * Flatten()(b_u[0][None]) + o_value) id_ = K.reshape(id_, [-1] + list(b_u.shape[1:])) w_ = conv2d( id_, self.kernel, strides=self.strides, padding=self.padding, data_format=self.data_format, dilation_rate=self.dilation_rate, ) if flatten: if self.data_format == "channels_last": c_in, height, width, c_out = w_.shape w_ = K.reshape(w_, (c_in*height*width, c_out)) else: c_out, height, width, c_in = w_.shape w_ = K.reshape(w_, (c_out, c_in * height * width)) w_ = K.transpose(w_, (1, 0)) w_ = K.reshape(w_, (n_in, -1)) n_repeat = int(w_.shape[-1]/self.bias.shape[-1]) b_ = K.reshape(K.repeat(self.bias[None], n_repeat), (-1,)) return w_, b_ def shared_weights(self, layer): if not self.shared: pass self.kernel = layer.kernel self.bias = layer.bias def set_linear(self, bool_init): if self.activation is not None and self.get_config()['activation'] != 'linear': self.linear_layer=bool_init def call_linear(self, inputs, **kwargs): """ computing the perturbation analysis of the operator without the activation function :param inputs: list of input tensors :param kwargs: :return: List of updated tensors """ z_value = K.cast(0.0, K.floatx()) o_value = K.cast(1., K.floatx()) if not isinstance(inputs, list): raise ValueError("A merge layer should be called " "on a list of inputs.") if self.mode not in [F_HYBRID.name, F_IBP.name, F_FORWARD.name]: raise ValueError("unknown forward mode {}".format(self.mode)) if self.mode == F_HYBRID.name: if self.dc_decomp: #y, x_0, u_c, w_u, b_u, l_c, w_l, b_l, h, g = inputs[: self.nb_tensors] x_0, u_c, w_u, b_u, l_c, w_l, b_l, h, g = inputs[: self.nb_tensors] else: #y, x_0, u_c, w_u, b_u, l_c, w_l, b_l = inputs[: self.nb_tensors] x_0, u_c, w_u, b_u, l_c, w_l, b_l = inputs[: self.nb_tensors] elif self.mode == F_IBP.name: if self.dc_decomp: #y, x_0, u_c, l_c, h, g = inputs[: self.nb_tensors] u_c, l_c, h, g = inputs[: self.nb_tensors] else: #y, x_0, u_c, l_c = inputs[: self.nb_tensors] u_c, l_c = inputs[: self.nb_tensors] elif self.mode == F_FORWARD.name: if self.dc_decomp: #y, x_0, w_u, b_u, w_l, b_l, h, g = inputs[: self.nb_tensors] x_0, w_u, b_u, w_l, b_l, h, g = inputs[: self.nb_tensors] else: #y, x_0, w_u, b_u, w_l, b_l = inputs[: self.nb_tensors] x_0, w_u, b_u, w_l, b_l = inputs[: self.nb_tensors] #y_ = conv2d( # y, # self.kernel, # strides=self.strides, # padding=self.padding, # data_format=self.data_format, # dilation_rate=self.dilation_rate, #) def conv_pos(x): return conv2d( x, K.maximum(z_value, self.kernel), strides=self.strides, padding=self.padding, data_format=self.data_format, dilation_rate=self.dilation_rate, ) def conv_neg(x): return conv2d( x, K.minimum(z_value, self.kernel), strides=self.strides, padding=self.padding, data_format=self.data_format, dilation_rate=self.dilation_rate, ) if self.finetune and self.mode ==F_HYBRID.name: """ def conv_pos_alpha(x): return conv2d( x, K.maximum(z_value, self.kernel*self.alpha_), strides=self.strides, padding=self.padding, data_format=self.data_format, dilation_rate=self.dilation_rate, ) def conv_pos_gamma(x): return conv2d( x, K.maximum(z_value, self.kernel*self.gamma_), strides=self.strides, padding=self.padding, data_format=self.data_format, dilation_rate=self.dilation_rate, ) def conv_neg_alpha(x): return conv2d( x, K.minimum(z_value, self.kernel*self.alpha_), strides=self.strides, padding=self.padding, data_format=self.data_format, dilation_rate=self.dilation_rate, ) def conv_neg_gamma(x): return conv2d( x, K.minimum(z_value, self.kernel*self.gamma_), strides=self.strides, padding=self.padding, data_format=self.data_format, dilation_rate=self.dilation_rate, ) """ if self.dc_decomp: h_ = conv_pos(h) + conv_neg(g) g_ = conv_pos(g) + conv_neg(h) if self.mode in [F_HYBRID.name, F_IBP.name]: u_c_ = conv_pos(u_c) + conv_neg(l_c) l_c_ = conv_pos(l_c) + conv_neg(u_c) if self.mode in [F_FORWARD.name, F_HYBRID.name]: y_ = conv2d( b_u, self.kernel, strides=self.strides, padding=self.padding, data_format=self.data_format, dilation_rate=self.dilation_rate, ) if len(w_u.shape) == len(b_u.shape): id_ = self.diag_op(z_value * Flatten()(b_u[0][None]) + o_value) id_ = K.reshape(id_, [-1] + list(b_u.shape[1:])) w_u_ = conv2d( id_, self.kernel, strides=self.strides, padding=self.padding, data_format=self.data_format, dilation_rate=self.dilation_rate, ) w_u_ = K.expand_dims(w_u_, 0) + z_value * K.expand_dims(y_, 1) w_l_ = w_u_ b_u_ = 0 * y_ b_l_ = 0 * y_ if self.finetune and self.mode == F_HYBRID.name: self.frozen_alpha = True self.finetune=False self._trainable_weights = self._trainable_weights[:-4] else: # check for linearity #mask_b = 0 * y_ #mask_b = 0*b_u #if self.mode in [F_HYBRID.name]: # F_FORWARD.name x_max = get_upper(x_0, w_u - w_l, b_u - b_l, self.convex_domain) mask_b = o_value - K.sign(x_max) mask_a = o_value - mask_b def step_pos(x, _): return conv_pos(x), [] def step_neg(x, _): return conv_neg(x), [] if self.mode == F_HYBRID.name and self.finetune: b_u_ = K.rnn(step_function=step_pos, inputs=self.alpha_[None] * (b_u - u_c)[:,None], initial_states=[], unroll=False)[1] + u_c_[:,None]+\ K.rnn(step_function=step_neg, inputs=self.alpha_[None] * (b_l - l_c)[:, None], initial_states=[], unroll=False)[1] b_l_ = K.rnn(step_function=step_pos, inputs=self.gamma_[None] * (b_l - l_c)[:,None], initial_states=[], unroll=False)[1] + l_c_[:,None]+\ K.rnn(step_function=step_neg, inputs=self.gamma_[None] * (b_u - u_c)[:, None], initial_states=[], unroll=False)[1] else: #b_u_ = conv_pos(b_u) + conv_neg(mask_a * b_l + mask_b * b_u) #b_l_ = conv_pos(b_l) + conv_neg(mask_a * b_u + mask_b * b_l) b_u_ = conv_pos(b_u) + conv_neg(b_l) b_l_ = conv_pos(b_l) + conv_neg(b_u) mask_a = K.expand_dims(mask_a, 1) mask_b = K.expand_dims(mask_b, 1) if self.mode == F_HYBRID.name and self.finetune: n_x = w_u.shape[1] w_u_alpha = K.reshape(self.alpha_[None,None]*w_u[:,:,None], [-1, n_x*self.n_comp]+ self.n_in_) w_l_alpha = K.reshape(self.alpha_[None, None] * w_l[:,:,None], [-1, n_x * self.n_comp] + self.n_in_) w_u_gamma = K.reshape(self.gamma_[None, None] * w_u[:,:,None], [-1, n_x * self.n_comp] + self.n_in_) w_l_gamma = K.reshape(self.gamma_[None, None] * w_l[:,:,None], [-1, n_x * self.n_comp] + self.n_in_) w_u_ = K.rnn(step_function=step_pos, inputs=w_u_alpha, initial_states=[], unroll=False)[1] +\ K.rnn(step_function=step_neg, inputs=w_l_alpha, initial_states=[],unroll=False)[1] w_l_ = K.rnn(step_function=step_pos, inputs=w_l_gamma, initial_states=[], unroll=False)[1] + \ K.rnn(step_function=step_neg, inputs=w_u_gamma, initial_states=[], unroll=False)[1] n_out = [e for e in w_u_.shape[2:]] w_u_ = K.reshape(w_u_, [-1, n_x, self.n_comp]+n_out) w_l_ = K.reshape(w_l_, [-1, n_x, self.n_comp] + n_out) else: w_u_ = ( K.rnn(step_function=step_pos, inputs=w_u, initial_states=[], unroll=False)[1] + K.rnn( step_function=step_neg, inputs=w_l, initial_states=[], unroll=False )[1] ) w_l_ = ( K.rnn(step_function=step_pos, inputs=w_l, initial_states=[], unroll=False)[1] + K.rnn( step_function=step_neg, inputs=w_u, initial_states=[], unroll=False )[1] ) # add bias if self.mode == F_HYBRID.name: upper_ = get_upper(x_0, w_u_, b_u_, self.convex_domain) lower_ = get_lower(x_0, w_l_, b_l_, self.convex_domain) if self.finetune: # retrieve the best relaxation of the n_comp possible upper_ = K.min(upper_, 1) lower_ = K.max(lower_, 1) # affine combination on the output: take the best b_u_ = K.sum(self.alpha_out[None]*b_u_, 1) b_l_ = K.sum(self.gamma_out[None] * b_l_, 1) w_u_ = K.sum(self.alpha_out[None,None]*w_u_, 2) w_l_ = K.sum(self.gamma_out[None,None]*w_l_, 2) u_c_ = K.minimum(upper_, u_c_) l_c_ = K.maximum(lower_, l_c_) if self.use_bias: #y_ = bias_add(y_, self.bias, data_format=self.data_format) if self.dc_decomp: g_ = bias_add(g_, K.minimum(z_value, self.bias), data_format=self.data_format) h_ = bias_add(h_, K.maximum(z_value, self.bias), data_format=self.data_format) if self.mode in [F_HYBRID.name, F_FORWARD.name]: b_u_ = bias_add(b_u_, self.bias, data_format=self.data_format) b_l_ = bias_add(b_l_, self.bias, data_format=self.data_format) if self.mode in [F_HYBRID.name, F_IBP.name]: u_c_ = bias_add(u_c_, self.bias, data_format=self.data_format) l_c_ = bias_add(l_c_, self.bias, data_format=self.data_format) if self.mode == F_HYBRID.name: upper_ = get_upper(x_0, w_u_, b_u_, self.convex_domain) u_c_ = K.minimum(upper_, u_c_) lower_ = get_lower(x_0, w_l_, b_l_, self.convex_domain) l_c_ = K.maximum(lower_, l_c_) if self.mode == F_HYBRID.name: #output = [y_, x_0, u_c_, w_u_, b_u_, l_c_, w_l_, b_l_] output = [x_0, u_c_, w_u_, b_u_, l_c_, w_l_, b_l_] elif self.mode == F_IBP.name: #output = [y_, x_0, u_c_, l_c_] output = [u_c_, l_c_] elif self.mode == F_FORWARD.name: #output = [y_, x_0, w_u_, b_u_, w_l_, b_l_] output = [x_0, w_u_, b_u_, w_l_, b_l_] if self.dc_decomp: output += [h_, g_] return output def call(self, inputs, **kwargs): """ :param inputs: :return: """ output = self.call_linear(inputs, **kwargs) # temporary fix until all activations are ready if self.activation is not None: output = self.activation(output, dc_decomp=self.dc_decomp, mode=self.mode) return output def compute_output_shape(self, input_shape): """ :param input_shape: :return: """ assert len(input_shape) == self.nb_tensors if self.mode == F_IBP.name: y_shape = input_shape[0] if self.mode == F_FORWARD.name: x_0_shape = input_shape[0] y_shape = input_shape[2] if self.mode == F_HYBRID.name: x_0_shape = input_shape[0] y_shape = input_shape[1] #y_shape, x_0_shape = input_shape[:2] if self.data_format == "channels_last": space = y_shape[1:-1] elif self.data_format == "channels_first": space = y_shape[2:] new_space = [] for i in range(len(space)): new_dim = conv_utils.conv_output_length( space[i], self.kernel_size[i], padding=self.padding, stride=self.strides[i], dilation=self.dilation_rate[i], ) new_space.append(new_dim) if self.data_format == "channels_last": output_shape = (y_shape[0],) + tuple(new_space) + (self.filters,) elif self.data_format == "channels_first": output_shape = (y_shape[0], self.filters) + tuple(new_space) # b_u_shape_, b_l_shape_, u_c_shape, l_c_shape = [output_shape] * 4 #input_dim = x_0_shape[-1] if self.mode == F_IBP.name: #output_shape_ = [output_shape, x_0_shape, output_shape, output_shape] output_shape_ = [output_shape]*2 else: input_dim = x_0_shape[-1] w_shape_ = tuple([output_shape[0], input_dim] + list(output_shape)[1:]) if self.mode == F_FORWARD.name: #output_shape_ = [output_shape, x_0_shape] + [w_shape_, output_shape] * 2 output_shape_ = [x_0_shape] + [w_shape_, output_shape] * 2 if self.mode == F_HYBRID.name: #output_shape_ = [output_shape, x_0_shape] + [output_shape, w_shape_, output_shape] * 2 output_shape_ = [x_0_shape] + [output_shape, w_shape_, output_shape] * 2 if self.dc_decomp: output_shape_ += [output_shape] * 2 return output_shape_ def reset_layer(self, layer): """ :param layer: :return: """ # assert than we have the same configuration assert isinstance(layer, Conv2D), "wrong type of layers..." params = layer.get_weights() if self.finetune: params += self.get_weights()[2:] self.set_weights(params) def freeze_weights(self): if not self.frozen_weights: if self.finetune and self.mode == F_HYBRID.name: if self.use_bias: self._trainable_weights = self._trainable_weights[2:] else: self._trainable_weights = self._trainable_weights[1:] else: self._trainable_weights = [] self.frozen_weights = True def unfreeze_weights(self): if self.frozen_weights: if self.use_bias: self._trainable_weights = [self.bias] + self._trainable_weights self._trainable_weights = [self.kernel] + self._trainable_weights self.frozen_weights = False def freeze_alpha(self): if not self.frozen_alpha: if self.finetune and self.mode == F_HYBRID.name: self._trainable_weights = self._trainable_weights[:-4] self.frozen_alpha = True def unfreeze_alpha(self): if self.frozen_alpha: if self.finetune and self.mode == F_HYBRID.name: self._trainable_weights += [self.alpha_, self.gamma_, self.alpha_out, self.gamma_out] self.frozen_alpha = False def reset_finetuning(self): if self.finetune and self.mode == F_HYBRID.name: K.set_value(self.alpha_, np.ones_like(self.alpha_.value())) K.set_value(self.gamma_, np.ones_like(self.gamma_.value())) K.set_value(self.alpha_out, np.ones_like(self.alpha_neg_out.value())) K.set_value(self.gamma_out, np.ones_like(self.gamma_pos_out.value())) class DecomonDense(Dense, DecomonLayer): """ Forward LiRPA implementation of Dense layers. See Keras official documentation for further details on the Dense operator """ def __init__(self, units, mode=F_HYBRID.name, **kwargs): if "activation" not in kwargs: kwargs["activation"] = None activation = kwargs["activation"] kwargs["units"] = units kwargs["kernel_constraint"] = None super(DecomonDense, self).__init__(mode=mode, **kwargs) self.mode = mode self.kernel_constraint_pos_ = NonNeg() self.kernel_constraint_neg_ = NonPos() self.input_spec = [InputSpec(min_ndim=2) for _ in range(self.nb_tensors)] self.kernel_pos = None self.kernel_neg = None self.kernel = None self.kernel_constraints_pos = None self.kernel_constraints_neg = None self.activation = activations.get(activation) self.dot_op = Dot(axes=(1, 2)) self.n_subgrad = 0 # deprecated optimization scheme if activation is None: self.activation_name = 'linear' else: self.activation_name = activation self.input_shape_build=None self.op_dot = K.dot def build(self, input_shape): """ :param input_shape: list of input shape :return: """ assert len(input_shape) >= self.nb_tensors if self.mode==F_IBP.name: input_dim = input_shape[0][-1] if self.mode == F_HYBRID.name: input_dim = input_shape[1][-1] input_x = input_shape[0][-1] if self.mode == F_FORWARD.name: input_dim = input_shape[2][-1] input_x = input_shape[0][-1] # here pay attention to compute input_dim #input_dim = input_shape[0][-1] #input_x = input_shape[1][-1] if not self.shared: self.kernel = self.add_weight( shape=(input_dim, self.units), initializer=Project_initializer_pos(self.kernel_initializer), name="kernel_pos", regularizer=self.kernel_regularizer, constraint=self.kernel_constraints_pos, ) if self.use_bias: self.bias = self.add_weight( shape=(self.units,), initializer=self.bias_initializer, name="bias_pos", regularizer=self.bias_regularizer, constraint=self.bias_constraint, ) else: self.bias = None if self.finetune and self.mode == F_HYBRID.name: # create extra parameters that can be optimized if self.activation_name!='linear': if self.activation_name[:4]!='relu': self.beta_u_f_ = self.add_weight( shape=(self.units,), initializer="ones", name="beta_u_f", regularizer=None, constraint=ClipAlpha() ) self.beta_l_f_ = self.add_weight( shape=(self.units,), initializer="ones", name="beta_l_f", regularizer=None, constraint=ClipAlpha() ) self.alpha_ = self.add_weight( shape=(input_dim, self.units), initializer="ones", name="alpha_", regularizer=None, constraint=ClipAlpha() ) self.gamma_ = self.add_weight( shape=(input_dim, self.units), initializer="ones", name="gamma_", regularizer=None, constraint=ClipAlpha() ) # False # 6 inputs tensors : h, g, x_min, x_max, W_u, b_u, W_l, b_l if self.mode == F_HYBRID.name: self.input_spec = [ #InputSpec(min_ndim=2, axes={-1: input_dim}), # y InputSpec(min_ndim=2), # x_0 InputSpec(min_ndim=2, axes={-1: input_dim}), # u_c InputSpec(min_ndim=2, axes={-1: input_dim}), # W_u InputSpec(min_ndim=2, axes={-1: input_dim}), # b_u InputSpec(min_ndim=2, axes={-1: input_dim}), # l_c InputSpec(min_ndim=2, axes={-1: input_dim}), # W_l InputSpec(min_ndim=2, axes={-1: input_dim}), # b_l ] elif self.mode == F_IBP.name: self.input_spec = [ #InputSpec(min_ndim=2, axes={-1: input_dim}), # y #InputSpec(min_ndim=2, axes={-1: input_x}), # x_0 InputSpec(min_ndim=2, axes={-1: input_dim}), # u_c InputSpec(min_ndim=2, axes={-1: input_dim}), # l_c ] elif self.mode == F_FORWARD.name: self.input_spec = [ #InputSpec(min_ndim=2, axes={-1: input_dim}), # y InputSpec(min_ndim=2), # x_0 InputSpec(min_ndim=2, axes={-1: input_dim}), # W_u InputSpec(min_ndim=2, axes={-1: input_dim}), # b_u InputSpec(min_ndim=2, axes={-1: input_dim}), # W_l InputSpec(min_ndim=2, axes={-1: input_dim}), # b_l ] if self.dc_decomp: self.input_spec += [ InputSpec(min_ndim=2, axes={-1: input_dim}), # h InputSpec(min_ndim=2, axes={-1: input_dim}), ] # g if self.has_backward_bounds: self.input_spec+=[InputSpec(ndim=3, axes={-1:self.units, -2:self.units})] self.built = True self.input_shape_build = input_shape def shared_weights(self, layer): if not self.shared: pass self.kernel = layer.kernel if self.use_bias: self.bias = layer.bias def set_linear(self, bool_init): self.linear_layer = bool_init def get_linear(self): if self.activation is None and self.activation_name == 'linear': return self.linear_layer else: return False def set_back_bounds(self, has_backward_bounds): # check for activation if self.activation is not None and self.activation_name != 'linear' and has_backward_bounds: raise ValueError() self.has_backward_bounds = has_backward_bounds if self.built and has_backward_bounds: # rebuild with an additional input self.build(self.input_shape_build) if self.has_backward_bounds: op_ = Dot(1) self.op_dot=lambda x,y: op_([x,y]) def call_linear(self, inputs): """ :param inputs: :return: """ z_value = K.cast(0.0, K.floatx()) o_value = K.cast(1., K.floatx()) if not isinstance(inputs, list): raise ValueError("A merge layer should be called " "on a list of inputs.") if self.has_backward_bounds: back_bound = inputs[-1] inputs = inputs[:-1] if self.has_backward_bounds: kernel_ = K.sum(self.kernel[None,:,:,None]*back_bound[:,None], 2) kernel_pos_back = K.maximum(z_value, kernel_) kernel_neg_back = K.minimum(z_value, kernel_) kernel_pos = K.maximum(z_value, self.kernel) kernel_neg = K.minimum(z_value, self.kernel) if self.finetune and self.mode==F_HYBRID.name: kernel_pos_alpha = K.maximum(z_value, self.kernel*self.alpha_) kernel_pos_gamma = K.maximum(z_value, self.kernel*self.gamma_) kernel_neg_alpha = K.minimum(z_value, self.kernel*self.alpha_) kernel_neg_gamma = K.minimum(z_value, self.kernel * self.gamma_) if self.dc_decomp: h, g = inputs[-2:] h_ = K.dot(h, kernel_pos) + K.dot(g, kernel_neg) g_ = K.dot(g, kernel_pos) + K.dot(h, kernel_neg) if self.dc_decomp: rest = 2 else: rest=0 if self.mode == F_HYBRID.name: #y, x_0, u_c, w_u, b_u, l_c, w_l, b_l = inputs[:8] x_0, u_c, w_u, b_u, l_c, w_l, b_l = inputs[:self.nb_tensors-rest] if self.mode == F_IBP.name: #y, x_0, u_c, l_c = inputs[:4] u_c, l_c = inputs[:self.nb_tensors-rest] if self.mode == F_FORWARD.name: #y, x_0, w_u, b_u, w_l, b_l = inputs[:6] x_0, w_u, b_u, w_l, b_l = inputs[:self.nb_tensors-rest] #y_ = K.dot(y, self.kernel) # + K.dot(y, self.kernel_neg) #mask_b = 0 * (y) if self.mode in [F_HYBRID.name, F_FORWARD.name]: if len(w_u.shape) != len(b_u.shape): x_max = get_upper(x_0, w_u - w_l, b_u - b_l, self.convex_domain) mask_b = o_value - K.sign(x_max) mask_a = o_value - mask_b if self.mode in [F_HYBRID.name, F_IBP.name]: if not self.linear_layer: if not self.has_backward_bounds: u_c_ = self.op_dot(u_c, kernel_pos) + self.op_dot(l_c, kernel_neg) l_c_ = self.op_dot(l_c, kernel_pos) + self.op_dot(u_c, kernel_neg) else: u_c_ = self.op_dot(u_c, kernel_pos_back) + self.op_dot(l_c, kernel_neg_back) l_c_ = self.op_dot(l_c, kernel_pos_back) + self.op_dot(u_c, kernel_neg_back) else: # check convex_domain if len(self.convex_domain) and self.convex_domain['name']==Ball.name: if self.mode == F_IBP.name: x_0 = (u_c+l_c)/2. b_ = (0*self.kernel[0])[None] if self.has_backward_bounds: raise NotImplementedError() u_c_ = get_upper(x_0, self.kernel[None], b_, convex_domain=self.convex_domain) l_c_ = get_lower(x_0, self.kernel[None], b_, convex_domain=self.convex_domain) else: if not self.has_backward_bounds: u_c_ = self.op_dot(u_c, kernel_pos) + self.op_dot(l_c, kernel_neg) l_c_ = self.op_dot(l_c, kernel_pos) + self.op_dot(u_c, kernel_neg) else: u_c_ = self.op_dot(u_c, kernel_pos_back) + self.op_dot(l_c, kernel_neg_back) l_c_ = self.op_dot(l_c, kernel_pos_back) + self.op_dot(u_c, kernel_neg_back) if self.mode in [F_HYBRID.name, F_FORWARD.name]: if len(w_u.shape) == len(b_u.shape): y_ = K.dot(b_u, self.kernel) # + K.dot(y, self.kernel_neg) w_u_ = K.expand_dims(0 * (y_), 1) + K.expand_dims(self.kernel, 0) w_l_ = w_u_ b_u_ = z_value * y_ b_l_ = b_u_ if self.finetune and self.mode == F_HYBRID.name: self.frozen_alpha = True self._trainable_weights = self._trainable_weights[:-2] # not optimal if len(w_u.shape) != len(b_u.shape): # first layer, it is necessary linear if self.finetune and self.mode == F_HYBRID.name: b_u_ = K.dot(b_u - u_c, kernel_pos_alpha) + \ K.dot((b_l - l_c), kernel_neg_alpha) + \ K.dot(u_c, kernel_pos) + K.dot(l_c, kernel_neg) # focus.... b_l_ = K.dot(b_l - l_c, kernel_pos_gamma) + \ K.dot((b_u - u_c), kernel_neg_gamma) + \ K.dot(l_c, kernel_pos) + K.dot(u_c, kernel_neg) """ b_u_ = K.dot(b_u-u_c, kernel_pos_alpha) +\ K.dot(mask_a * (b_l-l_c) + mask_b * (b_u-u_c), kernel_neg_alpha) +\ K.dot(u_c, kernel_pos) + K.dot(mask_a*l_c + mask_b*u_c, kernel_neg) # focus.... b_l_ = K.dot(b_l-l_c, kernel_pos_gamma) +\ K.dot(mask_a * (b_u-u_c) + mask_b * (b_l-l_c), kernel_neg_gamma) +\ K.dot(l_c, kernel_pos)+ K.dot(mask_a*u_c + mask_b*l_c, kernel_neg) """ """ b_u_ = K.dot(self.alpha_u_f * b_u + (1 - self.alpha_u_f) * u_c, kernel_pos) + K.dot( mask_a * (self.alpha_l_f * b_l + (1 - self.alpha_l_f) * l_c) + mask_b * (self.alpha_u_f * b_u + (1 - self.alpha_u_f) * u_c), kernel_neg, ) b_l_ = K.dot(self.alpha_l_f * b_l + (1 - self.alpha_l_f) * l_c, kernel_pos) + K.dot( mask_a * (self.alpha_u_f * b_u + (1 - self.alpha_u_f) * u_c) + mask_b * (self.alpha_l_f * b_l + (1 - self.alpha_l_f) * l_c), kernel_neg, ) """ else: # if not self.n_subgrad or self.mode == F_FORWARD.name: b_u_ = K.dot(b_u, kernel_pos) + K.dot(b_l, kernel_neg) b_l_ = K.dot(b_l, kernel_pos) + K.dot(b_u, kernel_neg) """ b_u_ = K.dot(b_u, kernel_pos) + \ K.dot(mask_a * (b_l) + mask_b * (b_u), kernel_neg) b_l_ = K.dot(b_l, kernel_pos) + \ K.dot(mask_a * (b_u) + mask_b * (b_l), kernel_neg_gamma) """ # else: mask_a = K.expand_dims(mask_a, 1) mask_b = K.expand_dims(mask_b, 1) # if not self.n_subgrad or self.mode == F_FORWARD.name: if self.finetune and self.mode == F_HYBRID.name: if self.has_backward_bounds: raise ValueError('last layer should not be finetuned') w_u_ = K.dot(w_u, kernel_pos_alpha) + K.dot(w_l, kernel_neg_alpha) w_l_ = K.dot(w_l, kernel_pos_gamma) + K.dot(w_u, kernel_neg_gamma) """ w_u_ = K.dot(self.alpha_u_f * w_u, kernel_pos) + K.dot( mask_a * self.alpha_l_f * w_l + mask_b * self.alpha_u_f * w_u, kernel_neg ) w_l_ = K.dot(self.alpha_l_f * w_l, kernel_pos) + K.dot( mask_a * self.alpha_u_f * w_u + mask_b * self.alpha_l_f * w_l, kernel_neg ) """ else: if not self.has_backward_bounds: w_u_ = K.dot(w_u, kernel_pos) + K.dot(w_l, kernel_neg) w_l_ = K.dot(w_l, kernel_pos) + K.dot(w_u, kernel_neg) else: raise NotImplementedError() # bug somewhere w_u_ = K.sum(K.expand_dims(w_u, -1)*K.expand_dims(kernel_pos_back, 1), 2)+ \ K.sum(K.expand_dims(w_l, -1) * K.expand_dims(kernel_neg_back, 1), 2) w_l_ = K.sum(K.expand_dims(w_l, -1) * K.expand_dims(kernel_pos_back, 1), 2) + \ K.sum(K.expand_dims(w_u, -1) * K.expand_dims(kernel_neg_back, 1), 2) """ w_u_ = K.dot(w_u, kernel_pos) + K.dot( mask_a *w_l + mask_b * w_u, kernel_neg) w_l_ = K.dot(w_l, kernel_pos) + K.dot( mask_a * w_u + mask_b * w_l, kernel_neg ) """ # else: """ if self.n_subgrad and self.mode == F_HYBRID.name: kernel_pos_ = K.expand_dims(kernel_pos_, 1) kernel_neg_ = K.expand_dims(kernel_neg_, 1) w_u_0_a = K.expand_dims(w_u, -1) * kernel_pos_ # w_u_0_ = K.sum(w_u_0_a, 2) # w_u_1_a = K.expand_dims(mask_a * w_l + mask_b * w_u, -1) * kernel_neg_ w_u_1_a = K.expand_dims(w_l, -1) * kernel_neg_ # w_u_1_ = K.sum(w_u_1_a, 2) # w_u_ = w_u_0_ + w_u_1_ w_l_0_a = K.expand_dims(w_l, -1) * kernel_pos_ # w_l_0_ = K.sum(w_l_0_a, 2) # w_l_1_a = K.expand_dims(mask_a * w_u + mask_b * w_l, -1) * kernel_neg_ w_l_1_a = K.expand_dims(w_u, -1) * kernel_neg_ # w_l_1_ = K.sum(w_l_1_a, 2) # w_l_ = w_l_0_ + w_l_1_ # if not self.fast and self.n_subgrad and self.mode == F_HYBRID.name: # test whether the layer is linear: # if it is: no need to use subgrad convex_l_0 = (l_c_0_a, w_l_0_a, b_l_0_a) # ??? convex_l_1 = (l_c_1_a, w_l_1_a, b_l_1_a) convex_u_0 = (-u_c_0_a, -w_u_0_a, -b_u_0_a) convex_u_1 = (-u_c_1_a, -w_u_1_a, -b_u_1_a) # import pdb; pdb.set_trace() l_sub = grad_descent(x_0, convex_l_0, convex_l_1, self.convex_domain, n_iter=self.n_subgrad) u_sub = grad_descent(x_0, convex_u_0, convex_u_1, self.convex_domain, n_iter=self.n_subgrad) u_c_ = u_sub # u_c_ = K.minimum(u_c_, u_sub) # l_c_ = K.maximum(l_c_, l_sub) """ if self.use_bias: if not self.has_backward_bounds: if self.mode in [F_HYBRID.name, F_IBP.name]: u_c_ = K.bias_add(u_c_, self.bias, data_format="channels_last") l_c_ = K.bias_add(l_c_, self.bias, data_format="channels_last") if self.mode in [F_FORWARD.name, F_HYBRID.name]: b_u_ = K.bias_add(b_u_, self.bias, data_format="channels_last") b_l_ = K.bias_add(b_l_, self.bias, data_format="channels_last") else: b_ = K.sum(back_bound * self.bias[None, None], 1) if self.mode in [F_HYBRID.name, F_IBP.name]: u_c_ = u_c_ + b_ l_c_ = l_c_ + b_ if self.mode in [F_FORWARD.name, F_HYBRID.name]: b_u_ = b_u_ + b_ b_l_ = b_l_ + b_ #y_ = K.bias_add(y_, self.bias, data_format="channels_last") if self.dc_decomp: if self.has_backward_bounds: raise NotImplementedError() h_ = K.bias_add(h_, K.maximum(z_value, self.bias), data_format="channels_last") g_ = K.bias_add(g_, K.minimum(z_value, self.bias), data_format="channels_last") if self.mode == F_HYBRID.name : upper_ = get_upper(x_0, w_u_, b_u_, self.convex_domain) lower_ = get_lower(x_0, w_l_, b_l_, self.convex_domain) l_c_ = K.maximum(lower_, l_c_) u_c_ = K.minimum(upper_, u_c_) if self.mode == F_HYBRID.name: output = [x_0, u_c_, w_u_, b_u_, l_c_, w_l_, b_l_] if self.mode == F_FORWARD.name: output = [x_0, w_u_, b_u_, w_l_, b_l_] if self.mode == F_IBP.name: output = [u_c_, l_c_] if self.dc_decomp: output += [h_, g_] return output def call(self, inputs): """ :param inputs: list of tensors :return: """ output = self.call_linear(inputs) if self.activation is not None and self.activation_name!='linear': if self.finetune: if self.activation_name[:4]!='relu': output = self.activation( output, dc_decomp=self.dc_decomp, convex_domain=self.convex_domain, mode=self.mode, finetune=[self.beta_u_f_, self.beta_l_f_] ) else: output = self.activation( output, dc_decomp=self.dc_decomp, convex_domain=self.convex_domain, mode=self.mode, finetune=self.beta_l_f_ ) else: output = self.activation( output, dc_decomp=self.dc_decomp, convex_domain=self.convex_domain, mode=self.mode, ) return output def compute_output_shape(self, input_shape): """ :param input_shape: :return: """ assert len(input_shape) == self.nb_tensors output_shape = [list(elem) for elem in input_shape[: self.nb_tensors]] for i in range(1, self.nb_tensors): output_shape[i][-1]=self.units if self.mode == F_IBP.name: output_shape[0][-1] = self.units """ for i in range(self.nb_tensors): assert input_shape[i] and len(input_shape[i]) >= 2 assert input_shape[i][-1] output_shape = [list(elem) for elem in input_shape[: self.nb_tensors]] for i, elem in enumerate(output_shape): if i == 1: # the convex domain is unchanged continue elem[-1] = self.units output_shape = [tuple(elem) for elem in output_shape] return output_shape '""" def reset_layer(self, dense): """ :param dense: :return: """ # assert than we have the same configuration assert isinstance(dense, Dense), "wrong type of layers..." if dense.built: params = dense.get_weights() if self.finetune: params += self.get_weights()[2:] self.set_weights(params) else: raise ValueError("the layer {} has not been built yet".format(dense.name)) def freeze_weights(self): if not self.frozen_weights: if self.finetune and self.mode == F_HYBRID.name: if self.use_bias: self._trainable_weights = self._trainable_weights[2:] else: self._trainable_weights = self._trainable_weights[1:] else: self._trainable_weights = [] self.frozen_weights = True def unfreeze_weights(self): if self.frozen_weights: if self.use_bias: self._trainable_weights = [self.bias] + self._trainable_weights self._trainable_weights = [self.kernel] + self._trainable_weights self.frozen_weights = False def freeze_alpha(self): if not self.frozen_alpha: if self.finetune and self.mode == F_HYBRID.name: if self.activation_name=='linear': self._trainable_weights = self._trainable_weights[:-2] else: if self.activation_name[:4]=='relu': self._trainable_weights = self._trainable_weights[:-3] else: self._trainable_weights = self._trainable_weights[:-4] self.frozen_alpha = True def unfreeze_alpha(self): if self.frozen_alpha: if self.finetune and self.mode == F_HYBRID.name: self._trainable_weights += [self.alpha_, self.gamma_] if self.activation_name!='linear': if self.activation_name[:4]=='relu': self._trainable_weights += [self.beta_u_f_, self.beta_l_f_] else: self._trainable_weights += [self.beta_u_f_, self.beta_l_f_] self.frozen_alpha = False def reset_finetuning(self): if self.finetune and self.mode == F_HYBRID.name: K.set_value(self.alpha_, np.ones_like(self.alpha_.value())) K.set_value(self.gamma_, np.ones_like(self.gamma_.value())) if self.activation_name!='linear': if self.activation_name[:4]=='relu': K.set_value(self.beta_l_f_, np.ones_like(self.beta_l_f_.value())) else: K.set_value(self.beta_u_f_, np.ones_like(self.beta_u_f_.value())) K.set_value(self.beta_l_f_, np.ones_like(self.beta_l_f_.value())) class DecomonActivation(Activation, DecomonLayer): """ Forward LiRPA implementation of Activation layers. See Keras official documentation for further details on the Activation operator """ def __init__(self, activation, mode=F_HYBRID.name, **kwargs): super(DecomonActivation, self).__init__(activation, mode=mode, **kwargs) self.supports_masking = True self.activation = activations.get(activation) self.activation_name = activation def build(self, input_shape): if self.finetune and self.mode in [F_HYBRID.name, F_FORWARD.name]: shape = input_shape[-1][1:] if self.activation_name != 'linear' and self.mode !=F_IBP.name: if self.activation_name[:4] != 'relu': self.beta_u_f = self.add_weight( shape=shape, initializer="ones", name="beta_u_f", regularizer=None, constraint=ClipAlpha(), ) self.beta_l_f = self.add_weight( shape=shape, initializer="ones", name="beta_l_f", regularizer=None, constraint=ClipAlpha(), ) def call(self, input): if self.finetune and self.mode in [F_FORWARD.name, F_HYBRID.name] and self.activation_name != 'linear': if self.activation_name[:4] == 'relu': return self.activation(input, mode=self.mode, dc_decomp=self.dc_decomp, convex_domain=self.convex_domain, finetune=self.beta_l_f) else: return self.activation(input, mode=self.mode, dc_decomp=self.dc_decomp, convex_domain=self.convex_domain, finetune=[self.beta_u_f, self.beta_l_f]) else: return self.activation(input, mode=self.mode, convex_domain=self.convex_domain, dc_decomp=self.dc_decomp) def reset_finetuning(self): if self.finetune and self.mode != F_IBP.name: if self.activation_name!='linear': if self.activation_name[:4]=='relu': K.set_value(self.beta_l_f, np.ones_like(self.beta_l_f.value())) else: K.set_value(self.beta_u_f, np.ones_like(self.beta_u_f.value())) K.set_value(self.beta_l_f, np.ones_like(self.beta_l_f.value())) def freeze_alpha(self): if not self.frozen_alpha: if self.finetune and self.mode in [F_FORWARD.name, F_HYBRID.name]: self._trainable_weights = [] self.frozen_alpha = True def unfreeze_alpha(self): if self.frozen_alpha: if self.finetune and self.mode in [F_FORWARD.name, F_HYBRID.name]: if self.activation_name!='linear': if self.activation_name[:4]!='relu': self._trainable_weights += [self.beta_u_f, self.beta_l_f] else: self._trainable_weights += [self.beta_l_f] self.frozen_alpha = False class DecomonFlatten(Flatten, DecomonLayer): """ Forward LiRPA implementation of Flatten layers. See Keras official documentation for further details on the Flatten operator """ def __init__(self, data_format=None, mode=F_HYBRID.name, **kwargs): """ :param data_format: :param kwargs: """ super(DecomonFlatten, self).__init__(data_format=data_format, mode=mode, **kwargs) if self.mode == F_HYBRID.name: self.input_spec = [ #InputSpec(min_ndim=1), # y InputSpec(min_ndim=1), # z InputSpec(min_ndim=1), # u InputSpec(min_ndim=2), # w_u InputSpec(min_ndim=2), # b_u InputSpec(min_ndim=1), # l InputSpec(min_ndim=2), # w_l InputSpec(min_ndim=2), # b_l ] elif self.mode == F_IBP.name: self.input_spec = [ #InputSpec(min_ndim=1), # y #InputSpec(min_ndim=1), # z InputSpec(min_ndim=1), # u InputSpec(min_ndim=1), # l ] elif self.mode == F_FORWARD.name: self.input_spec = [ #InputSpec(min_ndim=1), # y InputSpec(min_ndim=1), # z InputSpec(min_ndim=2), # w_u InputSpec(min_ndim=2), # b_u InputSpec(min_ndim=2), # w_l InputSpec(min_ndim=2), # b_l ] if self.dc_decomp: self.input_spec += [InputSpec(min_ndim=1), InputSpec(min_ndim=1)] def build(self, input_shape): """ :param self: :param input_shape: :return: """ return None def call(self, inputs): op = super(DecomonFlatten, self).call if self.dc_decomp: h, g = inputs[-2:] h_ = op(h) g_ = op(g) if self.mode == F_HYBRID.name: #y, x_0, u_c, w_u, b_u, l_c, w_l, b_l = inputs x_0, u_c, w_u, b_u, l_c, w_l, b_l = inputs[:self.nb_tensors] elif self.mode == F_IBP.name: #y, x_0, u_c, l_c = inputs u_c, l_c = inputs[:self.nb_tensors] elif self.mode == F_FORWARD.name: #y, x_0, w_u, b_u, w_l, b_l = inputs x_0, w_u, b_u, w_l, b_l = inputs[:self.nb_tensors] #y_ = op(y) if self.mode in [F_HYBRID.name, F_IBP.name]: u_c_ = op(u_c) l_c_ = op(l_c) if self.mode in [F_HYBRID.name, F_FORWARD.name]: b_u_ = op(b_u) b_l_ = op(b_l) output_shape = np.prod(list(K.int_shape(b_u_))[1:]) input_dim = K.int_shape(x_0)[-1] w_u_ = K.reshape(w_u, (-1, input_dim, output_shape)) w_l_ = K.reshape(w_l, (-1, input_dim, output_shape)) if self.mode == F_HYBRID.name: #output = [y_, x_0, u_c_, w_u_, b_u_, l_c_, w_l_, b_l_] output = [x_0, u_c_, w_u_, b_u_, l_c_, w_l_, b_l_] if self.mode == F_IBP.name: #output = [y_, x_0, u_c_, l_c_] output = [u_c_, l_c_] if self.mode == F_FORWARD.name: #output = [y_, x_0, w_u_, b_u_, w_l_, b_l_] output = [x_0, w_u_, b_u_, w_l_, b_l_] if self.dc_decomp: output += [h_, g_] return output class DecomonBatchNormalization(BatchNormalization, DecomonLayer): """ Forward LiRPA implementation of Batch Normalization layers. See Keras official documentation for further details on the BatchNormalization operator """ def __init__( self, axis=-1, momentum=0.99, epsilon=1e-3, center=True, scale=True, beta_initializer="zeros", gamma_initializer="ones", moving_mean_initializer="zeros", moving_variance_initializer="ones", beta_regularizer=None, gamma_regularizer=None, beta_constraint=None, gamma_constraint=None, mode=F_HYBRID.name, **kwargs, ): super(DecomonBatchNormalization, self).__init__( axis=axis, momentum=momentum, epsilon=epsilon, center=center, scale=scale, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, moving_mean_initializer=moving_mean_initializer, moving_variance_initializer=moving_variance_initializer, beta_regularizer=beta_regularizer, gamma_regularizer=gamma_regularizer, beta_constraint=beta_constraint, gamma_constraint=gamma_constraint, mode=mode, **kwargs, ) def build(self, input_shape): super(DecomonBatchNormalization, self).build(input_shape[0]) self.input_spec = [InputSpec(min_ndim=len(elem)) for elem in input_shape] def compute_output_shape(self, input_shape): output_shape_ = super(DecomonBatchNormalization, self).compute_output_shape(input_shape[-1]) if self.mode in [F_FORWARD.name, F_HYBRID.name]: x_shape = input_shape[0] input_dim = x_shape[-1] output = [] if self.mode == F_IBP.name: #output = [output_shape_, x_shape, output_shape_, output_shape_] output = [output_shape_]*2 if self.mode in [F_HYBRID.name, F_FORWARD.name]: w_shape = list(output_shape_)[:, None] w_shape[:, 0] = input_dim if self.mode == F_FORWARD.name: #output = [output_shape_, x_shape, w_shape, output_shape_, w_shape, output_shape_] output = [x_shape]+[w_shape, output_shape_]*2 else: #output = [output_shape_,x_shape,output_shape_,w_shape,output_shape_,output_shape_,w_shape,output_shape_] output = [x_shape] + [output_shape_, w_shape, output_shape_] * 2 if self.dc_decomp: output += [output_shape_, output_shape_] return output def call(self, inputs, training=None): if training is None: training = K.learning_phase() z_value = K.cast(0.0, K.floatx()) o_value = K.cast(1., K.floatx()) if training: raise NotImplementedError("not working during training") call_op = super(DecomonBatchNormalization, self).call if self.dc_decomp: raise NotImplementedError() h, g = inputs[-2:] if self.mode == F_HYBRID.name: #y, x_0, u_c, w_u, b_u, l_c, w_l, b_l = inputs[:8] x_0, u_c, w_u, b_u, l_c, w_l, b_l = inputs[:self.nb_tensors] elif self.mode == F_IBP.name: #y, x_0, u_c, l_c = inputs[:4] u_c, l_c = inputs[:self.nb_tensors] elif self.mode == F_FORWARD.name: #y, x_0, w_u, b_u, w_l, b_l = inputs[:6] x_0, w_u, b_u, w_l, b_l = inputs[:self.nb_tensors] y_ = call_op(inputs[-1], training=training) n_dim = len(y_.shape) tuple_ = [1] * n_dim for i, ax in enumerate(self.axis): tuple_[ax] = self.moving_mean.shape[i] gamma_ = K.reshape(self.gamma + z_value, tuple_) beta_ = K.reshape(self.beta + z_value, tuple_) moving_mean_ = K.reshape(self.moving_mean + z_value, tuple_) moving_variance_ = K.reshape(self.moving_variance + z_value, tuple_) if self.mode in [F_HYBRID.name, F_IBP.name]: u_c_0 = (u_c - moving_mean_) / K.sqrt(moving_variance_ + self.epsilon) # + beta_ l_c_0 = (l_c - moving_mean_) / K.sqrt(moving_variance_ + self.epsilon) u_c_ = K.maximum(z_value, gamma_) * u_c_0 + K.minimum(z_value, gamma_) * l_c_0 + beta_ l_c_ = K.maximum(z_value, gamma_) * l_c_0 + K.minimum(z_value, gamma_) * u_c_0 + beta_ if self.mode in [F_HYBRID.name, F_FORWARD.name]: b_u_0 = (b_u - moving_mean_) / K.sqrt(moving_variance_ + self.epsilon) b_l_0 = (b_l - moving_mean_) / K.sqrt(moving_variance_ + self.epsilon) b_u_ = K.maximum(z_value, gamma_) * b_u_0 + K.minimum(z_value, gamma_) * b_l_0 + beta_ b_l_ = K.maximum(z_value, gamma_) * b_l_0 + K.minimum(z_value, gamma_) * b_u_0 + beta_ gamma_ = K.expand_dims(gamma_, 1) moving_variance_ = K.expand_dims(moving_variance_, 1) w_u_0 = w_u / K.sqrt(moving_variance_ + self.epsilon) w_l_0 = w_l / K.sqrt(moving_variance_ + self.epsilon) w_u_ = K.maximum(z_value, gamma_) * w_u_0 + K.minimum(z_value, gamma_) * w_l_0 w_l_ = K.maximum(z_value, gamma_) * w_l_0 + K.minimum(z_value, gamma_) * w_u_0 if self.mode == F_HYBRID.name: #output = [y_, x_0, u_c_, w_u_, b_u_, l_c_, w_l_, b_l_] output = [x_0, u_c_, w_u_, b_u_, l_c_, w_l_, b_l_] if self.mode == F_IBP.name: #output = [y_, x_0, u_c_, l_c_] output = [u_c_, l_c_] if self.mode == F_FORWARD.name: #output = [y_, x_0, w_u_, b_u_, w_l_, b_l_] output = [x_0, w_u_, b_u_, w_l_, b_l_] return output def reset_layer(self, layer): """ :param layer: :return: """ assert isinstance(layer, BatchNormalization), "wrong type of layers..." params = layer.get_weights() self.set_weights(params) class DecomonDropout(Dropout, DecomonLayer): """ Forward LiRPA implementation of Dropout layers. See Keras official documentation for further details on the Dropout operator """ def __init__(self, rate, noise_shape=None, seed=None, mode=F_HYBRID.name, **kwargs): super(DecomonDropout, self).__init__(rate=rate, noise_shape=noise_shape, seed=seed, mode=mode, **kwargs) def compute_output_shape(self, input_shape): return input_shape def build(self, input_shape): super(DecomonDropout, self).build(input_shape[0]) self.input_spec = [InputSpec(min_ndim=len(elem)) for elem in input_shape] def call(self, inputs, training=None): if training is None: training = K.learning_phase() if training: raise NotImplementedError("not working during training") return inputs call_op = super(DecomonDropout, self).call if self.mode == F_HYBRID.name: if self.dc_decomp: #y, x_0, u_c, w_u, b_u, l_c, w_l, b_l, h, g = inputs[: self.nb_tensors] x_0, u_c, w_u, b_u, l_c, w_l, b_l, h, g = inputs[: self.nb_tensors] else: #y, x_0, u_c, w_u, b_u, l_c, w_l, b_l = inputs[: self.nb_tensors] x_0, u_c, w_u, b_u, l_c, w_l, b_l = inputs[: self.nb_tensors] elif self.mode == F_IBP.name: if self.dc_decomp: #y, x_0, u_c, l_c, h, g = inputs[: self.nb_tensors] u_c, l_c, h, g = inputs[: self.nb_tensors] else: #y, x_0, u_c, l_c = inputs[: self.nb_tensors] u_c, l_c = inputs[: self.nb_tensors] elif self.mode == F_FORWARD.name: if self.dc_decomp: #y, x_0, w_u, b_u, w_l, b_l, h, g = inputs[: self.nb_tensors] x_0, w_u, b_u, w_l, b_l, h, g = inputs[: self.nb_tensors] else: #y, x_0, w_u, b_u, w_l, b_l = inputs[: self.nb_tensors] x_0, w_u, b_u, w_l, b_l = inputs[: self.nb_tensors] #y_ = call_op(y, training=training) if self.mode in [F_HYBRID.name, F_IBP.name]: u_c_ = call_op(u_c, training=training) l_c_ = call_op(l_c, training=training) if self.mode in [F_HYBRID.name, F_FORWARD.name]: b_u_ = call_op(b_u, training=training) b_l_ = call_op(b_l, training=training) input_dim = w_u.shape[1] w_u_list = tf.split(w_u, input_dim, 1) w_l_list = tf.split(w_l, input_dim, 1) w_u_ = K.concatenate([call_op(w_u_i, training=training) for w_u_i in w_u_list], 1) w_l_ = K.concatenate([call_op(w_l_i, training=training) for w_l_i in w_l_list], 1) if self.mode == F_HYBRID.name: #output = [y_, x_0, u_c_, w_u_, b_u_, l_c_, w_l_, b_l_] output = [x_0, u_c_, w_u_, b_u_, l_c_, w_l_, b_l_] if self.mode == F_IBP.name: #output = [y_, x_0, u_c_, l_c_] output = [u_c_, l_c_] if self.mode == F_FORWARD.name: #output = [y_, x_0, w_u_, b_u_, w_l_, b_l_] output = [x_0, w_u_, b_u_, w_l_, b_l_] return output class DecomonInputLayer(DecomonLayer, InputLayer): """ Forward LiRPA implementation of Dropout layers. See Keras official documentation for further details on the Dropout operator """ def __init__(self, input_shape=None, batch_size=None, dtype=None, input_tensor=None, sparse=None, name=None, ragged=None, type_spec=None, mode=F_HYBRID.name, **kwargs): if type_spec is not None: super(DecomonInputLayer, self).__init__(input_shape=input_shape,batch_size=batch_size,dtype=dtype, type_spec=type_spec, input_tensor=input_tensor,sparse=sparse,name=name, ragged=ragged,mode=mode, **kwargs) else: super(DecomonInputLayer, self).__init__(input_shape=input_shape, batch_size=batch_size, dtype=dtype, input_tensor=input_tensor, sparse=sparse, name=name, ragged=ragged, mode=mode, **kwargs) def call(self, inputs): return inputs def compute_output_shape(self, input_shape): return input_shape def get_linear(self): return self.linear_layer # conditional import for deel-lip def to_monotonic( layer, input_dim, dc_decomp=False, convex_domain={}, finetune=False, IBP=True, forward=True, shared=True, fast=True ): """Transform a standard keras layer into a Decomon layer. Type of layer is tested to know how to transform it into a MonotonicLayer of the good type. If type is not treated yet, raises an TypeError :param layer: a Keras Layer :param input_dim: either an integer or a tuple that represents the dim of the input convex domain :param dc_decomp: boolean that indicates whether we return a difference of convex decomposition of our layer :param convex_domain: the type of convex domain :param IBP: boolean that indicates whether we propagate constant bounds :param forward: boolean that indicates whether we propagate affine bounds :return: the associated DecomonLayer :raises: TypeError """ # get class name class_name = layer.__class__.__name__ # remove deel-lip dependency if class_name[:len(DEEL_LIP.name)]==DEEL_LIP.name: class_name = class_name[len(DEEL_LIP.name):] # check if layer has a built argument that built is set to True if hasattr(layer, "built"): if not layer.built: raise ValueError("the layer {} has not been built yet".format(layer.name)) if isinstance(layer, Merge): return to_monotonic_merge(layer, input_dim, dc_decomp, convex_domain, finetune, IBP, forward) # do case by case for optimizing for k in range(3): # two runs before sending a failure if k == 2: # the immediate parent is not a native Keras class raise KeyError("unknown class {}".format(class_name)) try: monotonic_class_name = "Decomon{}".format(class_name) config_layer = layer.get_config() config_layer["name"] = layer.name + "_monotonic" config_layer["dc_decomp"] = dc_decomp config_layer["convex_domain"] = convex_domain mode = F_HYBRID.name if IBP and not forward: mode = F_IBP.name if not IBP and forward: mode = F_FORWARD.name config_layer["mode"] = mode config_layer["finetune"] = finetune config_layer["shared"] = shared config_layer["fast"] = fast """ if k==1: attr_parent = inspect.getargspec(layer.__class__.__bases__[0].__dict__['__init__'])[0] attr_child = inspect.getargspec(layer.__class__.__dict__['__init__'])[0] specific_item = [elem for elem in attr_child if not elem in attr_parent] import pdb; pdb.set_trace() """ layer_list=[] activation=None if 'activation' in config_layer.keys(): activation = config_layer['activation'] if activation=='linear': activation=None if not(activation is None) and not isinstance(layer, Activation): config_layer['activation']='linear' layer_monotonic = globals()[monotonic_class_name].from_config(config_layer) layer_monotonic.shared_weights(layer) layer_list.append(layer_monotonic) if not activation is None and not isinstance(layer, Activation) and not isinstance(activation, dict): layer_next = DecomonActivation(activation, \ mode=mode, finetune=finetune, \ dc_decomp=dc_decomp, convex_domain=convex_domain) layer_list.append(layer_next) else: if isinstance(activation, dict): layer_next_list = to_monotonic(layer.activation, input_dim,dc_decomp=dc_decomp, convex_domain=convex_domain, finetune=finetune, IBP=IBP, forward=forward, shared=shared, fast=fast) layer_list+=layer_next_list break except KeyError: """ # retrieve first parent to apply LiRPA decomposition class_name_= class_name class_name = layer.__class__.__bases__[0].__name__ warnings.warn('unknown class {} as a native Keras class. We replace it by its direct parent class {}'.format(class_name_, class_name)) """ if hasattr(layer, "vanilla_export"): shared = False # checking with Deel-LIP layer_ = layer.vanilla_export() layer_(layer.input) layer = layer_ class_name = layer.__class__.__name__ try: input_shape = list(layer.input_shape)[1:] if isinstance(input_dim, tuple): x_shape = Input(input_dim) input_dim = input_dim[-1] else: x_shape = Input((input_dim,)) if mode in [F_HYBRID.name, F_FORWARD.name]: w_shape = Input(tuple([input_dim] + input_shape)) y_shape = Input(tuple(input_shape)) if mode == F_HYBRID.name: #input_ = [y_shape, x_shape, y_shape, w_shape, y_shape, y_shape, w_shape, y_shape] input_ = [x_shape, y_shape, w_shape, y_shape, y_shape, w_shape, y_shape] elif mode == F_IBP.name: #input_ = [y_shape, x_shape, y_shape, y_shape] input_ = [y_shape, y_shape] elif mode == F_FORWARD.name: #input_ = [y_shape, x_shape, w_shape, y_shape, w_shape, y_shape] input_ = [x_shape, w_shape, y_shape, w_shape, y_shape] if dc_decomp: input_ += [y_shape, y_shape] layer_list[0](input_) layer_list[0].reset_layer(layer) except: pass #return layer_monotonic return layer_list # Aliases MonotonicConvolution2D = DecomonConv2D
StarcoderdataPython
11264784
import pytest from fixture import Application import json import os.path import ftputil target = None webfixture = None def load_config(file): global target if target is None: with open(file) as targetfile: target = json.load(targetfile) return target @pytest.fixture(scope="session") def config(request): return load_config(request.config.getoption("--target")) @pytest.fixture def app(request, config): global webfixture browser = request.config.getoption("--browser") if webfixture is None or not webfixture.is_valid(): webfixture = Application(browser=browser, config=config) webfixture.session.ensure_login( username=config["webadmin"]["username"], password=config["webadmin"]["password"] ) return webfixture @pytest.fixture(scope="session", autouse=True) def stop(request): global webfixture def fin(): if webfixture: webfixture.session.ensure_logout() webfixture.destroy() request.addfinalizer(fin) return webfixture def pytest_addoption(parser): parser.addoption("--browser", action="store", default="firefox") parser.addoption( "--target", action="store", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "target.json") ) @pytest.fixture(scope="session", autouse=True) def configure_ftp_server(request, config): install_server_configuration( host=config["ftp"]["host"], username=config["ftp"]["username"], password=config["ftp"]["password"] ) def fin(): restore_server_configuration( host=config["ftp"]["host"], username=config["ftp"]["username"], password=config["ftp"]["password"] ) request.addfinalizer(fin) def install_server_configuration(host, username, password): with ftputil.FTPHost(host, username, password) as remote: if remote.path.isfile("config_inc_ORIG_AUTOTEST.php"): remote.remove("config_inc_ORIG_AUTOTEST.php") if remote.path.isfile("config_inc.php"): remote.rename("config_inc.php", "config_inc_ORIG_AUTOTEST.php") disabled_captcha_config = os.path.join( os.path.dirname(os.path.abspath(__file__)), "resources/config_inc.php" ) remote.upload(disabled_captcha_config, "config_inc.php") def restore_server_configuration(host, username, password): with ftputil.FTPHost(host, username, password) as remote: if remote.path.isfile("config_inc_ORIG_AUTOTEST.php"): if remote.path.isfile("config_inc.php"): remote.remove("config_inc.php") remote.rename("config_inc_ORIG_AUTOTEST.php", "config_inc.php")
StarcoderdataPython
6610397
# coding=utf-8 from __future__ import unicode_literals, print_function from pylexibank.dataset import CldfDataset, TranscriptionReport from clldutils.misc import slug from clldutils.path import Path from pylexibank.lingpy_util import getEvoBibAsSource, iter_alignments from pylexibank.util import download_and_unpack_zipfiles import lingpy as lp URL = "https://zenodo.org/record/51328/files/partial-cognate-detection-v1.0.zip" PATH = Path('lingpy-partial-cognate-detection-2089b49', 'data') DSETS = ['Bai-110-9.tsv', 'Tujia-109-5.tsv', 'Chinese-180-18.tsv'] SOURCES = ['Wang2006', 'Starostin2013b', 'Hou2004'] TRANSCRIPTION_REPORT_CFG = {'column': 'Segments', 'segmentized': True} def download(dataset, **kw): download_and_unpack_zipfiles(URL, dataset, *[PATH.joinpath(dset) for dset in DSETS]) def cldf(dataset, concepticon, **kw): for dset, srckey in zip(DSETS, SOURCES): wl = lp.Wordlist(dataset.raw.joinpath(dset).as_posix()) src = getEvoBibAsSource(srckey) with CldfDataset(( 'ID', 'Language_ID', 'Language_name', 'Language_iso', 'Parameter_ID', 'Parameter_name', 'Value', 'Source', 'Segments', 'CLPA', 'Cognacy', 'Partial_cognacy' ) , dataset, subset=dset.split('-')[0]) as ds: ds.sources.add(src) for k in wl: ds.add_row([ '{0}-{1}'.format(srckey, k), wl[k, 'glottolog'], wl[k, 'doculect'], '', wl[k, 'concepticon_id'], wl[k, 'concept'], wl[k, 'ipa'], srckey, ' '.join(wl[k, 'tokens']), ' '.join(wl[k, 'clpa']), wl[k, 'cogid'], ' '.join([str(x) for x in wl[k, 'partialids']]) ]) cognates = [] for k in wl: concept = wl[k, 'concept'] idf = '-'.join([slug(concept), '%s' % wl[k, 'cogid']]) cognates += [[ '{0}-{1}'.format(srckey, k), ds.name, wl[k, 'ipa'], idf, '', 'expert', srckey, '', '', '' ]] dataset.cognates.extend(iter_alignments(wl, cognates, method='progressive', prefix=srckey + '-'))
StarcoderdataPython
3308667
<filename>ipsn_ranking_server.py #!/usr/bin/env python import SimpleHTTPServer import SocketServer class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(self): if self.path == '/': self.path = '/ranking.html' return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) Handler = MyRequestHandler server = SocketServer.TCPServer(('0.0.0.0', 5004), Handler) server.serve_forever()
StarcoderdataPython
1889764
<reponame>hishizuka/pyqtgraph """ Demonstrate the use of layouts to control placement of multiple plots / views / labels """ ## Add path to library (just for examples; you do not need this) import initExample from pyqtgraph.Qt import QtGui, QtCore import pyqtgraph as pg import numpy as np app = pg.mkQApp("Gradiant Layout Example") view = pg.GraphicsView() l = pg.GraphicsLayout(border=(100,100,100)) view.setCentralItem(l) view.show() view.setWindowTitle('pyqtgraph example: GraphicsLayout') view.resize(800,600) ## Title at top text = """ This example demonstrates the use of GraphicsLayout to arrange items in a grid.<br> The items added to the layout must be subclasses of QGraphicsWidget (this includes <br> PlotItem, ViewBox, LabelItem, and GrphicsLayout itself). """ l.addLabel(text, col=1, colspan=4) l.nextRow() ## Put vertical label on left side l.addLabel('Long Vertical Label', angle=-90, rowspan=3) ## Add 3 plots into the first row (automatic position) p1 = l.addPlot(title="Plot 1") p2 = l.addPlot(title="Plot 2") vb = l.addViewBox(lockAspect=True) img = pg.ImageItem(np.random.normal(size=(100,100))) vb.addItem(img) vb.autoRange() ## Add a sub-layout into the second row (automatic position) ## The added item should avoid the first column, which is already filled l.nextRow() l2 = l.addLayout(colspan=3, border=(50,0,0)) l2.setContentsMargins(10, 10, 10, 10) l2.addLabel("Sub-layout: this layout demonstrates the use of shared axes and axis labels", colspan=3) l2.nextRow() l2.addLabel('Vertical Axis Label', angle=-90, rowspan=2) p21 = l2.addPlot() p22 = l2.addPlot() l2.nextRow() p23 = l2.addPlot() p24 = l2.addPlot() l2.nextRow() l2.addLabel("HorizontalAxisLabel", col=1, colspan=2) ## hide axes on some plots p21.hideAxis('bottom') p22.hideAxis('bottom') p22.hideAxis('left') p24.hideAxis('left') p21.hideButtons() p22.hideButtons() p23.hideButtons() p24.hideButtons() ## Add 2 more plots into the third row (manual position) p4 = l.addPlot(row=3, col=1) p5 = l.addPlot(row=3, col=2, colspan=2) ## show some content in the plots p1.plot([1,3,2,4,3,5]) p2.plot([1,3,2,4,3,5]) p4.plot([1,3,2,4,3,5]) p5.plot([1,3,2,4,3,5]) if __name__ == '__main__': pg.exec()
StarcoderdataPython
6635349
import csv import random def generating_data(): """Reading and generating necessary data about random word.""" with open('word-meaning-examples.csv', encoding='utf-8') as csv_file: csv_reader = csv.DictReader(csv_file) num = random.randint(0, 13160) data = {} for row in csv_reader: data[row["Word"]] = [row["Meaning"]] examples = [row[example] for example in ["Examples/0", "Examples/1", "Examples/2", "Examples/3", "Examples/4", "Examples/5", "Examples/6", "Examples/7", "Examples/8", "Examples/9"] if row[example] != ""] data[row["Word"]].append(examples) key = random.choice(list(data.keys())) data = data[key] return [key] + data def quize_definitions(): """Definition quize generation.""" data_1 = generating_data() word_correct = data_1[0] words = [generating_data()[0], generating_data()[0], word_correct] words = random.sample(words, len(words)) words_str = '| ' for word in words: words_str += word + ' | ' print('\nPrint the correct word for this definition:' + f'\n"{data_1[1]}"') print(f"\nChoose among: {words_str}") word_input = str(input("\nYour answer: ")) if word_input == word_correct: print("Good job!") return True else: print("It's wrong word :(") print(f"Correct answer: {word_correct}\n") return False def quize_exampes(): """Example quize generation.""" data_1 = generating_data() word_correct = data_1[0] words = [generating_data()[0], generating_data()[0], word_correct] words = random.sample(words, len(words)) words_str = '| ' for word in words: words_str += word + ' | ' sentence = random.choice(data_1[2]).lower().replace(word_correct.lower(), '_________').capitalize() print('\nPut in the correct word into the sentence:' + f'\n"{sentence}"') print(f"\nChoose among: {words_str}") word_input = str(input("\nYour answer: ")) if word_input == word_correct: print("Good job!") return True else: print("It's wrong word :(") print(f"\nCorrect answer: {word_correct}\n") return False def choosing_quiz(): """Choosing one of quizes in random way.""" num = random.randint(0,1) if num == 0: return quize_exampes() else: return quize_definitions() def generating_quiz(): """Generating the whole quize process.""" for _ in range(2): res = choosing_quiz() if res == False: return False return True
StarcoderdataPython
6427178
<reponame>lucasemmanuelferreiradearaujo/AulasDePython ''' Crie um programa que leia nome, ano de nascimento e carteira de trabalho e cadastre-os (com idade) em um dicionario se por acaso a CTPS for diferente de ZERO, o diconario recebera também o ano de contratação e o salario. Calcule e acrescente, alem da idade, com quantos anos a pessoa vai se aposentar. ''' import datetime dados =dict() hj = datetime.date.today() dados['nome'] = str(input('Nome: ')) dados['ano'] = int(input('Ano de nascimento: ')) dados['carteira'] = int(input('CTPS: ')) if dados['carteira'] <= 0: del dados['carteira'] else: dados['anoContrato'] = int(input('Ano de contratação: ')) dados['salario'] = float(input('Salario: ')) dados['aposentadoria'] = 32 - (hj.year - dados['anoContrato']) dados['ano'] = hj.year - dados['ano'] for chave, valor in dados.items(): print(f'chave = {chave}, valor = {valor}')
StarcoderdataPython
9785115
import time, base64 #thanks to alexlavr #see: http://meta.osqa.net/question/25/installation-issue-importerror-cannot-import-name-auth_providers#43 try: from hashlib import md5 as md except ImportError: from md5 import new as md from openid.store import nonce as oid_nonce from openid.store.interface import OpenIDStore from openid.association import Association as OIDAssociation from django.conf import settings from models import OpenIdNonce as Nonce, OpenIdAssociation as Association class OsqaOpenIDStore(OpenIDStore): def __init__(self): self.max_nonce_age = 6 * 60 * 60 # Six hours def storeAssociation(self, server_url, association): assoc = Association( server_url = server_url, handle = association.handle, secret = base64.encodestring(association.secret), issued = association.issued, lifetime = association.lifetime, assoc_type = association.assoc_type ) assoc.save() def getAssociation(self, server_url, handle=None): assocs = [] if handle is not None: assocs = Association.objects.filter( server_url = server_url, handle = handle ) else: assocs = Association.objects.filter( server_url = server_url ) if not assocs: return None associations = [] for assoc in assocs: association = OIDAssociation( assoc.handle, base64.decodestring(assoc.secret), assoc.issued, assoc.lifetime, assoc.assoc_type ) if association.getExpiresIn() == 0: self.removeAssociation(server_url, assoc.handle) else: associations.append((association.issued, association)) if not associations: return None return associations[-1][1] def removeAssociation(self, server_url, handle): assocs = list(Association.objects.filter( server_url = server_url, handle = handle )) assocs_exist = len(assocs) > 0 for assoc in assocs: assoc.delete() return assocs_exist def storeNonce(self, nonce): nonce, created = Nonce.objects.get_or_create( nonce = nonce, defaults={'expires': int(time.time())} ) def useNonce(self, server_url, timestamp, salt): if abs(timestamp - time.time()) > oid_nonce.SKEW: return False try: nonce = Nonce( server_url=server_url, timestamp=timestamp, salt=salt) nonce.save() except: raise else: return 1 def getAuthKey(self): # Use first AUTH_KEY_LEN characters of md5 hash of SECRET_KEY return md(settings.SECRET_KEY).hexdigest()[:self.AUTH_KEY_LEN]
StarcoderdataPython
6647905
from flask import Blueprint from flask_restx import Api blueprint = Blueprint("api", __name__) api = Api( blueprint, title="MyToob Core API", version="1.0", description="API for managing MyToob Movies" ) from . resources.trip import ns_trips api.add_namespace(ns_trips)
StarcoderdataPython
1890688
<reponame>r-peschke/openslides-backend<gh_stars>0 from ....models.models import Role from ...generics.update import UpdateAction from ...util.default_schema import DefaultSchema from ...util.register import register_action from .deduplicate_permissions_mixin import DeduplicatePermissionsMixin @register_action("role.update") class RoleUpdateAction(DeduplicatePermissionsMixin, UpdateAction): """ Action to update a role. """ model = Role() schema = DefaultSchema(Role()).get_update_schema( optional_properties=["name", "permissions"] )
StarcoderdataPython
235298
<reponame>contrerasadolfo/Restaurant-app-Api from django.test import TestCase from django.contrib.auth import get_user_model class ModelTests(TestCase): def test_create_user_with_email_successful(self): """Crear un nuevo usuario con un correo electrónico de forma exitosa""" email = '<EMAIL>' password = '<PASSWORD>' user = get_user_model().objects.create_user( email=email, password=password ) self.assertEqual(user.email, email) self.assertTrue(user.check_password(password)) def test_new_user_email_normalized(self): """Normalizar el correo electrónico para un nuevo usuario""" email = '<EMAIL>' user = get_user_model().objects.create_user(email, 'test123') self.assertEqual(user.email, email.lower()) def test_new_user_invalid_email(self): """Prueba de validacion sin correo electrónico genera un error""" with self.assertRaises(ValueError): get_user_model().objects.create_user(None, 'test123')
StarcoderdataPython
1917587
from datetime import datetime from pprint import pprint from demo_hospital import demo2 # from solver_googleOR import solver from solver_with_urgency import solver print(demo2) schedule = solver(demo2, datetime.now()) pprint(schedule)
StarcoderdataPython
8184400
<reponame>StefanIGit/arjuna # This file is a part of Arjuna # Copyright 2015-2021 <NAME> # Website: www.RahulVerma.net # 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 arjuna import * from arjex.lib.gns_adv.app_page_section.app import WordPress @for_module def wordpress(request): # Setup wordpress = WordPress(section_dir="dyn") home = wordpress.launch() yield home # Teadown wordpress.quit() @for_module def dashboard(request): # Setup wordpress = WordPress(section_dir="dyn") home = wordpress.launch() dashboard = home.login_with_default_creds() yield dashboard # Teadown dashboard.top_nav.logout() wordpress.quit() @test def check_fmt_gns(request, dashboard): dashboard.left_nav.gns.formatter(text="Media").dyn_link.click() @test def check_fmt_config_gns(request, dashboard): dashboard.left_nav.gns.dyn_link_conf.click() @test def check_fmt_reference_gns(request, dashboard): dashboard.left_nav.gns.dyn_link_ref.click() @test def check_fmt_reference_l10n_gns(request, dashboard): dashboard.left_nav.gns.dyn_link_l10n.click() @test def check_fmt_gns_node(request, wordpress): e = wordpress.gns.formatter(idx="er_l").user_node_f1 print(e.source.content.root) e = wordpress.gns.formatter(attr='id', idx="er_l").user_node_f2 print(e.source.content.root) # Case insensitive e = wordpress.gns.formatter(ATTR1='id', idx="er_l", attr2='size', sz=20).user_node_f3 print(e.source.content.root) e = wordpress.gns.formatter(tg="input", attr1='id', idx="er_l", attr2='size', sz=20).user_node_f4 print(e.source.content.root) e = wordpress.gns.formatter(tg="html", cl1='locale-en-us', text='Me').body_node_1 print(e.source.content.root) e = wordpress.gns.formatter(tg="html", cl1='locale-en-us', text='Me').body_node_2 print(e.source.content.root)
StarcoderdataPython
1832662
import numpy as np import tensorflow as tf import cv2 import time import os, random, re, pickle import imgaug as ia from imgaug import augmenters as iaa def atoi(text): return int(text) if text.isdigit() else text def natural_keys(text): return [ atoi(c) for c in re.split('(\d+)', text) ] # https://stackoverflow.com/questions/22937589/how-to-add-noise-gaussian-salt-and-pepper-etc-to-image-in-python-with-opencv def noisy(image, noise_typ): if noise_typ == "gaussian": # np.array([103.939, 116.779, 123.68]) mean = 0 var = 0.01*255.0 sigma = var**0.5 gauss = np.random.normal(mean,sigma,image.shape) gauss = gauss.reshape(image.shape) noisy = image + gauss return noisy elif noise_typ == "salt&pepper": s_vs_p = 0.5 amount = 0.05 out = image.copy() # print image.size # Salt mode num_salt = np.ceil(amount * image.size * s_vs_p) coords = [np.random.randint(0, np.max((i-1,1)), int(num_salt)) for i in image.shape] out[coords] = 255.0 # Pepper mode num_pepper = np.ceil(amount* image.size * (1. - s_vs_p)) coords = [np.random.randint(0, np.max((i-1,1)), int(num_pepper)) for i in image.shape] out[coords] = 0.0 return out elif noise_typ == "poisson": vals = len(np.unique(image)) vals = 2 ** np.ceil(np.log2(vals)) noisy = np.random.poisson(np.abs(image) * vals) / float(vals) return noisy elif noise_typ =="speckle": gauss = np.random.randn(*image.shape) gauss = gauss.reshape(image.shape) noisy = image + image * 0.1* gauss return noisy else: return image.copy() def imageAugmentation(inputImages): noiseTypeList = ['gaussian', 'salt&pepper', 'poisson', 'speckle'] random.shuffle(noiseTypeList) select = np.random.randint(0, 2, len(noiseTypeList)) for i in range(len(noiseTypeList)): if select[i] == 1: inputImages = noisy(image=inputImages, noise_typ=noiseTypeList[i]) return inputImages '''https://github.com/aleju/imgaug''' def imgAug(inputImage, crop=True, flip=True, gaussianBlur=True, channelInvert=True, brightness=True, hueSat=True): augList = [] if crop: augList += [iaa.Crop(px=(0, 16))] # crop images from each side by 0 to 16px (randomly chosen) if flip: augList += [iaa.Fliplr(0.5)] # horizontally flip 50% of the images if gaussianBlur: augList += [iaa.GaussianBlur(sigma=(0, 3.0))] # blur images with a sigma of 0 to 3.0 if channelInvert: augList += [iaa.Invert(0.05, per_channel=True)] # invert color channels if brightness: augList += [iaa.Add((-30, 10), per_channel=True)] # change brightness of images (by -10 to 10 of original value) if hueSat: augList += [iaa.AddToHueAndSaturation((-20, 20))] # change hue and saturation seq = iaa.Sequential(augList) # seq = iaa.Sequential([ # iaa.Crop(px=(0, 16)), # crop images from each side by 0 to 16px (randomly chosen) # # iaa.Fliplr(0.5), # horizontally flip 50% of the images # iaa.GaussianBlur(sigma=(0, 3.0)), # blur images with a sigma of 0 to 3.0 # iaa.Invert(0.05, per_channel=True), # invert color channels # iaa.Add((-10, 10), per_channel=0.5), # change brightness of images (by -10 to 10 of original value) # iaa.AddToHueAndSaturation((-20, 20)), # change hue and saturation # ]) image_aug = seq.augment_image(inputImage) return image_aug def imageRandomAugmentation( inputImage, imageRowFinal, imageColFinal, imAug=True, imAugPr = 0.5, padding=True, randomTrans=True, randomScale=True, transPr=0.5, scalePr=0.5, transRatioMaxRow=0.2, transRatioMaxCol=0.2, scaleRatioMin=0.8, scaleRatioMax=1.2): imageRow, imageCol, _ = inputImage.shape # dRow, dCol = 0, 0 if imAug: if np.random.rand()<imAugPr: gaussian, brightness, hueSat, channelInvert = np.random.choice(a=[False, True], size=4, p=[0.5, 0.5]) inputImage = imgAug(inputImage=inputImage, crop=False, flip=False, gaussianBlur=gaussian, channelInvert=channelInvert, brightness=brightness, hueSat=hueSat) rowPadding, colPadding = 0, 0 if padding: expectedRow, expectedCol = imageRowFinal, imageColFinal if imageRow > expectedRow: eRowTemp, eColTemp = expectedRow, expectedCol expectedRow = eRowTemp * float(imageRow)/float(eRowTemp) expectedCol = eColTemp * float(imageRow)/float(eRowTemp) if imageCol > expectedCol: eRowTemp, eColTemp = expectedRow, expectedCol expectedRow = eRowTemp * float(imageCol)/float(eColTemp) expectedCol = eColTemp * float(imageCol)/float(eColTemp) rowGap, colGap = expectedRow - imageRow, expectedCol - imageCol if rowGap*expectedCol < colGap*expectedRow: rowPadding = 0 colPadding = int((colGap - rowGap*float(expectedCol)/float(expectedRow))/2) elif rowGap*expectedCol > colGap*expectedRow: rowPadding = int((rowGap - colGap*float(expectedRow)/float(expectedCol))/2) colPadding = 0 inputImage = cv2.copyMakeBorder( src=inputImage, top=rowPadding, bottom=rowPadding, left=colPadding, right=colPadding, borderType=cv2.BORDER_CONSTANT, value=[0., 0., 0.]) imageRow, imageCol, _ = inputImage.shape # # dRowScale, dColScale = 0,0 scaleRatio = 1.0 if randomScale: if np.random.rand() < scalePr: scaleRatio = np.random.uniform(low=scaleRatioMin, high=scaleRatioMax) # dRowScale = (imageRow - scaleRatio*imageRow)/2.0 # dColScale = (imageCol - scaleRatio*imageCol)/2.0 scaleMat = scaleRatio*np.float32([[1.0, 0, -imageCol/2], [0, 1.0, -imageRow/2]]) + np.float32([[0,0,imageCol/2],[0,0,imageRow/2]]) dRowTrans, dColTrans = 0,0 if randomTrans: if np.random.rand() < transPr: rowTransMax, colTransMax = int(imageRow*transRatioMaxRow), int(imageCol*transRatioMaxCol) dRowTrans, dColTrans = np.random.randint(-rowTransMax,rowTransMax), np.random.randint(-colTransMax,colTransMax) transMat = np.float32([[0,0,dColTrans], [0,0,dRowTrans]]) affineMat = scaleMat + transMat inputImage = cv2.warpAffine(inputImage, affineMat, (imageCol, imageRow), None, cv2.INTER_CUBIC, cv2.BORDER_CONSTANT, (0., 0., 0.)) inputImage = cv2.resize(inputImage, (imageColFinal, imageRowFinal), interpolation=cv2.INTER_CUBIC) # inputImage = inputImage/ 255. # dRow = rowPadding + dRowTrans # dCol = colPadding + dColTrans return inputImage, rowPadding, dRowTrans, colPadding, dColTrans, scaleRatio
StarcoderdataPython
4961813
# Copyright (c) 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Enforces workaround list is alphabetically sorted. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details on the presubmit API built into depot_tools. """ import difflib import os.path import io USE_PYTHON3 = True def _CheckGPUWorkaroundListSorted(input_api, output_api): """Check: gpu_workaround_list.txt feature list sorted alphabetically. """ filename = os.path.join(input_api.PresubmitLocalPath(), 'gpu_workaround_list.txt') with io.open(filename, encoding='utf-8') as f: workaround_list = [line.rstrip('\n') for line in f] workaround_list_sorted = sorted(workaround_list, key=lambda s: s.lower()) if workaround_list == workaround_list_sorted: return [] # Diff the sorted/unsorted versions. differ = difflib.Differ() diff = differ.compare(workaround_list, workaround_list_sorted) return [output_api.PresubmitError( 'gpu_workaround_list.txt features must be sorted alphabetically. ' 'Diff of feature order follows:', long_text='\n'.join(diff))] def CheckChangeOnUpload(input_api, output_api): return _CheckGPUWorkaroundListSorted(input_api, output_api) def CheckChangeOnCommit(input_api, output_api): return _CheckGPUWorkaroundListSorted(input_api, output_api)
StarcoderdataPython
1838474
# Import the necessary methods from tweepy library from tweepy import OAuthHandler from tweepy import API from classes.KafkaPC import KafkaPC class TwitterP(KafkaPC): def __init__(self, config_path=None, in_topic=None, in_group=None, in_schema_file=None, out_topic=None, out_schema_file=None): super().__init__(config_path, in_topic, in_group, in_schema_file, out_topic, out_schema_file) auth = OAuthHandler(*self.config['Twitter']['consumer_key'], *self.config['Twitter']['consumer_secret']) auth.set_access_token(*self.config['Twitter']['access_token'], *self.config['Twitter']['access_token_secret']) self.api = API(auth, wait_on_rate_limit=True)
StarcoderdataPython
135400
"""Dummy sensor script Sends dummy data to BuildingDepot. This script sends noises to uuids[0] to [9], and sends sin waves to uuids[10] to [13]. This emulates the situation where a TI SensorTag is being shaken """ import time import math import random from json_setting import JsonSetting from buildingdepot_helper import BuildingDepotHelper if __name__ == "__main__": '''Load settings If you installed BuildingDepot with its demo database, you do not need to change the parameters in connector_setting.json. Otherwise, update the file according to what you configured in BuildingDepot. ''' connector_setting = JsonSetting('./connector_setting.json') bd_helper = BuildingDepotHelper() uuids = connector_setting.get('sensor_uuids') sampling_period = connector_setting.get('sampling_period') 'Send dummy data' while True: data_array = [] timestamp = time.time() value = math.sin(timestamp*4) * 10 + 10 index = 0 for uuid in uuids: dic = {} dic['sensor_id'] = uuid if index<10: dic['samples'] = [{"time":timestamp,"value":random.random()}] else: dic['samples'] = [{"time":timestamp,"value":value}] dic['value_type']='' data_array.append(dic) index += 1 result = bd_helper.post_data_array(data_array) print result time.sleep(sampling_period);
StarcoderdataPython
9726557
import os from photogrammetry_importer.types.point import Point from photogrammetry_importer.file_handlers.ply_file_handler import PLYFileHandler from photogrammetry_importer.utility.blender_logging_utility import log_report class DataSemantics(object): def __init__(self): self.x_idx = None self.y_idx = None self.z_idx = None self.r_idx = None self.g_idx = None self.b_idx = None self.pseudo_color = None def is_color_initialized(self): return not None in [self.r_idx, self.g_idx, self.b_idx] def is_int(some_str): try: int(some_str) return True except ValueError: return False def is_float(some_str): try: float(some_str) return True except ValueError: return False class PointDataFileHandler(object): @staticmethod def read_lines_as_tuples(ifc, delimiter): lines_as_tup = [] for line in ifc.readlines(): elements = line.split(delimiter) lines_as_tup.append(elements) return lines_as_tup @staticmethod def guess_data_semantics(data_tuple): log_report('INFO', 'Guessing data semantics') data_semantics = DataSemantics() # Data must start with subsequent float values # representing the three-dimensional position for idx in [0, 1, 2]: assert is_float(data_tuple[idx]) data_semantics.x_idx = 0 data_semantics.y_idx = 1 data_semantics.z_idx = 2 num_data_entries = len(data_tuple) # Search for three subsequent int values between 0 and 255 # (which indicate RGB color information) for idx in [3, num_data_entries-3]: if not is_int(data_tuple[idx]): continue if not is_int(data_tuple[idx + 1]): continue if not is_int(data_tuple[idx + 2]): continue if not 0 <= int(data_tuple[idx]) <= 255: continue if not 0 <= int(data_tuple[idx]) <= 255: continue if not 0 <= int(data_tuple[idx]) <= 255: continue data_semantics.r_idx = idx data_semantics.g_idx = idx + 1 data_semantics.b_idx = idx + 2 data_semantics.pseudo_color = False break if data_semantics.is_color_initialized(): return data_semantics # If not int values are found, we assume that the color information # is stored as pseudo colors, i.e. we are looking for 3 subsequent # floats between (0,1). for idx in [3, num_data_entries-3]: assert is_float(data_tuple[idx]) if not 0 <= float(data_tuple[idx]) <= 1: continue if not 0 <= float(data_tuple[idx+1]) <= 1: continue if not 0 <= float(data_tuple[idx+2]) <= 1: continue data_semantics.r_idx = idx data_semantics.g_idx = idx + 1 data_semantics.b_idx = idx + 2 data_semantics.pseudo_color = True break return data_semantics @staticmethod def parse_header(line): data_semantics = DataSemantics() data_tuple = line.lstrip('//').rstrip().split(' ') for idx, val in enumerate(data_tuple): if val == 'X': data_semantics.x_idx = idx elif val == 'Y': data_semantics.y_idx = idx elif val == 'Z': data_semantics.z_idx = idx elif val == 'R': data_semantics.r_idx = idx data_semantics.pseudo_color = False elif val == 'G': data_semantics.g_idx = idx data_semantics.pseudo_color = False elif val == 'B': data_semantics.b_idx = idx data_semantics.pseudo_color = False elif val == 'Rf': data_semantics.r_idx = idx data_semantics.pseudo_color = True elif val == 'Gf': data_semantics.g_idx = idx data_semantics.pseudo_color = True elif val == 'Bf': data_semantics.b_idx = idx data_semantics.pseudo_color = True return data_semantics @staticmethod def parse_asc_or_pts_or_csv(ifp, delimiter, only_data): points = [] with open(ifp, 'r') as ifc: data_semantics = None if not only_data: line = ifc.readline() if line.startswith('//'): data_semantics = PointDataFileHandler.parse_header(line) line = ifc.readline() num_points = int(line.strip()) else: num_points = int(line.strip()) lines_as_tuples = PointDataFileHandler.read_lines_as_tuples( ifc, delimiter=delimiter) if data_semantics is None: # Determine the semantics of the data data_tuple = lines_as_tuples[0] data_semantics = PointDataFileHandler.guess_data_semantics( data_tuple) if data_semantics.pseudo_color: factor = 255 else: factor = 1 for idx, data_tuple in enumerate(lines_as_tuples): point = Point( coord=[ float(data_tuple[data_semantics.x_idx]), float(data_tuple[data_semantics.y_idx]), float(data_tuple[data_semantics.z_idx])], color=[ int(factor * float(data_tuple[data_semantics.r_idx])), int(factor * float(data_tuple[data_semantics.g_idx])), int(factor * float(data_tuple[data_semantics.b_idx]))], id=idx, scalars=None) points.append(point) return points @staticmethod def parse_point_data_file(ifp): log_report('INFO', 'Parse Point Data File: ...') ext = os.path.splitext(ifp)[1].lower() if ext == '.ply': points = PLYFileHandler.parse_ply_file(ifp) elif ext == '.csv': points = PointDataFileHandler.parse_asc_or_pts_or_csv( ifp, delimiter=',', only_data=True) elif ext in ['.asc', '.pts']: # https://www.cloudcompare.org/doc/wiki/index.php?title=FILE_I/O points = PointDataFileHandler.parse_asc_or_pts_or_csv( ifp, delimiter=' ', only_data=False) else: log_report('ERROR', 'Extension ' + ext + ' not supported.', self) assert False log_report('INFO', 'Parse Point Data File: Done') return points
StarcoderdataPython
308089
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import boto3 import os import traceback import auditors def get_queue_url(queue_arn): # Given a queue_arn like "arn:aws:sqs:us-east-1:123456789012:remediator-queue" # returns "https://queue.amazonaws.com/123456789012/remediator-queue" parts = queue_arn.split(":") return "https://queue.amazonaws.com/{}/{}".format(parts[4], parts[5]) def handler(event, context, remediate=False): sqs = boto3.client("sqs") # Get environment variable for whether we should remediate if os.environ.get("REMEDIATE", "") != "": if os.environ["REMEDIATE"].lower() == "true": remediate = True remediation_resource_exception = (os.environ.get("REMEDIATION_RESOURCE_EXCEPTION", "")).split(',') print("custom resource exception: {}".format(remediation_resource_exception)) custom_module_exception = os.environ.get("REMEDIATION_MODULE_EXCEPTION", "") print("custom module exception: {}".format(custom_module_exception)) custom_module_exception = json.loads(custom_module_exception) for record in event["Records"]: # Records will look like this: # { # "messageId": "059f36b4-87a3-44ab-83d2-661975830a7d", # "receiptHandle": "<KEY> # "body": "{\"account\": \"123456789012\", \"region\": \"us-east-1\", \"type\": \"sqs\", \"id\": \"https://sqs.us-east-1.amazonaws.com/123456789012/remediator-queue\"}", # "attributes": { # "ApproximateReceiveCount": "6", # "SentTimestamp": "1576514933843", # "SenderId": "AIDAEXAMPLE:event_translator", # "ApproximateFirstReceiveTimestamp": "1576514933843" # }, # "messageAttributes": # {} # , # "md5OfBody": "284dc368c8caf5174468424aceaf88be", # "eventSource": "aws:sqs", # "eventSourceARN": "arn:aws:sqs:us-east-1:123456789012:remediator-queue", # "awsRegion": "us-east-1" # } # Delete the message from the queue so we don't keep rereading it # This strategy does mean if there are errors in remediating, we won't retry if "receiptHandle" in record: receipt_handle = record["receiptHandle"] queue_url = get_queue_url(record["eventSourceARN"]) # Delete received message from queue sqs.delete_message(QueueUrl=queue_url, ReceiptHandle=receipt_handle) resource = json.loads(record["body"]) print("Checking {}".format(resource)) # Get the module based on the type passed in the message resource_module = getattr(auditors, resource["type"]) try: # Call the auditor and check if custom whitelisting is present if (resource["account"] in custom_module_exception.keys() and resource[ "type" ] in custom_module_exception.get(resource["account"])) or (resource["id"] in remediation_resource_exception): remediate = False resource_module.audit(resource, remediate) else: resource_module.audit(resource, remediate) except Exception as e: print(e) traceback.print_exc() continue return True if __name__ == "__main__": # When called from the command-line (as opposed to being called as a Lambda), # read json lines from stdin and convert them to look like they were received from an SQS trigger # for the Lambda handler. import sys import argparse parser = argparse.ArgumentParser( description=""" To test manually, create a test file with contents: {"account": "123456789012", "region": "us-east-1", "type": "sqs", "id": "https://sqs.us-east-1.amazonaws.com/123456789012/misconfiguration_maker-bad"} Then run: cat test.json | python resources/remediator/main.py """, formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argument( "--remediate", help="Remediate the issues found", default=None, ) args = parser.parse_args() for line in sys.stdin: event = { "Records": [ { "messageId": "0", "body": line, "attributes": { "ApproximateReceiveCount": "1", "SentTimestamp": "0", "SenderId": "", "ApproximateFirstReceiveTimestamp": "0", }, "messageAttributes": {}, "md5OfBody": "", "eventSource": "aws:sqs", "eventSourceARN": "arn:aws:sqs:us-east-1:000000000000:remediator-queue", "awsRegion": "us-east-1", } ] } handler(event, None, remediate=args.remediate)
StarcoderdataPython
5178439
#!/usr/bin/env python """ Concatenate files containing trial data. SCL; Feb 2012. """ import sys import pickle if __name__ == "__main__": if len(sys.argv) < 3: print "Usage: %s FILE1 [...] OUTPUT" % sys.argv[0] exit(1) times = [] world_data = [] for file_index in range(len(sys.argv)-2): print "Reading %s..." % sys.argv[file_index+1] with open(sys.argv[file_index+1], "r") as f: (this_times, this_world_data) = pickle.load(f) times.extend(this_times) world_data.extend(this_world_data) print "Writing combined set to %s..." % sys.argv[-1] with open(sys.argv[-1], "w") as f: pickle.dump((times, world_data), f)
StarcoderdataPython
11227875
# Copyright (c) Microsoft Corporation # All rights reserved. # # MIT License # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and # to permit persons to whom the Software is furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING # BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import nni import subprocess import logging LOG = logging.getLogger('rocksdb-fillrandom') def run(**parameters): '''Run rocksdb benchmark and return throughput''' bench_type = parameters['benchmarks'] # recover args args = ["--{}={}".format(k, v) for k, v in parameters.items()] # subprocess communicate process = subprocess.Popen(['db_bench'] + args, stdout=subprocess.PIPE) out, err = process.communicate() # split into lines lines = out.decode("utf8").splitlines() match_lines = [] for line in lines: # find the line with matched str if bench_type not in line: continue else: match_lines.append(line) break results = {} for line in match_lines: key, _, value = line.partition(":") key = key.strip() value = value.split("op")[1] results[key] = float(value) return results[bench_type] def generate_params(received_params): '''generate parameters based on received parameters''' params = { "benchmarks": "fillrandom", "threads": 1, "key_size": 20, "value_size": 100, "num": 13107200, "db": "/tmp/rockdb", "disable_wal": 1, "max_background_flushes": 1, "max_background_compactions": 4, "write_buffer_size": 67108864, "max_write_buffer_number": 16, "min_write_buffer_number_to_merge": 2, "level0_file_num_compaction_trigger": 2, "max_bytes_for_level_base": 268435456, "max_bytes_for_level_multiplier": 10, "target_file_size_base": 33554432, "target_file_size_multiplier": 1 } for k, v in received_params.items(): params[k] = int(v) return params if __name__ == "__main__": try: # get parameters from tuner RECEIVED_PARAMS = nni.get_next_parameter() LOG.debug(RECEIVED_PARAMS) PARAMS = generate_params(RECEIVED_PARAMS) LOG.debug(PARAMS) # run benchmark throughput = run(**PARAMS) # report throughput to nni nni.report_final_result(throughput) except Exception as exception: LOG.exception(exception) raise
StarcoderdataPython
5024167
# Copyright 2022 The Kubeflow 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. """ module for bayesian optimization algorithm """ import numpy as np from sklearn.preprocessing import MinMaxScaler from pkg.suggestion.v1beta1.bayesianoptimization.global_optimizer import GlobalOptimizer class BOAlgorithm: """ class for bayesian optimization """ def __init__(self, experiment_name, dim, N, lowerbound, upperbound, X_train, y_train, mode, trade_off, length_scale, noise, nu, kernel_type, n_estimators, max_features, model_type, logger=None): # np.random.seed(0) self._experiment_name = experiment_name self.dim = dim self.N = N or 100 self.l = np.zeros((1, dim)) self.u = np.ones((1, dim)) self.lowerbound = lowerbound.reshape(1, dim) self.upperbound = upperbound.reshape(1, dim) self.logger = logger # normalize the upperbound and lowerbound to [0, 1] self.scaler = MinMaxScaler() self.scaler.fit(np.append(self.lowerbound, self.upperbound, axis=0)) self.X_train = X_train self.y_train = y_train if self.y_train is None: self.current_optimal = None else: self.current_optimal = max(self.y_train) self.logger.debug("create optimizer", extra={ "Experiment": self._experiment_name}) # initialize the global optimizer self.optimizer = GlobalOptimizer( N, self.l, self.u, self.scaler, self.X_train, self.y_train, self.current_optimal, experiment_name=self._experiment_name, mode=mode, trade_off=trade_off, length_scale=length_scale, noise=noise, nu=nu, kernel_type=kernel_type, n_estimators=n_estimators, max_features=max_features, model_type=model_type, logger=logger, ) self.logger.debug("optimizer created", extra={ "Experiment": self._experiment_name}) def get_suggestion(self, request_num): """ main function to provide suggestion """ x_next_list = [] if self.X_train is None and self.y_train is None and self.current_optimal is None: # randomly pick a point as the first trial for _ in range(request_num): x_next_list.append(np.random.uniform( self.lowerbound, self.upperbound, size=(1, self.dim))) else: _, x_next_list_que = self.optimizer.direct(request_num) for xn in x_next_list_que: x = np.array(xn).reshape(1, self.dim) x = self.scaler.inverse_transform(x) x_next_list.append(x) return x_next_list
StarcoderdataPython
5048059
import platform #This programe is create by <NAME> # Github: https://github.com/sujitmandal # Pypi : https://pypi.org/user/sujitmandal/ # LinkedIn : https://www.linkedin.com/in/sujit-mandal-91215013a/ def slash(): if platform.system() == 'Linux': system = '/' elif platform.system() == 'Windows': syste = ' \ ' system = syste.strip() return(system) if __name__ == "__main__": slash()
StarcoderdataPython
1875007
import sys from DB import db, User from Security import password if 'y' != input('Tämä tuohoaa tietokannan, oletko varma? [y/n]'): sys.exit() db.drop_all() db.create_all() u = User() u.username = 'swat' u.password_hash = password.hash('<PASSWORD>') u.email = '<EMAIL>' u.admin = True db.session.add(u) db.session.commit()
StarcoderdataPython
4854137
"""Unit tests for initialization of secrets.""" import unittest from unittest.mock import Mock from external.initialization.secrets import initialize_secrets class TestSecrets(unittest.TestCase): """Unit tests for initialization of secrets.""" def setUp(self): """Set up database mocks.""" self.database = Mock() self.database.secrets.insert = Mock() def test_initialize_secrets(self): """Test initialization of field encryption secrets.""" # A secret already exists self.database.secrets.find_one.return_value = True initialize_secrets(self.database) self.assertFalse(self.database.secrets.insert_one.called) # no secret exists yet, should insert self.database.secrets.find_one.return_value = None initialize_secrets(self.database) self.assertTrue(self.database.secrets.insert_one.called)
StarcoderdataPython
11387090
<reponame>snchvn/Python-Discord-NPC-bot<gh_stars>0 import discord import random import os # Mission giver Discord bot. Randomly allocates pre-written mission scripts to members of voice channel. # Read your Discord Bot's connecting token from Heroku config vars access_token = os.environ["ACCESS_TOKEN"] channel_id = os.environ["CHANNEL_ID"] # Read the missions.txt file with all the different missions [INSERT MISSION PARAMETERS IN THIS FILE] def read_missions(): with open("missions.txt","r") as f: lines = [i.strip() for i in f] return lines missions = read_missions() # Discord API calls begin here client = discord.Client() @client.event async def on_message(message): # Use below code to define mission invocation by user role # valid_users = ["$ROLES"] # if str(message.channel) in channels and str(message.author) in valid_users: channels = ["bot-commands"] if str(message.channel) in channels: # Setting the !risk command if message.content == "!risk": # Shuffle missions every time !risk is called random.shuffle(missions) # Get list of players present in the risk voice channel [Replace this with your own channel ID] risk_channel = client.get_channel(int(channel_id)) members = risk_channel.members # Generate a list of player IDs players = [] for member in members: players.append(str(member.id)) # Exit clause when script is invoked with no players if len(players)==0: await message.channel.send("Mission abort. There are no players on the Risk voice channel.") else: # Allocate missions to players for i in range(0,len(players)): # Get the user element from the iterable player ID (GOT STUCK HERE FOR 2 HOURS PASSING INTEGER AS STRING) player = discord.utils.get(client.get_all_members(), id=int(players[i])) # Compose message for each player allocating their respective mission messageContent = ("<@" + str(players[i]) + "> your mission is to " + missions[i]) #Send a DM to each player await player.send(messageContent) await message.channel.send("Mission orders issued successfully.") client.run(access_token)
StarcoderdataPython
1668535
<filename>tracardi/process_engine/action/v1/internal/inject_event/model/configuration.py from pydantic import BaseModel, validator class Configuration(BaseModel): event_id: str @validator("event_id") def event_id_can_not_be_empty(cls, value): if len(value) == 0: raise ValueError("Event id can not be empty") return value
StarcoderdataPython
1671218
# -*- coding: utf-8 -*- from __future__ import unicode_literals """ 维吉尼亚密码破解 """ from pycipher import Vigenere from ..utils import get_raw_plain_text import re LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def find_key_by_plain_cipher(plain, cipher): # key = '<KEY>' # cipher = '''jwm ewrboya fe gjbxcd hrzcvt.''' # plain = '''the tragedy of julius caesar.''' cipher = re.sub(r'[^A-Z]', '', cipher.upper()) plain = re.sub(r'[^A-Z]', '', plain.upper()) key = '' for i in range(len(cipher)): for x in LETTERS: if Vigenere(key + x).decipher(cipher)[i] == plain[i]: key += x break key = key.lower() print(key) return key def decode(cipher, key): plain = Vigenere(key).decipher(cipher) r = get_raw_plain_text(cipher, plain) print(r) return r def main(): cipher = """jwm ewrboya fe gjbxcd hrzcvt.""" plain = """the tragedy of julius caesar.""" key = find_key_by_plain_cipher(plain, cipher) decode(cipher, key) if __name__ == '__main__': main()
StarcoderdataPython
3487964
from chainer0.variable import Variable from chainer0.function import Function from chainer0.function import grad from chainer0.link import Link from chainer0.link import Chain from chainer0.functions import basic_math from chainer0.functions import array from chainer0.optimizer import Optimizer from chainer0.configuration import config from chainer0 import optimizers from chainer0 import functions from chainer0 import datasets from chainer0 import distributions basic_math.install_variable_arithmetics() array.install_variable_get_item() config.enable_backprop = True config.train = True
StarcoderdataPython
3571663
""" Is a message-queueing, a rabbitMQ, that allows 'Meter' and 'PV_simulator' to communicate with each other. It receives messages from 'Meter' and sends them to 'PV_simulator' """ import aio_pika from typing import Callable from logging import Logger class Broker: def __init__(self,address: str, queue_name:str, logger:Logger=None)->None: """ :param address: address of a broker (e.g: 'localhost' or IP address) :param queue_name: Name of the rabbitMQ queue :param logger: logger obj """ self.address = address self.queue_name = queue_name self.connection = None self.channel = None self.message_queue = None self.logger=logger async def connect(self)->bool: """ Create the connection and declare the queue In case it is not possible to create the connection an error message will explain the reason """ try: # connect to the rabbitMQ, create a channel and declare the queue self.connection = await aio_pika.connect(self.address) self.channel = await self.connection.channel() self.message_queue = await self.channel.declare_queue(self.queue_name) self.logger.info("broker connected") except Exception as e: self.logger.error (f"Not enable to create the connection because '{e}' exception") raise e return True async def close(self)->bool: """ Closes the connection In case it is not possible to close the connection an error message will explain the reason """ if self.connection: try: # close the connection await self.connection.close() self.logger.info("broker closed") return True except Exception as e: self.logger.error(f"Not enable to close the connection because '{e}' exception") raise e return False async def publish_msg(self, msg:str)->None: """ Publishes (i.e.:sends) a message to the queue :param msg: message """ await self.channel.default_exchange.publish( aio_pika.Message( body=msg.encode('utf-8')), routing_key=self.queue_name) async def consume_msg(self, process_message:Callable)->None: """ consumes a message from the queue :param process_message: callable function (e.g.: PV_simulator.process_message) """ await self.message_queue.consume(process_message, no_ack=True)
StarcoderdataPython
9727736
class Solution: def totalFruit(self, tree): """ :type tree: List[int] :rtype: int """ # each basket has one kind # longest sub-array that has two kinds of fruits # need to remember the last seen index of each fruit ans = 0 i = 0 s, idxes = set(), {} for j, val in enumerate(tree): s.add(val) idxes[val] = j if len(s) > 2: kind = min(s, key=lambda x : idxes[x]) i = idxes[kind] + 1 s.remove(kind) ans = max(j - i + 1, ans) return ans
StarcoderdataPython
8181156
## Copyright (c) 2015 SONATA-NFV, 2017 5GTANGO [, ANY ADDITIONAL AFFILIATION] ## 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. ## ## Neither the name of the SONATA-NFV, 5GTANGO [, ANY ADDITIONAL AFFILIATION] ## nor the names of its contributors may be used to endorse or promote ## products derived from this software without specific prior written ## permission. ## ## This work has been performed in the framework of the SONATA project, ## funded by the European Commission under Grant number 671517 through ## the Horizon 2020 and 5G-PPP programmes. The authors would like to ## acknowledge the contributions of their colleagues of the SONATA ## partner consortium (www.sonata-nfv.eu). ## ## This work has been performed in the framework of the 5GTANGO project, ## funded by the European Commission under Grant number 761493 through ## the Horizon 2020 and 5G-PPP programmes. The authors would like to ## acknowledge the contributions of their colleagues of the 5GTANGO ## partner consortium (www.5gtango.eu). # encoding: utf-8 import logging,os from logging.handlers import RotatingFileHandler from statscollector import vnf_monitor if __name__ == '__main__': logger = logging.getLogger('Monitoring Container') hdlr = RotatingFileHandler('monitoring.log', maxBytes=1000000, backupCount=1) formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.WARNING) logger.setLevel(logging.INFO) prom_url = os.getenv('PW_URL', 'pushgateway.sonata.svc:9091') vnf_url = os.getenv('VNF_STATS_URL', None) interval = os.getenv('INTERVAL', 2) if (not prom_url) or (not vnf_url) or (not interval): print('PW_URL :'+str(prom_url)) print('VNF_STATS_URL :' + str(vnf_url)) print('INTERVAL :' + str(interval)) else: vnf_monitor(prom_pw_url_=prom_url,vnf_stats_url_=vnf_url,interval_=int(interval), logger_=logger)
StarcoderdataPython
6466760
#Resolvendo o problema do arquivo não fechar quando ocorrer erro no código try: arquivo = open('pessoas.csv') for linha in arquivo: print('Nome: {}, Idade: {}'.format(*linha.strip().split(','))) #Usando * irá extrair os elementos de uma coleção de dados (lista, tuplas dicionários, sets, etc) except IndexError: pass finally: print('fim do programa') arquivo.close() if arquivo.closed: print('O arquivo já foi fechado') '''OBS: O bloco finally sempre será executado independetemente se ocorrerá erro ou não dentro do bloco try, mas não irá executar a linha arquivo.closed se ocorrer erros. Para contornar isso, utiliza-se o bloco except com o pass que irá passar diretamente para as próximas linhas, inclusive o arquivo.closed'''
StarcoderdataPython
3415237
<reponame>ehaka/lie-algebra-gradings from lie_gradings.classification.classified_lie_algebra import ClassifiedNilpotentLieAlgebra __all__ = ['L1_1'] def L1_1(F): sc = {} return ClassifiedNilpotentLieAlgebra(F, 'L1_1', sc, names=['X_1'])
StarcoderdataPython
376742
<reponame>dkirkby/batoid import os import numpy as np import batoid from test_helpers import timer from batoid.utils import normalized @timer def test_plane_refraction_plane(): import random random.seed(5) wavelength = 500e-9 # arbitrary plane = batoid.Plane() m1 = batoid.ConstMedium(1.1) m2 = batoid.ConstMedium(1.3) for i in range(1000): x = random.gauss(0, 1) y = random.gauss(0, 1) vx = random.gauss(0, 1e-1) vy = random.gauss(0, 1e-1) v = np.array([vx, vy, 1]) v /= np.linalg.norm(v) ray = batoid.Ray([x, y, -10], v/m1.getN(wavelength), 0) rray = plane.refract(ray, m1, m2) np.testing.assert_allclose(np.linalg.norm(rray.v), 1./m2.getN(wavelength), rtol=1e-15) # also check refractInPlace rray2 = batoid.Ray(ray) plane.refractInPlace(rray2, m1, m2) assert rray == rray2 # ray.v, surfaceNormal, and rray.v should all be in the same plane, and # hence (ray.v x surfaceNormal) . rray.v should have zero magnitude. normal = plane.normal(rray.r[0], rray.r[1]) np.testing.assert_allclose( np.dot(np.cross(ray.v, normal), rray.v), 0.0, rtol=0, atol=1e-15) # Test Snell's law np.testing.assert_allclose( m1.getN(wavelength)*np.linalg.norm(np.cross(normalized(ray.v), normal)), m2.getN(wavelength)*np.linalg.norm(np.cross(normalized(rray.v), normal)), rtol=0, atol=1e-15) @timer def test_plane_refraction_reversal(): import random random.seed(57) wavelength = 500e-9 # arbitrary plane = batoid.Plane() m1 = batoid.ConstMedium(1.5) m2 = batoid.ConstMedium(1.2) for i in range(1000): x = random.gauss(0, 1) y = random.gauss(0, 1) vx = random.gauss(0, 1e-1) vy = random.gauss(0, 1e-1) ray = batoid.Ray([x, y, -10], normalized(np.array([vx, vy, 1]))/m1.getN(wavelength), 0) rray = plane.refract(ray, m1, m2) np.testing.assert_allclose(np.linalg.norm(rray.v), 1./m2.getN(wavelength), rtol=1e-15) # Invert the refracted ray, and see that it ends back at the starting # point # Keep going a bit before turning around though turn_around = rray.positionAtTime(rray.t+0.1) return_ray = batoid.Ray(turn_around, -rray.v, -(rray.t+0.1)) riray = plane.intersect(return_ray) np.testing.assert_allclose(rray.r[0], riray.r[0], rtol=0, atol=1e-10) np.testing.assert_allclose(rray.r[1], riray.r[1], rtol=0, atol=1e-10) np.testing.assert_allclose(rray.r[2], riray.r[2], rtol=0, atol=1e-10) # Refract and propagate back to t=0. cray = plane.refract(return_ray, m2, m1) np.testing.assert_allclose(np.linalg.norm(cray.v), 1./m1.getN(wavelength), rtol=1e-15) cpoint = cray.positionAtTime(0) np.testing.assert_allclose(cpoint[0], x, rtol=0, atol=1e-10) np.testing.assert_allclose(cpoint[1], y, rtol=0, atol=1e-10) np.testing.assert_allclose(cpoint[2], -10, rtol=0, atol=1e-10) @timer def test_paraboloid_refraction_plane(): import random random.seed(577) wavelength = 500e-9 # arbitrary para = batoid.Paraboloid(-20.0) m1 = batoid.ConstMedium(1.11) m2 = batoid.ConstMedium(1.32) for i in range(1000): x = random.gauss(0, 1) y = random.gauss(0, 1) vx = random.gauss(0, 1e-1) vy = random.gauss(0, 1e-1) v = normalized(np.array([vx, vy, 1]))/m1.getN(wavelength) ray = batoid.Ray(x, y, -10, v[0], v[1], v[2], 0) rray = para.refract(ray, m1, m2) np.testing.assert_allclose(np.linalg.norm(rray.v), 1./m2.getN(wavelength), rtol=1e-15) # also check refractInPlace rray2 = batoid.Ray(ray) para.refractInPlace(rray2, m1, m2) assert rray == rray2 # ray.v, surfaceNormal, and rray.v should all be in the same plane, and # hence (ray.v x surfaceNormal) . rray.v should have zero magnitude. # magnitude zero. normal = para.normal(rray.r[0], rray.r[1]) np.testing.assert_allclose( np.dot(np.cross(ray.v, normal), rray.v), 0.0, rtol=0, atol=1e-15) # Test Snell's law np.testing.assert_allclose( m1.getN(wavelength)*np.linalg.norm(np.cross(normalized(ray.v), normal)), m2.getN(wavelength)*np.linalg.norm(np.cross(normalized(rray.v), normal)), rtol=0, atol=1e-15) @timer def test_paraboloid_refraction_reversal(): import random random.seed(5772) wavelength = 500e-9 # arbitrary para = batoid.Paraboloid(-20.0) m1 = batoid.ConstMedium(1.43) m2 = batoid.ConstMedium(1.34) for i in range(1000): x = random.gauss(0, 1) y = random.gauss(0, 1) vx = random.gauss(0, 1e-1) vy = random.gauss(0, 1e-1) ray = batoid.Ray([x, y, -10], normalized(np.array([vx, vy, 1]))/m1.getN(wavelength), 0) rray = para.refract(ray, m1, m2) np.testing.assert_allclose(np.linalg.norm(rray.v), 1./m2.getN(wavelength), rtol=1e-15) # Invert the refracted ray, and see that it ends back at the starting # point # Keep going a bit before turning around though turn_around = rray.positionAtTime(rray.t+0.1) return_ray = batoid.Ray(turn_around, -rray.v, -(rray.t+0.1)) riray = para.intersect(return_ray) # First check that we intersected at the same point np.testing.assert_allclose(rray.r[0], riray.r[0], rtol=0, atol=1e-10) np.testing.assert_allclose(rray.r[1], riray.r[1], rtol=0, atol=1e-10) np.testing.assert_allclose(rray.r[2], riray.r[2], rtol=0, atol=1e-10) # Refract and propagate back to t=0. cray = para.refract(return_ray, m2, m1) np.testing.assert_allclose(np.linalg.norm(cray.v), 1./m1.getN(wavelength), rtol=1e-15) cpoint = cray.positionAtTime(0) np.testing.assert_allclose(cpoint[0], x, rtol=0, atol=1e-10) np.testing.assert_allclose(cpoint[1], y, rtol=0, atol=1e-10) np.testing.assert_allclose(cpoint[2], -10, rtol=0, atol=1e-10) @timer def test_asphere_refraction_plane(): import random random.seed(57721) wavelength = 500e-9 # arbitrary asphere = batoid.Asphere(25.0, -0.97, [1e-3, 1e-5]) m1 = batoid.ConstMedium(1.7) m2 = batoid.ConstMedium(1.2) for i in range(1000): x = random.gauss(0, 1) y = random.gauss(0, 1) vx = random.gauss(0, 1e-1) vy = random.gauss(0, 1e-1) v = normalized(np.array([vx, vy, 1]))/m1.getN(wavelength) ray = batoid.Ray(x, y, -0.1, v[0], v[1], v[2], 0) rray = asphere.refract(ray, m1, m2) np.testing.assert_allclose(np.linalg.norm(rray.v), 1./m2.getN(wavelength), rtol=1e-15) # also check refractInPlace rray2 = batoid.Ray(ray) asphere.refractInPlace(rray2, m1, m2) assert rray == rray2 # ray.v, surfaceNormal, and rray.v should all be in the same plane, and # hence (ray.v x surfaceNormal) . rray.v should have zero magnitude. # magnitude zero. normal = asphere.normal(rray.r[0], rray.r[1]) np.testing.assert_allclose( np.dot(np.cross(ray.v, normal), rray.v), 0.0, rtol=0, atol=1e-15) # Test Snell's law np.testing.assert_allclose( m1.getN(wavelength)*np.linalg.norm(np.cross(normalized(ray.v), normal)), m2.getN(wavelength)*np.linalg.norm(np.cross(normalized(rray.v), normal)), rtol=0, atol=1e-15) @timer def test_asphere_refraction_reversal(): import random random.seed(577215) wavelength = 500e-9 # arbitrary asphere = batoid.Asphere(23.0, -0.97, [1e-5, 1e-6]) m1 = batoid.ConstMedium(1.7) m2 = batoid.ConstMedium(1.9) for i in range(1000): x = random.gauss(0, 1) y = random.gauss(0, 1) vx = random.gauss(0, 1e-1) vy = random.gauss(0, 1e-1) ray = batoid.Ray([x, y, -0.1], normalized(np.array([vx, vy, 1]))/m1.getN(wavelength), 0) rray = asphere.refract(ray, m1, m2) np.testing.assert_allclose(np.linalg.norm(rray.v), 1./m2.getN(wavelength), rtol=1e-15) # Invert the refracted ray, and see that it ends back at the starting # point # Keep going a bit before turning around though turn_around = rray.positionAtTime(rray.t+0.1) return_ray = batoid.Ray(turn_around, -rray.v, -(rray.t+0.1)) riray = asphere.intersect(return_ray) # First check that we intersected at the same point np.testing.assert_allclose(rray.r[0], riray.r[0], rtol=0, atol=1e-10) np.testing.assert_allclose(rray.r[1], riray.r[1], rtol=0, atol=1e-10) np.testing.assert_allclose(rray.r[2], riray.r[2], rtol=0, atol=1e-10) # Refract and propagate back to t=0. cray = asphere.refract(return_ray, m2, m1) np.testing.assert_allclose(np.linalg.norm(cray.v), 1./m1.getN(wavelength), rtol=1e-15) cpoint = cray.positionAtTime(0) np.testing.assert_allclose(cpoint[0], x, rtol=0, atol=1e-10) np.testing.assert_allclose(cpoint[1], y, rtol=0, atol=1e-10) np.testing.assert_allclose(cpoint[2], -0.1, rtol=0, atol=1e-10) @timer def test_table_medium_refraction(): import random random.seed(57721566) filename = os.path.join(batoid.datadir, "media", "silica_dispersion.txt") wave, n = np.genfromtxt(filename).T table = batoid.Table(wave, n, batoid.Table.Interpolant.linear) silica = batoid.TableMedium(table) air = batoid.ConstMedium(1.000277) asphere = batoid.Asphere(25.0, -0.97, [1e-3, 1e-5]) for i in range(10000): x = random.gauss(0, 1) y = random.gauss(0, 1) vx = random.gauss(0, 1e-1) vy = random.gauss(0, 1e-1) wavelength = random.uniform(0.3, 1.2) ray = batoid.Ray(x, y, -0.1, vx, vy, 1, 0, wavelength) cm1 = batoid.ConstMedium(silica.getN(wavelength)) cm2 = batoid.ConstMedium(air.getN(wavelength)) rray1 = asphere.refract(ray, silica, air) rray2 = asphere.refract(ray, cm1, cm2) assert rray1 == rray2 @timer def test_refraction_chromatic(): import random random.seed(577215664) wavelength1 = 500e-9 wavelength2 = 600e-9 flux = 1.0 plane = batoid.Plane() filename = os.path.join(batoid.datadir, "media", "silica_dispersion.txt") wave, n = np.genfromtxt(filename).T wave *= 1e-6 # micron -> meters table = batoid.Table(wave, n, batoid.Table.Interpolant.linear) silica = batoid.TableMedium(table) air = batoid.Air() thx, thy = 0.001, 0.0001 dirCos = batoid.utils.gnomicToDirCos(thx, thy) rv1 = batoid.rayGrid(10.0, 1., dirCos[0], dirCos[1], -dirCos[2], 2, wavelength1, flux, silica) rv2 = batoid.rayGrid(10.0, 1., dirCos[0], dirCos[1], -dirCos[2], 2, wavelength2, flux, silica) rays = [] for ray in rv1: rays.append(ray) for ray in rv2: rays.append(ray) rvCombined = batoid.RayVector(rays) rv1r = plane.refract(rv1, silica, air) rv2r = plane.refract(rv2, silica, air) assert rv1r != rv2r rays = [] for ray in rv1r: rays.append(ray) for ray in rv2r: rays.append(ray) rvrCombined1 = batoid.RayVector(rays) rvrCombined2 = plane.refract(rvCombined, silica, air) assert rvrCombined1 == rvrCombined2 # Check in-place plane.refractInPlace(rv1, silica, air) plane.refractInPlace(rv2, silica, air) assert rv1 != rv2 plane.refractInPlace(rvCombined, silica, air) rays = [] for ray in rv1: rays.append(ray) for ray in rv2: rays.append(ray) rvCombined2 = batoid.RayVector(rays) assert rvCombined == rvCombined2 if __name__ == '__main__': test_plane_refraction_plane() test_plane_refraction_reversal() test_paraboloid_refraction_plane() test_paraboloid_refraction_reversal() test_asphere_refraction_plane() test_asphere_refraction_reversal() test_table_medium_refraction() test_refraction_chromatic()
StarcoderdataPython
3418424
#!/usr/bin/python # # Copyright 2002-2019 Barcelona Supercomputing Center (www.bsc.es) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # -*- coding: utf-8 -*- """ PyCOMPSs Util - JVM Configuration Parser ========================================= This file contains all methods required to parse the jvm options file. """ def convert_to_dict(jvm_opt_file): """ JVM parameter file converter to dictionary. :param jvm_opt_file: JVM parameters file :return: Dictionary with the parameters specified on the file. """ opts = {} with open(jvm_opt_file) as fp: for line in fp: line = line.strip() if line: if line.startswith("-XX:"): # These parameters have no value key = line.split(":")[1].replace('\n', '') opts[key] = True elif line.startswith("-D"): key = line.split("=")[0] value = line.split("=")[1].replace('\n', '') value = value.strip() if not value: value = None opts[key] = value else: key = line.replace('\n', '') opts[key] = True return opts
StarcoderdataPython
5114496
import ast import logging from typing import List, Set from grimp.application.ports.importscanner import AbstractImportScanner from grimp.domain.valueobjects import DirectImport, Module from grimp import exceptions logger = logging.getLogger(__name__) class NotAnImport(Exception): pass class ImportScanner(AbstractImportScanner): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # We gain a big performance increase by building the set of root modules once, # instead of letting each node parser figure them out from the internal modules. self._root_modules = {module.root for module in self.modules} def scan_for_imports(self, module: Module) -> Set[DirectImport]: """ Note: this method only analyses the module in question and will not load any other code, so it relies on self.modules to deduce which modules it imports. (This is because you can't know whether "from foo.bar import baz" is importing a module called `baz`, or a function `baz` from the module `bar`.) """ direct_imports: Set[DirectImport] = set() module_filename = self._determine_module_filename(module) is_package = self._module_is_package(module_filename) module_contents = self._read_module_contents(module_filename) module_lines = module_contents.splitlines() try: ast_tree = ast.parse(module_contents) except SyntaxError as e: raise exceptions.SourceSyntaxError( filename=module_filename, lineno=e.lineno, text=e.text, ) for node in ast.walk(ast_tree): direct_imports |= self._parse_direct_imports_from_node( node, module, module_lines, is_package ) return direct_imports def _parse_direct_imports_from_node( self, node: ast.AST, module: Module, module_lines: List[str], is_package: bool ) -> Set[DirectImport]: """ Parse an ast node into a set of DirectImports. """ try: parser = _get_node_parser( node=node, module=module, internal_modules=self.modules, root_modules=self._root_modules, is_package=is_package, ) except NotAnImport: return set() direct_imports: Set[DirectImport] = set() for imported in parser.determine_imported_modules( include_external_packages=self.include_external_packages ): direct_imports.add( DirectImport( importer=module, imported=imported, line_number=node.lineno, line_contents=module_lines[node.lineno - 1].strip(), ) ) return direct_imports def _determine_module_filename(self, module: Module) -> str: """ Work out the full filename of the given module. Any given module can either be a straight Python file (foo.py) or else a package (in which case the file is an __init__.py within a directory). """ module_components = module.name.split(".") package_directory = self._lookup_module_package_directory(module) package_directory_parts = self.file_system.split(package_directory) assert ( module_components[0] == package_directory_parts[-1] ), "The package directory should be the same as the first part of the module name." filename_root = self.file_system.join(package_directory, *module_components[1:]) candidate_filenames = ( f"{filename_root}.py", self.file_system.join(filename_root, "__init__.py"), ) for candidate_filename in candidate_filenames: if self.file_system.exists(candidate_filename): return candidate_filename raise FileNotFoundError(f"Could not find module {module}.") def _lookup_module_package_directory(self, module: Module) -> str: for package_directory, modules in self.modules_by_package_directory.items(): if module in modules: return package_directory raise KeyError(f"{module} was not present in the scanner.") def _read_module_contents(self, module_filename: str) -> str: """ Read the file contents of the module. """ return self.file_system.read(module_filename) def _module_is_package(self, module_filename: str) -> bool: """ Whether or not the supplied module filename is a package. """ return self.file_system.split(module_filename)[-1] == "__init__.py" class _BaseNodeParser: """ Works out from an AST node what the imported modules are. """ def __init__( self, node: ast.AST, module: Module, internal_modules: Set[Module], root_modules: Set[Module], is_package: bool, ) -> None: self.node = node self.module = module self.internal_modules = internal_modules self.root_modules = root_modules self.module_is_package = is_package def determine_imported_modules( self, include_external_packages: bool ) -> Set[Module]: """ Return the imported modules in the statement. """ raise NotImplementedError def _is_internal_module(self, module: Module) -> bool: return module.root in self.root_modules class _ImportNodeParser(_BaseNodeParser): """ Parser for statements in the form 'import x'. """ node_class = ast.Import def determine_imported_modules( self, include_external_packages: bool ) -> Set[Module]: imported_modules: Set[Module] = set() assert isinstance(self.node, self.node_class) # For type checker. for alias in self.node.names: module_from_alias = Module(alias.name) if self._is_internal_module(module_from_alias): imported_module = module_from_alias else: if include_external_packages: imported_module = Module(module_from_alias.package_name) else: continue imported_modules.add(imported_module) return imported_modules class _ImportFromNodeParser(_BaseNodeParser): """ Parser for statements in the form 'from x import ...'. """ node_class = ast.ImportFrom def determine_imported_modules( self, include_external_packages: bool ) -> Set[Module]: imported_modules: Set[Module] = set() assert isinstance(self.node, self.node_class) # For type checker. assert isinstance(self.node.level, int) # For type checker. if self.node.level == 0: # Absolute import. # Let the type checker know we expect node.module to be set here. assert isinstance(self.node.module, str) node_module = Module(self.node.module) if not self._is_internal_module(node_module): if include_external_packages: # Just return the top level package of the external module. return {Module(node_module.package_name)} else: return set() # Don't include imports of modules outside this package. module_base = self.node.module elif self.node.level >= 1: # Relative import. The level corresponds to how high up the tree it goes; # for example 'from ... import foo' would be level 3. importing_module_components = self.module.name.split(".") # TODO: handle level that is too high. # Trim the base module by the number of levels. if self.module_is_package: # If the scanned module an __init__.py file, we don't want # to go up an extra level. number_of_levels_to_trim_by = self.node.level - 1 else: number_of_levels_to_trim_by = self.node.level if number_of_levels_to_trim_by: module_base = ".".join( importing_module_components[:-number_of_levels_to_trim_by] ) else: module_base = ".".join(importing_module_components) if self.node.module: module_base = ".".join([module_base, self.node.module]) # node.names corresponds to 'a', 'b' and 'c' in 'from x import a, b, c'. for alias in self.node.names: full_module_name = ".".join([module_base, alias.name]) try: imported_module = self._trim_to_internal_module( untrimmed_module=Module(full_module_name) ) except FileNotFoundError: logger.warning( f"Could not find {full_module_name} when scanning {self.module}. " "This may be due to a missing __init__.py file in the parent package." ) else: imported_modules.add(imported_module) return imported_modules def _trim_to_internal_module(self, untrimmed_module: Module) -> Module: """ Raises FileNotFoundError if it could not find a valid module. """ if untrimmed_module in self.internal_modules: return untrimmed_module else: # The module isn't in the internal modules. This is because it's something *within* # a module (e.g. a function): the result of something like 'from .subpackage # import my_function'. So we trim the components back to the module. components = untrimmed_module.name.split(".")[:-1] trimmed_module = Module(".".join(components)) if trimmed_module in self.internal_modules: return trimmed_module else: raise FileNotFoundError() def _get_node_parser( node: ast.AST, module: Module, internal_modules: Set[Module], root_modules: Set[Module], is_package: bool, ) -> _BaseNodeParser: """ Return a NodeParser instance for the supplied node. Raises NotAnImport if the supplied node is not an import statement. """ parser_class_map = { ast.ImportFrom: _ImportFromNodeParser, ast.Import: _ImportNodeParser, } for node_class, parser_class in parser_class_map.items(): if isinstance(node, node_class): return parser_class( node=node, module=module, internal_modules=internal_modules, root_modules=root_modules, is_package=is_package, ) raise NotAnImport
StarcoderdataPython
1835443
<gh_stars>0 from bs4 import BeautifulSoup from bs4.element import NavigableString, Tag tags = { 'ignore': ['head', 'a', 'map', 'style', 'meta', 'base', 'link', 'script', 'noscript', 'img'], 'table': ['table'], 'table_cell': ['td', 'th'], 'table_colspan': 'colspan', 'table_row': ['tr'], 'table_rowspan': 'rowspan' } class ParsingTree: def __init__(self, html): self.tags = tags self.bs = BeautifulSoup(html, 'html.parser') self.elements = self.parse_tree(self.bs) def parse_tree(self, vertex): elements = [] if self.is_table(vertex): elements.append(('table', self.parse_table_tree(vertex))) else: if self.is_navigable(vertex): for child in vertex.children: elements += self.parse_tree(child) elif type(vertex) == NavigableString: text = str(vertex) if not self.is_void(text): elements.append(('text', text)) return elements def parse_table_tree(self, vertex): return self.parse_meta_tree( vertex, self.is_table_row, self.parse_row_tree) def parse_row_tree(self, vertex): return self.parse_meta_tree( vertex, self.is_table_cell, self.parse_cell_tree) def parse_cell_tree(self, vertex): row_span, col_span = self.get_span(vertex) text = ' | '.join(self.parse_string_tree(vertex)) return row_span, col_span, text @staticmethod def get_text(string): return str(string) if string else '' @staticmethod def is_void(text): if len(text.strip()) == 0: return True return False def parse_string_tree(self, vertex): return self.parse_meta_tree( vertex, self.is_string, self.get_text) def is_string(self, vertex): if (type(vertex) == NavigableString and not self.is_void(str(vertex))): return True def get_span(self, cell): rowspan, colspan = 1, 1 if self.tags['table_rowspan'] in cell.attrs: rowspan = int(cell[self.tags['table_rowspan']]) if self.tags['table_colspan'] in cell.attrs: colspan = int(cell[self.tags['table_colspan']]) return rowspan, colspan def parse_meta_tree(self, vertex, condition, parse_result): meta_tags = [] if condition(vertex): meta_tags.append(parse_result(vertex)) elif self.is_navigable(vertex): for child in vertex.children: meta_tags += self.parse_meta_tree(child, condition, parse_result) return meta_tags def is_table_row(self, vertex): return vertex.name in self.tags['table_row'] def is_table_cell(self, vertex): return vertex.name in self.tags['table_cell'] def is_navigable(self, tag): if type(tag) not in [Tag, BeautifulSoup]: return False if tag.name in self.tags['ignore']: return False return True def is_table(self, tag): if tag.name in self.tags['table']: return True return False
StarcoderdataPython
8169361
<reponame>ptrebert/reference-data # coding=utf-8 import os as os import io as io import re as re import gzip as gz import functools as fnt from pipelines.auxmod.auxiliary import read_chromsizes, check_bounds, open_comp def adjust_coordinates(regtype, start, end, strand): """ :param regtype: :param start: :param end: :param strand: :return: """ norm = 1 if strand in ['+', '.'] else -1 if regtype == 'reg5p': if norm > 0: s, e = start - 1000, start + 500 else: s, e = end - 500, end + 1000 elif regtype == 'body': s, e = start, end elif regtype == 'uprr': if norm > 0: s, e = start - 4000, start - 1000 else: s, e = end + 1000, end + 4000 else: raise ValueError('Unknown region type: {}'.format(regtype)) return s, e def make_bed_roi(inputfile, outputfile, chromfile, regtype): """ :param inputfile: :param outputfile: :param chromfile: :param regtype: :return: """ assert os.path.isfile(inputfile), 'Invalid input file: {}'.format(inputfile) chrom_bounds = read_chromsizes(chromfile) opn, mode, dec = open_comp(inputfile, read=True) regions = [] adjust = fnt.partial(adjust_coordinates, *(regtype,)) with opn(inputfile, mode) as infile: header = dec(infile.readline()) if header.startswith('#'): regions.append('\t'.join(header.split())) # assert \t separation else: infile.seek(0) for line in infile: region = dec(line).split() start, end = adjust(int(region[1]), int(region[2]), region[5]) assert start >= 0, 'Invalid start coordinate: {}'.format(start) assert end > 0, 'Invalid end coordinate: {}'.format(end) assert start < end, 'Invalid start - end: {} - {}'.format(start, end) try: _ = check_bounds(region[0], start, end, chrom_bounds, inputfile) except AssertionError: max_end = chrom_bounds[region[0]] assert end > max_end, 'Weirdly malformed region: {} - {} - {} - {}'.format(region, start, end, max_end) end = max_end assert start < end, 'Invalid region created: {} - {}'.format(start, end) region[1] = str(start) region[2] = str(end) regions.append('\t'.join(region)) opn, mode, enc = open_comp(outputfile, read=False) regions.append('') # assert newline at end of output file with opn(outputfile, mode) as outfile: _ = outfile.write(enc('\n'.join(regions))) return outputfile def normalize_join(inputfiles, outputfiles): """ :param inputfiles: :param outputfiles: :return: """ buffer_ncbi = [] buffer_ens = [] prefixed_chroms = re.compile('^[0-9XYM]') for fp in inputfiles: if fp.endswith('.gz'): opn, mode = gz.open, 'rt' to_strip = '.bed.gz' else: opn, mode = open, 'r' to_strip = '.bed' with opn(fp, mode) as infile: for idx, line in enumerate(infile, start=1): if not line.strip() or line.startswith('#'): continue cols = line.strip().split() region = cols[:3] try: name = cols[3] except IndexError: name = os.path.basename(fp).rstrip(to_strip) + '_' + str(idx) try: _ = int(name) name = os.path.basename(fp).rstrip(to_strip) + '_' + str(idx) except ValueError: pass region.append(name) if region[0].startswith('chr'): buffer_ncbi.append(region) region = [region[0][3:], region[1], region[2], region[3]] buffer_ens.append(region) else: if prefixed_chroms.match(region[0]): buffer_ens.append(region) region = ['chr' + region[0], region[1], region[2], region[3]] buffer_ncbi.append(region) else: buffer_ncbi.append(region) buffer_ens.append(region) buffer_ens = sorted(buffer_ens, key=lambda x: (x[0], int(x[1]), int(x[2]))) buffer_ncbi = sorted(buffer_ncbi, key=lambda x: (x[0], int(x[1]), int(x[2]))) ncbi_output = outputfiles[0] with open(ncbi_output, 'w') as outf: _ = outf.write('\n'.join(['\t'.join(reg) for reg in buffer_ncbi]) + '\n') ensembl_output = outputfiles[1] with open(ensembl_output, 'w') as outf: _ = outf.write('\n'.join(['\t'.join(reg) for reg in buffer_ens]) + '\n') return ncbi_output, ensembl_output
StarcoderdataPython
11255236
<gh_stars>0 """ whois_bridge service for Windows """ import os import sys import logging import win32service import win32serviceutil import servicemanager import jaraco.logging log = logging.getLogger(__name__) class Service(win32serviceutil.ServiceFramework): _svc_name_ = 'whois_bridge' _svc_display_name_ = 'Whois HTTP Bridge' def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) self.listener.server_close() def SvcDoRun(self): self._setup_logging() log.info('%s service is starting.', self._svc_display_name_) servicemanager.LogMsg( servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, ''), ) self.run() servicemanager.LogMsg( servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STOPPED, (self._svc_name_, ''), ) log.info('%s service is stopped.', self._svc_display_name_) def run(self): from jaraco.net.whois import init, Listener init() self.listener = Listener() self.listener.serve_until_closed() def _setup_logging(self): logfile = os.path.join( os.environ['WINDIR'], 'system32', 'LogFiles', self._svc_display_name_, 'events.log', ) handler = jaraco.logging.TimestampFileHandler(logfile) handlerFormat = '[%(asctime)s] - %(levelname)s - [%(name)s] %(message)s' handler.setFormatter(logging.Formatter(handlerFormat)) logging.root.addHandler(handler) # Redirect stdout and stderr, else when the stdio flushes, # an exception will be thrown and the service will bail sys.stdout = jaraco.logging.LogFileWrapper('stdout') sys.stderr = jaraco.logging.LogFileWrapper('stderr') logging.root.level = logging.INFO @classmethod def handle_command_line(cls): win32serviceutil.HandleCommandLine(cls)
StarcoderdataPython
203607
#!/usr/bin/env python2 import os import json import unittest from partialView.partialView import PartialView, PodDescriptor class TestPartialView(unittest.TestCase): @classmethod def setUpClass(cls): pass def setUp(self): self.partialView = PartialView("172.16.31.10") self.descriptors = [] self.ips = ["192.168.127.12", "172.16.17.32", "172.16.17.32", "172.16.31.10", "192.168.3.11"] for ip in self.ips: self.descriptors.append(PodDescriptor(ip)) # Limit should be equal to VIEW_LIMIT and shuffle_length should be equal to SHUFFLE_LENGTH def test_set_up_ok(self): self.assertEqual(self.partialView.limit, int(os.environ['VIEW_LIMIT'])) self.assertEqual(self.partialView.shuffle_length, int(os.environ['SHUFFLE_LENGTH'])) # Initial partialView should be empty def test_initial_partial_view_empty(self): self.assertEqual(self.partialView.size, 0) self.assertTrue(self.partialView.is_empty()) # Method is_full should return false if partial view is not full def test_initial_partial_view_should_not_be_full(self): self.assertFalse(self.partialView.is_full()) # Method is_full should return true if partial view is full def test_is_full_should_return_true_if_full(self): for i in range(self.partialView.limit): self.partialView.add_peer(self.descriptors[i]) self.assertTrue(self.partialView.is_full()) self.assertEqual(self.partialView.size, self.partialView.limit) # Method add_peer should return false if peer already contained def test_add_peer_should_return_false_if_peer_already_contained(self): peer = PodDescriptor("A new IP") self.partialView.add_peer(peer) size = self.partialView.size duplicated = PodDescriptor("A new IP") success = self.partialView.add_peer(duplicated) self.assertFalse(success) self.assertEqual(self.partialView.size, size) self.assertEqual(self.partialView.size, len(self.partialView.peer_list)) # Method add_peer should not allow to insert a self entry def test_add_peer_should_not_allow_self_entry(self): ip = "my ip" p1 = PartialView(ip) peer = PodDescriptor(ip) size = self.partialView.size success = p1.add_peer(peer) self.assertFalse(success) self.assertFalse(p1.contains_ip(ip)) self.assertEqual(p1.size, size) # Method add_peer should allow to insert a self entry if forced def test_add_peer_with_allow_self_should_allow_self_entry(self): ip = "my ip" p1 = PartialView(ip) peer = PodDescriptor(ip) size = self.partialView.size success = p1.add_peer(peer, True) self.assertTrue(success) self.assertTrue(p1.contains_ip(ip)) self.assertEqual(p1.size, size + 1) # Method add_peer should increment size if view is not full def test_add_peer_should_increment_size_if_not_full(self): size = self.partialView.size peer = PodDescriptor("A new IP") self.partialView.add_peer(peer) self.assertTrue(self.partialView.contains(peer)) self.assertEqual(self.partialView.size, size + 1) self.assertEqual(self.partialView.size, len(self.partialView.peer_list)) # Method add_peer should not increment size if view is full def test_add_peer_should_not_increment_size_if_full(self): peer = PodDescriptor("A new IP") for i in range(self.partialView.limit): self.partialView.add_peer(self.descriptors[i]) size = self.partialView.size success = self.partialView.add_peer(peer) self.assertFalse(success) self.assertFalse(self.partialView.contains(peer)) self.assertEqual(self.partialView.size, size) self.assertEqual(self.partialView.size, len(self.partialView.peer_list)) # Method add_peer_ip should return false if peer already contained def test_add_peer_ip_should_return_false_if_peer_already_contained(self): peer = "A new IP" self.partialView.add_peer_ip(peer) size = self.partialView.size duplicated = "A new IP" success = self.partialView.add_peer_ip(duplicated) self.assertFalse(success) self.assertEqual(self.partialView.size, size) self.assertEqual(self.partialView.size, len(self.partialView.peer_list)) # Method add_peer_ip should not allow to insert a self entry def test_add_peer_ip_should_not_allow_self_entry(self): ip = "my ip" p1 = PartialView(ip) size = self.partialView.size success = p1.add_peer_ip(ip) self.assertFalse(success) self.assertFalse(p1.contains_ip(ip)) self.assertEqual(p1.size, size) # Method add_peer_ip should allow to insert a self entry if forced def test_add_peer_ip_with_allow_self_should_allow_self_entry(self): ip = "my ip" p1 = PartialView(ip) size = self.partialView.size success = p1.add_peer_ip(ip, True) self.assertTrue(success) self.assertTrue(p1.contains_ip(ip)) self.assertEqual(p1.size, size + 1) # Method add_peer_ip should increment size if view is not full def test_add_peer_ip_should_increment_size_if_not_full(self): size = self.partialView.size peer = "A new IP" self.partialView.add_peer_ip(peer) self.assertTrue(self.partialView.contains_ip(peer)) self.assertEqual(self.partialView.size, size + 1) self.assertEqual(self.partialView.size, len(self.partialView.peer_list)) # Method add_peer_ip should not increment size if view is full def test_add_peer_ip_should_not_increment_size_if_full(self): peer = "A new IP" for i in range(self.partialView.limit): self.partialView.add_peer(self.descriptors[i]) size = self.partialView.size success = self.partialView.add_peer_ip(peer) self.assertFalse(success) self.assertFalse(self.partialView.contains_ip(peer)) self.assertEqual(self.partialView.size, size) self.assertEqual(self.partialView.size, len(self.partialView.peer_list)) # Initial age should be zero def test_initial_age_peer(self): self.partialView.add_peer(PodDescriptor("192.168.3.11")) self.assertEqual(self.partialView.peer_list[0].age, 0) # Initial age should be zero def test_initial_age_peer_ip(self): self.partialView.add_peer_ip("192.168.3.11") self.assertEqual(self.partialView.peer_list[0].age, 0) # Method get_peer_ip_list should return a list of ips def test_get_peer_ip_list_returns_ips(self): for ip in self.ips: self.partialView.add_peer_ip(ip) self.assertEqual(self.partialView.get_peer_ip_list(), self.ips[:self.partialView.limit]) # Initial age should be zero def test_partial_view_size_limit(self): for ip in self.ips: self.partialView.add_peer_ip(ip) self.assertEqual(self.partialView.size, self.partialView.limit) self.assertTrue(self.partialView.is_full()) for i in range(self.partialView.limit): self.assertEqual(self.partialView.peer_list[i].ip, self.ips[i]) def test_contains_return_true_if_contained(self): for descr in self.descriptors: self.partialView.add_peer(descr) for descr in self.descriptors[:self.partialView.size]: self.assertTrue(self.partialView.contains(descr)) for descr in self.descriptors[self.partialView.size:]: self.assertFalse(self.partialView.contains(descr)) def test_contains_ip_return_true_if_contained(self): for ip in self.ips: self.partialView.add_peer_ip(ip) for ip in self.ips[:self.partialView.size]: self.assertTrue(self.partialView.contains_ip(ip)) for ip in self.ips[self.partialView.size:]: self.assertFalse(self.partialView.contains_ip(ip)) # Age should be incremented by one def test_increment(self): self.partialView.add_peer(PodDescriptor("192.168.3.11", 1)) self.partialView.add_peer(PodDescriptor("172.16.17.32", 3)) self.partialView.increment() self.assertEqual(self.partialView.peer_list[0].age, 2) self.assertEqual(self.partialView.peer_list[1].age, 4) # Sort should sort view by peer's age def test_sort(self): self.partialView.add_peer(PodDescriptor("192.168.3.11", 2)) self.partialView.add_peer(PodDescriptor("172.16.31.10", 3)) self.partialView.add_peer(PodDescriptor("172.16.31.10", 1)) self.partialView.sort() self.assertEqual(self.partialView.peer_list[0].ip, "172.16.31.10") self.assertEqual(self.partialView.peer_list[1].ip, "192.168.3.11") self.assertEqual(self.partialView.peer_list[2].ip, "172.16.31.10") # Method sample_descriptors should return an empty list if view is empty def test_sample_descriptors_should_return_empty_list_if_empty_view(self): sample = self.partialView.sample_descriptors(3) self.assertEqual(len(sample), 0) self.assertEqual(sample, []) self.assertTrue(isinstance(sample, list)) # Method sample_descriptors should return a list of size element if the view's size is less than the limit given as parameter def test_sample_descriptors_should_return_less_than_limit_peers_if_size_less_than_limit(self): self.partialView.add_peer(PodDescriptor("192.168.3.11", 2)) self.partialView.add_peer(PodDescriptor("172.16.31.10", 3)) size = self.partialView.size sample = self.partialView.sample_descriptors(3) self.assertEqual(len(sample), size) # Method sample_descriptors should return a list of limit peers despite the size of the the view is greater then limit def test_sample_descriptors_should_return_no_more_than_limit_peers(self): self.partialView.add_peer(PodDescriptor("192.168.3.11", 2)) self.partialView.add_peer(PodDescriptor("172.16.31.10", 3)) self.partialView.add_peer(PodDescriptor("172.16.17.32", 4)) limit = 2 size = self.partialView.size sample = self.partialView.sample_descriptors(limit) self.assertNotEqual(limit, size) self.assertEqual(len(sample), limit) # Method sample_descriptors should return a list of 1 peer and avoid the peer given as parameter def test_sample_descriptors_with_avoid_peer_more_than_limit(self): to_avoid = PodDescriptor("172.16.17.32", 4) self.partialView.add_peer(PodDescriptor("192.168.3.11", 2)) self.partialView.add_peer(PodDescriptor("172.16.31.10", 3)) self.partialView.add_peer(to_avoid) limit = 1 sample = self.partialView.sample_descriptors(limit, to_avoid) self.assertEqual(len(sample), limit) self.assertFalse(to_avoid in sample) # Method sample_descriptors should return a list of 2 peers and avoid the peer given as parameter def test_sample_descriptors_with_avoid_peer_less_than_limit(self): to_avoid = PodDescriptor("172.16.17.32", 4) self.partialView.add_peer(PodDescriptor("192.168.3.11", 2)) self.partialView.add_peer(PodDescriptor("172.16.31.10", 3)) self.partialView.add_peer(to_avoid) limit = 3 sample = self.partialView.sample_descriptors(limit, to_avoid) self.assertEqual(len(sample), 2) self.assertFalse(to_avoid in sample) # Method sample_descriptors should return a list of 3 peers if the peer to avoid is not contained in the view def test_sample_descriptors_with_avoid_peer_not_in_view(self): to_avoid = PodDescriptor("172.16.17.32", 4) self.partialView.add_peer(PodDescriptor("192.168.3.11", 2)) self.partialView.add_peer(PodDescriptor("172.16.31.10", 3)) self.partialView.add_peer(PodDescriptor("172.16.31.10", 8)) limit = 3 sample = self.partialView.sample_descriptors(limit, to_avoid) self.assertEqual(len(sample), limit) self.assertFalse(to_avoid in sample) # Method sample_ips should return a list of 3 ips def test_sample_ips_should_return_a_list_of_ips(self): self.partialView.add_peer(PodDescriptor("192.168.3.11", 2)) self.partialView.add_peer(PodDescriptor("172.16.31.10", 3)) self.partialView.add_peer(PodDescriptor("172.16.31.10", 8)) limit = 3 sample = self.partialView.sample_ips(limit) self.assertIn("192.168.3.11", sample) self.assertIn("172.16.31.10", sample) self.assertIn("172.16.31.10", sample) # Method sample_ips should return a list of 3 ips loadable by epto # def test_sample_ips_should_return_a_list_of_ips_loadable_by_epto(self): # self.partialView.add_peer(PodDescriptor("192.168.3.11", 2)) # self.partialView.add_peer(PodDescriptor("172.16.31.10", 3)) # self.partialView.add_peer(PodDescriptor("172.16.31.10", 8)) # sample = json.dumps(self.partialView.sample_ips(2)) # # EpTO's code when EpTO invokes get_k_view() # view = [ip.encode('ascii', 'ignore') for ip in json.loads(sample)] # for destination in view: # self.assertIsInstance(destination, str) # self.assertIn(destination, self.partialView.get_peer_ip_list()) # Test the exchange of views. # P1 plays the role of P while P2 plays the role of Q described in comments def test_exchange_views(self): p1 = PartialView("First IP", 4, 3) p1.add_peer(PodDescriptor("192.168.3.11", 0)) p1.add_peer(PodDescriptor("172.16.17.32", 2)) p1.add_peer(PodDescriptor("192.168.3.11", 3)) p1.add_peer(PodDescriptor("Second IP", 5)) p2 = PartialView("Second IP", 4, 3) p2.add_peer(PodDescriptor("172.16.17.32", 0)) p2.add_peer(PodDescriptor("192.168.3.11", 1)) p2.add_peer(PodDescriptor("172.16.17.32", 2)) p2.add_peer(PodDescriptor("192.168.127.12", 4)) ######################## # P1 starts the exchange ######################## # 1) Increase by one the age of all neighbors p1.increment() # 2) Select neighbor Q with the highest age among all neighbors. oldest = p1.get_oldest_peer() # 3) Select l - 1 other random neighbors (meaning avoid oldest). request = p1.select_neighbors_for_request(oldest) # 4) Replace Q's entry with a new entry of age 0 and with P's address. request.add_peer_ip(p1.ip, allow_self_ip=True) self.assertTrue(request.is_full()) self.assertEqual(request.size, p1.shuffle_length) ################################################ # P2 receives neighbors and prepares a reply ################################################ reply = p2.select_neighbors_for_reply() self.assertTrue(request.is_full()) self.assertEqual(request.size, p1.shuffle_length) # Note that in p1 the oldest is p2 # p1 and p2 know two peers in common # p2 does not have an entry with p1's ip # p1.merge should: # - Discard 172.16.17.32 and 192.168.3.11 # - Put in unknown list 172.16.17.32, 192.168.127.12 # 6) I remove the oldest peer from my view p1.remove_peer(oldest) p1.merge(request, reply) self.assertTrue(p1.is_full()) for peer in reply.get_peer_list(): self.assertTrue(p1.contains(peer)) self.assertLessEqual(self.partialView.size, self.partialView.limit) # Test the exchange of views. # P1 plays the role of P while P2 plays the role of Q described in comments # def test_exchange_views_2(self): # # p1 = PartialView("First IP", 4, 3) # p1.add_peer(PodDescriptor("192.168.3.11", 0)) # p1.add_peer(PodDescriptor("172.16.17.32", 2)) # p1.add_peer(PodDescriptor("192.168.3.11", 3)) # p1.add_peer(PodDescriptor("Second IP", 5)) # # p2 = PartialView("Second IP", 4, 3) # p2.add_peer(PodDescriptor("172.16.17.32", 0)) # p2.add_peer(PodDescriptor("192.168.3.11", 1)) # p2.add_peer(PodDescriptor("172.16.17.32", 2)) # p2.add_peer(PodDescriptor("First IP", 4)) # # ######################## # # P1 starts the exchange # ######################## # # # 1) Increase by one the age of all neighbors # p1.increment() # # 2) Select neighbor Q with the highest age among all neighbors. # oldest = p1.get_oldest_peer() # # 3) Select l - 1 other random neighbors (meaning avoid oldest). # request = p1.select_neighbors_for_request(oldest) # # 4) Replace Q's entry with a new entry of age 0 and with P's address. # request.add_peer_ip(p1.ip, allow_self_ip=True) # # self.assertTrue(request.is_full()) # self.assertEqual(request.size, p1.shuffle_length) # # ################################################ # # P2 receives neighbors and prepares a reply # ################################################ # # reply = p2.select_neighbors_for_reply() # # self.assertTrue(request.is_full()) # self.assertEqual(request.size, p1.shuffle_length) # # # Note that in p1 the oldest is p2 # # p1 and p2 know two peers in common # # p2 does have an entry with p1's ip # # p1.merge should: # # - Discard 172.16.17.32 and 192.168.3.11 because are well known # # - Discard First IP because self ip is not allowed # # # 6) I remove the oldest peer from my view # p1.remove_peer(oldest) # p1.merge(request, reply) # # for peer in reply.get_peer_list(): # if peer != p1.ip: # self.assertTrue(p1.contains(peer)) # # self.assertLessEqual(self.partialView.size, self.partialView.limit) # Method get_oldest_peer should return a PodDescriptor def test_get_oldest_peer_should_return_none_if_empty_view(self): oldest = self.partialView.get_oldest_peer() self.assertEqual(oldest, None) # Method get_oldest_peer should return a PodDescriptor def test_get_oldest_peer_should_return_a_pod_descriptor(self): self.partialView.add_peer(PodDescriptor("192.168.3.11", 2)) self.partialView.add_peer(PodDescriptor("172.16.31.10", 1)) self.partialView.add_peer(PodDescriptor("192.168.3.11", 4)) oldest = self.partialView.get_oldest_peer() self.assertTrue(isinstance(oldest, PodDescriptor)) # Method get_oldest_peer should return the peer with the highest age def test_get_oldest_peer(self): self.partialView.add_peer(PodDescriptor("192.168.3.11", 2)) self.partialView.add_peer(PodDescriptor("172.16.31.10", 1)) self.partialView.add_peer(PodDescriptor("192.168.3.11", 4)) oldest = self.partialView.get_oldest_peer() self.assertEqual(oldest.ip, "192.168.3.11") self.assertEqual(oldest.age, 4) def test_select_neighbors_for_request_should_return_a_non_full_view(self): oldest = PodDescriptor("172.16.31.10", 1) self.partialView.add_peer(PodDescriptor("192.168.3.11", 2)) self.partialView.add_peer(oldest) self.partialView.add_peer(PodDescriptor("192.168.3.11", 4)) neighbors = self.partialView.select_neighbors_for_request(oldest) self.assertFalse(neighbors.is_full()) self.assertEqual(neighbors.size, neighbors.shuffle_length - 1) def test_select_neighbors_for_request_should_not_contain_oldest_peer(self): oldest = PodDescriptor("172.16.31.10", 1) self.partialView.add_peer(PodDescriptor("192.168.3.11", 2)) self.partialView.add_peer(oldest) self.partialView.add_peer(PodDescriptor("192.168.3.11", 4)) neighbors = self.partialView.select_neighbors_for_request(oldest) self.assertFalse(neighbors.contains(oldest)) def test_select_neighbors_for_request_and_add_peer_should_return_full_view(self): oldest = PodDescriptor("172.16.31.10", 1) self.partialView.add_peer(PodDescriptor("192.168.3.11", 2)) self.partialView.add_peer(oldest) self.partialView.add_peer(PodDescriptor("192.168.3.11", 4)) neighbors = self.partialView.select_neighbors_for_request(oldest) neighbors.add_peer_ip(self.partialView.ip, allow_self_ip=True) self.assertEqual(neighbors.size, self.partialView.shuffle_length) self.assertTrue(neighbors.is_full()) def test_select_neighbors_for_reply_should_return_a_full_view(self): oldest = PodDescriptor("172.16.31.10", 1) self.partialView.add_peer(PodDescriptor("192.168.3.11", 2)) self.partialView.add_peer(oldest) self.partialView.add_peer(PodDescriptor("192.168.3.11", 4)) neighbors = self.partialView.select_neighbors_for_reply(oldest) self.assertTrue(neighbors.is_full()) self.assertEqual(neighbors.size, neighbors.shuffle_length) def test_select_neighbors_for_reply_should_contain_avoid_peer_if_size_eq_shuffle_length(self): oldest = PodDescriptor("172.16.31.10", 1) self.partialView.add_peer(PodDescriptor("192.168.3.11", 2)) self.partialView.add_peer(oldest) neighbors = self.partialView.select_neighbors_for_reply(oldest) self.assertTrue(neighbors.is_full()) self.assertEqual(neighbors.size, neighbors.shuffle_length) def test_select_neighbors_for_reply_should_not_contain_oldest_peer(self): oldest = PodDescriptor("172.16.31.10", 1) self.partialView.add_peer(PodDescriptor("192.168.3.11", 2)) self.partialView.add_peer(oldest) self.partialView.add_peer(PodDescriptor("192.168.3.11", 4)) neighbors = self.partialView.select_neighbors_for_reply(oldest) self.assertFalse(neighbors.contains(oldest)) def test_empty_partial_view_to_json(self): jsonized = self.partialView.to_json() self.assertEqual(jsonized, {"ip": "172.16.31.10", "limit": 3, "shuffle_length": 2, "peer_list": [], "size": 0}) def test_unmarshal_partial_view(self): for ip in self.ips: self.partialView.add_peer_ip(ip) jsonized = self.partialView.to_json() partial_view = PartialView.from_dict(jsonized) self.assertIsInstance(partial_view, PartialView) for peer in partial_view.peer_list: self.assertIsInstance(peer, PodDescriptor) self.assertEqual(partial_view.ip, self.partialView.ip) self.assertEqual(partial_view.size, 3) self.assertEqual(partial_view.limit, 3) for i in range(self.partialView.limit): self.assertEqual(partial_view.peer_list[i].ip, self.descriptors[i].ip) self.assertEqual(partial_view.peer_list[i].age, self.descriptors[i].age) # Every time the view size is checked if it is equal to the actual size def tearDown(self): self.assertEqual(len(self.partialView.peer_list), self.partialView.size) if __name__ == '__main__': unittest.main()
StarcoderdataPython
65207
#------------------------------------------------------------------------- # Copyright (c) Microsoft. 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 base64 import hashlib import hmac import sys from ._common_models import ( _unicode_type, ) if sys.version_info < (3,): def _str(value): if isinstance(value, unicode): return value.encode('utf-8') return str(value) else: _str = str def _str_or_none(value): if value is None: return None return _str(value) def _int_or_none(value): if value is None: return None return str(int(value)) def _bool_or_none(value): if value is None: return None if isinstance(value, bool): if value: return 'true' else: return 'false' return str(value) def _encode_base64(data): if isinstance(data, _unicode_type): data = data.encode('utf-8') encoded = base64.b64encode(data) return encoded.decode('utf-8') def _decode_base64_to_bytes(data): if isinstance(data, _unicode_type): data = data.encode('utf-8') return base64.b64decode(data) def _decode_base64_to_text(data): decoded_bytes = _decode_base64_to_bytes(data) return decoded_bytes.decode('utf-8') def _sign_string(key, string_to_sign, key_is_base64=True): if key_is_base64: key = _decode_base64_to_bytes(key) else: if isinstance(key, _unicode_type): key = key.encode('utf-8') if isinstance(string_to_sign, _unicode_type): string_to_sign = string_to_sign.encode('utf-8') signed_hmac_sha256 = hmac.HMAC(key, string_to_sign, hashlib.sha256) digest = signed_hmac_sha256.digest() encoded_digest = _encode_base64(digest) return encoded_digest def _lower(text): return text.lower()
StarcoderdataPython
4893959
import os import cv2 as cv import mediapipe as mp from ILib.utils import makeFolder, collect_image_files class AutoAligner(): def __init__(self): self.mp_drawing = mp.solutions.drawing_utils self.mp_pose = mp.solutions.pose self.mp_holistic = mp.solutions.holistic self.mp_face_detection = mp.solutions.face_detection def align_image(self, img, min_face_detection_confidence = 0.5, min_pose_detection_confidence = 0.5): """ :param img: image to align :param min_face_detection_confidence: confidence for face detection in the image :param min_pose_detection_confidence: confidence for pose detection in the image :return: aligned image """ with self.mp_pose.Pose(static_image_mode=True, model_complexity=2, min_detection_confidence=min_pose_detection_confidence) as pose: image = img image_height, image_width, _ = image.shape results = pose.process(cv.cvtColor(image, cv.COLOR_BGR2RGB)) if not results.pose_landmarks: i = 0 while(True): mp_face_detection = self.mp_face_detection with mp_face_detection.FaceDetection(model_selection=1, min_detection_confidence=min_face_detection_confidence) as face_detection: if i == 4: return image results2 = face_detection.process(cv.cvtColor(image, cv.COLOR_BGR2RGB)) if not results2.detections: i+=1 image = cv.rotate(image, rotateCode = 0) continue return image n = results.pose_landmarks.landmark[self.mp_holistic.PoseLandmark.NOSE].y r = results.pose_landmarks.landmark[self.mp_holistic.PoseLandmark.RIGHT_SHOULDER].y l = results.pose_landmarks.landmark[self.mp_holistic.PoseLandmark.LEFT_SHOULDER].y if n<r and n<l: pass elif n>r and n>l: image = cv.rotate(image, rotateCode = 1) elif n<r and n>l: image = cv.rotate(image, rotateCode = 0) else: image = cv.rotate(image, rotateCode = 2) return image def auto_align(input_file, output_file, min_face_detection_confidence = 0.5, min_pose_detection_confidence = 0.5): """ :param input_file: file containing images :param output_file: file to store aligned images :param min_face_detection_confidence: confidence for face detection in the image :param min_pose_detection_confidence: confidence for pose detection in the image """ images = collect_image_files(input_file) # makeFolder(output_file) path = output_file mp_drawing = mp.solutions.drawing_utils mp_pose = mp.solutions.pose mp_holistic = mp.solutions.holistic with mp_pose.Pose(static_image_mode=True, model_complexity=2, min_detection_confidence=min_pose_detection_confidence) as pose: for idx, file in enumerate(images): image = cv.imread(input_file + "\\" + file) filename, file_ext = os.path.splitext(images[idx]) image_height, image_width, _ = image.shape results = pose.process(cv.cvtColor(image, cv.COLOR_BGR2RGB)) if not results.pose_landmarks: i = 0 while(True): mp_face_detection = mp.solutions.face_detection with mp_face_detection.FaceDetection(model_selection=1, min_detection_confidence=min_face_detection_confidence) as face_detection: if i == 4: try: cv.imwrite(path + '\\' + filename + file_ext, image) except: cv.imwrite(path + '\\' + filename + ".png", image) break results2 = face_detection.process(cv.cvtColor(image, cv.COLOR_BGR2RGB)) if not results2.detections: i+=1 image = cv.rotate(image,rotateCode = 0) continue try: cv.imwrite(path + '\\' + filename + file_ext, image) except: cv.imwrite(path + '\\' + filename + ".png", image) break continue n = results.pose_landmarks.landmark[mp_holistic.PoseLandmark.NOSE].y r = results.pose_landmarks.landmark[mp_holistic.PoseLandmark.RIGHT_SHOULDER].y l = results.pose_landmarks.landmark[mp_holistic.PoseLandmark.LEFT_SHOULDER].y if n<r and n<l: pass elif n>r and n>l: image = cv.rotate(image,rotateCode = 1) elif n<r and n>l: image = cv.rotate(image,rotateCode = 0) else: image = cv.rotate(image,rotateCode = 2) try: cv.imwrite(path + '\\' + filename + file_ext, image) except: cv.imwrite(path + '\\' + filename + ".png", image)
StarcoderdataPython
187133
<filename>digsby/src/msn/p12/__init__.py<gh_stars>10-100 from MSNP12Switchboard import MSNP12Switchboard as Switchboard from MSNP12Notification import MSNP12Notification as Notification
StarcoderdataPython
110169
import ujson from dataclasses import dataclass, asdict @dataclass class BaseModelMixin: @property def as_json_string(self): return ujson.dumps(asdict(self)) @classmethod def from_json(cls, jstr): if not jstr: return None d = ujson.loads(jstr) return cls(**d)
StarcoderdataPython
254036
<gh_stars>0 from datetime import datetime nascimento = int(input('Insira seu ano de nascimento: ')) idade = datetime.today().year - nascimento if idade < 18: print('Você ainda vai se alistar') tempo = 18 - idade print(f'Falta {tempo} anos para você se alistar') elif idade == 18: print('Está na hora de você se alistar') else: print('Já passou da hora de se alistar') tempo = idade - 18 print(f'Já passou {tempo} desde que vc se alistou')
StarcoderdataPython
11222655
from flask import Flask, request, render_template import tweepy from textblob import TextBlob import plotly.plotly as py import plotly.graph_objs as go import plotly plotly.tools.set_credentials_file(username='lastps', api_key='cB0kWozoTEjQDZJpCUhP') def Gauge_Printer(): base_chart = { "values": [40, 10, 10, 10, 10, 10, 10], "labels": ["-", "0", "20", "40", "60", "80", "100"], "domain": {"x": [0, .48]}, "marker": { "colors": [ 'rgb(255, 255, 255)', 'rgb(255, 255, 255)', 'rgb(255, 255, 255)', 'rgb(255, 255, 255)', 'rgb(255, 255, 255)', 'rgb(255, 255, 255)', 'rgb(255, 255, 255)' ], "line": { "width": 1 } }, "name": "Gauge", "hole": .4, "type": "pie", "direction": "clockwise", "rotation": 108, "showlegend": False, "hoverinfo": "none", "textinfo": "label", "textposition": "outside" } meter_chart = { "values": [50, 10, 10, 10, 10, 10], "labels": ["BS Level", "Minimal", "A Tad", "Skeptical", "A lot", "BULLS***"], "marker": { 'colors': [ 'rgb(255, 255, 255)', 'rgb(240,248,255)', 'rgb(176,224,230)', 'rgb(0,191,255)', 'rgb(30,144,255)', 'rgb(0,0,128)' ] }, "domain": {"x": [0, 0.48]}, "name": "Gauge", "hole": .3, "type": "pie", "direction": "clockwise", "rotation": 90, "showlegend": False, "textinfo": "label", "textposition": "inside", "hoverinfo": "none" } layout = { 'xaxis': { 'showticklabels': False, 'autotick': False, 'showgrid': False, 'zeroline': False, }, 'yaxis': { 'showticklabels': False, 'autotick': False, 'showgrid': False, 'zeroline': False, }, 'shapes': [ { 'type': 'path', 'path': 'M 0.235 0.5 L 0.24 0.65 L 0.245 0.5 Z', 'fillcolor': 'rgba(44, 160, 101, 0.5)', 'line': { 'width': 0.5 }, 'xref': 'paper', 'yref': 'paper' } ], 'annotations': [ { 'xref': 'paper', 'yref': 'paper', 'x': 0.23, 'y': 0.45, 'text': '50', 'showarrow': False } ] } # we don't want the boundary now base_chart['marker']['line']['width'] = 0 fig = {"data": [base_chart, meter_chart], "layout": layout} py.iplot(fig, filename='gauge-meter-chart') app = Flask(__name__, static_url_path='/static') @app.route("/", methods=['GET', 'POST']) def hello(): if request.method == 'POST': search = request.form['search_query'] if not search: return render_template('index.html') consumer_key = "8ncrufW2yEegl2KcjI8EwPBbM" consumer_secret = "<KEY>" access_token = "<KEY>" access_token_secret = "<KEY>" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) tweets_not_subjective = [] tweets_subjective = [] tweets_positive = [] tweets_negative = [] overall_sentiment = "" overall_subjectivity = "" sentiment_array = [] subjectivity_array = [] count1, count2, counter_positive, counter_negative, counter_subjective, counter_objective = 0, 0, 0, 0, 0, 0 search_term = "" tweets_public = api.search(q=search, count=100, lang ="en") for tweets in tweets_public: # print(tweets.text) # print(tweets.created_at) sent = TextBlob(tweets.text) # print(sent.sentiment) sentiment_array.append(sent.sentiment.polarity) subjectivity_array.append(sent.sentiment.subjectivity) if sent.sentiment.subjectivity < 0.5 and counter_objective <= 5: tweets_not_subjective.append(tweets) counter_objective += 1 elif sent.sentiment.subjectivity > 0.5 and counter_subjective <= 5: tweets_subjective.append(tweets) counter_subjective += 1 if sent.sentiment.polarity > 0.0 and counter_positive <= 5: tweets_positive.append(tweets) counter_positive += 1 elif sent.sentiment.polarity < 0.0 and counter_positive <= 5: tweets_negative.append(tweets) counter_negative += 1 count1 += sent.sentiment.subjectivity count2 += sent.sentiment.polarity average1 = count1 / 100.0 average2 = count2 / 100.0 if average1 > 0.5: overall_sentiment = "a lot of " elif average1 <0.5: overall_sentiment = "minimal" elif average1 == 0.5: overall_sentiment = "a bit of" if average2 > 0: overall_sentiment = "negatively" elif average2 <0: overall_sentiment = "positively" elif average2 == 0: overall_sentiment = "neutral" trace0 = go.Scatter( x=sentiment_array, y=subjectivity_array, mode='markers', name='markers' ) layout = go.Layout( title='', xaxis=dict( title='Positivity', titlefont=dict( family='Courier New, monospace', size=18, color='#7f7f7f' ) ), yaxis=dict( title='Subjectivity', titlefont=dict( family='Courier New, monospace', size=18, color='#7f7f7f' ) ) ) # trace1 = go.Scatter( # k = [0], # f = [0.3] # ) data = [trace0] # Plot and embed in ipython notebook! fig = go.Figure(data=data, layout=layout) py.plot(fig, filename='', auto_open=False) #### Gauge_Printer() return render_template('index.html', tweets_plus=tweets_positive, tweets_minus=tweets_negative, tweets_fact=tweets_not_subjective, tweets_unfact=tweets_subjective, sub_overall=overall_subjectivity, sent_overall=overall_sentiment) return render_template('index.html') if __name__ == "__main__": app.run(debug=True)
StarcoderdataPython
3358200
from sqlalchemy import Boolean, Column, String from models.base import Base class User(Base): __tablename__ = "users" email = Column(String, unique=True, index=True, nullable=False) password = Column(String, nullable=False) active = Column(Boolean, nullable=False, default=True)
StarcoderdataPython
11311720
""" Tests for the basic functions in tedopa/tmps.py To check if the whole time evolution works (i.e. the more advanced functions orchestrating the basic functions) see test_tmps_for_transverse_ising_model.py """ import pytest as pt import numpy as np from numpy.testing import assert_array_almost_equal from tedopa import tmps @pt.mark.parametrize('subsystems, len_step_numbers', [([0, 1], 4), ([[0, 1], [2, 3], [4, 8]], 3)]) def test_get_subsystems_list(subsystems, len_step_numbers): subsystems = tmps._get_subsystems_list(subsystems, len_step_numbers) assert len(subsystems) == len_step_numbers @pt.mark.parametrize('matrix, mpo_shape', [(np.array([[0, 1], [1, 0]]), [[2, 2]]), (np.array([[3, 5, 4], [6, 8, 3]]), [[1, 2], [3, 1]])]) def test_matrix_to_mpo(matrix, mpo_shape): assert_array_almost_equal( matrix, tmps.matrix_to_mpo(matrix, mpo_shape).to_array_global().reshape( matrix.shape))
StarcoderdataPython
12783
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Taskmaster-2 implementation for ParlAI. No official train/valid/test splits are available as of 2020-05-18, so we make our own splits. """ import os import pandas as pd import hashlib from collections import Counter from parlai.core.opt import Opt from parlai.core.teachers import DialogTeacher from parlai.core.metrics import AverageMetric, F1Metric, BleuMetric from parlai.utils.misc import warn_once import json import parlai.utils.logging as logging from typing import Optional, Tuple from parlai.core.message import Message from parlai.utils.io import PathManager import parlai.tasks.taskmaster2.build as build_ DOMAINS = [ 'flights', 'food-ordering', 'hotels', 'movies', 'restaurant-search', 'sports', 'music', ] ONTO_TOKEN = "Onto:" CALL_TOKEN = "Call:" RESP_TOKEN = "Result:" class _Abstract(DialogTeacher): """ Abstract data loader. """ @classmethod def add_cmdline_args(cls, argparser): argparser.add_argument('--include-ontology', type=bool, default=False) argparser.add_argument( '--domains', nargs='+', default=DOMAINS, choices=DOMAINS, help='Uses last passed in configuration.', ) return argparser def __init__(self, opt: Opt, shared=None): self.fold = opt['datatype'].split(':')[0] opt['datafile'] = self.fold self.dpath = os.path.join(opt['datapath'], 'taskmaster-2') if shared is None: warn_once( "Taskmaster2 is a beta dataset, and format may significantly change." ) build_.build(opt) super().__init__(opt, shared) def _h(self, x): """ Hash function. """ h = int(hashlib.sha1(x.encode('utf-8')).hexdigest(), 16) % 10 if h == 0: return 'valid' elif h == 1: return 'test' else: return 'train' def _normalize_annotation(self, anno): return anno def _load_data(self, fold, domains): # load up the ontology ontology = {} for section in domains: parts = [] fn = os.path.join(self.dpath, section + '.onto.json') with PathManager.open(fn, 'r') as f: o = json.load(f) assert len(o) == 1 o = list(o.values())[0] for sub in o: prefix = sub['prefix'] parts += [ self._normalize_annotation(f'{prefix}.{a}') for a in sub['annotations'] ] ontology[section] = ' ; '.join(parts) chunks = [] for section in domains: with PathManager.open(os.path.join(self.dpath, section + '.json')) as f: subset = pd.read_json(f) subset['domain'] = section chunks.append(subset) chunks = pd.concat(chunks, axis=0) # shuffle deterministically for randomness in few-shot training chunks = chunks.sample(frac=1.0, random_state=42) chunks['fold'] = self._label_fold(chunks) # only the fold we need here chunks = chunks[chunks.fold == fold].reset_index() chunks['ontology'] = chunks['domain'].apply(ontology.get) return chunks def _segments2text(self, segments): output = [] slots = {} for segment in segments: val = segment['text'] for anno_ in segment['annotations']: anno = anno_['name'] anno = self._normalize_annotation(anno) output.append(f'{anno} = {val}') slots[anno] = val return " ; ".join(output), slots def custom_evaluation( self, teacher_action: Message, labels: Optional[Tuple[str]], model_response: Message, ): if 'metrics' in model_response and 'type' in teacher_action: # keep copies of metrics across both api calls/responses prefix = teacher_action['type'] keys = list(model_response['metrics'].keys()) for k in keys: self.metrics.add(f'{prefix}_{k}', model_response['metrics'][k]) if 'text' not in model_response or not labels or 'type' not in teacher_action: return domain = teacher_action['domain'] if teacher_action['type'] == 'apicall': # also count slot accuracy text = model_response['text'] slot_guesses = set( text.replace(CALL_TOKEN + " ", "").split(' ; ') ) # prevent cheating via repeated guesses correct = 0 for slot_guess in slot_guesses: if ' = ' not in slot_guess: continue try: slot, guess = slot_guess.split(' = ') except ValueError: continue if teacher_action['slots'].get(slot) == guess: self.metrics.add('slot_p', AverageMetric(1)) self.metrics.add(f'{domain}_slot_p', AverageMetric(1)) correct += 1 else: self.metrics.add('slot_p', AverageMetric(0)) self.metrics.add(f'{domain}_slot_p', AverageMetric(0)) logging.debug( f"Bad slot guess '{slot_guess}' != {teacher_action['slots']}" ) if teacher_action['slots']: self.metrics.add( 'slot_r', AverageMetric(correct, len(teacher_action['slots'])) ) self.metrics.add( f'{domain}_slot_r', AverageMetric(correct, len(teacher_action['slots'])), ) self.metrics.add( 'jga', AverageMetric(correct == len(teacher_action['slots'])) ) elif teacher_action['type'] == 'apiresp': # keep track of statistics by domain f1_metric = F1Metric.compute(model_response['text'], labels) bleu_metric = BleuMetric.compute(model_response['text'], labels) self.metrics.add(f'{domain}_lex_f1', f1_metric) self.metrics.add(f'{domain}_lex_bleu', bleu_metric) delex_text = model_response['text'] delex_label = labels[0] # compute delexicalized string metrics for slot, value in teacher_action['slots'].items(): delex_text = delex_text.replace(value, slot) delex_label = delex_label.replace(value, slot) f1_metric = F1Metric.compute(delex_text, (delex_label,)) self.metrics.add('delex_f1', f1_metric) self.metrics.add(f'{domain}_delex_f1', f1_metric) bleu_metric = BleuMetric.compute(delex_text, [delex_label]) self.metrics.add('delex_bleu', bleu_metric) self.metrics.add(f'{domain}_delex_bleu', bleu_metric) def setup_data(self, fold): domains = self.opt.get('domains', DOMAINS) chunks = self._load_data(fold, domains) domains_cnt = Counter() for _, row in chunks.iterrows(): domains_cnt[row['domain']] += 1 first = True utterances = row['utterances'][:] if ( len(utterances) >= 3 and utterances[0]['speaker'] == 'USER' and utterances[1]['speaker'] == 'ASSISTANT' and utterances[2]['speaker'] == 'ASSISTANT' and "help you?" in utterances[1]['text'] ): # skip this one utterances.pop(1) if self.opt['include_ontology']: yield {'text': f"{ONTO_TOKEN} {row['ontology']}", 'label': ''}, True first = False while utterances: utt = utterances.pop(0) segtxt, slots = self._segments2text(utt.get('segments', [])) if utt['speaker'] == 'USER': yield { 'text': utt['text'], 'label': f'{CALL_TOKEN} {segtxt}', 'domain': row['domain'], 'slots': slots, 'type': 'apicall', }, first first = False elif utt['speaker'] == 'ASSISTANT': yield { 'text': f'{RESP_TOKEN} {segtxt}', 'label': utt['text'], 'domain': row['domain'], 'slots': slots, 'type': 'apiresp', }, first first = False logging.debug(f"Fold {fold} domains: {domains_cnt}") class DelexTeacher(_Abstract): def _label_fold(self, chunks): return chunks.conversation_id.apply(self._h) def _delexicalize(self, text, slots): for key, value in slots.items(): text = text.replace(value, key) return text def setup_data(self, fold): domains_cnt = Counter() chunks = self._load_data(fold) for _, row in chunks.iterrows(): domains_cnt[row['domain']] += 1 first = True utterances = row['utterances'][:] if ( len(utterances) >= 3 and utterances[0]['speaker'] == 'USER' and utterances[1]['speaker'] == 'ASSISTANT' and utterances[2]['speaker'] == 'ASSISTANT' and "help you?" in utterances[1]['text'] ): # skip this one utterances.pop(1) user_utterances = [] asst_utterances = [] while utterances: utt = utterances.pop(0) _, slots = self._segments2text(utt.get('segments', [])) if utt['speaker'] == 'USER': if asst_utterances: yield { 'text': ' __BREAK__ '.join(user_utterances), 'label': ' __BREAK__ '.join(asst_utterances), 'domain': row['domain'], }, first first = False user_utterances = [] asst_utterances = [] user_utterances.append(self._delexicalize(utt['text'], slots)) elif utt['speaker'] == 'ASSISTANT': asst_utterances.append(self._delexicalize(utt['text'], slots)) if not user_utterances: user_utterances.append('__SILENCE__') if asst_utterances: yield { 'text': ' __BREAK__ '.join(user_utterances), 'label': ' __BREAK__ '.join(asst_utterances), 'domain': row['domain'], }, first class TextOnlyTeacher(DelexTeacher): def _delexicalize(self, text, slots): return text class FullShotTeacher(_Abstract): """ The full shot teacher uses a standard 80-10-10 split, without regarding domain. """ def _label_fold(self, chunks): return chunks.conversation_id.apply(self._h) class FewShotTeacher(_Abstract): """ Few shot teacher tests for generalization to new domains. """ @classmethod def add_cmdline_args(cls, argparser): argparser.add_argument( '--holdout', default=DOMAINS[0], choices=DOMAINS, help='Domain which is held out from test', ) argparser.add_argument( '--n-shot', default=100, type=int, help='Number of few shot examples to provide in training fold.', ) return super().add_cmdline_args(argparser) def _label_fold(self, chunks): folds = [] num_shots = 0 for _, row in chunks.iterrows(): if row['domain'] != self.opt['holdout']: # if it's not in the holdout, always mark it train folds.append('train') else: # keep the same valid/test sets as in fullshot, and only leak # a small number of the training examples (i.e. throw away the # vast majority of our data but keep test sets the same) f = self._h(row['conversation_id']) if f != 'train': folds.append(f) elif num_shots < self.opt['n_shot']: folds.append('train') num_shots += 1 else: folds.append('throwaway') return folds class DefaultTeacher(FullShotTeacher): pass
StarcoderdataPython
6547092
import unittest from spacel.model.aws import INSTANCE_VOLUMES # AWS < Heinz INSTANCE_TYPE_COUNT = 54 class TestInstanceTypes(unittest.TestCase): def test_instance_volumes(self): self.assertEqual(INSTANCE_TYPE_COUNT, len(INSTANCE_VOLUMES))
StarcoderdataPython
3537625
<reponame>helinwang/pytorch-semseg import torch import argparse import numpy as np import scipy.misc as misc import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import csv from ptsemseg.models import get_model from ptsemseg.utils import convert_state_dict N_CLASSES = 151 class Classifier(nn.Module): def __init__(self): super(Classifier, self).__init__() self.fc1 = nn.Linear(900, 3) def forward(self, x): x = F.avg_pool2d(x, 8) x = x.view(-1, 900) x = self.fc1(x) return F.log_softmax(x, dim=1) def decode_segmap(temp, plot=False): r = temp.copy() g = temp.copy() b = temp.copy() for l in range(0, N_CLASSES): r[temp == l] = 10 * (l % 10) g[temp == l] = l b[temp == l] = 0 rgb = np.zeros((temp.shape[0], temp.shape[1], 3)) rgb[:, :, 0] = r / 255.0 rgb[:, :, 1] = g / 255.0 rgb[:, :, 2] = b / 255.0 if plot: plt.imshow(rgb) plt.show() else: return rgb def train_step(feature_net, classifier, optimizer, img, label, device): optimizer.zero_grad() img = img.to(device) outputs = feature_net(img) pred_raw = outputs.data.max(1)[1] feature = pred_raw.type(torch.cuda.FloatTensor) / N_CLASSES turn_logit = classifier(feature) l = torch.tensor(label).type(torch.LongTensor).to(device) loss = F.nll_loss(turn_logit, l) loss.backward() optimizer.step() print(loss.detach().cpu().numpy()) # print(label) # print(turn_logit.detach().cpu().numpy()) def eval(feature_net, classifier, img, label): outputs = feature_net(img) pred_raw = outputs.data.max(1)[1] feature = pred_raw.type(torch.FloatTensor) / N_CLASSES turn_logit = classifier(feature) print("accuracy", (turn_logit.max(1)[1] == torch.tensor(label)).sum().double() / len(label)) def read_samples(csv_path, batch_size): images = [] labels = [] with open(csv_path) as csv_file: reader = csv.DictReader(csv_file) for row in reader: img = misc.imread(row['image']) img = misc.imresize(img, (240, 240)) img = img[:, :, ::-1] img = img.astype(np.float64) img -= np.array([104.00699, 116.66877, 122.67892]) img = img.astype(float) / 255.0 # NHWC -> NCHW img = img.transpose(2, 0, 1) # img = np.expand_dims(img, 0) img = torch.from_numpy(img).float() images.append(img) labels.append(int(row['label'])) permutation = torch.randperm(len(images)) batches = [] for i in range(0, len(images), batch_size): batches.append((torch.stack(images[i:i+batch_size]), labels[i:i+batch_size])) return batches def train(args): device = torch.device("cuda") # Setup model model = get_model({"arch":"fcn8s"}, N_CLASSES, version="mit_sceneparsing_benchmark") state = convert_state_dict(torch.load(args.feature_model_path)["model_state"]) model = model.cuda() model.load_state_dict(state) model.to(device) # Setup classifier classifier = Classifier() if args.classifier_model_path is not None: classifier.load_state_dict(torch.load(args.classifier_model_path)) classifier = classifier.cuda() classifier.to(device) optimizer = optim.SGD(classifier.parameters(), lr=0.0001, momentum=True) if args.train_csv_path is not None: print("Read training csv file from : {}".format(args.train_csv_path)) train_data = read_samples(args.train_csv_path, args.batch_size) for i in range(args.num_epoch): for img, label in train_data: train_step(model, classifier, optimizer, img, label, device) torch.save(classifier.state_dict(), args.output_model_path) if args.test_csv_path is not None: classifier.eval() print("Read testing csv file from : {}".format(args.test_csv_path)) test_data = read_samples(args.test_csv_path, 999) eval(model, classifier, test_data[0][0], test_data[0][1]) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Params") parser.add_argument("--feature_model_path", nargs="?", type=str, help="Path to the saved feature model" ) parser.add_argument("--classifier_model_path", nargs="?", type=str, help="Path to the saved classifier model" ) parser.add_argument( "--output_model_path", nargs="?", type=str, default=None, help="Path to save the trained model" ) parser.add_argument( "--train_csv_path", nargs="?", type=str, default=None, help="Path of the training csv file" ) parser.add_argument( "--test_csv_path", nargs="?", type=str, default=None, help="Path of the testing csv file" ) parser.add_argument( "--batch_size", nargs="?", type=int, default=1, help="training batch size" ) parser.add_argument( "--num_epoch", nargs="?", type=int, default=1, help="number of epochs to train" ) args = parser.parse_args() train(args)
StarcoderdataPython
10438
<gh_stars>0 from setuptools import setup from nats.aio.client import __version__ EXTRAS = { 'nkeys': ['nkeys'], } setup( name='nats-py', version=__version__, description='NATS client for Python', long_description='Python client for NATS, a lightweight, high-performance cloud native messaging system', classifiers=[ 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10' ], url='https://github.com/nats-io/nats.py', author='<NAME>', author_email='<EMAIL>', license='Apache 2 License', packages=['nats', 'nats.aio', 'nats.protocol', 'nats.js'], zip_safe=True, extras_require=EXTRAS )
StarcoderdataPython
1693007
from django.urls import path from .views import show_foilaw urlpatterns = [ path("<slug:slug>/", show_foilaw, name="publicbody-foilaw-show"), ]
StarcoderdataPython
121950
# -*- coding: utf-8 -*- """ Created on Wed Oct 28 09:27:49 2020 @author: <NAME> """ import pickle import pandas as pd import numpy as np from country import country from scipy.integrate import solve_ivp from scipy.optimize import minimize from scipy.optimize import dual_annealing from scipy.optimize import brute from scipy.interpolate import interp1d from scipy.ndimage.filters import uniform_filter1d import psutil from functools import partial import multiprocessing as mp from tqdm import tqdm_notebook as tqdm import pdb from datetime import date, datetime, timedelta import time from pathlib import Path from matplotlib import pyplot as plt import statsmodels.api as sm from sklearn import linear_model import matplotlib.patches as mpatches import country_converter as coco import math import seaborn as sns # -------------------------------------------------------- # Global variables, chosen cohorts of data and estimates # -------------------------------------------------------- from param_simple import * # ---------------------- # Main class # ---------------------- class solveCovid: def __init__(self,iso2: str): # eg 'US' self.iso2 = iso2 # Policy strategies for forecast self.policy = 'optim' # ['optim', 'linear'] self.phi_option = 'fit' # ['fit','exo']: Fit phi to latest data or specify as exogenous self.phi_exo = 2.5e-9 # weight on mobility in social welfare function self.phi_min = 1e-13 # Lowerbound for phi - authorities care about output # Infection rate model for forecast self.gamma_tilde_model = 'AR1' # ['AR1','AR2','shock'] self.gamma_shock_length = 10 # Shock gamma_tilde for x days self.gamma_shock_depth = 0.5 # Daily increment of gamma self.default_init_single = default_init_single self.default_bounds_single = default_bounds_single # Vaccine assumptions self.vac_assump = 'vac_base' # Vaccination scenarios: ['vac_base','vac_worse','vac_better'] self.vac_receiver = 'S+R' # Vaccines given to S or S+R? ['S only','S+R'] self.effi_one = 0.5 # Efficacy after one dose in % self.effi_two = 0.95 # Efficacy after two doses in % self.target_weight = 0.7 # How targeted vaccine distribution is (1 = sequenced from eldest to youngest, 0 is random) self.vac_base_cover = 1 # Baseline: (already started): % of effective coverage by December 2021 (to be controlled by country-specific scaling factor below) self.vac_base_delayedstart = '2021-06-30' # Baseline: (hasn't started): first date of vaccination self.vac_base_delayedcover = 0.75 # Baseline: (hasn't started): % of contracted dosages deployed by December 2021 self.vac_worse_cover = 0.3 # Worse (started): Use by end of 2021 self.vac_worse_delayedstart = '2021-09-30' # Worse (hasn't started): Starting date self.vac_worse_delayedcover = 0.3 # Worse (hasn't started): Use by end of 2021 self.vac_better_cover = 1.3 self.vac_better_delayedstart = '2021-06-30' self.vac_better_delayedcover = 1 # Reinfection and loss of immunity self.reinfect = 'immune' # ['immune','reinfect'] self.r_re1_R = np.log(2)/10000 # Baseline: R loses immunity after 3 years self.r_re1_V = np.log(2)/10000 # Baseline: V loses immunity after 3 years self.r_re2_R = np.log(2)/60 # Downside risk: R loses immunity after 60 days, approx 1% of R lose immunity each day self.r_re2_V = np.log(2)/60 # Downside risk: V loses immunity after 60 days, approx 1% of V lose immunity each day # Death probabilities self.pdth_assump = 'martingale' # ['martingale','treatment'] self.pdth_min = 0.005 # Lowerbound on death probability - countries with very few cases still think there is death probability self.pdth_halflife = 60 # Halflife for treatment case; no. of days it takes to close half the gap of current and assumed minimum death prob self.pdth_theta = np.exp(-np.log(2)/self.pdth_halflife) # --------------- 1. Preliminary: Get the data ------------------------ def prelim(self): iso2 = self.iso2 self.N = df1.fillna(method='ffill')['population'][iso2].iloc[-1] df2 = df1.iloc[:,df1.columns.get_level_values(1)==iso2][[ 'total_cases','total_deaths','new_cases','new_deaths', 'google_smooth','icu_patients','hosp_patients','reproduction_rate', 'new_tests','tests_per_case','aged_70_older', 'vac_total','vac_people', 'vac_fully']][df1['total_cases'][iso2] > virus_thres] df2 = df2.droplevel('iso2',axis=1) df2['vac_total'] = df2['vac_total'].interpolate() df2['vac_people'] = df2['vac_people'].interpolate() if iso2 == 'AU' or iso2 == 'SA': # Countries with no breakdowns; do manual approximation df2['vac_partial'] = 0.8 * df2['vac_total'] df2['vac_fully'] = 0.2 * df2['vac_total'] else : # For most countries, date1 = df2['vac_fully'].first_valid_index() # Next 2 lines fill NA in 'vac_fully', so vac_partial is defined df2['vac_fully'].iloc[:df2.index.get_loc(date1)-1] = 0 df2['vac_fully'] = df2['vac_fully'].interpolate() df2['vac_partial'] = df2['vac_people'] - df2['vac_fully'] df2 = df2.fillna(0) # Replace NaN by 0 - deaths and vaccinations PopulationI = df2['total_cases'][0] PopulationD = df2['total_deaths'][0] if PopulationD==0: PopulationD = 0 PopulationR = 5 else: PopulationR = PopulationD * 5 PopulationCI = PopulationI - PopulationD - PopulationR # Undetected and infectious cases self.cases_data_fit = df2['total_cases'].tolist() self.deaths_data_fit = df2['total_deaths'].tolist() self.newcases_data_fit = df2['new_cases'].tolist() self.newdeaths_data_fit = df2['new_deaths'].tolist() self.balance = self.cases_data_fit[-1] / max(self.deaths_data_fit[-1], 10) / 3 date_day_since100 = pd.to_datetime(df2.index[0]) self.maxT = (default_maxT - date_day_since100).days + 1 self.mobility_vec = df2['google_smooth'].values self.T = len(df2) self.t_cases = np.arange(0,self.T) self.mobility_interp = interp1d(self.t_cases,self.mobility_vec,bounds_error=False,fill_value=0.,kind='cubic') self.GLOBAL_PARAMS = (self.N, PopulationCI, PopulationR, PopulationD, PopulationI, p_d, p_h, p_v) self.gamma_0_days = 1 # average of gamma_t during first n days becomes the target # Compute vaccination parameters self.vac_partial = df2['vac_partial'].values self.vac_fully = df2['vac_fully'].values #self.vac_contracted = 1000*df_vac.loc[iso2]['No. of people covered (thousands)']/self.N df2['V_'] = self.N * (self.effi_one*df2['vac_partial'] + self.effi_two*df2['vac_fully'])/100 # V = expected number of effectively vaccinated persons ix = pd.date_range(start=df2.index[0], end=default_maxT, freq='D') # Expand time-sample, to include forecast later df_v = df2.reindex(ix) # Vaccination assumptions if self.iso2 in ['GB','US']: vac_scale = 1 elif self.iso2 in ['BE','FR','DE','IT','NL','PL','SG','ES','CH','RO','CL','CA']: vac_scale = 0.8 elif self.iso2 in ['AU','SA','SE','TR']: vac_scale = 0.65 elif self.iso2 in ['AR','BR','MX','RU']: vac_scale = 0.50 elif self.iso2 in ['ID','IN','JP','KR','MY','TH']: vac_scale = 0.25 elif self.iso2 in ['ZA']: vac_scale = 0.10 else: vac_scale = 0.50 print('Missing vaccine assumption for selected country') if self.vac_assump == 'vac_base': if df2['V_'][-1] > 0: # already started df_v['V_'].loc['2021-12-31'] = self.vac_base_cover * vac_scale * self.N elif df2['V_'][-1] == 0: # If has not started, assume starting by xxx and cover xxx at year end df_v['V_'].loc[self.vac_base_delayedstart] = 100 # 100 = assumed number of effectively vaccinated on first day df_v['V_'].loc['2021-12-31'] = self.vac_base_delayedcover* vac_scale*self.N # partial orders filled by year end elif self.vac_assump == 'vac_worse': if df2['V_'][-1] > 0: df_v['V_'].loc['2021-12-31'] = self.vac_worse_cover * vac_scale * self.N elif df2['V_'][-1] == 0: df_v['V_'].loc[self.vac_worse_delayedstart] = 100 df_v['V_'].loc['2021-12-31'] = self.vac_worse_delayedcover* vac_scale*self.N elif self.vac_assump == 'vac_better': if df2['V_'][-1]>0: df_v['V_'].loc['2021-12-31'] = self.vac_better_cover * vac_scale * self.N elif df2['V_'][-1] == 0: df_v['V_'].loc[self.vac_better_delayedstart] = 100 df_v['V_'].loc['2021-12-31'] = self.vac_better_delayedcover* vac_scale*self.N df_v['V_'] = df_v['V_'].interpolate() df_v['V_'] = df_v['V_'].clip(0,self.N) self.df2 = df2 self.df_v = df_v print(f'Data preparation for {iso2} done') # --------------------------3 . SEIR model ------------------ def step_seir(self, t, x, gamma_t, p_dth) -> list: """ SEIR model building on DELPHI v.3 Features 16 distinct states, taking into account undetected, deaths, hospitalized and recovered [0 S, 1 E, 2 I, 3 UR, 4 DHR, 5 DQR, 6 UD, 7 DHD, 8 DQD, 9 R, 10 D, 11 TH, 12 DVR,13 DVD, 14 DD, 15 DT, 16 V] """ S, E, I, AR, DHR, DQR, AD, DHD, DQD, R, D, TH, DVR, DVD, DD, DT, V = x r_v = self.df_v['V_'].iloc[t+1] - self.df_v['V_'].iloc[t] # Reinfection parameters if self.reinfect == 'immune': r_re_R = self.r_re1_R r_re_V = self.r_re1_V elif self.reinfect == 'reinfect': if t <= self.T: r_re_R = self.r_re1_R r_re_V = self.r_re1_V else: r_re_R = self.r_re2_R r_re_V = self.r_re2_V # Vaccination recipients (S, or S+R) if self.vac_receiver == 'S only': zeta = 1 elif self.vac_receiver == 'S+R': zeta = S/(S+R) else: print('Re-specify vaccine recipient choice') # Main equations S1 = S - gamma_t * S * I / self.N + r_re_R*R +r_re_V*V - r_v * zeta if S1 < 0: # Vaccination reaches saturating point S1 = 0 r_v = (S - gamma_t * S * I / self.N + r_re_R*R +r_re_V*V) /zeta E1 = E + gamma_t * S * I / self.N - r_i * E I1 = I + r_i * E - r_d * I AR1 = AR + r_d * (1 - p_dth) * (1 - p_d) * I - r_ri * AR DHR1 = DHR + r_d * (1 - p_dth) * p_d * p_h * I - r_rh * DHR DQR1 = DQR + r_d * (1 - p_dth) * p_d * (1 - p_h) * I - r_ri * DQR AD1 = AD + r_d * p_dth * (1 - p_d) * I - r_dth * AD DHD1 = DHD + r_d * p_dth * p_d * p_h * I - r_dth * DHD DQD1 = DQD + r_d * p_dth * p_d * (1 - p_h) * I - r_dth * DQD R1 = R + r_ri * (AR + DQR) + r_rh * DHR - r_re_R*R - r_v * (1-zeta) D1 = D + r_dth * (AD + DQD + DHD) # Helper states TH1 = TH + r_d * p_d * p_h * I DVR1 = DVR + r_d * (1 - p_dth) * p_d * p_h * p_v * I - r_rv * DVR DVD1 = DVD + r_d * p_dth * p_d * p_h * p_v * I - r_dth * DVD DD1 = DD + r_dth * (DHD + DQD) DT1 = DT + r_d * p_d * I V1 = V + r_v -r_re_V*V x1 = [S1, E1, I1, AR1, DHR1, DQR1, AD1, DHD1, DQD1, R1, D1, TH1, DVR1, DVD1, DD1, DT1, V1] return x1 # ------------------ X. Construct initial conditions def initial_states_func(self,k): N, PopulationCI, PopulationR, PopulationD, PopulationI, p_d, p_h, p_v = self.GLOBAL_PARAMS p_dth0 = self.newdeaths_data_fit[0]/(r_dth*PopulationCI) # Set p_dth0 to match D1-D0 to newdeaths_data_fit E_0 = PopulationCI / p_d * k I_0 = PopulationCI / p_d * k UR_0 = (PopulationCI / p_d - PopulationCI) * (1 - p_dth0) DHR_0 = (PopulationCI * p_h) * (1 - p_dth0) DQR_0 = PopulationCI * (1 - p_h) * (1 - p_dth0) UD_0 = (PopulationCI / p_d - PopulationCI) * p_dth0 DHD_0 = PopulationCI * p_h * p_dth0 DQD_0 = PopulationCI * (1 - p_h) * p_dth0 R_0 = PopulationR / p_d D_0 = PopulationD / p_d S_0 = N - (E_0 +I_0 +UR_0 +DHR_0 +DQR_0 +UD_0 +DHD_0 +DQD_0 +R_0 +D_0) TH_0 = PopulationCI * p_h DVR_0 = (PopulationCI * p_h * p_v) * (1 - p_dth0) DVD_0 = (PopulationCI * p_h * p_v) * p_dth0 DD_0 = PopulationD DT_0 = PopulationI V_0 = 0 x_init = [ S_0, E_0, I_0, UR_0, DHR_0, DQR_0, UD_0, DHD_0, DQD_0, R_0, D_0, TH_0, DVR_0, DVD_0, DD_0, DT_0, V_0 ] return x_init # Find k=k1,k2 that matches gamma_0 to 2.08 (R0=6 equivalent) def loss_gamma0(self,k): newcases = np.array(self.newcases_data_fit) newdeaths = np.array(self.newdeaths_data_fit) newcases_sm = uniform_filter1d(newcases, size=21, mode='nearest') newdeaths_sm = uniform_filter1d(newdeaths, size=21, mode='nearest') gamma_t_vec = [] x_init = self.initial_states_func(k) (S_0, E_0, I_0, UR_0, DHR_0, DQR_0, UD_0, DHD_0, DQD_0, R_0, D_0, TH_0, DVR_0, DVD_0, DD_0, DT_0, V_0) = x_init newcases_sm2 = np.append(newcases_sm, newcases_sm[-2:]) # Extend the list for forward projection below newdeaths_sm2 = np.append(newdeaths_sm, newdeaths_sm[-1]) x_0 = x_init.copy() for t in range(self.gamma_0_days): # Target first n days gamma_t = (newcases_sm2[t+2]/(r_d*p_d) - (1-r_d)**2 *I_0 - r_i*(2-r_d-r_i)*E_0 )*self.N/(r_i*S_0*I_0) p_dth = (newdeaths_sm2[t+1] - r_dth*(1-r_dth)*(DHD_0 + DQD_0))/(r_dth*r_d*p_d*I_0) gamma_t = np.clip(gamma_t, 0.01, 10) p_dth = np.clip(p_dth,0,1) # Probability limit [0,1] x_1 = self.step_seir(t, x_0, gamma_t, p_dth) x_0 = x_1 gamma_t_vec.append(gamma_t) gamma_0 = np.mean(gamma_t_vec) loss = (gamma_0 - (r_d*6) )**2 # gamma_0 equivalent to R0=6 is 2.08 return loss def fit_gamma0(self): output = dual_annealing( self.loss_gamma0, x0 = [5], bounds = [(1,50)], ) k_star = output.x return k_star def get_initial_conditions(self): if Path(f'../params/param_fixed/kstar.csv').exists(): df = pd.read_csv(f'../params/param_fixed/kstar.csv') kstar = df[self.iso2].values[0] else: kstar = self.fit_gamma0()[0] # find kstar that matches gamma_0 to target x_init = self.initial_states_func(kstar) return x_init # -------------------- x. Implied gamma_t and pdth_t in-sample ------------------- def gamma_t_compute(self): newcases = np.array(self.newcases_data_fit) newdeaths = np.array(self.newdeaths_data_fit) newcases_sm = uniform_filter1d(newcases, size=21, mode='nearest') newdeaths_sm = uniform_filter1d(newdeaths, size=21, mode='nearest') gamma_t_vec = [] p_dth_vec = [] x_init = self.get_initial_conditions() S_0, E_0, I_0, AR_0, DHR_0, DQR_0, AD_0, DHD_0, DQD_0, R_0, D_0, TH_0, DVR_0, DVD_0, DD_0, DT_0, V_0 = x_init S_vec = [S_0] E_vec = [E_0] I_vec = [I_0] DT_vec = [DT_0] DD_vec = [DD_0] DHR_vec = [DHR_0] DHD_vec = [DHD_0] newcases_sm2 = np.append(newcases_sm, newcases_sm[-2:]) # Extend the list for forward projection below newdeaths_sm2 = np.append(newdeaths_sm, newdeaths_sm[-1]) x_0 = x_init.copy() for t in range(len(newcases)): # Work backwards to compute 'exact' gamma_t and p_dth gamma_t = (newcases_sm2[t+2]/(r_d*p_d) - (1-r_d)**2 *I_0 - r_i*(2-r_d-r_i)*E_0 )*self.N/(r_i*S_0*I_0) p_dth = (newdeaths_sm2[t+1] - r_dth*(1-r_dth)*(DHD_0 + DQD_0))/(r_dth*r_d*p_d*I_0) gamma_t = np.clip(gamma_t, 0.01, 10) p_dth = np.clip(p_dth,0,1) # Probability limit [0,1] x_1 = self.step_seir(t, x_0, gamma_t, p_dth) S_0, E_0, I_0, AR_0, DHR_0, DQR_0, AD_0, DHD_0, DQD_0, R_0, D_0, TH_0, DVR_0, DVD_0, DD_0, DT_0, V_0 = x_1 x_0 = x_1 gamma_t_vec.append(gamma_t) p_dth_vec.append(p_dth) S_vec.append(S_0) I_vec.append(I_0) E_vec.append(E_0) DT_vec.append(DT_0) DD_vec.append(DD_0) DHR_vec.append(DHR_0) DHD_vec.append(DHD_0) self.df2['gamma_t'] = gamma_t_vec self.df2['pdth_t'] = p_dth_vec self.S_vec = S_vec # In-sample estmates, useful for phi calculation later on self.I_vec = I_vec self.DHR_vec = DHR_vec # For fitting death probability self.DHD_vec = DHD_vec HD_HR = np.array(self.DHR_vec) + np.array(self.DHD_vec) self.df2['HD_HR'] = 100*HD_HR[:-1]/self.N # gamma_t_sm = uniform_filter1d(gamma_t_vec, size=6, mode='nearest') # self.df2['gamma_sm'] = gamma_t_sm return gamma_t_vec, p_dth_vec # -------------------- x. Estimating the model ----------- def gamma_func(self, params): m_t = self.df2['google_smooth'].values tvec = np.arange(len(m_t)) beta0, beta1 = params gamma_vec = beta0*np.exp(beta1* m_t) return gamma_vec def loss_betas(self, params) -> float: gamma_model = self.gamma_func(params) loss = sum( (self.df2['gamma_t'].values[:len(gamma_model)] - gamma_model)**2 ) return loss def fitmodel(self): # A. Fit beta0 and beta1 x0 = self.default_init_single bounds_0 = self.default_bounds_single output = dual_annealing( self.loss_betas, x0 = x0, bounds = bounds_0, ) best_betas = output.x self.best_betas = best_betas # B. Fit the residual (gamma_tilde) to AR models m_t = self.df2['google_smooth'].values tvec = np.arange(len(self.df2)) beta0, beta1 = self.best_betas self.df2['gamma_mob'] = beta0*np.exp(beta1* m_t) self.df2['gamma_tilde'] = self.df2['gamma_t'] - self.df2['gamma_mob'] self.df2['gamma_tilde_sm'] = uniform_filter1d(self.df2['gamma_tilde'], size=21, mode='reflect') self.df2['gamma_tilde_resid'] = self.df2['gamma_tilde'] - self.df2['gamma_tilde_sm'] y = self.df2['gamma_tilde_sm'] self.df2['gamma_tilde_sm_lag1'] = self.df2['gamma_tilde_sm'].shift(1) # No constant term self.df2['gamma_tilde_sm_lag2'] = self.df2['gamma_tilde_sm'].shift(2) reg_AR1 = sm.OLS(y,self.df2['gamma_tilde_sm_lag1'],missing='drop').fit() reg_AR2 = sm.OLS(y,self.df2[['gamma_tilde_sm_lag1','gamma_tilde_sm_lag2']],missing='drop').fit() best_rho1 = reg_AR1.params[0] best_rho1 = np.clip(best_rho1, 0.1, 0.99) #Assume stationarity best_rho2 = reg_AR2.params[:] best_params = np.array([beta0, beta1, best_rho1, best_rho2[0], best_rho2[1]]) self.best_rho1 = best_rho1 self.best_rho2 = best_rho2 self.best_params = best_params # C. Empirically fit phi for optimal policy to last observation if self.phi_option == 'fit': m = self.df2['google_smooth'][-15:].mean() # Take average of last 15 days to smooth volatility s = self.S_vec[-1]/self.N i = self.I_vec[-1]/self.N gamma_tilde = self.df2['gamma_tilde'][-1] pdth = self.df2['pdth_t'][-1] pdth = max(pdth, self.pdth_min) # Get around cases where pdth=0 for countries with very few cases LHS1 = pdth*r_d*i*s*(beta0*beta1*np.exp(beta1*m)) LHS2 = pdth*r_d*i*(1 - r_d + s*(gamma_tilde + beta0*np.exp(beta1*m))) phi = -(LHS1 * LHS2)/m self.phi = max(phi, self.phi_min) elif self.phi_option == 'exo': self.phi = self.phi_exo return best_params # ------------------ x. Forecasts --------------------------- def step_gamma_tilde(self, gamma_tilde_lag1, gamma_tilde_lag2, model='AR1'): if model =='AR1': return self.best_rho1*gamma_tilde_lag1 elif model =='AR2': return self.best_rho2[0]*gamma_tilde_lag1 + self.best_rho2[1]*gamma_tilde_lag2 def mobility_choice(self,x,gamma_tilde,pdth): if self.policy == 'constant': mob = self.poparam_constant elif self.policy == 'linear-I': # Respond linearly to infection level mob = self.poparam_linear_I[0] + self.poparam_linear_I[1]*x[2] elif self.policy == 'linear-dI': # Respond to new infections dI = r_i*x[1] - r_d*x[2] # x[1]=E, x[2]=I mob = self.poparam_linear_dI[0] + self.poparam_linear_dI[1]*dI elif self.policy == 'optim': # Analytical optimal policy based on simplified model and quadratic losses beta0 = self.best_params[0] beta1 = self.best_params[1] phi = self.phi s = x[0]/self.N i = x[2]/self.N m_set = np.linspace(-1,0,101) RHS = -phi*m_set LHS1 = pdth*r_d*i*s*(beta0*beta1*np.exp(beta1*m_set)) LHS2 = pdth*r_d*i*(1 - r_d + s*(gamma_tilde + beta0*np.exp(beta1*m_set))) LHS = LHS1 * LHS2 m_id = np.argmin(np.abs(RHS-LHS)) mob = m_set[m_id] return mob def fatality_factor(self,V): # Factor to adjust 'base' fatality prob idx = (f_table[self.iso2]['vaccine_%'] - V/self.N).abs().argmin() # Find idx to look up in fatality table factor = f_table[self.iso2]['fatality_ratio'][idx] return factor def sim_seir(self): df2 = self.df2 ix = pd.date_range(start=df2.index[0], end=default_maxT, freq='D') # Expand time-sample, to include forecast later df3 = df2.reindex(ix) x_init = self.get_initial_conditions() x_data = np.array(x_init) gamma_tilde_fc = self.df2['gamma_tilde'].values gamma_tilde_sm_fc = self.df2['gamma_tilde_sm'].values pdth_t_targ = [] # Death prob when vaccines are targeted pdth_t_base = [] # Base death prob if vaccines are given randomly pdth_t_fc = self.df2['pdth_t'].values pdth_t_base_fc = pdth_t_fc.copy() gamma_mob_fc = self.df2['gamma_mob'].values mob_fc = self.df2['google_smooth'].values # Load parameters if hasattr(self, 'best_params'): beta0, beta1, rho, rhos_1, rhos_2 = self.best_params else: df_param = pd.read_csv(f'../params/{param_load_folder}/param_est.csv') beta0, beta1, rho, rhos_1, rhos_2 = df_param[self.iso2] for t in range(self.maxT): factor = self.fatality_factor(x_init[-1]) eta = self.target_weight if t<len(self.df2): # In sample pdth_t = pdth_t_fc[t] pdth_base = pdth_t/(eta*factor + 1-eta) pdth_targ = factor*pdth_base # if t==len(self.df2): # Parse pdth_base of hospitalised/N # y = pdth_t_base # X = self.df2['HD_HR'].shift(30) # Use lagged hospitalised as the predictor # X = sm.add_constant(X) # reg_pdth = sm.OLS(y,X, missing='drop').fit() # thetas = reg_pdth.params # self.best_theta = thetas # pdb.set_trace() # pdth_t_basex = y - thetas[0] - thetas[1]*X # Base death prob, parsed of hospitalisation wave # self.df2['pdth_base'] = pdth_t_base # self.df2['pdth_base_x'] = pdth_t_basex if t>len(self.df2)-1: # Out of sample # Death probability if self.pdth_assump == 'martingale': # Martingale death rate pdth_base = pdth_t_base[-1] elif self.pdth_assump == 'treatment': # Death prob slowly declines to assumed minimum and assumed halflife pdth_base = self.pdth_theta*pdth_t_base[-1] + (1-self.pdth_theta)*self.pdth_min pdth_base = max(pdth_base, self.pdth_min) # To get around pdth=0 for countries with very few cases pdth_t = (eta*factor + 1-eta)*pdth_base pdth_targ = factor*pdth_base # Gamma_tilde if self.gamma_tilde_model == 'AR1': gamma_tilde = rho*gamma_tilde_sm_fc[t-1] elif self.gamma_tilde_model == 'AR2': gamma_tilde = rhos_1*gamma_tilde_sm_fc[t-1] + rhos_2*gamma_tilde_sm_fc[t-2] elif self.gamma_tilde_model =='shock': if t < len(self.df2) + self.gamma_shock_length: gamma_tilde = gamma_tilde_sm_fc[len(self.df2)-1] + self.gamma_shock_depth else: gamma_tilde = rho*gamma_tilde_sm_fc[t-1] # Mobility and overall gamma_t mob_t = self.mobility_choice(x_init, gamma_tilde, pdth_t) mob_t = max(mob_t, max_lockdown) gamma_mob_t = beta0*np.exp(beta1*mob_t) gamma_t = gamma_tilde + gamma_mob_t # Append to data array gamma_tilde_sm_fc = np.append(gamma_tilde_sm_fc, gamma_tilde) gamma_tilde_fc = np.append(gamma_tilde_fc, gamma_tilde) gamma_mob_fc = np.append(gamma_mob_fc, gamma_mob_t) mob_fc = np.append(mob_fc, mob_t) pdth_t_fc = np.append(pdth_t_fc, pdth_t) pdth_t_base.append(pdth_base) pdth_t_targ.append(pdth_targ) # For in sample, use 'true' inputs gamma_t = gamma_tilde_fc[t] + gamma_mob_fc[t] p_dth = pdth_t_fc[t] if t < range(self.maxT)[-1]: # Stop forecasting at the final period x_next = self.step_seir(t, x_init, gamma_t, p_dth) x_data = np.vstack((x_data, np.array(x_next))) x_init = x_next # Fill dataframe col_temp = ['S', 'E', 'I', 'AR', 'DHR', 'DQR', 'AD', 'DHD', 'DQD', 'R', 'D', 'TH', 'DVR', 'DVD', 'DD', 'DT', 'V'] df4 = pd.DataFrame(x_data, columns=col_temp, index=df3.index) df3 = df3.merge(df4, how='left', left_index=True, right_index=True) df3['gamma_tilde_fc'] = gamma_tilde_fc df3['gamma_mob_fc'] = gamma_mob_fc df3['gamma_t_fc'] = df3['gamma_tilde_fc'] + df3['gamma_mob_fc'] df3['mob_fc'] = mob_fc df3['pdth_t_fc'] = pdth_t_fc df3['pdth_t_base'] = np.array(pdth_t_base) df3['pdth_t_targ'] = np.array(pdth_t_targ) df3[['S_N','I_N','DT_N','DD_N','V_N']] = df3[['S','I','DT','DD','V']]/self.N self.df3 = df3 return df3 # ------------------ 5. Predict and plot --------------------- def plot_all(self, saveplot=False): df = self.df3 transpa = 0.0 fig, ax = plt.subplots(nrows=2, ncols=3, figsize=(15,8), constrained_layout=True) # df_bar = df_bar0[['GDP lost','Total deaths']] # df_bar.plot(kind='bar', ax=ax[1,2], secondary_y='Total deaths', rot=0, legend=False) # ax[1,2].set_ylabel('percent') # ax[1,2].right_ax.set_ylabel('per million') # ax[1,2].set_title('Losses of lives and output',fontsize='x-large') # L = [mpatches.Patch(color=c, label=col) # for col,c in zip( ('GDP loss','Deaths (rhs)'), plt.rcParams['axes.prop_cycle'].by_key()['color'])] # ax[1,2] = plt.legend(handles=L, loc=1, framealpha=transpa) ax[0,0].plot(df.index, 100*df['total_cases']/self.N, linewidth = 3, label='Case data', color='blue') ax[0,0].plot(df.index, 100*df['DT']/self.N, label='$DT_t$', color='red') ax[0,0].axvline(df.index[self.T], linewidth = 2, color='gray', linestyle=':') ax[0,0].set_title('Cases',fontsize='x-large') ax[0,0].set(ylabel = '% of population') ax2 = ax[0,0].twinx() ax2.plot(df.index, 100*df['I']/self.N, label='$I_t$ (rhs)',color='green',linestyle='--') lines, labels = ax[0,0].get_legend_handles_labels() lines2, labels2 = ax2.get_legend_handles_labels() ax2.legend(lines + lines2, labels + labels2, loc='center right', framealpha=transpa,fontsize='x-large') #ax2.set(ylabel='% of population') ax[0,1].plot(df.index, 100*df['total_deaths']/self.N, linewidth = 3, label='Death data', color='blue') ax[0,1].plot(df.index, 100*df['DD']/self.N, label='$DD_t$', color='red') ax[0,1].axvline(df.index[self.T], linewidth = 2, color='gray', linestyle=':') ax[0,1].set_title('Deaths',fontsize='x-large') ax[0,1].set(ylabel='% of population') ax[0,1].legend(loc='best', framealpha=transpa ,fontsize='x-large') ax[0,2].plot(df.index, 100*df['S']/self.N, label='$S_t$',color='red') ax[0,2].plot(df.index, 100*df['V']/self.N, label='$V_t$',color='red',linestyle=':') ax[0,2].axvline(df.index[self.T], linewidth = 2, color='gray', linestyle=':') ax[0,2].set_title('Susceptible & vaccinated',fontsize='x-large') ax[0,2].legend(loc='best',framealpha=transpa ,fontsize='x-large') ax[0,2].set(ylabel='% of population') ax[1,0].plot(df.index, df['gamma_t'], label=r'$\gamma_t$',color='red') ax[1,0].plot(df.index, df['gamma_mob'], label=r'$\gamma^{m}_t$', color ='blue') ax[1,0].plot(df.index, df['gamma_tilde'], label=r'$\gamma^{d}$', color='orange') ax[1,0].plot(df.index, df['gamma_t_fc'], color='red',linestyle=':') ax[1,0].plot(df.index, df['gamma_mob_fc'], color ='blue',linestyle=':') ax[1,0].plot(df.index, df['gamma_tilde_fc'], color='orange',linestyle=':') ax[1,0].axvline(df.index[self.T], linewidth = 2, color='gray', linestyle=':') ax[1,0].set_title('Infection rate',fontsize='x-large') ax[1,0].legend(loc='best',framealpha=transpa ,fontsize='x-large') ax[1,1].plot(df.index, 100*df['google_smooth'], linewidth = 3, label='Google mobility', color='blue') ax[1,1].plot(df.index, 100*df['mob_fc'], label='Model', color='red') ax[1,1].axvline(df.index[self.T], linewidth = 2, color='gray', linestyle=':') ax[1,1].legend(loc=0,framealpha=transpa ,fontsize='x-large') ax[1,1].set_title('Activity',fontsize='x-large') ax[1,1].set(ylabel='% deviations from norm') ax[1,2].plot(df.index, 100*df['pdth_t'], label='Death probability', linewidth=3, color='blue') ax[1,2].plot(df.index, 100*df['pdth_t_fc'], color='black', label='Forecast') ax[1,2].plot(df.index, 100*df['pdth_t_base'], color='black', linestyle='dashed', label='Random vaccines') ax[1,2].plot(df.index, 100*df['pdth_t_targ'], color='black', linestyle=':', label='Targeted vaccines') ax[1,2].axvline(df.index[self.T], linewidth = 2, color='gray', linestyle=':') ax[1,2].legend(loc=0,framealpha=transpa ,fontsize='x-large') ax[1,2].set_title('Death probability',fontsize='x-large') ax[1,2].set(ylabel='%') plt.setp(ax[0,0].get_xticklabels(), rotation=30, horizontalalignment='right') plt.setp(ax[0,1].get_xticklabels(), rotation=30, horizontalalignment='right') plt.setp(ax[0,2].get_xticklabels(), rotation=30, horizontalalignment='right') plt.setp(ax[1,0].get_xticklabels(), rotation=30, horizontalalignment='right') plt.setp(ax[1,1].get_xticklabels(), rotation=30, horizontalalignment='right') plt.setp(ax[1,2].get_xticklabels(), rotation=30, horizontalalignment='right') cname = coco.convert(names=self.iso2,to='name_short') fig.suptitle(f'{cname}-{self.vac_assump}-{self.reinfect}',fontsize='xx-large') if saveplot: Path(f'../pics/fig_{date.today()}').mkdir(exist_ok=True) fig.savefig(f'../pics/fig_{date.today()}/{self.iso2}-{self.policy}-{self.gamma_tilde_model}-{self.vac_assump}-{self.reinfect}.png') return fig def plot_portrait(self, saveplot=False): df = self.df3 transpa = 0.0 fig, ax = plt.subplots(nrows=3, ncols=2, figsize=(10,12), constrained_layout=True) ax[0,0].plot(df.index, 100*df['total_cases']/self.N, linewidth = 3, label='Case data', color='blue') ax[0,0].plot(df.index, 100*df['DT']/self.N, label='$DT_t$', color='red') ax[0,0].axvline(df.index[self.T], linewidth = 2, color='gray', linestyle=':') ax[0,0].set_title('Cases',fontsize='x-large') ax[0,0].set(ylabel = '% of population') ax2 = ax[0,0].twinx() ax2.plot(df.index, 100*df['I']/self.N, label='$I_t$ (rhs)',color='green',linestyle='--') ax2.grid(None) lines, labels = ax[0,0].get_legend_handles_labels() lines2, labels2 = ax2.get_legend_handles_labels() ax2.legend(lines + lines2, labels + labels2, loc='center right', framealpha=transpa,fontsize='x-large') #ax2.set(ylabel='% of population') ax[0,1].plot(df.index, 100*df['total_deaths']/self.N, linewidth = 3, label='Death data', color='blue') ax[0,1].plot(df.index, 100*df['DD']/self.N, label='$DD_t$', color='red') ax[0,1].axvline(df.index[self.T], linewidth = 2, color='gray', linestyle=':') ax[0,1].set_title('Deaths',fontsize='x-large') ax[0,1].set(ylabel='% of population') ax[0,1].legend(loc='best', framealpha=transpa ,fontsize='x-large') ax[1,0].plot(df.index, 100*df['S']/self.N, label='$S_t$',color='red') ax[1,0].plot(df.index, 100*df['V']/self.N, label='$V_t$',color='red',linestyle=':') ax[1,0].axvline(df.index[self.T], linewidth = 2, color='gray', linestyle=':') ax[1,0].set_title('Susceptible & vaccinated',fontsize='x-large') ax[1,0].legend(loc='best',framealpha=transpa ,fontsize='x-large') ax[1,0].set(ylabel='% of population') ax[1,1].plot(df.index, df['gamma_t'], label=r'$\gamma_t$',color='red') ax[1,1].plot(df.index, df['gamma_mob'], label=r'$\gamma^{m}_t$', color ='blue') ax[1,1].plot(df.index, df['gamma_tilde'], label=r'$\gamma^{d}$', color='orange') ax[1,1].plot(df.index, df['gamma_t_fc'], color='red',linestyle=':') ax[1,1].plot(df.index, df['gamma_mob_fc'], color ='blue',linestyle=':') ax[1,1].plot(df.index, df['gamma_tilde_fc'], color='orange',linestyle=':') ax[1,1].axvline(df.index[self.T], linewidth = 2, color='gray', linestyle=':') ax[1,1].set_title('Infection rate',fontsize='x-large') ax[1,1].legend(loc='best',framealpha=transpa ,fontsize='x-large') ax[2,0].plot(df.index, 100*df['google_smooth'], linewidth = 3, label='Google mobility', color='blue') ax[2,0].plot(df.index, 100*df['mob_fc'], label='Model', color='red') ax[2,0].axvline(df.index[self.T], linewidth = 2, color='gray', linestyle=':') ax[2,0].legend(loc=0,framealpha=transpa ,fontsize='x-large') ax[2,0].set_title('Mobility',fontsize='x-large') ax[2,0].set(ylabel='% deviations from norm') ax[2,1].plot(df.index, 100*df['pdth_t'], label='Death probability', linewidth=3, color='blue') ax[2,1].plot(df.index, 100*df['pdth_t_fc'], color='black', label='Forecast') ax[2,1].plot(df.index, 100*df['pdth_t_base'], color='black', linestyle='dashed', label='Random vaccines') ax[2,1].plot(df.index, 100*df['pdth_t_targ'], color='black', linestyle=':', label='Targeted vaccines') ax[2,1].axvline(df.index[self.T], linewidth = 2, color='gray', linestyle=':') ax[2,1].legend(loc=0,framealpha=transpa ,fontsize='x-large') ax[2,1].set_title('Death probability',fontsize='x-large') ax[2,1].set(ylabel='%') plt.setp(ax[0,0].get_xticklabels(), rotation=30, horizontalalignment='right') plt.setp(ax[0,1].get_xticklabels(), rotation=30, horizontalalignment='right') plt.setp(ax[1,0].get_xticklabels(), rotation=30, horizontalalignment='right') plt.setp(ax[1,1].get_xticklabels(), rotation=30, horizontalalignment='right') plt.setp(ax[2,0].get_xticklabels(), rotation=30, horizontalalignment='right') plt.setp(ax[2,1].get_xticklabels(), rotation=30, horizontalalignment='right') cname = coco.convert(names=self.iso2,to='name_short') fig.suptitle(f'{cname}',fontsize=18) if saveplot: Path(f'../pics/fig_{date.today()}').mkdir(exist_ok=True) fig.savefig(f'../pics/fig_{date.today()}/Portrait-{self.iso2}-{self.policy}-{self.gamma_tilde_model}-{self.vac_assump}-{self.reinfect}.pdf') return fig # --------------------------------------------- # Calling functions # --------------------------------------------- # ----------------------------------------- # x. Prelim parameters estimation # Estimate k_star and save in file (only need to do this once) def estimate_kstar(cset=['US']): dict = {'Parameter': ['kstar']} for c in cset: tmp = solveCovid(c) tmp.prelim() kstar = tmp.fit_gamma0() dict[c] = kstar df = pd.DataFrame(dict) df.to_csv(f'../params/param_fixed/kstar.csv',index=False) return df # ------------------------- # x. Run complete package under scenarios: estimate, forecast, plot, save def run_baseline(cset=['US']): p_dict = {'Parameters': ['beta0','beta1','rho','rhos_1','rhos_2','phi']} for c in cset: tmp = solveCovid(c) tmp.prelim() tmp.gamma_t_compute() tmp.fitmodel() p_dict[c] = np.append(tmp.best_params, 1e9*tmp.phi) tmp.sim_seir() tmp.plot_all(saveplot='False') tmp.df3.to_csv(f'../output/{out_save_folder}/df3_{tmp.iso2}.csv') pd.DataFrame(p_dict).to_csv(f'../params/{param_save_folder}/param_est.csv',float_format='%.4f',index=False) def run_gammashock(cset=['US']): for c in cset: tmp = solveCovid(c) tmp.prelim() tmp.gamma_t_compute() tmp.fitmodel() tmp.gamma_tilde_model = 'shock' tmp.sim_seir() tmp.plot_all(saveplot=True) def run_vaccines(cset=['US'],vac_assump='vac_worse'): for c in cset: tmp = solveCovid(c) tmp.vac_assump = vac_assump tmp.prelim() tmp.gamma_t_compute() tmp.fitmodel() tmp.sim_seir() tmp.plot_all(saveplot=True) def run_reinfect(cset=['US'],reinfect = 'reinfect'): for c in cset: tmp = solveCovid(c) tmp.reinfect = reinfect tmp.prelim() tmp.gamma_t_compute() tmp.fitmodel() tmp.sim_seir() tmp.plot_all(saveplot=True) def run_scenarios(cset=['US']): # Save class objects under various scenarios so we could draw plots across countries/scenarios p_dict = {'Parameters': ['beta0','beta1','rho','rhos_1','rhos_2','phi']} for c in cset: #Baseline tmp = solveCovid(c) tmp.prelim() tmp.gamma_t_compute() tmp.fitmodel() p_dict[c] = np.append(tmp.best_params, 1e9*tmp.phi) tmp.sim_seir() tmp.plot_all(saveplot=True) name = f'../output/{out_save_folder}/{c}_baseline.pkl' pickle.dump(tmp,open(name,'wb')) # Vaccines t_vac = solveCovid(c) t_vac.vac_assump = 'vac_worse' t_vac.prelim() t_vac.gamma_t_compute() t_vac.fitmodel() t_vac.sim_seir() t_vac.plot_all(saveplot=True) name = f'../output/{out_save_folder}/{c}_vacworse.pkl' pickle.dump(t_vac,open(name,'wb')) # Spikes t_spike = solveCovid(c) t_spike.prelim() t_spike.gamma_t_compute() t_spike.fitmodel() t_spike.gamma_tilde_model = 'shock' t_spike.sim_seir() t_spike.plot_all(saveplot=True) name = f'../output/{out_save_folder}/{c}_shock.pkl' pickle.dump(t_spike,open(name,'wb')) # Reinfection t_reinfect = solveCovid(c) t_reinfect.reinfect = 'reinfect' t_reinfect.prelim() t_reinfect.gamma_t_compute() t_reinfect.fitmodel() t_reinfect.sim_seir() t_reinfect.plot_all(saveplot=True) name = f'../output/{out_save_folder}/{c}_reinfect.pkl' pickle.dump(t_reinfect,open(name,'wb')) # Better t_better = solveCovid(c) t_better.vac_assump = 'vac_better' # (a) 30% Faster vaccines t_better.target_weight = 0.9 # (b) More targeted t_better.prelim() t_better.gamma_t_compute() t_better.fitmodel() t_better.sim_seir() t_better.plot_all(saveplot=True) name = f'../output/{out_save_folder}/{c}_better.pkl' pickle.dump(t_better,open(name,'wb')) pd.DataFrame(p_dict).to_csv(f'../params/{param_save_folder}/param_est.csv',float_format='%.4f',index=False) def save_results(cset=['US']): # Unpack pickle and save all results into an excel with pd.ExcelWriter(f'../output/{out_save_folder}/output_all.xlsx') as writer: for c in cset: print(f'Loading pickle for {c}') tmp = pickle.load(open(f'../output/{out_load_folder}/{c}_baseline.pkl','rb')) t_vac = pickle.load(open(f'../output/{out_load_folder}/{c}_vacworse.pkl','rb')) t_spike = pickle.load(open(f'../output/{out_load_folder}/{c}_shock.pkl','rb')) t_reinfect = pickle.load(open(f'../output/{out_load_folder}/{c}_reinfect.pkl','rb')) #t_better = pickle.load(open(f'../output/{out_load_folder}/{c}_better.pkl','rb')) tmp.df3.to_excel(writer, sheet_name=f'{c}_base') t_vac.df3.to_excel(writer, sheet_name=f'{c}_vacworse') t_spike.df3.to_excel(writer, sheet_name=f'{c}_shock') t_reinfect.df3.to_excel(writer, sheet_name=f'{c}_reinfect') #t_better.df3.to_excel(writer, sheet_name=f'{c}_better') # --------------------------------------------------- # x. Plotting functions # ***** Utilities ***** def scatter1(x,y,xlab,ylab,df): x1 = df[x] y1 = df[y] fig, ax = plt.subplots(figsize=(10,8)) ax.scatter(x1,y1,marker='o',facecolors='none', edgecolors='none') for i, label in enumerate(df.index): ax.annotate(label, (x1.iloc[i], y1.iloc[i]), size=16) ax.plot(np.unique(x1), np.poly1d(np.polyfit(x1, y1, 1))(np.unique(x1)), color='black') ax.set_xlabel(xlab,size=20) ax.set_ylabel(ylab,size=20) plt.xticks(fontsize= 20) plt.yticks(fontsize= 20) return fig, ax def scatter2(x,y,x2,y2,xlab,ylab,df): x1 = df[x] y1 = df[y] x2 = df[x2] y2 = df[y2] fig, ax = plt.subplots(figsize=(10,8)) ax.scatter(x1,y1,marker='o',facecolors='none', edgecolors='none') for i, label in enumerate(df.index): ax.annotate(label, (x1.iloc[i], y1.iloc[i]), size=16, color='gray') ax.plot(np.unique(x1), np.poly1d(np.polyfit(x1, y1, 1))(np.unique(x1)), color='gray') ax.set_xlabel(xlab,size=20) ax.set_ylabel(ylab,size=20) # Super impose with a new set ax.scatter(x2,y2,marker='o',facecolors='none', edgecolors='none') for i, label in enumerate(df.index): ax.annotate(label, (x2.iloc[i], y2.iloc[i]), size=16, color='blue') ax.plot(np.unique(x2), np.poly1d(np.polyfit(x2, y2, 1))(np.unique(x2)), color='blue') ax.set_xlabel(xlab,size=20) ax.set_ylabel(ylab,size=20) plt.xticks(fontsize= 20) plt.yticks(fontsize= 20) return fig, ax def all_output(cset=['US','DE']): data_col = ['Mob 2021','Mob fc', 'GDP 2021','GDP fc', 'dDeath 2021','dDeath fc', 'dD/mn 2021','dD/mn fc', 'Mob 2021 3rdwave', 'Mob fc 3rdwave', 'GDP 2021 3rdwave', 'GDP fc 3rdwave', 'dDeath 2021 3rdwave', 'dDeath fc 3rdwave', 'dD/mn 2021 3rdwave', 'dD/mn fc 3rdwave', 'Mob 2021 vacworse', 'Mob fc vacworse', 'GDP 2021 vacworse', 'GDP fc vacworse', 'dDeath 2021 vacworse', 'dDeath fc vacworse', 'dD/mn 2021 vacworse', 'dD/mn fc vacworse', 'Mob 2021 reinfect', 'Mob fc reinfect', 'GDP 2021 reinfect', 'GDP fc reinfect', 'dDeath 2021 reinfect', 'dDeath fc reinfect', 'dD/mn 2021 reinfect', 'dD/mn fc reinfect', # 'Mob 2021 better', 'Mob fc better', # 'GDP 2021 better', 'GDP fc better', # 'dDeath 2021 better', 'dDeath fc better', # 'dD/mn 2021 better', 'dD/mn fc better', ] data = {} df_yratio = pd.read_csv(f'../output/growth-mob.csv', index_col=0) for c in cset: tmp = pickle.load(open(f'../output/{out_load_folder}/{c}_baseline.pkl','rb')) tmp1 = pickle.load(open(f'../output/{out_load_folder}/{c}_shock.pkl','rb')) tmp2 = pickle.load(open(f'../output/{out_load_folder}/{c}_vacworse.pkl','rb')) tmp3 = pickle.load(open(f'../output/{out_load_folder}/{c}_reinfect.pkl','rb')) # tmp4 = pickle.load(open(f'../output/{out_load_folder}/{c}_better.pkl','rb')) cnum = tmp.df3.index.get_loc('2020-12-31')+1 d = tmp.df3['total_cases'].last_valid_index() dnum = tmp.df3.index.get_loc(d)+1 mob_2021 = tmp.df3['mob_fc'].iloc[cnum:].mean() # Average mobility for 2021 mob_fc = tmp.df3['mob_fc'].iloc[dnum:].mean() # Average mobility from current date till year end GDP_2021 = 100*mob_2021*df_yratio.loc[c]['ym_ratio'] GDP_fc = 100*mob_fc*df_yratio.loc[c]['ym_ratio'] dD_2021 = tmp.df3['DD'][-1] - tmp.df3['DD'][cnum] dD_fc = tmp.df3['DD'][-1] - tmp.df3['DD'][dnum] dD_mn_2021 = 1000000*dD_2021/tmp.N dD_mn_fc = 1000000*dD_fc/tmp.N mob_2021_shock = tmp1.df3['mob_fc'].iloc[cnum:].mean() # Average mobility for 2021 mob_fc_shock = tmp1.df3['mob_fc'].iloc[dnum:].mean() # Average mobility from current date till year end GDP_2021_shock = 100*mob_2021_shock*df_yratio.loc[c]['ym_ratio'] GDP_fc_shock = 100*mob_fc_shock*df_yratio.loc[c]['ym_ratio'] dD_2021_shock = tmp1.df3['DD'][-1] - tmp1.df3['DD'][cnum] dD_fc_shock = tmp1.df3['DD'][-1] - tmp1.df3['DD'][dnum] dD_mn_2021_shock = 1000000*dD_2021_shock/tmp.N dD_mn_fc_shock = 1000000*dD_fc_shock/tmp.N mob_2021_vacworse = tmp2.df3['mob_fc'].iloc[cnum:].mean() # Average mobility for 2021 mob_fc_vacworse = tmp2.df3['mob_fc'].iloc[dnum:].mean() # Average mobility from current date till year end GDP_2021_vacworse = 100*mob_2021_vacworse*df_yratio.loc[c]['ym_ratio'] GDP_fc_vacworse = 100*mob_fc_vacworse*df_yratio.loc[c]['ym_ratio'] dD_2021_vacworse = tmp2.df3['DD'][-1] - tmp2.df3['DD'][cnum] dD_fc_vacworse = tmp2.df3['DD'][-1] - tmp2.df3['DD'][dnum] dD_mn_2021_vacworse = 1000000*dD_2021_vacworse/tmp.N dD_mn_fc_vacworse = 1000000*dD_fc_vacworse/tmp.N mob_2021_reinfect = tmp3.df3['mob_fc'].iloc[cnum:].mean() # Average mobility for 2021 mob_fc_reinfect = tmp3.df3['mob_fc'].iloc[dnum:].mean() # Average mobility from current date till year end GDP_2021_reinfect = 100*mob_2021_reinfect*df_yratio.loc[c]['ym_ratio'] GDP_fc_reinfect = 100*mob_fc_reinfect*df_yratio.loc[c]['ym_ratio'] dD_2021_reinfect = tmp3.df3['DD'][-1] - tmp3.df3['DD'][cnum] dD_fc_reinfect = tmp3.df3['DD'][-1] - tmp3.df3['DD'][dnum] dD_mn_2021_reinfect = 1000000*dD_2021_reinfect/tmp.N dD_mn_fc_reinfect = 1000000*dD_fc_reinfect/tmp.N # mob_2021_better = tmp4.df3['mob_fc'].iloc[cnum:].mean() # Average mobility for 2021 # mob_fc_better = tmp4.df3['mob_fc'].iloc[dnum:].mean() # Average mobility from current date till year end # GDP_2021_better = 100*mob_2021_better*df_yratio.loc[c]['ym_ratio'] # GDP_fc_better = 100*mob_fc_better*df_yratio.loc[c]['ym_ratio'] # dD_2021_better = tmp4.df3['DD'][-1] - tmp4.df3['DD'][cnum] # dD_fc_better = tmp4.df3['DD'][-1] - tmp4.df3['DD'][dnum] # dD_mn_2021_better = 1000000*dD_2021_better/tmp.N # dD_mn_fc_better = 1000000*dD_fc_better/tmp.N data[c] = [mob_2021,mob_fc, GDP_2021,GDP_fc, dD_2021,dD_fc, dD_mn_2021,dD_mn_fc, mob_2021_shock, mob_fc_shock, GDP_2021_shock, GDP_fc_shock, dD_2021_shock, dD_fc_shock, dD_mn_2021_shock, dD_mn_fc_shock, mob_2021_vacworse, mob_fc_vacworse, GDP_2021_vacworse, GDP_fc_vacworse, dD_2021_vacworse, dD_fc_vacworse, dD_mn_2021_vacworse, dD_mn_fc_vacworse, mob_2021_reinfect, mob_fc_reinfect, GDP_2021_reinfect, GDP_fc_reinfect, dD_2021_reinfect, dD_fc_reinfect, dD_mn_2021_reinfect, dD_mn_fc_reinfect, # mob_2021_better, mob_fc_better, # GDP_2021_better, GDP_fc_better, # dD_2021_better, dD_fc_better, # dD_mn_2021_better, dD_mn_fc_better, ] df_out = pd.DataFrame.from_dict(data, orient='index', columns=data_col) name = f'../output/{out_save_folder}/all_output.pkl' pickle.dump(df_out,open(name,'wb')) with pd.ExcelWriter(f'../output/{out_save_folder}/output_condensed.xlsx') as writer: df_out.to_excel(writer, sheet_name='output') return df_out def update_table(cset=['US','DE']): data_col = ['Mobility 2021','Mobility, now to mid 2022', 'Deaths/mn 2021','Deaths/mn, now to mid 2022', ] data = {} for c in cset: tmp = pickle.load(open(f'../output/{out_load_folder}/{c}_baseline.pkl','rb')) cnum = tmp.df3.index.get_loc('2021-01-31') cnum2 = tmp.df3.index.get_loc('2021-12-31') d = tmp.df3['total_cases'].last_valid_index() dnum = tmp.df3.index.get_loc(d)+1 mob_2021 = tmp.df3['mob_fc'].iloc[cnum:cnum2].mean() # Average mobility for 2021 mob_fc = tmp.df3['mob_fc'].iloc[dnum:].mean() # Average mobility from current date till year end dD_2021 = tmp.df3['DD'][cnum2] - tmp.df3['DD'][cnum] dD_fc = tmp.df3['DD'][-1] - tmp.df3['DD'][dnum] dD_mn_2021 = 1000000*dD_2021/tmp.N dD_mn_fc = 1000000*dD_fc/tmp.N data[c] = [100*mob_2021,100*mob_fc, dD_mn_2021,dD_mn_fc, ] df_out = pd.DataFrame.from_dict(data, orient='index', columns=data_col) df_out = df_out.round(decimals=1) return df_out # Compare 2 scenarios, showing 4 key charts def plot_2cases(c,df,df2,tmp,title,filename,saveplot=False): # Compute differences between 2 cases (lives saved at end points, and average mobility differences) d_death = int(round(df2['fitted_deaths'][-1]-df['fitted_deaths'][-1],0)) d_m = round((df2['fitted_m']['2021-01-01':'2021-12-31'] - df['fitted_m']['2021-01-01':'2021-12-31']).mean(),3) # Draw figure fig3, ax = plt.subplots(nrows=2, ncols=2, figsize=(10,8), constrained_layout=True) ax[0,0].plot(df.index, 100*df['fitted_cases']/tmp.N, linewidth = 2, label='Cases', color='red') ax[0,0].plot(df2.index, 100*df2['fitted_cases']/tmp.N, linewidth = 2, label='Cases alt', color='red', linestyle=':') ax[0,0].plot(df.index, 100*df['fitted_I']/tmp.N, linewidth = 2, label='Infected', color='green') ax[0,0].plot(df2.index, 100*df2['fitted_I']/tmp.N, linewidth = 2, label='Infected alt', color='green',linestyle=':') ax[0,0].axvline(df.index[tmp.T], linewidth = 2, color='gray', linestyle=':') ax[0,0].legend(loc='center right',fontsize='x-large',fancybox=True, framealpha=0.5) ax[0,0].set_title('Cases',fontsize='x-large') ax[0,1].plot(df.index, 100*df['fitted_deaths']/tmp.N, linewidth = 2, label='Deaths', color='red') ax[0,1].plot(df2.index, 100*df2['fitted_deaths']/tmp.N, linewidth = 2, label='Deaths alt', color='red', linestyle=':') ax[0,1].axvline(df.index[tmp.T], linewidth = 2, color='gray', linestyle=':') ax[0,1].legend(loc='lower right',fontsize='x-large',fancybox=True, framealpha=0.5) ax[0,1].set_title('Deaths',fontsize='x-large') ax[0,1].annotate(f'$\Delta$Death={d_death}', xy=(0.1,0.9), xycoords='axes fraction') ax[1,0].plot(df.index, 100*df['fitted_S']/tmp.N, linewidth = 2, label='S ', color='red') ax[1,0].plot(df2.index, 100*df2['fitted_S']/tmp.N, linewidth = 2, label='S alt', color='red',linestyle=':') ax[1,0].plot(df.index, 100*df['fitted_V']/tmp.N, linewidth = 2, label='V ', color='green') ax[1,0].plot(df2.index, 100*df2['fitted_V']/tmp.N, linewidth = 2, label='V alt', color='green',linestyle=':') ax[1,0].axvline(df.index[tmp.T], linewidth = 2, color='gray', linestyle=':') ax[1,0].legend(loc='upper right',fontsize='x-large',fancybox=True, framealpha=0.5) ax[1,0].set_title('Susceptible & Vaccinated',fontsize='x-large') ax[1,1].plot(df.index, 100*df['fitted_m'], linewidth = 2, label='Mobility', color='red') ax[1,1].plot(df2.index, 100*df2['fitted_m'], linewidth = 2, label='Mobility alt', color='red', linestyle=':') ax[1,1].axvline(df.index[tmp.T], linewidth = 2, color='gray', linestyle=':') ax[1,1].legend(loc='lower right',fontsize='x-large',fancybox=True, framealpha=0.5) ax[1,1].set_title('Mobility',fontsize='x-large') ax[1,1].annotate(f'$\Delta$m={d_m}', xy=(0.1,0.9), xycoords='axes fraction') plt.setp(ax[0,0].get_xticklabels(), rotation=30, horizontalalignment='right') plt.setp(ax[0,1].get_xticklabels(), rotation=30, horizontalalignment='right') plt.setp(ax[1,0].get_xticklabels(), rotation=30, horizontalalignment='right') plt.setp(ax[1,1].get_xticklabels(), rotation=30, horizontalalignment='right') ax[0,0].set_ylabel('Percent of population') ax[0,1].set_ylabel('Percent of population') ax[1,0].set_ylabel('Percent of population') ax[1,1].set_ylabel('Percent deviations from norm') fig3.suptitle(f'{c}: {title}',fontsize='x-large') if saveplot: Path(f'../pics/fig_{date.today()}').mkdir(exist_ok=True) fig3.savefig(f'../pics/fig_{date.today()}/fig-{tmp.iso2}-{filename}.png') # ------------------------------ # x. Diagnostic/Inspect functions # Plot m_t and gamma_t (data) def plot_m_gamma(cset=['US','DE']): no_fig = len(cset) nrows_ = round(no_fig/2) ncols_ = 2 fig, ax = plt.subplots(nrows=nrows_, ncols=ncols_, figsize=(14,6*nrows_)) i = 0 j = 0 for c in cset: tmp = solveCovid(c) tmp.prelim() tmp.gamma_t_compute() ax[i,j].plot(tmp.df2['gamma_sm'], label = 'gamma_sm', color='black') ax2 = ax[i,j].twinx() ax2.plot(tmp.df2['google_smooth'], label='mobility',color='blue') lines, labels = ax[i,j].get_legend_handles_labels() lines2, labels2 = ax2.get_legend_handles_labels() ax2.legend(lines + lines2, labels + labels2, loc=0, fontsize='x-large') plt.setp(ax[i,j].get_xticklabels(), rotation=30, horizontalalignment='right') ax[i,j].set_title(f'{c}') if j == 0: j +=1 else: j = 0 i +=1 # Plot realised mobility against model-implied I/N def policy_check(): cset = ['US','DE','FR'] fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(15,6), constrained_layout=True) n = 0 dict = {} for c in cset: tmp = solveCovid(c) tmp.prelim() param = mod.get_params('round2')['all'] fig_tmp, df = tmp.predict(params=param,plot=False,saveplot=False) dfa = df[['google_smooth','fitted_I']].dropna() dfa.loc[:,'fitted_I'] = dfa['fitted_I']/tmp.N dfa = dfa.iloc[-120:-1] ax[n].plot(dfa.index, dfa['google_smooth'],label='mobility') ax2 = ax[n].twinx() ax2.plot(dfa.index, dfa['fitted_I'],label='infected',color='g') ax[n].set_title(c,fontsize='x-large') n +=1 # Regressions on more recent samples X = sm.add_constant(dfa['fitted_I']) y = dfa['google_smooth'] model = sm.OLS(y,X).fit() dict[c]=model.summary() return dict
StarcoderdataPython
1897236
_zfpy = None try: import zfpy as _zfpy except ImportError: # pragma: no cover pass if _zfpy: from .abc import Codec from .compat import ndarray_copy, ensure_contiguous_ndarray, ensure_bytes import numpy as np # noinspection PyShadowingBuiltins class ZFPY(Codec): """Codec providing compression using zfpy via the Python standard library. Parameters ---------- mode : integer One of the zfpy mode choice, e.g., ``zfpy.mode_fixed_accuracy``. tolerance : double, optional A double-precision number, specifying the compression accuracy needed. rate : double, optional A double-precision number, specifying the compression rate needed. precision : int, optional A integer number, specifying the compression precision needed. """ codec_id = "zfpy" def __init__( self, mode=_zfpy.mode_fixed_accuracy, tolerance=-1, rate=-1, precision=-1, compression_kwargs=None, ): self.mode = mode if mode == _zfpy.mode_fixed_accuracy: self.compression_kwargs = {"tolerance": tolerance} elif mode == _zfpy.mode_fixed_rate: self.compression_kwargs = {"rate": rate} elif mode == _zfpy.mode_fixed_precision: self.compression_kwargs = {"precision": precision} else: pass self.tolerance = tolerance self.rate = rate self.precision = precision def encode(self, buf): # not flatten c-order array and raise exception for f-order array if not isinstance(buf, np.ndarray): raise TypeError("The zfp codec does not support none numpy arrays." f" Your buffers were {type(buf)}.") if buf.flags.c_contiguous: flatten = False else: raise ValueError("The zfp codec does not support F order arrays. " f"Your arrays flags were {buf.flags}.") buf = ensure_contiguous_ndarray(buf, flatten=flatten) # do compression return _zfpy.compress_numpy( buf, write_header=True, **self.compression_kwargs ) def decode(self, buf, out=None): # normalise inputs buf = ensure_bytes(buf) if out is not None: out = ensure_contiguous_ndarray(out) # do decompression dec = _zfpy.decompress_numpy(buf) # handle destination if out is not None: return ndarray_copy(dec, out) else: return dec def __repr__(self): r = "%s(mode=%r, tolerance=%s, rate=%s, precision=%s)" % ( type(self).__name__, self.mode, self.tolerance, self.rate, self.precision, ) return r
StarcoderdataPython
367956
from Traceroute import Traceroute from datetime import datetime import bases import detector import sys import parameters as param def main(hitlist, numCortes, tamanhoJanela, iface = None, source = None): conjuntoBase = [x for x in bases.main(hitlist, iface, source) if not x[param.INCOMPLETE]] cortesNaJanela = [] numCortesJanela = 0 while True: for rota in conjuntoBase: res = bases.measure(rota[param.DESTINATION], iface, source) corte = detector.Detectar(rota[param.ROUTE], res[param.ROUTE]) cortesNaJanela.append(corte) if corte is not None: print("Corte; %s; %s;" % (rota[param.DESTINATION], corte)) numCortesJanela += 1 if numCortesJanela >= numCortes: print("Hijack; %s;" % datetime.utcnow()) if len(cortesNaJanela) == tamanhoJanela: removido = cortesNaJanela.pop(0) if removido is not None: numCortesJanela -= 1 if __name__ == "__main__": print(sys.argv) if len(sys.argv) == 4: main(sys.argv[1], int(sys.argv[2]), int(sys.argv[3])) elif len(sys.argv) == 6: main(sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), sys.argv[4], sys.argv[5])
StarcoderdataPython
6445746
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2019, AGB & pysat team # Full license can be found in License.md #----------------------------------------------------------------------------- """ Routines to extract observational-style data from model output Routines -------- satellite_view_through_model extract_modelled_observations """ from __future__ import absolute_import from __future__ import unicode_literals import numpy as np import pandas as pds import scipy.interpolate as interpolate import pysat.utils as pyutils import pysatModelUtils as pysat_mu # Needs a better name, Jeff are you using this anywhere? def satellite_view_through_model(obs, mod, obs_coords, mod_dat_names): """Interpolate model values onto satellite orbital path. Parameters ---------- obs : pysat.Instrument object Instrument object with observational data mod : pysat.Instrument object Instrument object with modelled data obs_coords : array-like List of variable names containing the observational data coordinates at which the model data will be interpolated mod_dat_names : array-like List of model data output variable names to interpolate Notes ----- Updates the obs Instrument with interpolated data from the mod Instrument """ # Ensure the coordinate and data variable names are array-like obs_coords = np.asarray(obs_coords) mod_dat_names = np.asarray(mod_dat_names) # Create input array using observational data's time/position # This needs to be changed, pretty sure it doesn't work for xarray data pysat_mu.logger.debug("the coordinate data section needs to be fixed") coords = [obs.data[cc] for cc in obs_coords] coords.insert(0, obs.index.values.astype(int)) obs_pts = [inp for inp in zip(*coords)] # what is this doing? # Interpolate each model data value onto the observations time and location for label in mod_dat_names: points = [mod.data.coords[dim].values if dim != 'time' else mod.data.coords[dim].values.astype(int) for dim in mod[label].dims] interp_val = interpolate.RegularGridInterpolator(points, mod[label].values, bounds_error=False, fill_value=None) obs[''.join(('model_', label))] = interp_val(obs_pts) # Update the observation's meta data pysat_mu.logger.debug("Missing meta data update") return def extract_modelled_observations(inst=None, model=None, inst_name=[], mod_name=[], mod_datetime_name=None, mod_time_name=None, mod_units=[], sel_name=None, method='linear', model_label='model'): """Extracts instrument-aligned data from a modelled data set Parameters ---------- inst : pysat.Instrument instance instrument object for which modelled data will be extracted model : xarray Dataset modelled data set inst_name : list of strings list of names of the data series to use for determing instrument location mod_name : list of strings list of names of the data series to use for determing model locations in the same order as inst_name. These must make up a regular grid. mod_datetime_name : string Name of the data series in the model Dataset containing datetime info mod_time_name : string Name of the time coordinate in the model Dataset mod_units : list of strings units for each of the mod_name location attributes. Currently supports: rad/radian(s), deg/degree(s), h/hr(s)/hour(s), m, km, and cm sel_name : list of strings or NoneType list of names of modelled data indices to append to instrument object, or None to append all modelled data (default=None) method : string Interpolation method. Supported are 'linear', 'nearest', and 'splinef2d'. The last is only supported for 2D data and is not recommended here. (default='linear') model_label : string name of model, used to identify interpolated data values in instrument (default="model") Returns ------- added_names : list of strings list of names of modelled data added to the instrument Notes -------- For best results, select clean instrument data after alignment with model """ # Test input if inst is None: raise ValueError('Must provide a pysat instrument object') if model is None: raise ValueError('Must provide modelled data') if mod_datetime_name is None: raise ValueError('Need datetime key for model datasets') if mod_time_name is None: raise ValueError('Need time coordinate name for model datasets') if len(inst_name) == 0: estr = 'Must provide instrument location attribute names as a list' raise ValueError(estr) if len(inst_name) != len(mod_name): estr = 'Must provide the same number of instrument and model ' estr += 'location attribute names as a list' raise ValueError(estr) if len(mod_name) != len(mod_units): raise ValueError('Must provide units for each model location ' + 'attribute') inst_scale = np.ones(shape=len(inst_name), dtype=float) for i, ii in enumerate(inst_name): if ii not in list(inst.data.keys()): raise ValueError('Unknown instrument location index ' + '{:}'.format(ii)) inst_scale[i] = pyutils.scale_units(mod_units[i], inst.meta.data.units[ii]) # Determine which data to interpolate and initialize the interpolated # output if sel_name is None: sel_name = list(model.data_vars.keys()) for mi in mod_name: if mi in sel_name: sel_name.pop(sel_name.index(mi)) # Determine the model time resolution tm_sec = (np.array(model.data_vars[mod_datetime_name][1:]) - np.array(model.data_vars[mod_datetime_name][:-1])).min() tm_sec /= np.timedelta64(1, 's') ti_sec = (inst.index[1:] - inst.index[:-1]).min().total_seconds() min_del = tm_sec if tm_sec < ti_sec else ti_sec # Determine which instrument observations are within the model time # resolution of a model run mind = list() iind = list() for i, tt in enumerate(np.array(model.data_vars[mod_datetime_name])): del_sec = abs(tt - inst.index).total_seconds() if del_sec.min() <= min_del: iind.append(del_sec.argmin()) mind.append(i) # Determine the model coordinates closest to the satellite track interp_data = dict() interp_shape = inst.index.shape if inst.pandas_format else \ inst.data.data_vars.items()[0][1].shape inst_coord = {kk: getattr(inst.data, inst_name[i]).values * inst_scale[i] for i, kk in enumerate(mod_name)} for i, ii in enumerate(iind): # Cycle through each model data type, since it may not depend on # all the dimensions for mdat in sel_name: # Determine the dimension values dims = list(model.data_vars[mdat].dims) ndim = model.data_vars[mdat].data.shape indices = {mod_time_name: mind[i]} # Construct the data needed for interpolation values = model[indices][mdat].data points = [model.coords[kk].data for kk in dims if kk in mod_name] get_coords = True if len(points) > 0 else False idims = 0 while get_coords: if inst.pandas_format: # This data iterates only by time xout = ii xi = [inst_coord[kk][ii] for kk in dims if kk in mod_name] get_coords = False else: # This data may have additional dimensions if idims == 0: # Determine the number of dimensions idims = len(inst.data.coords) idim_names = inst.data.coords.keys()[1:] # Find relevent dimensions for cycling and slicing ind_dims = [k for k, kk in enumerate(inst_name) if kk in idim_names] imod_dims = [k for k in ind_dims if mod_name[k] in dims] ind_dims = [inst.data.coords.keys().index(inst_name[k]) for k in imod_dims] # Set the number of cycles icycles = 0 ncycles = sum([len(inst.data.coords[inst_name[k]]) for k in imod_dims]) cinds = np.zeros(shape=len(imod_dims), dtype=int) # Get the instrument coordinate for this cycle if icycles < ncycles or icycles == 0: ss = [ii if k == 0 else 0 for k in range(idims)] se = [ii + 1 if k == 0 else len(inst.data.coords[idim_names[k-1]]) for k in range(idims)] xout = [cinds[ind_dims.index(k)] if k in ind_dims else slice(ss[k], se[k]) for k in range(idims)] xind = [cinds[ind_dims.index(k)] if k in ind_dims else ss[k] for k in range(idims)] xout = tuple(xout) xind = tuple(xind) xi = list() for kk in dims: if kk in mod_name: # This is the next instrument coordinate k = mod_name.index(kk) if k in imod_dims: # This is an xarray coordiante xi.append(inst_coord[kk][cinds[k]]) else: # This is an xarray variable xi.append(inst_coord[kk][xind]) # Cycle the indices if len(cinds) > 0: k = 0 cinds[k] += 1 while cinds[k] > \ inst.data.coords.dims[inst_name[imod_dims[k]]]: k += 1 if k < len(cinds): cinds[k-1] = 0 cinds[k] += 1 else: break icycles += 1 # If we have cycled through all the coordinates for this # time, move onto the next time if icycles >= ncycles: get_coords = False # Interpolate the desired value try: yi = interpolate.interpn(points, values, xi, method=method) except ValueError as verr: if str(verr).find("requested xi is out of bounds") > 0: # This is acceptable, pad the interpolated data with # NaN print("Warning: {:} for ".format(verr) + "{:s} data at {:}".format(mdat, xi)) yi = [np.nan] else: raise ValueError(verr) # Save the output attr_name = "{:s}_{:s}".format(model_label, mdat) if attr_name not in interp_data.keys(): interp_data[attr_name] = np.full(shape=interp_shape, fill_value=np.nan) interp_data[attr_name][xout] = yi[0] # Test and ensure the instrument data doesn't already have the interpolated # data. This should not happen if np.any([mdat in inst.data.keys() for mdat in interp_data.keys()]): raise ValueError("instrument object already contains model data") # Update the instrument object and attach units to the metadata for mdat in interp_data.keys(): attr_name = mdat.split("{:s}_".format(model_label))[-1] inst.meta[mdat] = {inst.units_label: model.data_vars[attr_name].units} if inst.pandas_format: inst[mdat] = pds.Series(interp_data[mdat], index=inst.index) else: inst.data = inst.data.assign(interp_key=(inst.data.coords.keys(), interp_data[mdat])) inst.data.rename({"interp_key": mdat}, inplace=True) return interp_data.keys()
StarcoderdataPython
9640020
#!/usr/local/bin/python3 # on mac: brew install python3 # # helper script to update all version numbers (mac, windows, frontend) import sys, os, os.path, re pj = os.path.join def match_replace_group(s, m, group, replacement): b = m.start(1) e = m.end(1) return s[:b] + replacement + s[e:] def replace_string(s, ver): r = re.compile('''<string>([\d\.^<]+)</string>''', re.MULTILINE | re.DOTALL | re.IGNORECASE) m = r.search(s) return match_replace_group(s, m, 1, ver) def is_plist_ver_key(s): if "CFBundleShortVersionString" in s: return True return "CFBundleVersion" in s def update_mac_ver(ver): path = pj("mac", "dbHero", "Info.plist") lines = open(path, "r").readlines() res = [] ver_is_next = False for l in lines: if ver_is_next: l = replace_string(l, ver) ver_is_next = False else: ver_is_next = is_plist_ver_key(l) res.append(l) s = "".join(res) open(path, "w").write(s) def update_win_ver_in_file(ver, path): while len(ver.split(".")) < 4: ver += ".0" s = open(path).read() r = re.compile('''AssemblyVersion\(\"([\d\.^"]+)"''', re.MULTILINE | re.DOTALL | re.IGNORECASE) m = r.search(s) s = match_replace_group(s, m, 1, ver) r = re.compile('''AssemblyFileVersion\(\"([\d\.^"]+)"''', re.MULTILINE | re.DOTALL | re.IGNORECASE) m = r.search(s) s = match_replace_group(s, m, 1, ver) s = s.replace("\n", "\r\n") open(path, "w").write(s) def update_win_ver(ver): path = pj("win", "dbhero", "Properties", "AssemblyInfo.cs") update_win_ver_in_file(ver, path) path = pj("win-cef", "dbhero", "Properties", "AssemblyInfo.cs") update_win_ver_in_file(ver, path) def update_frontend_ver(ver): path = pj("s", "index.html") s = open(path).read() r = re.compile('''gVersionNumber = \"([\d\.^"]+)";''', re.MULTILINE | re.DOTALL | re.IGNORECASE) m = r.search(s) s = match_replace_group(s, m, 1, ver) open(path, "w").write(s) def usage_and_exit(): print("usage: python ./scripts/update_ver.py ${ver}") sys.exit(1) def fatal(msg): print(msg) sys.exit(1) def is_num(s): try: n = int(s) return True except: return False def verify_ver(ver): parts = ver.split(".") if len(parts) > 4: fatal("'%s' is not a valid version number (too manu parts)" % ver) for part in parts: if not is_num(part): fatal("'%s' is not a valid version number" % ver) def main(): if len(sys.argv) != 2: usage_and_exit() ver = sys.argv[1].rstrip(".0") verify_ver(ver) update_mac_ver(ver) update_win_ver(ver) update_frontend_ver(ver) print("updated versions to '%s'!" % ver) if __name__ == "__main__": main()
StarcoderdataPython
12840211
import emcee import numpy as np from matplotlib import pyplot as plt from remu import binning, likelihood, likelihood_utils, plotting with open("../01/reco-binning.yml") as f: reco_binning = binning.yaml.full_load(f) with open("../01/optimised-truth-binning.yml") as f: truth_binning = binning.yaml.full_load(f) reco_binning.fill_from_csv_file("../00/real_data.txt") data = reco_binning.get_entries_as_ndarray() data_model = likelihood.PoissonData(data) response_matrix = "../03/response_matrix.npz" matrix_predictor = likelihood.ResponseMatrixPredictor(response_matrix) calc = likelihood.LikelihoodCalculator(data_model, matrix_predictor) truth_binning.fill_from_csv_file("../00/modelA_truth.txt") modelA = truth_binning.get_values_as_ndarray() modelA /= np.sum(modelA) modelA_shape = likelihood.TemplatePredictor([modelA]) calcA = calc.compose(modelA_shape) samplerA = likelihood_utils.emcee_sampler(calcA) guessA = likelihood_utils.emcee_initial_guess(calcA) state = samplerA.run_mcmc(guessA, 100) chain = samplerA.get_chain(flat=True) with open("chain_shape.txt", "w") as f: print(chain.shape, file=f) fig, ax = plt.subplots() ax.hist(chain[:, 0]) ax.set_xlabel("model A weight") fig.savefig("burn_short.png") with open("burn_short_tau.txt", "w") as f: try: tau = samplerA.get_autocorr_time() print(tau, file=f) except emcee.autocorr.AutocorrError as e: print(e, file=f) samplerA.reset() state = samplerA.run_mcmc(guessA, 200 * 50) chain = samplerA.get_chain(flat=True) with open("burn_long_tau.txt", "w") as f: try: tau = samplerA.get_autocorr_time() print(tau, file=f) except emcee.autocorr.AutocorrError as e: print(e, file=f) fig, ax = plt.subplots() ax.hist(chain[:, 0]) ax.set_xlabel("model A weight") fig.savefig("burn_long.png") samplerA.reset() state = samplerA.run_mcmc(state, 100 * 50) chain = samplerA.get_chain(flat=True) with open("tauA.txt", "w") as f: try: tau = samplerA.get_autocorr_time() print(tau, file=f) except emcee.autocorr.AutocorrError as e: print(e, file=f) fig, ax = plt.subplots() ax.hist(chain[:, 0]) ax.set_xlabel("model A weight") fig.savefig("weightA.png") truth, _ = modelA_shape(chain) truth.shape = (np.prod(truth.shape[:-1]), truth.shape[-1]) pltr = plotting.get_plotter(truth_binning) pltr.plot_array(truth, stack_function=np.median, label="Post. median", hatch=None) pltr.plot_array(truth, stack_function=0.68, label="Post. 68%", scatter=0) pltr.legend() pltr.savefig("truthA.png") reco, _ = calcA.predictor(chain) reco.shape = (np.prod(reco.shape[:-1]), reco.shape[-1]) pltr = plotting.get_plotter(reco_binning) pltr.plot_array(reco, stack_function=np.median, label="Post. median", hatch=None) pltr.plot_array(reco, stack_function=0.68, label="Post. 68%") pltr.plot_array(data, label="Data", hatch=None, linewidth=2) pltr.legend() pltr.savefig("recoA.png") truth_binning.reset() truth_binning.fill_from_csv_file("../00/modelB_truth.txt") modelB = truth_binning.get_values_as_ndarray() modelB /= np.sum(modelB) combined = likelihood.TemplatePredictor([modelA, modelB]) calcC = calc.compose(combined) samplerC = likelihood_utils.emcee_sampler(calcC) guessC = likelihood_utils.emcee_initial_guess(calcC) state = samplerC.run_mcmc(guessC, 200 * 50) chain = samplerC.get_chain(flat=True) with open("combined_chain_shape.txt", "w") as f: print(chain.shape, file=f) with open("burn_combined_tau.txt", "w") as f: try: tau = samplerC.get_autocorr_time() print(tau, file=f) except emcee.autocorr.AutocorrError as e: print(e, file=f) samplerC.reset() state = samplerC.run_mcmc(state, 100 * 50) chain = samplerC.get_chain(flat=True) with open("combined_tau.txt", "w") as f: try: tau = samplerC.get_autocorr_time() print(tau, file=f) except emcee.autocorr.AutocorrError as e: print(e, file=f) fig, ax = plt.subplots() ax.hist2d(chain[:, 0], chain[:, 1]) ax.set_xlabel("model A weight") ax.set_ylabel("model B weight") fig.savefig("combined.png") fig, ax = plt.subplots() ax.hist(np.sum(chain, axis=-1)) ax.set_xlabel("model A weight + model B weight") fig.savefig("total.png")
StarcoderdataPython
327231
import unittest from src.assignments.Assignment9.invoice import Invoice from src.assignments.Assignment9.invoice_item import InvoiceItem class Test_Assign8(unittest.TestCase): invoice_items = [] #list of Invoice Item instance objects def test_invoice_item_extended_cost_w_qty_10_cost_5(self): ''' Create an Invoice item instance with argument values: 'Widget1', 10, and 5 The extended cost result should be 50; ''' invoice_item = InvoiceItem('Widget1', 10, 5) #create the assert code self.assertEqual(50, invoice_item.get_extended_cost()) def test_invoice__w_3_invoice_items(self): ''' Create an Invoice instance with argument values: 'ABC company', '03282018' Three invoice items as follows argument values: 'Widget1', 10, and 5 'Widget2', 7, and 8 'Widget3', 20, and 10 Get Extended result should be 50 + 56 + 200 = 306 ''' invoice = Invoice('ABC Company', '03282018') invoice.add_invoice_item(InvoiceItem('Widget1', 10, 5)) invoice.add_invoice_item(InvoiceItem('Widget2', 7, 8)) invoice.add_invoice_item(InvoiceItem('Widget3', 20, 10)) #create the assert equal code self.assertEqual(306, invoice.get_invoice_total()) #if __name__ == '__main__': # unittest.main(verbosity=2)
StarcoderdataPython
8047322
import fileinput import numpy as np from numpy.core.numeric import count_nonzero def main(): folds: list[tuple[str, int]] = [] dots: list[tuple[int, int]] = [] max_x = 0 max_y = 0 for line in fileinput.input(): line = line.strip() if not line: continue if line.startswith('fold'): direction = line[11] position = int(line.split('=')[1]) folds.append((direction, position)) else: x, y = map(int, line.split(',')) dots.append((x,y)) for fold in folds: if fold[0] == 'x': max_x = max(max_x, fold[1]*2) else: max_y = max(max_y, fold[1]*2) # NB: This is going to render transposed from the figures on the website. dotfield = np.zeros((max_x+1, max_y+1), dtype=np.int0) for x,y in dots: dotfield[x,y] = 1 # Do the first fold. for fold_dir, fold_pos in folds: if fold_dir == 'x': # the part we'll be folding "onto": hold_field = dotfield[:fold_pos] # the part we'll flip and fold: fold_field = np.flipud(dotfield[fold_pos+1:]) else: hold_field = dotfield[:, :fold_pos] fold_field = np.fliplr(dotfield[:, fold_pos+1:]) # Do an OR to see where the dots shine through: dotfield = np.logical_or(hold_field, fold_field).astype(int) # print(np.array2string(np.transpose(dotfield), max_line_width=250)) # Printing it as an int array doesn't look great. Let's do ASCII art instead. for row in np.transpose(dotfield): for val in row: print('#' if val else ' ', end='') print() if __name__ == '__main__': main()
StarcoderdataPython
6627314
<gh_stars>0 # -*- coding: utf-8 -*- # 获取客户端引擎API模块 import client.extraClientApi as clientApi # 获取客户端system的基类ClientSystem ClientSystem = clientApi.GetClientSystemCls() # 在modMain中注册的Client System类 class TutorialClientSystem(ClientSystem): # 客户端System的初始化函数 def __init__(self, namespace, systemName): # 首先初始化TutorialClientSystem的基类ClientSystem super(TutorialClientSystem, self).__init__(namespace, systemName) print "==== TutorialClientSystem Init ====" # 函数名为Destroy才会被调用,在这个System被引擎回收的时候会调这个函数来销毁一些内容 def Destroy(self): pass
StarcoderdataPython
11392867
<gh_stars>1-10 # Copyright 2011,2012,2013 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Implementation of an OpenFlow flow table """ from libopenflow_01 import * from pox.lib.revent import * from pox.core import core import time import math # FlowTable Entries: # match - ofp_match (13-tuple) # counters - hash from name -> count. May be stale # actions - ordered list of ofp_action_*s to apply for matching packets class TableEntry (object): """ Models a flow table entry, with a match, actions, and options/flags/counters. Note: The current time can either be specified explicitely with the optional 'now' parameter or is taken from time.time() """ def __init__ (self, priority=OFP_DEFAULT_PRIORITY, cookie=0, idle_timeout=0, hard_timeout=0, flags=0, match=ofp_match(), actions=[], buffer_id=None, now=None): """ Initialize table entry """ if now is None: now = time.time() self.created = now self.last_touched = self.created self.byte_count = 0 self.packet_count = 0 self.priority = priority self.cookie = cookie self.idle_timeout = idle_timeout self.hard_timeout = hard_timeout self.flags = flags self.match = match self.actions = actions self.buffer_id = buffer_id @staticmethod def from_flow_mod (flow_mod): return TableEntry(priority=flow_mod.priority, cookie=flow_mod.cookie, idle_timeout=flow_mod.idle_timeout, hard_timeout=flow_mod.hard_timeout, flags=flow_mod.flags, match=flow_mod.match, actions=flow_mod.actions, buffer_id=flow_mod.buffer_id) def to_flow_mod (self, flags=None, **kw): if flags is None: flags = self.flags return ofp_flow_mod(priority=self.priority, cookie=self.cookie, match=self.match, idle_timeout=self.idle_timeout, hard_timeout=self.hard_timeout, actions=self.actions, buffer_id=self.buffer_id, flags=flags, **kw) @property def effective_priority (self): """ Exact matches effectively have an "infinite" priority """ return self.priority if self.match.is_wildcarded else (1<<16) + 1 def is_matched_by (self, match, priority=None, strict=False, out_port=None): """ Tests whether a given match object matches this entry Used for, e.g., flow_mod updates If out_port is any value besides None, the the flow entry must contain an output action to the specified port. """ match_a = lambda a: isinstance(a, ofp_action_output) and a.port == out_port port_matches = (out_port is None) or any(match_a(a) for a in self.actions) if strict: return port_matches and self.match == match and self.priority == priority else: return port_matches and match.matches_with_wildcards(self.match) def touch_packet (self, byte_count, now=None): """ Updates information of this entry based on encountering a packet. Updates both the cumulative given byte counts of packets encountered and the expiration timer. """ if now is None: now = time.time() self.byte_count += byte_count self.packet_count += 1 self.last_touched = now def is_idle_timed_out (self, now=None): if now is None: now = time.time() if self.idle_timeout > 0: if (now - self.last_touched) > self.idle_timeout: return True return False def is_hard_timed_out (self, now=None): if now is None: now = time.time() if self.hard_timeout > 0: if (now - self.created) > self.hard_timeout: return True return False def is_expired (self, now=None): """ Tests whether this flow entry is expired due to its idle or hard timeout """ if now is None: now = time.time() return self.is_idle_timed_out(now) or self.is_hard_timed_out(now) def __str__ (self): return type(self).__name__ + "\n " + self.show() def __repr__ (self): return "TableEntry(" + self.show() + ")" def show (self): outstr = '' outstr += "priority=%s, " % self.priority outstr += "cookie=%x, " % self.cookie outstr += "idle_timeout=%d, " % self.idle_timeout outstr += "hard_timeout=%d, " % self.hard_timeout outstr += "match=%s, " % self.match outstr += "actions=%s, " % repr(self.actions) outstr += "buffer_id=%s" % str(self.buffer_id) return outstr def flow_stats (self, now=None): if now is None: now = time.time() dur_nsec,dur_sec = math.modf(now - self.created) return ofp_flow_stats(match=self.match, duration_sec=int(dur_sec), duration_nsec=int(dur_nsec * 1e9), priority=self.priority, idle_timeout=self.idle_timeout, hard_timeout=self.hard_timeout, cookie=self.cookie, packet_count=self.packet_count, byte_count=self.byte_count, actions=self.actions) def to_flow_removed (self, now=None, reason=None): #TODO: Rename flow_stats to to_flow_stats and refactor? if now is None: now = time.time() dur_nsec,dur_sec = math.modf(now - self.created) fr = ofp_flow_removed() fr.match = self.match fr.cookie = self.cookie fr.priority = self.priority fr.reason = reason fr.duration_sec = int(dur_sec) fr.duration_nsec = int(dur_nsec * 1e9) fr.idle_timeout = self.idle_timeout fr.hard_timeout = self.hard_timeout fr.packet_count = self.packet_count fr.byte_count = self.byte_count return fr class FlowTableModification (Event): def __init__ (self, added=[], removed=[], reason=None): Event.__init__(self) self.added = added self.removed = removed # Reason for modification. # Presently, this is only used for removals and is either one of OFPRR_x, # or None if it does not correlate to any of the items in the spec. self.reason = reason class FlowTable (EventMixin): """ General model of a flow table. Maintains an ordered list of flow entries, and finds matching entries for packets and other entries. Supports expiration of flows. """ _eventMixin_events = set([FlowTableModification]) def __init__ (self): EventMixin.__init__(self) # Table is a list of TableEntry sorted by descending effective_priority. self._table = [] def _dirty (self): """ Call when table changes """ pass @property def entries (self): return self._table def __len__ (self): return len(self._table) def add_entry (self, entry): assert isinstance(entry, TableEntry) #self._table.append(entry) #self._table.sort(key=lambda e: e.effective_priority, reverse=True) # Use binary search to insert at correct place # This is faster even for modest table sizes, and way, way faster # as the tables grow larger. priority = entry.effective_priority table = self._table low = 0 high = len(table) while low < high: middle = (low + high) // 2 if priority >= table[middle].effective_priority: high = middle continue low = middle + 1 table.insert(low, entry) self._dirty() self.raiseEvent(FlowTableModification(added=[entry])) def remove_entry (self, entry, reason=None): assert isinstance(entry, TableEntry) self._table.remove(entry) self._dirty() self.raiseEvent(FlowTableModification(removed=[entry], reason=reason)) def matching_entries (self, match, priority=0, strict=False, out_port=None): entry_match = lambda e: e.is_matched_by(match, priority, strict, out_port) return [ entry for entry in self._table if entry_match(entry) ] def flow_stats (self, match, out_port=None, now=None): mc_es = self.matching_entries(match=match, strict=False, out_port=out_port) return [ e.flow_stats(now) for e in mc_es ] def aggregate_stats (self, match, out_port=None): mc_es = self.matching_entries(match=match, strict=False, out_port=out_port) packet_count = 0 byte_count = 0 flow_count = 0 for entry in mc_es: packet_count += entry.packet_count byte_count += entry.byte_count flow_count += 1 return ofp_aggregate_stats(packet_count=packet_count, byte_count=byte_count, flow_count=flow_count) def _remove_specific_entries (self, flows, reason=None): #for entry in flows: # self._table.remove(entry) #self._table = [entry for entry in self._table if entry not in flows] if not flows: return self._dirty() remove_flows = set(flows) i = 0 while i < len(self._table): entry = self._table[i] if entry in remove_flows: del self._table[i] remove_flows.remove(entry) if not remove_flows: break else: i += 1 assert len(remove_flows) == 0 self.raiseEvent(FlowTableModification(removed=flows, reason=reason)) def remove_expired_entries (self, now=None): idle = [] hard = [] if now is None: now = time.time() for entry in self._table: if entry.is_idle_timed_out(now): idle.append(entry) elif entry.is_hard_timed_out(now): hard.append(entry) self._remove_specific_entries(idle, OFPRR_IDLE_TIMEOUT) self._remove_specific_entries(hard, OFPRR_HARD_TIMEOUT) def remove_matching_entries (self, match, priority=0, strict=False, out_port=None, reason=None): remove_flows = self.matching_entries(match, priority, strict, out_port) self._remove_specific_entries(remove_flows, reason=reason) return remove_flows def entry_for_packet (self, packet, in_port): """ Finds the flow table entry that matches the given packet. Returns the highest priority flow table entry that matches the given packet on the given in_port, or None if no matching entry is found. """ packet_match = ofp_match.from_packet(packet, in_port, spec_frags = True) for entry in self._table: if entry.match.matches_with_wildcards(packet_match, consider_other_wildcards=False): return entry return None def check_for_overlapping_entry (self, in_entry): #FELIPE TOMM - TCC #Esta funcao verifica se ja existe uma flow identica. #Sera essa minha funcao base? log = core.getLogger() log.debug("Debug TCC - Flow Table: Iniciando analise de conflito") """ Tests if the input entry overlaps with another entry in this table. Returns true if there is an overlap, false otherwise. Since the table is sorted, there is only a need to check a certain portion of it. """ #NOTE: Assumes that entries are sorted by decreasing effective_priority #NOTE: Ambiguous whether matching should be based on effective_priority # or the regular priority. Doing it based on effective_priority # since that's what actually affects packet matching. #NOTE: We could improve performance by doing a binary search to find the # right priority entries. priority = in_entry.effective_priority for e in self._table: if e.effective_priority < priority: break elif e.effective_priority > priority: continue else: if e.is_matched_by(in_entry.match) or in_entry.is_matched_by(e.match): print ("Debug TCC - Flow Table: O Flow: ja existe.") return True return False
StarcoderdataPython
9735612
#!/usr/bin/env python2 # # dockbar.py # # Example program places a coloured bar across the top of the # current monitor # # demonstrates # # (a) creating the bar as an undecorated "dock" window # (b) setting its colour # (c) getting the number of monitors and their sizes # # JL 20140512 import gtk window = gtk.Window() # the screen contains all monitors screen = window.get_screen() print "screen size: %d x %d" % (gtk.gdk.screen_width(),gtk.gdk.screen_height()) # collect data about each monitor monitors = [] nmons = screen.get_n_monitors() print "there are %d monitors" % nmons for m in range(nmons): mg = screen.get_monitor_geometry(m) print "monitor %d: %d x %d" % (m,mg.width,mg.height) monitors.append(mg) # current monitor curmon = screen.get_monitor_at_window(screen.get_active_window()) x, y, width, height = monitors[curmon] print "monitor %d: %d x %d (current)" % (curmon,width,height)
StarcoderdataPython
9710522
<reponame>elraro/tweetfs-release # unpack a dict into a dir or file from bitstring import BitArray import bson from os.path import exists from os import chdir, chmod, mkdir, tmpfile from util import is_file, is_dir, assert_type def fatal_if_exists(name, kind): '''Fail if a file exists.''' if exists(name): raise RuntimeError('FATAL: %s "%s" already exists' % (kind, name)) def deserialize(bits): assert_type(bits, BitArray, 'deserialize') s = bits.tobytes() assert_type(s, str, 'deserialize') # print 'serialized payload from twitter: %s bytes -> %s bytes' % \ # (len(bits) / 8.0, len(s)) print 'serialized payload from twitter: %s bytes' % len(s) x = bson.loads(s) if not is_file(x) and not is_dir(x): raise ArgumentError('FATAL: bad type "%s"' % x['type']) return x def unpack(payload, tweet_id, downloader, concealer, name_override=None, recur=False): assert_type(payload, dict, 'unpack') if is_file(payload): data, name, perms = payload['data'], payload['name'], int(payload['perms']) if name_override: name = name_override fatal_if_exists(name, 'file') print 'unpacked "%s" from tweet_id %s' % (name, tweet_id) write_file(name, data) print 'permissions: %s' % perms chmod(name, perms) print '' elif is_dir(payload): ids, name, perms = payload['ids'], payload['name'], int(payload['perms']) if name_override: name = name_override fatal_if_exists(name, 'directory') print 'unpacked "%s" with child tweet_ids %s' % (name, ids) write_dir(name) print 'permissions: %s' % perms chmod(name, perms) print '' if recur: chdir(name) for tweet_id in ids: payload = downloader(tweet_id) payload = concealer.reveal(payload) payload = deserialize(payload) unpack(payload, tweet_id, downloader, concealer, name_override=None, recur=recur) chdir('..') def write_file(name, data): '''create file on filesystem name + bits -> fd''' fatal_if_exists(name, 'file') print 'creating "%s" (%s bytes)...' % (name, len(data)), f = open(name, 'wb') # simple. TODO: metadata support f.write(data) f.close() print 'ok' def write_dir(name): '''create dir on filesystem''' fatal_if_exists(name, 'directory') print ('creating directory "%s"...' % name), mkdir(name) # uses umask and current working dir print 'ok'
StarcoderdataPython
6417063
<gh_stars>0 # Copyright 2015 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. # ============================================================================== """A deep MNIST classifier using convolutional layers. See extensive documentation at https://www.tensorflow.org/get_started/mnist/pros """ import tensorflow as tf from preprocess import * from PIL import Image NUM_POOLS = 5 BN_EPSILON = 0.001 batch_size = 50 learning_rate = 5e-3 epochs = 30000 def deepnn(x, phase_train, keep_prob): '''Convolution -> Batch Normalization -> Relu Layer''' with tf.name_scope('conv1'): W_conv1 = weight_variable([3, 3, 3, 64]) b_conv1 = bias_variable([64]) h_conv1 = conv_bn_relu(x, W_conv1, b_conv1, 64, phase_train) with tf.name_scope('dropout1'): h_conv1_drop = tf.nn.dropout(h_conv1, keep_prob) '''Convolution -> Batch Normalization -> Relu Layer''' with tf.name_scope('conv2'): W_conv2 = weight_variable([3, 3, 64, 128]) b_conv2 = bias_variable([128]) h_conv2 = conv_bn_relu(h_conv1_drop, W_conv2, b_conv2, 128, phase_train) '''Pooling layer - Downsamples image by 50%''' with tf.name_scope('pool1'): h_pool1 = max_pool_2x2(h_conv2) with tf.name_scope('dropout2'): h_pool1_drop = tf.nn.dropout(h_pool1, keep_prob) '''Convolution -> Batch Normalization -> Relu Layer''' with tf.name_scope('conv3'): W_conv3 = weight_variable([3, 3, 128, 128]) b_conv3 = bias_variable([128]) h_conv3 = conv_bn_relu(h_pool1_drop, W_conv3, b_conv3, 128, phase_train) with tf.name_scope('dropout3'): h_conv3_drop = tf.nn.dropout(h_conv3, keep_prob) '''Convolution -> Pool -> Batch Normalization -> Relu Layer''' #Pooling downsamples by % with tf.name_scope('conv4'): W_conv4 = weight_variable([3, 3, 128, 128]) b_conv4 = bias_variable([128]) h_conv4 = conv2d(h_conv3_drop, W_conv4) + b_conv4 with tf.name_scope('pool2'): h_pool2 = tf.nn.relu(batch_normalization_layer(max_pool_2x2(h_conv4), 128, phase_train)) with tf.name_scope('dropout4'): h_pool2_drop = tf.nn.dropout(h_pool2, keep_prob) '''Convolution -> Batch Normalization -> Relu Layer''' with tf.name_scope('conv5'): W_conv5 = weight_variable([3, 3, 128, 128]) b_conv5 = bias_variable([128]) h_conv5 = conv_bn_relu(h_pool2_drop, W_conv5, b_conv5, 128, phase_train) with tf.name_scope('dropout5'): h_conv5_drop = tf.nn.dropout(h_conv5, keep_prob) '''Pooling layer - Downsamples by 50%''' with tf.name_scope('pool3'): h_pool3 = max_pool_2x2(h_conv5_drop) '''Convolution -> Batch Normalization -> Relu Layer''' with tf.name_scope('conv6'): W_conv6= weight_variable([3, 3, 128, 128]) b_conv6 = bias_variable([128]) h_conv6 = conv_bn_relu(h_pool3, W_conv6, b_conv6, 128, phase_train) with tf.name_scope('dropout6'): h_conv6_drop = tf.nn.dropout(h_conv6, keep_prob) '''Convolution -> Batch Normalization -> Relu Layer''' with tf.name_scope('conv7'): W_conv7 = weight_variable([1, 1, 128, 128]) b_conv7 = bias_variable([128]) h_conv7 = conv_bn_relu(h_conv6_drop, W_conv7, b_conv7, 128, phase_train) with tf.name_scope('dropout7'): h_conv7_drop = tf.nn.dropout(h_conv7, keep_prob) '''Pooling layer - Downsamples by %''' with tf.name_scope('pool4'): h_pool4 = max_pool_2x2(h_conv7_drop) with tf.name_scope('dropout8'): h_pool4_drop = tf.nn.dropout(h_pool4, keep_prob) '''Convolution -> Batch Normalization -> Relu Layer''' with tf.name_scope('conv8'): W_conv8 = weight_variable([3, 3, 128, 128]) b_conv8 = bias_variable([128]) h_conv8 = conv_bn_relu(h_pool4_drop, W_conv8, b_conv8, 128, phase_train) '''Pooling layer - downsamples by 50% ''' with tf.name_scope('pool5'): h_pool5 = max_pool_2x2(h_conv8) '''Fully connected layer''' with tf.name_scope('fc1'): W_fc1 = weight_variable([(IMAGE_SIZE/(2**NUM_POOLS)) *(IMAGE_SIZE/(2**NUM_POOLS)) * 128, 1024]) b_fc1 = bias_variable([1024]) h_pool5_flat = tf.reshape(h_pool5, [-1, (IMAGE_SIZE/(2**NUM_POOLS)) *(IMAGE_SIZE/(2**NUM_POOLS)) * 128]) #Flatten the 4D output of pool5 into a 2D tensor h_fc1 = tf.nn.relu(tf.matmul(h_pool5_flat, W_fc1) + b_fc1) with tf.name_scope('dropout10'): h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) '''Dot product layer''' with tf.name_scope('fc2'): W_fc2 = weight_variable([1024, 25]) b_fc2 = bias_variable([25]) y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2 return y_conv, keep_prob, phase_train '''Wrapper function for Convolution -> Batch Normalization -> ReLu Layers''' def conv_bn_relu(input, weight, bias, out_channel, phase_train): return tf.nn.relu(batch_normalization_layer(conv2d(input, weight) + bias, out_channel, phase_train)) '''Batch Normalization function''' def batch_normalization_layer(input_layer, dimension, phase_train): mean, variance = tf.nn.moments(input_layer, axes=[0, 1, 2]) beta = tf.Variable(tf.constant(0.0, shape = [dimension]), name ='beta', trainable=True) gamma = tf.Variable(tf.constant(1.0, shape = [dimension]), name='gamma', trainable=True) bn_layer = tf.nn.batch_normalization(input_layer, mean, variance, beta, gamma, BN_EPSILON) return bn_layer #Wrapper for Convlution function with input tensor x, filter size W, stride = 1 and SAME padding def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') #Wrapper for Pooling function with 2x2 kernal, stride = 2 and SAME padding def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME') #Creates a weight variable with shape = shape gaussian initialization def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.01) return tf.Variable(initial) #Creates bias variable with shape = shape and constant initiialization def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) def main(): #Load data using Preprocess.py train_x, vali_x, train_shapes, vali_shapes, train_y, vali_y = load_data() print "Data Loaded!" global learning_rate # Create the model x = tf.placeholder(tf.float32, [None, IMAGE_SIZE, IMAGE_SIZE, 3], name='input') y_ = tf.placeholder(tf.float32, [None, NUM_CLASSES], name='labels') keep_prob = tf.placeholder(tf.float32, name='keep_prob') phase_train = tf.placeholder(tf.bool, name='phase_train' ) learningrate = tf.placeholder(tf.float32, name='learning_rate') # Build the graph for the deep net y_conv, keep_prob, phase_train = deepnn(x, phase_train, keep_prob) #Loss function - Cross entropy with tf.name_scope('loss'): cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_,logits=y_conv) cross_entropy = tf.reduce_mean(cross_entropy) #Learning optimizer with tf.name_scope('adam_optimizer'): train_step = tf.train.AdamOptimizer(learningrate).minimize(cross_entropy) #Accuracy calculator with tf.name_scope('accuracy'): correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1)) correct_prediction = tf.cast(correct_prediction, tf.float32) accuracy = tf.reduce_mean(correct_prediction) #Returns the predicted class with tf.name_scope('final_answer'): final_answer = tf.argmax(y_conv, 1) #Tensorboard Summary Writing step = tf.Variable(0, trainable=False, name='step') ema1 = tf.train.ExponentialMovingAverage(0.0 , step) ema2 = tf.train.ExponentialMovingAverage(0.95, step) val_op = tf.group(step.assign_add(1), ema1.apply([cross_entropy, accuracy]), ema2.apply([cross_entropy, accuracy])) training_loss = ema1.average(cross_entropy) vali_accuracy = ema1.average(accuracy) training_loss_avg = ema2.average(cross_entropy) vali_accuracy_avg = ema2.average(accuracy) tf.summary.scalar('learning_rate' , learningrate) tf.summary.scalar('training loss' , training_loss) tf.summary.scalar('average training loss' , training_loss_avg) tf.summary.scalar('validation accuracy' , vali_accuracy) tf.summary.scalar('average validation accuracy', vali_accuracy_avg) merged = tf.summary.merge_all() #Saves GPU memory because tensorflow allocates entire gpu memory by default config = tf.ConfigProto() config.gpu_options.allow_growth = True config.gpu_options.per_process_gpu_memory_fraction = 0.5 #Initializes saver object for saving the model for later use without training saver = tf.train.Saver(var_list=tf.trainable_variables()) #Running tensorflow session with tf.Session(config = config) as sess: #Initialize variables sess.run(tf.global_variables_initializer()) #Initialize summary writer object summary_writer = tf.summary.FileWriter("./logs", sess.graph) #Start training for i in xrange(epochs): #Show accuracy and write summaries at set number of epochs if i % show_steps == 0: vali_batch_x, vali_batch_y = batch(batch_size, vali_x, vali_shapes, vali_y, 'vali') train_accuracy, summary, _ = sess.run([accuracy, merged, val_op], feed_dict=\ {x: vali_batch_x, y_: vali_batch_y, keep_prob: 1.0, phase_train:False, learningrate : learning_rate}) summary_writer.add_summary(summary, i) print('step %d, training accuracy %g' % (i, train_accuracy)) #Training batch_x, batch_y = batch(batch_size, train_x, train_shapes, train_y) train_step.run(feed_dict={x: batch_x, y_: batch_y, keep_prob: 0.5, phase_train:True, learningrate:learning_rate}) #Final test using unseen images test_x, test_shapes, test_labels = load_test_data() test_batch_x, test_batch_y = test_batch(batch_size, test_x, test_shapes, test_labels) #Save model save_path = saver.save(sess, "./model.ckpt") main()
StarcoderdataPython
3370562
import math import numpy as np import shapely.geometry as geom from shapely import affinity import itertools from matplotlib import pyplot as plt from matplotlib import patches from descartes import PolygonPatch class Environment: def __init__(self, obstacles, start, goal_region, bounds=None): self.environment_loaded = False self.obstacles = obstacles # list of lists of tuples self.bounds = bounds self.start = start # (x,y) self.goal_region = goal_region # list of tuples defining corner points self.control_points = [] self.calculate_scene_dimensions() def add_obstacles(self, obstacles): self.obstacles += obstacles self.calculate_scene_dimensions() def set_goal_region(self, goal_region): self.goal_region = goal_region self.calculate_scene_dimensions() def add_control_points(self, points): self.control_points += points self.calculate_scene_dimensions() def calculate_scene_dimensions(self): """Compute scene bounds from obstacles, start, and goal """ points = [] for elem in self.obstacles: points = points + elem if self.start: points += [self.start] if self.goal_region: points += self.goal_region if len(self.control_points) > 0: points += self.control_points mp = geom.MultiPoint(points) self.bounds = mp.bounds def plot_ellipse_environment(scene, bounds, figsize): ''' scene - dict from scenarios bounds - [[minx, maxx], [miny, maxy]] ''' fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111) for obs in scene['obs_list']: h, k, a, b, theta = obs ellipse = patches.Ellipse( (h, k), a, b, theta, fc='orange', ec='k', alpha=0.5, zorder=5) ax.add_patch(ellipse) # start / goal goal_poly = geom.Polygon(scene['goal']) ax.add_patch(PolygonPatch(goal_poly, fc='green', ec='green', alpha=0.5, zorder=1)) start = geom.Point(scene['start']).buffer(0.2, resolution=3) ax.add_patch(PolygonPatch(start, fc='red', ec='black', alpha=0.7, zorder=1)) plt.xlim(bounds[0]) plt.ylim(bounds[1]) ax.set_aspect('equal', adjustable='box') return ax def plot_environment(env, bounds=None, figsize=None, margin=1.0): if bounds is None and env.bounds: minx, miny, maxx, maxy = env.bounds minx -= margin miny -= margin maxx += margin maxy += margin elif bounds: minx, miny, maxx, maxy = bounds else: minx, miny, maxx, maxy = (-10, -5, 10, 5) max_width, max_height = 12, 5.5 if figsize is None: width, height = max_width, (maxy-miny)*max_width/(maxx-minx) if height > 5: width, height = (maxx-minx)*max_height/(maxy-miny), max_height figsize = (width, height) f = plt.figure(figsize=figsize) ax = f.add_subplot(111) # obstacles for i, obs in enumerate(env.obstacles): poly = geom.Polygon(obs) patch = PolygonPatch(poly, fc='orange', ec='black', alpha=0.5, zorder=20) ax.add_patch(patch) # start / goal goal_poly = geom.Polygon(env.goal_region) ax.add_patch(PolygonPatch(goal_poly, fc='green', ec='green', alpha=0.5, zorder=1)) start = geom.Point(env.start).buffer(0.2, resolution=3) ax.add_patch(PolygonPatch(start, fc='red', ec='black', alpha=0.7, zorder=1)) # control points cx = [c[0] for c in env.control_points] cy = [c[1] for c in env.control_points] ax.plot(cx, cy, 'ko', markersize=8, alpha=0.8, label='control points') plt.xlim([minx, maxx]) plt.ylim([miny, maxy]) ax.set_aspect('equal', adjustable='box') return f, ax # Helpers for obstacle constraint handling def centroid(obstacle): ''' Averages all vertices in a given obstacle. Average of x's and y's is guaranteed to lie inside polygon ''' x_avg = sum([v[0] for v in obstacle])/len(obstacle) y_avg = sum([v[1] for v in obstacle])/len(obstacle) return (x_avg, y_avg) def linear_obstacle_constraints(obs, buffer): ''' Given polygonal obstsacle, returns a list of values for a, b, c Constraints take form: cy <= ax + b - buffer + Mz Assumes obstacles are given as consecutive ordered list of vertices ''' constraints = [] cent = centroid(obs) for i, v in enumerate(obs): v1 = obs[i] # get next vertex; loop back to first for last constraint v2 = obs[(i+1) % len(obs)] dx = v2[0] - v1[0] dy = v2[1] - v1[1] if dx == 0: # vertical constaint case; cy <= ax + b --> x <= b c = 0 if cent[0] <= v1[0]: # flip constraint a, b, c = 1, -v1[0] - buffer, 0 else: a, b, c = -1, v1[0] - buffer, 0 else: # non-vertical constraint; cy <= ax + b a = dy / dx b = v1[1] - a * v1[0] if cent[1] < a * cent[0] + b: # flip constraint a, b, c = -a, -b, -1 a, b, c = calc_offset_coefs((a, b, c), buffer) else: a, b, c = a, b, 1 a, b, c = calc_offset_coefs((a, b, c), buffer) constraints.append((a, b, c)) return constraints def calc_offset_coefs(coefs, offset): a, b, c = coefs b_new = b - offset*np.sqrt(a**2+1) return a, b_new, c # Test if __name__ == '__main__': import scenarios scene = scenarios.two_ellipse print(scene) ax = plot_ellipse_environment(scene, [[-1, 15], [-1, 10]], (12, 8)) ax.plot([1], [2], 'ro') plt.show() # import trajectory_gen as tgen # import scenarios # scene = scenarios.two_obstacle # control_pts = [(3, 0), (4.5, 1), (5, 2.8), # (3.5, 3.4), (2, 5.1), (3.7, 6.7), (5.5, 6.3)] # env = Environment(scene['obs_list'], # scene['start'], scene['goal']) # env.add_control_points(control_pts) # ax = plot_environment(env) # xc = [p[0] for p in control_pts] # yc = [p[1] for p in control_pts] # v = 5 # dt = 0.1 # bc_headings = (np.pi/8, -np.pi/12) # xs, ys, psi = tgen.sample_trajectory(xc, yc, bc_headings, v, dt) # constraints = linear_obstacle_constraints(env.obstacles[0]) # print(constraints) # ax.plot(xs, ys, 'ob', alpha=0.8, markersize=4, color='darkblue') # plt.show()
StarcoderdataPython
5171246
<reponame>gerryjenkinslb/cs22-slides-and-py-files from pythonds.basic.stack import Stack ''' :param decNumber: value to convert to binary :return: string displaying binary value for decNumber ''' def divide_by_2(dec_number): rem_stack = Stack() while dec_number > 0: remainder = dec_number % 2 rem_stack.push(remainder) dec_number = dec_number // 2 bin_string = "" while not rem_stack.isEmpty(): bin_string = bin_string + str(rem_stack.pop()) return bin_string print("42 is " + divide_by_2(42)) assert divide_by_2(2) == '10' assert divide_by_2(255) == "11111111" assert divide_by_2(8+1) == "1001"
StarcoderdataPython
8063089
<gh_stars>1-10 # -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-02-28 14:53 from __future__ import unicode_literals import django.core.validators from django.db import migrations, models import re class Migration(migrations.Migration): dependencies = [ ('judge', '0006_auto_20160227_1550'), ] operations = [ migrations.AlterField( model_name='profile', name='bitbucket_account', field=models.CharField(blank=True, max_length=32, validators=[django.core.validators.RegexValidator(re.compile('^[-a-zA-Z0-9_]+\\Z', 32), "Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens.", 'invalid')]), ), migrations.AlterField( model_name='profile', name='bitbucket_repository', field=models.CharField(blank=True, max_length=32, validators=[django.core.validators.RegexValidator(re.compile('^[-a-zA-Z0-9_]+\\Z', 32), "Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens.", 'invalid')]), ), ]
StarcoderdataPython
3207642
#! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = 'kute' # __mtime__ = '2016/12/24 20:45' """ 多线程,协称 执行器 """ import os import attr import gevent from gevent import monkey from gevent.pool import Pool monkey.patch_all() def valide_func(instance, attribute, value): if not callable(value): raise TypeError("{} is not callable") @attr.s class Eventor(object): func = attr.ib(validator=valide_func) taskunitcount = attr.ib(default=100, convert=int) threadcount = attr.ib(default=os.cpu_count() * 5, convert=int) interval = attr.ib(default=0, convert=int) def _slice_list_by_size(self, tasklist, slicesize): """按指定大小分隔集合 """ size = len(tasklist) if size <= slicesize: yield tasklist else: for i in list(range(0, size // slicesize + 1)): posi = i * slicesize templist = tasklist[posi: posi + slicesize] if len(templist) > 0: yield templist def _run(self, pool, tasklist, async=False): if async: return pool.map_async(self.func, tasklist) else: return pool.map(self.func, tasklist) def run_with_tasklist(self, tasklist=None, async=False, timeout=None): if not tasklist or len(tasklist) == 0: raise ValueError("parameters tasklist null value") if not isinstance(tasklist, list): raise ValueError("parameters tasklist wrong type, should be list, not {}".format(tasklist.__class__.__name__)) if not callable(self.func): raise ValueError("func is illegal function") if async and timeout is None: raise ValueError("timeout should be seted if special async=True") threadcount = self.threadcount or os.cpu_count() * 5 taskunitcount = self.taskunitcount or 100 pool = Pool(threadcount) size = len(tasklist) total = 0 resultlist = [] if size <= taskunitcount: result = self._run(pool, tasklist, async) resultlist.extend(result.get(timeout) if async else result) print("finished {} total tasks".format(size)) else: for slicelist in self._slice_list_by_size(tasklist, taskunitcount): result = self._run(pool, slicelist, async) resultlist.extend(result.get(timeout) if async else result) total += len(slicelist) gevent.sleep(self.interval) print("finished {} total tasks".format(total)) pool.join() return resultlist def run_with_file(self, file=None, async=False, timeout=None): if not os.path.exists(file) or not os.path.isfile(file): raise ValueError("wrong file or not exists") if not callable(self.func): raise ValueError("func is illegal function") if async and timeout is None: raise ValueError("timeout should be seted if special async=True") threadcount = self.threadcount or os.cpu_count() * 5 taskunitcount = self.taskunitcount or 100 pool = Pool(threadcount) plist = [] total = 0 resultlist = [] with open(file, "r") as f: for line in f: plist.append(line.strip()) if len(plist) >= taskunitcount: result = self._run(pool, plist, async) resultlist.extend(result.get(timeout) if async else result) total += len(plist) plist.clear() gevent.sleep(self.interval) if len(plist) > 0: result = self._run(pool, plist, async) resultlist.extend(result.get(timeout) if async else result) total += len(plist) plist.clear() print("finished {} total tasks".format(total)) pool.join() return resultlist
StarcoderdataPython
1978893
from __future__ import annotations import parsedatetime from subtypes import Enum class MetaInfoMixin: _calendar = parsedatetime.Calendar() class Enums: class WeekDay(Enum): """An Enum holding the days of the week.""" MONDAY = MON = Enum.Alias() TUESDAY = TUE = Enum.Alias() WEDNESDAY = WED = Enum.Alias() THURSDAY = THU = Enum.Alias() FRIDAY = FRI = Enum.Alias() SATURDAY = SAT = Enum.Alias() SUNDAY = SUN = Enum.Alias() class Month(Enum): """An Enum holding the months of the year.""" JANUARY = JAN = Enum.Alias() FEBRUARY = FEB = Enum.Alias() MARCH = MAR = Enum.Alias() APRIL = APR = Enum.Alias() MAY = Enum.Auto() JUNE = JUN = Enum.Alias() JULY = JUL = Enum.Alias() AUGUST = AUG = Enum.Alias() SEPTEMBER = SEP = Enum.Alias() OCTOBER = OCT = Enum.Alias() NOVEMBER = NOV = Enum.Alias() DECEMBER = DEC = Enum.Alias() class FormatCode: """An Enum containing all the formatcodes used by DateTime.strptime() and DateTime.strftime(), subdivided into further Enums.""" class TIMEZONE: NAME = "%Z" class WEEKDAY: SHORT, FULL, NUM = "%a", "%A", "%w" class WEEK: OF_YEAR_STARTING_MONDAY, OF_YEAR_STARTING_SUNDAY = "%W", "%U" class YEAR: WITHOUT_CENTURY, WITH_CENTURY = "%y", "%Y" class MONTH: SHORT, FULL, NUM = "%b", "%B", "%m" class DAY: NUM, OF_YEAR = "%d", "%j" class HOUR: H24, H12, AM_PM = "%H", "%I", "%p" class MINUTE: NUM = "%M" class SECOND: NUM = "%S" class MICROSECOND: NUM = "%f"
StarcoderdataPython
9624018
<reponame>PicusZeus/modern_greek_accentuation from modern_greek_accentuation.accentuation import convert_to_monotonic if __name__ == '__main__': print(convert_to_monotonic('ἐν τῷ πρόσθεν λόγῳ δεδήλωται'))
StarcoderdataPython
11244557
<reponame>dzil123/godot-gdscript-toolkit<filename>tests/common.py import os def write_file(tmp_dir, file_name, code): file_path = os.path.join(tmp_dir, file_name) with open(file_path, "w") as fh: fh.write(code) return file_path
StarcoderdataPython
7247
# Copyright 2020 Soil, Inc. # Copyright (c) 2011 X.commerce, a business unit of eBay Inc. # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # 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. """Implementation of SQLAlchemy backend.""" import collections import copy import datetime import functools import inspect import sys import threading from oslo_db.sqlalchemy import session as db_session from oslo_log import log as logging import soil.conf from soil.i18n import _ CONF = soil.conf.CONF LOG = logging.getLogger(__name__) _LOCK = threading.Lock() _FACADE = None def _create_facade_lazily(): global _LOCK with _LOCK: global _FACADE if _FACADE is None: _FACADE = db_session.EngineFacade( CONF.database.connection, **dict(CONF.database) ) return _FACADE def get_engine(): facade = _create_facade_lazily() return facade.get_engine() def get_session(**kwargs): facade = _create_facade_lazily() return facade.get_session(**kwargs) def dispose_engine(): get_engine().dispose()
StarcoderdataPython
5001311
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "<NAME>" __email__ = "<EMAIL>" __description__ = ''' Camera image source. Searches for a connected camera (that is not shaded). ''' import sys import os import cv2 import numpy as np class WebCamera: """ Camera input. An active switched-on camera whose number is in the given range is searched for. """ def __init__(self, range_of_camera_ids: range = range(10)): self._capture = None self._is_adjusted = False self._range_of_camera_ids = range_of_camera_ids def __del__(self): if not self._capture is None: self._capture.release() def _get_img(self) -> (np.ndarray, int): ret, img = self._capture.read() # Int id of image. In the case of camera it can be "Current position of the video file in microseconds". img_microseconds = int(1000 * self._capture.get(cv2.CAP_PROP_POS_MSEC)) return img, img_microseconds def _img_is_ok(self, img_array: np.ndarray, deep_check: bool=False, treshold: int = 100): if img_array is None: return False if deep_check: # test for some 'sweet' colors if np.sum(img_array > 100) < treshold: return False return True def _adjust_and_return_img(self) -> (np.ndarray, int): for i in self._range_of_camera_ids: try: self._capture = cv2.VideoCapture(i) except Exception as e: print(e) if self._capture.isOpened(): img, img_microseconds = self._get_img() if self._img_is_ok(img, deep_check=True): print('-' * 80) print('Found camera:', i) print('-' * 80) return img, img_microseconds return None, None def read(self) -> (np.ndarray, int): if not self._is_adjusted: # first initialization img_array, img_microseconds = self._adjust_and_return_img() else: img_array, img_microseconds = self._get_img() self._is_adjusted = self._img_is_ok(img_array) if self._is_adjusted: timestamp_ms=1000 * img_microseconds return img_array, timestamp_ms else: return img_array, -1
StarcoderdataPython
8010406
from queue import LifoQueue stack = LifoQueue(maxsize = 3) print(stack.qsize()) stack.put('a') stack.put('b') stack.put('c') print("Full: ", stack.full()) print("Size: ", stack.qsize()) print('\nElements poped from the stack') print(stack.get()) print(stack.get()) print(stack.get()) print("\nEmpty: ", stack.empty())
StarcoderdataPython
5088584
__all__ = [ "__version__", "Lockfile", "Pipfile", ] __version__ = '0.2.3.dev0' from .lockfiles import Lockfile from .pipfiles import Pipfile
StarcoderdataPython
11396879
from django.db import models from django.urls import reverse # Create your models here. class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) slug = models.SlugField(max_length=50) birthday = models.DateField() class Meta: abstract = True def __str__(self): return '{} {}'.format(self.first_name, self.last_name) class Actor(Person): def get_absolute_url(self): return reverse('actor-detail', kwargs={'pk': self.pk}) class Director(Person): def get_absolute_url(self): return reverse('director-detail', kwargs={'pk': self.pk}) class Movie(models.Model): name = models.CharField(max_length=250) year = models.IntegerField() RATINGS = [ ('G', 'G - General Audiences'), ('PG', 'PG - Parental Guidance Suggested'), ('PG-13', 'PG-13 - Parents Strongly Cautioned'), ('R', 'R - Restricted'), ('NC-17', 'NC-17 - No One Under 17 Admitted'), ] rating = models.CharField(max_length=7, choices=RATINGS) director = models.ForeignKey(Director, related_name='movies') actors = models.ManyToManyField(Actor, related_name='movies') def __str__(self): return '{} ({})'.format(self.name, self.year) def get_absolute_url(self): return reverse('movie-detail', kwargs={'pk': self.pk})
StarcoderdataPython
164179
#!/usr/bin/python with open('INCAR', 'r') as file: lines=file.readlines() for n,i in enumerate(lines): if 'MAGMOM' in i: # print(i) items=i.split() index=items.index('=') moments=items[index+1:] # print(moments) magmom='' size=4 for i in range(len(moments)//3): k=' '.join(k for k in moments[3*i:3*i+3]) magmom+=(k+' ')*size print(magmom)
StarcoderdataPython
147903
from methods.indirect_influence import indirect_pagerank, indirect_paths from methods.direct_influence import pairwise_inf from classes.GraphQW import GraphQW, nx """ LRIC centrality Arguments: graph - input graph (Graph or DiGraph object, NetworkX package) q (optional) - quota (threshold of influence) for each node (share of weighted in-degree). By default q = 20% dq (optional) - predefined fixed threshold value for each node (float, array or dictionary) group_size (optional) - maximal group size (cardinality of coalition). By default limcoal = 4 dw (optional) - nodes size (float, array or dictionary). By default node size is equal to weighted out-degree. group_size (optional) - maximal length of influence models (optional) - type of LRIC centrality (LRIC_max, LRIC_maxmin, LRIC_pagerank). By default models = "max" data - logical scalar. If the data arguments is False, then nodes centrality is returned. Otherwise, centrality and SRIC graph is returned. By default data = false Output: ranking - nodes SRIC centrality (dictionary) g - SRIC graph """ def lric(graph, q=20, dq=None, group_size=4, dw=None, limpath=3, models='max', data=False): if isinstance(models, str): models = [models] g = pairwise_inf(GraphQW(graph, q, dq, group_size, dw), method='LRIC') # evaluate direct influence if 'pagerank' in models: # calculate LRIC PageRank ranking = indirect_pagerank(g).aggregate() g.set_param('lric_pagerank', ranking) if 'max' in models: # calculate LRIC_Max ranking = indirect_paths(g, limpath, 0, 2).aggregate() g.set_param('lric_max', ranking) if 'maxmin' in models: ranking = indirect_paths(g, limpath, 0, 1).aggregate() g.set_param('lric_maxmin', ranking) if data: return ranking, g else: return ranking """ SRIC centrality Arguments: graph - input graph (Graph or DiGraph object, NetworkX package) q (optional) - quota (threshold of influence) for each node (share of weighted in-degree). By default q = 20% dq (optional) - predefined fixed threshold value for each node (float, array or dictionary) group_size (optional) - maximal group size (cardinality of coalition). By default limcoal = 4 dw (optional) - nodes size (float, array or dictionary). By default node size is equal to weighted out-degree. data - logical scalar. If the data arguments is False, then nodes centrality is returned. Otherwise, centrality and SRIC graph is returned. By default data = false Output: ranking - nodes SRIC centrality (dictionary) g - SRIC graph """ def sric(graph, q=20, dq=None, group_size=4, dw=None, dCoal=None, data=False): g = pairwise_inf(GraphQW(graph, q, dq, group_size, dw), method='SRIC') # calculate SRIC graph ranking = g.aggregate(name='sric') # calculate centrality of each node if data: return ranking, g else: return ranking
StarcoderdataPython