gt
stringclasses
1 value
context
stringlengths
2.49k
119k
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you 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 os import socket import subprocess import sys import time import pytest from _pytest.skipping import MarkEvaluator from selenium import webdriver from selenium.webdriver import DesiredCapabilities from test.selenium.webdriver.common.webserver import SimpleWebServer from test.selenium.webdriver.common.network import get_lan_ip if sys.version_info[0] == 3: from urllib.request import urlopen else: from urllib import urlopen drivers = ( 'BlackBerry', 'Chrome', 'Edge', 'Firefox', 'Ie', 'Marionette', 'Remote', 'Safari', 'WebKitGTK', ) def pytest_addoption(parser): parser.addoption('--driver', action='append', choices=drivers, dest='drivers', metavar='DRIVER', help='driver to run tests against ({})'.format(', '.join(drivers))) parser.addoption('--browser-binary', action='store', dest='binary', help='location of the browser binary') parser.addoption('--driver-binary', action='store', dest='executable', help='location of the service executable binary') parser.addoption('--browser-args', action='store', dest='args', help='arguments to start the browser with') def pytest_ignore_collect(path, config): _drivers = set(drivers).difference(config.getoption('drivers') or drivers) parts = path.dirname.split(os.path.sep) return len([d for d in _drivers if d.lower() in parts]) > 0 driver_instance = None @pytest.fixture(scope='function') def driver(request): kwargs = {} try: driver_class = request.param except AttributeError: raise Exception('This test requires a --driver to be specified.') # conditionally mark tests as expected to fail based on driver request.node._evalxfail = request.node._evalxfail or MarkEvaluator( request.node, 'xfail_{0}'.format(driver_class.lower())) if request.node._evalxfail.istrue(): def fin(): global driver_instance if driver_instance is not None: driver_instance.quit() driver_instance = None request.addfinalizer(fin) # skip driver instantiation if xfail(run=False) if not request.config.getoption('runxfail'): if request.node._evalxfail.istrue(): if request.node._evalxfail.get('run') is False: yield return driver_path = request.config.option.executable options = None global driver_instance if driver_instance is None: if driver_class == 'BlackBerry': kwargs.update({'device_password': 'password'}) if driver_class == 'Firefox': kwargs.update({'capabilities': {'marionette': False}}) options = get_options(driver_class, request.config) if driver_class == 'Marionette': driver_class = 'Firefox' options = get_options(driver_class, request.config) if driver_class == 'Remote': capabilities = DesiredCapabilities.FIREFOX.copy() kwargs.update({'desired_capabilities': capabilities}) options = get_options('Firefox', request.config) if driver_class == 'WebKitGTK': options = get_options(driver_class, request.config) if driver_path is not None: kwargs['executable_path'] = driver_path if options is not None: kwargs['options'] = options driver_instance = getattr(webdriver, driver_class)(**kwargs) yield driver_instance if MarkEvaluator(request.node, 'no_driver_after_test').istrue(): driver_instance = None def get_options(driver_class, config): browser_path = config.option.binary browser_args = config.option.args options = None if browser_path or browser_args: options = getattr(webdriver, '{}Options'.format(driver_class))() if driver_class == 'WebKitGTK': options.overlay_scrollbars_enabled = False if browser_path is not None: options.binary_location = browser_path if browser_args is not None: for arg in browser_args.split(): options.add_argument(arg) return options @pytest.fixture(scope='session', autouse=True) def stop_driver(request): def fin(): global driver_instance if driver_instance is not None: driver_instance.quit() driver_instance = None request.addfinalizer(fin) def pytest_exception_interact(node, call, report): if report.failed: global driver_instance if driver_instance is not None: driver_instance.quit() driver_instance = None @pytest.fixture def pages(driver, webserver): class Pages(object): def url(self, name): return webserver.where_is(name) def load(self, name): driver.get(self.url(name)) return Pages() @pytest.fixture(autouse=True, scope='session') def server(request): drivers = request.config.getoption('drivers') if drivers is None or 'Remote' not in drivers: yield None return _host = 'localhost' _port = 4444 _path = '../buck-out/gen/java/server/src/org/openqa/grid/selenium/selenium.jar' def wait_for_server(url, timeout): start = time.time() while time.time() - start < timeout: try: urlopen(url) return 1 except IOError: time.sleep(0.2) return 0 _socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) url = 'http://{}:{}/wd/hub'.format(_host, _port) try: _socket.connect((_host, _port)) print('The remote driver server is already running or something else' 'is using port {}, continuing...'.format(_port)) except Exception: print('Starting the Selenium server') process = subprocess.Popen(['java', '-jar', _path]) print('Selenium server running as process: {}'.format(process.pid)) assert wait_for_server(url, 10), 'Timed out waiting for Selenium server at {}'.format(url) print('Selenium server is ready') yield process process.terminate() process.wait() print('Selenium server has been terminated') @pytest.fixture(autouse=True, scope='session') def webserver(): webserver = SimpleWebServer(host=get_lan_ip()) webserver.start() yield webserver webserver.stop()
""" Serialize data to/from CSV Since CSV deals only in string values, certain conventions must be employed to represent other data types. The conventions used in this serializer implementation are as follows: - Boolean values are serialized as 'TRUE' and 'FALSE' - The strings 'TRUE' and 'FALSE' are serialized as "'TRUE'" and "'FALSE'" - None is serialized as 'NULL' - The string 'NULL' is serialized as "'NULL'" - Lists are serialized as comma separated items surrounded by brackets, e.g. [foo, bar] becomes '[foo, bar]' - Strings beginning with '[' and ending in ']' are serialized by being wrapped in single quotes, e.g. '[foo, bar]' becomes "'[foo, bar]'" See also: http://docs.djangoproject.com/en/1.2/topics/serialization/ """ import codecs import csv import re import StringIO from itertools import groupby from operator import itemgetter from django.core.serializers.python import Serializer as PythonSerializer from django.core.serializers.python import Deserializer as PythonDeserializer from django.utils.encoding import smart_unicode class Serializer(PythonSerializer): """ Convert a queryset to CSV. """ internal_use_only = False def end_serialization(self): def process_item(item): if isinstance(item, (list, tuple)): item = process_m2m(item) elif isinstance(item, bool): item = str(item).upper() elif isinstance(item, basestring): if item in ('TRUE', 'FALSE', 'NULL') or _LIST_RE.match(item): # Wrap these in quotes, so as not to be confused with # builtin types when deserialized item = "'%s'" % item elif item is None: item = 'NULL' return smart_unicode(item) def process_m2m(seq): parts = [] for item in seq: if isinstance(item, (list, tuple)): parts.append(process_m2m(item)) else: parts.append(process_item(item)) return '[%s]' % ', '.join(parts) writer = UnicodeWriter(self.stream) # Group objects by model and write out a header and rows for each. # Multiple models can be present when invoking from the command # line, e.g.: `python manage.py dumpdata --format csv auth` for k, g in groupby(self.objects, key=itemgetter('model')): write_header = True for d in g: # "flatten" the object. PK and model values come first, # then field values. Flat is better than nested, right? :-) pk, model, fields = d['pk'], d['model'], d['fields'] pk, model = smart_unicode(pk), smart_unicode(model) row = [pk, model] + map(process_item, fields.values()) if write_header: header = ['pk', 'model'] + fields.keys() writer.writerow(header) write_header = False writer.writerow(row) def getvalue(self): if callable(getattr(self.stream, 'getvalue', None)): return self.stream.getvalue() _QUOTED_BOOL_NULL = """ 'TRUE' 'FALSE' 'NULL' "TRUE" "FALSE" "NULL" """.split() # regular expressions used in deserialization _LIST_PATTERN = r'\[(.*)\]' _LIST_RE = re.compile(r'\A%s\Z' % _LIST_PATTERN) _QUOTED_LIST_RE = re.compile(r""" \A # beginning of string (['"]) # quote char %s # list \1 # matching quote \Z # end of string""" % _LIST_PATTERN, re.VERBOSE) _SPLIT_RE = re.compile(r', *') _NK_LIST_RE = re.compile(r""" \A # beginning of string \[ # opening bracket [^]]+ # one or more non brackets \] # closing bracket (?:, *\[[^]]+\])* # zero or more of above, separated # by a comma and optional spaces \Z # end of string""", re.VERBOSE) _NK_SPLIT_RE = re.compile(r""" (?<=\]) # closing bracket (lookbehind) , * # comma and optional spaces (?=\[) # opening bracket (lookahead)""", re.VERBOSE) def Deserializer(stream_or_string, **options): """ Deserialize a stream or string of CSV data. """ def process_item(item): m = _LIST_RE.match(item) if m: contents = m.group(1) if not contents: item = [] else: item = process_m2m(contents) else: if item == 'TRUE': item = True elif item == 'FALSE': item = False elif item == 'NULL': item = None elif (item in _QUOTED_BOOL_NULL or _QUOTED_LIST_RE.match(item)): item = item.strip('\'"') return item def process_m2m(contents): li = [] if _NK_LIST_RE.match(contents): for item in _NK_SPLIT_RE.split(contents): li.append(process_item(item)) else: li = _SPLIT_RE.split(contents) return li if isinstance(stream_or_string, basestring): stream = StringIO.StringIO(stream_or_string) else: stream = stream_or_string reader = UnicodeReader(stream) header = next(reader) # first line must be a header data = [] for row in reader: # Need to account for the presence of multiple headers in # the stream since serialized data can contain them. if row[:2] == ['pk', 'model']: # Not the best check. Perhaps csv.Sniffer.has_header # would be better? header = row continue d = dict(zip(header[:2], row[:2])) d['fields'] = dict(zip(header[2:], map(process_item, row[2:]))) data.append(d) for obj in PythonDeserializer(data, **options): yield obj # The classes below taken from http://docs.python.org/library/csv.html class UTF8Recoder(object): """ Iterator that reads an encoded stream and reencodes the input to UTF-8 """ def __init__(self, f, encoding): self.reader = codecs.getreader(encoding)(f) def __iter__(self): return self def next(self): return self.reader.next().encode('utf-8') class UnicodeReader(object): """ A CSV reader which will iterate over lines in the CSV file "f", which is encoded in the given encoding. """ def __init__(self, f, dialect=csv.excel, encoding='utf-8', **kwds): f = UTF8Recoder(f, encoding) self.reader = csv.reader(f, dialect=dialect, **kwds) def next(self): row = self.reader.next() return [unicode(s, 'utf-8') for s in row] def __iter__(self): return self class UnicodeWriter(object): """ A CSV writer which will write rows to CSV file "f", which is encoded in the given encoding. """ def __init__(self, f, dialect=csv.excel, encoding='utf-8', **kwds): # Redirect output to a queue self.queue = StringIO.StringIO() self.writer = csv.writer(self.queue, dialect=dialect, **kwds) self.stream = f self.encoder = codecs.getincrementalencoder(encoding)() def writerow(self, row): self.writer.writerow([s.encode('utf-8') for s in row]) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() data = data.decode('utf-8') # ... and reencode it into the target encoding data = self.encoder.encode(data) # write to the target stream self.stream.write(data) # empty queue self.queue.truncate(0) def writerows(self, rows): for row in rows: self.writerow(row)
#!/usr/bin/python #Standard python libs import sys import os # import datetime import numpy as np import h5py import matplotlib.pyplot as plt from math import * #Libs related to scipy and matplotlib from scipy import * from scipy.fftpack import fft from scipy.fftpack.helper import fftfreq sys.path.append("./" ) # time_integrator_analysis was created by Jose. # Jose's function was used directly here. from time_integrator_analysis import findpeaks, measure_damping, hht_damping_and_shift from mycolor_fun import * h5in_file_name=sys.argv[1] gamma=sys.argv[2] gamma=float(gamma) h5file_in=h5py.File(h5in_file_name,"r") # h5file_in=h5py.File("veri_newmark_dynamic.h5.feioutput","r") disp=h5file_in['/Model/Nodes/Generalized_Displacements'][()] time=h5file_in['/time'][()] # The required displacement. node_displ=disp[6][:] last=len(node_displ)-1 len_time=len(time) node_displ=np.delete(node_displ,[last],None) dt=time[1]-time[0] peak_indices=findpeaks(node_displ) measured_period=time[peak_indices[2]]-time[peak_indices[1]] alpha=0.0 N = node_displ.shape[0] D = fft(node_displ[:]) f = fftfreq(N, dt) xi, fs, Ys = measure_damping(f[0:N/2], abs(D[0:N/2])) # ********************************************** # The measured xi is not accurate by the previous method # Use the other method to measure xi: peak_indices=findpeaks(node_displ) pks = [] for index in peak_indices: pks.append(node_displ[index]) deltaSize=len(pks)-1; delta=np.zeros([deltaSize,1]); for i in xrange(len(delta)): delta[i] =1.0/(i+1.0)*np.log(pks[0]/pks[i+1]) deltaAverage=np.mean(delta); xi_measure=deltaAverage/2./pi; # print "old xi = " + str(xi) # print "new xi = " + str(xi_measure) # ********************************************** peak_index = 0 max_Y = 0 T_system=1.0 for i in arange(len(fs)): if (abs(Ys[i]) > max_Y) : max_Y = abs(Ys[i]) peak_index = i # xi_measure = xi[peak_index] measured_period = 1./fs[peak_index] measured_period_shift=(1./fs[peak_index]-T_system)/T_system T_system=1.0 w = 2*pi/T_system beta = 0.25*(0.5 + gamma)**2 wbar, xi_analytic = hht_damping_and_shift(beta, gamma, alpha, w, dt) T_theory = 2*pi/wbar T_shift = (T_theory - T_system)/T_system # xi_measure_error=abs(xi_measure-xi_analytic)/xi_measure T_error=abs(T_system-T_theory)/T_system # standard 1 # print dt, " & ", gamma, " & ", "%0.6f" %xi_measure, " & ", "%0.6f" %xi_analytic, " & ", "%0.6f" %xi_measure_error, " & ", "\\\\ " # print dt, " & ", gamma, " & ", "%0.6f" %T_system, " & ", "%0.6f" %T_theory, " & ", "%0.6f" %T_error, " & ", "\\\\ " # standard 2 # 1 measured xi_measure 2 xi_analytic xi_analytic=xi_analytic+0 xi_analytic=abs(xi_analytic) ssize=len(node_displ)-1 i = 1 peak_val = [] for i in xrange(ssize-1): # if( (node_displ[i-1] < node_displ[i]) and (node_displ[i+1] < node_displ[i]) ): if( (node_displ[i] < node_displ[i+1]) and (node_displ[i+2] < node_displ[i+1]) ): peak_val.append(node_displ[i+1]) deltaSize=len(peak_val)-1; ddelta= linspace(0,0,deltaSize) # for i=1:deltaSize for i in range(1,deltaSize): ddelta[i]=1/i*log(peak_val[1]/peak_val[i+1]) deltaAverage=mean(ddelta) measured_xi=deltaAverage/2/pi measured_xi=100*measured_xi; # print dt, " & ", gamma, " & ", "%0.6f" %measured_xi," & ", "%0.6f" %xi_analytic, " & ", "%0.6f" %measured_period_shift, " & ", "%0.6f" %T_shift, "\\\\ \\hline" # new printing xi_err = abs(xi_analytic - xi_measure) period_err = abs(T_shift - measured_period_shift) xi_rel_err = abs(xi_analytic - xi_measure) / xi_analytic period_rel_err = abs(T_shift - measured_period_shift) / T_shift if period_rel_err > 1.0: period_rel_err = 1.0 if xi_rel_err > 1.0: xi_rel_err =1.0 print headrun() , "-----------Testing results-----------------" print headstep() , "Newmark: dt = " + str(dt) + " gamma = " + str(gamma) print headstep() ,'{0} {1} {2} {3}'.format('Analytic ','ESSI ','Absolute_Error ','Relative_Error') print headDamping() ,'{0:+0.2e} {1:+0.2e} {2:+0.2f} {3:+0.2f}'.format(xi_analytic, xi_measure, xi_err, xi_rel_err ) print headPeriodShift() ,'{0:+0.2e} {1:+0.2e} {2:+0.2f} {3:+0.2f}'.format(T_shift, measured_period_shift, period_err, period_rel_err ) # My own method to calculate the theoretical wbar for Newmark method: # I got the same result with the pre-exi_measuresting one. # dtw=dt*w # numerator=dtw*sqrt(1+dtw**2*(beta-0.25*(gamma+0.5)**2)) # denominator=1+dtw**2*(beta-0.5*(gamma+0.5))w # Phi=arctan(numerator/denominator) # wbarmy=Phi/dt # wbarmy # # time=np.transpose(time) # print ("%16.8f \n" %len(node_displ)) # print ("%16.8f \n" %len_time) # print ("%16.8f \n" %node_displ[0]) # print ("%16.8f \n" %node_displ[1]) # print ("%16.8f \n" %time[0]) # print ("%16.8f \n" %time[1]) # xi_measure=0.1 # u_0=0.1 # w_n=2*pi # w_D=w_n*np.sqrt(1-xi_measure**2) # u_exact=np.exp(-xi_measure*w_n*time)*(u_0*np.cos(time*w_D)+(xi_measure*w_n*u_0)/w_D*np.sin(w_D*time)) # # print("time") # # , (comma) cannot be ignored. # u_essi,=plt.plot(time, node_displ,'ro-') # u_disp,=plt.plot(time, u_exact,'b^--') # plt.xlabel('Time') # plt.ylabel('Displacement') # plt.legend([u_essi, u_disp], ["ESSI", "Exact"]) # plt.show()
# Copyright (C) 2011-2013 Claudio Guarnieri. # Copyright (C) 2014-2018 Cuckoo Foundation. # This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org # See the file 'docs/LICENSE' for copying permission. import datetime import hashlib import logging import os import pkgutil import socket import struct import sys import threading import traceback import urllib import urllib2 import xmlrpclib import zipfile from lib.api.process import Process from lib.common.abstracts import Package, Auxiliary from lib.common.constants import SHUTDOWN_MUTEX from lib.common.decide import dump_memory from lib.common.defines import KERNEL32 from lib.common.exceptions import CuckooError, CuckooDisableModule from lib.common.hashing import hash_file from lib.common.rand import random_string from lib.common.results import upload_to_host from lib.core.config import Config from lib.core.ioctl import zer0m0n from lib.core.packages import choose_package from lib.core.pipe import PipeServer, PipeForwarder, PipeDispatcher from lib.core.privileges import grant_privilege from lib.core.startup import init_logging, set_clock from modules import auxiliary log = logging.getLogger("analyzer") class Files(object): PROTECTED_NAMES = () def __init__(self): self.files = {} self.files_orig = {} self.dumped = [] def is_protected_filename(self, file_name): """Do we want to inject into a process with this name?""" return file_name.lower() in self.PROTECTED_NAMES def add_pid(self, filepath, pid, verbose=True): """Tracks a process identifier for this file.""" if not pid or filepath.lower() not in self.files: return if pid not in self.files[filepath.lower()]: self.files[filepath.lower()].append(pid) verbose and log.info("Added pid %s for %r", pid, filepath) def add_file(self, filepath, pid=None): """Add filepath to the list of files and track the pid.""" if filepath.lower() not in self.files: log.info( "Added new file to list with pid %s and path %s", pid, filepath.encode("utf8") ) self.files[filepath.lower()] = [] self.files_orig[filepath.lower()] = filepath self.add_pid(filepath, pid, verbose=False) def dump_file(self, filepath): """Dump a file to the host.""" if not os.path.isfile(filepath): log.warning("File at path %r does not exist, skip.", filepath) return False # Check whether we've already dumped this file - in that case skip it. try: sha256 = hash_file(hashlib.sha256, filepath) if sha256 in self.dumped: return except IOError as e: log.info("Error dumping file from path \"%s\": %s", filepath, e) return filename = "%s_%s" % (sha256[:16], os.path.basename(filepath)) upload_path = os.path.join("files", filename) try: upload_to_host( # If available use the original filepath, the one that is # not lowercased. self.files_orig.get(filepath.lower(), filepath), upload_path, self.files.get(filepath.lower(), []) ) self.dumped.append(sha256) except (IOError, socket.error) as e: log.error( "Unable to upload dropped file at path \"%s\": %s", filepath, e ) def delete_file(self, filepath, pid=None): """A file is about to removed and thus should be dumped right away.""" self.add_pid(filepath, pid) self.dump_file(filepath) # Remove the filepath from the files list. self.files.pop(filepath.lower(), None) self.files_orig.pop(filepath.lower(), None) def move_file(self, oldfilepath, newfilepath, pid=None): """A file will be moved - track this change.""" self.add_pid(oldfilepath, pid) if oldfilepath.lower() in self.files: # Replace the entry with the new filepath. self.files[newfilepath.lower()] = \ self.files.pop(oldfilepath.lower(), []) def dump_files(self): """Dump all pending files.""" while self.files: self.delete_file(self.files.keys()[0]) class ProcessList(object): def __init__(self): self.pids = [] self.pids_notrack = [] def add_pid(self, pid, track=True): """Add a process identifier to the process list. Track determines whether the analyzer should be monitoring this process, i.e., whether Cuckoo should wait for this process to finish. """ if int(pid) not in self.pids and int(pid) not in self.pids_notrack: if track: self.pids.append(int(pid)) else: self.pids_notrack.append(int(pid)) def add_pids(self, pids): """Add one or more process identifiers to the process list.""" if isinstance(pids, (tuple, list)): for pid in pids: self.add_pid(pid) else: self.add_pid(pids) def has_pid(self, pid, notrack=True): """Is this process identifier being tracked?""" if int(pid) in self.pids: return True if notrack and int(pid) in self.pids_notrack: return True return False def remove_pid(self, pid): """Remove a process identifier from being tracked.""" if pid in self.pids: self.pids.remove(pid) if pid in self.pids_notrack: self.pids_notrack.remove(pid) class CommandPipeHandler(object): """Pipe Handler. This class handles the notifications received through the Pipe Server and decides what to do with them. """ ignore_list = dict(pid=[]) def __init__(self, analyzer): self.analyzer = analyzer self.tracked = {} def _handle_debug(self, data): """Debug message from the monitor.""" log.debug(data) def _handle_info(self, data): """Regular message from the monitor.""" log.info(data) def _handle_warning(self, data): """Warning message from the monitor.""" log.warning(data) def _handle_critical(self, data): """Critical message from the monitor.""" log.critical(data) def _handle_loaded(self, data): """The monitor has loaded into a particular process.""" if not data or data.count(",") != 1: log.warning("Received loaded command with incorrect parameters, " "skipping it.") return pid, track = data.split(",") if not pid.isdigit() or not track.isdigit(): log.warning("Received loaded command with incorrect parameters, " "skipping it.") return self.analyzer.process_lock.acquire() self.analyzer.process_list.add_pid(int(pid), track=int(track)) self.analyzer.process_lock.release() log.debug("Loaded monitor into process with pid %s", pid) def _handle_getpids(self, data): """Return the process identifiers of the agent and its parent process.""" return struct.pack("II", self.analyzer.pid, self.analyzer.ppid) def _inject_process(self, process_id, thread_id, mode): """Helper function for injecting the monitor into a process.""" # We acquire the process lock in order to prevent the analyzer to # terminate the analysis while we are operating on the new process. self.analyzer.process_lock.acquire() # Set the current DLL to the default one provided at submission. dll = self.analyzer.default_dll if process_id in (self.analyzer.pid, self.analyzer.ppid): if process_id not in self.ignore_list["pid"]: log.warning("Received request to inject Cuckoo processes, " "skipping it.") self.ignore_list["pid"].append(process_id) self.analyzer.process_lock.release() return # We inject the process only if it's not being monitored already, # otherwise we would generated polluted logs (if it wouldn't crash # horribly to start with). if self.analyzer.process_list.has_pid(process_id): # This pid is already on the notrack list, move it to the # list of tracked pids. if not self.analyzer.process_list.has_pid(process_id, notrack=False): log.debug("Received request to inject pid=%d. It was already " "on our notrack list, moving it to the track list.") self.analyzer.process_list.remove_pid(process_id) self.analyzer.process_list.add_pid(process_id) self.ignore_list["pid"].append(process_id) # Spit out an error once and just ignore it further on. elif process_id not in self.ignore_list["pid"]: self.ignore_list["pid"].append(process_id) # We're done operating on the processes list, release the lock. self.analyzer.process_lock.release() return # Open the process and inject the DLL. Hope it enjoys it. proc = Process(pid=process_id, tid=thread_id) filename = os.path.basename(proc.get_filepath()) if not self.analyzer.files.is_protected_filename(filename): # Add the new process ID to the list of monitored processes. self.analyzer.process_list.add_pid(process_id) # We're done operating on the processes list, # release the lock. Let the injection do its thing. self.analyzer.process_lock.release() # If we have both pid and tid, then we can use APC to inject. if process_id and thread_id: proc.inject(dll, apc=True, mode="%s" % mode) else: proc.inject(dll, apc=False, mode="%s" % mode) log.info("Injected into process with pid %s and name %r", proc.pid, filename) def _handle_process(self, data): """Request for injection into a process.""" # Parse the process identifier. if not data or not data.isdigit(): log.warning("Received PROCESS command from monitor with an " "incorrect argument.") return return self._inject_process(int(data), None, 0) def _handle_process2(self, data): """Request for injection into a process using APC.""" # Parse the process and thread identifier. if not data or data.count(",") != 2: log.warning("Received PROCESS2 command from monitor with an " "incorrect argument.") return pid, tid, mode = data.split(",") if not pid.isdigit() or not tid.isdigit() or not mode.isdigit(): log.warning("Received PROCESS2 command from monitor with an " "incorrect argument.") return return self._inject_process(int(pid), int(tid), int(mode)) def _handle_file_new(self, data): """Notification of a new dropped file.""" self.analyzer.files.add_file(data.decode("utf8"), self.pid) def _handle_file_del(self, data): """Notification of a file being removed (if it exists) - we have to dump it before it's being removed.""" filepath = data.decode("utf8") if os.path.exists(filepath): self.analyzer.files.delete_file(filepath, self.pid) def _handle_file_move(self, data): """A file is being moved - track these changes.""" if "::" not in data: log.warning("Received FILE_MOVE command from monitor with an " "incorrect argument.") return old_filepath, new_filepath = data.split("::", 1) self.analyzer.files.move_file( old_filepath.decode("utf8"), new_filepath.decode("utf8"), self.pid ) def _handle_kill(self, data): """A process is being killed.""" if not data.isdigit(): log.warning("Received KILL command with an incorrect argument.") return if self.analyzer.config.options.get("procmemdump"): dump_memory(int(data)) def _handle_dumpmem(self, data): """Dump the memory of a process as it is right now.""" if not data.isdigit(): log.warning("Received DUMPMEM command with an incorrect argument.") return dump_memory(int(data)) def _handle_dumpreqs(self, data): if not data.isdigit(): log.warning("Received DUMPREQS command with an incorrect argument %r.", data) return pid = int(data) if pid not in self.tracked: log.warning("Received DUMPREQS command but there are no reqs for pid %d.", pid) return dumpreqs = self.tracked[pid].get("dumpreq", []) for addr, length in dumpreqs: log.debug("tracked dump req (%r, %r, %r)", pid, addr, length) if not addr or not length: continue Process(pid=pid).dump_memory_block(int(addr), int(length)) def _handle_track(self, data): if not data.count(":") == 2: log.warning("Received TRACK command with an incorrect argument %r.", data) return pid, scope, params = data.split(":", 2) pid = int(pid) paramtuple = params.split(",") if pid not in self.tracked: self.tracked[pid] = {} if scope not in self.tracked[pid]: self.tracked[pid][scope] = [] self.tracked[pid][scope].append(paramtuple) def dispatch(self, data): response = "NOPE" if not data or ":" not in data: log.critical("Unknown command received from the monitor: %r", data.strip()) else: # Backwards compatibility (old syntax is, e.g., "FILE_NEW:" vs the # new syntax, e.g., "1234:FILE_NEW:"). if data[0].isupper(): command, arguments = data.strip().split(":", 1) self.pid = None else: self.pid, command, arguments = data.strip().split(":", 2) fn = getattr(self, "_handle_%s" % command.lower(), None) if not fn: log.critical("Unknown command received from the monitor: %r", data.strip()) else: try: response = fn(arguments) except: log.exception( "Pipe command handler exception occurred (command " "%s args %r).", command, arguments ) return response class Analyzer(object): """Cuckoo Windows Analyzer. This class handles the initialization and execution of the analysis procedure, including handling of the pipe server, the auxiliary modules and the analysis packages. """ def __init__(self): self.config = None self.target = None self.do_run = True self.time_counter = 0 self.process_lock = threading.Lock() self.default_dll = None self.pid = os.getpid() self.ppid = Process(pid=self.pid).get_parent_pid() self.files = Files() self.process_list = ProcessList() self.package = None self.reboot = [] def get_pipe_path(self, name): """Returns \\\\.\\PIPE on Windows XP and \\??\\PIPE elsewhere.""" version = sys.getwindowsversion() if version.major == 5 and version.minor == 1: return "\\\\.\\PIPE\\%s" % name return "\\??\\PIPE\\%s" % name def prepare(self): """Prepare env for analysis.""" # Get SeDebugPrivilege for the Python process. It will be needed in # order to perform the injections. grant_privilege("SeDebugPrivilege") grant_privilege("SeLoadDriverPrivilege") # Initialize logging. init_logging() # Parse the analysis configuration file generated by the agent. self.config = Config(cfg="analysis.conf") # Pass the configuration through to the Process class. Process.set_config(self.config) # Set virtual machine clock. set_clock(datetime.datetime.strptime( self.config.clock, "%Y%m%dT%H:%M:%S" )) # Set the default DLL to be used for this analysis. self.default_dll = self.config.options.get("dll") # If a pipe name has not set, then generate a random one. self.config.pipe = self.get_pipe_path( self.config.options.get("pipe", random_string(16, 32)) ) # Generate a random name for the logging pipe server. self.config.logpipe = self.get_pipe_path(random_string(16, 32)) # Initialize and start the Command Handler pipe server. This is going # to be used for communicating with the monitored processes. self.command_pipe = PipeServer( PipeDispatcher, self.config.pipe, message=True, dispatcher=CommandPipeHandler(self) ) self.command_pipe.daemon = True self.command_pipe.start() # Initialize and start the Log Pipe Server - the log pipe server will # open up a pipe that monitored processes will use to send logs to # before they head off to the host machine. destination = self.config.ip, self.config.port self.log_pipe_server = PipeServer( PipeForwarder, self.config.logpipe, destination=destination ) self.log_pipe_server.daemon = True self.log_pipe_server.start() # We update the target according to its category. If it's a file, then # we store the target path. if self.config.category == "file": self.target = os.path.join( os.environ["TEMP"], self.config.file_name ) elif self.config.category == "archive": zip_path = os.path.join(os.environ["TEMP"], self.config.file_name) zipfile.ZipFile(zip_path).extractall(os.environ["TEMP"]) self.target = os.path.join( os.environ["TEMP"], self.config.options["filename"] ) # If it's a URL, well.. we store the URL. else: self.target = self.config.target def stop(self): """Allows an auxiliary module to stop the analysis.""" self.do_run = False def complete(self): """End analysis.""" # Stop the Pipe Servers. self.command_pipe.stop() self.log_pipe_server.stop() # Dump all the notified files. self.files.dump_files() # Hell yeah. log.info("Analysis completed.") def run(self): """Run analysis. @return: operation status. """ self.prepare() self.path = os.getcwd() log.debug("Starting analyzer from: %s", self.path) log.debug("Pipe server name: %s", self.config.pipe) log.debug("Log pipe server name: %s", self.config.logpipe) # If no analysis package was specified at submission, we try to select # one automatically. if not self.config.package: log.debug( "No analysis package specified, trying to detect " "it automagically." ) # If the analysis target is a file, we choose the package according # to the file format. if self.config.category == "file": package = choose_package( self.config.file_type, self.config.file_name, self.config.pe_exports.split(",") ) # If it's an URL, we'll just use the default Internet Explorer # package. else: package = "ie" # If we weren't able to automatically determine the proper package, # we need to abort the analysis. if not package: raise CuckooError("No valid package available for file " "type: {0}".format(self.config.file_type)) log.info("Automatically selected analysis package \"%s\"", package) # Otherwise just select the specified package. else: package = self.config.package # Generate the package path. package_name = "modules.packages.%s" % package # Try to import the analysis package. try: __import__(package_name, globals(), locals(), ["dummy"], -1) # If it fails, we need to abort the analysis. except ImportError: raise CuckooError("Unable to import package \"{0}\", does " "not exist.".format(package_name)) # Initialize the package parent abstract. Package() # Enumerate the abstract subclasses. try: package_class = Package.__subclasses__()[0] except IndexError as e: raise CuckooError("Unable to select package class " "(package={0}): {1}".format(package_name, e)) # Initialize the analysis package. self.package = package_class(self.config.options, analyzer=self) # Move the sample to the current working directory as provided by the # task - one is able to override the starting path of the sample. # E.g., for some samples it might be useful to run from %APPDATA% # instead of %TEMP%. if self.config.category == "file": self.target = self.package.move_curdir(self.target) # Initialize Auxiliary modules Auxiliary() prefix = auxiliary.__name__ + "." for loader, name, ispkg in pkgutil.iter_modules(auxiliary.__path__, prefix): if ispkg: continue # Import the auxiliary module. try: __import__(name, globals(), locals(), ["dummy"], -1) except ImportError as e: log.warning("Unable to import the auxiliary module " "\"%s\": %s", name, e) # Walk through the available auxiliary modules. aux_enabled, aux_avail = [], [] for module in Auxiliary.__subclasses__(): # Try to start the auxiliary module. try: aux = module(options=self.config.options, analyzer=self) aux_avail.append(aux) aux.init() aux.start() except (NotImplementedError, AttributeError): log.exception( "Auxiliary module %s was not implemented", module.__name__ ) except CuckooDisableModule: continue except Exception as e: log.exception( "Cannot execute auxiliary module %s: %s", module.__name__, e ) else: log.debug("Started auxiliary module %s", module.__name__) aux_enabled.append(aux) # Inform zer0m0n of the ResultServer address. zer0m0n.resultserver(self.config.ip, self.config.port) # Forward the command pipe and logpipe names on to zer0m0n. zer0m0n.cmdpipe(self.config.pipe) zer0m0n.channel(self.config.logpipe) # Hide the Cuckoo Analyzer & Cuckoo Agent. zer0m0n.hidepid(self.pid) zer0m0n.hidepid(self.ppid) # Initialize zer0m0n with our compiled Yara rules. zer0m0n.yarald("bin/rules.yarac") # Propagate the requested dump interval, if set. zer0m0n.dumpint(int(self.config.options.get("dumpint", "0"))) # Start analysis package. If for any reason, the execution of the # analysis package fails, we have to abort the analysis. pids = self.package.start(self.target) # If the analysis package returned a list of process identifiers, we # add them to the list of monitored processes and enable the process monitor. if pids: self.process_list.add_pids(pids) pid_check = True # If the package didn't return any process ID (for example in the case # where the package isn't enabling any behavioral analysis), we don't # enable the process monitor. else: log.info("No process IDs returned by the package, running " "for the full timeout.") pid_check = False # Check in the options if the user toggled the timeout enforce. If so, # we need to override pid_check and disable process monitor. if self.config.enforce_timeout: log.info("Enabled timeout enforce, running for the full timeout.") pid_check = False while self.do_run: self.time_counter += 1 if self.time_counter == int(self.config.timeout): log.info("Analysis timeout hit, terminating analysis.") break # If the process lock is locked, it means that something is # operating on the list of monitored processes. Therefore we # cannot proceed with the checks until the lock is released. if self.process_lock.locked(): KERNEL32.Sleep(1000) continue try: # If the process monitor is enabled we start checking whether # the monitored processes are still alive. if pid_check: # We also track the PIDs provided by zer0m0n. self.process_list.add_pids(zer0m0n.getpids()) for pid in self.process_list.pids: if not Process(pid=pid).is_alive(): log.info("Process with pid %s has terminated", pid) self.process_list.remove_pid(pid) # If none of the monitored processes are still alive, we # can terminate the analysis. if not self.process_list.pids: log.info("Process list is empty, " "terminating analysis.") break # Update the list of monitored processes available to the # analysis package. It could be used for internal # operations within the module. self.package.set_pids(self.process_list.pids) try: # The analysis packages are provided with a function that # is executed at every loop's iteration. If such function # returns False, it means that it requested the analysis # to be terminate. if not self.package.check(): log.info("The analysis package requested the " "termination of the analysis.") break # If the check() function of the package raised some exception # we don't care, we can still proceed with the analysis but we # throw a warning. except Exception as e: log.warning("The package \"%s\" check function raised " "an exception: %s", package_name, e) finally: # Zzz. KERNEL32.Sleep(1000) if not self.do_run: log.debug("The analyzer has been stopped on request by an " "auxiliary module.") # Create the shutdown mutex. KERNEL32.CreateMutexA(None, False, SHUTDOWN_MUTEX) try: # Before shutting down the analysis, the package can perform some # final operations through the finish() function. self.package.finish() except Exception as e: log.warning("The package \"%s\" finish function raised an " "exception: %s", package_name, e) try: # Upload files the package created to package_files in the # results folder. for path, name in self.package.package_files() or []: upload_to_host(path, os.path.join("package_files", name)) except Exception as e: log.warning("The package \"%s\" package_files function raised an " "exception: %s", package_name, e) # Terminate the Auxiliary modules. for aux in aux_enabled: try: aux.stop() except (NotImplementedError, AttributeError): continue except Exception as e: log.warning("Cannot terminate auxiliary module %s: %s", aux.__class__.__name__, e) if self.config.terminate_processes: # Try to terminate remaining active processes. log.info("Terminating remaining processes before shutdown.") for pid in self.process_list.pids: proc = Process(pid=pid) if proc.is_alive(): try: proc.terminate() except: continue # Run the finish callback of every available Auxiliary module. for aux in aux_avail: try: aux.finish() except (NotImplementedError, AttributeError): continue except Exception as e: log.warning("Exception running finish callback of auxiliary " "module %s: %s", aux.__class__.__name__, e) # Let's invoke the completion procedure. self.complete() return True if __name__ == "__main__": success = False error = "" try: # Initialize the main analyzer class. analyzer = Analyzer() # Run it and wait for the response. success = analyzer.run() data = { "status": "complete", "description": success, } # This is not likely to happen. except KeyboardInterrupt: error = "Keyboard Interrupt" # If the analysis process encountered a critical error, it will raise a # CuckooError exception, which will force the termination of the analysis. # Notify the agent of the failure. Also catch unexpected exceptions. except Exception as e: # Store the error. error_exc = traceback.format_exc() error = "%s\n%s" % (e, error_exc) # Just to be paranoid. if len(log.handlers): log.exception(error_exc) else: sys.stderr.write("{0}\n".format(error_exc)) data = { "status": "exception", "description": error_exc, } finally: # Report that we're finished. First try with the XML RPC thing and # if that fails, attempt the new Agent. try: server = xmlrpclib.Server("http://127.0.0.1:8000") server.complete(success, error, "unused_path") except xmlrpclib.ProtocolError: urllib2.urlopen("http://127.0.0.1:8000/status", urllib.urlencode(data)).read()
from __future__ import annotations from typing import Dict, Text, Union, List, Tuple from rasa.utils.io import WriteRow from pathlib import Path import csv import numpy as np from rasa.core.evaluation.marker_base import EventMetaData def compute_statistics( values: List[Union[float, int]] ) -> Dict[Text, Union[int, np.float]]: """Computes some statistics over the given numbers.""" return { "count": len(values) if values else 0, "mean": np.mean(values) if values else np.nan, "median": np.median(values) if values else np.nan, "min": min(values) if values else np.nan, "max": max(values) if values else np.nan, } class MarkerStatistics: """Computes some statistics on marker extraction results. (1) Number of sessions where markers apply: For each marker, we compute the total number (as well as the percentage) of sessions in which a marker applies at least once. Moreover, we output the total number of sessions that were parsed. (2) Number of user turns preceding relevant events - per sessions: For each marker, we consider all relevant events where that marker applies. Everytime a marker applies, we check how many user turns precede that event. We collect all these numbers and compute basic statistics (e.g. count and mean) on them. This means, per session, we compute how often a marker applies and how many user turns precede a relevant marker application on average, in that session. (3) Number of user turns preceding relevant events - over all sessions: Here, for each marker, we consider all relevant events where a marker applies *in any of the sessions*. Then, we again calculate basic statistics over the respective number of user turns that precede each of these events. This means, we compute how many events the marker applies in total and we compute an estimate of the expected number of user turns preceding that precede an (relevant) event where a marker applies. """ NO_MARKER = "-" STAT_NUM_SESSIONS = "total_number_of_sessions" STAT_NUM_SESSIONS_WHERE_APPLIES = ( "number_of_sessions_where_marker_applied_at_least_once" ) STAT_PERCENTAGE_SESSIONS_WHERE_APPLIES = ( "percentage_of_sessions_where_marker_applied_at_least_once" ) @staticmethod def _add_num_user_turns_str_to(stat_name: Text) -> Text: return f"{stat_name}(number of preceding user turns)" ALL_SESSIONS = np.nan ALL_SENDERS = "all" def __init__(self) -> None: """Creates a new marker statistics object.""" # to ensure consistency of processed rows self._marker_names = [] # (1) For collecting the per-session analysis: # NOTE: we could stream / compute them later instead of collecting them... self.session_results: Dict[Text, Dict[Text, List[Union[int, float]]]] = {} self.session_identifier: List[Tuple[Text, int]] = [] # (2) For the overall statistics: self.num_preceding_user_turns_collected: Dict[Text, List[int]] = {} self.count_if_applied_at_least_once: Dict[Text, int] = {} self.num_sessions = 0 def process( self, sender_id: Text, session_idx: int, meta_data_on_relevant_events_per_marker: Dict[Text, List[EventMetaData]], ) -> None: """Processes the meta data that was extracted from a single session. Internally, this method .. 1. computes some statistics for the given meta data and saves it for later 2. keeps track of the total number of sessions processed and the collects all metadata to be able to compute meta data over *all* Args: sender_id: an id that, together with the `session_idx` identifies the session from which the markers where extracted session_idx: an index that, together with the `sender_id` identifies the session from which the markers where extracted meta_data_on_relevant_events_per_marker: marker extraction results, i.e. a dictionary mapping marker names to the meta data describing relevant events for those markers """ if len(self._marker_names) == 0: # sort and initialise here once so our result tables are sorted self._marker_names = sorted(meta_data_on_relevant_events_per_marker.keys()) self.count_if_applied_at_least_once = { marker_name: 0 for marker_name in self._marker_names } self.num_preceding_user_turns_collected = { marker_name: [] for marker_name in self._marker_names } # NOTE: we could stream / compute them later instead of collecting them... stat_names = sorted(compute_statistics([]).keys()) self.session_results = { marker_name: {stat_name: [] for stat_name in stat_names} for marker_name in self._marker_names } else: given_markers = meta_data_on_relevant_events_per_marker.keys() if set(given_markers) != set(self._marker_names): raise RuntimeError( f"Expected all processed extraction results to contain information" f"for the same set of markers. But found " f"{sorted(given_markers)} which differs from " f"the marker extracted so far (i.e. {sorted(self._marker_names)})." ) # update session identifiers / count self.num_sessions += 1 self.session_identifier.append((sender_id, session_idx)) for marker_name, meta_data in meta_data_on_relevant_events_per_marker.items(): num_preceding_user_turns = [ event_meta_data.preceding_user_turns for event_meta_data in meta_data ] # update per session statistics statistics = compute_statistics(num_preceding_user_turns) for stat_name, stat_value in statistics.items(): self.session_results[marker_name][stat_name].append(stat_value) # update overall statistics self.num_preceding_user_turns_collected[marker_name].extend( num_preceding_user_turns ) if len(num_preceding_user_turns): self.count_if_applied_at_least_once[marker_name] += 1 def overall_statistic_to_csv(self, path: Path, overwrite: bool = False) -> None: """Exports the overall statistics (over all processes sessions) to a csv file. Args: path: path to where the csv file should be written. overwrite: set to `True` to enable overwriting an existing file """ if path.is_file() and not overwrite: raise FileExistsError(f"Expected that there was no file at {path}.") with path.open(mode="w") as f: table_writer = csv.writer(f) table_writer.writerow(self._header()) self._write_overview(table_writer) self._write_overall_statistics(table_writer) def per_session_statistics_to_csv( self, path: Path, overwrite: bool = False ) -> None: """Exports the resulting statistics to a csv file. Args: path: path to where the csv file should be written. overwrite: set to `True` to enable overwriting an existing file """ if path.is_file() and not overwrite: raise FileExistsError(f"Expected that there was no file at {path}.") with path.open(mode="w") as f: table_writer = csv.writer(f) table_writer.writerow(self._header()) # NOTE: we could stream / compute them later instead of collecting them... self._write_per_session_statistics(table_writer) @staticmethod def _header() -> List[Text]: return [ "sender_id", "session_idx", "marker", "statistic", "value", ] def _write_overview(self, table_writer: WriteRow) -> None: special_sender_idx = self.ALL_SENDERS special_session_idx = self.ALL_SESSIONS self._write_row( table_writer=table_writer, sender_id=special_sender_idx, session_idx=special_session_idx, marker_name=self.NO_MARKER, statistic_name=self.STAT_NUM_SESSIONS, statistic_value=self.num_sessions, ) for marker_name, count in self.count_if_applied_at_least_once.items(): self._write_row( table_writer=table_writer, sender_id=special_sender_idx, session_idx=special_session_idx, marker_name=marker_name, statistic_name=self.STAT_NUM_SESSIONS_WHERE_APPLIES, statistic_value=count, ) self._write_row( table_writer=table_writer, sender_id=special_sender_idx, session_idx=special_session_idx, marker_name=marker_name, statistic_name=self.STAT_PERCENTAGE_SESSIONS_WHERE_APPLIES, statistic_value=(count / self.num_sessions * 100) if self.num_sessions else 100.0, ) def _write_overall_statistics(self, table_writer: WriteRow) -> None: for marker_name, num_list in self.num_preceding_user_turns_collected.items(): for statistic_name, value in compute_statistics(num_list).items(): MarkerStatistics._write_row( table_writer=table_writer, sender_id=self.ALL_SENDERS, session_idx=self.ALL_SESSIONS, marker_name=marker_name, statistic_name=self._add_num_user_turns_str_to(statistic_name), statistic_value=value, ) def _write_per_session_statistics(self, table_writer: WriteRow) -> None: for marker_name, collected_statistics in self.session_results.items(): for statistic_name, values in collected_statistics.items(): self._write_per_session_statistic( table_writer=table_writer, marker_name=marker_name, statistic_name=statistic_name, session_identifiers=self.session_identifier, values=values, ) @staticmethod def _write_per_session_statistic( table_writer: WriteRow, marker_name: Text, statistic_name: Text, session_identifiers: List[Tuple[Text, int]], values: List[Union[np.float, int]], ) -> None: for record_idx, (sender_id, session_idx) in enumerate(session_identifiers): MarkerStatistics._write_row( table_writer=table_writer, sender_id=sender_id, session_idx=session_idx, marker_name=marker_name, statistic_name=MarkerStatistics._add_num_user_turns_str_to( statistic_name ), statistic_value=values[record_idx], ) @staticmethod def _write_row( table_writer: WriteRow, sender_id: Text, session_idx: Union[int, np.float], marker_name: Text, statistic_name: Text, statistic_value: Union[int, np.float], ) -> None: if isinstance(statistic_value, int): value_str = str(statistic_value) elif np.isnan(statistic_value): value_str = str(np.nan) else: value_str = np.round(statistic_value, 3) table_writer.writerow( [ str(item) for item in [ sender_id, session_idx, marker_name, statistic_name, value_str, ] ] )
from __future__ import division from itertools import izip import math, random, copy, sys import pygame as pg from .. import setup, observer from .. import constants as c #Python 2/3 compatibility. if sys.version_info[0] == 2: range = xrange class Trigger(pg.sprite.Sprite): def __init__(self, left, top): super(Trigger, self).__init__() self.rect = pg.Rect(left, top, 32, 32) self.dialogue = None self.location = self.get_tile_location() def get_tile_location(self): """ Convert pygame coordinates into tile coordinates. """ if self.rect.x == 0: tile_x = 0 elif self.rect.x % 32 == 0: tile_x = (self.rect.x / 32) else: tile_x = 0 if self.rect.y == 0: tile_y = 0 elif self.rect.y % 32 == 0: tile_y = (self.rect.y / 32) else: tile_y = 0 return [tile_x, tile_y] class Person(pg.sprite.Sprite): """Base class for all world characters controlled by the computer""" def __init__(self, sheet_key, x, y, direction='down', state='resting', index=0): super(Person, self).__init__() self.alpha = 255 self.name = sheet_key self.get_image = setup.tools.get_image self.spritesheet_dict = self.create_spritesheet_dict(sheet_key) self.animation_dict = self.create_animation_dict() self.index = index self.direction = direction self.image_list = self.animation_dict[self.direction] self.image = self.image_list[self.index] self.rect = self.image.get_rect(left=x, top=y) self.origin_pos = self.rect.topleft self.state_dict = self.create_state_dict() self.vector_dict = self.create_vector_dict() self.x_vel = 0 self.y_vel = 0 self.timer = 0.0 self.move_timer = 0.0 self.current_time = 0.0 self.state = state self.blockers = self.set_blockers() self.location = self.get_tile_location() self.dialogue = ['Location: ' + str(self.location)] self.default_direction = direction self.item = None self.wander_box = self.make_wander_box() self.observers = [observer.SoundEffects()] self.health = 0 self.death_image = pg.transform.scale2x(self.image) self.battle = None def create_spritesheet_dict(self, sheet_key): """ Make a dictionary of images from sprite sheet. """ image_list = [] image_dict = {} sheet = setup.GFX[sheet_key] image_keys = ['facing up 1', 'facing up 2', 'facing down 1', 'facing down 2', 'facing left 1', 'facing left 2', 'facing right 1', 'facing right 2'] for row in range(2): for column in range(4): image_list.append( self.get_image(column*32, row*32, 32, 32, sheet)) for key, image in izip(image_keys, image_list): image_dict[key] = image return image_dict def create_animation_dict(self): """ Return a dictionary of image lists for animation. """ image_dict = self.spritesheet_dict left_list = [image_dict['facing left 1'], image_dict['facing left 2']] right_list = [image_dict['facing right 1'], image_dict['facing right 2']] up_list = [image_dict['facing up 1'], image_dict['facing up 2']] down_list = [image_dict['facing down 1'], image_dict['facing down 2']] direction_dict = {'left': left_list, 'right': right_list, 'up': up_list, 'down': down_list} return direction_dict def create_state_dict(self): """ Return a dictionary of all state methods. """ state_dict = {'resting': self.resting, 'moving': self.moving, 'animated resting': self.animated_resting, 'autoresting': self.auto_resting, 'automoving': self.auto_moving, 'battle resting': self.battle_resting, 'attack': self.attack, 'enemy attack': self.enemy_attack, c.RUN_AWAY: self.run_away, c.VICTORY_DANCE: self.victory_dance, c.KNOCK_BACK: self.knock_back, c.FADE_DEATH: self.fade_death} return state_dict def create_vector_dict(self): """ Return a dictionary of x and y velocities set to direction keys. """ vector_dict = {'up': (0, -1), 'down': (0, 1), 'left': (-1, 0), 'right': (1, 0)} return vector_dict def update(self, current_time, *args): """ Update sprite. """ self.blockers = self.set_blockers() self.current_time = current_time self.image_list = self.animation_dict[self.direction] state_function = self.state_dict[self.state] state_function() self.location = self.get_tile_location() def set_blockers(self): """ Sets blockers to prevent collision with other sprites. """ blockers = [] if self.state == 'resting' or self.state == 'autoresting': blockers.append(pg.Rect(self.rect.x, self.rect.y, 32, 32)) elif self.state == 'moving' or self.state == 'automoving': if self.rect.x % 32 == 0: tile_float = self.rect.y / float(32) tile1 = (self.rect.x, math.ceil(tile_float)*32) tile2 = (self.rect.x, math.floor(tile_float)*32) tile_rect1 = pg.Rect(tile1[0], tile1[1], 32, 32) tile_rect2 = pg.Rect(tile2[0], tile2[1], 32, 32) blockers.extend([tile_rect1, tile_rect2]) elif self.rect.y % 32 == 0: tile_float = self.rect.x / float(32) tile1 = (math.ceil(tile_float)*32, self.rect.y) tile2 = (math.floor(tile_float)*32, self.rect.y) tile_rect1 = pg.Rect(tile1[0], tile1[1], 32, 32) tile_rect2 = pg.Rect(tile2[0], tile2[1], 32, 32) blockers.extend([tile_rect1, tile_rect2]) return blockers def get_tile_location(self): """ Convert pygame coordinates into tile coordinates. """ if self.rect.x == 0: tile_x = 0 elif self.rect.x % 32 == 0: tile_x = (self.rect.x / 32) else: tile_x = 0 if self.rect.y == 0: tile_y = 0 elif self.rect.y % 32 == 0: tile_y = (self.rect.y / 32) else: tile_y = 0 return [tile_x, tile_y] def make_wander_box(self): """ Make a list of rects that surround the initial location of a sprite to limit his/her wandering. """ x = int(self.location[0]) y = int(self.location[1]) box_list = [] box_rects = [] for i in range(x-3, x+4): box_list.append([i, y-3]) box_list.append([i, y+3]) for i in range(y-2, y+3): box_list.append([x-3, i]) box_list.append([x+3, i]) for box in box_list: left = box[0]*32 top = box[1]*32 box_rects.append(pg.Rect(left, top, 32, 32)) return box_rects def resting(self): """ When the Person is not moving between tiles. Checks if the player is centered on a tile. """ self.image = self.image_list[self.index] if self.rect.y % 32 != 0: self.correct_position(self.rect.y) if self.rect.x % 32 != 0: self.correct_position(self.rect.x) def moving(self): """ Increment index and set self.image for animation. """ self.animation() assert(self.rect.x % 32 == 0 or self.rect.y % 32 == 0), \ 'Not centered on tile' def animated_resting(self): self.animation(500) def animation(self, freq=100): """ Adjust sprite image frame based on timer. """ if (self.current_time - self.timer) > freq: if self.index < (len(self.image_list) - 1): self.index += 1 else: self.index = 0 self.timer = self.current_time self.image = self.image_list[self.index] def begin_moving(self, direction): """ Transition the player into the 'moving' state. """ self.direction = direction self.image_list = self.animation_dict[direction] self.timer = self.current_time self.move_timer = self.current_time self.state = 'moving' if self.rect.x % 32 == 0: self.y_vel = self.vector_dict[self.direction][1] if self.rect.y % 32 == 0: self.x_vel = self.vector_dict[self.direction][0] def begin_resting(self): """ Transition the player into the 'resting' state. """ self.state = 'resting' self.index = 1 self.x_vel = self.y_vel = 0 def begin_auto_moving(self, direction): """ Transition sprite to a automatic moving state. """ self.direction = direction self.image_list = self.animation_dict[direction] self.state = 'automoving' self.x_vel = self.vector_dict[direction][0] self.y_vel = self.vector_dict[direction][1] self.move_timer = self.current_time def begin_auto_resting(self): """ Transition sprite to an automatic resting state. """ self.state = 'autoresting' self.index = 1 self.x_vel = self.y_vel = 0 self.move_timer = self.current_time def auto_resting(self): """ Determine when to move a sprite from resting to moving in a random direction. """ self.image_list = self.animation_dict[self.direction] self.image = self.image_list[self.index] if self.rect.y % 32 != 0: self.correct_position(self.rect.y) if self.rect.x % 32 != 0: self.correct_position(self.rect.x) if (self.current_time - self.move_timer) > 2000: direction_list = ['up', 'down', 'left', 'right'] random.shuffle(direction_list) direction = direction_list[0] self.begin_auto_moving(direction) self.move_timer = self.current_time def correct_position(self, rect_pos): """ Adjust sprite position to be centered on tile. """ diff = rect_pos % 32 if diff <= 16: rect_pos - diff else: rect_pos + diff def battle_resting(self): """ Player stays still during battle state unless he attacks. """ pass def enter_attack_state(self, enemy): """ Set values for attack state. """ self.notify(c.SWORD) self.attacked_enemy = enemy self.x_vel = -5 self.state = 'attack' def enter_spell_state(self, enemies): self.notify(c.FIRE) self.attacked_enemy = enemies self.x_vel = -5 self.state = 'attack' def attack(self): """ Player does an attack animation. """ FAST_FORWARD = -5 FAST_BACK = 5 self.rect.x += self.x_vel if self.x_vel == FAST_FORWARD: self.image = self.spritesheet_dict['facing left 1'] self.image = pg.transform.scale2x(self.image) if self.rect.x <= self.origin_pos[0] - 110: self.x_vel = FAST_BACK self.notify(c.ENEMY_DAMAGED) else: if self.rect.x >= self.origin_pos[0]: self.rect.x = self.origin_pos[0] self.x_vel = 0 self.state = 'battle resting' self.image = self.spritesheet_dict['facing left 2'] self.image = pg.transform.scale2x(self.image) self.notify(c.PLAYER_FINISHED_ATTACK) def enter_enemy_attack_state(self, mon): """ Set values for enemy attack state. """ self.x_vel = -5 self.state = 'enemy attack' self.attacked_monster = mon self.origin_pos = self.rect.topleft self.move_counter = 0 def enemy_attack(self): """ Enemy does an attack animation. """ FAST_LEFT = -5 FAST_RIGHT = 5 STARTX = self.origin_pos[0] self.rect.x += self.x_vel if self.move_counter == 3: self.x_vel = 0 self.state = 'battle resting' self.rect.x = STARTX self.notify(c.PLAYER_DAMAGED) elif self.x_vel == FAST_LEFT: if self.rect.x <= (STARTX - 15): self.x_vel = FAST_RIGHT elif self.x_vel == FAST_RIGHT: if self.rect.x >= (STARTX + 15): self.move_counter += 1 self.x_vel = FAST_LEFT def auto_moving(self): """ Animate sprite and check to stop. """ self.animation() assert(self.rect.x % 32 == 0 or self.rect.y % 32 == 0), \ 'Not centered on tile' def notify(self, event): """ Notify all observers of events. """ for observer in self.observers: observer.on_notify(event) def calculate_hit(self, armor_list, inventory): """ Calculate hit strength based on attack stats. """ armor_power = 0 for armor in armor_list: armor_power += inventory[armor]['power'] max_strength = max(1, (self.level * 5) - armor_power) min_strength = 0 return random.randint(min_strength, max_strength) def run_away(self): """ Run away from battle state. """ X_VEL = 5 self.rect.x += X_VEL self.direction = 'right' self.small_image_list = self.animation_dict[self.direction] self.image_list = [] for image in self.small_image_list: self.image_list.append(pg.transform.scale2x(image)) self.animation() def victory_dance(self): """ Post Victory Dance. """ self.small_image_list = self.animation_dict[self.direction] self.image_list = [] for image in self.small_image_list: self.image_list.append(pg.transform.scale2x(image)) self.animation(500) def knock_back(self): """ Knock back when hit. """ FORWARD_VEL = -2 self.rect.x += self.x_vel if self.name == 'player': if self.rect.x >= (self.origin_pos[0] + 10): self.x_vel = FORWARD_VEL elif self.rect.x <= self.origin_pos[0]: self.rect.x = self.origin_pos[0] self.state = 'battle resting' self.x_vel = 0 else: if self.rect.x <= (self.origin_pos[0] - 10): self.x_vel = 2 elif self.rect.x >= self.origin_pos[0]: self.rect.x = self.origin_pos[0] self.state = 'battle resting' self.x_vel = 0 def fade_death(self): """ Make character become transparent in death. """ self.image = pg.Surface((64, 64)).convert() self.image.set_colorkey(c.BLACK) self.image.set_alpha(self.alpha) self.image.blit(self.death_image, (0, 0)) self.alpha -= 8 if self.alpha <= 0: self.kill() self.notify(c.ENEMY_DEAD) def enter_knock_back_state(self): """ Set values for entry to knock back state. """ if self.name == 'player': self.x_vel = 4 else: self.x_vel = -4 self.state = c.KNOCK_BACK self.origin_pos = self.rect.topleft class Player(Person): """ User controlled character. """ def __init__(self, direction, game_data, x=0, y=0, state='resting', index=0, name='Hanami Otozono'): super(Player, self).__init__(name, x, y, direction, state, index) self.damaged = False self.healing = False self.damage_alpha = 0 self.healing_alpha = 0 self.fade_in = True self.game_data = game_data self.index = 1 self.image = self.image_list[self.index] @property def level(self): """ Make level property equal to player level in game_data. """ return self.game_data['player stats']['Level'] def create_vector_dict(self): """Return a dictionary of x and y velocities set to direction keys.""" vector_dict = {'up': (0, -2), 'down': (0, 2), 'left': (-2, 0), 'right': (2, 0)} return vector_dict def update(self, keys, current_time): """Updates player behavior""" self.current_time = current_time self.damage_animation() self.healing_animation() self.blockers = self.set_blockers() self.keys = keys self.check_for_input() state_function = self.state_dict[self.state] state_function() self.location = self.get_tile_location() def damage_animation(self): """ Put a red overlay over sprite to indicate damage. """ if self.damaged: self.image = copy.copy(self.spritesheet_dict['facing left 2']) self.image = pg.transform.scale2x(self.image).convert_alpha() damage_image = copy.copy(self.image).convert_alpha() damage_image.fill((255, 0, 0, self.damage_alpha), special_flags=pg.BLEND_RGBA_MULT) self.image.blit(damage_image, (0, 0)) if self.fade_in: self.damage_alpha += 25 if self.damage_alpha >= 255: self.fade_in = False self.damage_alpha = 255 elif not self.fade_in: self.damage_alpha -= 25 if self.damage_alpha <= 0: self.damage_alpha = 0 self.damaged = False self.fade_in = True self.image = self.spritesheet_dict['facing left 2'] self.image = pg.transform.scale2x(self.image) def healing_animation(self): """ Put a green overlay over sprite to indicate healing. """ if self.healing: self.image = copy.copy(self.spritesheet_dict['facing left 2']) self.image = pg.transform.scale2x(self.image).convert_alpha() healing_image = copy.copy(self.image).convert_alpha() healing_image.fill((0, 255, 0, self.healing_alpha), special_flags=pg.BLEND_RGBA_MULT) self.image.blit(healing_image, (0, 0)) if self.fade_in: self.healing_alpha += 25 if self.healing_alpha >= 255: self.fade_in = False self.healing_alpha = 255 elif not self.fade_in: self.healing_alpha -= 25 if self.healing_alpha <= 0: self.healing_alpha = 0 self.healing = False self.fade_in = True self.image = self.spritesheet_dict['facing left 2'] self.image = pg.transform.scale2x(self.image) def check_for_input(self): """Checks for player input""" if self.state == 'resting': if self.keys[pg.K_UP]: self.begin_moving('up') elif self.keys[pg.K_DOWN]: self.begin_moving('down') elif self.keys[pg.K_LEFT]: self.begin_moving('left') elif self.keys[pg.K_RIGHT]: self.begin_moving('right') def calculate_hit(self): """ Calculate hit strength based on attack stats. """ weapon = self.game_data['player inventory']['equipped weapon'] weapon_power = self.game_data['player inventory'][weapon]['power'] max_strength = weapon_power min_strength = max_strength - 7 return random.randint(min_strength, max_strength) class Enemy(Person): """ Enemy sprite. """ def __init__(self, sheet_key, x, y, direction='down', state='resting', index=0): super(Enemy, self).__init__(sheet_key, x, y, direction, state, index) self.level = 1 self.type = 'enemy' self.attacked_monster = None class Chest(Person): """ Treasure chest that contains items to collect. """ def __init__(self, x, y, id): super(Chest, self).__init__('treasurechest', x, y) self.spritesheet_dict = self.make_image_dict() self.image_list = self.make_image_list() self.image = self.image_list[self.index] self.rect = self.image.get_rect(x=x, y=y) self.id = id def make_image_dict(self): """ Make a dictionary for the sprite's images. """ sprite_sheet = setup.GFX['treasurechest'] image_dict = {'closed': self.get_image(0, 0, 32, 32, sprite_sheet), 'opened': self.get_image(32, 0, 32, 32, sprite_sheet)} return image_dict def make_image_list(self): """ Make the list of two images for the chest. """ image_list = [self.spritesheet_dict['closed'], self.spritesheet_dict['opened']] return image_list def update(self, current_time, *args): """Implemented by inheriting classes""" self.blockers = self.set_blockers() self.current_time = current_time state_function = self.state_dict[self.state] state_function() self.location = self.get_tile_location()
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import warnings from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.ads.googleads.v8.resources.types import bidding_strategy_simulation from google.ads.googleads.v8.services.types import ( bidding_strategy_simulation_service, ) from .base import BiddingStrategySimulationServiceTransport, DEFAULT_CLIENT_INFO class BiddingStrategySimulationServiceGrpcTransport( BiddingStrategySimulationServiceTransport ): """gRPC backend transport for BiddingStrategySimulationService. Service to fetch bidding strategy simulations. This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation and call it. It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ def __init__( self, *, host: str = "googleads.googleapis.com", credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, ssl_channel_credentials: grpc.ChannelCredentials = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if ``channel`` is provided. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if ``channel`` is provided. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if ``channel`` is provided. channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or applicatin default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials for grpc channel. It is ignored if ``channel`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. """ self._ssl_channel_credentials = ssl_channel_credentials if channel: # Sanity check: Ensure that channel and credentials are not both # provided. credentials = False # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None elif api_mtls_endpoint: warnings.warn( "api_mtls_endpoint and client_cert_source are deprecated", DeprecationWarning, ) host = ( api_mtls_endpoint if ":" in api_mtls_endpoint else api_mtls_endpoint + ":443" ) if credentials is None: credentials, _ = google.auth.default( scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id ) # Create SSL credentials with client_cert_source or application # default SSL credentials. if client_cert_source: cert, key = client_cert_source() ssl_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) else: ssl_credentials = SslCredentials().ssl_credentials # create a new channel. The provided one is ignored. self._grpc_channel = type(self).create_channel( host, credentials=credentials, credentials_file=credentials_file, ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) self._ssl_channel_credentials = ssl_credentials else: host = host if ":" in host else host + ":443" if credentials is None: credentials, _ = google.auth.default(scopes=self.AUTH_SCOPES) # create a new channel. The provided one is ignored. self._grpc_channel = type(self).create_channel( host, credentials=credentials, ssl_credentials=ssl_channel_credentials, scopes=self.AUTH_SCOPES, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) self._stubs = {} # type: Dict[str, Callable] # Run the base constructor. super().__init__( host=host, credentials=credentials, client_info=client_info, ) @classmethod def create_channel( cls, host: str = "googleads.googleapis.com", credentials: ga_credentials.Credentials = None, scopes: Optional[Sequence[str]] = None, **kwargs, ) -> grpc.Channel: """Create and return a gRPC channel object. Args: address (Optionsl[str]): The host for the channel to use. credentials (Optional[~.Credentials]): The authorization credentials to attach to requests. These credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. kwargs (Optional[dict]): Keyword arguments, which are passed to the channel creation. Returns: grpc.Channel: A gRPC channel object. """ return grpc_helpers.create_channel( host, credentials=credentials, scopes=scopes or cls.AUTH_SCOPES, **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: """Return the channel designed to connect to this service. """ return self._grpc_channel @property def get_bidding_strategy_simulation( self, ) -> Callable[ [ bidding_strategy_simulation_service.GetBiddingStrategySimulationRequest ], bidding_strategy_simulation.BiddingStrategySimulation, ]: r"""Return a callable for the get bidding strategy simulation method over gRPC. Returns the requested bidding strategy simulation in full detail. Returns: Callable[[~.GetBiddingStrategySimulationRequest], ~.BiddingStrategySimulation]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_bidding_strategy_simulation" not in self._stubs: self._stubs[ "get_bidding_strategy_simulation" ] = self.grpc_channel.unary_unary( "/google.ads.googleads.v8.services.BiddingStrategySimulationService/GetBiddingStrategySimulation", request_serializer=bidding_strategy_simulation_service.GetBiddingStrategySimulationRequest.serialize, response_deserializer=bidding_strategy_simulation.BiddingStrategySimulation.deserialize, ) return self._stubs["get_bidding_strategy_simulation"] __all__ = ("BiddingStrategySimulationServiceGrpcTransport",)
import pytest import numpy as np from scipy import sparse from scipy.sparse import csgraph from scipy.linalg import eigh from sklearn.manifold import SpectralEmbedding from sklearn.manifold._spectral_embedding import _graph_is_connected from sklearn.manifold._spectral_embedding import _graph_connected_component from sklearn.manifold import spectral_embedding from sklearn.metrics.pairwise import rbf_kernel from sklearn.metrics import normalized_mutual_info_score from sklearn.neighbors import NearestNeighbors from sklearn.cluster import KMeans from sklearn.datasets import make_blobs from sklearn.utils.extmath import _deterministic_vector_sign_flip from sklearn.utils._testing import assert_array_almost_equal from sklearn.utils._testing import assert_array_equal # non centered, sparse centers to check the centers = np.array( [ [0.0, 5.0, 0.0, 0.0, 0.0], [0.0, 0.0, 4.0, 0.0, 0.0], [1.0, 0.0, 0.0, 5.0, 1.0], ] ) n_samples = 1000 n_clusters, n_features = centers.shape S, true_labels = make_blobs( n_samples=n_samples, centers=centers, cluster_std=1.0, random_state=42 ) def _assert_equal_with_sign_flipping(A, B, tol=0.0): """Check array A and B are equal with possible sign flipping on each columns""" tol_squared = tol ** 2 for A_col, B_col in zip(A.T, B.T): assert ( np.max((A_col - B_col) ** 2) <= tol_squared or np.max((A_col + B_col) ** 2) <= tol_squared ) def test_sparse_graph_connected_component(): rng = np.random.RandomState(42) n_samples = 300 boundaries = [0, 42, 121, 200, n_samples] p = rng.permutation(n_samples) connections = [] for start, stop in zip(boundaries[:-1], boundaries[1:]): group = p[start:stop] # Connect all elements within the group at least once via an # arbitrary path that spans the group. for i in range(len(group) - 1): connections.append((group[i], group[i + 1])) # Add some more random connections within the group min_idx, max_idx = 0, len(group) - 1 n_random_connections = 1000 source = rng.randint(min_idx, max_idx, size=n_random_connections) target = rng.randint(min_idx, max_idx, size=n_random_connections) connections.extend(zip(group[source], group[target])) # Build a symmetric affinity matrix row_idx, column_idx = tuple(np.array(connections).T) data = rng.uniform(0.1, 42, size=len(connections)) affinity = sparse.coo_matrix((data, (row_idx, column_idx))) affinity = 0.5 * (affinity + affinity.T) for start, stop in zip(boundaries[:-1], boundaries[1:]): component_1 = _graph_connected_component(affinity, p[start]) component_size = stop - start assert component_1.sum() == component_size # We should retrieve the same component mask by starting by both ends # of the group component_2 = _graph_connected_component(affinity, p[stop - 1]) assert component_2.sum() == component_size assert_array_equal(component_1, component_2) def test_spectral_embedding_two_components(seed=36): # Test spectral embedding with two components random_state = np.random.RandomState(seed) n_sample = 100 affinity = np.zeros(shape=[n_sample * 2, n_sample * 2]) # first component affinity[0:n_sample, 0:n_sample] = ( np.abs(random_state.randn(n_sample, n_sample)) + 2 ) # second component affinity[n_sample::, n_sample::] = ( np.abs(random_state.randn(n_sample, n_sample)) + 2 ) # Test of internal _graph_connected_component before connection component = _graph_connected_component(affinity, 0) assert component[:n_sample].all() assert not component[n_sample:].any() component = _graph_connected_component(affinity, -1) assert not component[:n_sample].any() assert component[n_sample:].all() # connection affinity[0, n_sample + 1] = 1 affinity[n_sample + 1, 0] = 1 affinity.flat[:: 2 * n_sample + 1] = 0 affinity = 0.5 * (affinity + affinity.T) true_label = np.zeros(shape=2 * n_sample) true_label[0:n_sample] = 1 se_precomp = SpectralEmbedding( n_components=1, affinity="precomputed", random_state=np.random.RandomState(seed) ) embedded_coordinate = se_precomp.fit_transform(affinity) # Some numpy versions are touchy with types embedded_coordinate = se_precomp.fit_transform(affinity.astype(np.float32)) # thresholding on the first components using 0. label_ = np.array(embedded_coordinate.ravel() < 0, dtype="float") assert normalized_mutual_info_score(true_label, label_) == pytest.approx(1.0) @pytest.mark.parametrize("X", [S, sparse.csr_matrix(S)], ids=["dense", "sparse"]) def test_spectral_embedding_precomputed_affinity(X, seed=36): # Test spectral embedding with precomputed kernel gamma = 1.0 se_precomp = SpectralEmbedding( n_components=2, affinity="precomputed", random_state=np.random.RandomState(seed) ) se_rbf = SpectralEmbedding( n_components=2, affinity="rbf", gamma=gamma, random_state=np.random.RandomState(seed), ) embed_precomp = se_precomp.fit_transform(rbf_kernel(X, gamma=gamma)) embed_rbf = se_rbf.fit_transform(X) assert_array_almost_equal(se_precomp.affinity_matrix_, se_rbf.affinity_matrix_) _assert_equal_with_sign_flipping(embed_precomp, embed_rbf, 0.05) def test_precomputed_nearest_neighbors_filtering(): # Test precomputed graph filtering when containing too many neighbors n_neighbors = 2 results = [] for additional_neighbors in [0, 10]: nn = NearestNeighbors(n_neighbors=n_neighbors + additional_neighbors).fit(S) graph = nn.kneighbors_graph(S, mode="connectivity") embedding = ( SpectralEmbedding( random_state=0, n_components=2, affinity="precomputed_nearest_neighbors", n_neighbors=n_neighbors, ) .fit(graph) .embedding_ ) results.append(embedding) assert_array_equal(results[0], results[1]) @pytest.mark.parametrize("X", [S, sparse.csr_matrix(S)], ids=["dense", "sparse"]) def test_spectral_embedding_callable_affinity(X, seed=36): # Test spectral embedding with callable affinity gamma = 0.9 kern = rbf_kernel(S, gamma=gamma) se_callable = SpectralEmbedding( n_components=2, affinity=(lambda x: rbf_kernel(x, gamma=gamma)), gamma=gamma, random_state=np.random.RandomState(seed), ) se_rbf = SpectralEmbedding( n_components=2, affinity="rbf", gamma=gamma, random_state=np.random.RandomState(seed), ) embed_rbf = se_rbf.fit_transform(X) embed_callable = se_callable.fit_transform(X) assert_array_almost_equal(se_callable.affinity_matrix_, se_rbf.affinity_matrix_) assert_array_almost_equal(kern, se_rbf.affinity_matrix_) _assert_equal_with_sign_flipping(embed_rbf, embed_callable, 0.05) # TODO: Remove when pyamg does replaces sp.rand call with np.random.rand # https://github.com/scikit-learn/scikit-learn/issues/15913 @pytest.mark.filterwarnings( "ignore:scipy.rand is deprecated:DeprecationWarning:pyamg.*" ) # TODO: Remove when pyamg removes the use of np.float @pytest.mark.filterwarnings( "ignore:`np.float` is a deprecated alias:DeprecationWarning:pyamg.*" ) # TODO: Remove when pyamg removes the use of pinv2 @pytest.mark.filterwarnings( "ignore:scipy.linalg.pinv2 is deprecated:DeprecationWarning:pyamg.*" ) def test_spectral_embedding_amg_solver(seed=36): # Test spectral embedding with amg solver pytest.importorskip("pyamg") se_amg = SpectralEmbedding( n_components=2, affinity="nearest_neighbors", eigen_solver="amg", n_neighbors=5, random_state=np.random.RandomState(seed), ) se_arpack = SpectralEmbedding( n_components=2, affinity="nearest_neighbors", eigen_solver="arpack", n_neighbors=5, random_state=np.random.RandomState(seed), ) embed_amg = se_amg.fit_transform(S) embed_arpack = se_arpack.fit_transform(S) _assert_equal_with_sign_flipping(embed_amg, embed_arpack, 1e-5) # same with special case in which amg is not actually used # regression test for #10715 # affinity between nodes row = [0, 0, 1, 2, 3, 3, 4] col = [1, 2, 2, 3, 4, 5, 5] val = [100, 100, 100, 1, 100, 100, 100] affinity = sparse.coo_matrix( (val + val, (row + col, col + row)), shape=(6, 6) ).toarray() se_amg.affinity = "precomputed" se_arpack.affinity = "precomputed" embed_amg = se_amg.fit_transform(affinity) embed_arpack = se_arpack.fit_transform(affinity) _assert_equal_with_sign_flipping(embed_amg, embed_arpack, 1e-5) # TODO: Remove filterwarnings when pyamg does replaces sp.rand call with # np.random.rand: # https://github.com/scikit-learn/scikit-learn/issues/15913 @pytest.mark.filterwarnings( "ignore:scipy.rand is deprecated:DeprecationWarning:pyamg.*" ) # TODO: Remove when pyamg removes the use of np.float @pytest.mark.filterwarnings( "ignore:`np.float` is a deprecated alias:DeprecationWarning:pyamg.*" ) # TODO: Remove when pyamg removes the use of pinv2 @pytest.mark.filterwarnings( "ignore:scipy.linalg.pinv2 is deprecated:DeprecationWarning:pyamg.*" ) def test_spectral_embedding_amg_solver_failure(): # Non-regression test for amg solver failure (issue #13393 on github) pytest.importorskip("pyamg") seed = 36 num_nodes = 100 X = sparse.rand(num_nodes, num_nodes, density=0.1, random_state=seed) upper = sparse.triu(X) - sparse.diags(X.diagonal()) sym_matrix = upper + upper.T embedding = spectral_embedding( sym_matrix, n_components=10, eigen_solver="amg", random_state=0 ) # Check that the learned embedding is stable w.r.t. random solver init: for i in range(3): new_embedding = spectral_embedding( sym_matrix, n_components=10, eigen_solver="amg", random_state=i + 1 ) _assert_equal_with_sign_flipping(embedding, new_embedding, tol=0.05) @pytest.mark.filterwarnings("ignore:the behavior of nmi will change in version 0.22") def test_pipeline_spectral_clustering(seed=36): # Test using pipeline to do spectral clustering random_state = np.random.RandomState(seed) se_rbf = SpectralEmbedding( n_components=n_clusters, affinity="rbf", random_state=random_state ) se_knn = SpectralEmbedding( n_components=n_clusters, affinity="nearest_neighbors", n_neighbors=5, random_state=random_state, ) for se in [se_rbf, se_knn]: km = KMeans(n_clusters=n_clusters, random_state=random_state) km.fit(se.fit_transform(S)) assert_array_almost_equal( normalized_mutual_info_score(km.labels_, true_labels), 1.0, 2 ) def test_spectral_embedding_unknown_eigensolver(seed=36): # Test that SpectralClustering fails with an unknown eigensolver se = SpectralEmbedding( n_components=1, affinity="precomputed", random_state=np.random.RandomState(seed), eigen_solver="<unknown>", ) with pytest.raises(ValueError): se.fit(S) def test_spectral_embedding_unknown_affinity(seed=36): # Test that SpectralClustering fails with an unknown affinity type se = SpectralEmbedding( n_components=1, affinity="<unknown>", random_state=np.random.RandomState(seed) ) with pytest.raises(ValueError): se.fit(S) def test_connectivity(seed=36): # Test that graph connectivity test works as expected graph = np.array( [ [1, 0, 0, 0, 0], [0, 1, 1, 0, 0], [0, 1, 1, 1, 0], [0, 0, 1, 1, 1], [0, 0, 0, 1, 1], ] ) assert not _graph_is_connected(graph) assert not _graph_is_connected(sparse.csr_matrix(graph)) assert not _graph_is_connected(sparse.csc_matrix(graph)) graph = np.array( [ [1, 1, 0, 0, 0], [1, 1, 1, 0, 0], [0, 1, 1, 1, 0], [0, 0, 1, 1, 1], [0, 0, 0, 1, 1], ] ) assert _graph_is_connected(graph) assert _graph_is_connected(sparse.csr_matrix(graph)) assert _graph_is_connected(sparse.csc_matrix(graph)) def test_spectral_embedding_deterministic(): # Test that Spectral Embedding is deterministic random_state = np.random.RandomState(36) data = random_state.randn(10, 30) sims = rbf_kernel(data) embedding_1 = spectral_embedding(sims) embedding_2 = spectral_embedding(sims) assert_array_almost_equal(embedding_1, embedding_2) def test_spectral_embedding_unnormalized(): # Test that spectral_embedding is also processing unnormalized laplacian # correctly random_state = np.random.RandomState(36) data = random_state.randn(10, 30) sims = rbf_kernel(data) n_components = 8 embedding_1 = spectral_embedding( sims, norm_laplacian=False, n_components=n_components, drop_first=False ) # Verify using manual computation with dense eigh laplacian, dd = csgraph.laplacian(sims, normed=False, return_diag=True) _, diffusion_map = eigh(laplacian) embedding_2 = diffusion_map.T[:n_components] embedding_2 = _deterministic_vector_sign_flip(embedding_2).T assert_array_almost_equal(embedding_1, embedding_2) def test_spectral_embedding_first_eigen_vector(): # Test that the first eigenvector of spectral_embedding # is constant and that the second is not (for a connected graph) random_state = np.random.RandomState(36) data = random_state.randn(10, 30) sims = rbf_kernel(data) n_components = 2 for seed in range(10): embedding = spectral_embedding( sims, norm_laplacian=False, n_components=n_components, drop_first=False, random_state=seed, ) assert np.std(embedding[:, 0]) == pytest.approx(0) assert np.std(embedding[:, 1]) > 1e-3 # TODO: Remove in 1.1 @pytest.mark.parametrize("affinity", ["precomputed", "precomputed_nearest_neighbors"]) def test_spectral_embedding_pairwise_deprecated(affinity): se = SpectralEmbedding(affinity=affinity) msg = r"Attribute `_pairwise` was deprecated in version 0\.24" with pytest.warns(FutureWarning, match=msg): se._pairwise
#!/usr/bin/env python3 """IP4 VRF Multi-instance Test Case HLD: **NOTES:** - higher number of pg-ip4 interfaces causes problems => only 15 pg-ip4 \ interfaces in 5 VRFs are tested - jumbo packets in configuration with 15 pg-ip4 interfaces leads to \ problems too **config 1** - add 15 pg-ip4 interfaces - configure 5 hosts per pg-ip4 interface - configure 4 VRFs - add 3 pg-ip4 interfaces per VRF **test 1** - send IP4 packets between all pg-ip4 interfaces in all VRF groups **verify 1** - check VRF data by parsing output of ip_fib_dump API command - all packets received correctly in case of pg-ip4 interfaces in the same VRF - no packet received in case of pg-ip4 interfaces not in VRF - no packet received in case of pg-ip4 interfaces in different VRFs **config 2** - reset 2 VRFs **test 2** - send IP4 packets between all pg-ip4 interfaces in all VRF groups **verify 2** - all packets received correctly in case of pg-ip4 interfaces in the same VRF - no packet received in case of pg-ip4 interfaces not in VRF - no packet received in case of pg-ip4 interfaces in different VRFs **config 3** - add 1 of reset VRFs and 1 new VRF **test 3** - send IP4 packets between all pg-ip4 interfaces in all VRF groups **verify 3** - check VRF data by parsing output of ip_fib_dump API command - all packets received correctly in case of pg-ip4 interfaces in the same VRF - no packet received in case of pg-ip4 interfaces not in VRF - no packet received in case of pg-ip4 interfaces in different VRFs **config 4** - reset all created VRFs **test 4** - send IP4 packets between all pg-ip4 interfaces in all VRF groups **verify 4** - check VRF data by parsing output of ip_fib_dump API command - all packets received correctly in case of pg-ip4 interfaces in the same VRF - no packet received in case of pg-ip4 interfaces not in VRF - no packet received in case of pg-ip4 interfaces in different VRFs """ import unittest import random import socket import scapy.compat from scapy.packet import Raw from scapy.layers.l2 import Ether, ARP from scapy.layers.inet import IP, UDP from framework import VppTestCase, VppTestRunner from util import ppp from vrf import VRFState def is_ipv4_misc(p): """ Is packet one of uninteresting IPv4 broadcasts? """ if p.haslayer(ARP): return True return False class TestIp4VrfMultiInst(VppTestCase): """ IP4 VRF Multi-instance Test Case """ @classmethod def setUpClass(cls): """ Perform standard class setup (defined by class method setUpClass in class VppTestCase) before running the test case, set test case related variables and configure VPP. """ super(TestIp4VrfMultiInst, cls).setUpClass() # Test variables cls.hosts_per_pg = 5 cls.nr_of_vrfs = 5 cls.pg_ifs_per_vrf = 3 try: # Create pg interfaces cls.create_pg_interfaces( range(cls.nr_of_vrfs * cls.pg_ifs_per_vrf)) # Packet flows mapping pg0 -> pg1, pg2 etc. cls.flows = dict() for i in range(len(cls.pg_interfaces)): multiplicand = i // cls.pg_ifs_per_vrf pg_list = [ cls.pg_interfaces[multiplicand * cls.pg_ifs_per_vrf + j] for j in range(cls.pg_ifs_per_vrf) if (multiplicand * cls.pg_ifs_per_vrf + j) != i] cls.flows[cls.pg_interfaces[i]] = pg_list # Packet sizes - jumbo packet (9018 bytes) skipped cls.pg_if_packet_sizes = [64, 512, 1518] # Set up all interfaces for pg_if in cls.pg_interfaces: pg_if.admin_up() pg_if.generate_remote_hosts(cls.hosts_per_pg) # Create list of VRFs cls.vrf_list = list() # Create list of reset VRFs cls.vrf_reset_list = list() # Create list of pg_interfaces in VRFs cls.pg_in_vrf = list() # Create list of pg_interfaces not in VRFs cls.pg_not_in_vrf = [pg_if for pg_if in cls.pg_interfaces] # Create mapping of pg_interfaces to VRF IDs cls.pg_if_by_vrf_id = dict() for i in range(cls.nr_of_vrfs): vrf_id = i + 1 pg_list = [ cls.pg_interfaces[i * cls.pg_ifs_per_vrf + j] for j in range(cls.pg_ifs_per_vrf)] cls.pg_if_by_vrf_id[vrf_id] = pg_list except Exception: super(TestIp4VrfMultiInst, cls).tearDownClass() raise @classmethod def tearDownClass(cls): super(TestIp4VrfMultiInst, cls).tearDownClass() def setUp(self): """ Clear trace and packet infos before running each test. """ super(TestIp4VrfMultiInst, self).setUp() self.reset_packet_infos() def tearDown(self): """ Show various debug prints after each test. """ super(TestIp4VrfMultiInst, self).tearDown() def show_commands_at_teardown(self): self.logger.info(self.vapi.ppcli("show ip fib")) self.logger.info(self.vapi.ppcli("show ip4 neighbors")) def create_vrf_and_assign_interfaces(self, count, start=1): """ Create required number of FIB tables / VRFs, put 3 pg-ip4 interfaces to every FIB table / VRF. :param int count: Number of FIB tables / VRFs to be created. :param int start: Starting number of the FIB table / VRF ID. \ (Default value = 1) """ for i in range(count): vrf_id = i + start pg_if = self.pg_if_by_vrf_id[vrf_id][0] dest_addr = pg_if.local_ip4n dest_addr_len = 24 self.vapi.ip_table_add_del(is_add=1, table={'table_id': vrf_id}) self.logger.info("IPv4 VRF ID %d created" % vrf_id) if vrf_id not in self.vrf_list: self.vrf_list.append(vrf_id) if vrf_id in self.vrf_reset_list: self.vrf_reset_list.remove(vrf_id) for j in range(self.pg_ifs_per_vrf): pg_if = self.pg_if_by_vrf_id[vrf_id][j] pg_if.set_table_ip4(vrf_id) self.logger.info("pg-interface %s added to IPv4 VRF ID %d" % (pg_if.name, vrf_id)) if pg_if not in self.pg_in_vrf: self.pg_in_vrf.append(pg_if) if pg_if in self.pg_not_in_vrf: self.pg_not_in_vrf.remove(pg_if) pg_if.config_ip4() pg_if.configure_ipv4_neighbors() self.logger.debug(self.vapi.ppcli("show ip fib")) self.logger.debug(self.vapi.ppcli("show ip4 neighbors")) def reset_vrf_and_remove_from_vrf_list(self, vrf_id): """ Reset required FIB table / VRF and remove it from VRF list. :param int vrf_id: The FIB table / VRF ID to be reset. """ self.vapi.ip_table_flush(table={'table_id': vrf_id}) if vrf_id in self.vrf_list: self.vrf_list.remove(vrf_id) if vrf_id not in self.vrf_reset_list: self.vrf_reset_list.append(vrf_id) for j in range(self.pg_ifs_per_vrf): pg_if = self.pg_if_by_vrf_id[vrf_id][j] pg_if.unconfig_ip4() if pg_if in self.pg_in_vrf: self.pg_in_vrf.remove(pg_if) if pg_if not in self.pg_not_in_vrf: self.pg_not_in_vrf.append(pg_if) self.logger.info("IPv4 VRF ID %d reset finished" % vrf_id) self.logger.debug(self.vapi.ppcli("show ip fib")) self.logger.debug(self.vapi.ppcli("show ip neighbors")) self.vapi.ip_table_add_del(is_add=0, table={'table_id': vrf_id}) def create_stream(self, src_if, packet_sizes): """ Create input packet stream for defined interface using hosts list. :param object src_if: Interface to create packet stream for. :param list packet_sizes: List of required packet sizes. :return: Stream of packets. """ pkts = [] src_hosts = src_if.remote_hosts for dst_if in self.flows[src_if]: for dst_host in dst_if.remote_hosts: src_host = random.choice(src_hosts) pkt_info = self.create_packet_info(src_if, dst_if) payload = self.info_to_payload(pkt_info) p = (Ether(dst=src_if.local_mac, src=src_host.mac) / IP(src=src_host.ip4, dst=dst_host.ip4) / UDP(sport=1234, dport=1234) / Raw(payload)) pkt_info.data = p.copy() size = random.choice(packet_sizes) self.extend_packet(p, size) pkts.append(p) self.logger.debug("Input stream created for port %s. Length: %u pkt(s)" % (src_if.name, len(pkts))) return pkts def create_stream_crosswise_vrf(self, src_if, vrf_id, packet_sizes): """ Create input packet stream for negative test for leaking across different VRFs for defined interface using hosts list. :param object src_if: Interface to create packet stream for. :param int vrf_id: The FIB table / VRF ID where src_if is assigned. :param list packet_sizes: List of required packet sizes. :return: Stream of packets. """ pkts = [] src_hosts = src_if.remote_hosts vrf_lst = list(self.vrf_list) vrf_lst.remove(vrf_id) for vrf in vrf_lst: for dst_if in self.pg_if_by_vrf_id[vrf]: for dst_host in dst_if.remote_hosts: src_host = random.choice(src_hosts) pkt_info = self.create_packet_info(src_if, dst_if) payload = self.info_to_payload(pkt_info) p = (Ether(dst=src_if.local_mac, src=src_host.mac) / IP(src=src_host.ip4, dst=dst_host.ip4) / UDP(sport=1234, dport=1234) / Raw(payload)) pkt_info.data = p.copy() size = random.choice(packet_sizes) self.extend_packet(p, size) pkts.append(p) self.logger.debug("Input stream created for port %s. Length: %u pkt(s)" % (src_if.name, len(pkts))) return pkts def verify_capture(self, pg_if, capture): """ Verify captured input packet stream for defined interface. :param object pg_if: Interface to verify captured packet stream for. :param list capture: Captured packet stream. """ last_info = dict() for i in self.pg_interfaces: last_info[i.sw_if_index] = None dst_sw_if_index = pg_if.sw_if_index for packet in capture: try: ip = packet[IP] udp = packet[UDP] payload_info = self.payload_to_info(packet[Raw]) packet_index = payload_info.index self.assertEqual(payload_info.dst, dst_sw_if_index) self.logger.debug("Got packet on port %s: src=%u (id=%u)" % (pg_if.name, payload_info.src, packet_index)) next_info = self.get_next_packet_info_for_interface2( payload_info.src, dst_sw_if_index, last_info[payload_info.src]) last_info[payload_info.src] = next_info self.assertIsNotNone(next_info) self.assertEqual(packet_index, next_info.index) saved_packet = next_info.data # Check standard fields self.assertEqual(ip.src, saved_packet[IP].src) self.assertEqual(ip.dst, saved_packet[IP].dst) self.assertEqual(udp.sport, saved_packet[UDP].sport) self.assertEqual(udp.dport, saved_packet[UDP].dport) except: self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise for i in self.pg_interfaces: remaining_packet = self.get_next_packet_info_for_interface2( i, dst_sw_if_index, last_info[i.sw_if_index]) self.assertIsNone( remaining_packet, "Port %u: Packet expected from source %u didn't arrive" % (dst_sw_if_index, i.sw_if_index)) def verify_vrf(self, vrf_id): """ Check if the FIB table / VRF ID is configured. :param int vrf_id: The FIB table / VRF ID to be verified. :return: 1 if the FIB table / VRF ID is configured, otherwise return 0. """ ip_fib_dump = self.vapi.ip_route_dump(vrf_id) vrf_exist = len(ip_fib_dump) vrf_count = 0 for ip_fib_details in ip_fib_dump: addr = ip_fib_details.route.prefix.network_address found = False for pg_if in self.pg_if_by_vrf_id[vrf_id]: if found: break for host in pg_if.remote_hosts: if str(addr) == host.ip4: vrf_count += 1 found = True break if not vrf_exist and vrf_count == 0: self.logger.info("IPv4 VRF ID %d is not configured" % vrf_id) return VRFState.not_configured elif vrf_exist and vrf_count == 0: self.logger.info("IPv4 VRF ID %d has been reset" % vrf_id) return VRFState.reset else: self.logger.info("IPv4 VRF ID %d is configured" % vrf_id) return VRFState.configured def run_verify_test(self): """ Create packet streams for all configured pg interfaces, send all \ prepared packet streams and verify that: - all packets received correctly on all pg-ip4 interfaces assigned to VRFs - no packet received on all pg-ip4 interfaces not assigned to VRFs :raise RuntimeError: If no packet captured on pg-ip4 interface assigned to VRF or if any packet is captured on pg-ip4 interface not assigned to VRF. """ # Test # Create incoming packet streams for packet-generator interfaces for pg_if in self.pg_interfaces: pkts = self.create_stream(pg_if, self.pg_if_packet_sizes) pg_if.add_stream(pkts) # Enable packet capture and start packet sending self.pg_enable_capture(self.pg_interfaces) self.pg_start() # Verify # Verify outgoing packet streams per packet-generator interface for pg_if in self.pg_interfaces: if pg_if in self.pg_in_vrf: capture = pg_if.get_capture(remark="interface is in VRF") self.verify_capture(pg_if, capture) elif pg_if in self.pg_not_in_vrf: pg_if.assert_nothing_captured(remark="interface is not in VRF", filter_out_fn=is_ipv4_misc) self.logger.debug("No capture for interface %s" % pg_if.name) else: raise Exception("Unknown interface: %s" % pg_if.name) def run_crosswise_vrf_test(self): """ Create packet streams for every pg-ip4 interface in VRF towards all pg-ip4 interfaces in other VRFs, send all prepared packet streams and \ verify that: - no packet received on all configured pg-ip4 interfaces :raise RuntimeError: If any packet is captured on any pg-ip4 interface. """ # Test # Create incoming packet streams for packet-generator interfaces for vrf_id in self.vrf_list: for pg_if in self.pg_if_by_vrf_id[vrf_id]: pkts = self.create_stream_crosswise_vrf( pg_if, vrf_id, self.pg_if_packet_sizes) pg_if.add_stream(pkts) # Enable packet capture and start packet sending self.pg_enable_capture(self.pg_interfaces) self.pg_start() # Verify # Verify outgoing packet streams per packet-generator interface for pg_if in self.pg_interfaces: pg_if.assert_nothing_captured(remark="interface is in other VRF", filter_out_fn=is_ipv4_misc) self.logger.debug("No capture for interface %s" % pg_if.name) def test_ip4_vrf_01(self): """ IP4 VRF Multi-instance test 1 - create 4 VRFs """ # Config 1 # Create 4 VRFs self.create_vrf_and_assign_interfaces(4) # Verify 1 for vrf_id in self.vrf_list: self.assert_equal(self.verify_vrf(vrf_id), VRFState.configured, VRFState) # Test 1 self.run_verify_test() self.run_crosswise_vrf_test() def test_ip4_vrf_02(self): """ IP4 VRF Multi-instance test 2 - reset 2 VRFs """ # Config 2 # Reset 2 VRFs self.reset_vrf_and_remove_from_vrf_list(1) self.reset_vrf_and_remove_from_vrf_list(2) # Verify 2 for vrf_id in self.vrf_reset_list: self.assert_equal(self.verify_vrf(vrf_id), VRFState.reset, VRFState) for vrf_id in self.vrf_list: self.assert_equal(self.verify_vrf(vrf_id), VRFState.configured, VRFState) # Test 2 self.run_verify_test() self.run_crosswise_vrf_test() def test_ip4_vrf_03(self): """ IP4 VRF Multi-instance 3 - add 2 VRFs """ # Config 3 # Add 1 of reset VRFs and 1 new VRF self.create_vrf_and_assign_interfaces(1) self.create_vrf_and_assign_interfaces(1, start=5) # Verify 3 for vrf_id in self.vrf_reset_list: self.assert_equal(self.verify_vrf(vrf_id), VRFState.reset, VRFState) for vrf_id in self.vrf_list: self.assert_equal(self.verify_vrf(vrf_id), VRFState.configured, VRFState) # Test 3 self.run_verify_test() self.run_crosswise_vrf_test() def test_ip4_vrf_04(self): """ IP4 VRF Multi-instance test 4 - reset 4 VRFs """ # Config 4 # Reset all VRFs (i.e. no VRF except VRF=0 configured) for i in range(len(self.vrf_list)): self.reset_vrf_and_remove_from_vrf_list(self.vrf_list[0]) # Verify 4 for vrf_id in self.vrf_reset_list: self.assert_equal(self.verify_vrf(vrf_id), VRFState.reset, VRFState) vrf_list_length = len(self.vrf_list) self.assertEqual( vrf_list_length, 0, "List of configured VRFs is not empty: %s != 0" % vrf_list_length) # Test 4 self.run_verify_test() self.run_crosswise_vrf_test() if __name__ == '__main__': unittest.main(testRunner=VppTestRunner)
import collections import itertools import datetime import isodate from rdflib.compat import Mapping, MutableMapping from rdflib.namespace import NamespaceManager from rdflib import Variable, BNode, Graph, ConjunctiveGraph, URIRef, Literal from rdflib.term import Node from rdflib.plugins.sparql.parserutils import CompValue import rdflib.plugins.sparql class SPARQLError(Exception): def __init__(self, msg=None): Exception.__init__(self, msg) class NotBoundError(SPARQLError): def __init__(self, msg=None): SPARQLError.__init__(self, msg) class AlreadyBound(SPARQLError): """Raised when trying to bind a variable that is already bound!""" def __init__(self): SPARQLError.__init__(self) class SPARQLTypeError(SPARQLError): def __init__(self, msg): SPARQLError.__init__(self, msg) class Bindings(MutableMapping): """ A single level of a stack of variable-value bindings. Each dict keeps a reference to the dict below it, any failed lookup is propegated back In python 3.3 this could be a collections.ChainMap """ def __init__(self, outer=None, d=[]): self._d = dict(d) self.outer = outer def __getitem__(self, key): if key in self._d: return self._d[key] if not self.outer: raise KeyError() return self.outer[key] def __contains__(self, key): try: self[key] return True except KeyError: return False def __setitem__(self, key, value): self._d[key] = value def __delitem__(self, key): raise Exception("DelItem is not implemented!") def __len__(self) -> int: i = 0 d = self while d is not None: i += len(d._d) d = d.outer return i # type: ignore[unreachable] def __iter__(self): d = self while d is not None: yield from d._d d = d.outer def __str__(self): return "Bindings({" + ", ".join((k, self[k]) for k in self) + "})" def __repr__(self): return str(self) class FrozenDict(Mapping): """ An immutable hashable dict Taken from http://stackoverflow.com/a/2704866/81121 """ def __init__(self, *args, **kwargs): self._d = dict(*args, **kwargs) self._hash = None def __iter__(self): return iter(self._d) def __len__(self): return len(self._d) def __getitem__(self, key): return self._d[key] def __hash__(self): # It would have been simpler and maybe more obvious to # use hash(tuple(sorted(self._d.items()))) from this discussion # so far, but this solution is O(n). I don't know what kind of # n we are going to run into, but sometimes it's hard to resist the # urge to optimize when it will gain improved algorithmic performance. if self._hash is None: self._hash = 0 for key, value in self.items(): self._hash ^= hash(key) self._hash ^= hash(value) return self._hash def project(self, vars): return FrozenDict((x for x in self.items() if x[0] in vars)) def disjointDomain(self, other): return not bool(set(self).intersection(other)) def compatible(self, other): for k in self: try: if self[k] != other[k]: return False except KeyError: pass return True def merge(self, other): res = FrozenDict(itertools.chain(self.items(), other.items())) return res def __str__(self): return str(self._d) def __repr__(self): return repr(self._d) class FrozenBindings(FrozenDict): def __init__(self, ctx, *args, **kwargs): FrozenDict.__init__(self, *args, **kwargs) self.ctx = ctx def __getitem__(self, key): if not isinstance(key, Node): key = Variable(key) if not isinstance(key, (BNode, Variable)): return key if key not in self._d: return self.ctx.initBindings[key] else: return self._d[key] def project(self, vars): return FrozenBindings(self.ctx, (x for x in self.items() if x[0] in vars)) def merge(self, other): res = FrozenBindings(self.ctx, itertools.chain(self.items(), other.items())) return res @property def now(self): return self.ctx.now @property def bnodes(self): return self.ctx.bnodes @property def prologue(self): return self.ctx.prologue def forget(self, before, _except=None): """ return a frozen dict only of bindings made in self since before """ if not _except: _except = [] # bindings from initBindings are newer forgotten return FrozenBindings( self.ctx, ( x for x in self.items() if ( x[0] in _except or x[0] in self.ctx.initBindings or before[x[0]] is None ) ), ) def remember(self, these): """ return a frozen dict only of bindings in these """ return FrozenBindings(self.ctx, (x for x in self.items() if x[0] in these)) class QueryContext(object): """ Query context - passed along when evaluating the query """ def __init__(self, graph=None, bindings=None, initBindings=None): self.initBindings = initBindings self.bindings = Bindings(d=bindings or []) if initBindings: self.bindings.update(initBindings) if isinstance(graph, ConjunctiveGraph): self._dataset = graph if rdflib.plugins.sparql.SPARQL_DEFAULT_GRAPH_UNION: self.graph = self.dataset else: self.graph = self.dataset.default_context else: self._dataset = None self.graph = graph self.prologue = None self._now = None self.bnodes = collections.defaultdict(BNode) @property def now(self) -> datetime.datetime: if self._now is None: self._now = datetime.datetime.now(isodate.tzinfo.UTC) return self._now def clone(self, bindings=None): r = QueryContext( self._dataset if self._dataset is not None else self.graph, bindings or self.bindings, initBindings=self.initBindings, ) r.prologue = self.prologue r.graph = self.graph r.bnodes = self.bnodes return r @property def dataset(self): """ "current dataset""" if self._dataset is None: raise Exception( "You performed a query operation requiring " + "a dataset (i.e. ConjunctiveGraph), but " + "operating currently on a single graph." ) return self._dataset def load(self, source, default=False, **kwargs): def _load(graph, source): try: return graph.parse(source, format="turtle", **kwargs) except Exception: pass try: return graph.parse(source, format="xml", **kwargs) except Exception: pass try: return graph.parse(source, format="n3", **kwargs) except Exception: pass try: return graph.parse(source, format="nt", **kwargs) except Exception: raise Exception( "Could not load %s as either RDF/XML, N3 or NTriples" % source ) if not rdflib.plugins.sparql.SPARQL_LOAD_GRAPHS: # we are not loading - if we already know the graph # being "loaded", just add it to the default-graph if default: self.graph += self.dataset.get_context(source) else: if default: _load(self.graph, source) else: _load(self.dataset, source) def __getitem__(self, key): # in SPARQL BNodes are just labels if not isinstance(key, (BNode, Variable)): return key try: return self.bindings[key] except KeyError: return None def get(self, key, default=None): try: return self[key] except KeyError: return default def solution(self, vars=None): """ Return a static copy of the current variable bindings as dict """ if vars: return FrozenBindings( self, ((k, v) for k, v in self.bindings.items() if k in vars) ) else: return FrozenBindings(self, self.bindings.items()) def __setitem__(self, key, value): if key in self.bindings and self.bindings[key] != value: raise AlreadyBound() self.bindings[key] = value def pushGraph(self, graph): r = self.clone() r.graph = graph return r def push(self): r = self.clone(Bindings(self.bindings)) return r def clean(self): return self.clone([]) def thaw(self, frozenbindings): """ Create a new read/write query context from the given solution """ c = self.clone(frozenbindings) return c class Prologue: """ A class for holding prefixing bindings and base URI information """ def __init__(self): self.base = None self.namespace_manager = NamespaceManager(Graph()) # ns man needs a store def resolvePName(self, prefix, localname): ns = self.namespace_manager.store.namespace(prefix or "") if ns is None: raise Exception("Unknown namespace prefix : %s" % prefix) return URIRef(ns + (localname or "")) def bind(self, prefix, uri): self.namespace_manager.bind(prefix, uri, replace=True) def absolutize(self, iri): """ Apply BASE / PREFIXes to URIs (and to datatypes in Literals) TODO: Move resolving URIs to pre-processing """ if isinstance(iri, CompValue): if iri.name == "pname": return self.resolvePName(iri.prefix, iri.localname) if iri.name == "literal": return Literal( iri.string, lang=iri.lang, datatype=self.absolutize(iri.datatype) ) elif isinstance(iri, URIRef) and not ":" in iri: return URIRef(iri, base=self.base) return iri class Query: """ A parsed and translated query """ def __init__(self, prologue, algebra): self.prologue = prologue self.algebra = algebra class Update: """ A parsed and translated update """ def __init__(self, prologue, algebra): self.prologue = prologue self.algebra = algebra
"""Test the condition helper.""" from logging import WARNING from unittest.mock import patch import pytest from homeassistant.exceptions import ConditionError, HomeAssistantError from homeassistant.helpers import condition from homeassistant.helpers.template import Template from homeassistant.setup import async_setup_component from homeassistant.util import dt async def test_invalid_condition(hass): """Test if invalid condition raises.""" with pytest.raises(HomeAssistantError): await condition.async_from_config( hass, { "condition": "invalid", "conditions": [ { "condition": "state", "entity_id": "sensor.temperature", "state": "100", }, ], }, ) async def test_and_condition(hass): """Test the 'and' condition.""" test = await condition.async_from_config( hass, { "condition": "and", "conditions": [ { "condition": "state", "entity_id": "sensor.temperature", "state": "100", }, { "condition": "numeric_state", "entity_id": "sensor.temperature", "below": 110, }, ], }, ) hass.states.async_set("sensor.temperature", 120) assert not test(hass) hass.states.async_set("sensor.temperature", 105) assert not test(hass) hass.states.async_set("sensor.temperature", 100) assert test(hass) async def test_and_condition_with_template(hass): """Test the 'and' condition.""" test = await condition.async_from_config( hass, { "condition": "and", "conditions": [ { "condition": "template", "value_template": '{{ states.sensor.temperature.state == "100" }}', }, { "condition": "numeric_state", "entity_id": "sensor.temperature", "below": 110, }, ], }, ) hass.states.async_set("sensor.temperature", 120) assert not test(hass) hass.states.async_set("sensor.temperature", 105) assert not test(hass) hass.states.async_set("sensor.temperature", 100) assert test(hass) async def test_or_condition(hass): """Test the 'or' condition.""" test = await condition.async_from_config( hass, { "condition": "or", "conditions": [ { "condition": "state", "entity_id": "sensor.temperature", "state": "100", }, { "condition": "numeric_state", "entity_id": "sensor.temperature", "below": 110, }, ], }, ) hass.states.async_set("sensor.temperature", 120) assert not test(hass) hass.states.async_set("sensor.temperature", 105) assert test(hass) hass.states.async_set("sensor.temperature", 100) assert test(hass) async def test_or_condition_with_template(hass): """Test the 'or' condition.""" test = await condition.async_from_config( hass, { "condition": "or", "conditions": [ {'{{ states.sensor.temperature.state == "100" }}'}, { "condition": "numeric_state", "entity_id": "sensor.temperature", "below": 110, }, ], }, ) hass.states.async_set("sensor.temperature", 120) assert not test(hass) hass.states.async_set("sensor.temperature", 105) assert test(hass) hass.states.async_set("sensor.temperature", 100) assert test(hass) async def test_not_condition(hass): """Test the 'not' condition.""" test = await condition.async_from_config( hass, { "condition": "not", "conditions": [ { "condition": "state", "entity_id": "sensor.temperature", "state": "100", }, { "condition": "numeric_state", "entity_id": "sensor.temperature", "below": 50, }, ], }, ) hass.states.async_set("sensor.temperature", 101) assert test(hass) hass.states.async_set("sensor.temperature", 50) assert test(hass) hass.states.async_set("sensor.temperature", 49) assert not test(hass) hass.states.async_set("sensor.temperature", 100) assert not test(hass) async def test_not_condition_with_template(hass): """Test the 'or' condition.""" test = await condition.async_from_config( hass, { "condition": "not", "conditions": [ { "condition": "template", "value_template": '{{ states.sensor.temperature.state == "100" }}', }, { "condition": "numeric_state", "entity_id": "sensor.temperature", "below": 50, }, ], }, ) hass.states.async_set("sensor.temperature", 101) assert test(hass) hass.states.async_set("sensor.temperature", 50) assert test(hass) hass.states.async_set("sensor.temperature", 49) assert not test(hass) hass.states.async_set("sensor.temperature", 100) assert not test(hass) async def test_time_window(hass): """Test time condition windows.""" sixam = dt.parse_time("06:00:00") sixpm = dt.parse_time("18:00:00") with patch( "homeassistant.helpers.condition.dt_util.now", return_value=dt.now().replace(hour=3), ): assert not condition.time(hass, after=sixam, before=sixpm) assert condition.time(hass, after=sixpm, before=sixam) with patch( "homeassistant.helpers.condition.dt_util.now", return_value=dt.now().replace(hour=9), ): assert condition.time(hass, after=sixam, before=sixpm) assert not condition.time(hass, after=sixpm, before=sixam) with patch( "homeassistant.helpers.condition.dt_util.now", return_value=dt.now().replace(hour=15), ): assert condition.time(hass, after=sixam, before=sixpm) assert not condition.time(hass, after=sixpm, before=sixam) with patch( "homeassistant.helpers.condition.dt_util.now", return_value=dt.now().replace(hour=21), ): assert not condition.time(hass, after=sixam, before=sixpm) assert condition.time(hass, after=sixpm, before=sixam) async def test_time_using_input_datetime(hass): """Test time conditions using input_datetime entities.""" await async_setup_component( hass, "input_datetime", { "input_datetime": { "am": {"has_date": True, "has_time": True}, "pm": {"has_date": True, "has_time": True}, } }, ) await hass.services.async_call( "input_datetime", "set_datetime", { "entity_id": "input_datetime.am", "datetime": str( dt.now() .replace(hour=6, minute=0, second=0, microsecond=0) .replace(tzinfo=None) ), }, blocking=True, ) await hass.services.async_call( "input_datetime", "set_datetime", { "entity_id": "input_datetime.pm", "datetime": str( dt.now() .replace(hour=18, minute=0, second=0, microsecond=0) .replace(tzinfo=None) ), }, blocking=True, ) with patch( "homeassistant.helpers.condition.dt_util.now", return_value=dt.now().replace(hour=3), ): assert not condition.time( hass, after="input_datetime.am", before="input_datetime.pm" ) assert condition.time( hass, after="input_datetime.pm", before="input_datetime.am" ) with patch( "homeassistant.helpers.condition.dt_util.now", return_value=dt.now().replace(hour=9), ): assert condition.time( hass, after="input_datetime.am", before="input_datetime.pm" ) assert not condition.time( hass, after="input_datetime.pm", before="input_datetime.am" ) with patch( "homeassistant.helpers.condition.dt_util.now", return_value=dt.now().replace(hour=15), ): assert condition.time( hass, after="input_datetime.am", before="input_datetime.pm" ) assert not condition.time( hass, after="input_datetime.pm", before="input_datetime.am" ) with patch( "homeassistant.helpers.condition.dt_util.now", return_value=dt.now().replace(hour=21), ): assert not condition.time( hass, after="input_datetime.am", before="input_datetime.pm" ) assert condition.time( hass, after="input_datetime.pm", before="input_datetime.am" ) with pytest.raises(ConditionError): condition.time(hass, after="input_datetime.not_existing") with pytest.raises(ConditionError): condition.time(hass, before="input_datetime.not_existing") async def test_if_numeric_state_raises_on_unavailable(hass, caplog): """Test numeric_state raises on unavailable/unknown state.""" test = await condition.async_from_config( hass, {"condition": "numeric_state", "entity_id": "sensor.temperature", "below": 42}, ) caplog.clear() caplog.set_level(WARNING) hass.states.async_set("sensor.temperature", "unavailable") with pytest.raises(ConditionError): test(hass) assert len(caplog.record_tuples) == 0 hass.states.async_set("sensor.temperature", "unknown") with pytest.raises(ConditionError): test(hass) assert len(caplog.record_tuples) == 0 async def test_state_raises(hass): """Test that state raises ConditionError on errors.""" # Unknown entity_id with pytest.raises(ConditionError, match="Unknown entity"): test = await condition.async_from_config( hass, { "condition": "state", "entity_id": "sensor.door_unknown", "state": "open", }, ) test(hass) # Unknown attribute with pytest.raises(ConditionError, match=r"Attribute .* does not exist"): test = await condition.async_from_config( hass, { "condition": "state", "entity_id": "sensor.door", "attribute": "model", "state": "acme", }, ) hass.states.async_set("sensor.door", "open") test(hass) async def test_state_multiple_entities(hass): """Test with multiple entities in condition.""" test = await condition.async_from_config( hass, { "condition": "and", "conditions": [ { "condition": "state", "entity_id": ["sensor.temperature_1", "sensor.temperature_2"], "state": "100", }, ], }, ) hass.states.async_set("sensor.temperature_1", 100) hass.states.async_set("sensor.temperature_2", 100) assert test(hass) hass.states.async_set("sensor.temperature_1", 101) hass.states.async_set("sensor.temperature_2", 100) assert not test(hass) hass.states.async_set("sensor.temperature_1", 100) hass.states.async_set("sensor.temperature_2", 101) assert not test(hass) async def test_multiple_states(hass): """Test with multiple states in condition.""" test = await condition.async_from_config( hass, { "condition": "and", "conditions": [ { "condition": "state", "entity_id": "sensor.temperature", "state": ["100", "200"], }, ], }, ) hass.states.async_set("sensor.temperature", 100) assert test(hass) hass.states.async_set("sensor.temperature", 200) assert test(hass) hass.states.async_set("sensor.temperature", 42) assert not test(hass) async def test_state_attribute(hass): """Test with state attribute in condition.""" test = await condition.async_from_config( hass, { "condition": "and", "conditions": [ { "condition": "state", "entity_id": "sensor.temperature", "attribute": "attribute1", "state": 200, }, ], }, ) hass.states.async_set("sensor.temperature", 100, {"unkown_attr": 200}) assert not test(hass) hass.states.async_set("sensor.temperature", 100, {"attribute1": 200}) assert test(hass) hass.states.async_set("sensor.temperature", 100, {"attribute1": "200"}) assert not test(hass) hass.states.async_set("sensor.temperature", 100, {"attribute1": 201}) assert not test(hass) hass.states.async_set("sensor.temperature", 100, {"attribute1": None}) assert not test(hass) async def test_state_attribute_boolean(hass): """Test with boolean state attribute in condition.""" test = await condition.async_from_config( hass, { "condition": "state", "entity_id": "sensor.temperature", "attribute": "happening", "state": False, }, ) hass.states.async_set("sensor.temperature", 100, {"happening": 200}) assert not test(hass) hass.states.async_set("sensor.temperature", 100, {"happening": True}) assert not test(hass) hass.states.async_set("sensor.temperature", 100, {"no_happening": 201}) with pytest.raises(ConditionError): test(hass) hass.states.async_set("sensor.temperature", 100, {"happening": False}) assert test(hass) async def test_state_using_input_entities(hass): """Test state conditions using input_* entities.""" await async_setup_component( hass, "input_text", { "input_text": { "hello": {"initial": "goodbye"}, } }, ) await async_setup_component( hass, "input_select", { "input_select": { "hello": {"options": ["cya", "goodbye", "welcome"], "initial": "cya"}, } }, ) test = await condition.async_from_config( hass, { "condition": "and", "conditions": [ { "condition": "state", "entity_id": "sensor.salut", "state": [ "input_text.hello", "input_select.hello", "input_number.not_exist", "salut", ], }, ], }, ) hass.states.async_set("sensor.salut", "goodbye") assert test(hass) hass.states.async_set("sensor.salut", "salut") assert test(hass) hass.states.async_set("sensor.salut", "hello") assert not test(hass) await hass.services.async_call( "input_text", "set_value", { "entity_id": "input_text.hello", "value": "hi", }, blocking=True, ) assert not test(hass) hass.states.async_set("sensor.salut", "hi") assert test(hass) hass.states.async_set("sensor.salut", "cya") assert test(hass) await hass.services.async_call( "input_select", "select_option", { "entity_id": "input_select.hello", "option": "welcome", }, blocking=True, ) assert not test(hass) hass.states.async_set("sensor.salut", "welcome") assert test(hass) async def test_numeric_state_raises(hass): """Test that numeric_state raises ConditionError on errors.""" # Unknown entity_id with pytest.raises(ConditionError, match="Unknown entity"): test = await condition.async_from_config( hass, { "condition": "numeric_state", "entity_id": "sensor.temperature_unknown", "above": 0, }, ) test(hass) # Unknown attribute with pytest.raises(ConditionError, match=r"Attribute .* does not exist"): test = await condition.async_from_config( hass, { "condition": "numeric_state", "entity_id": "sensor.temperature", "attribute": "temperature", "above": 0, }, ) hass.states.async_set("sensor.temperature", 50) test(hass) # Template error with pytest.raises(ConditionError, match="ZeroDivisionError"): test = await condition.async_from_config( hass, { "condition": "numeric_state", "entity_id": "sensor.temperature", "value_template": "{{ 1 / 0 }}", "above": 0, }, ) hass.states.async_set("sensor.temperature", 50) test(hass) # Unavailable state with pytest.raises(ConditionError, match="State is not available"): test = await condition.async_from_config( hass, { "condition": "numeric_state", "entity_id": "sensor.temperature", "above": 0, }, ) hass.states.async_set("sensor.temperature", "unavailable") test(hass) # Bad number with pytest.raises(ConditionError, match="cannot be processed as a number"): test = await condition.async_from_config( hass, { "condition": "numeric_state", "entity_id": "sensor.temperature", "above": 0, }, ) hass.states.async_set("sensor.temperature", "fifty") test(hass) # Below entity missing with pytest.raises(ConditionError, match="below entity"): test = await condition.async_from_config( hass, { "condition": "numeric_state", "entity_id": "sensor.temperature", "below": "input_number.missing", }, ) hass.states.async_set("sensor.temperature", 50) test(hass) # Above entity missing with pytest.raises(ConditionError, match="above entity"): test = await condition.async_from_config( hass, { "condition": "numeric_state", "entity_id": "sensor.temperature", "above": "input_number.missing", }, ) hass.states.async_set("sensor.temperature", 50) test(hass) async def test_numeric_state_multiple_entities(hass): """Test with multiple entities in condition.""" test = await condition.async_from_config( hass, { "condition": "and", "conditions": [ { "condition": "numeric_state", "entity_id": ["sensor.temperature_1", "sensor.temperature_2"], "below": 50, }, ], }, ) hass.states.async_set("sensor.temperature_1", 49) hass.states.async_set("sensor.temperature_2", 49) assert test(hass) hass.states.async_set("sensor.temperature_1", 50) hass.states.async_set("sensor.temperature_2", 49) assert not test(hass) hass.states.async_set("sensor.temperature_1", 49) hass.states.async_set("sensor.temperature_2", 50) assert not test(hass) async def test_numberic_state_attribute(hass): """Test with numeric state attribute in condition.""" test = await condition.async_from_config( hass, { "condition": "and", "conditions": [ { "condition": "numeric_state", "entity_id": "sensor.temperature", "attribute": "attribute1", "below": 50, }, ], }, ) hass.states.async_set("sensor.temperature", 100, {"unkown_attr": 10}) assert not test(hass) hass.states.async_set("sensor.temperature", 100, {"attribute1": 49}) assert test(hass) hass.states.async_set("sensor.temperature", 100, {"attribute1": "49"}) assert test(hass) hass.states.async_set("sensor.temperature", 100, {"attribute1": 51}) assert not test(hass) hass.states.async_set("sensor.temperature", 100, {"attribute1": None}) assert not test(hass) async def test_numeric_state_using_input_number(hass): """Test numeric_state conditions using input_number entities.""" await async_setup_component( hass, "input_number", { "input_number": { "low": {"min": 0, "max": 255, "initial": 10}, "high": {"min": 0, "max": 255, "initial": 100}, } }, ) test = await condition.async_from_config( hass, { "condition": "and", "conditions": [ { "condition": "numeric_state", "entity_id": "sensor.temperature", "below": "input_number.high", "above": "input_number.low", }, ], }, ) hass.states.async_set("sensor.temperature", 42) assert test(hass) hass.states.async_set("sensor.temperature", 10) assert not test(hass) hass.states.async_set("sensor.temperature", 100) assert not test(hass) await hass.services.async_call( "input_number", "set_value", { "entity_id": "input_number.high", "value": 101, }, blocking=True, ) assert test(hass) with pytest.raises(ConditionError): condition.async_numeric_state( hass, entity="sensor.temperature", below="input_number.not_exist" ) with pytest.raises(ConditionError): condition.async_numeric_state( hass, entity="sensor.temperature", above="input_number.not_exist" ) async def test_zone_multiple_entities(hass): """Test with multiple entities in condition.""" test = await condition.async_from_config( hass, { "condition": "and", "conditions": [ { "condition": "zone", "entity_id": ["device_tracker.person_1", "device_tracker.person_2"], "zone": "zone.home", }, ], }, ) hass.states.async_set( "zone.home", "zoning", {"name": "home", "latitude": 2.1, "longitude": 1.1, "radius": 10}, ) hass.states.async_set( "device_tracker.person_1", "home", {"friendly_name": "person_1", "latitude": 2.1, "longitude": 1.1}, ) hass.states.async_set( "device_tracker.person_2", "home", {"friendly_name": "person_2", "latitude": 2.1, "longitude": 1.1}, ) assert test(hass) hass.states.async_set( "device_tracker.person_1", "home", {"friendly_name": "person_1", "latitude": 20.1, "longitude": 10.1}, ) hass.states.async_set( "device_tracker.person_2", "home", {"friendly_name": "person_2", "latitude": 2.1, "longitude": 1.1}, ) assert not test(hass) hass.states.async_set( "device_tracker.person_1", "home", {"friendly_name": "person_1", "latitude": 2.1, "longitude": 1.1}, ) hass.states.async_set( "device_tracker.person_2", "home", {"friendly_name": "person_2", "latitude": 20.1, "longitude": 10.1}, ) assert not test(hass) async def test_multiple_zones(hass): """Test with multiple entities in condition.""" test = await condition.async_from_config( hass, { "condition": "and", "conditions": [ { "condition": "zone", "entity_id": "device_tracker.person", "zone": ["zone.home", "zone.work"], }, ], }, ) hass.states.async_set( "zone.home", "zoning", {"name": "home", "latitude": 2.1, "longitude": 1.1, "radius": 10}, ) hass.states.async_set( "zone.work", "zoning", {"name": "work", "latitude": 20.1, "longitude": 10.1, "radius": 10}, ) hass.states.async_set( "device_tracker.person", "home", {"friendly_name": "person", "latitude": 2.1, "longitude": 1.1}, ) assert test(hass) hass.states.async_set( "device_tracker.person", "home", {"friendly_name": "person", "latitude": 20.1, "longitude": 10.1}, ) assert test(hass) hass.states.async_set( "device_tracker.person", "home", {"friendly_name": "person", "latitude": 50.1, "longitude": 20.1}, ) assert not test(hass) async def test_extract_entities(): """Test extracting entities.""" assert condition.async_extract_entities( { "condition": "and", "conditions": [ { "condition": "state", "entity_id": "sensor.temperature", "state": "100", }, { "condition": "numeric_state", "entity_id": "sensor.temperature_2", "below": 110, }, { "condition": "not", "conditions": [ { "condition": "state", "entity_id": "sensor.temperature_3", "state": "100", }, { "condition": "numeric_state", "entity_id": "sensor.temperature_4", "below": 110, }, ], }, { "condition": "or", "conditions": [ { "condition": "state", "entity_id": "sensor.temperature_5", "state": "100", }, { "condition": "numeric_state", "entity_id": "sensor.temperature_6", "below": 110, }, ], }, { "condition": "state", "entity_id": ["sensor.temperature_7", "sensor.temperature_8"], "state": "100", }, { "condition": "numeric_state", "entity_id": ["sensor.temperature_9", "sensor.temperature_10"], "below": 110, }, Template("{{ is_state('light.example', 'on') }}"), ], } ) == { "sensor.temperature", "sensor.temperature_2", "sensor.temperature_3", "sensor.temperature_4", "sensor.temperature_5", "sensor.temperature_6", "sensor.temperature_7", "sensor.temperature_8", "sensor.temperature_9", "sensor.temperature_10", } async def test_extract_devices(): """Test extracting devices.""" assert ( condition.async_extract_devices( { "condition": "and", "conditions": [ {"condition": "device", "device_id": "abcd", "domain": "light"}, {"condition": "device", "device_id": "qwer", "domain": "switch"}, { "condition": "state", "entity_id": "sensor.not_a_device", "state": "100", }, { "condition": "not", "conditions": [ { "condition": "device", "device_id": "abcd_not", "domain": "light", }, { "condition": "device", "device_id": "qwer_not", "domain": "switch", }, ], }, { "condition": "or", "conditions": [ { "condition": "device", "device_id": "abcd_or", "domain": "light", }, { "condition": "device", "device_id": "qwer_or", "domain": "switch", }, ], }, Template("{{ is_state('light.example', 'on') }}"), ], } ) == {"abcd", "qwer", "abcd_not", "qwer_not", "abcd_or", "qwer_or"} ) async def test_condition_template_error(hass): """Test invalid template.""" test = await condition.async_from_config( hass, {"condition": "template", "value_template": "{{ undefined.state }}"} ) with pytest.raises(ConditionError, match="template"): test(hass) async def test_condition_template_invalid_results(hass): """Test template condition render false with invalid results.""" test = await condition.async_from_config( hass, {"condition": "template", "value_template": "{{ 'string' }}"} ) assert not test(hass) test = await condition.async_from_config( hass, {"condition": "template", "value_template": "{{ 10.1 }}"} ) assert not test(hass) test = await condition.async_from_config( hass, {"condition": "template", "value_template": "{{ 42 }}"} ) assert not test(hass) test = await condition.async_from_config( hass, {"condition": "template", "value_template": "{{ [1, 2, 3] }}"} ) assert not test(hass)
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 logging import sys # Using `from elasticsearch import *` would break elasticsearch mocking used in unit test. import elasticsearch import pendulum from elasticsearch_dsl import Search from airflow.configuration import conf from airflow.utils import timezone from airflow.utils.helpers import parse_template_string from airflow.utils.log.file_task_handler import FileTaskHandler from airflow.utils.log.json_formatter import JSONFormatter from airflow.utils.log.logging_mixin import LoggingMixin class ElasticsearchTaskHandler(FileTaskHandler, LoggingMixin): """ ElasticsearchTaskHandler is a python log handler that reads logs from Elasticsearch. Note logs are not directly indexed into Elasticsearch. Instead, it flushes logs into local files. Additional software setup is required to index the log into Elasticsearch, such as using Filebeat and Logstash. To efficiently query and sort Elasticsearch results, we assume each log message has a field `log_id` consists of ti primary keys: `log_id = {dag_id}-{task_id}-{execution_date}-{try_number}` Log messages with specific log_id are sorted based on `offset`, which is a unique integer indicates log message's order. Timestamp here are unreliable because multiple log messages might have the same timestamp. """ PAGE = 0 MAX_LINE_PER_PAGE = 1000 def __init__(self, base_log_folder, filename_template, log_id_template, end_of_log_mark, write_stdout, json_format, json_fields, host='localhost:9200', es_kwargs=conf.getsection("elasticsearch_configs")): """ :param base_log_folder: base folder to store logs locally :param log_id_template: log id template :param host: Elasticsearch host name """ es_kwargs = es_kwargs or {} super().__init__( base_log_folder, filename_template) self.closed = False self.log_id_template, self.log_id_jinja_template = \ parse_template_string(log_id_template) self.client = elasticsearch.Elasticsearch([host], **es_kwargs) self.mark_end_on_close = True self.end_of_log_mark = end_of_log_mark self.write_stdout = write_stdout self.json_format = json_format self.json_fields = [label.strip() for label in json_fields.split(",")] self.handler = None self.context_set = False def _render_log_id(self, ti, try_number): if self.log_id_jinja_template: jinja_context = ti.get_template_context() jinja_context['try_number'] = try_number return self.log_id_jinja_template.render(**jinja_context) if self.json_format: execution_date = self._clean_execution_date(ti.execution_date) else: execution_date = ti.execution_date.isoformat() return self.log_id_template.format(dag_id=ti.dag_id, task_id=ti.task_id, execution_date=execution_date, try_number=try_number) @staticmethod def _clean_execution_date(execution_date): """ Clean up an execution date so that it is safe to query in elasticsearch by removing reserved characters. # https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#_reserved_characters :param execution_date: execution date of the dag run. """ return execution_date.strftime("%Y_%m_%dT%H_%M_%S_%f") def _read(self, ti, try_number, metadata=None): """ Endpoint for streaming log. :param ti: task instance object :param try_number: try_number of the task instance :param metadata: log metadata, can be used for steaming log reading and auto-tailing. :return: a list of log documents and metadata. """ if not metadata: metadata = {'offset': 0} if 'offset' not in metadata: metadata['offset'] = 0 offset = metadata['offset'] log_id = self._render_log_id(ti, try_number) logs = self.es_read(log_id, offset, metadata) next_offset = offset if not logs else logs[-1].offset # Ensure a string here. Large offset numbers will get JSON.parsed incorrectly # on the client. Sending as a string prevents this issue. # https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER metadata['offset'] = str(next_offset) # end_of_log_mark may contain characters like '\n' which is needed to # have the log uploaded but will not be stored in elasticsearch. metadata['end_of_log'] = False if not logs \ else logs[-1].message == self.end_of_log_mark.strip() cur_ts = pendulum.now() # Assume end of log after not receiving new log for 5 min, # as executor heartbeat is 1 min and there might be some # delay before Elasticsearch makes the log available. if 'last_log_timestamp' in metadata: last_log_ts = timezone.parse(metadata['last_log_timestamp']) if cur_ts.diff(last_log_ts).in_minutes() >= 5 or 'max_offset' in metadata \ and offset >= metadata['max_offset']: metadata['end_of_log'] = True if offset != next_offset or 'last_log_timestamp' not in metadata: metadata['last_log_timestamp'] = str(cur_ts) # If we hit the end of the log, remove the actual end_of_log message # to prevent it from showing in the UI. i = len(logs) if not metadata['end_of_log'] else len(logs) - 1 message = '\n'.join([log.message for log in logs[0:i]]) return message, metadata def es_read(self, log_id, offset, metadata): """ Returns the logs matching log_id in Elasticsearch and next offset. Returns '' if no log is found or there was an error. :param log_id: the log_id of the log to read. :type log_id: str :param offset: the offset start to read log from. :type offset: str :param metadata: log metadata, used for steaming log download. :type metadata: dict """ # Offset is the unique key for sorting logs given log_id. search = Search(using=self.client) \ .query('match_phrase', log_id=log_id) \ .sort('offset') search = search.filter('range', offset={'gt': int(offset)}) max_log_line = search.count() if 'download_logs' in metadata and metadata['download_logs'] and 'max_offset' not in metadata: try: if max_log_line > 0: metadata['max_offset'] = search[max_log_line - 1].execute()[-1].offset else: metadata['max_offset'] = 0 except Exception: # pylint: disable=broad-except self.log.exception('Could not get current log size with log_id: %s', log_id) logs = [] if max_log_line != 0: try: logs = search[self.MAX_LINE_PER_PAGE * self.PAGE:self.MAX_LINE_PER_PAGE] \ .execute() except Exception as e: # pylint: disable=broad-except self.log.exception('Could not read log with log_id: %s, error: %s', log_id, str(e)) return logs def set_context(self, ti): """ Provide task_instance context to airflow task handler. :param ti: task instance object """ self.mark_end_on_close = not ti.raw if self.json_format: self.formatter = JSONFormatter( self.formatter._fmt, # pylint: disable=protected-access json_fields=self.json_fields, extras={ 'dag_id': str(ti.dag_id), 'task_id': str(ti.task_id), 'execution_date': self._clean_execution_date(ti.execution_date), 'try_number': str(ti.try_number) }) if self.write_stdout: if self.context_set: # We don't want to re-set up the handler if this logger has # already been initialized return self.handler = logging.StreamHandler(stream=sys.__stdout__) self.handler.setLevel(self.level) self.handler.setFormatter(self.formatter) else: super().set_context(ti) self.context_set = True def close(self): # When application exit, system shuts down all handlers by # calling close method. Here we check if logger is already # closed to prevent uploading the log to remote storage multiple # times when `logging.shutdown` is called. if self.closed: return if not self.mark_end_on_close: self.closed = True return # Case which context of the handler was not set. if self.handler is None: self.closed = True return # Reopen the file stream, because FileHandler.close() would be called # first in logging.shutdown() and the stream in it would be set to None. if self.handler.stream is None or self.handler.stream.closed: self.handler.stream = self.handler._open() # pylint: disable=protected-access # Mark the end of file using end of log mark, # so we know where to stop while auto-tailing. self.handler.stream.write(self.end_of_log_mark) if self.write_stdout: self.handler.close() sys.stdout = sys.__stdout__ super().close() self.closed = True
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2016 Timothy Dozat # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf #*************************************************************** sig_const = np.arctanh(1/3) tanh_const = np.arctanh(np.sqrt(1/3)) def tanh(x): return tf.tanh(x) def sigmoid(x): return (tf.tanh(x)+1)/2 #=============================================================== def orthonormal_initializer(input_size, output_size): """""" if not tf.get_variable_scope().reuse: print(tf.get_variable_scope().name) I = np.eye(output_size) lr = .1 eps = .05 / (output_size + input_size) success = False while not success: Q = np.random.randn(input_size, output_size) / np.sqrt(output_size) for i in xrange(100): QTQmI = Q.T.dot(Q) - I loss = np.sum(QTQmI ** 2 / 2) Q2 = Q ** 2 Q -= lr * Q.dot(QTQmI) / (np.abs(Q2 + Q2.sum(axis=0, keepdims=True) + Q2.sum(axis=1, keepdims=True) - 1) + eps) if np.isnan(Q[0, 0]): lr /= 2 break if np.isfinite(loss) and np.max(Q) < 1e6: success = True eps *= 2 print('Orthogonal pretrainer loss: %.2e' % loss) else: print('Orthogonal pretrainer failed, using non-orthogonal random matrix') Q = np.random.randn(input_size, output_size) / np.sqrt(output_size) return Q.astype(np.float32) #=============================================================== def linear(inputs, output_size, add_bias=True, n_splits=1, initializer=None, scope=None, moving_params=None): """""" if not isinstance(inputs, (list, tuple)): inputs = [inputs] output_size *= n_splits with tf.variable_scope(scope or 'Linear'): # Reformat the input total_input_size = 0 shapes = [a.get_shape().as_list() for a in inputs] for shape in shapes: total_input_size += shape[-1] input_shape = tf.shape(inputs[0]) output_shape = [] for i in xrange(len(shapes[0])): output_shape.append(input_shape[i]) output_shape[-1] = output_size output_shape = tf.stack(output_shape) for i, (input_, shape) in enumerate(zip(inputs, shapes)): inputs[i] = tf.reshape(input_, [-1, shape[-1]]) concatenation = tf.concat(axis=1, values=inputs) # Get the matrix if initializer is None and moving_params is None: mat = orthonormal_initializer(total_input_size, output_size//n_splits) mat = np.concatenate([mat]*n_splits, axis=1) initializer = tf.constant_initializer(mat) matrix = tf.get_variable('Weights', [total_input_size, output_size], initializer=initializer) if moving_params is not None: matrix = moving_params.average(matrix) else: tf.add_to_collection('Weights', matrix) # Get the bias if add_bias: bias = tf.get_variable('Biases', [output_size], initializer=tf.zeros_initializer()) if moving_params is not None: bias = moving_params.average(bias) else: bias = 0 # Do the multiplication new = tf.matmul(concatenation, matrix) + bias new = tf.reshape(new, output_shape) new.set_shape([tf.Dimension(None) for _ in xrange(len(shapes[0])-1)] + [tf.Dimension(output_size)]) if n_splits > 1: return tf.split(axis=len(new.get_shape().as_list())-1, num_or_size_splits=n_splits, value=new) else: return new #=============================================================== def bilinear(inputs1, inputs2, output_size, add_bias2=True, add_bias1=True, add_bias=False, initializer=None, scope=None, moving_params=None): """""" with tf.variable_scope(scope or 'Bilinear'): # Reformat the inputs ndims = len(inputs1.get_shape().as_list()) inputs1_shape = tf.shape(inputs1) inputs1_bucket_size = inputs1_shape[ndims-2] inputs1_size = inputs1.get_shape().as_list()[-1] inputs2_shape = tf.shape(inputs2) inputs2_bucket_size = inputs2_shape[ndims-2] inputs2_size = inputs2.get_shape().as_list()[-1] output_shape = [] batch_size = 1 for i in xrange(ndims-2): batch_size *= inputs1_shape[i] output_shape.append(inputs1_shape[i]) output_shape.append(inputs1_bucket_size) output_shape.append(output_size) output_shape.append(inputs2_bucket_size) output_shape = tf.stack(output_shape) inputs1 = tf.reshape(inputs1, tf.stack([batch_size, inputs1_bucket_size, inputs1_size])) inputs2 = tf.reshape(inputs2, tf.stack([batch_size, inputs2_bucket_size, inputs2_size])) if add_bias1: inputs1 = tf.concat(axis=2, values=[inputs1, tf.ones(tf.stack([batch_size, inputs1_bucket_size, 1]))]) if add_bias2: inputs2 = tf.concat(axis=2, values=[inputs2, tf.ones(tf.stack([batch_size, inputs2_bucket_size, 1]))]) # Get the matrix if initializer is None and moving_params is None: mat = orthonormal_initializer(inputs1_size+add_bias1, inputs2_size+add_bias2)[:,None,:] mat = np.concatenate([mat]*output_size, axis=1) initializer = tf.constant_initializer(mat) weights = tf.get_variable('Weights', [inputs1_size+add_bias1, output_size, inputs2_size+add_bias2], initializer=initializer) if moving_params is not None: weights = moving_params.average(weights) else: tf.add_to_collection('Weights', weights) # Do the multiplications # (bn x d) (d x rd) -> (bn x rd) lin = tf.matmul(tf.reshape(inputs1, [-1, inputs1_size+add_bias1]), tf.reshape(weights, [inputs1_size+add_bias1, -1])) # (b x nr x d) (b x n x d)T -> (b x nr x n) bilin = tf.matmul(tf.reshape(lin, tf.stack([batch_size, inputs1_bucket_size*output_size, inputs2_size+add_bias2])), inputs2, adjoint_b=True) # (bn x r x n) bilin = tf.reshape(bilin, tf.stack([-1, output_size, inputs2_bucket_size])) # (b x n x r x n) bilin = tf.reshape(bilin, output_shape) # Get the bias if add_bias: bias = tf.get_variable('Biases', [output_size], initializer=tf.zeros_initializer()) if moving_params is not None: bias = moving_params.average(bias) bilin += tf.expand_dims(bias, 1) return bilin # =============================================================== def bilinear_noreshape(inputs1, inputs2, output_size, add_bias2=True, add_bias1=True, add_bias=False, initializer=None, scope=None, moving_params=None): """""" with tf.variable_scope(scope or 'Bilinear'): # Reformat the inputs ndims = len(inputs1.get_shape().as_list()) inputs1_shape = tf.shape(inputs1) inputs1_bucket_size = inputs1_shape[ndims - 2] inputs1_size = inputs1.get_shape().as_list()[-1] inputs2_shape = tf.shape(inputs2) inputs2_bucket_size = inputs2_shape[ndims - 2] inputs2_size = inputs2.get_shape().as_list()[-1] # output_shape = [] batch_size1 = 1 batch_size2 = 1 for i in xrange(ndims - 2): batch_size1 *= inputs1_shape[i] batch_size2 *= inputs2_shape[i] # output_shape.append(inputs1_shape[i]) # output_shape.append(inputs1_bucket_size) # output_shape.append(output_size) # output_shape.append(inputs2_bucket_size) # output_shape = tf.stack(output_shape) inputs1 = tf.reshape(inputs1, tf.stack([batch_size1, inputs1_bucket_size, inputs1_size])) inputs2 = tf.reshape(inputs2, tf.stack([batch_size2, inputs2_bucket_size, inputs2_size])) if add_bias1: inputs1 = tf.concat(axis=2, values=[inputs1, tf.ones(tf.stack([batch_size1, inputs1_bucket_size, 1]))]) if add_bias2: inputs2 = tf.concat(axis=2, values=[inputs2, tf.ones(tf.stack([batch_size2, inputs2_bucket_size, 1]))]) # Get the matrix if initializer is None and moving_params is None: mat = orthonormal_initializer(inputs1_size + add_bias1, inputs2_size + add_bias2)[:, None, :] mat = np.concatenate([mat] * output_size, axis=1) initializer = tf.constant_initializer(mat) weights = tf.get_variable('Weights', [inputs1_size + add_bias1, output_size, inputs2_size + add_bias2], initializer=initializer) if moving_params is not None: weights = moving_params.average(weights) else: tf.add_to_collection('Weights', weights) # inputs1: num_triggers_in_batch x 1 x self.trigger_mlp_size # inputs2: batch x seq_len x self.role_mlp_size # Do the multiplications # (bn x d) (d x rd) -> (bn x rd) lin = tf.matmul(tf.reshape(inputs1, [-1, inputs1_size + add_bias1]), tf.reshape(weights, [inputs1_size + add_bias1, -1])) # (b x nr x d) (b x n x d)T -> (b x nr x n) lin_reshape = tf.reshape(lin, tf.stack([batch_size1, inputs1_bucket_size * output_size, inputs2_size + add_bias2])) bilin = tf.matmul(lin_reshape, inputs2, adjoint_b=True) # (bn x r x n) bilin = tf.reshape(bilin, tf.stack([-1, output_size, inputs2_bucket_size])) # (b x n x r x n) # bilin = tf.reshape(bilin, output_shape) # bilin = tf.Print(bilin, [batch_size1, inputs2_bucket_size, output_size, tf.shape(bilin)], "bilin shape") # Get the bias if add_bias: bias = tf.get_variable('Biases', [output_size], initializer=tf.zeros_initializer()) if moving_params is not None: bias = moving_params.average(bias) bilin += tf.expand_dims(bias, 1) return bilin #=============================================================== def diagonal_bilinear(inputs1, inputs2, output_size, add_bias2=True, add_bias1=True, add_bias=False, initializer=None, scope=None, moving_params=None): """""" with tf.variable_scope(scope or 'Bilinear'): # Reformat the inputs ndims = len(inputs1.get_shape().as_list()) inputs1_shape = tf.shape(inputs1) inputs2_shape = tf.shape(inputs2) inputs1_bucket_size = inputs1_shape[ndims-2] inputs2_bucket_size = inputs2_shape[ndims-2] inputs1_size = inputs1.get_shape().as_list()[-1] inputs2_size = inputs2.get_shape().as_list()[-1] assert inputs1_size == inputs2_size output_shape = [] batch_size = 1 for i in xrange(ndims-2): batch_size *= inputs1_shape[i] output_shape.append(inputs1_shape[i]) output_shape.append(inputs1_bucket_size) output_shape.append(output_size) output_shape.append(inputs2_bucket_size) output_shape = tf.stack(output_shape) inputs1 = tf.reshape(inputs1, tf.stack([batch_size, inputs1_bucket_size, inputs1_size])) inputs2 = tf.reshape(inputs2, tf.stack([batch_size, inputs2_bucket_size, inputs2_size])) inputs1.set_shape([tf.Dimension(None)]*2 + [tf.Dimension(inputs1_size)]) inputs2.set_shape([tf.Dimension(None)]*2 + [tf.Dimension(inputs2_size)]) inputs = broadcast_mult(inputs1, inputs2) with tf.variable_scope('Bilinear'): bilin = linear(inputs, output_size, add_bias=add_bias, initializer=initializer, scope=scope, moving_params=moving_params) with tf.variable_scope('Linear1'): lin1 = linear(inputs1, output_size, add_bias=False, initializer=initializer, scope=scope, moving_params=moving_params) lin1 = tf.expand_dims(lin1, 2) with tf.variable_scope('Linear2'): lin2 = linear(inputs2, output_size, add_bias=False, initializer=initializer, scope=scope, moving_params=moving_params) lin2 = tf.expand_dims(lin2, 1) bilin = tf.transpose(bilin+lin1+lin2, [0,1,3,2]) return bilin #=============================================================== def layer_norm(inputs, beta_start=0, gamma_start=1, scope=None, moving_params=None): """""" with tf.variable_scope(scope or "Layer_norm"): gamma = tf.get_variable('Gamma', shape=[], initializer=tf.constant_initializer(gamma_start)) beta = tf.get_variable('Beta', shape=[], initializer=tf.constant_initializer(beta_start)) if moving_params is not None: gamma = moving_params.average(gamma) beta = moving_params.average(beta) mean, var = tf.nn.moments(inputs, 1, keep_dims=True) inputs = gamma * (inputs-mean) / tf.sqrt(var+self.epsilon) + beta return inputs #=============================================================== def broadcast_add(inputs1, inputs2): """""" inputs1_shape = tf.shape(inputs1) inputs_size = inputs1.get_shape().as_list()[-1] inputs2_shape = tf.shape(inputs2) inputs1 = tf.transpose(inputs1, [0,2,1]) inputs2 = tf.transpose(inputs2, [0,2,1]) inputs1 = tf.reshape(inputs1, tf.stack([-1,inputs1_shape[1],1])) inputs2 = tf.reshape(inputs2, tf.stack([-1,1,inputs2_shape[1]])) inputs = inputs1 + inputs2 inputs = tf.reshape(inputs, [inputs1_shape[0], inputs1_shape[2], inputs1_shape[1], inputs2_shape[1]]) inputs = tf.transpose(inputs, [0,2,3,1]) inputs.set_shape([tf.Dimension(None)]*3 + [tf.Dimension(inputs_size)]) return inputs #=============================================================== def broadcast_sub(inputs1, inputs2): """""" inputs1_shape = tf.shape(inputs1) inputs_size = inputs1.get_shape().as_list()[-1] inputs2_shape = tf.shape(inputs2) inputs1 = tf.transpose(inputs1, [0,2,1]) inputs2 = tf.transpose(inputs2, [0,2,1]) inputs1 = tf.reshape(inputs1, tf.stack([-1,inputs1_shape[1],1])) inputs2 = tf.reshape(inputs2, tf.stack([-1,1,inputs2_shape[1]])) inputs = inputs1 - inputs2 inputs = tf.reshape(inputs, [inputs1_shape[0], inputs1_shape[2], inputs1_shape[1], inputs2_shape[1]]) inputs = tf.transpose(inputs, [0,2,3,1]) inputs.set_shape([tf.Dimension(None)]*3 + [tf.Dimension(inputs_size)]) return inputs #=============================================================== def broadcast_mult(inputs1, inputs2): """""" inputs1_shape = tf.shape(inputs1) inputs_size = inputs1.get_shape().as_list()[-1] inputs2_shape = tf.shape(inputs2) inputs1 = tf.transpose(inputs1, [0,2,1]) inputs2 = tf.transpose(inputs2, [0,2,1]) inputs1 = tf.reshape(inputs1, tf.stack([-1,inputs1_shape[1],1])) inputs2 = tf.reshape(inputs2, tf.stack([-1,1,inputs2_shape[1]])) inputs = inputs1 * inputs2 inputs = tf.reshape(inputs, tf.stack([inputs1_shape[0], inputs1_shape[2], inputs1_shape[1], inputs2_shape[1]])) inputs = tf.transpose(inputs, [0,2,3,1]) inputs.set_shape([tf.Dimension(None)]*3 + [tf.Dimension(inputs_size)]) return inputs #*************************************************************** if __name__ == '__main__': """""" x1 = tf.Variable(np.random.randn(5,5).astype(np.float32)) x2 = tf.Variable(np.random.randn(5,2).astype(np.float32)) z = linear([x1, x2], 10) zz = bilinear(x1, x2, 10) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) sess.run(z) sess.run(zz)
import unittest from urllib3_mock import Responses import demisto_client from datetime import datetime import json responses = Responses('requests.packages.urllib3') api_key = 'sample_api_key' host = 'http://localhost:8080' def assert_reset(): assert len(responses._urls) == 0 assert len(responses.calls) == 0 def test_get_docker_images(): '''Check GET docker images.''' @responses.activate def run(): body = '{ "images": [{"id": "aae7b8aaba8c", "repository": ' \ '"openapitools/openapi-generator-cli", "tag": "latest", "createdSince": "3 days ago", ' \ '"createdAt": "2019-08-19 13:34:22 +0300 IDT", "size": "131MB" }]}' responses.add('GET', '/settings/docker-images', body=body, status=200, content_type='application/json') # create an instance of the API class api_instance = demisto_client.configure(base_url=host, api_key=api_key) api_response = api_instance.get_docker_images() assert api_response.images[0].created_at == '2019-08-19 13:34:22 +0300 IDT' assert api_response.images[0].id == 'aae7b8aaba8c' assert api_response.images[0].repository == 'openapitools/openapi-generator-cli' assert len(responses.calls) == 1 assert responses.calls[0].request.url == '/settings/docker-images' assert responses.calls[0].request.host == 'localhost' assert responses.calls[0].request.scheme == 'http' run() assert_reset() def test_create_incident(): '''Check creating an incident.''' @responses.activate def run(): body = '{"name":"Test Incident","owner":"Admin","parent":"","phase":"",' \ '"playbookId":"playbook0","playbook_id":"playbook0","rawCategory":"",' \ '"rawCloseReason":"","rawJSON":"","rawName":"Test Incident","rawPhase":"",' \ '"rawType":"Unclassified","raw_category":"","raw_close_reason":"","raw_json":"",' \ '"raw_name":"Test Incident","raw_phase":"","raw_type":"Unclassified","reason":"",' \ '"runStatus":"","run_status":"","severity":0,"sourceBrand":"Manual",' \ '"sourceInstance":"admin","source_brand":"Manual","source_instance":"admin",' \ '"status":0,"type":"Unclassified","version":1}' responses.add('POST', '/incident', body=body, status=200, content_type='application/json') # create an instance of the API class api_instance = demisto_client.configure(base_url=host, api_key=api_key) create_incident_request = demisto_client.demisto_api.CreateIncidentRequest() create_incident_request.name = 'Test Incident' create_incident_request.type = 'Unclassified' create_incident_request.owner = 'Admin' create_incident_request.occurred = datetime.now() api_response = api_instance.create_incident(create_incident_request=create_incident_request) assert api_response.name == 'Test Incident' assert api_response.type == 'Unclassified' assert api_response.owner == 'Admin' assert len(responses.calls) == 1 req = responses.calls[0].request assert req.url == '/incident' assert req.host == 'localhost' assert req.scheme == 'http' # veriy date field occurred according to rfc 3339 req_body = json.loads(req.body) assert req_body['occurred'][-6] == '+' or req_body['occurred'][-6] == '-' # end with +/- offset run() assert_reset() def test_get_reports(): '''Testing GET all reports.''' @responses.activate def run(): body = '[{"created_by":"DBot","dashboard":"None","decoder":{},"description":"This report ' \ 'generates Mean Time to Resolve by Incident type for last 2 Quarters",' \ '"id":"MTTRbyIncidentType2Quar","locked":false,"name":"Mean time to Resolve by ' \ 'Incident Type (Last 2 Quarters)","orientation":"portrait","prev_name":"Mean time to ' \ 'Resolve by Incident Type (Last 2 Quarters)","prev_type":"pdf","type":"pdf",' \ '"version":4}]' responses.add('GET', '/reports', body=body, status=200, content_type='application/json') api_instance = demisto_client.configure(base_url=host, api_key=api_key, debug=False) api_response = api_instance.get_all_reports() assert api_response[0].id == 'MTTRbyIncidentType2Quar' assert api_response[ 0].description == 'This report generates Mean Time to Resolve by Incident type for ' \ '' \ 'last 2 Quarters' assert api_response[0].version == 4 assert len(responses.calls) == 1 assert responses.calls[0].request.url == '/reports' assert responses.calls[0].request.host == 'localhost' assert responses.calls[0].request.scheme == 'http' run() assert_reset() def test_indicators_search(): '''Testing search for indicator.''' @responses.activate def run(): body = r''' { "iocObjects": [{ "id": "4737", "version": 1, "modified": "2019-07-14T16:54:02.719044+03:00", "account": "", "timestamp": "2019-07-14T16:54:02.718422+03:00", "indicator_type": "IP", "value": "92.63.197.153", "source": "Recorded Future", "investigationIDs": ["1750"], "lastSeen": "2019-07-14T16:54:02.718378+03:00", "firstSeen": "2019-07-14T16:54:02.718378+03:00", "lastSeenEntryID": "API", "firstSeenEntryID": "API", "score": 3, "manualScore": true, "setBy": "DBotWeak", "manualSetTime": "0001-01-01T00:00:00Z", "insightCache": null, "calculatedTime": "2019-07-14T16:54:02.718378+03:00", "lastReputationRun": "0001-01-01T00:00:00Z", "comment": "From Recorded Future risk list, Score - 89", "manuallyEditedFields": null }], "total": 1 } ''' responses.add('POST', '/indicators/search', body=body, status=200, content_type='application/json') api_instance = demisto_client.configure(base_url=host, api_key=api_key, debug=False) indicator_filter = demisto_client.demisto_api.IndicatorFilter() # IndicatorFilter | (optional) indicator_filter.query = 'value:92.63.197.153' api_response = api_instance.indicators_search(indicator_filter=indicator_filter) assert api_response.ioc_objects[0].get('comment') == 'From Recorded Future risk list, Score - 89' # assert api_response.type == 'Unclassified' # assert api_response.owner == 'Admin' assert len(responses.calls) == 1 assert responses.calls[0].request.url == '/indicators/search' assert responses.calls[0].request.host == 'localhost' assert responses.calls[0].request.scheme == 'http' run() assert_reset() def test_export_entry(): '''Testing export entry artifact.''' @responses.activate def run(): body = "[email protected]" responses.add('POST', '/entry/exportArtifact', body=body, status=200, content_type='application/json') api_instance = demisto_client.configure(base_url=host, api_key=api_key, debug=False) download_entry = demisto_client.demisto_api.DownloadEntry() # DownloadEntry | (optional) download_entry.id = '6@1770' download_entry.investigation_id = '1770' api_result = api_instance.entry_export_artifact(download_entry=download_entry) assert api_result == '[email protected]' assert len(responses.calls) == 1 assert responses.calls[0].request.url == '/entry/exportArtifact' assert responses.calls[0].request.host == 'localhost' assert responses.calls[0].request.scheme == 'http' run() assert_reset() def test_generic_request(): '''Testing generic requst.''' @responses.activate def run(): responses.add('POST', '/test', body="all good", status=200, content_type='text/plain') api_instance = demisto_client.configure(base_url=host, api_key=api_key, debug=False) (res, code, headers) = api_instance.generic_request('/test', 'POST', body="this is a test", content_type='text/plain', accept='text/plain') assert res == 'all good' assert code == 200 assert len(responses.calls) == 1 assert responses.calls[0].request.url == '/test' assert responses.calls[0].request.host == 'localhost' assert responses.calls[0].request.scheme == 'http' run() assert_reset() def test_import_layout(mocker): """ Given: - Path for a layoutscontainer. When - Using client.import_layout() to upload a new layout. Then - The layout is being uploaded and getting back the layout metadata. """ client = demisto_client.configure(base_url=host, api_key=api_key, debug=False, verify_ssl=False) mocker.patch.object(client, 'import_layout_with_http_info', return_value={'test': 'test'}) res = client.import_layout('tests_data/layoutscontainer-test.json') assert res.get('test') == 'test' def test_import_layout_with_http_info_with_knowing_server_version(mocker): """ Given: - path for a layoutscontainer. When - Succeeding in getting demisto version using 'get_layouts_url_for_demisto_version' function Then - The layout is being uploaded and getting back the layout metadata. """ client = demisto_client.configure(base_url=host, api_key=api_key, debug=False, verify_ssl=False) mocker.patch.object(client.api_client, 'call_api', side_effect=[("{'demistoVersion': '6.0.0'}", 200, {'Content-type': 'application/json'}), {'test': 'test'}]) res = client.import_layout('tests_data/layoutscontainer-test.json') assert res.get('test') == 'test' def test_import_layout_with_http_info_without_knowing_server_version(mocker): """ Given: - Path for a layoutscontainer. When - Not knowing demisto version, and working with 6.0.0 or higher Then - The layout is being uploaded and getting back the layout metadata. """ client = demisto_client.configure(base_url=host, api_key=api_key, debug=False, verify_ssl=False) mocker.patch.object(client.api_client, 'call_api', side_effect=[("{'demistoVersion': '6.0.0'}", 404, {'Content-type': 'application/json'}), {'test': 'test'}]) res = client.import_layout('tests_data/layoutscontainer-test.json') assert res.get('test') == 'test' def test_import_layout_with_http_info_with_old_layout_format(mocker): """ Given: - Path for a layout When - Working with 5.0.0 and uploading a layout(the old version) Then - The layout is being uploaded and getting back the layout metadata. """ client = demisto_client.configure(base_url=host, api_key=api_key, debug=False, verify_ssl=False) mocker.patch.object(client.api_client, 'call_api', side_effect=[("{'demistoVersion': '5.0.0'}", 200, {'Content-type': 'application/json'}), {'test': 'test'}]) res = client.import_layout('tests_data/layout-details-test-V2.json') assert res.get('test') == 'test' class TestFailedGenericRequestNoEnv(unittest.TestCase): def test_generic_request(self): """ Given: - Request which should result in an ApiException When: - No environment variable has been set Then: - Return ApiException without the headers in the error """ from demisto_client.demisto_api.rest import ApiException @responses.activate def run(): responses.add('POST', '/test', body="Not good", status=400, content_type='text/plain') api_instance = demisto_client.configure(base_url=host, api_key=api_key, debug=False) with self.assertRaises(ApiException) as context: (_, _, _) = api_instance.generic_request('/test', 'POST', body="this is a test", content_type='text/plain', accept='text/plain') self.assertTrue('HTTP response body' in str(context.exception)) self.assertFalse('HTTP response headers' in str(context.exception)) assert len(responses.calls) == 1 assert responses.calls[0].request.url == '/test' assert responses.calls[0].request.host == 'localhost' assert responses.calls[0].request.scheme == 'http' run() assert_reset() class TestFailedGenericRequestWithEnv(unittest.TestCase): def test_generic_request(self): """ Given: - Request which should result in an ApiException When: - Environment variable DEMISTO_EXCEPTION_HEADER_LOGGING has been set to true Then: - Return ApiException with the headers in the error """ import sys # Error should be the same in both Py2 and Py3, but Py2 does not support unittest mock in # the same way if sys.version_info[0] > 2: import os from demisto_client.demisto_api.rest import ApiException from unittest import mock @mock.patch.dict(os.environ, {"DEMISTO_EXCEPTION_HEADER_LOGGING": "true"}) @responses.activate def run(): responses.add('POST', '/test', body="Not good", status=400, content_type='text/plain') api_instance = demisto_client.configure(base_url=host, api_key=api_key, debug=False) with self.assertRaises(ApiException) as context: (_, _, _) = api_instance.generic_request('/test', 'POST', body="this is a test", content_type='text/plain', accept='text/plain') self.assertTrue('HTTP response body' in str(context.exception)) self.assertTrue('HTTP response headers' in str(context.exception)) assert len(responses.calls) == 1 assert responses.calls[0].request.url == '/test' assert responses.calls[0].request.host == 'localhost' assert responses.calls[0].request.scheme == 'http' else: def run(): assert 1 == 1 run() assert_reset()
import os import struct import subprocess import sys import time import sharedstructures POOL_NAME_PREFIX = "HashTableTest-py-pool-" ALLOCATOR_TYPES = ('simple', 'logarithmic') def get_current_process_lsof(): return subprocess.check_output(['lsof', '-p', str(os.getpid())]) def expect_key_missing(table, k): try: table[k] assert False, 'table[%r] didn\'t raise' % k except KeyError: pass def verify_state(expected, table): assert len(expected) == len(table) for k, v in expected.items(): assert table[k] == v for k, v in table.items(): assert expected[k] == v verify_allocator(table) def verify_allocator(table): ret = table.verify() assert ret is None, ret.decode('utf-8') def run_basic_test(allocator_type): print("-- [%s] basic" % allocator_type) before_lsof_count = len(get_current_process_lsof().splitlines()) table = sharedstructures.HashTable(POOL_NAME_PREFIX + allocator_type, allocator_type) expected = {} def insert_both(e, t, k, v): t[k] = v e[k] = v def delete_both(e, t, k): del t[k] del e[k] verify_state(expected, table) insert_both(expected, table, b'key1', b'value1') verify_state(expected, table) insert_both(expected, table, b'key2', b'value2') verify_state(expected, table) insert_both(expected, table, b'key3', b'value3') verify_state(expected, table) delete_both(expected, table, b'key2') verify_state(expected, table) try: del table[b'key2'] assert False, "del table[\'key2\'] did not raise KeyError" except KeyError: pass verify_state(expected, table) insert_both(expected, table, b'key1', b'value0') verify_state(expected, table) delete_both(expected, table, b'key1') verify_state(expected, table) delete_both(expected, table, b'key3') verify_state(expected, table) assert {} == expected del table # this should unmap the shared memory pool and close the fd sharedstructures.delete_pool(POOL_NAME_PREFIX + allocator_type) # this will fail if the test prints anything after before_lsof is taken since # the stdout/stderr offsets will be different assert before_lsof_count == len(get_current_process_lsof().splitlines()) def run_conditional_writes_test(allocator_type): print("-- [%s] conditional writes" % allocator_type) table = sharedstructures.HashTable(POOL_NAME_PREFIX + allocator_type, allocator_type) expected = {} def insert_both(e, t, k, v): t[k] = v e[k] = v def delete_both(e, t, k): del t[k] del e[k] def conditional_insert_both(e, t, check_k, check_v, target_k, target_v, written): if t.check_and_set(check_k, check_v, target_k, target_v): e[target_k] = target_v assert written else: assert not written def conditional_missing_insert_both(e, t, check_k, target_k, target_v, written): if t.check_missing_and_set(check_k, target_k, target_v): e[target_k] = target_v assert written else: assert not written def conditional_delete_both(e, t, check_k, check_v, target_k, written): if t.check_and_set(check_k, check_v, target_k): del e[target_k] assert written else: assert not written def conditional_missing_delete_both(e, t, check_k, target_k, written): if t.check_missing_and_set(check_k, target_k): del e[target_k] assert written else: assert not written verify_state(expected, table) insert_both(expected, table, b"key1", b"value1") verify_state(expected, table) insert_both(expected, table, b"key2", b"value2") verify_state(expected, table) # check that conditions on the same key work conditional_insert_both(expected, table, b"key1", b"value2", b"key1", b"value1_1", False) verify_state(expected, table) conditional_insert_both(expected, table, b"key1", b"value1", b"key1", b"value1_1", True) verify_state(expected, table) # check that conditions on other keys work conditional_insert_both(expected, table, b"key2", b"value1", b"key1", b"value1", False) verify_state(expected, table) conditional_insert_both(expected, table, b"key2", b"value2", b"key1", b"value1", True) verify_state(expected, table) # check that missing conditions work conditional_missing_insert_both(expected, table, b"key2", b"key3", b"value3", False) verify_state(expected, table) conditional_missing_insert_both(expected, table, b"key3", b"key3", b"value3", True) verify_state(expected, table) # check that conditional deletes work conditional_delete_both(expected, table, b"key1", b"value2", b"key1", False) verify_state(expected, table) conditional_delete_both(expected, table, b"key1", b"value1", b"key1", True) verify_state(expected, table) conditional_missing_delete_both(expected, table, b"key3", b"key2", False) verify_state(expected, table) conditional_missing_delete_both(expected, table, b"key1", b"key2", True) verify_state(expected, table) delete_both(expected, table, b"key3") assert expected == {} def run_collision_test(allocator_type): print("-- [%s] collision" % allocator_type) table = sharedstructures.HashTable(POOL_NAME_PREFIX + allocator_type, allocator_type, 0, 2) expected = {} def insert_both(e, t, k, v): t[k] = v e[k] = v def delete_both(e, t, k): del t[k] del e[k] # writing 5 keys to a 4-slot hashtable forces a collision assert 2 == table.bits() assert 0 == len(table) insert_both(expected, table, b'key1', b'value1') insert_both(expected, table, b'key2', b'value2') insert_both(expected, table, b'key3', b'value3') insert_both(expected, table, b'key4', b'value4') insert_both(expected, table, b'key5', b'value5') verify_state(expected, table) while expected: k, _ = expected.popitem(); del table[k] verify_state(expected, table) def run_incr_test(allocator_type): print('-- [%s] incr' % allocator_type) table = sharedstructures.HashTable(POOL_NAME_PREFIX + allocator_type, allocator_type, 0, 6) expected = {} def insert_both(k, v): table[k] = v expected[k] = v def delete_both(k): del table[k] del expected[k] # giving garbage to incr() should cause a TypeError try: table.incr(b'missing', b'not a number, lolz') assert False except TypeError: pass try: table.incr(b'missing', {'still': 'not', 'a': 'number'}) assert False except TypeError: pass assert 0 == len(table) insert_both(b'int8', struct.pack(b'@b', 40)) insert_both(b'int16', struct.pack(b'@h', 4000)) insert_both(b'int32', struct.pack(b'@l', 60000000)) insert_both(b'int64', struct.pack(b'@q', 800000000000000)) insert_both(b'float', struct.pack(b'@f', 10.0)) insert_both(b'double', struct.pack(b'@d', 15.5)) insert_both(b'string', b'7 bytes') assert 7 == len(table) # incr should create the key if it doesn't exist assert -10 == table.incr(b"int8-2", -10) assert -4000 == table.incr(b"int16-2", -4000) assert -60000000 == table.incr(b"int32-2", -60000000) assert -800000000000000 == table.incr(b"int64-2", -800000000000000) assert -10.0 == table.incr(b"float-2", -10.0) assert -15.5 == table.incr(b"double-2", -15.5) assert 13 == len(table) # all the keys should have the values we set, but the keys created by incr # should all be 64 bits assert struct.pack(b'@b', 40) == table[b"int8"] assert struct.pack(b'@h', 4000) == table[b"int16"] assert struct.pack(b'@l', 60000000) == table[b"int32"] assert struct.pack(b'@q', 800000000000000) == table[b"int64"] assert struct.pack(b'@f', 10.0) == table[b"float"] assert struct.pack(b'@d', 15.5) == table[b"double"] assert struct.pack(b'@q', -10) == table[b"int8-2"] assert struct.pack(b'@q', -4000) == table[b"int16-2"] assert struct.pack(b'@q', -60000000) == table[b"int32-2"] assert struct.pack(b'@q', -800000000000000) == table[b"int64-2"] assert struct.pack(b'@d', -10.0) == table[b"float-2"] assert struct.pack(b'@d', -15.5) == table[b"double-2"] assert 13 == table.size() # incr should return the new value of the key assert struct.pack(b'@b', 44) == table.incr(b"int8", 4) assert struct.pack(b'@h', 4010) == table.incr(b"int16", 10) assert struct.pack(b'@l', 60000100) == table.incr(b"int32", 100) assert struct.pack(b'@q', 800000000001000) == table.incr(b"int64", 1000) assert struct.pack(b'@f', 30.0) == table.incr(b"float", 20.0) assert struct.pack(b'@d', 25.5) == table.incr(b"double", 10.0) assert struct.pack(b'@q', -14) == table.incr(b"int8-2", -4) assert struct.pack(b'@q', -4010) == table.incr(b"int16-2", -10) assert struct.pack(b'@q', -60000100) == table.incr(b"int32-2", -100) assert struct.pack(b'@q', -800000000001000) == table.incr(b"int64-2", -1000) assert struct.pack(b'@d', -30.0) == table.incr(b"float-2", -20.0) assert struct.pack(b'@d', -25.5) == table.incr(b"double-2", -10.0) assert 13 == table.size() # test incr() on keys of the wrong size try: table.incr(b"string", 14) assert False except ValueError: pass try: table.incr(b"string", 15.0) assert False except ValueError: pass # we're done here table.clear() assert len(table) == 0 # TODO: deduplicate this with PrefixTreeTest def run_concurrent_readers_test(allocator_type): print('-- [%s] concurrent readers' % allocator_type) table = sharedstructures.HashTable(POOL_NAME_PREFIX + allocator_type, allocator_type) del table child_pids = set() while (len(child_pids) < 8) and (0 not in child_pids): child_pids.add(os.fork()) if 0 in child_pids: # child process: try up to a second to get the key table = sharedstructures.HashTable(POOL_NAME_PREFIX + allocator_type, allocator_type) value = 100 start_time = int(time.time() * 1000000) while (value < 110) and \ (int(time.time() * 1000000) < (start_time + 1000000)): time.sleep(0.001) try: res = table[b'key1'] except KeyError: pass else: if res == value: print('-- [%s] child %d saw value %d' % (allocator_type, os.getpid(), value)) value += 1 if int(time.time() * 1000000) >= (start_time + 1000000): print('-- [%s] child %d timed out' % (allocator_type, os.getpid())) os._exit(int(value != 110)) else: # parent process: write the key, then wait for children to terminate table = sharedstructures.HashTable(POOL_NAME_PREFIX + allocator_type, allocator_type) for value in range(100, 110): time.sleep(0.05) table[b'key1'] = value num_failures = 0 while child_pids: pid, exit_status = os.wait() child_pids.remove(pid) if os.WIFEXITED(exit_status) and (os.WEXITSTATUS(exit_status) == 0): print('-- [%s] child %d terminated successfully' % ( allocator_type, pid)) else: print('-- [%s] child %d failed (%d)' % ( allocator_type, pid, exit_status)) num_failures += 1 assert 0 == len(child_pids) assert 0 == num_failures def main(): try: for allocator_type in ALLOCATOR_TYPES: sharedstructures.delete_pool(POOL_NAME_PREFIX + allocator_type) run_basic_test(allocator_type) sharedstructures.delete_pool(POOL_NAME_PREFIX + allocator_type) run_conditional_writes_test(allocator_type) sharedstructures.delete_pool(POOL_NAME_PREFIX + allocator_type) run_collision_test(allocator_type) # TODO: enable this test again when the python module supports incr # sharedstructures.delete_pool(POOL_NAME_PREFIX + allocator_type) # run_incr_test(allocator_type) sharedstructures.delete_pool(POOL_NAME_PREFIX + allocator_type) run_concurrent_readers_test(allocator_type) print('all tests passed') return 0 finally: for allocator_type in ALLOCATOR_TYPES: sharedstructures.delete_pool(POOL_NAME_PREFIX + allocator_type) if __name__ == '__main__': sys.exit(main())
""" desispec.calibfinder ==================== Reading and selecting calibration data from $DESI_SPECTRO_CALIB using content of image headers """ import re import os import numpy as np import yaml import os.path from desispec.util import parse_int_args, header2night from desiutil.log import get_logger def parse_date_obs(value): ''' converts DATE-OBS keywork to int with for instance DATE-OBS=2016-12-21T18:06:21.268371-05:00 ''' m = re.search(r'(\d+)-(\d+)-(\d+)T', value) Y,M,D=tuple(map(int, m.groups())) dateobs=int(Y*10000+M*100+D) return dateobs _sp2sm = None _sm2sp = None def _load_smsp(): """ Loads $DESI_SPECTRO_CALIB/spec/smsp.txt into global _sp2sm and _sm2sp dicts """ global _sp2sm global _sm2sp tmp_sp2sm = dict() tmp_sm2sp = dict() filename = os.getenv('DESI_SPECTRO_CALIB') + "/spec/smsp.txt" tmp = np.loadtxt(filename, dtype=str) for sp, sm in tmp: p = int(sp[2:]) m = int(sm[2:]) tmp_sp2sm[str(sp)] = str(sm) tmp_sm2sp[str(sm)] = str(sp) tmp_sp2sm[p] = m tmp_sm2sp[m] = p #- Assign to global variables only after successful loading and parsing _sp2sm = tmp_sp2sm _sm2sp = tmp_sm2sp def sp2sm(sp): """ Converts spectrograph sp logical number to sm hardware number Args: sp : spectrograph int 0-9 or str sp[0-9] Returns "smM" if input is str "spP", or int M if input is int P Note: uses $DESI_SPECTRO_CALIB/spec/smsp.txt TODO: add support for different mappings based on night """ global _sp2sm if _sp2sm is None: _load_smsp() return _sp2sm[sp] def sm2sp(sm, night=None): """ Converts spectrograph sm hardware number to sp logical number Args: sm : spectrograph sm number 1-10 or str sm[1-10] Returns "spP" if input is str "smM", or int P if input is int M Note: uses $DESI_SPECTRO_CALIB/spec/smsp.txt TODO: add support for different mappings based on night """ global _sm2sp if _sm2sp is None: _load_smsp() return _sm2sp[sm] def findcalibfile(headers,key,yaml_file=None) : """ read and select calibration data file from $DESI_SPECTRO_CALIB using the keywords found in the headers Args: headers: list of fits headers, or list of dictionnaries key: type of calib file, e.g. 'PSF' or 'FIBERFLAT' Optional: yaml_file: path to a specific yaml file. By default, the code will automatically find the yaml file from the environment variable DESI_SPECTRO_CALIB and the CAMERA keyword in the headers Returns path to calibration file """ cfinder = CalibFinder(headers,yaml_file) if cfinder.haskey(key) : return cfinder.findfile(key) else : return None def badfibers(headers,keys=["BROKENFIBERS","BADCOLUMNFIBERS","LOWTRANSMISSIONFIBERS"],yaml_file=None) : """ find list of bad fibers from $DESI_SPECTRO_CALIB using the keywords found in the headers Args: headers: list of fits headers, or list of dictionnaries Optional: keys: list of keywords, among ["BROKENFIBERS","BADCOLUMNFIBERS","LOWTRANSMISSIONFIBERS"]. Default is all of them. yaml_file: path to a specific yaml file. By default, the code will automatically find the yaml file from the environment variable DESI_SPECTRO_CALIB and the CAMERA keyword in the headers Returns List of bad fibers as a 1D array of intergers """ cfinder = CalibFinder(headers,yaml_file) return cfinder.badfibers(keys) class CalibFinder() : def __init__(self,headers,yaml_file=None) : """ Class to read and select calibration data from $DESI_SPECTRO_CALIB using the keywords found in the headers Args: headers: list of fits headers, or list of dictionnaries Optional: yaml_file: path to a specific yaml file. By default, the code will automatically find the yaml file from the environment variable DESI_SPECTRO_CALIB and the CAMERA keyword in the headers """ log = get_logger() old_version = False # temporary backward compatibility if not "DESI_SPECTRO_CALIB" in os.environ : if "DESI_CCD_CALIBRATION_DATA" in os.environ : log.warning("Using deprecated DESI_CCD_CALIBRATION_DATA env. variable to find calibration data\nPlease switch to DESI_SPECTRO_CALIB a.s.a.p.") self.directory = os.environ["DESI_CCD_CALIBRATION_DATA"] old_version = True else : log.error("Need environment variable DESI_SPECTRO_CALIB") raise KeyError("Need environment variable DESI_SPECTRO_CALIB") else : self.directory = os.environ["DESI_SPECTRO_CALIB"] if len(headers)==0 : log.error("Need at least a header") raise RuntimeError("Need at least a header") header=dict() for other_header in headers : for k in other_header : if k not in header : try : header[k]=other_header[k] except KeyError : # it happens with the current version of fitsio # if the value = 'None'. pass if "CAMERA" not in header : log.error("no 'CAMERA' keyword in header, cannot find calib") log.error("header is:") for k in header : log.error("{} : {}".format(k,header[k])) raise KeyError("no 'CAMERA' keyword in header, cannot find calib") log.debug("header['CAMERA']={}".format(header['CAMERA'])) camera=header["CAMERA"].strip().lower() if "SPECID" in header : log.debug("header['SPECID']={}".format(header['SPECID'])) specid=int(header["SPECID"]) else : specid=None dateobs = header2night(header) detector=header["DETECTOR"].strip() if "CCDCFG" in header : ccdcfg = header["CCDCFG"].strip() else : ccdcfg = None if "CCDTMING" in header : ccdtming = header["CCDTMING"].strip() else : ccdtming = None #if "DOSVER" in header : # dosver = str(header["DOSVER"]).strip() #else : # dosver = None #if "FEEVER" in header : # feever = str(header["FEEVER"]).strip() #else : # feever = None # Support simulated data even if $DESI_SPECTRO_CALIB points to # real data calibrations self.directory = os.path.normpath(self.directory) # strip trailing / if detector == "SIM" and (not self.directory.endswith("sim")) : newdir = os.path.join(self.directory, "sim") if os.path.isdir(newdir) : self.directory = newdir if not os.path.isdir(self.directory): raise IOError("Calibration directory {} not found".format(self.directory)) if dateobs < 20191211 or detector == 'SIM': # old spectro identifiers cameraid = camera spectro=int(camera[-1]) if yaml_file is None : if old_version : yaml_file = os.path.join(self.directory,"ccd_calibration.yaml") else : yaml_file = "{}/spec/sp{}/{}.yaml".format(self.directory,spectro,cameraid) else : if specid is None : log.error("dateobs = {} >= 20191211 but no SPECID keyword in header!".format(dateobs)) raise RuntimeError("dateobs = {} >= 20191211 but no SPECID keyword in header!".format(dateobs)) log.debug("Use spectrograph hardware identifier SMY") cameraid = "sm{}-{}".format(specid,camera[0].lower()) if yaml_file is None : yaml_file = "{}/spec/sm{}/{}.yaml".format(self.directory,specid,cameraid) if not os.path.isfile(yaml_file) : log.error("Cannot read {}".format(yaml_file)) raise IOError("Cannot read {}".format(yaml_file)) log.debug("reading calib data in {}".format(yaml_file)) stream = open(yaml_file, 'r') data = yaml.safe_load(stream) stream.close() if not cameraid in data : log.error("Cannot find data for camera %s in filename %s"%(cameraid,yaml_file)) raise KeyError("Cannot find data for camera %s in filename %s"%(cameraid,yaml_file)) data=data[cameraid] log.debug("Found %d data for camera %s in filename %s"%(len(data),cameraid,yaml_file)) log.debug("Finding matching version ...") log.debug("DATE-OBS=%d"%dateobs) found=False matching_data=None for version in data : log.debug("Checking version %s"%version) datebegin=int(data[version]["DATE-OBS-BEGIN"]) if dateobs < datebegin : log.debug("Skip version %s with DATE-OBS-BEGIN=%d > DATE-OBS=%d"%(version,datebegin,dateobs)) continue if "DATE-OBS-END" in data[version] and data[version]["DATE-OBS-END"].lower() != "none" : dateend=int(data[version]["DATE-OBS-END"]) if dateobs > dateend : log.debug("Skip version %s with DATE-OBS-END=%d < DATE-OBS=%d"%(version,datebegin,dateobs)) continue if detector != data[version]["DETECTOR"].strip() : log.debug("Skip version %s with DETECTOR=%s != %s"%(version,data[version]["DETECTOR"],detector)) continue if "CCDCFG" in data[version] : if ccdcfg is None or ccdcfg != data[version]["CCDCFG"].strip() : log.debug("Skip version %s with CCDCFG=%s != %s "%(version,data[version]["CCDCFG"],ccdcfg)) continue if "CCDTMING" in data[version] : if ccdtming is None or ccdtming != data[version]["CCDTMING"].strip() : log.debug("Skip version %s with CCDTMING=%s != %s "%(version,data[version]["CCDTMING"],ccdtming)) continue #if dosver is not None and "DOSVER" in data[version] and dosver != str(data[version]["DOSVER"]).strip() : # log.debug("Skip version %s with DOSVER=%s != %s "%(version,data[version]["DOSVER"],dosver)) # continue #if feever is not None and "FEEVER" in data[version] and feever != str(data[version]["FEEVER"]).strip() : # log.debug("Skip version %s with FEEVER=%s != %s"%(version,data[version]["FEEVER"],feever)) # continue log.debug("Found data version %s for camera %s in %s"%(version,cameraid,yaml_file)) if found : log.error("But we already has a match. Please fix this ambiguity in %s"%yaml_file) raise KeyError("Duplicate possible calibration data. Please fix this ambiguity in %s"%yaml_file) found=True matching_data=data[version] if not found : log.error("Didn't find matching calibration data in %s"%(yaml_file)) raise KeyError("Didn't find matching calibration data in %s"%(yaml_file)) self.data = matching_data def haskey(self,key) : """ Args: key: keyword, string, like 'GAINA' Returns: yes or no, boolean """ return ( key in self.data ) def value(self,key) : """ Args: key: header keyword, string, like 'GAINA' Returns: data found in yaml file """ return self.data[key] def findfile(self,key) : """ Args: key: header keyword, string, like 'DARK' Returns: path to calibration file """ return os.path.join(self.directory,self.data[key]) def badfibers(self,keys=["BROKENFIBERS","BADCOLUMNFIBERS","LOWTRANSMISSIONFIBERS","BADAMPFIBERS","EXCLUDEFIBERS"]) : """ Args: keys: ptional, list of keywords, among BROKENFIBERS,BADCOLUMNFIBERS,LOWTRANSMISSIONFIBERS,BADAMPFIBERS,EXCLUDEFIBERS. Default is all of them. Returns: List of bad fibers from yaml file as a 1D array of intergers """ log = get_logger() fibers=[] badfiber_keywords=["BROKENFIBERS","BADCOLUMNFIBERS","LOWTRANSMISSIONFIBERS","BADAMPFIBERS","EXCLUDEFIBERS"] for key in keys : if key not in badfiber_keywords : log.error(f"key '{key}' not in the list of valid keys for bad fibers: {validkeys}") continue if self.haskey(key) : val = self.value(key) fibers.append(parse_int_args(val)) if len(fibers)==0 : return np.array([],dtype=int) return np.unique(np.hstack(fibers))
# -*- coding: utf-8 -*- """ Created on Sun Apr 20 17:12:53 2014 author: Josef Perktold """ import numpy as np from numpy.testing import assert_allclose, assert_equal from statsmodels.regression.linear_model import OLS, WLS from statsmodels.sandbox.regression.predstd import wls_prediction_std from statsmodels.regression._prediction import get_prediction def test_predict_se(): # this test doesn't use reference values # checks conistency across options, and compares to direct calculation # generate dataset nsample = 50 x1 = np.linspace(0, 20, nsample) x = np.c_[x1, (x1 - 5)**2, np.ones(nsample)] np.random.seed(0)#9876789) #9876543) beta = [0.5, -0.01, 5.] y_true2 = np.dot(x, beta) w = np.ones(nsample) w[int(nsample * 6. / 10):] = 3 sig = 0.5 y2 = y_true2 + sig * w * np.random.normal(size=nsample) x2 = x[:,[0,2]] # estimate OLS res2 = OLS(y2, x2).fit() #direct calculation covb = res2.cov_params() predvar = res2.mse_resid + (x2 * np.dot(covb, x2.T).T).sum(1) predstd = np.sqrt(predvar) prstd, iv_l, iv_u = wls_prediction_std(res2) np.testing.assert_almost_equal(prstd, predstd, 15) #stats.t.isf(0.05/2., 50 - 2) q = 2.0106347546964458 ci_half = q * predstd np.testing.assert_allclose(iv_u, res2.fittedvalues + ci_half, rtol=1e-12) np.testing.assert_allclose(iv_l, res2.fittedvalues - ci_half, rtol=1e-12) prstd, iv_l, iv_u = wls_prediction_std(res2, x2[:3,:]) np.testing.assert_equal(prstd, prstd[:3]) np.testing.assert_allclose(iv_u, res2.fittedvalues[:3] + ci_half[:3], rtol=1e-12) np.testing.assert_allclose(iv_l, res2.fittedvalues[:3] - ci_half[:3], rtol=1e-12) # check WLS res3 = WLS(y2, x2, 1. / w).fit() #direct calculation covb = res3.cov_params() predvar = res3.mse_resid * w + (x2 * np.dot(covb, x2.T).T).sum(1) predstd = np.sqrt(predvar) prstd, iv_l, iv_u = wls_prediction_std(res3) np.testing.assert_almost_equal(prstd, predstd, 15) #stats.t.isf(0.05/2., 50 - 2) q = 2.0106347546964458 ci_half = q * predstd np.testing.assert_allclose(iv_u, res3.fittedvalues + ci_half, rtol=1e-12) np.testing.assert_allclose(iv_l, res3.fittedvalues - ci_half, rtol=1e-12) # testing shapes of exog prstd, iv_l, iv_u = wls_prediction_std(res3, x2[-1:,:], weights=3.) np.testing.assert_equal(prstd, prstd[-1]) prstd, iv_l, iv_u = wls_prediction_std(res3, x2[-1,:], weights=3.) np.testing.assert_equal(prstd, prstd[-1]) prstd, iv_l, iv_u = wls_prediction_std(res3, x2[-2:,:], weights=3.) np.testing.assert_equal(prstd, prstd[-2:]) prstd, iv_l, iv_u = wls_prediction_std(res3, x2[-2:,:], weights=[3, 3]) np.testing.assert_equal(prstd, prstd[-2:]) prstd, iv_l, iv_u = wls_prediction_std(res3, x2[:3,:]) np.testing.assert_equal(prstd, prstd[:3]) np.testing.assert_allclose(iv_u, res3.fittedvalues[:3] + ci_half[:3], rtol=1e-12) np.testing.assert_allclose(iv_l, res3.fittedvalues[:3] - ci_half[:3], rtol=1e-12) #use wrong size for exog #prstd, iv_l, iv_u = wls_prediction_std(res3, x2[-1,0], weights=3.) np.testing.assert_raises(ValueError, wls_prediction_std, res3, x2[-1,0], weights=3.) # check some weight values sew1 = wls_prediction_std(res3, x2[-3:,:])[0]**2 for wv in np.linspace(0.5, 3, 5): sew = wls_prediction_std(res3, x2[-3:,:], weights=1. / wv)[0]**2 np.testing.assert_allclose(sew, sew1 + res3.scale * (wv - 1)) class TestWLSPrediction(object): @classmethod def setup_class(cls): # from example wls.py nsample = 50 x = np.linspace(0, 20, nsample) X = np.column_stack((x, (x - 5)**2)) from statsmodels.tools.tools import add_constant X = add_constant(X) beta = [5., 0.5, -0.01] sig = 0.5 w = np.ones(nsample) w[int(nsample * 6. / 10):] = 3 y_true = np.dot(X, beta) e = np.random.normal(size=nsample) y = y_true + sig * w * e X = X[:,[0,1]] # ### WLS knowing the true variance ratio of heteroscedasticity mod_wls = WLS(y, X, weights=1./w) cls.res_wls = mod_wls.fit() def test_ci(self): res_wls = self.res_wls prstd, iv_l, iv_u = wls_prediction_std(res_wls) pred_res = get_prediction(res_wls) ci = pred_res.conf_int(obs=True) assert_allclose(pred_res.se_obs, prstd, rtol=1e-13) assert_allclose(ci, np.column_stack((iv_l, iv_u)), rtol=1e-13) sf = pred_res.summary_frame() col_names = ['mean', 'mean_se', 'mean_ci_lower', 'mean_ci_upper', 'obs_ci_lower', 'obs_ci_upper'] assert_equal(sf.columns.tolist(), col_names) pred_res2 = res_wls.get_prediction() ci2 = pred_res2.conf_int(obs=True) assert_allclose(pred_res2.se_obs, prstd, rtol=1e-13) assert_allclose(ci2, np.column_stack((iv_l, iv_u)), rtol=1e-13) sf2 = pred_res2.summary_frame() assert_equal(sf2.columns.tolist(), col_names) def test_glm(self): # prelimnimary, getting started with basic test for GLM.get_prediction from statsmodels.genmod.generalized_linear_model import GLM res_wls = self.res_wls mod_wls = res_wls.model y, X, wi = mod_wls.endog, mod_wls.exog, mod_wls.weights w_sqrt = np.sqrt(wi) # notation wi is weights, `w` is var mod_glm = GLM(y * w_sqrt, X * w_sqrt[:,None]) # compare using t distribution res_glm = mod_glm.fit(use_t=True) pred_glm = res_glm.get_prediction() sf_glm = pred_glm.summary_frame() pred_res_wls = res_wls.get_prediction() sf_wls = pred_res_wls.summary_frame() n_compare = 30 # in glm with predict wendog assert_allclose(sf_glm.values[:n_compare], sf_wls.values[:n_compare, :4]) # compare using normal distribution res_glm = mod_glm.fit() # default use_t=False pred_glm = res_glm.get_prediction() sf_glm = pred_glm.summary_frame() res_wls = mod_wls.fit(use_t=False) pred_res_wls = res_wls.get_prediction() sf_wls = pred_res_wls.summary_frame() assert_allclose(sf_glm.values[:n_compare], sf_wls.values[:n_compare, :4]) # function for parameter transformation # should be separate test method from statsmodels.genmod._prediction import params_transform_univariate rates = params_transform_univariate(res_glm.params, res_glm.cov_params()) rates2 = np.column_stack((np.exp(res_glm.params), res_glm.bse * np.exp(res_glm.params), np.exp(res_glm.conf_int()))) assert_allclose(rates.summary_frame().values, rates2, rtol=1e-13) from statsmodels.genmod.families import links # with identity transform pt = params_transform_univariate(res_glm.params, res_glm.cov_params(), link=links.identity()) assert_allclose(pt.tvalues, res_glm.tvalues, rtol=1e-13) assert_allclose(pt.se_mean, res_glm.bse, rtol=1e-13) ptt = pt.t_test() assert_allclose(ptt[0], res_glm.tvalues, rtol=1e-13) assert_allclose(ptt[1], res_glm.pvalues, rtol=1e-13) # prediction with exog and no weights does not error res_glm = mod_glm.fit() pred_glm = res_glm.get_prediction(X)
#!/usr/bin/env python #-*- coding: utf-8 -*- import os import matplotlib import matplotlib.pyplot as plt import numpy as np def pred_visualization(fname, arrays, picks, img_shape, tile_spacing=(0,0), scale_rows_to_unit_interval=True, output_pixel_vals=True): """Used for visualization of predictions Args: fname: filename for saving the image arrays: list of arrays containing the frames, first array is assumed to be ground truth (all of shape Nxnframesxframesize**2) picks: list containing indices of cases that should be used img_shape: shape of a frame tile_spacing: spacing between the tiles scale_rows_to_unit_interval: see tile_raster_images output_pixel_vals: see tile_raster_images """ ncases = len(picks) narrays = len(arrays) if narrays > 1: horizon = arrays[1].shape[1] horizon_gt = arrays[0].shape[1] n_presteps = horizon_gt - horizon if n_presteps > 0: visdata = np.ones((ncases, horizon_gt * narrays, np.prod(img_shape))) visdata[:,:horizon_gt] = arrays[0][picks] for i in range(1, narrays): visdata[:, i*horizon_gt:(i+1)*horizon_gt] = \ np.hstack(( (np.ones((ncases, n_presteps, np.prod(img_shape)))), arrays[i][picks])) else: visdata = np.hstack([arrays[i][picks] for i in range(narrays)]) else: horizon = arrays[0].shape[1] horizon_gt = horizon visdata = np.hstack([arrays[i][picks] for i in range(narrays)]) visdata = visdata.reshape(ncases*narrays*horizon_gt,-1) im = tile_raster_images(visdata, img_shape, (ncases*narrays, horizon_gt), tile_spacing, scale_rows_to_unit_interval, output_pixel_vals) for i in range(len(picks)*len(arrays)): #insert white patches for n_presteps for j in range(horizon_gt-horizon): if i % len(arrays) != 0: im[i*img_shape[0] + i*tile_spacing[0]:(i+1)*img_shape[0] + i*tile_spacing[0], j*img_shape[1] + j*tile_spacing[1]:(j+1)*img_shape[1] + j*tile_spacing[1]] = 255 #np.insert(im, [i * len(arrays) * img_shape[0] + i * (len(arrays)-1) * tile_spacing[0] for i in range(len(picks))], 0) h,w = im.shape fig = plt.figure(frameon=False) #fig.set_size_inches(1,h/np.float(w)) fig.set_size_inches(w/24.,h/24.) ax = plt.Axes(fig, [0.,0.,1.,1.]) ax.set_axis_off() fig.add_axes(ax) ax.imshow(im, aspect='normal', interpolation='nearest') fig.savefig(fname, dpi=24) return im def scale_to_unit_interval(ndar, eps=1e-8): """ Scales all values in the ndarray ndar to be between 0 and 1 """ ndar = ndar.copy() ndar -= ndar.min() ndar *= 1.0 / (ndar.max()+eps) return ndar def tile_raster_images(X, img_shape, tile_shape, tile_spacing = (0, 0), scale_rows_to_unit_interval = True, output_pixel_vals = True): """ Transform an array with one flattened image per row, into an array in which images are reshaped and layed out like tiles on a floor. This function is useful for visualizing datasets whose rows are images, and also columns of matrices for transforming those rows (such as the first layer of a neural net). :type X: a 2-D ndarray or a tuple of 4 channels, elements of which can be 2-D ndarrays or None; :param X: a 2-D array in which every row is a flattened image. :type img_shape: tuple; (height, width) :param img_shape: the original shape of each image :type tile_shape: tuple; (rows, cols) :param tile_shape: the number of images to tile (rows, cols) :param output_pixel_vals: if output should be pixel values (i.e. int8 values) or floats :param scale_rows_to_unit_interval: if the values need to be scaled before being plotted to [0, 1] or not :returns: array suitable for viewing as an image. (See:`PIL.Image.fromarray`.) :rtype: a 2-d array with same dtype as X. """ assert len(img_shape) == 2 assert len(tile_shape) == 2 assert len(tile_spacing) == 2 # The expression below can be re-written in a more C style as # follows : # # out_shape = [0, 0] # out_shape[0] = (img_shape[0]+tile_spacing[0])*tile_shape[0] - # tile_spacing[0] # out_shape[1] = (img_shape[1]+tile_spacing[1])*tile_shape[1] - # tile_spacing[1] out_shape = [(ishp + tsp) * tshp - tsp for ishp, tshp, tsp in zip(img_shape, tile_shape, tile_spacing)] if isinstance(X, tuple): assert len(X) == 4 # Create an output numpy ndarray to store the image if output_pixel_vals: out_array = np.zeros((out_shape[0], out_shape[1], 4), dtype='uint8') else: out_array = np.zeros((out_shape[0], out_shape[1], 4), dtype=X.dtype) #colors default to 0, alpha defaults to 1 (opaque) if output_pixel_vals: channel_defaults = [0, 0, 0, 255] else: channel_defaults = [0., 0., 0., 1.] for i in xrange(4): if X[i] is None: # if channel is None, fill it with zeros of the correct # dtype dt = out_array.dtype if output_pixel_vals: dt = 'uint8' out_array[:, :, i] = np.zeros(out_shape, dtype=dt) + channel_defaults[i] else: # use a recurrent call to compute the channel and store it # in the output out_array[:, :, i] = tile_raster_images( X[i], img_shape, tile_shape, tile_spacing, scale_rows_to_unit_interval, output_pixel_vals) return out_array else: # if we are dealing with only one channel H, W = img_shape Hs, Ws = tile_spacing # generate a matrix to store the output dt = X.dtype if output_pixel_vals: dt = 'uint8' out_array = np.zeros(out_shape, dtype=dt) for tile_row in xrange(tile_shape[0]): for tile_col in xrange(tile_shape[1]): if tile_row * tile_shape[1] + tile_col < X.shape[0]: if scale_rows_to_unit_interval: # if we should scale values to be between 0 and 1 # do this by calling the `scale_to_unit_interval` # function this_img = scale_to_unit_interval( X[tile_row * tile_shape[1] + tile_col].reshape(img_shape)) else: this_img = X[tile_row * tile_shape[1] + tile_col].reshape(img_shape) # add the slice to the corresponding position in the # output array c = 1 if output_pixel_vals: c = 255 out_array[ tile_row * (H+Hs):tile_row*(H+Hs)+H, tile_col * (W+Ws):tile_col*(W+Ws)+W ] \ = this_img * c return out_array def dispims_white(invwhitening, M, height, width, border=0, bordercolor=0.0, layout=None, **kwargs): """ Display a whole stack (colunmwise) of vectorized matrices. Useful eg. to display the weights of a neural network layer. """ numimages = M.shape[1] M = np.dot(invwhitening, M) if layout is None: n0 = int(np.ceil(np.sqrt(numimages))) n1 = int(np.ceil(np.sqrt(numimages))) else: n0, n1 = layout im = bordercolor * np.ones(((height+border)*n0+border, (width+border)*n1+border), dtype='<f8') for i in range(n0): for j in range(n1): if i*n1+j < M.shape[1]: im[i*(height+border)+border:(i+1)*(height+border)+border, j*(width+border)+border :(j+1)*(width+border)+border] =\ np.vstack(( np.hstack(( np.reshape(M[:, i*n1+j], (height, width)), bordercolor*np.ones((height, border), dtype=float))), bordercolor*np.ones((border, width+border), dtype=float))) plt.imshow(im, cmap=matplotlib.cm.gray, interpolation='nearest', **kwargs) def CreateMovie(filename, plotter, numberOfFrames, fps): for i in range(numberOfFrames): plotter(i) fname = '_tmp%05d.png' % i plt.savefig(fname) plt.clf() #os.system("rm %s.mp4" % filename) #os.system("ffmpeg -r "+str(fps)+" -b 1800 -i _tmp%05d.png "+filename+".mp4") os.system("convert -delay 20 -loop 0 _tmp*.png " +filename+".gif") os.system("rm _tmp*.png") def dispimsmovie_patchwise(filename, M, inv, patchsize, fps=5, *args, **kwargs): numframes = M.shape[0] / inv.shape[1] n = M.shape[0]/numframes def plotter(i): M_ = M[i*n:n*(i+1)] M_ = np.dot(inv,M_) width = int(np.ceil(np.sqrt(M.shape[1]))) image = tile_raster_images( M_.T, img_shape=(patchsize,patchsize), tile_shape=(10,10), tile_spacing = (1,1), scale_rows_to_unit_interval = True, output_pixel_vals = True) plt.imshow(image,cmap=matplotlib.cm.gray,interpolation='nearest') plt.axis('off') CreateMovie(filename, plotter, numframes, fps) def dispimsmovie(filename, W, filters, nframes, fps=5): patchsize = np.uint8(np.sqrt(W.shape[0])) def plotter(i): dispims_white(W, filters[i*W.shape[1]:(i+1)*W.shape[1], :], patchsize, patchsize, 1, bordercolor=filters.mean(), vmin=filters.min(), vmax=filters.max()*0.8) plt.axis('off') CreateMovie(filename, plotter, nframes, fps) def visualizefacenet(fname, imgs, patches_left, patches_right, true_label, predicted_label): """Builds a plot of facenet with attention per RNN step and classification result """ nsamples = imgs.shape[0] nsteps = patches_left.shape[1] is_correct = true_label == predicted_label w = nsteps + 2 + (nsteps % 2) h = nsamples * 2 plt.clf() plt.gray() for i in range(nsamples): plt.subplot(nsamples, w//2, i*w//2 + 1) plt.imshow(imgs[i]) msg = ('Prediction: ' + predicted_label[i] + ' TrueLabel: ' + true_label[i]) if is_correct[i]: plt.title(msg,color='green') else: plt.title(msg,color='red') plt.axis('off') for j in range(nsteps): plt.subplot(h, w, i*2*w + 2 + 1 + j) plt.imshow(patches_left[i, j]) plt.axis('off') plt.subplot(h, w, i*2*w + 2 + 1 + j + w) plt.imshow(patches_right[i, j]) plt.axis('off') plt.show() plt.savefig(fname) if __name__ == '__main__': from scipy.misc import lena imgs = lena()[None, ...].repeat(3, axis=0) patches_left = lena()[None, None, :256].repeat(3, axis=0).repeat(5, axis=1) patches_right = lena()[None, None, 256:].repeat(3, axis=0).repeat(5, axis=1) true_label = np.array(['angry', 'angry', 'sad']) predicted_label = np.array(['sad'] * 3) visualizefacenet('lena.pdf', imgs, patches_left, patches_right, true_label, predicted_label) # vim: set ts=4 sw=4 sts=4 expandtab:
import datetime import time from typing import List from unittest import mock from django.test import override_settings from django.utils.timezone import now as timezone_now from confirmation.models import one_click_unsubscribe_link from zerver.lib.actions import do_create_user from zerver.lib.digest import ( _enqueue_emails_for_realm, bulk_handle_digest_email, bulk_write_realm_audit_logs, enqueue_emails, gather_new_streams, handle_digest_email, streams_recently_modified_for_user, ) from zerver.lib.message import get_last_message_id from zerver.lib.streams import create_stream_if_needed from zerver.lib.test_classes import ZulipTestCase from zerver.lib.test_helpers import cache_tries_captured, queries_captured from zerver.models import ( Message, Realm, RealmAuditLog, Stream, UserActivityInterval, UserProfile, flush_per_request_caches, get_client, get_realm, get_stream, ) class TestDigestEmailMessages(ZulipTestCase): @mock.patch('zerver.lib.digest.enough_traffic') @mock.patch('zerver.lib.digest.send_future_email') def test_multiple_stream_senders(self, mock_send_future_email: mock.MagicMock, mock_enough_traffic: mock.MagicMock) -> None: othello = self.example_user('othello') self.subscribe(othello, 'Verona') one_day_ago = timezone_now() - datetime.timedelta(days=1) Message.objects.all().update(date_sent=one_day_ago) one_hour_ago = timezone_now() - datetime.timedelta(seconds=3600) cutoff = time.mktime(one_hour_ago.timetuple()) senders = ['hamlet', 'cordelia', 'iago', 'prospero', 'ZOE'] self.simulate_stream_conversation('Verona', senders) flush_per_request_caches() # When this test is run in isolation, one additional query is run which # is equivalent to # ContentType.objects.get(app_label='zerver', model='userprofile') # This code is run when we call `confirmation.models.create_confirmation_link`. # To trigger this, we call the one_click_unsubscribe_link function below. one_click_unsubscribe_link(othello, 'digest') with queries_captured() as queries: handle_digest_email(othello.id, cutoff) self.assert_length(queries, 10) self.assertEqual(mock_send_future_email.call_count, 1) kwargs = mock_send_future_email.call_args[1] self.assertEqual(kwargs['to_user_ids'], [othello.id]) hot_convo = kwargs['context']['hot_conversations'][0] expected_participants = { self.example_user(sender).full_name for sender in senders } self.assertEqual(set(hot_convo['participants']), expected_participants) self.assertEqual(hot_convo['count'], 5 - 2) # 5 messages, but 2 shown teaser_messages = hot_convo['first_few_messages'][0]['senders'] self.assertIn('some content', teaser_messages[0]['content'][0]['plain']) self.assertIn(teaser_messages[0]['sender'], expected_participants) @mock.patch('zerver.lib.digest.enough_traffic') @mock.patch('zerver.lib.digest.send_future_email') def test_guest_user_multiple_stream_sender(self, mock_send_future_email: mock.MagicMock, mock_enough_traffic: mock.MagicMock) -> None: othello = self.example_user('othello') hamlet = self.example_user('hamlet') cordelia = self.example_user('cordelia') polonius = self.example_user('polonius') create_stream_if_needed(cordelia.realm, 'web_public_stream', is_web_public=True) self.subscribe(othello, 'web_public_stream') self.subscribe(hamlet, 'web_public_stream') self.subscribe(cordelia, 'web_public_stream') self.subscribe(polonius, 'web_public_stream') one_day_ago = timezone_now() - datetime.timedelta(days=1) Message.objects.all().update(date_sent=one_day_ago) one_hour_ago = timezone_now() - datetime.timedelta(seconds=3600) cutoff = time.mktime(one_hour_ago.timetuple()) senders = ['hamlet', 'cordelia', 'othello', 'desdemona'] self.simulate_stream_conversation('web_public_stream', senders) flush_per_request_caches() # When this test is run in isolation, one additional query is run which # is equivalent to # ContentType.objects.get(app_label='zerver', model='userprofile') # This code is run when we call `confirmation.models.create_confirmation_link`. # To trigger this, we call the one_click_unsubscribe_link function below. one_click_unsubscribe_link(polonius, 'digest') with queries_captured() as queries: handle_digest_email(polonius.id, cutoff) self.assert_length(queries, 10) self.assertEqual(mock_send_future_email.call_count, 1) kwargs = mock_send_future_email.call_args[1] self.assertEqual(kwargs['to_user_ids'], [polonius.id]) new_stream_names = kwargs['context']['new_streams']['plain'] self.assertTrue('web_public_stream' in new_stream_names) def test_soft_deactivated_user_multiple_stream_senders(self) -> None: one_day_ago = timezone_now() - datetime.timedelta(days=1) Message.objects.all().update(date_sent=one_day_ago) digest_users = [ self.example_user('othello'), self.example_user('aaron'), self.example_user('desdemona'), self.example_user('polonius'), ] digest_users.sort(key = lambda user: user.id) for digest_user in digest_users: for stream in ['Verona', 'Scotland', 'Denmark']: self.subscribe(digest_user, stream) RealmAuditLog.objects.all().delete() for digest_user in digest_users: digest_user.long_term_idle = True digest_user.save(update_fields=['long_term_idle']) # Send messages to a stream and unsubscribe - subscribe from that stream senders = ['hamlet', 'cordelia', 'iago', 'prospero', 'ZOE'] self.simulate_stream_conversation('Verona', senders) for digest_user in digest_users: self.unsubscribe(digest_user, 'Verona') self.subscribe(digest_user, 'Verona') # Send messages to other streams self.simulate_stream_conversation('Scotland', senders) self.simulate_stream_conversation('Denmark', senders) one_hour_ago = timezone_now() - datetime.timedelta(seconds=3600) cutoff = time.mktime(one_hour_ago.timetuple()) flush_per_request_caches() # When this test is run in isolation, one additional query is run which # is equivalent to # ContentType.objects.get(app_label='zerver', model='userprofile') # This code is run when we call `confirmation.models.create_confirmation_link`. # To trigger this, we call the one_click_unsubscribe_link function below. one_click_unsubscribe_link(digest_users[0], 'digest') with mock.patch('zerver.lib.digest.send_future_email') as mock_send_future_email: digest_user_ids = [user.id for user in digest_users] with queries_captured() as queries: with cache_tries_captured() as cache_tries: bulk_handle_digest_email(digest_user_ids, cutoff) self.assert_length(queries, 37) self.assert_length(cache_tries, 0) self.assertEqual(mock_send_future_email.call_count, len(digest_users)) for i, digest_user in enumerate(digest_users): kwargs = mock_send_future_email.call_args_list[i][1] self.assertEqual(kwargs['to_user_ids'], [digest_user.id]) hot_conversations = kwargs['context']['hot_conversations'] self.assertEqual(2, len(hot_conversations), [digest_user.id]) hot_convo = hot_conversations[0] expected_participants = { self.example_user(sender).full_name for sender in senders } self.assertEqual(set(hot_convo['participants']), expected_participants) self.assertEqual(hot_convo['count'], 5 - 2) # 5 messages, but 2 shown teaser_messages = hot_convo['first_few_messages'][0]['senders'] self.assertIn('some content', teaser_messages[0]['content'][0]['plain']) self.assertIn(teaser_messages[0]['sender'], expected_participants) last_message_id = get_last_message_id() for digest_user in digest_users: log_rows = RealmAuditLog.objects.filter( modified_user_id=digest_user.id, event_type=RealmAuditLog.USER_DIGEST_EMAIL_CREATED, ) (log,) = log_rows self.assertEqual(log.event_last_message_id, last_message_id) def test_streams_recently_modified_for_user(self) -> None: othello = self.example_user('othello') cordelia = self.example_user('cordelia') for stream in ['Verona', 'Scotland', 'Denmark']: self.subscribe(othello, stream) self.subscribe(cordelia, stream) realm = othello.realm denmark = get_stream('Denmark', realm) verona = get_stream('Verona', realm) two_hours_ago = timezone_now() - datetime.timedelta(hours=2) one_hour_ago = timezone_now() - datetime.timedelta(hours=1) # Delete all RealmAuditLogs to start with a clean slate. RealmAuditLog.objects.all().delete() # Unsubscribe and subscribe Othello from a stream self.unsubscribe(othello, 'Denmark') self.subscribe(othello, 'Denmark') self.assertEqual( streams_recently_modified_for_user(othello, one_hour_ago), {denmark.id} ) # Backdate all our logs (so that Denmark will no longer # appear like a recently modified stream for Othello). RealmAuditLog.objects.all().update(event_time=two_hours_ago) # Now Denmark no longer appears recent to Othello. self.assertEqual( streams_recently_modified_for_user(othello, one_hour_ago), set() ) # Unsubscribe and subscribe from a stream self.unsubscribe(othello, 'Verona') self.subscribe(othello, 'Verona') # Now, Verona, but not Denmark, appears recent. self.assertEqual( streams_recently_modified_for_user(othello, one_hour_ago), {verona.id}, ) # make sure we don't mix up Othello and Cordelia self.unsubscribe(cordelia, 'Denmark') self.subscribe(cordelia, 'Denmark') self.assertEqual( streams_recently_modified_for_user(cordelia, one_hour_ago), {denmark.id} ) def active_human_users(self, realm: Realm) -> List[UserProfile]: users = list(UserProfile.objects.filter( realm=realm, is_active=True, is_bot=False, enable_digest_emails=True, )) assert len(users) >= 5 return users def test_twelve_hour_exemption(self) -> None: RealmAuditLog.objects.all().delete() realm = get_realm('zulip') cutoff = timezone_now() - datetime.timedelta(days=5) with mock.patch('zerver.lib.digest.queue_digest_recipient') as queue_mock: _enqueue_emails_for_realm(realm, cutoff) users = self.active_human_users(realm) self.assertEqual(queue_mock.call_count, len(users)) # Simulate that we have sent digests for all our users. bulk_write_realm_audit_logs(users) # Now if we run again, we won't get any users, since they will have # recent RealmAuditLog rows. with mock.patch('zerver.lib.digest.queue_digest_recipient') as queue_mock: _enqueue_emails_for_realm(realm, cutoff) self.assertEqual(queue_mock.call_count, 0) @override_settings(SEND_DIGEST_EMAILS=True) def test_inactive_users_queued_for_digest(self) -> None: UserActivityInterval.objects.all().delete() RealmAuditLog.objects.all().delete() # Turn on realm digest emails for all realms Realm.objects.update(digest_emails_enabled=True) cutoff = timezone_now() - datetime.timedelta(days=5) realm = get_realm("zulip") users = self.active_human_users(realm) # Check that all users without an a UserActivityInterval entry are considered # inactive users and get enqueued. with mock.patch('zerver.lib.digest.queue_digest_recipient') as queue_mock: _enqueue_emails_for_realm(realm, cutoff) self.assertEqual(queue_mock.call_count, len(users)) for user in users: last_visit = timezone_now() - datetime.timedelta(days=1) UserActivityInterval.objects.create( start=last_visit, end=last_visit, user_profile=user, ) # Now we expect no users, due to recent activity. with mock.patch('zerver.lib.digest.queue_digest_recipient') as queue_mock: _enqueue_emails_for_realm(realm, cutoff) self.assertEqual(queue_mock.call_count, 0) # Now, backdate all our users activity. last_visit = timezone_now() - datetime.timedelta(days=7) UserActivityInterval.objects.all().update(start=last_visit, end=last_visit) with mock.patch('zerver.lib.digest.queue_digest_recipient') as queue_mock: _enqueue_emails_for_realm(realm, cutoff) self.assertEqual(queue_mock.call_count, len(users)) def tuesday(self) -> datetime.datetime: return datetime.datetime(year=2016, month=1, day=5, tzinfo=datetime.timezone.utc) @override_settings(SEND_DIGEST_EMAILS=False) def test_disabled(self) -> None: RealmAuditLog.objects.all().delete() tuesday = self.tuesday() cutoff = tuesday - datetime.timedelta(days=5) with mock.patch("zerver.lib.digest.timezone_now", return_value=tuesday): with mock.patch("zerver.lib.digest.queue_digest_recipient") as queue_mock: enqueue_emails(cutoff) queue_mock.assert_not_called() @override_settings(SEND_DIGEST_EMAILS=True) def test_only_enqueue_on_valid_day(self) -> None: RealmAuditLog.objects.all().delete() not_tuesday = datetime.datetime(year=2016, month=1, day=6, tzinfo=datetime.timezone.utc) cutoff = not_tuesday - datetime.timedelta(days=5) with mock.patch("zerver.lib.digest.timezone_now", return_value=not_tuesday): with mock.patch("zerver.lib.digest.queue_digest_recipient") as queue_mock: enqueue_emails(cutoff) queue_mock.assert_not_called() @override_settings(SEND_DIGEST_EMAILS=True) def test_no_email_digest_for_bots(self) -> None: RealmAuditLog.objects.all().delete() cutoff = timezone_now() - datetime.timedelta(days=5) realm = get_realm('zulip') realm.digest_emails_enabled = True realm.save() bot = do_create_user( '[email protected]', 'password', realm, 'some_bot', bot_type=UserProfile.DEFAULT_BOT, ) # Check that bots are not sent emails with mock.patch('zerver.lib.digest.queue_digest_recipient') as queue_mock: _enqueue_emails_for_realm(realm, cutoff) assert queue_mock.call_count >= 5 for arg in queue_mock.call_args_list: user_id = arg[0][0] self.assertNotEqual(user_id, bot.id) @override_settings(SEND_DIGEST_EMAILS=True) def test_new_stream_link(self) -> None: Stream.objects.all().delete() cutoff = timezone_now() - datetime.timedelta(days=5) cordelia = self.example_user('cordelia') stream = create_stream_if_needed(cordelia.realm, 'New stream')[0] stream.date_created = timezone_now() stream.save() stream_count, stream_info = gather_new_streams(cordelia, cutoff) self.assertEqual(stream_count, 1) expected_html = f"<a href='http://zulip.testserver/#narrow/stream/{stream.id}-New-stream'>New stream</a>" self.assertEqual(stream_info['html'][0], expected_html) # Make the stream appear to be older. stream.date_created = timezone_now() - datetime.timedelta(days=7) stream.save() stream_count, stream_info = gather_new_streams(cordelia, cutoff) self.assertEqual(stream_count, 0) self.assertEqual(stream_info['html'], []) def simulate_stream_conversation(self, stream: str, senders: List[str]) -> List[int]: client = 'website' # this makes `sent_by_human` return True sending_client = get_client(client) message_ids = [] # List[int] for sender_name in senders: sender = self.example_user(sender_name) content = f'some content for {stream} from {sender_name}' message_id = self.send_stream_message(sender, stream, content) message_ids.append(message_id) Message.objects.filter(id__in=message_ids).update(sending_client=sending_client) return message_ids class TestDigestContentInBrowser(ZulipTestCase): def test_get_digest_content_in_browser(self) -> None: self.login('hamlet') result = self.client_get("/digest/") self.assert_in_success_response(["Click here to log in to Zulip and catch up."], result)
# Copyright 2015 Cloudbase Solutions SRL # 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. """ Unit tests for the Hyper-V Driver. """ import platform import mock from nova.tests.unit import fake_instance from nova.tests.unit.virt.hyperv import test_base from nova.virt import driver as base_driver from nova.virt.hyperv import driver from nova.virt.hyperv import vmutils class HyperVDriverTestCase(test_base.HyperVBaseTestCase): FAKE_WIN_2008R2_VERSION = '6.0.0' @mock.patch.object(driver.HyperVDriver, '_check_minimum_windows_version') def setUp(self, mock_check_minimum_windows_version): super(HyperVDriverTestCase, self).setUp() self.context = 'context' self.driver = driver.HyperVDriver(mock.sentinel.virtapi) self.driver._hostops = mock.MagicMock() self.driver._volumeops = mock.MagicMock() self.driver._vmops = mock.MagicMock() self.driver._snapshotops = mock.MagicMock() self.driver._livemigrationops = mock.MagicMock() self.driver._migrationops = mock.MagicMock() self.driver._rdpconsoleops = mock.MagicMock() @mock.patch.object(driver.hostutils.HostUtils, 'check_min_windows_version') def test_check_minimum_windows_version(self, mock_check_min_win_version): mock_check_min_win_version.return_value = False self.assertRaises(vmutils.HyperVException, self.driver._check_minimum_windows_version) def test_public_api_signatures(self): self.assertPublicAPISignatures(base_driver.ComputeDriver(None), self.driver) @mock.patch.object(driver.eventhandler, 'InstanceEventHandler') def test_init_host(self, mock_InstanceEventHandler): self.driver.init_host(mock.sentinel.host) self.driver._vmops.restart_vm_log_writers.assert_called_once_with() mock_InstanceEventHandler.assert_called_once_with( state_change_callback=self.driver.emit_event, running_state_callback=self.driver._vmops.log_vm_serial_output) fake_event_handler = mock_InstanceEventHandler.return_value fake_event_handler.start_listener.assert_called_once_with() def test_list_instance_uuids(self): self.driver.list_instance_uuids() self.driver._vmops.list_instance_uuids.assert_called_once_with() def test_list_instances(self): self.driver.list_instances() self.driver._vmops.list_instances.assert_called_once_with() @mock.patch.object(driver.objects.ImageMeta, 'from_dict') def test_spawn(self, mock_meta_from_dict): self.driver.spawn( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.image_meta, mock.sentinel.injected_files, mock.sentinel.admin_password, mock.sentinel.network_info, mock.sentinel.block_device_info) self.driver._vmops.spawn.assert_called_once_with( mock.sentinel.context, mock.sentinel.instance, mock_meta_from_dict.return_value, mock.sentinel.injected_files, mock.sentinel.admin_password, mock.sentinel.network_info, mock.sentinel.block_device_info) def test_reboot(self): self.driver.reboot( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.network_info, mock.sentinel.reboot_type, mock.sentinel.block_device_info, mock.sentinel.bad_vol_callback) self.driver._vmops.reboot.assert_called_once_with( mock.sentinel.instance, mock.sentinel.network_info, mock.sentinel.reboot_type) def test_destroy(self): self.driver.destroy( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.network_info, mock.sentinel.block_device_info, mock.sentinel.destroy_disks, mock.sentinel.migrate_data) self.driver._vmops.destroy.assert_called_once_with( mock.sentinel.instance, mock.sentinel.network_info, mock.sentinel.block_device_info, mock.sentinel.destroy_disks) def test_get_info(self): self.driver.get_info(mock.sentinel.instance) self.driver._vmops.get_info.assert_called_once_with( mock.sentinel.instance) def test_attach_volume(self): mock_instance = fake_instance.fake_instance_obj(self.context) self.driver.attach_volume( mock.sentinel.context, mock.sentinel.connection_info, mock_instance, mock.sentinel.mountpoint, mock.sentinel.disk_bus, mock.sentinel.device_type, mock.sentinel.encryption) self.driver._volumeops.attach_volume.assert_called_once_with( mock.sentinel.connection_info, mock_instance.name) def test_detach_volume(self): mock_instance = fake_instance.fake_instance_obj(self.context) self.driver.detach_volume( mock.sentinel.connection_info, mock_instance, mock.sentinel.mountpoint, mock.sentinel.encryption) self.driver._volumeops.detach_volume.assert_called_once_with( mock.sentinel.connection_info, mock_instance.name) def test_get_volume_connector(self): self.driver.get_volume_connector(mock.sentinel.instance) self.driver._volumeops.get_volume_connector.assert_called_once_with( mock.sentinel.instance) def test_get_available_resource(self): self.driver.get_available_resource(mock.sentinel.nodename) self.driver._hostops.get_available_resource.assert_called_once_with() def test_get_available_nodes(self): response = self.driver.get_available_nodes(mock.sentinel.refresh) self.assertEqual([platform.node()], response) def test_host_power_action(self): self.driver.host_power_action(mock.sentinel.action) self.driver._hostops.host_power_action.assert_called_once_with( mock.sentinel.action) def test_snapshot(self): self.driver.snapshot( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.image_id, mock.sentinel.update_task_state) self.driver._snapshotops.snapshot.assert_called_once_with( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.image_id, mock.sentinel.update_task_state) def test_pause(self): self.driver.pause(mock.sentinel.instance) self.driver._vmops.pause.assert_called_once_with( mock.sentinel.instance) def test_unpause(self): self.driver.unpause(mock.sentinel.instance) self.driver._vmops.unpause.assert_called_once_with( mock.sentinel.instance) def test_suspend(self): self.driver.suspend(mock.sentinel.context, mock.sentinel.instance) self.driver._vmops.suspend.assert_called_once_with( mock.sentinel.instance) def test_resume(self): self.driver.resume( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.network_info, mock.sentinel.block_device_info) self.driver._vmops.resume.assert_called_once_with( mock.sentinel.instance) def test_power_off(self): self.driver.power_off( mock.sentinel.instance, mock.sentinel.timeout, mock.sentinel.retry_interval) self.driver._vmops.power_off.assert_called_once_with( mock.sentinel.instance, mock.sentinel.timeout, mock.sentinel.retry_interval) def test_power_on(self): self.driver.power_on( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.network_info, mock.sentinel.block_device_info) self.driver._vmops.power_on.assert_called_once_with( mock.sentinel.instance, mock.sentinel.block_device_info) def test_resume_state_on_host_boot(self): self.driver.resume_state_on_host_boot( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.network_info, mock.sentinel.block_device_info) self.driver._vmops.resume_state_on_host_boot.assert_called_once_with( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.network_info, mock.sentinel.block_device_info) def test_live_migration(self): self.driver.live_migration( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.dest, mock.sentinel.post_method, mock.sentinel.recover_method, mock.sentinel.block_migration, mock.sentinel.migrate_data) self.driver._livemigrationops.live_migration.assert_called_once_with( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.dest, mock.sentinel.post_method, mock.sentinel.recover_method, mock.sentinel.block_migration, mock.sentinel.migrate_data) @mock.patch.object(driver.HyperVDriver, 'destroy') def test_rollback_live_migration_at_destination(self, mock_destroy): self.driver.rollback_live_migration_at_destination( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.network_info, mock.sentinel.block_device_info, mock.sentinel.destroy_disks, mock.sentinel.migrate_data) mock_destroy.assert_called_once_with( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.network_info, mock.sentinel.block_device_info) def test_pre_live_migration(self): self.driver.pre_live_migration( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.block_device_info, mock.sentinel.network_info, mock.sentinel.disk_info, mock.sentinel.migrate_data) pre_live_migration = self.driver._livemigrationops.pre_live_migration pre_live_migration.assert_called_once_with( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.block_device_info, mock.sentinel.network_info) def test_post_live_migration(self): self.driver.post_live_migration( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.block_device_info, mock.sentinel.migrate_data) post_live_migration = self.driver._livemigrationops.post_live_migration post_live_migration.assert_called_once_with( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.block_device_info) def test_post_live_migration_at_destination(self): self.driver.post_live_migration_at_destination( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.network_info, mock.sentinel.block_migration, mock.sentinel.block_device_info) mtd = self.driver._livemigrationops.post_live_migration_at_destination mtd.assert_called_once_with( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.network_info, mock.sentinel.block_migration) def test_check_can_live_migrate_destination(self): self.driver.check_can_live_migrate_destination( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.src_compute_info, mock.sentinel.dst_compute_info, mock.sentinel.block_migration, mock.sentinel.disk_over_commit) mtd = self.driver._livemigrationops.check_can_live_migrate_destination mtd.assert_called_once_with( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.src_compute_info, mock.sentinel.dst_compute_info, mock.sentinel.block_migration, mock.sentinel.disk_over_commit) def test_check_can_live_migrate_destination_cleanup(self): self.driver.check_can_live_migrate_destination_cleanup( mock.sentinel.context, mock.sentinel.dest_check_data) _livemigrops = self.driver._livemigrationops method = _livemigrops.check_can_live_migrate_destination_cleanup method.assert_called_once_with( mock.sentinel.context, mock.sentinel.dest_check_data) def test_check_can_live_migrate_source(self): self.driver.check_can_live_migrate_source( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.dest_check_data, mock.sentinel.block_device_info) method = self.driver._livemigrationops.check_can_live_migrate_source method.assert_called_once_with( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.dest_check_data) def test_plug_vifs(self): self.assertRaises(NotImplementedError, self.driver.plug_vifs, mock.sentinel.instance, mock.sentinel.network_info) def test_unplug_vifs(self): self.assertRaises(NotImplementedError, self.driver.unplug_vifs, mock.sentinel.instance, mock.sentinel.network_info) def test_refresh_instance_security_rules(self): self.assertRaises(NotImplementedError, self.driver.refresh_instance_security_rules, instance=mock.sentinel.instance) def test_migrate_disk_and_power_off(self): self.driver.migrate_disk_and_power_off( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.dest, mock.sentinel.flavor, mock.sentinel.network_info, mock.sentinel.block_device_info, mock.sentinel.timeout, mock.sentinel.retry_interval) migr_power_off = self.driver._migrationops.migrate_disk_and_power_off migr_power_off.assert_called_once_with( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.dest, mock.sentinel.flavor, mock.sentinel.network_info, mock.sentinel.block_device_info, mock.sentinel.timeout, mock.sentinel.retry_interval) def test_confirm_migration(self): self.driver.confirm_migration( mock.sentinel.migration, mock.sentinel.instance, mock.sentinel.network_info) self.driver._migrationops.confirm_migration.assert_called_once_with( mock.sentinel.migration, mock.sentinel.instance, mock.sentinel.network_info) def test_finish_revert_migration(self): self.driver.finish_revert_migration( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.network_info, mock.sentinel.block_device_info, mock.sentinel.power_on) finish_revert_migr = self.driver._migrationops.finish_revert_migration finish_revert_migr.assert_called_once_with( mock.sentinel.context, mock.sentinel.instance, mock.sentinel.network_info, mock.sentinel.block_device_info, mock.sentinel.power_on) @mock.patch.object(driver.objects.ImageMeta, 'from_dict') def test_finish_migration(self, mock_meta_from_dict): self.driver.finish_migration( mock.sentinel.context, mock.sentinel.migration, mock.sentinel.instance, mock.sentinel.disk_info, mock.sentinel.network_info, mock.sentinel.image_meta, mock.sentinel.resize_instance, mock.sentinel.block_device_info, mock.sentinel.power_on) self.driver._migrationops.finish_migration.assert_called_once_with( mock.sentinel.context, mock.sentinel.migration, mock.sentinel.instance, mock.sentinel.disk_info, mock.sentinel.network_info, mock_meta_from_dict.return_value, mock.sentinel.resize_instance, mock.sentinel.block_device_info, mock.sentinel.power_on) def test_get_host_ip_addr(self): self.driver.get_host_ip_addr() self.driver._hostops.get_host_ip_addr.assert_called_once_with() def test_get_host_uptime(self): self.driver.get_host_uptime() self.driver._hostops.get_host_uptime.assert_called_once_with() def test_get_rdp_console(self): self.driver.get_rdp_console( mock.sentinel.context, mock.sentinel.instance) self.driver._rdpconsoleops.get_rdp_console.assert_called_once_with( mock.sentinel.instance) def test_get_console_output(self): self.driver.get_console_output( mock.sentinel.context, mock.sentinel.instance) self.driver._vmops.get_console_output.assert_called_once_with( mock.sentinel.instance)
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. """ P1 tests for Account """ #Import Local Modules from marvin.cloudstackTestCase import cloudstackTestCase #from marvin.cloudstackAPI import * from marvin.lib.utils import (random_gen, cleanup_resources) from marvin.lib.base import (Domain, Account, ServiceOffering, VirtualMachine, Network, User, NATRule, Template, PublicIPAddress) from marvin.lib.common import (get_domain, get_zone, get_template, list_accounts, list_virtual_machines, list_service_offering, list_templates, list_users, get_builtin_template_info, wait_for_cleanup) from nose.plugins.attrib import attr from marvin.cloudstackException import CloudstackAPIException import time class Services: """Test Account Services """ def __init__(self): self.services = { "domain": { "name": "Domain", }, "account": { "email": "[email protected]", "firstname": "Test", "lastname": "User", "username": "test", # Random characters are appended for unique # username "password": "fr3sca", }, "user": { "email": "[email protected]", "firstname": "User", "lastname": "User", "username": "User", # Random characters are appended for unique # username "password": "fr3sca", }, "service_offering": { "name": "Micro Instance", "displaytext": "Micro Instance", "cpunumber": 1, "cpuspeed": 100, # in MHz "memory": 96, 'storagetype': 'local' # In MBs }, "virtual_machine": { "displayname": "Test VM", "username": "root", "password": "password", "ssh_port": 22, "hypervisor": 'XenServer', # Hypervisor type should be same as # hypervisor type of cluster "privateport": 22, "publicport": 22, "protocol": 'TCP', }, "template": { "displaytext": "Public Template", "name": "Public template", "ostype": 'CentOS 5.6 (64-bit)', "hypervisor": 'XenServer', "format": 'VHD', "url": "http://178.237.34.126:8099/template/tiny_linux.vhd", "passwordenabled": False }, "natrule": { "publicport": 22, "privateport": 22, "protocol": 'TCP', }, "service_offering_id": "86d6c534-2f57-11e4-977d-020043e40006", "template_id": "803881d6-2f57-11e4-977d-020043e40006", "ostype": 'CentOS 5.6 (64-bit)', # Cent OS 5.3 (64 bit) "sleep": 60, "timeout": 10, } class TestAccounts(cloudstackTestCase): @classmethod def setUpClass(cls): cls.testClient = super(TestAccounts, cls).getClsTestClient() cls.api_client = cls.testClient.getApiClient() cls.services = Services().services cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests()) cls.services['mode'] = cls.zone.networktype cls.template = get_template( cls.api_client, cls.zone.id, cls.services["ostype"] ) cls.services["virtual_machine"]["zoneid"] = cls.zone.id cls.services["virtual_machine"]["template"] = cls.template.id cls.service_offering = ServiceOffering.create( cls.api_client, cls.services["service_offering"] ) cls._cleanup = [cls.service_offering] #cls.service_offering = ServiceOffering.create(cls.api_client, cls.services["service_offering"]) #cls._cleanup = [cls.service_offering] #cls._cleanup = [] return @classmethod def tearDownClass(cls): try: #Cleanup resources used cleanup_resources(cls.api_client, cls._cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return def setUp(self): self.apiclient = self.testClient.getApiClient() self.dbclient = self.testClient.getDbConnection() self.cleanup = [] return def tearDown(self): try: #Clean up, terminate the created accounts, domains etc cleanup_resources(self.apiclient, self.cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return @attr(tags=["advanced", "basic", "eip", "advancedns", "sg", "selfservice"]) def test_01_create_account(self): """Test Create Account and user for that account """ # Validate the following # 1. Create an Account. Verify the account is created. # 2. Create User associated with that account. Verify the created user # Create an account account = Account.create( self.apiclient, self.services["account"] ) self.debug("Created account: %s" % account.name) self._cleanup.append(account) list_accounts_response = list_accounts( self.apiclient, id=account.id ) self.assertEqual( isinstance(list_accounts_response, list), True, "Check list accounts for valid data" ) self.assertNotEqual( len(list_accounts_response), 0, "Check List Account response" ) account_response = list_accounts_response[0] self.assertEqual( account.accounttype, account_response.accounttype, "Check Account Type of Created account" ) self.assertEqual( account.name, account_response.name, "Check Account Name of Created account" ) # Create an User associated with account user = User.create( self.apiclient, self.services["user"], account=account.name, domainid=account.domainid ) self.debug("Created user: %s" % user.id) list_users_response = list_users( self.apiclient, id=user.id ) self.assertEqual( isinstance(list_users_response, list), True, "Check list users for valid data" ) self.assertNotEqual( len(list_users_response), 0, "Check List User response" ) user_response = list_users_response[0] self.assertEqual( user.username, user_response.username, "Check username of Created user" ) self.assertEqual( user.state, user_response.state, "Check state of created user" ) return class TestAddVmToSubDomain(cloudstackTestCase): @classmethod def setUpClass(cls): cls.testClient = super(TestAddVmToSubDomain, cls).getClsTestClient() cls.api_client = cls.testClient.getApiClient() cls.services = Services().services cls.domain = get_domain(cls.api_client) cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests()) cls.services['mode'] = cls.zone.networktype cls.sub_domain = Domain.create( cls.api_client, cls.services["domain"], parentdomainid=cls.domain.id ) # Create account for doamin_1 cls.account_1 = Account.create( cls.api_client, cls.services["account"], admin=True, domainid=cls.domain.id ) # Create an account for domain_2 cls.account_2 = Account.create( cls.api_client, cls.services["account"], admin=True, domainid=cls.sub_domain.id ) cls.service_offering = ServiceOffering.create( cls.api_client, cls.services["service_offering"], domainid=cls.domain.id ) cls._cleanup = [ cls.account_2, cls.account_1, cls.sub_domain, cls.service_offering ] cls.template = get_template( cls.api_client, cls.zone.id, cls.services["ostype"] ) cls.services["virtual_machine"]["zoneid"] = cls.zone.id cls.vm_1 = VirtualMachine.create( cls.api_client, cls.services["virtual_machine"], templateid=cls.template.id, accountid=cls.account_1.name, domainid=cls.account_1.domainid, serviceofferingid=cls.service_offering.id ) print "offering ID", cls.service_offering.id, "template ID", cls.template.id cls.vm_2 = VirtualMachine.create( cls.api_client, cls.services["virtual_machine"], templateid=cls.template.id, accountid=cls.account_2.name, domainid=cls.account_2.domainid, serviceofferingid=cls.service_offering.id ) return @classmethod def tearDownClass(cls): try: #Clean up, terminate the created resources cleanup_resources(cls.api_client, cls._cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return def setUp(self): self.apiclient = self.testClient.getApiClient() self.dbclient = self.testClient.getDbConnection() self.cleanup = [] return def tearDown(self): try: #Clean up, terminate the created resources cleanup_resources(self.apiclient, self.cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return @attr(tags=["advanced", "basic", "eip", "advancedns", "sg", "selfservice"]) def test_01_add_vm_to_subdomain(self): """ Test Sub domain allowed to launch VM when a Domain level zone is created""" # Validate the following # 1. Verify VM created by Account_1 is in Running state # 2. Verify VM created by Account_2 is in Running state vm_response = list_virtual_machines( self.apiclient, id=self.vm_1.id ) self.assertEqual( isinstance(vm_response, list), True, "Check List VM for a valid response" ) self.assertNotEqual( len(vm_response), 0, "Check List Template response" ) for vm in vm_response: self.debug("VM ID: %s and state: %s" % (vm.id, vm.state)) self.assertEqual( vm.state, 'Running', "Check State of Virtual machine" ) vm_response = list_virtual_machines( self.apiclient, id=self.vm_2.id ) self.assertNotEqual( len(vm_response), 0, "Check List Template response" ) for vm in vm_response: self.debug("VM ID: %s and state: %s" % (vm.id, vm.state)) self.assertEqual( vm.state, 'Running', "Check State of Virtual machine" ) return class TestUserDetails(cloudstackTestCase): @classmethod def setUpClass(cls): cls.testClient = super(TestUserDetails, cls).getClsTestClient() cls.api_client = cls.testClient.getApiClient() cls.services = Services().services cls.domain = get_domain(cls.api_client) cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests()) cls.services['mode'] = cls.zone.networktype cls._cleanup = [] return @classmethod def tearDownClass(cls): try: #Cleanup resources used cleanup_resources(cls.api_client, cls._cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return def setUp(self): self.apiclient = self.testClient.getApiClient() self.dbclient = self.testClient.getDbConnection() self.cleanup = [] return def tearDown(self): try: #Clean up, terminate the created network offerings cleanup_resources(self.apiclient, self.cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return @attr(tags=[ "role", "accounts", "simulator", "advanced", "advancedns", "basic", "eip", "sg" ]) def test_updateUserDetails(self): """Test user update API """ # Steps for test scenario # 1. create a user account # 2. update the user details (firstname, lastname, user) with # updateUser API # 3. listUsers in the account # 4. delete the account # Validate the following # 1. listAccounts should show account created successfully # 2. updateUser API should return valid response # 3. user should be updated with new details self.debug("Creating an user account..") self.account = Account.create( self.apiclient, self.services["account"], domainid=self.domain.id ) self._cleanup.append(self.account) # Fetching the user details of account self.debug( "Fetching user details for account: %s" % self.account.name) users = User.list( self.apiclient, account=self.account.name, domainid=self.account.domainid ) self.assertEqual( isinstance(users, list), True, "List users should return a valid list for account" ) user_1 = users[0] self.debug("Updating the details of user: %s" % user_1.name) firstname = random_gen() lastname = random_gen() self.debug("New firstname: %s, lastname: %s" % (firstname, lastname)) User.update( self.apiclient, user_1.id, firstname=firstname, lastname=lastname ) # Fetching the user details of account self.debug( "Fetching user details for user: %s" % user_1.name) users = User.list( self.apiclient, id=user_1.id, listall=True ) self.assertEqual( isinstance(users, list), True, "List users should return a valid list for account" ) user_1 = users[0] self.assertEqual( user_1.firstname, firstname, "User's first name should be updated with new one" ) self.assertEqual( user_1.lastname, lastname, "User's last name should be updated with new one" ) return @attr(tags=[ "role", "accounts", "simulator", "advanced", "advancedns", "basic", "eip", "sg" ]) def test_updateAdminDetails(self): """Test update admin details """ # Steps for test scenario # 1. create a admin account # 2. update the user details (firstname, lastname, user) with # updateUser API # 3. listUsers in the account # 4. delete the account # Validate the following # 1. listAccounts should show account created successfully # 2. updateUser API should return valid response # 3. user should be updated with new details self.debug("Creating a ROOT admin account") self.account = Account.create( self.apiclient, self.services["account"], admin=True, ) self._cleanup.append(self.account) # Fetching the user details of account self.debug( "Fetching user details for account: %s" % self.account.name) users = User.list( self.apiclient, account=self.account.name, domainid=self.account.domainid ) self.assertEqual( isinstance(users, list), True, "List users should return a valid list for account" ) user_1 = users[0] self.debug("Updating the details of user: %s" % user_1.name) firstname = random_gen() lastname = random_gen() self.debug("New firstname: %s, lastname: %s" % (firstname, lastname)) User.update( self.apiclient, user_1.id, firstname=firstname, lastname=lastname ) # Fetching the user details of account self.debug( "Fetching user details for user: %s" % user_1.name) users = User.list( self.apiclient, id=user_1.id, listall=True ) self.assertEqual( isinstance(users, list), True, "List users should return a valid list for account" ) user_1 = users[0] self.assertEqual( user_1.firstname, firstname, "User's first name should be updated with new one" ) self.assertEqual( user_1.lastname, lastname, "User's last name should be updated with new one" ) return @attr(tags=[ "role", "accounts", "simulator", "advanced", "advancedns", "basic", "eip", "sg" ]) def test_updateDomainAdminDetails(self): """Test update domain admin details """ # Steps for test scenario # 2. update the user details (firstname, lastname, user) with # updateUser API # 3. listUsers in the account # 4. delete the account # Validate the following # 1. listAccounts should show account created successfully # 2. updateUser API should return valid response # 3. user should be updated with new details self.debug("Creating a domain admin account") self.account = Account.create( self.apiclient, self.services["account"], admin=True, domainid=self.domain.id ) self._cleanup.append(self.account) # Fetching the user details of account self.debug( "Fetching user details for account: %s" % self.account.name) users = User.list( self.apiclient, account=self.account.name, domainid=self.account.domainid ) self.assertEqual( isinstance(users, list), True, "List users should return a valid list for account" ) user_1 = users[0] self.debug("Updating the details of user: %s" % user_1.name) firstname = random_gen() lastname = random_gen() self.debug("New firstname: %s, lastname: %s" % (firstname, lastname)) User.update( self.apiclient, user_1.id, firstname=firstname, lastname=lastname ) # Fetching the user details of account self.debug( "Fetching user details for user: %s" % user_1.name) users = User.list( self.apiclient, id=user_1.id, listall=True ) self.assertEqual( isinstance(users, list), True, "List users should return a valid list for account" ) user_1 = users[0] self.assertEqual( user_1.firstname, firstname, "User's first name should be updated with new one" ) self.assertEqual( user_1.lastname, lastname, "User's last name should be updated with new one" ) return class TestUserLogin(cloudstackTestCase): @classmethod def setUpClass(cls): cls.testClient = super(TestUserLogin, cls).getClsTestClient() cls.api_client = cls.testClient.getApiClient() cls.services = Services().services cls.domain = get_domain(cls.api_client) cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests()) cls.services['mode'] = cls.zone.networktype cls._cleanup = [] return @classmethod def tearDownClass(cls): try: #Cleanup resources used cleanup_resources(cls.api_client, cls._cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return def setUp(self): self.apiclient = self.testClient.getApiClient() self.dbclient = self.testClient.getDbConnection() self.cleanup = [] return def tearDown(self): try: #Clean up, terminate the created network offerings cleanup_resources(self.apiclient, self.cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return @attr(tags=["login", "accounts", "simulator", "advanced", "advancedns", "basic", "eip", "sg"]) def test_LoginApiUuidResponse(self): """Test if Login API does not return UUID's """ # Steps for test scenario # 1. create a user account # 2. login to the user account with given credentials (loginCmd) # 3. delete the user account # Validate the following # 1. listAccounts should return account created # 2. loginResponse should have UUID only is response. Assert by # checking database id is not same as response id # Login also succeeds with non NULL sessionId in response self.debug("Creating an user account..") self.account = Account.create( self.apiclient, self.services["account"], domainid=self.domain.id ) self._cleanup.append(self.account) self.debug("Logging into the cloudstack with login API") respose = User.login( self.apiclient, username=self.account.name, password=self.services["account"]["password"] ) self.debug("Login API response: %s" % respose) self.assertNotEqual( respose.sessionkey, None, "Login to the CloudStack should be successful" + "response shall have non Null key" ) return @attr(tags=["login", "accounts", "simulator", "advanced", "advancedns", "basic", "eip", "sg"]) def test_LoginApiDomain(self): """Test login API with domain """ # Steps for test scenario # 1. create a domain # 2. create user in the domain # 3. login to the user account above using UUID domain/user # 4. delete the user account # Validate the following # 1. listDomains returns created domain # 2. listAccounts returns created user # 3. loginResponse should have UUID only in responses # Login also succeeds with non NULL sessionId in response self.debug("Creating a domain for login with API domain test") domain = Domain.create( self.apiclient, self.services["domain"], parentdomainid=self.domain.id ) self.debug("Domain: %s is created succesfully." % domain.name) self.debug( "Checking if the created domain is listed in list domains API") domains = Domain.list(self.apiclient, id=domain.id, listall=True) self.assertEqual( isinstance(domains, list), True, "List domains shall return a valid response" ) self.debug("Creating an user account in domain: %s" % domain.name) self.account = Account.create( self.apiclient, self.services["account"], domainid=domain.id ) self._cleanup.append(self.account) accounts = Account.list( self.apiclient, name=self.account.name, domainid=self.account.domainid, listall=True ) self.assertEqual( isinstance(accounts, list), True, "List accounts should return a valid response" ) self.debug("Logging into the cloudstack with login API") respose = User.login( self.apiclient, username=self.account.name, password=self.services["account"]["password"], domainid=domain.id) self.debug("Login API response: %s" % respose) self.assertNotEqual( respose.sessionkey, None, "Login to the CloudStack should be successful" + "response shall have non Null key" ) return class TestDomainForceRemove(cloudstackTestCase): @classmethod def setUpClass(cls): cls.testClient = super(TestDomainForceRemove, cls).getClsTestClient() cls.api_client = cls.testClient.getApiClient() cls.services = Services().services cls.domain = get_domain(cls.api_client) cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests()) cls.services['mode'] = cls.zone.networktype cls.template = get_template( cls.api_client, cls.zone.id, cls.services["ostype"] ) cls.services["virtual_machine"]["zoneid"] = cls.zone.id cls._cleanup = [] return @classmethod def tearDownClass(cls): try: #Clean up, terminate the created resources cleanup_resources(cls.api_client, cls._cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return def setUp(self): self.apiclient = self.testClient.getApiClient() self.dbclient = self.testClient.getDbConnection() self.cleanup = [] return def tearDown(self): try: #Clean up, terminate the created resources cleanup_resources(self.apiclient, self.cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return @attr(tags=["domains", "advanced", "advancedns", "simulator", "selfservice"]) def test_forceDeleteDomain(self): """ Test delete domain with force option""" # Steps for validations # 1. create a domain DOM # 2. create 2 users under this domain # 3. deploy 1 VM into each of these user accounts # 4. create PF / FW rules for port 22 on these VMs for their # respective accounts # 5. delete the domain with force=true option # Validate the following # 1. listDomains should list the created domain # 2. listAccounts should list the created accounts # 3. listvirtualmachines should show the Running VMs # 4. PF and FW rules should be shown in listFirewallRules # 5. domain should delete successfully and above three list calls # should show all the resources now deleted. listRouters should # not return any routers in the deleted accounts/domains self.debug("Creating a domain for login with API domain test") domain = Domain.create( self.apiclient, self.services["domain"], parentdomainid=self.domain.id ) self.debug("Domain is created succesfully.") self.debug( "Checking if the created domain is listed in list domains API") domains = Domain.list(self.apiclient, id=domain.id, listall=True) self.assertEqual( isinstance(domains, list), True, "List domains shall return a valid response" ) self.debug("Creating 2 user accounts in domain: %s" % domain.name) self.account_1 = Account.create( self.apiclient, self.services["account"], domainid=domain.id ) self.account_2 = Account.create( self.apiclient, self.services["account"], domainid=domain.id ) try: self.debug("Creating a tiny service offering for VM deployment") self.service_offering = ServiceOffering.create( self.apiclient, self.services["service_offering"], domainid=self.domain.id ) self.debug("Deploying virtual machine in account 1: %s" % self.account_1.name) vm_1 = VirtualMachine.create( self.apiclient, self.services["virtual_machine"], templateid=self.template.id, accountid=self.account_1.name, domainid=self.account_1.domainid, serviceofferingid=self.service_offering.id ) self.debug("Deploying virtual machine in account 2: %s" % self.account_2.name) VirtualMachine.create( self.apiclient, self.services["virtual_machine"], templateid=self.template.id, accountid=self.account_2.name, domainid=self.account_2.domainid, serviceofferingid=self.service_offering.id ) networks = Network.list( self.apiclient, account=self.account_1.name, domainid=self.account_1.domainid, listall=True ) self.assertEqual( isinstance(networks, list), True, "List networks should return a valid response" ) network_1 = networks[0] self.debug("Default network in account 1: %s is %s" % ( self.account_1.name, network_1.name)) src_nat_list = PublicIPAddress.list( self.apiclient, associatednetworkid=network_1.id, account=self.account_1.name, domainid=self.account_1.domainid, listall=True, issourcenat=True, ) self.assertEqual( isinstance(src_nat_list, list), True, "List Public IP should return a valid source NAT" ) self.assertNotEqual( len(src_nat_list), 0, "Length of response from listPublicIp should not be 0" ) src_nat = src_nat_list[0] self.debug( "Trying to create a port forwarding rule in source NAT: %s" % src_nat.ipaddress) #Create NAT rule nat_rule = NATRule.create( self.apiclient, vm_1, self.services["natrule"], ipaddressid=src_nat.id ) self.debug("Created PF rule on source NAT: %s" % src_nat.ipaddress) nat_rules = NATRule.list(self.apiclient, id=nat_rule.id) self.assertEqual( isinstance(nat_rules, list), True, "List NAT should return a valid port forwarding rules" ) self.assertNotEqual( len(nat_rules), 0, "Length of response from listLbRules should not be 0" ) except Exception as e: self._cleanup.append(self.account_1) self._cleanup.append(self.account_2) self.fail(e) self.debug("Deleting domain with force option") try: domain.delete(self.apiclient, cleanup=True) except Exception as e: self.debug("Waiting for account.cleanup.interval" + " to cleanup any remaining resouces") # Sleep 3*account.gc to ensure that all resources are deleted wait_for_cleanup(self.apiclient, ["account.cleanup.interval"]*3) with self.assertRaises(CloudstackAPIException): Domain.list( self.apiclient, id=domain.id, listall=True ) self.debug("Checking if the resources in domain are deleted") with self.assertRaises(CloudstackAPIException): Account.list( self.apiclient, name=self.account_1.name, domainid=self.account_1.domainid, listall=True ) return @attr(tags=["domains", "advanced", "advancedns", "simulator", "selfservice"]) def test_DeleteDomain(self): """ Test delete domain without force option""" # Steps for validations # 1. create a domain DOM # 2. create 2 users under this domain # 3. deploy 1 VM into each of these user accounts # 4. create PF / FW rules for port 22 on these VMs for their # respective accounts # 5. delete the domain with force=false option # Validate the following # 1. listDomains should list the created domain # 2. listAccounts should list the created accounts # 3. listvirtualmachines should show the Running VMs # 4. PF and FW rules should be shown in listFirewallRules # 5. domain deletion should fail saying there are resources under use self.debug("Creating a domain for login with API domain test") domain = Domain.create( self.apiclient, self.services["domain"], parentdomainid=self.domain.id ) self.debug("Domain: %s is created successfully." % domain.name) self.debug( "Checking if the created domain is listed in list domains API") domains = Domain.list(self.apiclient, id=domain.id, listall=True) self.assertEqual( isinstance(domains, list), True, "List domains shall return a valid response" ) self.debug("Creating 2 user accounts in domain: %s" % domain.name) self.account_1 = Account.create( self.apiclient, self.services["account"], domainid=domain.id ) self._cleanup.append(self.account_1) self.account_2 = Account.create( self.apiclient, self.services["account"], domainid=domain.id ) self._cleanup.append(self.account_2) self.debug("Creating a tiny service offering for VM deployment") self.service_offering = ServiceOffering.create( self.apiclient, self.services["service_offering"], domainid=self.domain.id ) self._cleanup.append(self.service_offering) self.debug("Deploying virtual machine in account 1: %s" % self.account_1.name) vm_1 = VirtualMachine.create( self.apiclient, self.services["virtual_machine"], templateid=self.template.id, accountid=self.account_1.name, domainid=self.account_1.domainid, serviceofferingid=self.service_offering.id ) self.debug("Deploying virtual machine in account 2: %s" % self.account_2.name) VirtualMachine.create( self.apiclient, self.services["virtual_machine"], templateid=self.template.id, accountid=self.account_2.name, domainid=self.account_2.domainid, serviceofferingid=self.service_offering.id ) networks = Network.list( self.apiclient, account=self.account_1.name, domainid=self.account_1.domainid, listall=True ) self.assertEqual( isinstance(networks, list), True, "List networks should return a valid response" ) network_1 = networks[0] self.debug("Default network in account 1: %s is %s" % ( self.account_1.name, network_1.name)) src_nat_list = PublicIPAddress.list( self.apiclient, associatednetworkid=network_1.id, account=self.account_1.name, domainid=self.account_1.domainid, listall=True, issourcenat=True, ) self.assertEqual( isinstance(src_nat_list, list), True, "List Public IP should return a valid source NAT" ) self.assertNotEqual( len(src_nat_list), 0, "Length of response from listPublicIp should not be 0" ) src_nat = src_nat_list[0] self.debug( "Trying to create a port forwarding rule in source NAT: %s" % src_nat.ipaddress) #Create NAT rule nat_rule = NATRule.create( self.apiclient, vm_1, self.services["natrule"], ipaddressid=src_nat.id ) self.debug("Created PF rule on source NAT: %s" % src_nat.ipaddress) nat_rules = NATRule.list(self.apiclient, id=nat_rule.id) self.assertEqual( isinstance(nat_rules, list), True, "List NAT should return a valid port forwarding rules" ) self.assertNotEqual( len(nat_rules), 0, "Length of response from listLbRules should not be 0" ) self.debug("Deleting domain without force option") with self.assertRaises(Exception): domain.delete(self.apiclient, cleanup=False) return
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 time from collections import OrderedDict from typing import Optional, Set import pendulum from sqlalchemy.orm.session import Session, make_transient from tabulate import tabulate from airflow import models from airflow.exceptions import ( AirflowException, BackfillUnfinished, DagConcurrencyLimitReached, NoAvailablePoolSlot, PoolNotFound, TaskConcurrencyLimitReached, ) from airflow.executors import executor_constants from airflow.jobs.base_job import BaseJob from airflow.models import DAG, DagPickle from airflow.models.dagrun import DagRun from airflow.models.taskinstance import TaskInstance, TaskInstanceKey from airflow.ti_deps.dep_context import DepContext from airflow.ti_deps.dependencies_deps import BACKFILL_QUEUED_DEPS from airflow.timetables.base import DagRunInfo from airflow.utils import helpers, timezone from airflow.utils.configuration import conf as airflow_conf, tmp_configuration_copy from airflow.utils.session import provide_session from airflow.utils.state import DagRunState, State, TaskInstanceState from airflow.utils.types import DagRunType class BackfillJob(BaseJob): """ A backfill job consists of a dag or subdag for a specific time range. It triggers a set of task instance runs, in the right order and lasts for as long as it takes for the set of task instance to be completed. """ STATES_COUNT_AS_RUNNING = (State.RUNNING, State.QUEUED) __mapper_args__ = {'polymorphic_identity': 'BackfillJob'} class _DagRunTaskStatus: """ Internal status of the backfill job. This class is intended to be instantiated only within a BackfillJob instance and will track the execution of tasks, e.g. running, skipped, succeeded, failed, etc. Information about the dag runs related to the backfill job are also being tracked in this structure, .e.g finished runs, etc. Any other status related information related to the execution of dag runs / tasks can be included in this structure since it makes it easier to pass it around. :param to_run: Tasks to run in the backfill :type to_run: dict[tuple[TaskInstanceKey], airflow.models.TaskInstance] :param running: Maps running task instance key to task instance object :type running: dict[tuple[TaskInstanceKey], airflow.models.TaskInstance] :param skipped: Tasks that have been skipped :type skipped: set[tuple[TaskInstanceKey]] :param succeeded: Tasks that have succeeded so far :type succeeded: set[tuple[TaskInstanceKey]] :param failed: Tasks that have failed :type failed: set[tuple[TaskInstanceKey]] :param not_ready: Tasks not ready for execution :type not_ready: set[tuple[TaskInstanceKey]] :param deadlocked: Deadlocked tasks :type deadlocked: set[airflow.models.TaskInstance] :param active_runs: Active dag runs at a certain point in time :type active_runs: list[DagRun] :param executed_dag_run_dates: Datetime objects for the executed dag runs :type executed_dag_run_dates: set[datetime.datetime] :param finished_runs: Number of finished runs so far :type finished_runs: int :param total_runs: Number of total dag runs able to run :type total_runs: int """ # TODO(edgarRd): AIRFLOW-1444: Add consistency check on counts def __init__( self, to_run=None, running=None, skipped=None, succeeded=None, failed=None, not_ready=None, deadlocked=None, active_runs=None, executed_dag_run_dates=None, finished_runs=0, total_runs=0, ): self.to_run = to_run or OrderedDict() self.running = running or {} self.skipped = skipped or set() self.succeeded = succeeded or set() self.failed = failed or set() self.not_ready = not_ready or set() self.deadlocked = deadlocked or set() self.active_runs = active_runs or [] self.executed_dag_run_dates = executed_dag_run_dates or set() self.finished_runs = finished_runs self.total_runs = total_runs def __init__( self, dag, start_date=None, end_date=None, mark_success=False, donot_pickle=False, ignore_first_depends_on_past=False, ignore_task_deps=False, pool=None, delay_on_limit_secs=1.0, verbose=False, conf=None, rerun_failed_tasks=False, run_backwards=False, run_at_least_once=False, *args, **kwargs, ): """ :param dag: DAG object. :type dag: airflow.models.DAG :param start_date: start date for the backfill date range. :type start_date: datetime.datetime :param end_date: end date for the backfill date range. :type end_date: datetime.datetime :param mark_success: flag whether to mark the task auto success. :type mark_success: bool :param donot_pickle: whether pickle :type donot_pickle: bool :param ignore_first_depends_on_past: whether to ignore depend on past :type ignore_first_depends_on_past: bool :param ignore_task_deps: whether to ignore the task dependency :type ignore_task_deps: bool :param pool: pool to backfill :type pool: str :param delay_on_limit_secs: :param verbose: :type verbose: flag to whether display verbose message to backfill console :param conf: a dictionary which user could pass k-v pairs for backfill :type conf: dictionary :param rerun_failed_tasks: flag to whether to auto rerun the failed task in backfill :type rerun_failed_tasks: bool :param run_backwards: Whether to process the dates from most to least recent :type run_backwards bool :param run_at_least_once: If true, always run the DAG at least once even if no logical run exists within the time range. :type: bool :param args: :param kwargs: """ self.dag = dag self.dag_id = dag.dag_id self.bf_start_date = start_date self.bf_end_date = end_date self.mark_success = mark_success self.donot_pickle = donot_pickle self.ignore_first_depends_on_past = ignore_first_depends_on_past self.ignore_task_deps = ignore_task_deps self.pool = pool self.delay_on_limit_secs = delay_on_limit_secs self.verbose = verbose self.conf = conf self.rerun_failed_tasks = rerun_failed_tasks self.run_backwards = run_backwards self.run_at_least_once = run_at_least_once super().__init__(*args, **kwargs) @provide_session def _update_counters(self, ti_status, session=None): """ Updates the counters per state of the tasks that were running. Can re-add to tasks to run in case required. :param ti_status: the internal status of the backfill job tasks :type ti_status: BackfillJob._DagRunTaskStatus """ tis_to_be_scheduled = [] refreshed_tis = [] TI = TaskInstance filter_for_tis = TI.filter_for_tis(list(ti_status.running.values())) if filter_for_tis is not None: refreshed_tis = session.query(TI).filter(filter_for_tis).all() for ti in refreshed_tis: # Here we remake the key by subtracting 1 to match in memory information reduced_key = ti.key.reduced if ti.state == TaskInstanceState.SUCCESS: ti_status.succeeded.add(reduced_key) self.log.debug("Task instance %s succeeded. Don't rerun.", ti) ti_status.running.pop(reduced_key) continue if ti.state == TaskInstanceState.SKIPPED: ti_status.skipped.add(reduced_key) self.log.debug("Task instance %s skipped. Don't rerun.", ti) ti_status.running.pop(reduced_key) continue if ti.state == TaskInstanceState.FAILED: self.log.error("Task instance %s failed", ti) ti_status.failed.add(reduced_key) ti_status.running.pop(reduced_key) continue # special case: if the task needs to run again put it back if ti.state == TaskInstanceState.UP_FOR_RETRY: self.log.warning("Task instance %s is up for retry", ti) ti_status.running.pop(reduced_key) ti_status.to_run[ti.key] = ti # special case: if the task needs to be rescheduled put it back elif ti.state == TaskInstanceState.UP_FOR_RESCHEDULE: self.log.warning("Task instance %s is up for reschedule", ti) # During handling of reschedule state in ti._handle_reschedule, try number is reduced # by one, so we should not use reduced_key to avoid key error ti_status.running.pop(ti.key) ti_status.to_run[ti.key] = ti # special case: The state of the task can be set to NONE by the task itself # when it reaches concurrency limits. It could also happen when the state # is changed externally, e.g. by clearing tasks from the ui. We need to cover # for that as otherwise those tasks would fall outside of the scope of # the backfill suddenly. elif ti.state == State.NONE: self.log.warning( "FIXME: task instance %s state was set to none externally or " "reaching concurrency limits. Re-adding task to queue.", ti, ) tis_to_be_scheduled.append(ti) ti_status.running.pop(reduced_key) ti_status.to_run[ti.key] = ti # Batch schedule of task instances if tis_to_be_scheduled: filter_for_tis = TI.filter_for_tis(tis_to_be_scheduled) session.query(TI).filter(filter_for_tis).update( values={TI.state: TaskInstanceState.SCHEDULED}, synchronize_session=False ) def _manage_executor_state(self, running): """ Checks if the executor agrees with the state of task instances that are running :param running: dict of key, task to verify """ executor = self.executor # TODO: query all instead of refresh from db for key, value in list(executor.get_event_buffer().items()): state, info = value if key not in running: self.log.warning("%s state %s not in running=%s", key, state, running.values()) continue ti = running[key] ti.refresh_from_db() self.log.debug("Executor state: %s task %s", state, ti) if ( state in (TaskInstanceState.FAILED, TaskInstanceState.SUCCESS) and ti.state in self.STATES_COUNT_AS_RUNNING ): msg = ( f"Executor reports task instance {ti} finished ({state}) although the task says its " f"{ti.state}. Was the task killed externally? Info: {info}" ) self.log.error(msg) ti.handle_failure_with_callback(error=msg) @provide_session def _get_dag_run(self, dagrun_info: DagRunInfo, dag: DAG, session: Session = None): """ Returns a dag run for the given run date, which will be matched to an existing dag run if available or create a new dag run otherwise. If the max_active_runs limit is reached, this function will return None. :param dagrun_info: Schedule information for the dag run :param dag: DAG :param session: the database session object :return: a DagRun in state RUNNING or None """ run_date = dagrun_info.logical_date # consider max_active_runs but ignore when running subdags respect_dag_max_active_limit = bool(dag.timetable.can_run and not dag.is_subdag) current_active_dag_count = dag.get_num_active_runs(external_trigger=False) # check if we are scheduling on top of a already existing dag_run # we could find a "scheduled" run instead of a "backfill" runs = DagRun.find(dag_id=dag.dag_id, execution_date=run_date, session=session) run: Optional[DagRun] if runs: run = runs[0] if run.state == DagRunState.RUNNING: respect_dag_max_active_limit = False else: run = None # enforce max_active_runs limit for dag, special cases already # handled by respect_dag_max_active_limit if respect_dag_max_active_limit and current_active_dag_count >= dag.max_active_runs: return None run = run or dag.create_dagrun( execution_date=run_date, data_interval=dagrun_info.data_interval, start_date=timezone.utcnow(), state=DagRunState.RUNNING, external_trigger=False, session=session, conf=self.conf, run_type=DagRunType.BACKFILL_JOB, creating_job_id=self.id, ) # set required transient field run.dag = dag # explicitly mark as backfill and running run.state = DagRunState.RUNNING run.run_type = DagRunType.BACKFILL_JOB run.verify_integrity(session=session) return run @provide_session def _task_instances_for_dag_run(self, dag_run, session=None): """ Returns a map of task instance key to task instance object for the tasks to run in the given dag run. :param dag_run: the dag run to get the tasks from :type dag_run: airflow.models.DagRun :param session: the database session object :type session: sqlalchemy.orm.session.Session """ tasks_to_run = {} if dag_run is None: return tasks_to_run # check if we have orphaned tasks self.reset_state_for_orphaned_tasks(filter_by_dag_run=dag_run, session=session) # for some reason if we don't refresh the reference to run is lost dag_run.refresh_from_db() make_transient(dag_run) try: for ti in dag_run.get_task_instances(): # all tasks part of the backfill are scheduled to run if ti.state == State.NONE: ti.set_state(TaskInstanceState.SCHEDULED, session=session) if ti.state != TaskInstanceState.REMOVED: tasks_to_run[ti.key] = ti session.commit() except Exception: session.rollback() raise return tasks_to_run def _log_progress(self, ti_status): self.log.info( '[backfill progress] | finished run %s of %s | tasks waiting: %s | succeeded: %s | ' 'running: %s | failed: %s | skipped: %s | deadlocked: %s | not ready: %s', ti_status.finished_runs, ti_status.total_runs, len(ti_status.to_run), len(ti_status.succeeded), len(ti_status.running), len(ti_status.failed), len(ti_status.skipped), len(ti_status.deadlocked), len(ti_status.not_ready), ) self.log.debug("Finished dag run loop iteration. Remaining tasks %s", ti_status.to_run.values()) @provide_session def _process_backfill_task_instances( self, ti_status, executor, pickle_id, start_date=None, session=None, ): """ Process a set of task instances from a set of dag runs. Special handling is done to account for different task instance states that could be present when running them in a backfill process. :param ti_status: the internal status of the job :type ti_status: BackfillJob._DagRunTaskStatus :param executor: the executor to run the task instances :type executor: BaseExecutor :param pickle_id: the pickle_id if dag is pickled, None otherwise :type pickle_id: int :param start_date: the start date of the backfill job :type start_date: datetime.datetime :param session: the current session object :type session: sqlalchemy.orm.session.Session :return: the list of execution_dates for the finished dag runs :rtype: list """ executed_run_dates = [] is_unit_test = airflow_conf.getboolean('core', 'unit_test_mode') while (len(ti_status.to_run) > 0 or len(ti_status.running) > 0) and len(ti_status.deadlocked) == 0: self.log.debug("*** Clearing out not_ready list ***") ti_status.not_ready.clear() # we need to execute the tasks bottom to top # or leaf to root, as otherwise tasks might be # determined deadlocked while they are actually # waiting for their upstream to finish @provide_session def _per_task_process(key, ti: TaskInstance, session=None): ti.refresh_from_db(lock_for_update=True, session=session) task = self.dag.get_task(ti.task_id, include_subdags=True) ti.task = task self.log.debug("Task instance to run %s state %s", ti, ti.state) # The task was already marked successful or skipped by a # different Job. Don't rerun it. if ti.state == TaskInstanceState.SUCCESS: ti_status.succeeded.add(key) self.log.debug("Task instance %s succeeded. Don't rerun.", ti) ti_status.to_run.pop(key) if key in ti_status.running: ti_status.running.pop(key) return elif ti.state == TaskInstanceState.SKIPPED: ti_status.skipped.add(key) self.log.debug("Task instance %s skipped. Don't rerun.", ti) ti_status.to_run.pop(key) if key in ti_status.running: ti_status.running.pop(key) return # guard against externally modified tasks instances or # in case max concurrency has been reached at task runtime elif ti.state == State.NONE: self.log.warning( "FIXME: Task instance %s state was set to None externally. This should not happen", ti ) ti.set_state(TaskInstanceState.SCHEDULED, session=session) if self.rerun_failed_tasks: # Rerun failed tasks or upstreamed failed tasks if ti.state in (TaskInstanceState.FAILED, TaskInstanceState.UPSTREAM_FAILED): self.log.error("Task instance %s with state %s", ti, ti.state) if key in ti_status.running: ti_status.running.pop(key) # Reset the failed task in backfill to scheduled state ti.set_state(TaskInstanceState.SCHEDULED, session=session) else: # Default behaviour which works for subdag. if ti.state in (TaskInstanceState.FAILED, TaskInstanceState.UPSTREAM_FAILED): self.log.error("Task instance %s with state %s", ti, ti.state) ti_status.failed.add(key) ti_status.to_run.pop(key) if key in ti_status.running: ti_status.running.pop(key) return if self.ignore_first_depends_on_past: dagrun = ti.get_dagrun(session=session) ignore_depends_on_past = dagrun.execution_date == (start_date or ti.start_date) else: ignore_depends_on_past = False backfill_context = DepContext( deps=BACKFILL_QUEUED_DEPS, ignore_depends_on_past=ignore_depends_on_past, ignore_task_deps=self.ignore_task_deps, flag_upstream_failed=True, ) # Is the task runnable? -- then run it # the dependency checker can change states of tis if ti.are_dependencies_met( dep_context=backfill_context, session=session, verbose=self.verbose ): if executor.has_task(ti): self.log.debug("Task Instance %s already in executor waiting for queue to clear", ti) else: self.log.debug('Sending %s to executor', ti) # Skip scheduled state, we are executing immediately ti.state = TaskInstanceState.QUEUED ti.queued_by_job_id = self.id ti.queued_dttm = timezone.utcnow() session.merge(ti) cfg_path = None if self.executor_class in ( executor_constants.LOCAL_EXECUTOR, executor_constants.SEQUENTIAL_EXECUTOR, ): cfg_path = tmp_configuration_copy() executor.queue_task_instance( ti, mark_success=self.mark_success, pickle_id=pickle_id, ignore_task_deps=self.ignore_task_deps, ignore_depends_on_past=ignore_depends_on_past, pool=self.pool, cfg_path=cfg_path, ) ti_status.running[key] = ti ti_status.to_run.pop(key) session.commit() return if ti.state == TaskInstanceState.UPSTREAM_FAILED: self.log.error("Task instance %s upstream failed", ti) ti_status.failed.add(key) ti_status.to_run.pop(key) if key in ti_status.running: ti_status.running.pop(key) return # special case if ti.state == TaskInstanceState.UP_FOR_RETRY: self.log.debug("Task instance %s retry period not expired yet", ti) if key in ti_status.running: ti_status.running.pop(key) ti_status.to_run[key] = ti return # special case if ti.state == TaskInstanceState.UP_FOR_RESCHEDULE: self.log.debug("Task instance %s reschedule period not expired yet", ti) if key in ti_status.running: ti_status.running.pop(key) ti_status.to_run[key] = ti return # all remaining tasks self.log.debug('Adding %s to not_ready', ti) ti_status.not_ready.add(key) try: for task in self.dag.topological_sort(include_subdag_tasks=True): for key, ti in list(ti_status.to_run.items()): if task.task_id != ti.task_id: continue pool = session.query(models.Pool).filter(models.Pool.pool == task.pool).first() if not pool: raise PoolNotFound(f'Unknown pool: {task.pool}') open_slots = pool.open_slots(session=session) if open_slots <= 0: raise NoAvailablePoolSlot( f"Not scheduling since there are {open_slots} open slots in pool {task.pool}" ) num_running_task_instances_in_dag = DAG.get_num_task_instances( self.dag_id, states=self.STATES_COUNT_AS_RUNNING, session=session, ) if num_running_task_instances_in_dag >= self.dag.max_active_tasks: raise DagConcurrencyLimitReached( "Not scheduling since DAG max_active_tasks limit is reached." ) if task.max_active_tis_per_dag: num_running_task_instances_in_task = DAG.get_num_task_instances( dag_id=self.dag_id, task_ids=[task.task_id], states=self.STATES_COUNT_AS_RUNNING, session=session, ) if num_running_task_instances_in_task >= task.max_active_tis_per_dag: raise TaskConcurrencyLimitReached( "Not scheduling since Task concurrency limit is reached." ) _per_task_process(key, ti) except (NoAvailablePoolSlot, DagConcurrencyLimitReached, TaskConcurrencyLimitReached) as e: self.log.debug(e) self.heartbeat(only_if_necessary=is_unit_test) # execute the tasks in the queue executor.heartbeat() # If the set of tasks that aren't ready ever equals the set of # tasks to run and there are no running tasks then the backfill # is deadlocked if ( ti_status.not_ready and ti_status.not_ready == set(ti_status.to_run) and len(ti_status.running) == 0 ): self.log.warning("Deadlock discovered for ti_status.to_run=%s", ti_status.to_run.values()) ti_status.deadlocked.update(ti_status.to_run.values()) ti_status.to_run.clear() # check executor state self._manage_executor_state(ti_status.running) # update the task counters self._update_counters(ti_status=ti_status) # update dag run state _dag_runs = ti_status.active_runs[:] for run in _dag_runs: run.update_state(session=session) if run.state in State.finished: ti_status.finished_runs += 1 ti_status.active_runs.remove(run) executed_run_dates.append(run.execution_date) self._log_progress(ti_status) # return updated status return executed_run_dates @provide_session def _collect_errors(self, ti_status, session=None): def tabulate_ti_keys_set(set_ti_keys: Set[TaskInstanceKey]) -> str: # Sorting by execution date first sorted_ti_keys = sorted( set_ti_keys, key=lambda ti_key: (ti_key.run_id, ti_key.dag_id, ti_key.task_id, ti_key.try_number), ) return tabulate(sorted_ti_keys, headers=["DAG ID", "Task ID", "Run ID", "Try number"]) def tabulate_tis_set(set_tis: Set[TaskInstance]) -> str: # Sorting by execution date first sorted_tis = sorted(set_tis, key=lambda ti: (ti.run_id, ti.dag_id, ti.task_id, ti.try_number)) tis_values = ((ti.dag_id, ti.task_id, ti.run_id, ti.try_number) for ti in sorted_tis) return tabulate(tis_values, headers=["DAG ID", "Task ID", "Run ID", "Try number"]) err = '' if ti_status.failed: err += "Some task instances failed:\n" err += tabulate_ti_keys_set(ti_status.failed) if ti_status.deadlocked: err += 'BackfillJob is deadlocked.' deadlocked_depends_on_past = any( t.are_dependencies_met( dep_context=DepContext(ignore_depends_on_past=False), session=session, verbose=self.verbose, ) != t.are_dependencies_met( dep_context=DepContext(ignore_depends_on_past=True), session=session, verbose=self.verbose ) for t in ti_status.deadlocked ) if deadlocked_depends_on_past: err += ( 'Some of the deadlocked tasks were unable to run because ' 'of "depends_on_past" relationships. Try running the ' 'backfill with the option ' '"ignore_first_depends_on_past=True" or passing "-I" at ' 'the command line.' ) err += '\nThese tasks have succeeded:\n' err += tabulate_ti_keys_set(ti_status.succeeded) err += '\n\nThese tasks are running:\n' err += tabulate_ti_keys_set(ti_status.running) err += '\n\nThese tasks have failed:\n' err += tabulate_ti_keys_set(ti_status.failed) err += '\n\nThese tasks are skipped:\n' err += tabulate_ti_keys_set(ti_status.skipped) err += '\n\nThese tasks are deadlocked:\n' err += tabulate_tis_set(ti_status.deadlocked) return err @provide_session def _execute_dagruns(self, dagrun_infos, ti_status, executor, pickle_id, start_date, session=None): """ Computes the dag runs and their respective task instances for the given run dates and executes the task instances. Returns a list of execution dates of the dag runs that were executed. :param dagrun_infos: Schedule information for dag runs :type dagrun_infos: list[DagRunInfo] :param ti_status: internal BackfillJob status structure to tis track progress :type ti_status: BackfillJob._DagRunTaskStatus :param executor: the executor to use, it must be previously started :type executor: BaseExecutor :param pickle_id: numeric id of the pickled dag, None if not pickled :type pickle_id: int :param start_date: backfill start date :type start_date: datetime.datetime :param session: the current session object :type session: sqlalchemy.orm.session.Session """ for dagrun_info in dagrun_infos: for dag in [self.dag] + self.dag.subdags: dag_run = self._get_dag_run(dagrun_info, dag, session=session) tis_map = self._task_instances_for_dag_run(dag_run, session=session) if dag_run is None: continue ti_status.active_runs.append(dag_run) ti_status.to_run.update(tis_map or {}) processed_dag_run_dates = self._process_backfill_task_instances( ti_status=ti_status, executor=executor, pickle_id=pickle_id, start_date=start_date, session=session, ) ti_status.executed_dag_run_dates.update(processed_dag_run_dates) @provide_session def _set_unfinished_dag_runs_to_failed(self, dag_runs, session=None): """ Go through the dag_runs and update the state based on the task_instance state. Then set DAG runs that are not finished to failed. :param dag_runs: DAG runs :param session: session :return: None """ for dag_run in dag_runs: dag_run.update_state() if dag_run.state not in State.finished: dag_run.set_state(DagRunState.FAILED) session.merge(dag_run) @provide_session def _execute(self, session=None): """ Initializes all components required to run a dag for a specified date range and calls helper method to execute the tasks. """ ti_status = BackfillJob._DagRunTaskStatus() start_date = self.bf_start_date # Get DagRun schedule between the start/end dates, which will turn into dag runs. dagrun_start_date = timezone.coerce_datetime(start_date) if self.bf_end_date is None: dagrun_end_date = pendulum.now(timezone.utc) else: dagrun_end_date = pendulum.instance(self.bf_end_date) dagrun_infos = list(self.dag.iter_dagrun_infos_between(dagrun_start_date, dagrun_end_date)) if self.run_backwards: tasks_that_depend_on_past = [t.task_id for t in self.dag.task_dict.values() if t.depends_on_past] if tasks_that_depend_on_past: raise AirflowException( f'You cannot backfill backwards because one or more ' f'tasks depend_on_past: {",".join(tasks_that_depend_on_past)}' ) dagrun_infos = dagrun_infos[::-1] if not dagrun_infos: if not self.run_at_least_once: self.log.info("No run dates were found for the given dates and dag interval.") return dagrun_infos = [DagRunInfo.interval(dagrun_start_date, dagrun_end_date)] # picklin' pickle_id = None if not self.donot_pickle and self.executor_class not in ( executor_constants.LOCAL_EXECUTOR, executor_constants.SEQUENTIAL_EXECUTOR, executor_constants.DASK_EXECUTOR, ): pickle = DagPickle(self.dag) session.add(pickle) session.commit() pickle_id = pickle.id executor = self.executor executor.job_id = "backfill" executor.start() ti_status.total_runs = len(dagrun_infos) # total dag runs in backfill try: remaining_dates = ti_status.total_runs while remaining_dates > 0: dagrun_infos_to_process = [ dagrun_info for dagrun_info in dagrun_infos if dagrun_info.logical_date not in ti_status.executed_dag_run_dates ] self._execute_dagruns( dagrun_infos=dagrun_infos_to_process, ti_status=ti_status, executor=executor, pickle_id=pickle_id, start_date=start_date, session=session, ) remaining_dates = ti_status.total_runs - len(ti_status.executed_dag_run_dates) err = self._collect_errors(ti_status=ti_status, session=session) if err: raise BackfillUnfinished(err, ti_status) if remaining_dates > 0: self.log.info( "max_active_runs limit for dag %s has been reached " " - waiting for other dag runs to finish", self.dag_id, ) time.sleep(self.delay_on_limit_secs) except (KeyboardInterrupt, SystemExit): self.log.warning("Backfill terminated by user.") # TODO: we will need to terminate running task instances and set the # state to failed. self._set_unfinished_dag_runs_to_failed(ti_status.active_runs) finally: session.commit() executor.end() self.log.info("Backfill done. Exiting.") @provide_session def reset_state_for_orphaned_tasks(self, filter_by_dag_run=None, session=None): """ This function checks if there are any tasks in the dagrun (or all) that have a schedule or queued states but are not known by the executor. If it finds those it will reset the state to None so they will get picked up again. The batch option is for performance reasons as the queries are made in sequence. :param filter_by_dag_run: the dag_run we want to process, None if all :type filter_by_dag_run: airflow.models.DagRun :return: the number of TIs reset :rtype: int """ queued_tis = self.executor.queued_tasks # also consider running as the state might not have changed in the db yet running_tis = self.executor.running # Can't use an update here since it doesn't support joins. resettable_states = [TaskInstanceState.SCHEDULED, TaskInstanceState.QUEUED] if filter_by_dag_run is None: resettable_tis = ( session.query(TaskInstance) .join(TaskInstance.dag_run) .filter( DagRun.state == DagRunState.RUNNING, DagRun.run_type != DagRunType.BACKFILL_JOB, TaskInstance.state.in_(resettable_states), ) ).all() else: resettable_tis = filter_by_dag_run.get_task_instances(state=resettable_states, session=session) tis_to_reset = [ti for ti in resettable_tis if ti.key not in queued_tis and ti.key not in running_tis] if not tis_to_reset: return 0 def query(result, items): if not items: return result filter_for_tis = TaskInstance.filter_for_tis(items) reset_tis = ( session.query(TaskInstance) .filter(filter_for_tis, TaskInstance.state.in_(resettable_states)) .with_for_update() .all() ) for ti in reset_tis: ti.state = State.NONE session.merge(ti) return result + reset_tis reset_tis = helpers.reduce_in_chunks(query, tis_to_reset, [], self.max_tis_per_query) task_instance_str = '\n\t'.join(repr(x) for x in reset_tis) session.flush() self.log.info("Reset the following %s TaskInstances:\n\t%s", len(reset_tis), task_instance_str) return len(reset_tis)
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import datetime from typing import List, Optional, Union from azure.core.exceptions import HttpResponseError import msrest.serialization class CommunicationError(msrest.serialization.Model): """The Communication Services error. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar code: Required. The error code. :vartype code: str :ivar message: Required. The error message. :vartype message: str :ivar target: The error target. :vartype target: str :ivar details: Further details about specific errors that led to this error. :vartype details: list[~azure.communication.identity.models.CommunicationError] :ivar inner_error: The inner error if any. :vartype inner_error: ~azure.communication.identity.models.CommunicationError """ _validation = { 'code': {'required': True}, 'message': {'required': True}, 'target': {'readonly': True}, 'details': {'readonly': True}, 'inner_error': {'readonly': True}, } _attribute_map = { 'code': {'key': 'code', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, 'target': {'key': 'target', 'type': 'str'}, 'details': {'key': 'details', 'type': '[CommunicationError]'}, 'inner_error': {'key': 'innererror', 'type': 'CommunicationError'}, } def __init__( self, *, code: str, message: str, **kwargs ): """ :keyword code: Required. The error code. :paramtype code: str :keyword message: Required. The error message. :paramtype message: str """ super(CommunicationError, self).__init__(**kwargs) self.code = code self.message = message self.target = None self.details = None self.inner_error = None class CommunicationErrorResponse(msrest.serialization.Model): """The Communication Services error. All required parameters must be populated in order to send to Azure. :ivar error: Required. The Communication Services error. :vartype error: ~azure.communication.identity.models.CommunicationError """ _validation = { 'error': {'required': True}, } _attribute_map = { 'error': {'key': 'error', 'type': 'CommunicationError'}, } def __init__( self, *, error: "CommunicationError", **kwargs ): """ :keyword error: Required. The Communication Services error. :paramtype error: ~azure.communication.identity.models.CommunicationError """ super(CommunicationErrorResponse, self).__init__(**kwargs) self.error = error class CommunicationIdentity(msrest.serialization.Model): """A communication identity. All required parameters must be populated in order to send to Azure. :ivar id: Required. Identifier of the identity. :vartype id: str """ _validation = { 'id': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, } def __init__( self, *, id: str, **kwargs ): """ :keyword id: Required. Identifier of the identity. :paramtype id: str """ super(CommunicationIdentity, self).__init__(**kwargs) self.id = id class CommunicationIdentityAccessToken(msrest.serialization.Model): """An access token. All required parameters must be populated in order to send to Azure. :ivar token: Required. The access token issued for the identity. :vartype token: str :ivar expires_on: Required. The expiry time of the token. :vartype expires_on: ~datetime.datetime """ _validation = { 'token': {'required': True}, 'expires_on': {'required': True}, } _attribute_map = { 'token': {'key': 'token', 'type': 'str'}, 'expires_on': {'key': 'expiresOn', 'type': 'iso-8601'}, } def __init__( self, *, token: str, expires_on: datetime.datetime, **kwargs ): """ :keyword token: Required. The access token issued for the identity. :paramtype token: str :keyword expires_on: Required. The expiry time of the token. :paramtype expires_on: ~datetime.datetime """ super(CommunicationIdentityAccessToken, self).__init__(**kwargs) self.token = token self.expires_on = expires_on class CommunicationIdentityAccessTokenRequest(msrest.serialization.Model): """CommunicationIdentityAccessTokenRequest. All required parameters must be populated in order to send to Azure. :ivar scopes: Required. List of scopes attached to the token. :vartype scopes: list[str or ~azure.communication.identity.models.CommunicationTokenScope] """ _validation = { 'scopes': {'required': True}, } _attribute_map = { 'scopes': {'key': 'scopes', 'type': '[str]'}, } def __init__( self, *, scopes: List[Union[str, "CommunicationTokenScope"]], **kwargs ): """ :keyword scopes: Required. List of scopes attached to the token. :paramtype scopes: list[str or ~azure.communication.identity.models.CommunicationTokenScope] """ super(CommunicationIdentityAccessTokenRequest, self).__init__(**kwargs) self.scopes = scopes class CommunicationIdentityAccessTokenResult(msrest.serialization.Model): """A communication identity with access token. All required parameters must be populated in order to send to Azure. :ivar identity: Required. A communication identity. :vartype identity: ~azure.communication.identity.models.CommunicationIdentity :ivar access_token: An access token. :vartype access_token: ~azure.communication.identity.models.CommunicationIdentityAccessToken """ _validation = { 'identity': {'required': True}, } _attribute_map = { 'identity': {'key': 'identity', 'type': 'CommunicationIdentity'}, 'access_token': {'key': 'accessToken', 'type': 'CommunicationIdentityAccessToken'}, } def __init__( self, *, identity: "CommunicationIdentity", access_token: Optional["CommunicationIdentityAccessToken"] = None, **kwargs ): """ :keyword identity: Required. A communication identity. :paramtype identity: ~azure.communication.identity.models.CommunicationIdentity :keyword access_token: An access token. :paramtype access_token: ~azure.communication.identity.models.CommunicationIdentityAccessToken """ super(CommunicationIdentityAccessTokenResult, self).__init__(**kwargs) self.identity = identity self.access_token = access_token class CommunicationIdentityCreateRequest(msrest.serialization.Model): """CommunicationIdentityCreateRequest. :ivar create_token_with_scopes: Also create access token for the created identity. :vartype create_token_with_scopes: list[str or ~azure.communication.identity.models.CommunicationTokenScope] """ _attribute_map = { 'create_token_with_scopes': {'key': 'createTokenWithScopes', 'type': '[str]'}, } def __init__( self, *, create_token_with_scopes: Optional[List[Union[str, "CommunicationTokenScope"]]] = None, **kwargs ): """ :keyword create_token_with_scopes: Also create access token for the created identity. :paramtype create_token_with_scopes: list[str or ~azure.communication.identity.models.CommunicationTokenScope] """ super(CommunicationIdentityCreateRequest, self).__init__(**kwargs) self.create_token_with_scopes = create_token_with_scopes class TeamsUserAccessTokenRequest(msrest.serialization.Model): """TeamsUserAccessTokenRequest. All required parameters must be populated in order to send to Azure. :ivar token: Required. AAD access token of a Teams User to acquire a new Communication Identity access token. :vartype token: str """ _validation = { 'token': {'required': True}, } _attribute_map = { 'token': {'key': 'token', 'type': 'str'}, } def __init__( self, *, token: str, **kwargs ): """ :keyword token: Required. AAD access token of a Teams User to acquire a new Communication Identity access token. :paramtype token: str """ super(TeamsUserAccessTokenRequest, self).__init__(**kwargs) self.token = token
__all__ = ['matrix', 'bmat', 'mat', 'asmatrix'] import sys import numpy.core.numeric as N from numpy.core.numeric import concatenate, isscalar, binary_repr, identity, asanyarray from numpy.core.numerictypes import issubdtype # make translation table _numchars = '0123456789.-+jeEL' if sys.version_info[0] >= 3: class _NumCharTable: def __getitem__(self, i): if chr(i) in _numchars: return chr(i) else: return None _table = _NumCharTable() def _eval(astr): return eval(astr.translate(_table)) else: _table = [None]*256 for k in range(256): _table[k] = chr(k) _table = ''.join(_table) _todelete = [] for k in _table: if k not in _numchars: _todelete.append(k) _todelete = ''.join(_todelete) del k def _eval(astr): return eval(astr.translate(_table,_todelete)) def _convert_from_string(data): rows = data.split(';') newdata = [] count = 0 for row in rows: trow = row.split(',') newrow = [] for col in trow: temp = col.split() newrow.extend(map(_eval,temp)) if count == 0: Ncols = len(newrow) elif len(newrow) != Ncols: raise ValueError("Rows not the same size.") count += 1 newdata.append(newrow) return newdata def asmatrix(data, dtype=None): """ Interpret the input as a matrix. Unlike `matrix`, `asmatrix` does not make a copy if the input is already a matrix or an ndarray. Equivalent to ``matrix(data, copy=False)``. Parameters ---------- data : array_like Input data. Returns ------- mat : matrix `data` interpreted as a matrix. Examples -------- >>> x = np.array([[1, 2], [3, 4]]) >>> m = np.asmatrix(x) >>> x[0,0] = 5 >>> m matrix([[5, 2], [3, 4]]) """ return matrix(data, dtype=dtype, copy=False) def matrix_power(M,n): """ Raise a square matrix to the (integer) power `n`. For positive integers `n`, the power is computed by repeated matrix squarings and matrix multiplications. If ``n == 0``, the identity matrix of the same shape as M is returned. If ``n < 0``, the inverse is computed and then raised to the ``abs(n)``. Parameters ---------- M : ndarray or matrix object Matrix to be "powered." Must be square, i.e. ``M.shape == (m, m)``, with `m` a positive integer. n : int The exponent can be any integer or long integer, positive, negative, or zero. Returns ------- M**n : ndarray or matrix object The return value is the same shape and type as `M`; if the exponent is positive or zero then the type of the elements is the same as those of `M`. If the exponent is negative the elements are floating-point. Raises ------ LinAlgError If the matrix is not numerically invertible. See Also -------- matrix Provides an equivalent function as the exponentiation operator (``**``, not ``^``). Examples -------- >>> from numpy import linalg as LA >>> i = np.array([[0, 1], [-1, 0]]) # matrix equiv. of the imaginary unit >>> LA.matrix_power(i, 3) # should = -i array([[ 0, -1], [ 1, 0]]) >>> LA.matrix_power(np.matrix(i), 3) # matrix arg returns matrix matrix([[ 0, -1], [ 1, 0]]) >>> LA.matrix_power(i, 0) array([[1, 0], [0, 1]]) >>> LA.matrix_power(i, -3) # should = 1/(-i) = i, but w/ f.p. elements array([[ 0., 1.], [-1., 0.]]) Somewhat more sophisticated example >>> q = np.zeros((4, 4)) >>> q[0:2, 0:2] = -i >>> q[2:4, 2:4] = i >>> q # one of the three quarternion units not equal to 1 array([[ 0., -1., 0., 0.], [ 1., 0., 0., 0.], [ 0., 0., 0., 1.], [ 0., 0., -1., 0.]]) >>> LA.matrix_power(q, 2) # = -np.eye(4) array([[-1., 0., 0., 0.], [ 0., -1., 0., 0.], [ 0., 0., -1., 0.], [ 0., 0., 0., -1.]]) """ M = asanyarray(M) if len(M.shape) != 2 or M.shape[0] != M.shape[1]: raise ValueError("input must be a square array") if not issubdtype(type(n),int): raise TypeError("exponent must be an integer") from numpy.linalg import inv if n==0: M = M.copy() M[:] = identity(M.shape[0]) return M elif n<0: M = inv(M) n *= -1 result = M if n <= 3: for _ in range(n-1): result=N.dot(result,M) return result # binary decomposition to reduce the number of Matrix # multiplications for n > 3. beta = binary_repr(n) Z,q,t = M,0,len(beta) while beta[t-q-1] == '0': Z = N.dot(Z,Z) q += 1 result = Z for k in range(q+1,t): Z = N.dot(Z,Z) if beta[t-k-1] == '1': result = N.dot(result,Z) return result class matrix(N.ndarray): """ matrix(data, dtype=None, copy=True) Returns a matrix from an array-like object, or from a string of data. A matrix is a specialized 2-D array that retains its 2-D nature through operations. It has certain special operators, such as ``*`` (matrix multiplication) and ``**`` (matrix power). Parameters ---------- data : array_like or string If `data` is a string, it is interpreted as a matrix with commas or spaces separating columns, and semicolons separating rows. dtype : data-type Data-type of the output matrix. copy : bool If `data` is already an `ndarray`, then this flag determines whether the data is copied (the default), or whether a view is constructed. See Also -------- array Examples -------- >>> a = np.matrix('1 2; 3 4') >>> print a [[1 2] [3 4]] >>> np.matrix([[1, 2], [3, 4]]) matrix([[1, 2], [3, 4]]) """ __array_priority__ = 10.0 def __new__(subtype, data, dtype=None, copy=True): if isinstance(data, matrix): dtype2 = data.dtype if (dtype is None): dtype = dtype2 if (dtype2 == dtype) and (not copy): return data return data.astype(dtype) if isinstance(data, N.ndarray): if dtype is None: intype = data.dtype else: intype = N.dtype(dtype) new = data.view(subtype) if intype != data.dtype: return new.astype(intype) if copy: return new.copy() else: return new if isinstance(data, str): data = _convert_from_string(data) # now convert data to an array arr = N.array(data, dtype=dtype, copy=copy) ndim = arr.ndim shape = arr.shape if (ndim > 2): raise ValueError("matrix must be 2-dimensional") elif ndim == 0: shape = (1,1) elif ndim == 1: shape = (1,shape[0]) order = False if (ndim == 2) and arr.flags.fortran: order = True if not (order or arr.flags.contiguous): arr = arr.copy() ret = N.ndarray.__new__(subtype, shape, arr.dtype, buffer=arr, order=order) return ret def __array_finalize__(self, obj): self._getitem = False if (isinstance(obj, matrix) and obj._getitem): return ndim = self.ndim if (ndim == 2): return if (ndim > 2): newshape = tuple([x for x in self.shape if x > 1]) ndim = len(newshape) if ndim == 2: self.shape = newshape return elif (ndim > 2): raise ValueError("shape too large to be a matrix.") else: newshape = self.shape if ndim == 0: self.shape = (1,1) elif ndim == 1: self.shape = (1,newshape[0]) return def __getitem__(self, index): self._getitem = True try: out = N.ndarray.__getitem__(self, index) finally: self._getitem = False if not isinstance(out, N.ndarray): return out if out.ndim == 0: return out[()] if out.ndim == 1: sh = out.shape[0] # Determine when we should have a column array try: n = len(index) except: n = 0 if n > 1 and isscalar(index[1]): out.shape = (sh,1) else: out.shape = (1,sh) return out def __mul__(self, other): if isinstance(other,(N.ndarray, list, tuple)) : # This promotes 1-D vectors to row vectors return N.dot(self, asmatrix(other)) if isscalar(other) or not hasattr(other, '__rmul__') : return N.dot(self, other) return NotImplemented def __rmul__(self, other): return N.dot(other, self) def __imul__(self, other): self[:] = self * other return self def __pow__(self, other): return matrix_power(self, other) def __ipow__(self, other): self[:] = self ** other return self def __rpow__(self, other): return NotImplemented def __repr__(self): s = repr(self.__array__()).replace('array', 'matrix') # now, 'matrix' has 6 letters, and 'array' 5, so the columns don't # line up anymore. We need to add a space. l = s.splitlines() for i in range(1, len(l)): if l[i]: l[i] = ' ' + l[i] return '\n'.join(l) def __str__(self): return str(self.__array__()) def _align(self, axis): """A convenience function for operations that need to preserve axis orientation. """ if axis is None: return self[0,0] elif axis==0: return self elif axis==1: return self.transpose() else: raise ValueError("unsupported axis") def _collapse(self, axis): """A convenience function for operations that want to collapse to a scalar like _align, but are using keepdims=True """ if axis is None: return self[0,0] else: return self # Necessary because base-class tolist expects dimension # reduction by x[0] def tolist(self): """ Return the matrix as a (possibly nested) list. See `ndarray.tolist` for full documentation. See Also -------- ndarray.tolist Examples -------- >>> x = np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.tolist() [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]] """ return self.__array__().tolist() # To preserve orientation of result... def sum(self, axis=None, dtype=None, out=None): """ Returns the sum of the matrix elements, along the given axis. Refer to `numpy.sum` for full documentation. See Also -------- numpy.sum Notes ----- This is the same as `ndarray.sum`, except that where an `ndarray` would be returned, a `matrix` object is returned instead. Examples -------- >>> x = np.matrix([[1, 2], [4, 3]]) >>> x.sum() 10 >>> x.sum(axis=1) matrix([[3], [7]]) >>> x.sum(axis=1, dtype='float') matrix([[ 3.], [ 7.]]) >>> out = np.zeros((1, 2), dtype='float') >>> x.sum(axis=1, dtype='float', out=out) matrix([[ 3.], [ 7.]]) """ return N.ndarray.sum(self, axis, dtype, out, keepdims=True)._collapse(axis) def mean(self, axis=None, dtype=None, out=None): """ Returns the average of the matrix elements along the given axis. Refer to `numpy.mean` for full documentation. See Also -------- numpy.mean Notes ----- Same as `ndarray.mean` except that, where that returns an `ndarray`, this returns a `matrix` object. Examples -------- >>> x = np.matrix(np.arange(12).reshape((3, 4))) >>> x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.mean() 5.5 >>> x.mean(0) matrix([[ 4., 5., 6., 7.]]) >>> x.mean(1) matrix([[ 1.5], [ 5.5], [ 9.5]]) """ return N.ndarray.mean(self, axis, dtype, out, keepdims=True)._collapse(axis) def std(self, axis=None, dtype=None, out=None, ddof=0): """ Return the standard deviation of the array elements along the given axis. Refer to `numpy.std` for full documentation. See Also -------- numpy.std Notes ----- This is the same as `ndarray.std`, except that where an `ndarray` would be returned, a `matrix` object is returned instead. Examples -------- >>> x = np.matrix(np.arange(12).reshape((3, 4))) >>> x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.std() 3.4520525295346629 >>> x.std(0) matrix([[ 3.26598632, 3.26598632, 3.26598632, 3.26598632]]) >>> x.std(1) matrix([[ 1.11803399], [ 1.11803399], [ 1.11803399]]) """ return N.ndarray.std(self, axis, dtype, out, ddof, keepdims=True)._collapse(axis) def var(self, axis=None, dtype=None, out=None, ddof=0): """ Returns the variance of the matrix elements, along the given axis. Refer to `numpy.var` for full documentation. See Also -------- numpy.var Notes ----- This is the same as `ndarray.var`, except that where an `ndarray` would be returned, a `matrix` object is returned instead. Examples -------- >>> x = np.matrix(np.arange(12).reshape((3, 4))) >>> x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.var() 11.916666666666666 >>> x.var(0) matrix([[ 10.66666667, 10.66666667, 10.66666667, 10.66666667]]) >>> x.var(1) matrix([[ 1.25], [ 1.25], [ 1.25]]) """ return N.ndarray.var(self, axis, dtype, out, ddof, keepdims=True)._collapse(axis) def prod(self, axis=None, dtype=None, out=None): """ Return the product of the array elements over the given axis. Refer to `prod` for full documentation. See Also -------- prod, ndarray.prod Notes ----- Same as `ndarray.prod`, except, where that returns an `ndarray`, this returns a `matrix` object instead. Examples -------- >>> x = np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.prod() 0 >>> x.prod(0) matrix([[ 0, 45, 120, 231]]) >>> x.prod(1) matrix([[ 0], [ 840], [7920]]) """ return N.ndarray.prod(self, axis, dtype, out, keepdims=True)._collapse(axis) def any(self, axis=None, out=None): """ Test whether any array element along a given axis evaluates to True. Refer to `numpy.any` for full documentation. Parameters ---------- axis: int, optional Axis along which logical OR is performed out: ndarray, optional Output to existing array instead of creating new one, must have same shape as expected output Returns ------- any : bool, ndarray Returns a single bool if `axis` is ``None``; otherwise, returns `ndarray` """ return N.ndarray.any(self, axis, out, keepdims=True)._collapse(axis) def all(self, axis=None, out=None): """ Test whether all matrix elements along a given axis evaluate to True. Parameters ---------- See `numpy.all` for complete descriptions See Also -------- numpy.all Notes ----- This is the same as `ndarray.all`, but it returns a `matrix` object. Examples -------- >>> x = np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> y = x[0]; y matrix([[0, 1, 2, 3]]) >>> (x == y) matrix([[ True, True, True, True], [False, False, False, False], [False, False, False, False]], dtype=bool) >>> (x == y).all() False >>> (x == y).all(0) matrix([[False, False, False, False]], dtype=bool) >>> (x == y).all(1) matrix([[ True], [False], [False]], dtype=bool) """ return N.ndarray.all(self, axis, out, keepdims=True)._collapse(axis) def max(self, axis=None, out=None): """ Return the maximum value along an axis. Parameters ---------- See `amax` for complete descriptions See Also -------- amax, ndarray.max Notes ----- This is the same as `ndarray.max`, but returns a `matrix` object where `ndarray.max` would return an ndarray. Examples -------- >>> x = np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.max() 11 >>> x.max(0) matrix([[ 8, 9, 10, 11]]) >>> x.max(1) matrix([[ 3], [ 7], [11]]) """ return N.ndarray.max(self, axis, out, keepdims=True)._collapse(axis) def argmax(self, axis=None, out=None): """ Indices of the maximum values along an axis. Parameters ---------- See `numpy.argmax` for complete descriptions See Also -------- numpy.argmax Notes ----- This is the same as `ndarray.argmax`, but returns a `matrix` object where `ndarray.argmax` would return an `ndarray`. Examples -------- >>> x = np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.argmax() 11 >>> x.argmax(0) matrix([[2, 2, 2, 2]]) >>> x.argmax(1) matrix([[3], [3], [3]]) """ return N.ndarray.argmax(self, axis, out)._align(axis) def min(self, axis=None, out=None): """ Return the minimum value along an axis. Parameters ---------- See `amin` for complete descriptions. See Also -------- amin, ndarray.min Notes ----- This is the same as `ndarray.min`, but returns a `matrix` object where `ndarray.min` would return an ndarray. Examples -------- >>> x = -np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, -1, -2, -3], [ -4, -5, -6, -7], [ -8, -9, -10, -11]]) >>> x.min() -11 >>> x.min(0) matrix([[ -8, -9, -10, -11]]) >>> x.min(1) matrix([[ -3], [ -7], [-11]]) """ return N.ndarray.min(self, axis, out, keepdims=True)._collapse(axis) def argmin(self, axis=None, out=None): """ Return the indices of the minimum values along an axis. Parameters ---------- See `numpy.argmin` for complete descriptions. See Also -------- numpy.argmin Notes ----- This is the same as `ndarray.argmin`, but returns a `matrix` object where `ndarray.argmin` would return an `ndarray`. Examples -------- >>> x = -np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, -1, -2, -3], [ -4, -5, -6, -7], [ -8, -9, -10, -11]]) >>> x.argmin() 11 >>> x.argmin(0) matrix([[2, 2, 2, 2]]) >>> x.argmin(1) matrix([[3], [3], [3]]) """ return N.ndarray.argmin(self, axis, out)._align(axis) def ptp(self, axis=None, out=None): """ Peak-to-peak (maximum - minimum) value along the given axis. Refer to `numpy.ptp` for full documentation. See Also -------- numpy.ptp Notes ----- Same as `ndarray.ptp`, except, where that would return an `ndarray` object, this returns a `matrix` object. Examples -------- >>> x = np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.ptp() 11 >>> x.ptp(0) matrix([[8, 8, 8, 8]]) >>> x.ptp(1) matrix([[3], [3], [3]]) """ return N.ndarray.ptp(self, axis, out)._align(axis) def getI(self): """ Returns the (multiplicative) inverse of invertible `self`. Parameters ---------- None Returns ------- ret : matrix object If `self` is non-singular, `ret` is such that ``ret * self`` == ``self * ret`` == ``np.matrix(np.eye(self[0,:].size)`` all return ``True``. Raises ------ numpy.linalg.LinAlgError: Singular matrix If `self` is singular. See Also -------- linalg.inv Examples -------- >>> m = np.matrix('[1, 2; 3, 4]'); m matrix([[1, 2], [3, 4]]) >>> m.getI() matrix([[-2. , 1. ], [ 1.5, -0.5]]) >>> m.getI() * m matrix([[ 1., 0.], [ 0., 1.]]) """ M,N = self.shape if M == N: from numpy.dual import inv as func else: from numpy.dual import pinv as func return asmatrix(func(self)) def getA(self): """ Return `self` as an `ndarray` object. Equivalent to ``np.asarray(self)``. Parameters ---------- None Returns ------- ret : ndarray `self` as an `ndarray` Examples -------- >>> x = np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.getA() array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) """ return self.__array__() def getA1(self): """ Return `self` as a flattened `ndarray`. Equivalent to ``np.asarray(x).ravel()`` Parameters ---------- None Returns ------- ret : ndarray `self`, 1-D, as an `ndarray` Examples -------- >>> x = np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.getA1() array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) """ return self.__array__().ravel() def getT(self): """ Returns the transpose of the matrix. Does *not* conjugate! For the complex conjugate transpose, use `getH`. Parameters ---------- None Returns ------- ret : matrix object The (non-conjugated) transpose of the matrix. See Also -------- transpose, getH Examples -------- >>> m = np.matrix('[1, 2; 3, 4]') >>> m matrix([[1, 2], [3, 4]]) >>> m.getT() matrix([[1, 3], [2, 4]]) """ return self.transpose() def getH(self): """ Returns the (complex) conjugate transpose of `self`. Equivalent to ``np.transpose(self)`` if `self` is real-valued. Parameters ---------- None Returns ------- ret : matrix object complex conjugate transpose of `self` Examples -------- >>> x = np.matrix(np.arange(12).reshape((3,4))) >>> z = x - 1j*x; z matrix([[ 0. +0.j, 1. -1.j, 2. -2.j, 3. -3.j], [ 4. -4.j, 5. -5.j, 6. -6.j, 7. -7.j], [ 8. -8.j, 9. -9.j, 10.-10.j, 11.-11.j]]) >>> z.getH() matrix([[ 0. +0.j, 4. +4.j, 8. +8.j], [ 1. +1.j, 5. +5.j, 9. +9.j], [ 2. +2.j, 6. +6.j, 10.+10.j], [ 3. +3.j, 7. +7.j, 11.+11.j]]) """ if issubclass(self.dtype.type, N.complexfloating): return self.transpose().conjugate() else: return self.transpose() T = property(getT, None, doc="transpose") A = property(getA, None, doc="base array") A1 = property(getA1, None, doc="1-d base array") H = property(getH, None, doc="hermitian (conjugate) transpose") I = property(getI, None, doc="inverse") def _from_string(str,gdict,ldict): rows = str.split(';') rowtup = [] for row in rows: trow = row.split(',') newrow = [] for x in trow: newrow.extend(x.split()) trow = newrow coltup = [] for col in trow: col = col.strip() try: thismat = ldict[col] except KeyError: try: thismat = gdict[col] except KeyError: raise KeyError("%s not found" % (col,)) coltup.append(thismat) rowtup.append(concatenate(coltup,axis=-1)) return concatenate(rowtup,axis=0) def bmat(obj, ldict=None, gdict=None): """ Build a matrix object from a string, nested sequence, or array. Parameters ---------- obj : str or array_like Input data. Names of variables in the current scope may be referenced, even if `obj` is a string. Returns ------- out : matrix Returns a matrix object, which is a specialized 2-D array. See Also -------- matrix Examples -------- >>> A = np.mat('1 1; 1 1') >>> B = np.mat('2 2; 2 2') >>> C = np.mat('3 4; 5 6') >>> D = np.mat('7 8; 9 0') All the following expressions construct the same block matrix: >>> np.bmat([[A, B], [C, D]]) matrix([[1, 1, 2, 2], [1, 1, 2, 2], [3, 4, 7, 8], [5, 6, 9, 0]]) >>> np.bmat(np.r_[np.c_[A, B], np.c_[C, D]]) matrix([[1, 1, 2, 2], [1, 1, 2, 2], [3, 4, 7, 8], [5, 6, 9, 0]]) >>> np.bmat('A,B; C,D') matrix([[1, 1, 2, 2], [1, 1, 2, 2], [3, 4, 7, 8], [5, 6, 9, 0]]) """ if isinstance(obj, str): if gdict is None: # get previous frame frame = sys._getframe().f_back glob_dict = frame.f_globals loc_dict = frame.f_locals else: glob_dict = gdict loc_dict = ldict return matrix(_from_string(obj, glob_dict, loc_dict)) if isinstance(obj, (tuple, list)): # [[A,B],[C,D]] arr_rows = [] for row in obj: if isinstance(row, N.ndarray): # not 2-d return matrix(concatenate(obj,axis=-1)) else: arr_rows.append(concatenate(row,axis=-1)) return matrix(concatenate(arr_rows,axis=0)) if isinstance(obj, N.ndarray): return matrix(obj) mat = asmatrix
from itertools import product import numpy as np from sympy import And import pytest from conftest import skipif, opts_tiling from devito import (ConditionalDimension, Grid, Function, TimeFunction, SparseFunction, # noqa Eq, Operator, Constant, Dimension, SubDimension, switchconfig, SubDomain, Lt, Le, Gt, Ge, Ne, Buffer) from devito.ir.iet import (Conditional, Expression, Iteration, FindNodes, retrieve_iteration_tree) from devito.symbolics import indexify, retrieve_functions, IntDiv from devito.types import Array class TestBufferedDimension(object): def test_multi_buffer(self): grid = Grid((3, 3)) f = TimeFunction(name="f", grid=grid) g = TimeFunction(name="g", grid=grid, save=Buffer(7)) op = Operator([Eq(f.forward, 1), Eq(g, f.forward)]) op(time_M=3) # f looped all time_order buffer and is 1 everywhere assert np.allclose(f.data, 1) # g looped indices 0 to 3, rest is still 0 assert np.allclose(g.data[0:4], 1) assert np.allclose(g.data[4:], 0) def test_multi_buffer_long_time(self): grid = Grid((3, 3)) time = grid.time_dim f = TimeFunction(name="f", grid=grid) g = TimeFunction(name="g", grid=grid, save=Buffer(7)) op = Operator([Eq(f.forward, time), Eq(g, time+1)]) op(time_M=20) # f[0] is time=19, f[1] is time=20 assert np.allclose(f.data[0], 19) assert np.allclose(f.data[1], 20) # g is time 15 to 21 (loop twice the 7 buffer then 15->21) for i in range(7): assert np.allclose(g.data[i], 14+i+1) class TestSubDimension(object): @pytest.mark.parametrize('opt', opts_tiling) def test_interior(self, opt): """ Tests application of an Operator consisting of a single equation over the ``interior`` subdomain. """ grid = Grid(shape=(4, 4, 4)) x, y, z = grid.dimensions interior = grid.interior u = TimeFunction(name='u', grid=grid) eqn = [Eq(u.forward, u + 2, subdomain=interior)] op = Operator(eqn, opt=opt) op.apply(time_M=2) assert np.all(u.data[1, 1:-1, 1:-1, 1:-1] == 6.) assert np.all(u.data[1, :, 0] == 0.) assert np.all(u.data[1, :, -1] == 0.) assert np.all(u.data[1, :, :, 0] == 0.) assert np.all(u.data[1, :, :, -1] == 0.) def test_domain_vs_interior(self): """ Tests application of an Operator consisting of two equations, one over the whole domain (default), and one over the ``interior`` subdomain. """ grid = Grid(shape=(4, 4, 4)) x, y, z = grid.dimensions t = grid.stepping_dim # noqa interior = grid.interior u = TimeFunction(name='u', grid=grid) # noqa eqs = [Eq(u.forward, u + 1), Eq(u.forward, u.forward + 2, subdomain=interior)] op = Operator(eqs, opt='noop') trees = retrieve_iteration_tree(op) assert len(trees) == 2 op.apply(time_M=1) assert np.all(u.data[1, 0, :, :] == 1) assert np.all(u.data[1, -1, :, :] == 1) assert np.all(u.data[1, :, 0, :] == 1) assert np.all(u.data[1, :, -1, :] == 1) assert np.all(u.data[1, :, :, 0] == 1) assert np.all(u.data[1, :, :, -1] == 1) assert np.all(u.data[1, 1:3, 1:3, 1:3] == 3) @pytest.mark.parametrize('opt', opts_tiling) def test_subdim_middle(self, opt): """ Tests that instantiating SubDimensions using the classmethod constructors works correctly. """ grid = Grid(shape=(4, 4, 4)) x, y, z = grid.dimensions t = grid.stepping_dim # noqa u = TimeFunction(name='u', grid=grid) # noqa xi = SubDimension.middle(name='xi', parent=x, thickness_left=1, thickness_right=1) eqs = [Eq(u.forward, u + 1)] eqs = [e.subs(x, xi) for e in eqs] op = Operator(eqs, opt=opt) u.data[:] = 1.0 op.apply(time_M=1) assert np.all(u.data[1, 0, :, :] == 1) assert np.all(u.data[1, -1, :, :] == 1) assert np.all(u.data[1, 1:3, :, :] == 2) def test_symbolic_size(self): """Check the symbolic size of all possible SubDimensions is as expected.""" grid = Grid(shape=(4,)) x, = grid.dimensions thickness = 4 xleft = SubDimension.left(name='xleft', parent=x, thickness=thickness) assert xleft.symbolic_size == xleft.thickness.left[0] xi = SubDimension.middle(name='xi', parent=x, thickness_left=thickness, thickness_right=thickness) assert xi.symbolic_size == (x.symbolic_max - x.symbolic_min - xi.thickness.left[0] - xi.thickness.right[0] + 1) xright = SubDimension.right(name='xright', parent=x, thickness=thickness) assert xright.symbolic_size == xright.thickness.right[0] @pytest.mark.parametrize('opt', opts_tiling) def test_bcs(self, opt): """ Tests application of an Operator consisting of multiple equations defined over different sub-regions, explicitly created through the use of SubDimensions. """ grid = Grid(shape=(20, 20)) x, y = grid.dimensions t = grid.stepping_dim thickness = 4 u = TimeFunction(name='u', save=None, grid=grid, space_order=0, time_order=1) xleft = SubDimension.left(name='xleft', parent=x, thickness=thickness) xi = SubDimension.middle(name='xi', parent=x, thickness_left=thickness, thickness_right=thickness) xright = SubDimension.right(name='xright', parent=x, thickness=thickness) yi = SubDimension.middle(name='yi', parent=y, thickness_left=thickness, thickness_right=thickness) t_in_centre = Eq(u[t+1, xi, yi], 1) leftbc = Eq(u[t+1, xleft, yi], u[t+1, xleft+1, yi] + 1) rightbc = Eq(u[t+1, xright, yi], u[t+1, xright-1, yi] + 1) op = Operator([t_in_centre, leftbc, rightbc], opt=opt) op.apply(time_m=1, time_M=1) assert np.all(u.data[0, :, 0:thickness] == 0.) assert np.all(u.data[0, :, -thickness:] == 0.) assert all(np.all(u.data[0, i, thickness:-thickness] == (thickness+1-i)) for i in range(thickness)) assert all(np.all(u.data[0, -i, thickness:-thickness] == (thickness+2-i)) for i in range(1, thickness + 1)) assert np.all(u.data[0, thickness:-thickness, thickness:-thickness] == 1.) def test_flow_detection_interior(self): """ Test detection of flow directions when SubDimensions are used (in this test they are induced by the ``interior`` subdomain). Stencil uses values at new timestep as well as those at previous ones This forces an evaluation order onto x. Weights are: x=0 x=1 x=2 x=3 t=N 2 ---3 v / t=N+1 o--+----4 Flow dependency should traverse x in the negative direction x=2 x=3 x=4 x=5 x=6 t=0 0 --- 0 -- 1 -- 0 v / v / v / t=1 44 -+--- 11 -+--- 2--+ -- 0 """ grid = Grid(shape=(10, 10)) x, y = grid.dimensions interior = grid.interior u = TimeFunction(name='u', grid=grid, save=10, time_order=1, space_order=0) step = Eq(u.forward, 2*u + 3*u.subs(x, x+x.spacing) + 4*u.forward.subs(x, x+x.spacing), subdomain=interior) op = Operator(step) u.data[0, 5, 5] = 1.0 op.apply(time_M=0) assert u.data[1, 5, 5] == 2 assert u.data[1, 4, 5] == 11 assert u.data[1, 3, 5] == 44 assert u.data[1, 2, 5] == 4*44 assert u.data[1, 1, 5] == 4*4*44 # This point isn't updated because of the `interior` selection assert u.data[1, 0, 5] == 0 assert np.all(u.data[1, 6:, :] == 0) assert np.all(u.data[1, :, 0:5] == 0) assert np.all(u.data[1, :, 6:] == 0) @pytest.mark.parametrize('exprs,expected,', [ # Carried dependence in both /t/ and /x/ (['Eq(u[t+1, x, y], u[t+1, x-1, y] + u[t, x, y])'], 'y'), (['Eq(u[t+1, x, y], u[t+1, x-1, y] + u[t, x, y], subdomain=interior)'], 'i0y'), # Carried dependence in both /t/ and /y/ (['Eq(u[t+1, x, y], u[t+1, x, y-1] + u[t, x, y])'], 'x'), (['Eq(u[t+1, x, y], u[t+1, x, y-1] + u[t, x, y], subdomain=interior)'], 'i0x'), # Carried dependence in /y/, leading to separate /y/ loops, one # going forward, the other backward (['Eq(u[t+1, x, y], u[t+1, x, y-1] + u[t, x, y], subdomain=interior)', 'Eq(u[t+1, x, y], u[t+1, x, y+1] + u[t, x, y], subdomain=interior)'], 'i0x'), ]) def test_iteration_property_parallel(self, exprs, expected): """Tests detection of sequental and parallel Iterations when applying equations over different subdomains.""" grid = Grid(shape=(20, 20)) x, y = grid.dimensions # noqa t = grid.time_dim # noqa interior = grid.interior # noqa u = TimeFunction(name='u', grid=grid, save=10, time_order=1) # noqa # List comprehension would need explicit locals/globals mappings to eval for i, e in enumerate(list(exprs)): exprs[i] = eval(e) op = Operator(exprs, opt='noop') iterations = FindNodes(Iteration).visit(op) assert all(i.is_Sequential for i in iterations if i.dim.name != expected) assert all(i.is_Parallel for i in iterations if i.dim.name == expected) @skipif(['device']) @pytest.mark.parametrize('exprs,expected,', [ # All parallel, the innermost Iteration gets vectorized (['Eq(u[time, x, yleft], u[time, x, yleft] + 1.)'], ['yleft']), # All outers are parallel, carried dependence in `yleft`, so the middle # Iteration over `x` gets vectorized (['Eq(u[time, x, yleft], u[time, x, yleft+1] + 1.)'], ['x']), # Only the middle Iteration is parallel, so no vectorization (the Iteration # is left non-vectorised for OpenMP parallelism) (['Eq(u[time+1, x, yleft], u[time, x, yleft+1] + u[time+1, x, yleft+1])'], []) ]) def test_iteration_property_vector(self, exprs, expected): """Tests detection of vector Iterations when using subdimensions.""" grid = Grid(shape=(20, 20)) x, y = grid.dimensions # noqa time = grid.time_dim # noqa # The leftmost 10 elements yleft = SubDimension.left(name='yleft', parent=y, thickness=10) # noqa u = TimeFunction(name='u', grid=grid, save=10, time_order=0, space_order=1) # noqa # List comprehension would need explicit locals/globals mappings to eval for i, e in enumerate(list(exprs)): exprs[i] = eval(e) op = Operator(exprs, opt='simd') iterations = FindNodes(Iteration).visit(op) vectorized = [i.dim.name for i in iterations if i.is_Vectorized] assert set(vectorized) == set(expected) @pytest.mark.parametrize('opt', opts_tiling) def test_subdimmiddle_parallel(self, opt): """ Tests application of an Operator consisting of a subdimension defined over different sub-regions, explicitly created through the use of SubDimensions. """ grid = Grid(shape=(20, 20)) x, y = grid.dimensions t = grid.stepping_dim thickness = 4 u = TimeFunction(name='u', save=None, grid=grid, space_order=0, time_order=1) xi = SubDimension.middle(name='xi', parent=x, thickness_left=thickness, thickness_right=thickness) yi = SubDimension.middle(name='yi', parent=y, thickness_left=thickness, thickness_right=thickness) # a 5 point stencil that can be computed in parallel centre = Eq(u[t+1, xi, yi], u[t, xi, yi] + u[t, xi-1, yi] + u[t, xi+1, yi] + u[t, xi, yi-1] + u[t, xi, yi+1]) u.data[0, 10, 10] = 1.0 op = Operator([centre], opt=opt) print(op.ccode) iterations = FindNodes(Iteration).visit(op) assert all(i.is_Affine and i.is_Parallel for i in iterations if i.dim in [xi, yi]) op.apply(time_m=0, time_M=0) assert np.all(u.data[1, 9:12, 10] == 1.0) assert np.all(u.data[1, 10, 9:12] == 1.0) # Other than those, it should all be 0 u.data[1, 9:12, 10] = 0.0 u.data[1, 10, 9:12] = 0.0 assert np.all(u.data[1, :] == 0) def test_subdimleft_parallel(self): """ Tests application of an Operator consisting of a subdimension defined over different sub-regions, explicitly created through the use of SubDimensions. This tests that flow direction is not being automatically inferred from whether the subdimension is on the left or right boundary. """ grid = Grid(shape=(20, 20)) x, y = grid.dimensions t = grid.stepping_dim thickness = 4 u = TimeFunction(name='u', save=None, grid=grid, space_order=0, time_order=1) xl = SubDimension.left(name='xl', parent=x, thickness=thickness) yi = SubDimension.middle(name='yi', parent=y, thickness_left=thickness, thickness_right=thickness) # Can be done in parallel eq = Eq(u[t+1, xl, yi], u[t, xl, yi] + 1) op = Operator([eq]) iterations = FindNodes(Iteration).visit(op) assert all(i.is_Affine and i.is_Parallel for i in iterations if i.dim in [xl, yi]) op.apply(time_m=0, time_M=0) assert np.all(u.data[1, 0:thickness, 0:thickness] == 0) assert np.all(u.data[1, 0:thickness, -thickness:] == 0) assert np.all(u.data[1, 0:thickness, thickness:-thickness] == 1) assert np.all(u.data[1, thickness+1:, :] == 0) def test_subdimmiddle_notparallel(self): """ Tests application of an Operator consisting of a subdimension defined over different sub-regions, explicitly created through the use of SubDimensions. Different from ``test_subdimmiddle_parallel`` because an interior dimension cannot be evaluated in parallel. """ grid = Grid(shape=(20, 20)) x, y = grid.dimensions t = grid.stepping_dim thickness = 4 u = TimeFunction(name='u', save=None, grid=grid, space_order=0, time_order=1) xi = SubDimension.middle(name='xi', parent=x, thickness_left=thickness, thickness_right=thickness) yi = SubDimension.middle(name='yi', parent=y, thickness_left=thickness, thickness_right=thickness) # flow dependencies in x and y which should force serial execution # in reverse direction centre = Eq(u[t+1, xi, yi], u[t, xi, yi] + u[t+1, xi+1, yi+1]) u.data[0, 10, 10] = 1.0 op = Operator([centre]) iterations = FindNodes(Iteration).visit(op) assert all(i.is_Affine and i.is_Sequential for i in iterations if i.dim == xi) assert all(i.is_Affine and i.is_Parallel for i in iterations if i.dim == yi) op.apply(time_m=0, time_M=0) for i in range(4, 11): assert u.data[1, i, i] == 1.0 u.data[1, i, i] = 0.0 assert np.all(u.data[1, :] == 0) def test_subdimleft_notparallel(self): """ Tests application of an Operator consisting of a subdimension defined over different sub-regions, explicitly created through the use of SubDimensions. This tests that flow direction is not being automatically inferred from whether the subdimension is on the left or right boundary. """ grid = Grid(shape=(20, 20)) x, y = grid.dimensions t = grid.stepping_dim thickness = 4 u = TimeFunction(name='u', save=None, grid=grid, space_order=1, time_order=0) xl = SubDimension.left(name='xl', parent=x, thickness=thickness) yi = SubDimension.middle(name='yi', parent=y, thickness_left=thickness, thickness_right=thickness) # Flows inward (i.e. forward) rather than outward eq = Eq(u[t+1, xl, yi], u[t+1, xl-1, yi] + 1) op = Operator([eq]) iterations = FindNodes(Iteration).visit(op) assert all(i.is_Affine and i.is_Sequential for i in iterations if i.dim == xl) assert all(i.is_Affine and i.is_Parallel for i in iterations if i.dim == yi) op.apply(time_m=1, time_M=1) assert all(np.all(u.data[0, :thickness, thickness+i] == [1, 2, 3, 4]) for i in range(12)) assert np.all(u.data[0, thickness:] == 0) assert np.all(u.data[0, :, thickness+12:] == 0) def test_subdim_fd(self): """ Test that the FD shortcuts are handled correctly with SubDimensions """ grid = Grid(shape=(20, 20)) x, y = grid.dimensions u = TimeFunction(name='u', save=None, grid=grid, space_order=1, time_order=1) u.data[:] = 2. # Flows inward (i.e. forward) rather than outward eq = [Eq(u.forward, u.dx + u.dy, subdomain=grid.interior)] op = Operator(eq) op.apply(time_M=0) assert np.all(u.data[1, -1, :] == 2.) assert np.all(u.data[1, :, 0] == 2.) assert np.all(u.data[1, :, -1] == 2.) assert np.all(u.data[1, 0, :] == 2.) assert np.all(u.data[1, 1:18, 1:18] == 0.) def test_arrays_defined_over_subdims(self): """ Check code generation when an Array uses a SubDimension. """ grid = Grid(shape=(3,)) x, = grid.dimensions xi, = grid.interior.dimensions f = Function(name='f', grid=grid) a = Array(name='a', dimensions=(xi,), dtype=grid.dtype) op = Operator([Eq(a[xi], 1), Eq(f, f + a[xi + 1], subdomain=grid.interior)], openmp=False) assert len(op.parameters) == 6 # neither `x_size` nor `xi_size` are expected here assert not any(i.name in ('x_size', 'xi_size') for i in op.parameters) # Try running it -- regardless of what it will produce, this should run # ie, this checks this error isn't raised: # "ValueError: No value found for parameter xi_size" op() @pytest.mark.parametrize('opt', opts_tiling) def test_expandingbox_like(self, opt): """ Make sure SubDimensions aren't an obstacle to expanding boxes. """ grid = Grid(shape=(8, 8)) x, y = grid.dimensions u = TimeFunction(name='u', grid=grid) xi = SubDimension.middle(name='xi', parent=x, thickness_left=2, thickness_right=2) yi = SubDimension.middle(name='yi', parent=y, thickness_left=2, thickness_right=2) eqn = Eq(u.forward, u + 1) eqn = eqn.subs({x: xi, y: yi}) op = Operator(eqn, opt=opt) op.apply(time=3, x_m=2, x_M=5, y_m=2, y_M=5, xi_ltkn=0, xi_rtkn=0, yi_ltkn=0, yi_rtkn=0) assert np.all(u.data[0, 2:-2, 2:-2] == 4.) assert np.all(u.data[1, 2:-2, 2:-2] == 3.) assert np.all(u.data[:, :2] == 0.) assert np.all(u.data[:, -2:] == 0.) assert np.all(u.data[:, :, :2] == 0.) assert np.all(u.data[:, :, -2:] == 0.) class TestConditionalDimension(object): """ A collection of tests to check the correct functioning of ConditionalDimensions. """ def test_basic(self): nt = 19 grid = Grid(shape=(11, 11)) time = grid.time_dim u = TimeFunction(name='u', grid=grid) assert(grid.stepping_dim in u.indices) u2 = TimeFunction(name='u2', grid=grid, save=nt) assert(time in u2.indices) factor = 4 time_subsampled = ConditionalDimension('t_sub', parent=time, factor=factor) usave = TimeFunction(name='usave', grid=grid, save=(nt+factor-1)//factor, time_dim=time_subsampled) assert(time_subsampled in usave.indices) eqns = [Eq(u.forward, u + 1.), Eq(u2.forward, u2 + 1.), Eq(usave, u)] op = Operator(eqns) op.apply(t_M=nt-2) assert np.all(np.allclose(u.data[(nt-1) % 3], nt-1)) assert np.all([np.allclose(u2.data[i], i) for i in range(nt)]) assert np.all([np.allclose(usave.data[i], i*factor) for i in range((nt+factor-1)//factor)]) def test_basic_shuffles(self): """ Like ``test_basic``, but with different equation orderings. Nevertheless, we assert against the same exact values as in ``test_basic``, since we save `u`, not `u.forward`. """ nt = 19 grid = Grid(shape=(11, 11)) time = grid.time_dim u = TimeFunction(name='u', grid=grid) u2 = TimeFunction(name='u2', grid=grid, save=nt) factor = 4 time_subsampled = ConditionalDimension('t_sub', parent=time, factor=factor) usave = TimeFunction(name='usave', grid=grid, save=(nt+factor-1)//factor, time_dim=time_subsampled) # Shuffle 1 eqns = [Eq(usave, u), Eq(u.forward, u + 1.), Eq(u2.forward, u2 + 1.)] op = Operator(eqns) op.apply(t_M=nt-2) assert np.all(np.allclose(u.data[(nt-1) % 3], nt-1)) assert np.all([np.allclose(u2.data[i], i) for i in range(nt)]) assert np.all([np.allclose(usave.data[i], i*factor) for i in range((nt+factor-1)//factor)]) # Shuffle 2 usave.data[:] = 0. u.data[:] = 0. u2.data[:] = 0. eqns = [Eq(u.forward, u + 1.), Eq(usave, u), Eq(u2.forward, u2 + 1.)] op = Operator(eqns) op.apply(t_M=nt-2) assert np.all(np.allclose(u.data[(nt-1) % 3], nt-1)) assert np.all([np.allclose(u2.data[i], i) for i in range(nt)]) assert np.all([np.allclose(usave.data[i], i*factor) for i in range((nt+factor-1)//factor)]) @pytest.mark.parametrize('opt', opts_tiling) def test_spacial_subsampling(self, opt): """ Test conditional dimension for the spatial ones. This test saves u every two grid points : u2[x, y] = u[2*x, 2*y] """ nt = 19 grid = Grid(shape=(11, 11)) time = grid.time_dim u = TimeFunction(name='u', grid=grid, save=nt) assert(grid.time_dim in u.indices) # Creates subsampled spatial dimensions and accordine grid dims = tuple([ConditionalDimension(d.name+'sub', parent=d, factor=2) for d in u.grid.dimensions]) grid2 = Grid((6, 6), dimensions=dims, time_dimension=time) u2 = TimeFunction(name='u2', grid=grid2, save=nt) assert(time in u2.indices) eqns = [Eq(u.forward, u + 1.), Eq(u2, u)] op = Operator(eqns, opt=opt) op.apply(time_M=nt-2) # Verify that u2[x,y]= u[2*x, 2*y] assert np.allclose(u.data[:-1, 0::2, 0::2], u2.data[:-1, :, :]) def test_time_subsampling_fd(self): nt = 19 grid = Grid(shape=(11, 11)) x, y = grid.dimensions time = grid.time_dim factor = 4 time_subsampled = ConditionalDimension('t_sub', parent=time, factor=factor) usave = TimeFunction(name='usave', grid=grid, save=(nt+factor-1)//factor, time_dim=time_subsampled, time_order=2) dx2 = [indexify(i) for i in retrieve_functions(usave.dt2.evaluate)] assert dx2 == [usave[time_subsampled - 1, x, y], usave[time_subsampled + 1, x, y], usave[time_subsampled, x, y]] def test_issue_1592(self): grid = Grid(shape=(11, 11)) time = grid.time_dim time_sub = ConditionalDimension('t_sub', parent=time, factor=2) v = TimeFunction(name="v", grid=grid, space_order=4, time_dim=time_sub, save=5) w = Function(name="w", grid=grid, space_order=4) Operator(Eq(w, v.dx))(time=6) op = Operator(Eq(v.forward, v.dx)) op.apply(time=6) exprs = FindNodes(Expression).visit(op) assert exprs[-1].expr.lhs.indices[0] == IntDiv(time, 2) + 1 def test_subsampled_fd(self): """ Test that the FD shortcuts are handled correctly with ConditionalDimensions """ grid = Grid(shape=(11, 11)) time = grid.time_dim # Creates subsampled spatial dimensions and accordine grid dims = tuple([ConditionalDimension(d.name+'sub', parent=d, factor=2) for d in grid.dimensions]) grid2 = Grid((6, 6), dimensions=dims, time_dimension=time) u2 = TimeFunction(name='u2', grid=grid2, space_order=2, time_order=1) u2.data.fill(2.) eqns = [Eq(u2.forward, u2.dx + u2.dy)] op = Operator(eqns) op.apply(time_M=0, x_M=11, y_M=11) # Verify that u2 contains subsampled fd values assert np.all(u2.data[0, :, :] == 2.) assert np.all(u2.data[1, 0, 0] == 0.) assert np.all(u2.data[1, -1, -1] == -20.) assert np.all(u2.data[1, 0, -1] == -10.) assert np.all(u2.data[1, -1, 0] == -10.) assert np.all(u2.data[1, 1:-1, 0] == 0.) assert np.all(u2.data[1, 0, 1:-1] == 0.) assert np.all(u2.data[1, 1:-1, -1] == -10.) assert np.all(u2.data[1, -1, 1:-1] == -10.) assert np.all(u2.data[1, 1:4, 1:4] == 0.) # This test generates an openmp loop form which makes older gccs upset @switchconfig(openmp=False) def test_nothing_in_negative(self): """Test the case where when the condition is false, there is nothing to do.""" nt = 4 grid = Grid(shape=(11, 11)) time = grid.time_dim u = TimeFunction(name='u', save=nt, grid=grid) assert(grid.time_dim in u.indices) factor = 4 time_subsampled = ConditionalDimension('t_sub', parent=time, factor=factor) usave = TimeFunction(name='usave', grid=grid, save=(nt+factor-1)//factor, time_dim=time_subsampled) assert(time_subsampled in usave.indices) eqns = [Eq(usave, u)] op = Operator(eqns) u.data[:] = 1.0 usave.data[:] = 0.0 op.apply(time_m=1, time_M=1) assert np.allclose(usave.data, 0.0) op.apply(time_m=0, time_M=0) assert np.allclose(usave.data, 1.0) def test_laplace(self): grid = Grid(shape=(20, 20, 20)) x, y, z = grid.dimensions time = grid.time_dim t = grid.stepping_dim tsave = ConditionalDimension(name='tsave', parent=time, factor=2) u = TimeFunction(name='u', grid=grid, save=None, time_order=2) usave = TimeFunction(name='usave', grid=grid, time_dim=tsave, time_order=0, space_order=0) steps = [] # save of snapshot steps.append(Eq(usave, u)) # standard laplace-like thing steps.append(Eq(u[t+1, x, y, z], u[t, x, y, z] - u[t-1, x, y, z] + u[t, x-1, y, z] + u[t, x+1, y, z] + u[t, x, y-1, z] + u[t, x, y+1, z] + u[t, x, y, z-1] + u[t, x, y, z+1])) op = Operator(steps) u.data[:] = 0.0 u.data[0, 10, 10, 10] = 1.0 op.apply(time_m=0, time_M=0) assert np.sum(u.data[0, :, :, :]) == 1.0 assert np.sum(u.data[1, :, :, :]) == 7.0 assert np.all(usave.data[0, :, :, :] == u.data[0, :, :, :]) def test_as_expr(self): nt = 19 grid = Grid(shape=(11, 11)) time = grid.time_dim u = TimeFunction(name='u', grid=grid) assert(grid.stepping_dim in u.indices) u2 = TimeFunction(name='u2', grid=grid, save=nt) assert(time in u2.indices) factor = 4 time_subsampled = ConditionalDimension('t_sub', parent=time, factor=factor) usave = TimeFunction(name='usave', grid=grid, save=(nt+factor-1)//factor, time_dim=time_subsampled) assert(time_subsampled in usave.indices) eqns = [Eq(u.forward, u + 1.), Eq(u2.forward, u2 + 1.), Eq(usave, time_subsampled * u)] op = Operator(eqns) op.apply(t=nt-2) assert np.all(np.allclose(u.data[(nt-1) % 3], nt-1)) assert np.all([np.allclose(u2.data[i], i) for i in range(nt)]) assert np.all([np.allclose(usave.data[i], i*factor*i) for i in range((nt+factor-1)//factor)]) def test_shifted(self): nt = 19 grid = Grid(shape=(11, 11)) time = grid.time_dim u = TimeFunction(name='u', grid=grid) assert(grid.stepping_dim in u.indices) u2 = TimeFunction(name='u2', grid=grid, save=nt) assert(time in u2.indices) factor = 4 time_subsampled = ConditionalDimension('t_sub', parent=time, factor=factor) usave = TimeFunction(name='usave', grid=grid, save=2, time_dim=time_subsampled) assert(time_subsampled in usave.indices) t_sub_shift = Constant(name='t_sub_shift', dtype=np.int32) eqns = [Eq(u.forward, u + 1.), Eq(u2.forward, u2 + 1.), Eq(usave.subs(time_subsampled, time_subsampled - t_sub_shift), u)] op = Operator(eqns) # Starting at time_m=10, so time_subsampled - t_sub_shift is in range op.apply(time_m=10, time_M=nt-2, t_sub_shift=3) assert np.all(np.allclose(u.data[0], 8)) assert np.all([np.allclose(u2.data[i], i - 10) for i in range(10, nt)]) assert np.all([np.allclose(usave.data[i], 2+i*factor) for i in range(2)]) def test_no_index(self): """Test behaviour when the ConditionalDimension is used as a symbol in an expression.""" nt = 19 grid = Grid(shape=(11, 11)) time = grid.time_dim u = TimeFunction(name='u', grid=grid) assert(grid.stepping_dim in u.indices) v = Function(name='v', grid=grid) factor = 4 time_subsampled = ConditionalDimension('t_sub', parent=time, factor=factor) eqns = [Eq(u.forward, u + 1), Eq(v, v + u*u*time_subsampled)] op = Operator(eqns) op.apply(t_M=nt-2) assert np.all(np.allclose(u.data[(nt-1) % 3], nt-1)) # expected result is 1024 # v = u[0]**2 * 0 + u[4]**2 * 1 + u[8]**2 * 2 + u[12]**2 * 3 + u[16]**2 * 4 # with u[t] = t # v = 16 * 1 + 64 * 2 + 144 * 3 + 256 * 4 = 1600 assert np.all(np.allclose(v.data, 1600)) def test_no_index_sparse(self): """Test behaviour when the ConditionalDimension is used as a symbol in an expression over sparse data objects.""" grid = Grid(shape=(4, 4), extent=(3.0, 3.0)) time = grid.time_dim f = TimeFunction(name='f', grid=grid, save=1) f.data[:] = 0. coordinates = [(0.5, 0.5), (0.5, 2.5), (2.5, 0.5), (2.5, 2.5)] sf = SparseFunction(name='sf', grid=grid, npoint=4, coordinates=coordinates) sf.data[:] = 1. sd = sf.dimensions[sf._sparse_position] # We want to write to `f` through `sf` so that we obtain the # following 4x4 grid (the '*' show the position of the sparse points) # We do that by emulating an injection # # 0 --- 0 --- 0 --- 0 # | * | | * | # 0 --- 1 --- 1 --- 0 # | | | | # 0 --- 1 --- 1 --- 0 # | * | | * | # 0 --- 0 --- 0 --- 0 radius = 1 indices = [(i, i+radius) for i in sf._coordinate_indices] bounds = [i.symbolic_size - radius for i in grid.dimensions] eqs = [] for e, i in enumerate(product(*indices)): args = [j > 0 for j in i] args.extend([j < k for j, k in zip(i, bounds)]) condition = And(*args, evaluate=False) cd = ConditionalDimension('sfc%d' % e, parent=sd, condition=condition) index = [time] + list(i) eqs.append(Eq(f[index], f[index] + sf[cd])) op = Operator(eqs) op.apply(time=0) assert np.all(f.data[0, 1:-1, 1:-1] == 1.) assert np.all(f.data[0, 0] == 0.) assert np.all(f.data[0, -1] == 0.) assert np.all(f.data[0, :, 0] == 0.) assert np.all(f.data[0, :, -1] == 0.) def test_symbolic_factor(self): """ Test ConditionalDimension with symbolic factor (provided as a Constant). """ g = Grid(shape=(4, 4, 4)) u = TimeFunction(name='u', grid=g, time_order=0) fact = Constant(name='fact', dtype=np.int32, value=4) tsub = ConditionalDimension(name='tsub', parent=g.time_dim, factor=fact) usave = TimeFunction(name='usave', grid=g, time_dim=tsub, save=4) op = Operator([Eq(u, u + 1), Eq(usave, u)]) op.apply(time=7) # Use `fact`'s default value, 4 assert np.all(usave.data[0] == 1) assert np.all(usave.data[1] == 5) u.data[:] = 0. op.apply(time=7, fact=2) assert np.all(usave.data[0] == 1) assert np.all(usave.data[1] == 3) assert np.all(usave.data[2] == 5) assert np.all(usave.data[3] == 7) def test_implicit_dims(self): """ Test ConditionalDimension as an implicit dimension for an equation. """ # This test makes an Operator that should create a vector of increasing # integers, but stop incrementing when a certain stop value is reached shape = (50,) stop_value = 20 time = Dimension(name='time') f = TimeFunction(name='f', shape=shape, dimensions=[time]) # The condition to stop incrementing cond = ConditionalDimension(name='cond', parent=time, condition=f[time] < stop_value) eqs = [Eq(f.forward, f), Eq(f.forward, f.forward + 1, implicit_dims=[cond])] op = Operator(eqs) op.apply(time_M=shape[0] - 2) # Make the same calculation in python to assert the result F = np.zeros(shape[0]) for i in range(shape[0]): F[i] = i if i < stop_value else stop_value assert np.all(f.data == F) def test_grouping(self): """ Test that Clusters over the same set of ConditionalDimensions fall within the same Conditional. This is a follow up to issue #1610. """ grid = Grid(shape=(10, 10)) time = grid.time_dim cond = ConditionalDimension(name='cond', parent=time, condition=time < 5) u = TimeFunction(name='u', grid=grid, space_order=4) # We use a SubDomain only to keep the two Eqs separated eqns = [Eq(u.forward, u + 1, subdomain=grid.interior), Eq(u.forward, u.dx.dx + 1., implicit_dims=[cond])] op = Operator(eqns, opt=('advanced-fsg', {'cire-mincost-sops': 1})) conds = FindNodes(Conditional).visit(op) assert len(conds) == 1 assert len(retrieve_iteration_tree(conds[0].then_body)) == 2 def test_stepping_dim_in_condition_lowering(self): """ Check that the compiler performs lowering on conditions with TimeDimensions and generates the expected code:: if (g[t][x + 1][y + 1] <= 10){ if (g[t0][x + 1][y + 1] <= 10){ ... --> ... } } This test increments a function by one at every timestep until it is less-or-equal to 10 (g<=10) while although operator runs for 13 timesteps. """ grid = Grid(shape=(4, 4)) _, y = grid.dimensions ths = 10 g = TimeFunction(name='g', grid=grid) ci = ConditionalDimension(name='ci', parent=y, condition=Le(g, ths)) op = Operator(Eq(g.forward, g + 1, implicit_dims=ci)) op.apply(time_M=ths+3) assert np.all(g.data[0, :, :] == ths) assert np.all(g.data[1, :, :] == ths + 1) assert 'if (g[t0][x + 1][y + 1] <= 10)\n' '{\n g[t1][x + 1][y + 1] = g[t0][x + 1][y + 1] + 1' in str(op.ccode) def test_expr_like_lowering(self): """ Test the lowering of an expr-like ConditionalDimension's condition. This test makes an Operator that should indexify and lower the condition passed in the Conditional Dimension """ grid = Grid(shape=(3, 3)) g1 = Function(name='g1', grid=grid) g2 = Function(name='g2', grid=grid) g1.data[:] = 0.49 g2.data[:] = 0.49 x, y = grid.dimensions ci = ConditionalDimension(name='ci', parent=y, condition=Le((g1 + g2), 1.01*(g1 + g2))) f = Function(name='f', shape=grid.shape, dimensions=(x, ci)) Operator(Eq(f, g1+g2)).apply() assert np.all(f.data[:] == g1.data[:] + g2.data[:]) @pytest.mark.parametrize('setup_rel, rhs, c1, c2, c3, c4', [ # Relation, RHS, c1 to c4 used as indexes in assert (Lt, 3, 2, 4, 4, -1), (Le, 2, 2, 4, 4, -1), (Ge, 3, 4, 6, 1, 4), (Gt, 2, 4, 6, 1, 4), (Ne, 5, 2, 6, 1, 2) ]) def test_relational_classes(self, setup_rel, rhs, c1, c2, c3, c4): """ Test ConditionalDimension using conditions based on Relations over SubDomains. """ class InnerDomain(SubDomain): name = 'inner' def define(self, dimensions): return {d: ('middle', 2, 2) for d in dimensions} inner_domain = InnerDomain() grid = Grid(shape=(8, 8), subdomains=(inner_domain,)) g = Function(name='g', grid=grid) g2 = Function(name='g2', grid=grid) for i in [g, g2]: i.data[:4, :4] = 1 i.data[4:, :4] = 2 i.data[4:, 4:] = 3 i.data[:4, 4:] = 4 xi, yi = grid.subdomains['inner'].dimensions cond = setup_rel(0.25*g + 0.75*g2, rhs, subdomain=grid.subdomains['inner']) ci = ConditionalDimension(name='ci', parent=yi, condition=cond) f = Function(name='f', shape=grid.shape, dimensions=(xi, ci)) eq1 = Eq(f, 0.4*g + 0.6*g2) eq2 = Eq(f, 5) Operator([eq1, eq2]).apply() assert np.all(f.data[2:6, c1:c2] == 5.) assert np.all(f.data[:, c3:c4] < 5.) def test_from_cond_to_param(self): """ Test that Functions appearing in the condition of a ConditionalDimension but not explicitly in an Eq are actually part of the Operator input (stems from issue #1298). """ grid = Grid(shape=(8, 8)) x, y = grid.dimensions g = Function(name='g', grid=grid) h = Function(name='h', grid=grid) ci = ConditionalDimension(name='ci', parent=y, condition=Lt(g, 2 + h)) f = Function(name='f', shape=grid.shape, dimensions=(x, ci)) for _ in range(5): # issue #1298 was non deterministic Operator(Eq(f, 5)).apply() @skipif('device') def test_no_fusion_simple(self): """ If ConditionalDimensions are present, then Clusters must not be fused so that ultimately Eqs get scheduled to different loop nests. """ grid = Grid(shape=(4, 4, 4)) time = grid.time_dim f = TimeFunction(name='f', grid=grid) g = Function(name='g', grid=grid) h = Function(name='h', grid=grid) # No ConditionalDimensions yet. Will be fused and optimized eqns = [Eq(f.forward, f + 1), Eq(h, f + 1), Eq(g, f + 1)] op = Operator(eqns) exprs = FindNodes(Expression).visit(op._func_table['bf0'].root) assert len(exprs) == 4 assert exprs[1].expr.rhs is exprs[0].output assert exprs[2].expr.rhs is exprs[0].output assert exprs[3].expr.rhs is exprs[0].output # Now with a ConditionalDimension. No fusion, no optimization ctime = ConditionalDimension(name='ctime', parent=time, condition=time > 4) eqns = [Eq(f.forward, f + 1), Eq(h, f + 1), Eq(g, f + 1, implicit_dims=[ctime])] op = Operator(eqns) exprs = FindNodes(Expression).visit(op._func_table['bf0'].root) assert len(exprs) == 3 assert exprs[1].expr.rhs is exprs[0].output assert exprs[2].expr.rhs is exprs[0].output exprs = FindNodes(Expression).visit(op._func_table['bf1'].root) assert len(exprs) == 1 @skipif('device') def test_no_fusion_convoluted(self): """ Conceptually like `test_no_fusion_simple`, but with more expressions and non-trivial data flow. """ grid = Grid(shape=(4, 4, 4)) time = grid.time_dim f = TimeFunction(name='f', grid=grid) g = Function(name='g', grid=grid) h = Function(name='h', grid=grid) ctime = ConditionalDimension(name='ctime', parent=time, condition=time > 4) eqns = [Eq(f.forward, f + 1), Eq(h, f + 1), Eq(g, f + 1, implicit_dims=[ctime]), Eq(f.forward, f + 1, implicit_dims=[ctime]), Eq(f.forward, f + 1), Eq(g, f + 1)] op = Operator(eqns) exprs = FindNodes(Expression).visit(op._func_table['bf0'].root) assert len(exprs) == 3 assert exprs[1].expr.rhs is exprs[0].output assert exprs[2].expr.rhs is exprs[0].output exprs = FindNodes(Expression).visit(op._func_table['bf1'].root) assert len(exprs) == 3 exprs = FindNodes(Expression).visit(op._func_table['bf2'].root) assert len(exprs) == 3 assert exprs[1].expr.rhs is exprs[0].output assert exprs[2].expr.rhs is exprs[0].output def test_affiness(self): """ Test for issue #1616. """ nt = 19 grid = Grid(shape=(11, 11)) time = grid.time_dim factor = 4 time_subsampled = ConditionalDimension('t_sub', parent=time, factor=factor) u = TimeFunction(name='u', grid=grid) usave = TimeFunction(name='usave', grid=grid, save=(nt+factor-1)//factor, time_dim=time_subsampled) eqns = [Eq(u.forward, u + 1.), Eq(usave, u)] op = Operator(eqns) iterations = [i for i in FindNodes(Iteration).visit(op) if i.dim is not time] assert all(i.is_Affine for i in iterations) class TestMashup(object): """ Check the correct functioning of the compiler in presence of many Dimension types. """ def test_topofusion_w_subdims_conddims(self): """ Check that topological fusion works across guarded Clusters over different iteration spaces and in presence of anti-dependences. This test uses both SubDimensions (via SubDomains) and ConditionalDimensions. """ grid = Grid(shape=(4, 4, 4)) time = grid.time_dim f = TimeFunction(name='f', grid=grid, time_order=2) g = TimeFunction(name='g', grid=grid, time_order=2) h = TimeFunction(name='h', grid=grid, time_order=2) fsave = TimeFunction(name='fsave', grid=grid, time_order=2, save=5) gsave = TimeFunction(name='gsave', grid=grid, time_order=2, save=5) ctime = ConditionalDimension(name='ctime', parent=time, condition=time > 4) eqns = [Eq(f.forward, f + 1), Eq(g.forward, g + 1), Eq(fsave, f.dt2, implicit_dims=[ctime]), Eq(h, f + g, subdomain=grid.interior), Eq(gsave, g.dt2, implicit_dims=[ctime])] op = Operator(eqns) # Check generated code -- expect the gsave equation to be scheduled together # in the same loop nest with the fsave equation assert len(op._func_table) == 3 exprs = FindNodes(Expression).visit(op._func_table['bf0'].root) assert len(exprs) == 2 assert exprs[0].write is f assert exprs[1].write is g exprs = FindNodes(Expression).visit(op._func_table['bf1'].root) assert len(exprs) == 3 assert exprs[1].write is fsave assert exprs[2].write is gsave exprs = FindNodes(Expression).visit(op._func_table['bf2'].root) assert len(exprs) == 1 assert exprs[0].write is h def test_topofusion_w_subdims_conddims_v2(self): """ Like `test_topofusion_w_subdims_conddims` but with more SubDomains, so we expect fewer loop nests. """ grid = Grid(shape=(4, 4, 4)) time = grid.time_dim f = TimeFunction(name='f', grid=grid, time_order=2) g = TimeFunction(name='g', grid=grid, time_order=2) h = TimeFunction(name='h', grid=grid, time_order=2) fsave = TimeFunction(name='fsave', grid=grid, time_order=2, save=5) gsave = TimeFunction(name='gsave', grid=grid, time_order=2, save=5) ctime = ConditionalDimension(name='ctime', parent=time, condition=time > 4) eqns = [Eq(f.forward, f + 1, subdomain=grid.interior), Eq(g.forward, g + 1, subdomain=grid.interior), Eq(fsave, f.dt2, implicit_dims=[ctime]), Eq(h, f + g, subdomain=grid.interior), Eq(gsave, g.dt2, implicit_dims=[ctime])] op = Operator(eqns) # Check generated code -- expect the gsave equation to be scheduled together # in the same loop nest with the fsave equation assert len(op._func_table) == 2 assert len(FindNodes(Expression).visit(op._func_table['bf0'].root)) == 3 assert len(FindNodes(Expression).visit(op._func_table['bf1'].root)) == 2 + 1 # r0 def test_topofusion_w_subdims_conddims_v3(self): """ Like `test_topofusion_w_subdims_conddims_v2` but with an extra anti-dependence, which causes scheduling over more loop nests. """ grid = Grid(shape=(4, 4, 4)) time = grid.time_dim f = TimeFunction(name='f', grid=grid, time_order=2) g = TimeFunction(name='g', grid=grid, time_order=2) h = TimeFunction(name='h', grid=grid, time_order=2) fsave = TimeFunction(name='fsave', grid=grid, time_order=2, save=5) gsave = TimeFunction(name='gsave', grid=grid, time_order=2, save=5) ctime = ConditionalDimension(name='ctime', parent=time, condition=time > 4) eqns = [Eq(f.forward, f + 1, subdomain=grid.interior), Eq(g.forward, g + 1, subdomain=grid.interior), Eq(fsave, f.dt2, implicit_dims=[ctime]), Eq(h, f.dt2.dx + g, subdomain=grid.interior), Eq(gsave, g.dt2, implicit_dims=[ctime])] op = Operator(eqns) # Check generated code -- expect the gsave equation to be scheduled together # in the same loop nest with the fsave equation assert len(op._func_table) == 3 exprs = FindNodes(Expression).visit(op._func_table['bf0'].root) assert len(exprs) == 2 assert exprs[0].write is f assert exprs[1].write is g exprs = FindNodes(Expression).visit(op._func_table['bf1'].root) assert len(exprs) == 3 assert exprs[1].write is fsave assert exprs[2].write is gsave exprs = FindNodes(Expression).visit(op._func_table['bf2'].root) assert len(exprs) == 2 assert exprs[1].write is h
# Copyright 2013-2014 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test mongo using the synchronizer, i.e. as it would be used by an user """ import time import os import sys if sys.version_info[:2] == (2, 6): import unittest2 as unittest else: import unittest sys.path[0:0] = [""] from pymongo import MongoClient from tests import mongo_host, STRESS_COUNT from tests.setup_cluster import (start_replica_set, kill_replica_set, start_mongo_proc, restart_mongo_proc, kill_mongo_proc) from mongo_connector.doc_managers.mongo_doc_manager import DocManager from mongo_connector.connector import Connector from mongo_connector.util import retry_until_ok from pymongo.errors import OperationFailure, AutoReconnect from tests.util import assert_soon class TestSynchronizer(unittest.TestCase): """ Tests the mongo instance """ @classmethod def setUpClass(cls): try: os.unlink("config.txt") except OSError: pass open("config.txt", "w").close() cls.standalone_port = start_mongo_proc(options=['--nojournal', '--noprealloc']) cls.mongo_doc = DocManager('%s:%d' % (mongo_host, cls.standalone_port)) cls.mongo_doc._remove() _, cls.secondary_p, cls.primary_p = start_replica_set('test-mongo') cls.conn = MongoClient(mongo_host, cls.primary_p, replicaSet='test-mongo') @classmethod def tearDownClass(cls): """ Kills cluster instance """ kill_mongo_proc(cls.standalone_port) kill_replica_set('test-mongo') def tearDown(self): self.connector.join() def setUp(self): self.connector = Connector( address='%s:%s' % (mongo_host, self.primary_p), oplog_checkpoint="config.txt", target_url='%s:%d' % (mongo_host, self.standalone_port), ns_set=['test.test'], u_key='_id', auth_key=None, doc_manager='mongo_connector/doc_managers/mongo_doc_manager.py' ) self.connector.start() assert_soon(lambda: len(self.connector.shard_set) > 0) self.conn['test']['test'].remove() assert_soon(lambda: sum(1 for _ in self.mongo_doc._search()) == 0) def test_shard_length(self): """Tests the shard_length to see if the shard set was recognized properly """ self.assertEqual(len(self.connector.shard_set), 1) def test_insert(self): """Tests insert """ self.conn['test']['test'].insert({'name': 'paulie'}) assert_soon(lambda: sum(1 for _ in self.mongo_doc._search()) == 1) result_set_1 = self.mongo_doc._search() self.assertEqual(sum(1 for _ in result_set_1), 1) result_set_2 = self.conn['test']['test'].find_one() for item in result_set_1: self.assertEqual(item['_id'], result_set_2['_id']) self.assertEqual(item['name'], result_set_2['name']) def test_remove(self): """Tests remove """ self.conn['test']['test'].insert({'name': 'paulie'}) assert_soon(lambda: sum(1 for _ in self.mongo_doc._search()) == 1) self.conn['test']['test'].remove({'name': 'paulie'}) assert_soon(lambda: sum(1 for _ in self.mongo_doc._search()) != 1) self.assertEqual(sum(1 for _ in self.mongo_doc._search()), 0) def test_update(self): """Test update operations.""" # Insert self.conn.test.test.insert({"a": 0}) assert_soon(lambda: sum(1 for _ in self.mongo_doc._search()) == 1) def check_update(update_spec): updated = self.conn.test.test.find_and_modify( {"a": 0}, update_spec, new=True ) # Allow some time for update to propagate time.sleep(2) replicated = self.mongo_doc.mongo.test.test.find_one({"a": 0}) self.assertEqual(replicated, updated) # Update by adding a field check_update({"$set": {"b": [{"c": 10}, {"d": 11}]}}) # Update by setting an attribute of a sub-document beyond end of array. check_update({"$set": {"b.10.c": 42}}) # Update by changing a value within a sub-document (contains array) check_update({"$inc": {"b.0.c": 1}}) # Update by changing the value within an array check_update({"$inc": {"b.1.f": 12}}) # Update by adding new bucket to list check_update({"$push": {"b": {"e": 12}}}) # Update by changing an entire sub-document check_update({"$set": {"b.0": {"e": 4}}}) # Update by adding a sub-document check_update({"$set": {"b": {"0": {"c": 100}}}}) # Update whole document check_update({"a": 0, "b": {"1": {"d": 10000}}}) def test_rollback(self): """Tests rollback. We force a rollback by adding a doc, killing the primary, adding another doc, killing the new primary, and then restarting both. """ primary_conn = MongoClient(mongo_host, self.primary_p) self.conn['test']['test'].insert({'name': 'paul'}) condition = lambda: self.conn['test']['test'].find_one( {'name': 'paul'}) is not None assert_soon(condition) assert_soon(lambda: sum(1 for _ in self.mongo_doc._search()) == 1) kill_mongo_proc(self.primary_p, destroy=False) new_primary_conn = MongoClient(mongo_host, self.secondary_p) admin = new_primary_conn['admin'] condition = lambda: admin.command("isMaster")['ismaster'] assert_soon(lambda: retry_until_ok(condition)) retry_until_ok(self.conn.test.test.insert, {'name': 'pauline'}) assert_soon(lambda: sum(1 for _ in self.mongo_doc._search()) == 2) result_set_1 = list(self.mongo_doc._search()) result_set_2 = self.conn['test']['test'].find_one({'name': 'pauline'}) self.assertEqual(len(result_set_1), 2) #make sure pauline is there for item in result_set_1: if item['name'] == 'pauline': self.assertEqual(item['_id'], result_set_2['_id']) kill_mongo_proc(self.secondary_p, destroy=False) restart_mongo_proc(self.primary_p) assert_soon( lambda: primary_conn['admin'].command("isMaster")['ismaster']) restart_mongo_proc(self.secondary_p) time.sleep(2) result_set_1 = list(self.mongo_doc._search()) self.assertEqual(len(result_set_1), 1) for item in result_set_1: self.assertEqual(item['name'], 'paul') find_cursor = retry_until_ok(self.conn['test']['test'].find) self.assertEqual(retry_until_ok(find_cursor.count), 1) def test_stress(self): """Test stress by inserting and removing the number of documents specified in global variable """ for i in range(0, STRESS_COUNT): self.conn['test']['test'].insert({'name': 'Paul ' + str(i)}) time.sleep(5) search = self.mongo_doc._search condition = lambda: sum(1 for _ in search()) == STRESS_COUNT assert_soon(condition) for i in range(0, STRESS_COUNT): result_set_1 = self.mongo_doc._search() for item in result_set_1: if(item['name'] == 'Paul' + str(i)): self.assertEqual(item['_id'], item['_id']) def test_stressed_rollback(self): """Test stressed rollback with number of documents equal to specified in global variable. Strategy for rollback is the same as before. """ for i in range(0, STRESS_COUNT): self.conn['test']['test'].insert({'name': 'Paul ' + str(i)}) search = self.mongo_doc._search condition = lambda: sum(1 for _ in search()) == STRESS_COUNT assert_soon(condition) primary_conn = MongoClient(mongo_host, self.primary_p) kill_mongo_proc(self.primary_p, destroy=False) new_primary_conn = MongoClient(mongo_host, self.secondary_p) admin = new_primary_conn['admin'] assert_soon(lambda: admin.command("isMaster")['ismaster']) time.sleep(5) count = -1 while count + 1 < STRESS_COUNT: try: count += 1 self.conn['test']['test'].insert( {'name': 'Pauline ' + str(count)}) except (OperationFailure, AutoReconnect): time.sleep(1) assert_soon(lambda: sum(1 for _ in self.mongo_doc._search()) == self.conn['test']['test'].find().count()) result_set_1 = self.mongo_doc._search() for item in result_set_1: if 'Pauline' in item['name']: result_set_2 = self.conn['test']['test'].find_one( {'name': item['name']}) self.assertEqual(item['_id'], result_set_2['_id']) kill_mongo_proc(self.secondary_p, destroy=False) restart_mongo_proc(self.primary_p) db_admin = primary_conn['admin'] assert_soon(lambda: db_admin.command("isMaster")['ismaster']) restart_mongo_proc(self.secondary_p) search = self.mongo_doc._search condition = lambda: sum(1 for _ in search()) == STRESS_COUNT assert_soon(condition) result_set_1 = list(self.mongo_doc._search()) self.assertEqual(len(result_set_1), STRESS_COUNT) for item in result_set_1: self.assertTrue('Paul' in item['name']) find_cursor = retry_until_ok(self.conn['test']['test'].find) self.assertEqual(retry_until_ok(find_cursor.count), STRESS_COUNT) if __name__ == '__main__': unittest.main()
#! /usr/bin/python # # Copyright (c) 2014 IBM, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # from oslo_log import log as logging from congress.datalog import base as datalog_base from congress.datalog.builtin import congressbuiltin from congress.datalog import compile from congress import exception from congress.policy_engines import agnostic from congress.tests import base from congress.tests import helper LOG = logging.getLogger(__name__) addmap = { 'comparison': [ {'func': 'f(x,y)', 'num_inputs': 2, 'code': lambda x, y: x if x > y else y}], 'newcategory': [ {'func': 'g(x,y)', 'num_inputs': 2, 'code': lambda x, y: x + y}]} append_builtin = {'arithmetic': [{'func': 'div(x,y)', 'num_inputs': 2, 'code': 'lambda x,y: x / y'}]} class TestBuiltins(base.TestCase): def setUp(self): super(TestBuiltins, self).setUp() self.cbcmap = congressbuiltin.CongressBuiltinCategoryMap( congressbuiltin._builtin_map) self.predl = self.cbcmap.builtin('lt') def test_add_and_delete_map(self): cbcmap_before = self.cbcmap self.cbcmap.add_map(append_builtin) self.cbcmap.delete_map(append_builtin) self.assertTrue(self.cbcmap.mapequal(cbcmap_before)) def test_add_map_only(self): self.cbcmap.add_map(append_builtin) predl = self.cbcmap.builtin('div') self.assertNotEqual(predl, None) self.cbcmap.add_map(addmap) predl = self.cbcmap.builtin('max') self.assertNotEqual(predl, None) def test_add_and_delete_builtin(self): cbcmap_before = self.cbcmap self.cbcmap.add_map(append_builtin) self.cbcmap.delete_builtin('arithmetic', 'div', 2) self.assertTrue(self.cbcmap.mapequal(cbcmap_before)) def test_string_pred_string(self): predstring = str(self.predl) self.assertNotEqual(predstring, 'ltc(x,y') def test_add_and_delete_to_category(self): cbcmap_before = self.cbcmap arglist = ['x', 'y', 'z'] pred = congressbuiltin.CongressBuiltinPred('testfunc', arglist, 1, lambda x: not x) self.cbcmap.insert_to_category('arithmetic', pred) self.cbcmap.delete_from_category('arithmetic', pred) self.assertTrue(self.cbcmap.mapequal(cbcmap_before)) def test_all_checks(self): predtotest = self.cbcmap.builtin('lt') self.assertTrue(self.cbcmap.builtin_is_registered(predtotest)) def test_eval_builtin(self): predl = self.cbcmap.builtin('plus') result = predl.code(1, 2) self.assertEqual(result, 3) predl = self.cbcmap.builtin('gt') result = predl.code(1, 2) self.assertEqual(result, False) class TestReorder(base.TestCase): def check(self, input_string, correct_string, msg): rule = compile.parse1(input_string) actual = compile.reorder_for_safety(rule) correct = compile.parse1(correct_string) if correct != actual: emsg = "Correct: " + str(correct) emsg += "; Actual: " + str(actual) self.fail(msg + " :: " + emsg) def check_err(self, input_string, unsafe_lit_strings, msg): rule = compile.parse1(input_string) try: compile.reorder_for_safety(rule) self.fail("Failed to raise exception for " + input_string) except exception.PolicyException as e: errmsg = str(e) # parse then print to string so string rep same in err msg unsafe_lits = [str(compile.parse1(x)) for x in unsafe_lit_strings] missing_lits = [m for m in unsafe_lits if m + " (vars" not in errmsg] if len(missing_lits) > 0: self.fail( "Unsafe literals {} not reported in error: {}".format( ";".join(missing_lits), errmsg)) def test_reorder_builtins(self): self.check("p(x, z) :- q(x, y), plus(x, y, z)", "p(x, z) :- q(x, y), plus(x, y, z)", "No reorder") self.check("p(x, z) :- plus(x, y, z), q(x, y)", "p(x, z) :- q(x, y), plus(x, y, z)", "Basic reorder") self.check("p(x, z) :- q(x, y), r(w), plus(x, y, z), plus(z, w, y)", "p(x, z) :- q(x, y), r(w), plus(x, y, z), plus(z, w, y)", "Chaining: no reorder") self.check("p(x, z) :- q(x, y), plus(x, y, z), plus(z, w, y), r(w)", "p(x, z) :- q(x, y), plus(x, y, z), r(w), plus(z, w, y)", "Chaining: reorder") self.check("p(x) :- lt(t, v), plus(z, w, t), plus(z, u, v), " " plus(x, y, z), q(y), r(x), s(u), t(w) ", "p(x) :- q(y), r(x), plus(x, y, z), s(u), plus(z, u, v), " " t(w), plus(z, w, t), lt(t, v)", "Partial-order chaining") def test_unsafe_builtins(self): # an output self.check_err("p(x) :- q(x), plus(x, y, z)", ["plus(x,y,z)"], "Basic Unsafe input") self.check_err("p(x) :- q(x), r(z), plus(x, y, z)", ["plus(x,y,z)"], "Basic Unsafe input 2") self.check_err("p(x, z) :- plus(x, y, z), plus(z, y, x), " " plus(x, z, y)", ["plus(x, y, z)", "plus(z, y, x)", "plus(x, z, y)"], "Unsafe with cycle") # no outputs self.check_err("p(x) :- q(x), lt(x, y)", ["lt(x,y)"], "Basic Unsafe input, no outputs") self.check_err("p(x) :- q(y), lt(x, y)", ["lt(x,y)"], "Basic Unsafe input, no outputs 2") self.check_err("p(x, z) :- lt(x, y), lt(y, x)", ["lt(x,y)", "lt(y, x)"], "Unsafe with cycle, no outputs") # chaining self.check_err("p(x) :- q(x, y), plus(x, y, z), plus(z, 3, w), " " plus(w, t, u)", ["plus(w, t, u)"], "Unsafe chaining") self.check_err("p(x) :- q(x, y), plus(x, y, z), plus(z, 3, w), " " lt(w, t)", ["lt(w, t)"], "Unsafe chaining 2") def test_reorder_negation(self): self.check("p(x) :- q(x), not u(x), r(y), not s(x, y)", "p(x) :- q(x), not u(x), r(y), not s(x, y)", "No reordering") self.check("p(x) :- not q(x), r(x)", "p(x) :- r(x), not q(x)", "Basic") self.check("p(x) :- r(x), not q(x, y), s(y)", "p(x) :- r(x), s(y), not q(x,y)", "Partially safe") self.check("p(x) :- not q(x, y), not r(x), not r(x, z), " " t(x, y), u(x), s(z)", "p(x) :- t(x,y), not q(x,y), not r(x), u(x), s(z), " " not r(x, z)", "Complex") def test_unsafe_negation(self): self.check_err("p(x) :- not q(x)", ["q(x)"], "Basic") self.check_err("p(x) :- not q(x), not r(x)", ["q(x)", "r(x)"], "Cycle") self.check_err("p(x) :- not q(x, y), r(y)", ["q(x, y)"], "Partially safe") def test_reorder_builtins_negation(self): self.check("p(x) :- not q(z), plus(x, y, z), s(x), s(y)", "p(x) :- s(x), s(y), plus(x, y, z), not q(z)", "Basic") self.check("p(x) :- not q(z, w), plus(x, y, z), lt(z, w), " " plus(x, 3, w), s(x, y)", "p(x) :- s(x,y), plus(x, y, z), plus(x, 3, w), " " not q(z, w), lt(z, w)", "Partial order") def test_unsafe_builtins_negation(self): self.check_err("p(x) :- plus(x, y, z), not q(x, y)", ['plus(x,y,z)', 'q(x,y)'], 'Unsafe cycle') self.check_err("p(x) :- plus(x, y, z), plus(z, w, t), not q(z, t)," " s(x), t(y)", ['plus(z, w, t)', 'q(z, t)'], 'Unsafety propagates') NREC_THEORY = 'non-recursive theory test' MAT_THEORY = 'materialized view theory test' class TestTheories(base.TestCase): def prep_runtime(self, code=None, msg=None, target=None): # compile source if msg is not None: LOG.debug(msg) if code is None: code = "" if target is None: target = NREC_THEORY run = agnostic.Runtime() run.create_policy(NREC_THEORY, abbr="NRT", kind=datalog_base.NONRECURSIVE_POLICY_TYPE) run.create_policy(MAT_THEORY, abbr="MAT", kind=datalog_base.MATERIALIZED_POLICY_TYPE) run.debug_mode() run.insert(code, target=target) return run def check_equal(self, actual_string, correct_string, msg): self.assertTrue(helper.datalog_equal( actual_string, correct_string, msg)) def test_materialized_builtins(self): self.test_builtins(MAT_THEORY) def test_builtins(self, th=NREC_THEORY): """Test the mechanism that implements builtins.""" run = self.prep_runtime() run.insert('p(x) :- q(x,y), plus(x,y,z), r(z)' 'q(1,2)' 'q(2,3)' 'r(3)' 'r(5)', target=th) self.check_equal(run.select('p(x)', target=th), "p(1) p(2)", "Plus") run.delete('r(5)', target=th) self.check_equal(run.select('p(x)', target=th), "p(1)", "Plus") run = self.prep_runtime() run.insert('p(x) :- q(x,y), minus(x,y,z), r(z)' 'q(2,1)' 'q(3,1)' 'r(1)' 'r(4)', target=th) self.check_equal(run.select('p(x)', target=th), "p(2)", "Minus") run.delete('r(4)', target=th) run.insert('r(2)', target=th) self.check_equal(run.select('p(x)', target=th), "p(2) p(3)", "Minus") run = self.prep_runtime() run.insert('p(x, z) :- q(x,y), plus(x,y,z)' 'q(1,2)' 'q(2,3)', target=th) self.check_equal(run.select('p(x, y)', target=th), "p(1, 3) p(2, 5)", "Plus") run = self.prep_runtime() run.insert('m(x) :- j(x,y), lt(x,y)' 'j(1,2)' 'j(3,2)', target=th) self.check_equal(run.select('m(x)', target=th), 'm(1)', "LT") run = self.prep_runtime() run.insert('m(x) :- j(x,y), lt(x,y), r(y)' 'j(1,2)' 'j(2,3)' 'j(3,2)' 'r(2)', target=th) self.check_equal(run.select('m(x)', target=th), 'm(1)', "LT 2") run = self.prep_runtime() run.insert('p(x,z) :- q(x), plus(x,1,z)' 'q(3)' 'q(5)', target=th) self.check_equal(run.select('p(x,z)', target=th), 'p(3, 4) p(5,6)', "Bound input") run = self.prep_runtime() run.insert('p(x) :- q(x), plus(x,1,5)' 'q(4)' 'q(5)', target=th) self.check_equal(run.select('p(x)', target=th), 'p(4)', "Bound output") run = self.prep_runtime() run.insert('p(x, z) :- plus(x,y,z), q(x), r(y)' 'q(4)' 'r(5)', target=th) self.check_equal(run.select('p(x, y)', target=th), 'p(4, 9)', "Reordering") run = self.prep_runtime() run.insert('p(x, z) :- plus(x,y,z), q(x), q(y)' 'q(4)' 'q(5)', target=th) self.check_equal(run.select('p(x, y)', target=th), 'p(4, 9) p(4, 8) p(5, 9) p(5, 10)', "Reordering with self joins") def test_materialized_builtins_content(self): self.test_builtins_content(MAT_THEORY) def test_builtins_content(self, th=NREC_THEORY): """Test the content of the builtins, not the mechanism.""" def check_true(code, msg): run = self.prep_runtime('') run.insert(code, target=th) self.check_equal( run.select('p(x)', target=th), 'p(1)', msg) def check_false(code, msg): th = NREC_THEORY run = self.prep_runtime('') run.insert(code, target=th) self.check_equal( run.select('p(x)', target=th), '', msg) # # Numbers # # int code = 'p(1) :- int(2,2)' check_true(code, "int") code = 'p(1) :- int(2.3, 2)' check_true(code, "int") code = 'p(1) :- int(2, 3.3)' check_false(code, "int") # float code = 'p(1) :- float(2,2.0)' check_true(code, "float") code = 'p(1) :- float(2.3,2.3)' check_true(code, "float") code = 'p(1) :- float(2,3.3)' check_false(code, "int") # plus code = 'p(1) :- plus(2,3,5)' check_true(code, "plus") code = 'p(1) :- plus(2,3,1)' check_false(code, "plus") # minus code = 'p(1) :- minus(5, 3, 2)' check_true(code, "minus") code = 'p(1) :- minus(5, 3, 6)' check_false(code, "minus") # minus negative: negative numbers should not be supported # code = 'p(1) :- minus(3, 5, x)' # check_false(code, "minus") # times code = 'p(1) :- mul(3, 5, 15)' check_true(code, "multiply") code = 'p(1) :- mul(2, 5, 1)' check_false(code, "multiply") # divides code = 'p(1) :- div(10, 2, 5)' check_true(code, "divides") code = 'p(1) :- div(10, 4, 2)' check_true(code, "integer divides") code = 'p(1) :- div(10, 4.0, 2.5)' check_true(code, "float divides") code = 'p(1) :- div(10.0, 3, 3.3)' check_false(code, "divides") # # Comparison # # less than code = 'p(1) :- lt(1, 3)' check_true(code, "lessthan") code = 'p(1) :- lt(5, 2)' check_false(code, "lessthan") # less than equal code = 'p(1) :- lteq(1, 3)' check_true(code, "lessthaneq") code = 'p(1) :- lteq(3, 3)' check_true(code, "lessthaneq") code = 'p(1) :- lteq(4, 3)' check_false(code, "lessthaneq") # greater than code = 'p(1) :- gt(9, 5)' check_true(code, "greaterthan") code = 'p(1) :- gt(5, 9)' check_false(code, "greaterthan") # greater than equal code = 'p(1) :- gteq(10, 5)' check_true(code, "greaterthaneq") code = 'p(1) :- gteq(10, 10)' check_true(code, "greaterthaneq") code = 'p(1) :- gteq(5, 20)' check_false(code, "greaterthaneq") # equal code = 'p(1) :- equal(5, 5)' check_true(code, "equal") code = 'p(1) :- equal(5, 7)' check_false(code, "equal") # max code = 'p(1) :- max(3, 4, 4)' check_true(code, "max") code = 'p(1) :- max(3, 7, 3)' check_false(code, "max") # # Strings # # len code = 'p(1) :- len("abcde", 5)' check_true(code, "Len") code = 'p(1) :- len("abcde", 7)' check_false(code, "Len") # concat code = 'p(1) :- concat("abc", "def", "abcdef")' check_true(code, "concat") code = 'p(1) :- concat("abc", "def", "zxy")' check_false(code, "concat") # # Datetime # We should make some of these more robust but can't do # that with the safety restrictions in place at the time # of writing. # # lessthan code = ('p(1) :- datetime_lt(' '"Jan 1, 2014 10:00:00", "2014-01-02 10:00:00")') check_true(code, "True datetime_lt") code = ('p(1) :- datetime_lt(' '"2014-01-03 10:00:00", "Jan 2, 2014 10:00:00")') check_false(code, "False datetime_lt") # lessthanequal code = ('p(1) :- datetime_lteq(' '"Jan 1, 2014 10:00:00", "2014-01-02 10:00:00")') check_true(code, "True datetime_lteq") code = ('p(1) :- datetime_lteq(' '"Jan 1, 2014 10:00:00", "2014-01-01 10:00:00")') check_true(code, "True datetime_lteq") code = ('p(1) :- datetime_lteq(' '"2014-01-02 10:00:00", "Jan 1, 2014 10:00:00")') check_false(code, "False datetime_lteq") # greaterthan code = ('p(1) :- datetime_gt(' '"Jan 5, 2014 10:00:00", "2014-01-02 10:00:00")') check_true(code, "True datetime_gt") code = ('p(1) :- datetime_gt(' '"2014-01-03 10:00:00", "Feb 2, 2014 10:00:00")') check_false(code, "False datetime_gt") # greaterthanequal code = ('p(1) :- datetime_gteq(' '"Jan 5, 2014 10:00:00", "2014-01-02 10:00:00")') check_true(code, "True datetime_gteq") code = ('p(1) :- datetime_gteq(' '"Jan 5, 2014 10:00:00", "2014-01-05 10:00:00")') check_true(code, "True datetime_gteq") code = ('p(1) :- datetime_gteq(' '"2014-01-02 10:00:00", "Mar 1, 2014 10:00:00")') check_false(code, "False datetime_gteq") # equal code = ('p(1) :- datetime_equal(' '"Jan 5, 2014 10:00:00", "2014-01-05 10:00:00")') check_true(code, "True datetime_equal") code = ('p(1) :- datetime_equal(' '"Jan 5, 2014 10:00:00", "2014-01-02 10:00:00")') check_false(code, "False datetime_equal") # plus code = ('p(1) :- datetime_plus(' '"Jan 5, 2014 10:00:00", 3600, "2014-01-05 11:00:00")') check_true(code, "True datetime_plus") code = ('p(1) :- datetime_plus(' '"Jan 5, 2014 10:00:00", "1:00:00", "2014-01-05 11:00:00")') check_true(code, "True datetime_plus") code = ('p(1) :- datetime_plus(' '"Jan 5, 2014 10:00:00", 3600, "2014-01-05 12:00:00")') check_false(code, "False datetime_plus") # minus code = ('p(1) :- datetime_minus(' '"Jan 5, 2014 10:00:00", "25:00:00", "2014-01-04 09:00:00")') check_true(code, "True datetime_minus") code = ('p(1) :- datetime_minus(' '"Jan 5, 2014 10:00:00", 3600, "2014-01-05 09:00:00")') check_true(code, "True datetime_minus") code = ('p(1) :- datetime_minus(' '"Jan 5, 2014 10:00:00", "9:00:00", "Jan 4, 2014 10:00:00")') check_false(code, "False datetime_minus") # to_seconds code = ('p(1) :- datetime_to_seconds(' '"Jan 1, 1900 1:00:00", 3600)') check_true(code, "True datetime_to_seconds") code = ('p(1) :- datetime_to_seconds(' '"Jan 1, 1900 1:00:00", 3601)') check_false(code, "False datetime_to_seconds") # extract_time code = ('p(1) :- extract_time(' '"Jan 1, 1900 1:00:00", "01:00:00")') check_true(code, "True extract_time") code = ('p(1) :- extract_time(' '"Jan 1, 1900 1:00:00", "02:00:00")') check_false(code, "False extract_time") # extract_date code = ('p(1) :- extract_date(' '"Jan 1, 1900 1:00:00", "1900-01-01")') check_true(code, "True extract_date") code = ('p(1) :- extract_date(' '"Jan 1, 1900 1:00:00", "2000-01-01")') check_false(code, "False extract_date") # pack_datetime code = ('p(1) :- pack_datetime(2000, 1, 1, 10, 5, 6, ' '"2000-1-1 10:5:6")') check_true(code, "True pack_datetime") code = ('p(1) :- pack_datetime(2000, 1, 1, 10, 5, 6, ' '"2000-1-1 10:5:20")') check_false(code, "False pack_datetime") # pack_date code = ('p(1) :- pack_date(2000, 1, 1, ' '"2000-1-1")') check_true(code, "True pack_date") code = ('p(1) :- pack_date(2000, 1, 1, ' '"2000-1-2")') check_false(code, "False pack_date") # pack_time code = ('p(1) :- pack_time(5, 6, 7, ' '"5:6:7")') check_true(code, "True pack_time") code = ('p(1) :- pack_time(5, 6, 7, ' '"10:6:7")') check_false(code, "False pack_time") # unpack_datetime code = ('p(1) :- unpack_datetime("2000-1-1 10:5:6", ' '2000, 1, 1, 10, 5, 6)') check_true(code, "True unpack_datetime") code = ('p(1) :- unpack_datetime("2000-1-1 10:5:6", ' '2000, 1, 1, 12, 5, 6)') check_false(code, "False unpack_datetime") # unpack_date code = ('p(1) :- unpack_date("2000-1-1 10:5:6", ' '2000, 1, 1)') check_true(code, "True unpack_date") code = ('p(1) :- unpack_date("2000-1-1 10:5:6", ' '2000, 1, 5)') check_false(code, "False unpack_date") # unpack_time code = ('p(1) :- unpack_time("2000-1-1 10:5:6", ' '10, 5, 6)') check_true(code, "True unpack_time") code = ('p(1) :- unpack_time("2000-1-1 10:5:6", ' '12, 5, 6)') check_false(code, "False unpack_time") # unpack_time code = 'p(1) :- now(x)' check_true(code, "True unpack_time")
import os import platform import unittest import pytest import requests from mock import Mock from conans import DEFAULT_REVISION_V1 from conans.client.conf import ConanClientConfigParser from conans.client.remote_manager import Remote from conans.client.rest.auth_manager import ConanApiAuthManager from conans.client.rest.conan_requester import ConanRequester from conans.client.rest.rest_client import RestApiClientFactory from conans.client.rest.rest_client_v1 import complete_url from conans.client.tools import environment_append from conans.client.userio import UserIO from conans.model.info import ConanInfo from conans.model.manifest import FileTreeManifest from conans.model.ref import ConanFileReference, PackageReference from conans.paths import CONANFILE, CONANINFO, CONAN_MANIFEST from conans.test.assets.genconanfile import GenConanfile from conans.test.utils.mocks import LocalDBMock, TestBufferConanOutput from conans.test.utils.server_launcher import TestServerLauncher from conans.test.utils.test_files import temp_folder from conans.util.env_reader import get_env from conans.util.files import md5, save from conans.test.utils.tools import get_free_port class RestApiUnitTest(unittest.TestCase): def test_relative_url_completion(self): # test absolute urls self.assertEqual(complete_url("http://host2", "http://host"), "http://host") self.assertEqual(complete_url("http://host2", "http://host:1234"), "http://host:1234") self.assertEqual(complete_url("http://host2", "https://host"), "https://host") self.assertEqual(complete_url("http://host2", "https://host:1234"), "https://host:1234") # test relative urls self.assertEqual(complete_url("http://host", "v1/path_to_file.txt"), "http://host/v1/path_to_file.txt") self.assertEqual(complete_url("http://host:1234", "v1/path_to_file.txt"), "http://host:1234/v1/path_to_file.txt") self.assertEqual(complete_url("https://host", "v1/path_to_file.txt"), "https://host/v1/path_to_file.txt") self.assertEqual(complete_url("https://host:1234", "v1/path_to_file.txt"), "https://host:1234/v1/path_to_file.txt") # test relative urls with subdirectory self.assertEqual(complete_url("https://host:1234/subdir/", "v1/path_to_file.txt"), "https://host:1234/subdir/v1/path_to_file.txt") @pytest.mark.slow @pytest.mark.rest_api class RestApiTest(unittest.TestCase): """Open a real server (sockets) to test rest_api function.""" server = None api = None @classmethod def setUpClass(cls): if not cls.server: with environment_append({"CONAN_SERVER_PORT": str(get_free_port())}): cls.server = TestServerLauncher(server_capabilities=['ImCool', 'TooCool']) cls.server.start() filename = os.path.join(temp_folder(), "conan.conf") save(filename, "") config = ConanClientConfigParser(filename) requester = ConanRequester(config, requests) client_factory = RestApiClientFactory(Mock(), requester=requester, config=config) localdb = LocalDBMock() mocked_user_io = UserIO(out=TestBufferConanOutput()) mocked_user_io.get_username = Mock(return_value="private_user") mocked_user_io.get_password = Mock(return_value="private_pass") cls.auth_manager = ConanApiAuthManager(client_factory, mocked_user_io, localdb) cls.remote = Remote("myremote", "http://127.0.0.1:%s" % str(cls.server.port), True, True) cls.auth_manager._authenticate(cls.remote, user="private_user", password="private_pass") cls.api = client_factory.new(cls.remote, localdb.access_token, localdb.refresh_token, {}) @classmethod def tearDownClass(cls): cls.server.stop() def tearDown(self): RestApiTest.server.clean() def test_server_capabilities(self): capabilities = self.api.server_capabilities() self.assertEqual(capabilities, ["ImCool", "TooCool"]) def test_get_conan(self): # Upload a conans ref = ConanFileReference.loads("conan1/1.0.0@private_user/testing") self._upload_recipe(ref) # Get the conans tmp_dir = temp_folder() self.api.get_recipe(ref, tmp_dir) self.assertIn(CONANFILE, os.listdir(tmp_dir)) self.assertIn(CONAN_MANIFEST, os.listdir(tmp_dir)) def test_get_recipe_manifest(self): # Upload a conans ref = ConanFileReference.loads("conan2/1.0.0@private_user/testing") self._upload_recipe(ref) # Get the conans digest digest = self.api.get_recipe_manifest(ref) self.assertEqual(digest.summary_hash, "6fae00c91be4d09178af3c6fdc4d59e9") self.assertEqual(digest.time, 123123123) def test_get_package(self): # Upload a conans ref = ConanFileReference.loads("conan3/1.0.0@private_user/testing") self._upload_recipe(ref) # Upload an package pref = PackageReference(ref, "1F23223EFDA2") self._upload_package(pref) # Get the package tmp_dir = temp_folder() self.api.get_package(pref, tmp_dir) self.assertIn("hello.cpp", os.listdir(tmp_dir)) def test_get_package_info(self): # Upload a conans ref = ConanFileReference.loads("conan3/1.0.0@private_user/testing") self._upload_recipe(ref) # Upload an package pref = PackageReference(ref, "1F23223EFDA") conan_info = """[settings] arch=x86_64 compiler=gcc os=Linux [options] 386=False [requires] Hello Bye/2.9 Say/2.1@user/testing Chat/2.1@user/testing:SHA_ABC """ self._upload_package(pref, {CONANINFO: conan_info}) # Get the package info info = self.api.get_package_info(pref, headers=None) self.assertIsInstance(info, ConanInfo) self.assertEqual(info, ConanInfo.loads(conan_info)) def test_upload_huge_conan(self): if platform.system() != "Windows": # Upload a conans ref = ConanFileReference.loads("conanhuge/1.0.0@private_user/testing") files = {"file%s.cpp" % name: "File conent" for name in range(1000)} self._upload_recipe(ref, files) # Get the conans tmp = temp_folder() files = self.api.get_recipe(ref, tmp) self.assertIsNotNone(files) self.assertTrue(os.path.exists(os.path.join(tmp, "file999.cpp"))) def test_search(self): # Upload a conan1 conan_name1 = "HelloOnly/0.10@private_user/testing" ref1 = ConanFileReference.loads(conan_name1) self._upload_recipe(ref1) # Upload a package conan_info = """[settings] arch=x86_64 compiler=gcc os=Linux [options] 386=False [requires] Hello Bye/2.9 Say/2.1@user/testing Chat/2.1@user/testing:SHA_ABC """ pref = PackageReference(ref1, "1F23223EFDA") self._upload_package(pref, {CONANINFO: conan_info}) # Upload a conan2 conan_name2 = "helloonlyToo/2.1@private_user/stable" ref2 = ConanFileReference.loads(conan_name2) self._upload_recipe(ref2) # Get the info about this ConanFileReference info = self.api.search_packages(ref1, None) self.assertEqual(ConanInfo.loads(conan_info).serialize_min(), info["1F23223EFDA"]) # Search packages results = self.api.search("HelloOnly*", ignorecase=False) results = [r.copy_clear_rev() for r in results] self.assertEqual(results, [ref1]) @pytest.mark.skipif(get_env("TESTING_REVISIONS_ENABLED", False), reason="Not prepared with revs") def test_remove(self): # Upload a conans ref = ConanFileReference.loads("MyFirstConan/1.0.0@private_user/testing") self._upload_recipe(ref) ref = ref.copy_with_rev(DEFAULT_REVISION_V1) path1 = self.server.server_store.base_folder(ref) self.assertTrue(os.path.exists(path1)) # Remove conans and packages self.api.remove_recipe(ref) self.assertFalse(os.path.exists(path1)) @pytest.mark.skipif(get_env("TESTING_REVISIONS_ENABLED", False), reason="Not prepared with revs") def test_remove_packages(self): ref = ConanFileReference.loads("MySecondConan/2.0.0@private_user/testing#%s" % DEFAULT_REVISION_V1) self._upload_recipe(ref) folders = {} for sha in ["1", "2", "3", "4", "5"]: # Upload an package pref = PackageReference(ref, sha, DEFAULT_REVISION_V1) self._upload_package(pref, {CONANINFO: ""}) folder = self.server.server_store.package(pref) self.assertTrue(os.path.exists(folder)) folders[sha] = folder data = self.api.search_packages(ref, None) self.assertEqual(len(data), 5) self.api.remove_packages(ref, ["1"]) self.assertTrue(os.path.exists(self.server.server_store.base_folder(ref))) self.assertFalse(os.path.exists(folders["1"])) self.assertTrue(os.path.exists(folders["2"])) self.assertTrue(os.path.exists(folders["3"])) self.assertTrue(os.path.exists(folders["4"])) self.assertTrue(os.path.exists(folders["5"])) self.api.remove_packages(ref, ["2", "3"]) self.assertTrue(os.path.exists(self.server.server_store.base_folder(ref))) self.assertFalse(os.path.exists(folders["1"])) self.assertFalse(os.path.exists(folders["2"])) self.assertFalse(os.path.exists(folders["3"])) self.assertTrue(os.path.exists(folders["4"])) self.assertTrue(os.path.exists(folders["5"])) self.api.remove_packages(ref, []) self.assertTrue(os.path.exists(self.server.server_store.base_folder(ref))) for sha in ["1", "2", "3", "4", "5"]: self.assertFalse(os.path.exists(folders[sha])) def _upload_package(self, package_reference, base_files=None): files = {"conanfile.py": GenConanfile("3").with_requires("1", "12").with_exports("*"), "hello.cpp": "hello"} if base_files: files.update(base_files) tmp_dir = temp_folder() abs_paths = {} for filename, content in files.items(): abs_path = os.path.join(tmp_dir, filename) save(abs_path, str(content)) abs_paths[filename] = abs_path self.api.upload_package(package_reference, abs_paths, None, retry=1, retry_wait=0) def _upload_recipe(self, ref, base_files=None, retry=1, retry_wait=0): files = {"conanfile.py": GenConanfile("3").with_requires("1", "12")} if base_files: files.update(base_files) content = """ from conans import ConanFile class MyConan(ConanFile): name = "%s" version = "%s" settings = arch, compiler, os """ % (ref.name, ref.version) files[CONANFILE] = content files_md5s = {filename: md5(content) for filename, content in files.items()} conan_digest = FileTreeManifest(123123123, files_md5s) tmp_dir = temp_folder() abs_paths = {} for filename, content in files.items(): abs_path = os.path.join(tmp_dir, filename) save(abs_path, content) abs_paths[filename] = abs_path abs_paths[CONAN_MANIFEST] = os.path.join(tmp_dir, CONAN_MANIFEST) conan_digest.save(tmp_dir) self.api.upload_recipe(ref, abs_paths, None, retry, retry_wait)
from pygame import event as pygevent from thorpy.elements.draggable import Draggable from thorpy.miscgui import constants, functions, style, painterstyle class Dragger(Draggable): def __init__(self, slider, normal_params=None, press_params=None): super(Dragger, self).__init__("", [], normal_params, press_params) self.slider = slider params = {"color": style.COLOR_HOVER_DRAGGER} self.normal_params.polite_set("params hover", {"painter": painterstyle.DEF_PAINTER, "params": params}) self.normal_params.polite_set("typ hover", "redraw") def set_setter(self): self.dragmove = self.dragmove_setter def _reaction_drag_transp(self, shift): self.unblit() self.update() self.move((shift[0], shift[1])) self.blit() self.update() class DraggerX(Dragger): def __init__(self, slider, normal_params=None, press_params=None): Dragger.__init__(self, slider, normal_params, press_params) def dragmove_setter(self, x): self._reaction_drag_transp((x, 0)) self.slider.refresh_value() def dragmove(self, x): self._reaction_drag_transp((x, 0)) def is_and_will_be_inside(self, shift): slider_rect = self.slider._get_slide_rect() left = slider_rect.left right = slider_rect.right now = left <= self.current_state.ghost_rect.centerx <= right future = left <= self.current_state.ghost_rect.centerx + shift <= right return now and future def will_be_inside(self, shift): """Shift is in pixels units""" slider_rect = self.slider._get_slide_rect() left = slider_rect.left right = slider_rect.right return left <= self.current_state.ghost_rect.centerx + shift <= right def _reaction_drag(self, event): if self.current_state_key == constants.STATE_PRESSED: if self.will_be_inside(event.rel[0]): self.dragmove(event.rel[0]) drag_event = pygevent.Event(constants.THORPY_EVENT, name=constants.EVENT_SLIDE, el=self.father) pygevent.post(drag_event) def shift(self, sign=1): if self.will_be_inside(sign): self.dragmove(sign) def place_at(self, value): x0 = self.slider._get_slide_rect().left pix = self.slider.val_to_pix(value, x0) ## test = self.slider.pix_to_val(pix, x0) == value ? self.set_center((pix, None)) class DraggerY(Dragger): def __init__(self, slider, normal_params=None, press_params=None): Dragger.__init__(self, slider, normal_params, press_params) def goto_start(self): y = self.slider._plus.get_fus_topleft()[1] y += self.slider._plus.get_fus_size()[1] yself = self.get_fus_topleft()[1] shift = yself - y self.dragmove(-shift) return shift def goto_end(self): y = self.slider._minus.get_fus_topleft()[1] yself = self.get_fus_topleft()[1] yself += self.get_fus_size()[1] shift = yself - y self.dragmove(-shift) return shift def dragmove(self, y): self.unblit() self.update() self.move((0, y)) self.blit() self.update() def is_and_will_be_inside(self, shift): slider_rect = self.slider._get_slide_rect() top = slider_rect.y bottom = slider_rect.bottom now = top <= self.current_state.ghost_rect.centery <= bottom future = top <= self.current_state.ghost_rect.centery + shift <= bottom return now and future def will_be_inside(self, shift): slider_rect = self.slider._get_slide_rect() top = slider_rect.y bottom = slider_rect.bottom return top <= self.current_state.ghost_rect.centery + shift <= bottom def _reaction_drag(self, event): if self.current_state_key == constants.STATE_PRESSED: if self.will_be_inside(event.rel[1]): self.dragmove(event.rel[1]) def place_at(self, value): y0 = self.slider._get_slide_rect().y pix = self.slider.val_to_pix(value, y0) self.set_center((None, pix)) def shift(self, sign=1): sign = -sign if self.is_and_will_be_inside(sign): self.dragmove(sign) debug_msg(self.slider.get_value()) class DraggerLiftY(DraggerY): """Dragger for a lift""" def __init__(self, slider, image=None, colorkey=None): super(DraggerLiftY, self).__init__(slider, image, colorkey) self.last_value = self.slider._limvals[0] # init last_value def shift(self, sign=1): sign = -sign if self.is_and_will_be_inside(sign): self.dragmove(sign) current_value = self.slider.get_value() delta = self.last_value - current_value shift_y = 1 * delta self.slider._linked.scroll_children([self.slider], (0, shift_y)) functions.debug_msg("Lift value : ", current_value) self.last_value = current_value def goto_start(self): shift = DraggerY.goto_start(self) current_value = self.slider.get_value() self.last_value = current_value self.slider._linked.scroll_children([self.slider], (0, shift)) def goto_end(self): shift = DraggerY.goto_end(self) current_value = self.slider.get_value() self.last_value = current_value self.slider._linked.scroll_children([self.slider], (0, shift)) def _reaction_drag(self, event): if self.current_state_key == constants.STATE_PRESSED: if self.will_be_inside(event.rel[1]): self.dragmove(event.rel[1]) current_value = self.slider.get_value() delta = self.last_value - current_value shift_y = 1 * delta # move childrens self.slider._linked.scroll_children([self.slider], (0, shift_y)) self.last_value = current_value class DraggerDirViewerY(DraggerLiftY): def refresh_and_blit_ddlf(self): ddlf = self.slider._linked ddlf.unblit() ddlf.blit() ddlf.update() def shift(self, sign=1): sign = -sign if self.is_and_will_be_inside(sign): self.dragmove(sign) self.slider._linked._dv.pix_0 += sign self.refresh_and_blit_ddlf() def _reaction_drag(self, event): if self.current_state_key == constants.STATE_PRESSED: if self.will_be_inside(event.rel[1]): self.dragmove(event.rel[1]) current_value = self.slider.get_value() shift_y = round(self.last_value - current_value) self.slider._linked._dv.pix_0 -= shift_y self.refresh_and_blit_ddlf() self.last_value = current_value
# -*- coding: utf-8 -*- from __future__ import absolute_import import functools from .. import backend as K from keras import activations from keras import initializers from keras import regularizers from keras import constraints from keras.engine import Layer from keras.engine import InputSpec from keras.layers.convolutional import Convolution3D from keras.utils.generic_utils import get_custom_objects from keras.utils.conv_utils import conv_output_length from keras.utils.conv_utils import normalize_data_format import numpy as np class Deconvolution3D(Convolution3D): """Transposed convolution operator for filtering windows of 3-D inputs. The need for transposed convolutions generally arises from the desire to use a transformation going in the opposite direction of a normal convolution, i.e., from something that has the shape of the output of some convolution to something that has the shape of its input while maintaining a connectivity pattern that is compatible with said convolution. When using this layer as the first layer in a model, provide the keyword argument `input_shape` (tuple of integers, does not include the sample axis), e.g. `input_shape=(3, 128, 128, 128)` for a 128x128x128 volume with three channels. To pass the correct `output_shape` to this layer, one could use a test model to predict and observe the actual output shape. # Examples ```python # TH dim ordering. # apply a 3x3x3 transposed convolution # with stride 1x1x1 and 3 output filters on a 12x12x12 image: model = Sequential() model.add(Deconvolution3D(3, 3, 3, 3, output_shape=(None, 3, 14, 14, 14), padding='valid', input_shape=(3, 12, 12, 12))) # we can predict with the model and print the shape of the array. dummy_input = np.ones((32, 3, 12, 12, 12)) preds = model.predict(dummy_input) print(preds.shape) # (None, 3, 14, 14, 14) # apply a 3x3x3 transposed convolution # with stride 2x2x2 and 3 output filters on a 12x12x12 image: model = Sequential() model.add(Deconvolution3D(3, 3, 3, 3, output_shape=(None, 3, 25, 25, 25), strides=(2, 2, 2), padding='valid', input_shape=(3, 12, 12, 12))) model.summary() # we can predict with the model and print the shape of the array. dummy_input = np.ones((32, 3, 12, 12, 12)) preds = model.predict(dummy_input) print(preds.shape) # (None, 3, 25, 25, 25) ``` ```python # TF dim ordering. # apply a 3x3x3 transposed convolution # with stride 1x1x1 and 3 output filters on a 12x12x12 image: model = Sequential() model.add(Deconvolution3D(3, 3, 3, 3, output_shape=(None, 14, 14, 14, 3), padding='valid', input_shape=(12, 12, 12, 3))) # we can predict with the model and print the shape of the array. dummy_input = np.ones((32, 12, 12, 12, 3)) preds = model.predict(dummy_input) print(preds.shape) # (None, 14, 14, 14, 3) # apply a 3x3x3 transposed convolution # with stride 2x2x2 and 3 output filters on a 12x12x12 image: model = Sequential() model.add(Deconvolution3D(3, 3, 3, 3, output_shape=(None, 25, 25, 25, 3), strides=(2, 2, 2), padding='valid', input_shape=(12, 12, 12, 3))) model.summary() # we can predict with the model and print the shape of the array. dummy_input = np.ones((32, 12, 12, 12, 3)) preds = model.predict(dummy_input) print(preds.shape) # (None, 25, 25, 25, 3) ``` # Arguments filters: Number of transposed convolution filters to use. kernel_size: kernel_size: An integer or tuple/list of 3 integers, specifying the dimensions of the convolution window. output_shape: Output shape of the transposed convolution operation. tuple of integers `(nb_samples, filters, conv_dim1, conv_dim2, conv_dim3)`. It is better to use a dummy input and observe the actual output shape of a layer, as specified in the examples. init: name of initialization function for the weights of the layer (see [initializers](../initializers.md)), or alternatively, Theano function to use for weights initialization. This parameter is only relevant if you don't pass a `weights` argument. activation: name of activation function to use (see [activations](../activations.md)), or alternatively, elementwise Theano/TensorFlow function. If you don't specify anything, no activation is applied (ie. "linear" activation: a(x) = x). weights: list of numpy arrays to set as initial weights. padding: 'valid', 'same' or 'full' ('full' requires the Theano backend). strides: tuple of length 3. Factor by which to oversample output. Also called strides elsewhere. kernel_regularizer: instance of [WeightRegularizer](../regularizers.md) (eg. L1 or L2 regularization), applied to the main weights matrix. bias_regularizer: instance of [WeightRegularizer](../regularizers.md), applied to the use_bias. activity_regularizer: instance of [ActivityRegularizer](../regularizers.md), applied to the network output. kernel_constraint: instance of the [constraints](../constraints.md) module (eg. maxnorm, nonneg), applied to the main weights matrix. bias_constraint: instance of the [constraints](../constraints.md) module, applied to the use_bias. data_format: 'channels_first' or 'channels_last'. In 'channels_first' mode, the channels dimension (the depth) is at index 1, in 'channels_last' mode is it at index 4. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "tf". use_bias: whether to include a use_bias (i.e. make the layer affine rather than linear). # Input shape 5D tensor with shape: `(samples, channels, conv_dim1, conv_dim2, conv_dim3)` if data_format='channels_first' or 5D tensor with shape: `(samples, conv_dim1, conv_dim2, conv_dim3, channels)` if data_format='channels_last'. # Output shape 5D tensor with shape: `(samples, filters, nekernel_conv_dim1, nekernel_conv_dim2, nekernel_conv_dim3)` if data_format='channels_first' or 5D tensor with shape: `(samples, nekernel_conv_dim1, nekernel_conv_dim2, nekernel_conv_dim3, filters)` if data_format='channels_last'. `nekernel_conv_dim1`, `nekernel_conv_dim2` and `nekernel_conv_dim3` values might have changed due to padding. # References - [A guide to convolution arithmetic for deep learning](https://arxiv.org/abs/1603.07285v1) - [Transposed convolution arithmetic](http://deeplearning.net/software/theano_versions/dev/tutorial/conv_arithmetic.html#transposed-convolution-arithmetic) - [Deconvolutional Networks](http://www.matthewzeiler.com/pubs/cvpr2010/cvpr2010.pdf) """ def __init__(self, filters, kernel_size, output_shape, activation=None, weights=None, padding='valid', strides=(1, 1, 1), data_format=None, kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', **kwargs): if padding not in {'valid', 'same', 'full'}: raise ValueError('Invalid border mode for Deconvolution3D:', padding) if len(output_shape) == 4: # missing the batch size output_shape = (None,) + tuple(output_shape) self.output_shape_ = output_shape super(Deconvolution3D, self).__init__(kernel_size=kernel_size, filters=filters, activation=activation, weights=weights, padding=padding, strides=strides, data_format=data_format, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, bias_constraint=bias_constraint, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, **kwargs) def compute_output_shape(self, input_shape): if self.data_format == 'channels_first': conv_dim1 = self.output_shape_[2] conv_dim2 = self.output_shape_[3] conv_dim3 = self.output_shape_[4] return (input_shape[0], self.filters, conv_dim1, conv_dim2, conv_dim3) elif self.data_format == 'channels_last': conv_dim1 = self.output_shape_[1] conv_dim2 = self.output_shape_[2] conv_dim3 = self.output_shape_[3] return (input_shape[0], conv_dim1, conv_dim2, conv_dim3, self.filters) else: raise ValueError('Invalid data format: ', self.data_format) def call(self, x, mask=None): kernel_shape = K.get_value(self.kernel).shape output = K.deconv3d(x, self.kernel, self.output_shape_, strides=self.strides, padding=self.padding, data_format=self.data_format, filter_shape=kernel_shape) if self.use_bias: if self.data_format == 'channels_first': output += K.reshape(self.bias, (1, self.filters, 1, 1, 1)) elif self.data_format == 'channels_last': output += K.reshape(self.bias, (1, 1, 1, 1, self.filters)) else: raise ValueError('Invalid data_format: ', self.data_format) output = self.activation(output) return output def get_config(self): config = {'output_shape': self.output_shape_} base_config = super(Deconvolution3D, self).get_config() return dict(list(base_config.items()) + list(config.items())) Deconv3D = Deconvolution3D get_custom_objects().update({'Deconvolution3D': Deconvolution3D}) get_custom_objects().update({'Deconv3D': Deconv3D}) class CosineConvolution2D(Layer): """Cosine Normalized Convolution operator for filtering windows of two-dimensional inputs. Cosine Normalization: Using Cosine Similarity Instead of Dot Product in Neural Networks https://arxiv.org/pdf/1702.05870.pdf When using this layer as the first layer in a model, provide the keyword argument `input_shape` (tuple of integers, does not include the sample axis), e.g. `input_shape=(3, 128, 128)` for 128x128 RGB pictures. # Examples ```python # apply a 3x3 convolution with 64 output filters on a 256x256 image: model = Sequential() model.add(CosineConvolution2D(64, 3, 3, padding='same', input_shape=(3, 256, 256))) # now model.output_shape == (None, 64, 256, 256) # add a 3x3 convolution on top, with 32 output filters: model.add(CosineConvolution2D(32, 3, 3, padding='same')) # now model.output_shape == (None, 32, 256, 256) ``` # Arguments filters: Number of convolution filters to use. kernel_size: kernel_size: An integer or tuple/list of 2 integers, specifying the dimensions of the convolution window. init: name of initialization function for the weights of the layer (see [initializers](../initializers.md)), or alternatively, Theano function to use for weights initialization. This parameter is only relevant if you don't pass a `weights` argument. activation: name of activation function to use (see [activations](../activations.md)), or alternatively, elementwise Theano function. If you don't specify anything, no activation is applied (ie. "linear" activation: a(x) = x). weights: list of numpy arrays to set as initial weights. padding: 'valid', 'same' or 'full' ('full' requires the Theano backend). strides: tuple of length 2. Factor by which to strides output. Also called strides elsewhere. kernel_regularizer: instance of [WeightRegularizer](../regularizers.md) (eg. L1 or L2 regularization), applied to the main weights matrix. bias_regularizer: instance of [WeightRegularizer](../regularizers.md), applied to the use_bias. activity_regularizer: instance of [ActivityRegularizer](../regularizers.md), applied to the network output. kernel_constraint: instance of the [constraints](../constraints.md) module (eg. maxnorm, nonneg), applied to the main weights matrix. bias_constraint: instance of the [constraints](../constraints.md) module, applied to the use_bias. data_format: 'channels_first' or 'channels_last'. In 'channels_first' mode, the channels dimension (the depth) is at index 1, in 'channels_last' mode is it at index 3. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "tf". use_bias: whether to include a use_bias (i.e. make the layer affine rather than linear). # Input shape 4D tensor with shape: `(samples, channels, rows, cols)` if data_format='channels_first' or 4D tensor with shape: `(samples, rows, cols, channels)` if data_format='channels_last'. # Output shape 4D tensor with shape: `(samples, filters, nekernel_rows, nekernel_cols)` if data_format='channels_first' or 4D tensor with shape: `(samples, nekernel_rows, nekernel_cols, filters)` if data_format='channels_last'. `rows` and `cols` values might have changed due to padding. """ def __init__(self, filters, kernel_size, kernel_initializer='glorot_uniform', activation=None, weights=None, padding='valid', strides=(1, 1), data_format=None, kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, use_bias=True, **kwargs): if data_format is None: data_format = K.image_data_format() if padding not in {'valid', 'same', 'full'}: raise ValueError('Invalid border mode for CosineConvolution2D:', padding) self.filters = filters self.kernel_size = kernel_size self.nb_row, self.nb_col = self.kernel_size self.kernel_initializer = initializers.get(kernel_initializer) self.activation = activations.get(activation) self.padding = padding self.strides = tuple(strides) self.data_format = normalize_data_format(data_format) self.kernel_regularizer = regularizers.get(kernel_regularizer) self.bias_regularizer = regularizers.get(bias_regularizer) self.activity_regularizer = regularizers.get(activity_regularizer) self.kernel_constraint = constraints.get(kernel_constraint) self.bias_constraint = constraints.get(bias_constraint) self.use_bias = use_bias self.input_spec = [InputSpec(ndim=4)] self.initial_weights = weights super(CosineConvolution2D, self).__init__(**kwargs) def build(self, input_shape): if self.data_format == 'channels_first': stack_size = input_shape[1] self.kernel_shape = (self.filters, stack_size, self.nb_row, self.nb_col) self.kernel_norm_shape = (1, stack_size, self.nb_row, self.nb_col) elif self.data_format == 'channels_last': stack_size = input_shape[3] self.kernel_shape = (self.nb_row, self.nb_col, stack_size, self.filters) self.kernel_norm_shape = (self.nb_row, self.nb_col, stack_size, 1) else: raise ValueError('Invalid data_format:', self.data_format) self.W = self.add_weight(self.kernel_shape, initializer=functools.partial(self.kernel_initializer), name='{}_W'.format(self.name), regularizer=self.kernel_regularizer, constraint=self.kernel_constraint) self.kernel_norm = K.variable(np.ones(self.kernel_norm_shape), name='{}_kernel_norm'.format(self.name)) if self.use_bias: self.b = self.add_weight((self.filters,), initializer='zero', name='{}_b'.format(self.name), regularizer=self.bias_regularizer, constraint=self.bias_constraint) else: self.b = None if self.initial_weights is not None: self.set_weights(self.initial_weights) del self.initial_weights self.built = True def compute_output_shape(self, input_shape): if self.data_format == 'channels_first': rows = input_shape[2] cols = input_shape[3] elif self.data_format == 'channels_last': rows = input_shape[1] cols = input_shape[2] else: raise ValueError('Invalid data_format:', self.data_format) rows = conv_output_length(rows, self.nb_row, self.padding, self.strides[0]) cols = conv_output_length(cols, self.nb_col, self.padding, self.strides[1]) if self.data_format == 'channels_first': return (input_shape[0], self.filters, rows, cols) elif self.data_format == 'channels_last': return (input_shape[0], rows, cols, self.filters) def call(self, x, mask=None): b, xb = 0., 0. if self.data_format == 'channels_first': kernel_sum_axes = [1, 2, 3] if self.use_bias: b = K.reshape(self.b, (self.filters, 1, 1, 1)) xb = 1. elif self.data_format == 'channels_last': kernel_sum_axes = [0, 1, 2] if self.use_bias: b = K.reshape(self.b, (1, 1, 1, self.filters)) xb = 1. Wnorm = K.sqrt(K.sum(K.square(self.W), axis=kernel_sum_axes, keepdims=True) + K.square(b) + K.epsilon()) xnorm = K.sqrt(K.conv2d(K.square(x), self.kernel_norm, strides=self.strides, padding=self.padding, data_format=self.data_format, filter_shape=self.kernel_norm_shape) + xb + K.epsilon()) W = self.W / Wnorm output = K.conv2d(x, W, strides=self.strides, padding=self.padding, data_format=self.data_format, filter_shape=self.kernel_shape) if K.backend() == 'theano': xnorm = K.pattern_broadcast(xnorm, [False, True, False, False]) output /= xnorm if self.use_bias: b /= Wnorm if self.data_format == 'channels_first': b = K.reshape(b, (1, self.filters, 1, 1)) elif self.data_format == 'channels_last': b = K.reshape(b, (1, 1, 1, self.filters)) else: raise ValueError('Invalid data_format:', self.data_format) b /= xnorm output += b output = self.activation(output) return output def get_config(self): config = {'filters': self.filters, 'kernel_size': self.kernel_size, 'kernel_initializer': initializers.serialize(self.kernel_initializer), 'activation': activations.serialize(self.activation), 'padding': self.padding, 'strides': self.strides, 'data_format': self.data_format, 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer), 'bias_regularizer': regularizers.serialize(self.bias_regularizer), 'activity_regularizer': regularizers.serialize(self.activity_regularizer), 'kernel_constraint': constraints.serialize(self.kernel_constraint), 'bias_constraint': constraints.serialize(self.bias_constraint), 'use_bias': self.use_bias} base_config = super(CosineConvolution2D, self).get_config() return dict(list(base_config.items()) + list(config.items())) CosineConv2D = CosineConvolution2D get_custom_objects().update({'CosineConvolution2D': CosineConvolution2D}) get_custom_objects().update({'CosineConv2D': CosineConv2D}) class SubPixelUpscaling(Layer): """ Sub-pixel convolutional upscaling layer based on the paper "Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network" (https://arxiv.org/abs/1609.05158). This layer requires a Convolution2D prior to it, having output filters computed according to the formula : filters = k * (scale_factor * scale_factor) where k = a user defined number of filters (generally larger than 32) scale_factor = the upscaling factor (generally 2) This layer performs the depth to space operation on the convolution filters, and returns a tensor with the size as defined below. # Example : ```python # A standard subpixel upscaling block x = Convolution2D(256, 3, 3, padding='same', activation='relu')(...) u = SubPixelUpscaling(scale_factor=2)(x) [Optional] x = Convolution2D(256, 3, 3, padding='same', activation='relu')(u) ``` In practice, it is useful to have a second convolution layer after the SubPixelUpscaling layer to speed up the learning process. However, if you are stacking multiple SubPixelUpscaling blocks, it may increase the number of parameters greatly, so the Convolution layer after SubPixelUpscaling layer can be removed. # Arguments scale_factor: Upscaling factor. data_format: Can be None, 'channels_first' or 'channels_last'. # Input shape 4D tensor with shape: `(samples, k * (scale_factor * scale_factor) channels, rows, cols)` if data_format='channels_first' or 4D tensor with shape: `(samples, rows, cols, k * (scale_factor * scale_factor) channels)` if data_format='channels_last'. # Output shape 4D tensor with shape: `(samples, k channels, rows * scale_factor, cols * scale_factor))` if data_format='channels_first' or 4D tensor with shape: `(samples, rows * scale_factor, cols * scale_factor, k channels)` if data_format='channels_last'. """ def __init__(self, scale_factor=2, data_format=None, **kwargs): super(SubPixelUpscaling, self).__init__(**kwargs) self.scale_factor = scale_factor self.data_format = normalize_data_format(data_format) def build(self, input_shape): pass def call(self, x, mask=None): y = K.depth_to_space(x, self.scale_factor, self.data_format) return y def compute_output_shape(self, input_shape): if self.data_format == 'channels_first': b, k, r, c = input_shape return (b, k // (self.scale_factor ** 2), r * self.scale_factor, c * self.scale_factor) else: b, r, c, k = input_shape return (b, r * self.scale_factor, c * self.scale_factor, k // (self.scale_factor ** 2)) def get_config(self): config = {'scale_factor': self.scale_factor, 'data_format': self.data_format} base_config = super(SubPixelUpscaling, self).get_config() return dict(list(base_config.items()) + list(config.items())) get_custom_objects().update({'SubPixelUpscaling': SubPixelUpscaling})
from builtins import range, str, object import os import re import copy import json import numpy as np import pickle from functools import partial from contextlib import contextmanager from peri import util, comp, models from peri.logger import log as baselog log = baselog.getChild('states') class UpdateError(Exception): pass def sample(field, inds=None, slicer=None, flat=True): """ Take a sample from a field given flat indices or a shaped slice Parameters ----------- inds : list of indices One dimensional (raveled) indices to return from the field slicer : slice object A shaped (3D) slicer that returns a section of image flat : boolean Whether to flatten the sampled item before returning """ if inds is not None: out = field.ravel()[inds] elif slicer is not None: out = field[slicer].ravel() else: out = field if flat: return out.ravel() return out _graddoc = \ """ Parameters ----------- func : callable Function wrt to take a derivative, should return a nparray that is the same shape for all params and values params : string or list of strings Paramter(s) to take the derivative wrt dl : float Derivative step size for numerical deriv rts : boolean Return To Start. Return the state to how you found it when done, needs another update call, so can be ommitted sometimes (small dl). If True, functions return the final answer along with the final func evaluation so that it may be passed onto other calls. nout : Int, optional How many objects the function returns. Allows for gradient of multiple things (e.g. residuals + error) at the same time in a nice, contiguous way. Default is 1 out : ndarray or None, optional If set, the return array for the output. Performance feature. Does not check for shape internally; will just raise an error. Default is None, i.e. initialize the output internally. **kwargs : Arguments to `func` """ _sampledoc = \ """ kwargs (supply only one): ----------------------------- inds : list of indices One dimensional (raveled) indices to return from the field slicer : slice object A shaped (3D) slicer that returns a section of image flat : boolean Whether to flatten the sampled item before returning """ #============================================================================= # Super class of State, has all basic components and structure #============================================================================= class State(comp.ParameterGroup): def __init__(self, params, values, logpriors=None, hyper_params=['sigma'], hyper_values=[0.04], **kwargs): """ A model and corresponding functions to perform a fit to data using a variety of optimization routines. A model takes parameters and values (names and values) which determine the output of a model, which is then compared with data. Parameters ----------- params : list of strings The names of the parameters (should be a unique set) values : list of numbers The corresponding values of the parameters logpriors : list of `peri.prior.Prior` Priors (constraints) to apply to parameters hyper_params : list of strings, optional The names of any hyper-parameters (should be a unique set). Stored as a `peri.comp.ParameterGroup`. Default is `['sigma']`, the standard-deviation of the noise distribution. hyper_values : list of numbers, optional The corresponding values of the hyper-parameters. Stored as a `peri.comp.ParameterGroup`. Default is `[0.04]` kwargs : Arguments to pass to super class :class:`peri.comp.ParameterGroup` including `ordered` and `category`. """ self.stack = [] self.logpriors = logpriors super(State, self).__init__(params, values, **kwargs) self.hyper_parameters = comp.ParameterGroup(hyper_params, hyper_values) self.build_funcs() @property def data(self): """ Class property: the raw data of the model fit. Should return a number (preferrably float) or an ndarray (essentially any object which as operands +-/...). This object is constant since it is data. """ pass @property def model(self): """ Class property: the current model fit to the data. Should return a number or ndarray. Ideally this object should be an object updated by the :func:`peri.states.State.update` function and simply returned in this property """ pass @property def residuals(self): """ Class property: the model residuals wrt data, residuals = data - model, :math:`R_i = D_i - M_i(\\theta)` """ return self.data - self.model @property def error(self): """ Class property: Sum of the squared errors, :math:`E = \sum_i (D_i - M_i(\\theta))^2` """ r = self.residuals.ravel() return np.dot(r,r) #faster than flatiter @property def loglikelihood(self): """ Class property: loglikelihood calculated by the model error, :math:`\\mathcal{L} = - \\frac{1}{2} \\sum\\left[ \\left(\\frac{D_i - M_i(\\theta)}{\sigma}\\right)^2 + \\log{(2\pi \sigma^2)} \\right]` """ sig = self.hyper_parameters.get_values('sigma') err = self.error N = np.size(self.data) return -0.5*err/sig**2 - np.log(np.sqrt(2*np.pi)*sig)*N @property def logposterior(self): """ Class property: log of posterior prob (including likelihood calculated by the model error and priors): self.logprior + self.loglikelihood """ return self.logprior + self.loglikelihood @property def logprior(self): """ Class property: logprior calculated from the sum of all prior objects """ return 0 # FIXME should return the sum of the log priors def update(self, params, values): """ Update a single parameter or group of parameters ``params`` with ``values``. Parameters ---------- params : string or list of strings Parameter names which to update value : number or list of numbers Values of those parameters which to update """ return super(State, self).update(params, values) def update_hyper(self, params, values): """ Update any single hyper parameter or group of parameters ``params`` with ``values``. Parameters ---------- params : string or list of strings Parameter names which to update value : number or list of numbers Values of those parameters which to update """ self.hyper_parameters.update(params, values) def update_sigma(self, sigma): """Updates the expected sigma of the noise distribution""" self.update_hyper('sigma', sigma) def push_update(self, params, values): """ Perform a parameter update and keep track of the change on the state. Same call structure as :func:`peri.states.States.update` """ curr = self.get_values(params) self.stack.append((params, curr)) self.update(params, values) def pop_update(self): """ Pop the last update from the stack push by :func:`peri.states.States.push_update` by undoing the chnage last performed. """ params, values = self.stack.pop() self.update(params, values) @contextmanager def temp_update(self, params, values): """ Context manager to temporarily perform a parameter update (by using the stack structure). To use: with state.temp_update(params, values): # measure the cost or something state.error """ self.push_update(params, values) yield self.pop_update() def param_all(self): return self.params def _grad_one_param(self, funct, p, dl=2e-5, rts=False, nout=1, **kwargs): """ Gradient of `func` wrt a single parameter `p`. (see _graddoc) """ vals = self.get_values(p) f0 = funct(**kwargs) self.update(p, vals+dl) f1 = funct(**kwargs) if rts: self.update(p, vals) if nout == 1: return (f1 - f0) / dl else: return [(f1[i] - f0[i]) / dl for i in range(nout)] def _hess_two_param(self, funct, p0, p1, dl=2e-5, rts=False, **kwargs): """ Hessian of `func` wrt two parameters `p0` and `p1`. (see _graddoc) """ vals0 = self.get_values(p0) vals1 = self.get_values(p1) f00 = funct(**kwargs) self.update(p0, vals0+dl) f10 = funct(**kwargs) self.update(p1, vals1+dl) f11 = funct(**kwargs) self.update(p0, vals0) f01 = funct(**kwargs) if rts: self.update(p0, vals0) self.update(p1, vals1) return (f11 - f10 - f01 + f00) / (dl**2) def _grad(self, funct, params=None, dl=2e-5, rts=False, nout=1, out=None, **kwargs): """ Gradient of `func` wrt a set of parameters params. (see _graddoc) """ if params is None: params = self.param_all() ps = util.listify(params) f0 = funct(**kwargs) # get the shape of the entire gradient to return and make an array calc_shape = ( lambda ar: (len(ps),) + (ar.shape if isinstance( ar, np.ndarray) else (1,))) if out is not None: grad = out # reference elif nout == 1: shape = calc_shape(f0) grad = np.zeros(shape) # must be preallocated for mem reasons else: shape = [calc_shape(f0[i]) for i in range(nout)] grad = [np.zeros(shp) for shp in shape] for i, p in enumerate(ps): if nout == 1: grad[i] = self._grad_one_param(funct, p, dl=dl, rts=rts, nout=nout, **kwargs) else: stuff = self._grad_one_param(funct, p, dl=dl, rts=rts, nout=nout, **kwargs) for a in range(nout): grad[a][i] = stuff[a] return grad # was np.squeeze(grad) def _jtj(self, funct, params=None, dl=2e-5, rts=False, **kwargs): """ jTj of a `func` wrt to parmaeters `params`. (see _graddoc) """ grad = self._grad(funct=funct, params=params, dl=dl, rts=rts, **kwargs) return np.dot(grad, grad.T) def _hess(self, funct, params=None, dl=2e-5, rts=False, **kwargs): """ Hessian of a `func` wrt to parmaeters `params`. (see _graddoc) """ if params is None: params = self.param_all() ps = util.listify(params) f0 = funct(**kwargs) # get the shape of the entire hessian, allocate an array shape = f0.shape if isinstance(f0, np.ndarray) else (1,) shape = (len(ps), len(ps)) + shape hess = np.zeros(shape) for i, pi in enumerate(ps): for j, pj in enumerate(ps[i:]): J = j + i thess = self._hess_two_param(funct, pi, pj, dl=dl, rts=rts, **kwargs) hess[i][J] = thess hess[J][i] = thess return np.squeeze(hess) def _dograddoc(self, f): f.__func__.__doc__ += _graddoc def build_funcs(self): """ Here, we build gradient and hessian functions based on the properties of a state that are generally wanted. For each one, we fill in _grad or _hess with a function that takes care of various options such as slicing and flattening. For example, `m` below takes the model, selects different indices from it, maybe flattens it and copies it. This is then used in the fisherinformation, gradmodel, and hessmodel functions. """ # create essentially lambda functions, but with a nice signature def m(inds=None, slicer=None, flat=True): return sample(self.model, inds=inds, slicer=slicer, flat=flat).copy() def r(inds=None, slicer=None, flat=True): return sample(self.residuals, inds=inds, slicer=slicer, flat=flat).copy() def l(): return self.loglikelihood def r_e(**kwargs): """sliced etc residuals, with state.error appended on""" return r(**kwargs), np.copy(self.error) def m_e(**kwargs): """sliced etc residuals, with state.error appended on""" return m(**kwargs), np.copy(self.error) # set the member functions using partial self.fisherinformation = partial(self._jtj, funct=m) self.gradloglikelihood = partial(self._grad, funct=l) self.hessloglikelihood = partial(self._hess, funct=l) self.gradmodel = partial(self._grad, funct=m) self.hessmodel = partial(self._hess, funct=m) self.JTJ = partial(self._jtj, funct=r) self.J = partial(self._grad, funct=r) self.J_e = partial(self._grad, funct=r_e, nout=2) self.gradmodel_e = partial(self._grad, funct=m_e, nout=2) # add the appropriate documentation to the following functions self.fisherinformation.__doc__ = _graddoc + _sampledoc self.gradloglikelihood.__doc__ = _graddoc self.hessloglikelihood.__doc__ = _graddoc self.gradmodel.__doc__ = _graddoc + _sampledoc self.hessmodel.__doc__ = _graddoc + _sampledoc self.JTJ.__doc__ = _graddoc + _sampledoc self.J.__doc__ = _graddoc + _sampledoc # add documentation to the private functions as well. this is done # slightly differently, hence the function call self._dograddoc(self._grad_one_param) self._dograddoc(self._hess_two_param) self._dograddoc(self._grad) self._dograddoc(self._hess) # the state object is a workaround so that other interfaces still # work. this should probably be removed in the long run class _Statewrap(object): def __init__(self, obj): self.obj = obj def __getitem__(self, d=None): if d is None: d = self.obj.params return util.delistify(self.obj.get_values(d), d) self.state = _Statewrap(self) def crb(self, params=None, *args, **kwargs): """ Calculate the diagonal elements of the minimum covariance of the model with respect to parameters params. ``*args`` and ``**kwargs`` go to ``fisherinformation``. """ fish = self.fisherinformation(params=params, *args, **kwargs) return np.sqrt(np.diag(np.linalg.inv(fish))) * self.sigma def __str__(self): return "{}\n{}".format(self.__class__.__name__, json.dumps(self.param_dict, indent=2)) def __repr__(self): return self.__str__() class PolyFitState(State): def __init__(self, x, y, order=2, coeffs=None, sigma=1.0): # FIXME -- add prior for sigma > 0 self._data = y self._xpts = x params = ['c-%i' %i for i in range(order)] values = coeffs if coeffs is not None else [0.0]*order params.append('sigma') values.append(1.0) super(PolyFitState, self).__init__( params=params, values=values, ordered=False ) self.update(self.params, self.values) def update(self, params, values): super(PolyFitState, self).update(params, values) self._model = np.polyval(self.values, self._xpts) @property def data(self): """ Get the raw data of the model fit """ return self._data @property def model(self): """ Get the current model fit to the data """ return self._model #============================================================================= # Image state which specializes to components with regions, etc. #============================================================================= class ImageState(State, comp.ComponentCollection): def __init__(self, image, comps, mdl=models.ConfocalImageModel(), sigma=0.04, priors=None, pad=24, model_as_data=False): """ The state object to create a confocal image. The model is that of a spatially varying illumination field, from which platonic particle shapes are subtracted. This is then spread with a point spread function (PSF). Parameters ----------- image : :class:`peri.util.Image` object The raw image with which to compare the model image from this class. This image should have been prepared through prepare_for_state, which does things such as padding necessary for this class. In the case of the RawImage, paths are used to keep track of the image object to save on pickle size. comp : list of :class:`peri.comp.comp.Component` or :class:`peri.comp.comp.ComponentCollection` Components used to make up the model image. Each separate component must be of a different category, otherwise combining them would be ambiguous. If you desire multiple Components of one category, combine them using a ComponentCollection (which has functions for combining) and supply that to the comps list. The component types must match the list of categories in the ``ImageState.catmap`` which tells how components are matched to parts of the model equation. mdl : :class:`peri.models.Model` object Model defining how to combine different Components into a single model. priors: list of ``peri.priors`` [default: ()] Whether or not to turn on overlap priors using neighborlists pad : integer or tuple of integers (optional) No recommended to set by hand. The padding level of the raw image needed by the PSF support. model_as_data : boolean Whether to use the model image as the true image after initializing """ self.dim = image.get_image().ndim self.sigma = sigma self.priors = priors self.pad = util.aN(pad, dim=self.dim) self.model_as_data = model_as_data comp.ComponentCollection.__init__(self, comps=comps) self.set_model(mdl=mdl) self.set_image(image) self.build_funcs() if self.model_as_data: self.model_to_data(self.sigma) def set_model(self, mdl): """ Setup the image model formation equation and corresponding objects into their various objects. `mdl` is a `peri.models.Model` object """ self.mdl = mdl self.mdl.check_inputs(self.comps) for c in self.comps: setattr(self, '_comp_'+c.category, c) def set_image(self, image): """ Update the current comparison (real) image """ if isinstance(image, np.ndarray): image = util.Image(image) if isinstance(image, util.NullImage): self.model_as_data = True else: self.model_as_data = False self.image = image self._data = self.image.get_padded_image(self.pad) # set up various slicers and Tiles associated with the image and pad self.oshape = util.Tile(self._data.shape) self.ishape = self.oshape.pad(-self.pad) self.inner = self.ishape.slicer for c in self.comps: c.set_shape(self.oshape, self.ishape) self._model = np.zeros(self._data.shape, dtype=np.float64) self._residuals = np.zeros(self._data.shape, dtype=np.float64) self.calculate_model() def set_tile_full(self): self.set_tile(self.oshape) def model_to_data(self, sigma=0.0): """ Switch out the data for the model's recreation of the data. """ im = self.model.copy() im += sigma*np.random.randn(*im.shape) self.set_image(util.NullImage(image=im)) def reset(self): for c in self.comps: c.initialize() self.calculate_model() def calculate_model(self): self._model[:] = self._calc_model() self._residuals[:] = self._calc_residuals() self._loglikelihood = self._calc_loglikelihood() self._logprior = self._calc_logprior() @property def data(self): """ Get the raw data of the model fit """ return self._data[self.inner] @property def model(self): """ Get the current model fit to the data """ return self._model[self.inner] @property def residuals(self): return self._residuals[self.inner] @property def loglikelihood(self): return self._loglikelihood def get_update_io_tiles(self, params, values): """ Get the tiles corresponding to a particular section of image needed to be updated. Inputs are the parameters and values. Returned is the padded tile, inner tile, and slicer to go between, but accounting for wrap with the edge of the image as necessary. """ # get the affected area of the model image otile = self.get_update_tile(params, values) if otile is None: return [None]*3 ptile = self.get_padding_size(otile) or util.Tile(0, dim=otile.dim) otile = util.Tile.intersection(otile, self.oshape) if (otile.shape <= 0).any(): raise UpdateError("update triggered invalid tile size") if (ptile.shape < 0).any() or (ptile.shape > self.oshape.shape).any(): raise UpdateError("update triggered invalid padding tile size") # now remove the part of the tile that is outside the image and pad the # interior part with that overhang. reflect the necessary padding back # into the image itself for the outer slice which we will call outer outer = otile.pad((ptile.shape+1)//2) inner, outer = outer.reflect_overhang(self.oshape) iotile = inner.translate(-outer.l) outer = util.Tile.intersection(outer, self.oshape) inner = util.Tile.intersection(inner, self.oshape) return outer, inner, iotile def update(self, params, values): """ Actually perform an image (etc) update based on a set of params and values. These parameter can be any present in the components in any number. If there is only one component affected then difference image updates will be employed. """ # FIXME needs to update priors comps = self.affected_components(params) if len(comps) == 0: return False # get the affected area of the model image otile, itile, iotile = self.get_update_io_tiles(params, values) if otile is None: return False # have all components update their tiles self.set_tile(otile) oldmodel = self._model[itile.slicer].copy() # here we diverge depending if there is only one component update # (so that we may calculate a variation / difference image) or if many # parameters are being update (should just update the whole model). if len(comps) == 1 and self.mdl.get_difference_model(comps[0].category): comp = comps[0] model0 = copy.deepcopy(comp.get()) super(ImageState, self).update(params, values) model1 = copy.deepcopy(comp.get()) diff = model1 - model0 diff = self.mdl.evaluate( self.comps, 'get', diffmap={comp.category: diff} ) if isinstance(model0, (float, int)): self._model[itile.slicer] += diff else: self._model[itile.slicer] += diff[iotile.slicer] else: super(ImageState, self).update(params, values) # allow the model to be evaluated using our components diff = self.mdl.evaluate(self.comps, 'get') self._model[itile.slicer] = diff[iotile.slicer] newmodel = self._model[itile.slicer].copy() # use the model image update to modify other class variables which # are hard to compute globally for small local updates self.update_from_model_change(oldmodel, newmodel, itile) return True def get(self, name): """ Return component by category name """ for c in self.comps: if c.category == name: return c return None def set(self, name, obj): comp.ComponentCollection.set(self, name, obj) obj.set_shape(self.oshape, self.ishape) self.calculate_model() def _calc_model(self): self.set_tile_full() return self.mdl.evaluate(self.comps, 'get') def _calc_residuals(self): return self._data - self._model def _calc_logprior(self): """Allows for fast local updates of log-priors""" return 0. # FIXME this should be incorporated somewhere def _calc_loglikelihood(self, model=None, tile=None): """Allows for fast local updates of log-likelihood""" if model is None: res = self.residuals else: res = model - self._data[tile.slicer] sig, isig = self.sigma, 1.0/self.sigma nlogs = -np.log(np.sqrt(2*np.pi)*sig)*res.size return -0.5*isig*isig*np.dot(res.flat, res.flat) + nlogs def update_sigma(self, sigma): # FIXME hyperparameters.... self.sigma = sigma self._loglikelihood = self._calc_loglikelihood() def update_from_model_change(self, oldmodel, newmodel, tile): """ Update various internal variables from a model update from oldmodel to newmodel for the tile `tile` """ self._loglikelihood -= self._calc_loglikelihood(oldmodel, tile=tile) self._loglikelihood += self._calc_loglikelihood(newmodel, tile=tile) self._residuals[tile.slicer] = self._data[tile.slicer] - newmodel def exports(self): raise NotImplementedError('inherited but not relevant') def register(self, parent): raise NotImplementedError('inherited but not relevant') def __str__(self): def _pad(s): return re.subn('(\n)', '\n ', s)[0] stats = _pad('\nstats: E={} LL={}\n'.format(self.error, self.loglikelihood)) model = _pad('model: {}\n'.format(str(self.mdl))) image = _pad('image: {}\n'.format(str(self.image))) comps = _pad('\n'.join([c.category+': '+str(c) for c in self.comps])) return "{} [{}{}{}{}{}\n]".format( self.__class__.__name__, stats, model, image, _pad('-'*70+'\n'), comps ) def __getstate__(self): return {'image': self.image, 'comps': self.comps, 'mdl': self.mdl, 'sigma': self.sigma, 'priors': self.priors, 'pad': self.pad, 'model_as_data': self.model_as_data} def __setstate__(self, idct): self.__init__(**idct) def set_mem_level(self, mem_level='hi'): """ Sets the memory usage level of the state. Parameters ---------- mem_level : string Can be set to one of: * hi : all mem's are np.float64 * med-hi : image, platonic are float32, rest are float64 * med : all mem's are float32 * med-lo : image, platonic are float16, rest float32 * lo : all are float16, which is bad for accuracy. Notes ----- Right now the PSF is not affected by the mem-level changes, which is OK for mem but it means that self._model, self._residuals are always float64, which can be a chunk of mem. """ #A little thing to parse strings for convenience: key = ''.join([c if c in 'mlh' else '' for c in mem_level]) if key not in ['h','mh','m','ml','m', 'l']: raise ValueError('mem_level must be one of hi, med-hi, med, med-lo, lo.') mem_levels = { 'h': [np.float64, np.float64], 'mh': [np.float64, np.float32], 'm': [np.float32, np.float32], 'ml': [np.float32, np.float16], 'l': [np.float16, np.float16] } hi_lvl, lo_lvl = mem_levels[key] cat_lvls = {'obj':lo_lvl, 'ilm':hi_lvl, 'bkg':lo_lvl } #no psf... self.image.float_precision = hi_lvl self.image.image = self.image.image.astype(lo_lvl) self.set_image(self.image) for cat in cat_lvls.keys(): obj = self.get(cat) #check if it's a component collection if hasattr(obj, 'comps'): for c in obj.comps: c.float_precision = lo_lvl else: obj.float_precision = lo_lvl self._model = self._model.astype(hi_lvl) self._residuals = self._model.astype(hi_lvl) self.reset() def save(state, filename=None, desc='', extra=None): """ Save the current state with extra information (for example samples and LL from the optimization procedure). Parameters ---------- state : peri.states.ImageState the state object which to save filename : string if provided, will override the default that is constructed based on the state's raw image file. If there is no filename and the state has a RawImage, the it is saved to RawImage.filename + "-peri-save.pkl" desc : string if provided, will augment the default filename to be RawImage.filename + '-peri-' + desc + '.pkl' extra : list of pickleable objects if provided, will be saved with the state """ if isinstance(state.image, util.RawImage): desc = desc or 'save' filename = filename or state.image.filename + '-peri-' + desc + '.pkl' else: if not filename: raise AttributeError("Must provide filename since RawImage is not used") if extra is None: save = state else: save = [state] + extra if os.path.exists(filename): ff = "{}-tmp-for-copy".format(filename) if os.path.exists(ff): os.remove(ff) os.rename(filename, ff) pickle.dump(save, open(filename, 'wb'), protocol=2) def load(filename): """ Load the state from the given file, moving to the file's directory during load (temporarily, moving back after loaded) Parameters ---------- filename : string name of the file to open, should be a .pkl file """ path, name = os.path.split(filename) path = path or '.' with util.indir(path): return pickle.load(open(name, 'rb'))
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 json import os import subprocess from typing import Optional # noqa: W0611 from airflow import settings from airflow.exceptions import AirflowException from airflow.models import Connection # Please keep these variables in alphabetical order. from tests.test_utils import AIRFLOW_MAIN_FOLDER from tests.test_utils.logging_command_executor import LoggingCommandExecutor GCP_AI_KEY = 'gcp_ai.json' GCP_AUTOML_KEY = 'gcp_automl.json' GCP_BIGQUERY_KEY = 'gcp_bigquery.json' GCP_BIGTABLE_KEY = 'gcp_bigtable.json' GCP_CLOUD_BUILD_KEY = 'gcp_cloud_build.json' GCP_CLOUDSQL_KEY = 'gcp_cloudsql.json' GCP_COMPUTE_KEY = 'gcp_compute.json' GCP_COMPUTE_SSH_KEY = 'gcp_compute_ssh.json' GCP_DATAFLOW_KEY = 'gcp_dataflow.json' GCP_DATAFUSION_KEY = 'gcp_datafusion.json' GCP_DATAPROC_KEY = 'gcp_dataproc.json' GCP_DATASTORE_KEY = 'gcp_datastore.json' GCP_DLP_KEY = 'gcp_dlp.json' GCP_FUNCTION_KEY = 'gcp_function.json' GCP_GCS_KEY = 'gcp_gcs.json' GCP_GCS_TRANSFER_KEY = 'gcp_gcs_transfer.json' GCP_GKE_KEY = "gcp_gke.json" GCP_LIFE_SCIENCES_KEY = 'gcp_life_sciences.json' GCP_MEMORYSTORE = 'gcp_memorystore.json' GCP_PUBSUB_KEY = "gcp_pubsub.json" GCP_SECRET_MANAGER_KEY = 'gcp_secret_manager.json' GCP_SPANNER_KEY = 'gcp_spanner.json' GCP_STACKDDRIVER = 'gcp_stackdriver.json' GCP_TASKS_KEY = 'gcp_tasks.json' GMP_KEY = 'gmp.json' G_FIREBASE_KEY = 'g_firebase.json' GCP_AWS_KEY = 'gcp_aws.json' KEYPATH_EXTRA = 'extra__google_cloud_platform__key_path' KEYFILE_DICT_EXTRA = 'extra__google_cloud_platform__keyfile_dict' SCOPE_EXTRA = 'extra__google_cloud_platform__scope' PROJECT_EXTRA = 'extra__google_cloud_platform__project' class GcpAuthenticator(LoggingCommandExecutor): """ Initialises the authenticator. :param gcp_key: name of the key to use for authentication (see GCP_*_KEY values) :param project_extra: optional extra project parameter passed to google cloud connection """ original_account = None # type: Optional[str] def __init__(self, gcp_key: str, project_extra: Optional[str] = None): super().__init__() self.gcp_key = gcp_key self.project_extra = project_extra self.project_id = self.get_project_id() self.full_key_path = None self._set_key_path() @staticmethod def get_project_id(): return os.environ.get('GCP_PROJECT_ID') def set_key_path_in_airflow_connection(self): """ Set key path in 'google_cloud_default' connection to point to the full key path :return: None """ session = settings.Session() try: conn = session.query(Connection).filter(Connection.conn_id == 'google_cloud_default')[0] extras = conn.extra_dejson extras[KEYPATH_EXTRA] = self.full_key_path if extras.get(KEYFILE_DICT_EXTRA): del extras[KEYFILE_DICT_EXTRA] extras[SCOPE_EXTRA] = 'https://www.googleapis.com/auth/cloud-platform' extras[PROJECT_EXTRA] = self.project_extra if self.project_extra else self.project_id conn.extra = json.dumps(extras) session.commit() except BaseException as ex: self.log.error('Airflow DB Session error: %s', str(ex)) session.rollback() raise finally: session.close() def set_dictionary_in_airflow_connection(self): """ Set dictionary in 'google_cloud_default' connection to contain content of the json service account file. :return: None """ session = settings.Session() try: conn = session.query(Connection).filter(Connection.conn_id == 'google_cloud_default')[0] extras = conn.extra_dejson with open(self.full_key_path) as path_file: content = json.load(path_file) extras[KEYFILE_DICT_EXTRA] = json.dumps(content) if extras.get(KEYPATH_EXTRA): del extras[KEYPATH_EXTRA] extras[SCOPE_EXTRA] = 'https://www.googleapis.com/auth/cloud-platform' extras[PROJECT_EXTRA] = self.project_extra conn.extra = json.dumps(extras) session.commit() except BaseException as ex: self.log.error('Airflow DB Session error: %s', str(ex)) session.rollback() raise finally: session.close() def _set_key_path(self): """ Sets full key path - if GCP_CONFIG_DIR points to absolute directory, it tries to find the key in this directory. Otherwise it assumes that Airflow is running from the directory where configuration is checked out next to airflow directory in config directory it tries to find the key folder in the workspace's config directory. :param : name of the key file to find. """ if "GCP_CONFIG_DIR" in os.environ: gcp_config_dir = os.environ["GCP_CONFIG_DIR"] else: gcp_config_dir = os.path.join(AIRFLOW_MAIN_FOLDER, os.pardir, "config") if not os.path.isdir(gcp_config_dir): self.log.info("The %s is not a directory", gcp_config_dir) key_dir = os.path.join(gcp_config_dir, "keys") if not os.path.isdir(key_dir): self.log.error("The %s is not a directory", key_dir) return key_path = os.path.join(key_dir, self.gcp_key) if not os.path.isfile(key_path): self.log.error("The %s file is missing", key_path) self.full_key_path = key_path def _validate_key_set(self): if self.full_key_path is None: raise AirflowException("The gcp_key is not set!") if not os.path.isfile(self.full_key_path): raise AirflowException( "The key {} could not be found. Please copy it to the {} path.".format( self.gcp_key, self.full_key_path ) ) def gcp_authenticate(self): """ Authenticate with service account specified via key name. """ self._validate_key_set() self.log.info("Setting the Google Cloud key to %s", self.full_key_path) # Checking if we can authenticate using service account credentials provided self.execute_cmd( [ 'gcloud', 'auth', 'activate-service-account', f'--key-file={self.full_key_path}', f'--project={self.project_id}', ] ) self.set_key_path_in_airflow_connection() def gcp_revoke_authentication(self): """ Change default authentication to none - which is not existing one. """ self._validate_key_set() self.log.info("Revoking authentication - setting it to none") self.execute_cmd(['gcloud', 'config', 'get-value', 'account', f'--project={self.project_id}']) self.execute_cmd(['gcloud', 'config', 'set', 'account', 'none', f'--project={self.project_id}']) def gcp_store_authentication(self): """ Store authentication as it was originally so it can be restored and revoke authentication. """ self._validate_key_set() if not GcpAuthenticator.original_account: GcpAuthenticator.original_account = self.check_output( ['gcloud', 'config', 'get-value', 'account', f'--project={self.project_id}'] ).decode('utf-8') self.log.info("Storing account: to restore it later %s", GcpAuthenticator.original_account) def gcp_restore_authentication(self): """ Restore authentication to the original one one. """ self._validate_key_set() if GcpAuthenticator.original_account: self.log.info("Restoring original account stored: %s", GcpAuthenticator.original_account) subprocess.call( [ 'gcloud', 'config', 'set', 'account', GcpAuthenticator.original_account, f'--project={self.project_id}', ] ) else: self.log.info("Not restoring the original Google Cloud account: it is not set")
""" Utililty objects for the polynomial modules. This module provides: error and warning objects; a polynomial base class; and some routines used in both the `polynomial` and `chebyshev` modules. Error objects ------------- - `PolyError` -- base class for this sub-package's errors. - `PolyDomainError` -- raised when domains are "mismatched." Warning objects --------------- - `RankWarning` -- raised by a least-squares fit when a rank-deficient matrix is encountered. Base class ---------- - `PolyBase` -- The base class for the `Polynomial` and `Chebyshev` classes. Functions --------- - `as_series` -- turns a list of array_likes into 1-D arrays of common type. - `trimseq` -- removes trailing zeros. - `trimcoef` -- removes trailing coefficients that are less than a given magnitude (thereby removing the corresponding terms). - `getdomain` -- returns a domain appropriate for a given set of abscissae. - `mapdomain` -- maps points between domains. - `mapparms` -- parameters of the linear map between domains. """ from __future__ import division __all__ = ['RankWarning', 'PolyError', 'PolyDomainError', 'PolyBase', 'as_series', 'trimseq', 'trimcoef', 'getdomain', 'mapdomain', 'mapparms'] import warnings import numpy as np import sys # # Warnings and Exceptions # class RankWarning(UserWarning) : """Issued by chebfit when the design matrix is rank deficient.""" pass class PolyError(Exception) : """Base class for errors in this module.""" pass class PolyDomainError(PolyError) : """Issued by the generic Poly class when two domains don't match. This is raised when an binary operation is passed Poly objects with different domains. """ pass # # Base class for all polynomial types # class PolyBase(object) : pass # # We need the any function for python < 2.5 # if sys.version_info[:2] < (2,5) : def any(iterable) : for element in iterable: if element : return True return False # # Helper functions to convert inputs to 1-D arrays # def trimseq(seq) : """Remove small Poly series coefficients. Parameters ---------- seq : sequence Sequence of Poly series coefficients. This routine fails for empty sequences. Returns ------- series : sequence Subsequence with trailing zeros removed. If the resulting sequence would be empty, return the first element. The returned sequence may or may not be a view. Notes ----- Do not lose the type info if the sequence contains unknown objects. """ if len(seq) == 0 : return seq else : for i in range(len(seq) - 1, -1, -1) : if seq[i] != 0 : break return seq[:i+1] def as_series(alist, trim=True) : """ Return argument as a list of 1-d arrays. The returned list contains array(s) of dtype double, complex double, or object. A 1-d argument of shape ``(N,)`` is parsed into ``N`` arrays of size one; a 2-d argument of shape ``(M,N)`` is parsed into ``M`` arrays of size ``N`` (i.e., is "parsed by row"); and a higher dimensional array raises a Value Error if it is not first reshaped into either a 1-d or 2-d array. Parameters ---------- a : array_like A 1- or 2-d array_like trim : boolean, optional When True, trailing zeros are removed from the inputs. When False, the inputs are passed through intact. Returns ------- [a1, a2,...] : list of 1-D arrays A copy of the input data as a list of 1-d arrays. Raises ------ ValueError : Raised when `as_series` cannot convert its input to 1-d arrays, or at least one of the resulting arrays is empty. Examples -------- >>> from numpy import polynomial as P >>> a = np.arange(4) >>> P.as_series(a) [array([ 0.]), array([ 1.]), array([ 2.]), array([ 3.])] >>> b = np.arange(6).reshape((2,3)) >>> P.as_series(b) [array([ 0., 1., 2.]), array([ 3., 4., 5.])] """ arrays = [np.array(a, ndmin=1, copy=0) for a in alist] if min([a.size for a in arrays]) == 0 : raise ValueError("Coefficient array is empty") if any([a.ndim != 1 for a in arrays]) : raise ValueError("Coefficient array is not 1-d") if trim : arrays = [trimseq(a) for a in arrays] if any([a.dtype == np.dtype(object) for a in arrays]) : ret = [] for a in arrays : if a.dtype != np.dtype(object) : tmp = np.empty(len(a), dtype=np.dtype(object)) tmp[:] = a[:] ret.append(tmp) else : ret.append(a.copy()) else : try : dtype = np.common_type(*arrays) except : raise ValueError("Coefficient arrays have no common type") ret = [np.array(a, copy=1, dtype=dtype) for a in arrays] return ret def trimcoef(c, tol=0) : """ Remove "small" "trailing" coefficients from a polynomial. "Small" means "small in absolute value" and is controlled by the parameter `tol`; "trailing" means highest order coefficient(s), e.g., in ``[0, 1, 1, 0, 0]`` (which represents ``0 + x + x**2 + 0*x**3 + 0*x**4``) both the 3-rd and 4-th order coefficients would be "trimmed." Parameters ---------- c : array_like 1-d array of coefficients, ordered from lowest order to highest. tol : number, optional Trailing (i.e., highest order) elements with absolute value less than or equal to `tol` (default value is zero) are removed. Returns ------- trimmed : ndarray 1-d array with trailing zeros removed. If the resulting series would be empty, a series containing a single zero is returned. Raises ------ ValueError If `tol` < 0 See Also -------- trimseq Examples -------- >>> from numpy import polynomial as P >>> P.trimcoef((0,0,3,0,5,0,0)) array([ 0., 0., 3., 0., 5.]) >>> P.trimcoef((0,0,1e-3,0,1e-5,0,0),1e-3) # item == tol is trimmed array([ 0.]) >>> i = complex(0,1) # works for complex >>> P.trimcoef((3e-4,1e-3*(1-i),5e-4,2e-5*(1+i)), 1e-3) array([ 0.0003+0.j , 0.0010-0.001j]) """ if tol < 0 : raise ValueError("tol must be non-negative") [c] = as_series([c]) [ind] = np.where(np.abs(c) > tol) if len(ind) == 0 : return c[:1]*0 else : return c[:ind[-1] + 1].copy() def getdomain(x) : """ Return a domain suitable for given abscissae. Find a domain suitable for a polynomial or Chebyshev series defined at the values supplied. Parameters ---------- x : array_like 1-d array of abscissae whose domain will be determined. Returns ------- domain : ndarray 1-d array containing two values. If the inputs are complex, then the two returned points are the lower left and upper right corners of the smallest rectangle (aligned with the axes) in the complex plane containing the points `x`. If the inputs are real, then the two points are the ends of the smallest interval containing the points `x`. See Also -------- mapparms, mapdomain Examples -------- >>> from numpy.polynomial import polyutils as pu >>> points = np.arange(4)**2 - 5; points array([-5, -4, -1, 4]) >>> pu.getdomain(points) array([-5., 4.]) >>> c = np.exp(complex(0,1)*np.pi*np.arange(12)/6) # unit circle >>> pu.getdomain(c) array([-1.-1.j, 1.+1.j]) """ [x] = as_series([x], trim=False) if x.dtype.char in np.typecodes['Complex'] : rmin, rmax = x.real.min(), x.real.max() imin, imax = x.imag.min(), x.imag.max() return np.array((complex(rmin, imin), complex(rmax, imax))) else : return np.array((x.min(), x.max())) def mapparms(old, new) : """ Linear map parameters between domains. Return the parameters of the linear map ``offset + scale*x`` that maps `old` to `new` such that ``old[i] -> new[i]``, ``i = 0, 1``. Parameters ---------- old, new : array_like Domains. Each domain must (successfully) convert to a 1-d array containing precisely two values. Returns ------- offset, scale : scalars The map ``L(x) = offset + scale*x`` maps the first domain to the second. See Also -------- getdomain, mapdomain Notes ----- Also works for complex numbers, and thus can be used to calculate the parameters required to map any line in the complex plane to any other line therein. Examples -------- >>> from numpy import polynomial as P >>> P.mapparms((-1,1),(-1,1)) (0.0, 1.0) >>> P.mapparms((1,-1),(-1,1)) (0.0, -1.0) >>> i = complex(0,1) >>> P.mapparms((-i,-1),(1,i)) ((1+1j), (1+0j)) """ oldlen = old[1] - old[0] newlen = new[1] - new[0] off = (old[1]*new[0] - old[0]*new[1])/oldlen scl = newlen/oldlen return off, scl def mapdomain(x, old, new) : """ Apply linear map to input points. The linear map ``offset + scale*x`` that maps the domain `old` to the domain `new` is applied to the points `x`. Parameters ---------- x : array_like Points to be mapped. If `x` is a subtype of ndarray the subtype will be preserved. old, new : array_like The two domains that determine the map. Each must (successfully) convert to 1-d arrays containing precisely two values. Returns ------- x_out : ndarray Array of points of the same shape as `x`, after application of the linear map between the two domains. See Also -------- getdomain, mapparms Notes ----- Effectively, this implements: .. math :: x\\_out = new[0] + m(x - old[0]) where .. math :: m = \\frac{new[1]-new[0]}{old[1]-old[0]} Examples -------- >>> from numpy import polynomial as P >>> old_domain = (-1,1) >>> new_domain = (0,2*np.pi) >>> x = np.linspace(-1,1,6); x array([-1. , -0.6, -0.2, 0.2, 0.6, 1. ]) >>> x_out = P.mapdomain(x, old_domain, new_domain); x_out array([ 0. , 1.25663706, 2.51327412, 3.76991118, 5.02654825, 6.28318531]) >>> x - P.mapdomain(x_out, new_domain, old_domain) array([ 0., 0., 0., 0., 0., 0.]) Also works for complex numbers (and thus can be used to map any line in the complex plane to any other line therein). >>> i = complex(0,1) >>> old = (-1 - i, 1 + i) >>> new = (-1 + i, 1 - i) >>> z = np.linspace(old[0], old[1], 6); z array([-1.0-1.j , -0.6-0.6j, -0.2-0.2j, 0.2+0.2j, 0.6+0.6j, 1.0+1.j ]) >>> new_z = P.mapdomain(z, old, new); new_z array([-1.0+1.j , -0.6+0.6j, -0.2+0.2j, 0.2-0.2j, 0.6-0.6j, 1.0-1.j ]) """ x = np.asanyarray(x) off, scl = mapparms(old, new) return off + scl*x
# -*- coding: utf-8 -*- """ File related views, including view_file, edit_file, view_history_file, view_trash_file, view_snapshot_file """ import os import hashlib import json import stat import tempfile import urllib import urllib2 import chardet from django.contrib.sites.models import Site, RequestSite from django.core.urlresolvers import reverse from django.contrib import messages from django.http import HttpResponse, HttpResponseBadRequest, Http404, \ HttpResponseRedirect from django.shortcuts import render_to_response, redirect from django.template import Context, loader, RequestContext from django.template.loader import render_to_string from django.utils.http import urlquote from django.utils.translation import ugettext as _ import seaserv from seaserv import seafile_api from pysearpc import SearpcError from seahub.auth.decorators import login_required from seahub.base.decorators import user_mods_check from seahub.base.models import FileContributors from seahub.wiki.models import PersonalWiki, WikiDoesNotExist, WikiPageMissing from seahub.wiki import get_personal_wiki_page, get_personal_wiki_repo, \ convert_wiki_link, get_wiki_pages from seahub.wiki.forms import WikiCreateForm, WikiNewPageForm from seahub.wiki.utils import clean_page_name from seahub.utils import render_error @login_required @user_mods_check def personal_wiki(request, page_name="home"): username = request.user.username wiki_exists = True try: content, repo, dirent = get_personal_wiki_page(username, page_name) except WikiDoesNotExist: wiki_exists = False owned_repos = seafile_api.get_owned_repo_list(username) owned_repos = [r for r in owned_repos if not r.encrypted] return render_to_response("wiki/personal_wiki.html", { "wiki_exists": wiki_exists, "owned_repos": owned_repos, }, context_instance=RequestContext(request)) except WikiPageMissing: repo = get_personal_wiki_repo(username) filename = clean_page_name(page_name) + '.md' if not seaserv.post_empty_file(repo.id, "/", filename, username): return render_error(request, _("Failed to create wiki page. Please retry later.")) return HttpResponseRedirect(reverse('personal_wiki', args=[page_name])) else: url_prefix = reverse('personal_wiki', args=[]) content = convert_wiki_link(content, url_prefix, repo.id, username) # fetch file latest contributor and last modified path = '/' + dirent.obj_name file_path_hash = hashlib.md5(urllib2.quote(path.encode('utf-8'))).hexdigest()[:12] contributors, last_modified, last_commit_id = \ FileContributors.objects.get_file_contributors( repo.id, path.encode('utf-8'), file_path_hash, dirent.obj_id) latest_contributor = contributors[0] if contributors else None wiki_index_exists = True index_pagename = 'index' index_content = None try: index_content, index_repo, index_dirent = get_personal_wiki_page(username, index_pagename) except (WikiDoesNotExist, WikiPageMissing) as e: wiki_index_exists = False else: index_content = convert_wiki_link(index_content, url_prefix, index_repo.id, username) return render_to_response("wiki/personal_wiki.html", { "wiki_exists": wiki_exists, "content": content, "page": os.path.splitext(dirent.obj_name)[0], "last_modified": last_modified, "latest_contributor": latest_contributor, "path": path, "repo_id": repo.id, "search_repo_id": repo.id, "search_wiki": True, "wiki_index_exists": wiki_index_exists, "index_content": index_content, }, context_instance=RequestContext(request)) @login_required @user_mods_check def personal_wiki_pages(request): """ List personal wiki pages. """ try: username = request.user.username repo = get_personal_wiki_repo(username) pages = get_wiki_pages(repo) except SearpcError: return render_error(request, _('Internal Server Error')) except WikiDoesNotExist: return render_error(request, _('Wiki does not exists.')) return render_to_response("wiki/personal_wiki_pages.html", { "pages": pages, "repo_id": repo.id, "search_repo_id": repo.id, "search_wiki": True, }, context_instance=RequestContext(request)) @login_required def personal_wiki_create(request): if request.method != 'POST': raise Http404 content_type = 'application/json; charset=utf-8' def json_error(err_msg, status=400): result = {'error': err_msg} return HttpResponse(json.dumps(result), status=status, content_type=content_type) if not request.user.permissions.can_add_repo(): return json_error(_('You do not have permission to create wiki'), 403) form = WikiCreateForm(request.POST) if not form.is_valid(): return json_error(str(form.errors.values()[0])) # create group repo in user context repo_name = form.cleaned_data['repo_name'] repo_desc = form.cleaned_data['repo_desc'] username = request.user.username passwd = None permission = "rw" repo_id = seaserv.create_repo(repo_name, repo_desc, username, passwd) if not repo_id: return json_error(_(u'Failed to create'), 500) PersonalWiki.objects.save_personal_wiki(username=username, repo_id=repo_id) # create home page page_name = "home.md" if not seaserv.post_empty_file(repo_id, "/", page_name, username): return json_error(_(u'Failed to create home page. Please retry later'), 500) next = reverse('personal_wiki', args=[]) return HttpResponse(json.dumps({'href': next}), content_type=content_type) @login_required def personal_wiki_use_lib(request): if request.method != 'POST': raise Http404 repo_id = request.POST.get('dst_repo', '') username = request.user.username next = reverse('personal_wiki', args=[]) repo = seafile_api.get_repo(repo_id) if repo is None: messages.error(request, _('Failed to set wiki library.')) return HttpResponseRedirect(next) PersonalWiki.objects.save_personal_wiki(username=username, repo_id=repo_id) # create home page if not exist page_name = "home.md" if not seaserv.get_file_id_by_path(repo_id, "/" + page_name): if not seaserv.post_empty_file(repo_id, "/", page_name, username): messages.error(request, _('Failed to create home page. Please retry later')) return HttpResponseRedirect(next) @login_required def personal_wiki_page_new(request, page_name="home"): if request.method == 'POST': page_name = request.POST.get('page_name', '') if not page_name: return HttpResponseRedirect(request.META.get('HTTP_REFERER')) page_name = clean_page_name(page_name) try: repo = get_personal_wiki_repo(request.user.username) except WikiDoesNotExist: return render_error(request, _('Wiki is not found.')) filename = page_name + ".md" filepath = "/" + page_name + ".md" # check whether file exists if seaserv.get_file_id_by_path(repo.id, filepath): return render_error(request, _('Page "%s" already exists.') % filename) if not seaserv.post_empty_file(repo.id, "/", filename, request.user.username): return render_error(request, _('Failed to create wiki page. Please retry later.')) url = "%s?p=%s&from=personal_wiki_page_new" % ( reverse('file_edit', args=[repo.id]), urlquote(filepath.encode('utf-8'))) return HttpResponseRedirect(url) @login_required def personal_wiki_page_edit(request, page_name="home"): try: repo = get_personal_wiki_repo(request.user.username) except WikiDoesNotExist: return render_error(request, _('Wiki is not found.')) filepath = "/" + page_name + ".md" url = "%s?p=%s&from=personal_wiki_page_edit" % ( reverse('file_edit', args=[repo.id]), urllib2.quote(filepath.encode('utf-8'))) return HttpResponseRedirect(url) @login_required def personal_wiki_page_delete(request, page_name): try: repo = get_personal_wiki_repo(request.user.username) except WikiDoesNotExist: return render_error(request, _('Wiki is not found.')) file_name = page_name + '.md' username = request.user.username if seaserv.del_file(repo.id, '/', file_name, username): messages.success(request, 'Successfully deleted "%s".' % page_name) else: messages.error(request, 'Failed to delete "%s". Please retry later.' % page_name) return HttpResponseRedirect(reverse('personal_wiki', args=[]))
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Hoverlabel(_BaseTraceHierarchyType): # class properties # -------------------- _parent_path_str = "scatterpolar" _path_str = "scatterpolar.hoverlabel" _valid_props = { "align", "alignsrc", "bgcolor", "bgcolorsrc", "bordercolor", "bordercolorsrc", "font", "namelength", "namelengthsrc", } # align # ----- @property def align(self): """ Sets the horizontal alignment of the text content within hover label box. Has an effect only if the hover label text spans more two or more lines The 'align' property is an enumeration that may be specified as: - One of the following enumeration values: ['left', 'right', 'auto'] - A tuple, list, or one-dimensional numpy array of the above Returns ------- Any|numpy.ndarray """ return self["align"] @align.setter def align(self, val): self["align"] = val # alignsrc # -------- @property def alignsrc(self): """ Sets the source reference on Chart Studio Cloud for align . The 'alignsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["alignsrc"] @alignsrc.setter def alignsrc(self, val): self["alignsrc"] = val # bgcolor # ------- @property def bgcolor(self): """ Sets the background color of the hover labels for this trace The 'bgcolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen - A list or array of any of the above Returns ------- str|numpy.ndarray """ return self["bgcolor"] @bgcolor.setter def bgcolor(self, val): self["bgcolor"] = val # bgcolorsrc # ---------- @property def bgcolorsrc(self): """ Sets the source reference on Chart Studio Cloud for bgcolor . The 'bgcolorsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["bgcolorsrc"] @bgcolorsrc.setter def bgcolorsrc(self, val): self["bgcolorsrc"] = val # bordercolor # ----------- @property def bordercolor(self): """ Sets the border color of the hover labels for this trace. The 'bordercolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen - A list or array of any of the above Returns ------- str|numpy.ndarray """ return self["bordercolor"] @bordercolor.setter def bordercolor(self, val): self["bordercolor"] = val # bordercolorsrc # -------------- @property def bordercolorsrc(self): """ Sets the source reference on Chart Studio Cloud for bordercolor . The 'bordercolorsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["bordercolorsrc"] @bordercolorsrc.setter def bordercolorsrc(self, val): self["bordercolorsrc"] = val # font # ---- @property def font(self): """ Sets the font used in hover labels. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.scatterpolar.hoverlabel.Font` - A dict of string/value properties that will be passed to the Font constructor Supported dict properties: color colorsrc Sets the source reference on Chart Studio Cloud for color . family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". familysrc Sets the source reference on Chart Studio Cloud for family . size sizesrc Sets the source reference on Chart Studio Cloud for size . Returns ------- plotly.graph_objs.scatterpolar.hoverlabel.Font """ return self["font"] @font.setter def font(self, val): self["font"] = val # namelength # ---------- @property def namelength(self): """ Sets the default length (in number of characters) of the trace name in the hover labels for all traces. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis. The 'namelength' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [-1, 9223372036854775807] - A tuple, list, or one-dimensional numpy array of the above Returns ------- int|numpy.ndarray """ return self["namelength"] @namelength.setter def namelength(self, val): self["namelength"] = val # namelengthsrc # ------------- @property def namelengthsrc(self): """ Sets the source reference on Chart Studio Cloud for namelength . The 'namelengthsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["namelengthsrc"] @namelengthsrc.setter def namelengthsrc(self, val): self["namelengthsrc"] = val # Self properties description # --------------------------- @property def _prop_descriptions(self): return """\ align Sets the horizontal alignment of the text content within hover label box. Has an effect only if the hover label text spans more two or more lines alignsrc Sets the source reference on Chart Studio Cloud for align . bgcolor Sets the background color of the hover labels for this trace bgcolorsrc Sets the source reference on Chart Studio Cloud for bgcolor . bordercolor Sets the border color of the hover labels for this trace. bordercolorsrc Sets the source reference on Chart Studio Cloud for bordercolor . font Sets the font used in hover labels. namelength Sets the default length (in number of characters) of the trace name in the hover labels for all traces. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis. namelengthsrc Sets the source reference on Chart Studio Cloud for namelength . """ def __init__( self, arg=None, align=None, alignsrc=None, bgcolor=None, bgcolorsrc=None, bordercolor=None, bordercolorsrc=None, font=None, namelength=None, namelengthsrc=None, **kwargs ): """ Construct a new Hoverlabel object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.scatterpolar.Hoverlabel` align Sets the horizontal alignment of the text content within hover label box. Has an effect only if the hover label text spans more two or more lines alignsrc Sets the source reference on Chart Studio Cloud for align . bgcolor Sets the background color of the hover labels for this trace bgcolorsrc Sets the source reference on Chart Studio Cloud for bgcolor . bordercolor Sets the border color of the hover labels for this trace. bordercolorsrc Sets the source reference on Chart Studio Cloud for bordercolor . font Sets the font used in hover labels. namelength Sets the default length (in number of characters) of the trace name in the hover labels for all traces. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis. namelengthsrc Sets the source reference on Chart Studio Cloud for namelength . Returns ------- Hoverlabel """ super(Hoverlabel, self).__init__("hoverlabel") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.scatterpolar.Hoverlabel constructor must be a dict or an instance of :class:`plotly.graph_objs.scatterpolar.Hoverlabel`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) # Populate data dict with properties # ---------------------------------- _v = arg.pop("align", None) _v = align if align is not None else _v if _v is not None: self["align"] = _v _v = arg.pop("alignsrc", None) _v = alignsrc if alignsrc is not None else _v if _v is not None: self["alignsrc"] = _v _v = arg.pop("bgcolor", None) _v = bgcolor if bgcolor is not None else _v if _v is not None: self["bgcolor"] = _v _v = arg.pop("bgcolorsrc", None) _v = bgcolorsrc if bgcolorsrc is not None else _v if _v is not None: self["bgcolorsrc"] = _v _v = arg.pop("bordercolor", None) _v = bordercolor if bordercolor is not None else _v if _v is not None: self["bordercolor"] = _v _v = arg.pop("bordercolorsrc", None) _v = bordercolorsrc if bordercolorsrc is not None else _v if _v is not None: self["bordercolorsrc"] = _v _v = arg.pop("font", None) _v = font if font is not None else _v if _v is not None: self["font"] = _v _v = arg.pop("namelength", None) _v = namelength if namelength is not None else _v if _v is not None: self["namelength"] = _v _v = arg.pop("namelengthsrc", None) _v = namelengthsrc if namelengthsrc is not None else _v if _v is not None: self["namelengthsrc"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
#!/usr/bin/env python import os import sys import tempfile import shutil import glob import atexit import textwrap import site from scripttest import TestFileEnvironment, FoundDir from tests.path import Path, curdir, u from pip.util import rmtree pyversion = sys.version[:3] # the directory containing all the tests here = Path(__file__).abspath.folder # the root of this pip source distribution src_folder = here.folder download_cache = tempfile.mkdtemp(prefix='pip-test-cache') site_packages_suffix = site.USER_SITE[len(site.USER_BASE) + 1:] def path_to_url(path): """ Convert a path to URI. The path will be made absolute and will not have quoted path parts. (adapted from pip.util) """ path = os.path.normpath(os.path.abspath(path)) drive, path = os.path.splitdrive(path) filepath = path.split(os.path.sep) url = '/'.join(filepath) if drive: return 'file:///' + drive + url return 'file://' +url def demand_dirs(path): if not os.path.exists(path): os.makedirs(path) # Tweak the path so we can find up-to-date pip sources # (http://bitbucket.org/ianb/pip/issue/98) sys.path = [src_folder] + sys.path def create_virtualenv(where, distribute=False): import virtualenv if sys.version_info[0] > 2: distribute = True virtualenv.create_environment( where, use_distribute=distribute, unzip_setuptools=True) return virtualenv.path_locations(where) def relpath(root, other): """a poor man's os.path.relpath, since we may not have Python 2.6""" prefix = root+Path.sep assert other.startswith(prefix) return Path(other[len(prefix):]) if 'PYTHONPATH' in os.environ: del os.environ['PYTHONPATH'] try: any except NameError: def any(seq): for item in seq: if item: return True return False def clear_environ(environ): return dict(((k, v) for k, v in environ.items() if not k.lower().startswith('pip_'))) def install_setuptools(env): easy_install = os.path.join(env.bin_path, 'easy_install') version = 'setuptools==0.6c11' if sys.platform != 'win32': return env.run(easy_install, version) tempdir = tempfile.mkdtemp() try: for f in glob.glob(easy_install+'*'): shutil.copy2(f, tempdir) return env.run(os.path.join(tempdir, 'easy_install'), version) finally: rmtree(tempdir) env = None def reset_env(environ=None, use_distribute=None, system_site_packages=False, sitecustomize=None): """Return a test environment. Keyword arguments: environ: an environ object to use. use_distribute: use distribute, not setuptools. system_site_packages: create a virtualenv that simulates --system-site-packages. sitecustomize: a string containing python code to add to sitecustomize.py. """ global env # FastTestPipEnv reuses env, not safe if use_distribute specified if use_distribute is None and not system_site_packages: env = FastTestPipEnvironment(environ, sitecustomize=sitecustomize) else: env = TestPipEnvironment(environ, use_distribute=use_distribute, sitecustomize=sitecustomize) if system_site_packages: #testing often occurs starting from a private virtualenv (e.g. with tox) #from that context, you can't successfully use virtualenv.create_environment #to create a 'system-site-packages' virtualenv #hence, this workaround (env.lib_path/'no-global-site-packages.txt').rm() return env class TestFailure(AssertionError): """ An "assertion" failed during testing. """ pass # # This cleanup routine prevents the __del__ method that cleans up the tree of # the last TestPipEnvironment from firing after shutil has already been # unloaded. It also ensures that FastTestPipEnvironment doesn't leave an # environment hanging around that might confuse the next test run. # def _cleanup(): global env del env rmtree(download_cache, ignore_errors=True) rmtree(fast_test_env_root, ignore_errors=True) rmtree(fast_test_env_backup, ignore_errors=True) atexit.register(_cleanup) class TestPipResult(object): def __init__(self, impl, verbose=False): self._impl = impl if verbose: print(self.stdout) if self.stderr: print('======= stderr ========') print(self.stderr) print('=======================') def __getattr__(self, attr): return getattr(self._impl, attr) if sys.platform == 'win32': @property def stdout(self): return self._impl.stdout.replace('\r\n', '\n') @property def stderr(self): return self._impl.stderr.replace('\r\n', '\n') def __str__(self): return str(self._impl).replace('\r\n', '\n') else: # Python doesn't automatically forward __str__ through __getattr__ def __str__(self): return str(self._impl) def assert_installed(self, pkg_name, with_files=[], without_files=[], without_egg_link=False, use_user_site=False): e = self.test_env pkg_dir = e.venv/ 'src'/ pkg_name.lower() if use_user_site: egg_link_path = e.user_site / pkg_name + '.egg-link' else: egg_link_path = e.site_packages / pkg_name + '.egg-link' if without_egg_link: if egg_link_path in self.files_created: raise TestFailure('unexpected egg link file created: '\ '%r\n%s' % (egg_link_path, self)) else: if not egg_link_path in self.files_created: raise TestFailure('expected egg link file missing: '\ '%r\n%s' % (egg_link_path, self)) egg_link_file = self.files_created[egg_link_path] if not (# FIXME: I don't understand why there's a trailing . here egg_link_file.bytes.endswith('.') and egg_link_file.bytes[:-1].strip().endswith(pkg_dir)): raise TestFailure(textwrap.dedent(u('''\ Incorrect egg_link file %r Expected ending: %r ------- Actual contents ------- %s -------------------------------''' % ( egg_link_file, pkg_dir + u('\n.'), egg_link_file.bytes)))) if use_user_site: pth_file = Path.string(e.user_site / 'easy-install.pth') else: pth_file = Path.string(e.site_packages / 'easy-install.pth') if (pth_file in self.files_updated) == without_egg_link: raise TestFailure('%r unexpectedly %supdated by install' % ( pth_file, (not without_egg_link and 'not ' or ''))) if (pkg_dir in self.files_created) == (curdir in without_files): raise TestFailure(textwrap.dedent('''\ expected package directory %r %sto be created actually created: %s ''') % ( Path.string(pkg_dir), (curdir in without_files and 'not ' or ''), sorted(self.files_created.keys()))) for f in with_files: if not (pkg_dir/f).normpath in self.files_created: raise TestFailure('Package directory %r missing '\ 'expected content %f' % (pkg_dir, f)) for f in without_files: if (pkg_dir/f).normpath in self.files_created: raise TestFailure('Package directory %r has '\ 'unexpected content %f' % (pkg_dir, f)) class TestPipEnvironment(TestFileEnvironment): """A specialized TestFileEnvironment for testing pip""" # # Attribute naming convention # --------------------------- # # Instances of this class have many attributes representing paths # in the filesystem. To keep things straight, absolute paths have # a name of the form xxxx_path and relative paths have a name that # does not end in '_path'. # The following paths are relative to the root_path, and should be # treated by clients as instance attributes. The fact that they # are defined in the class is an implementation detail # where we'll create the virtual Python installation for testing # # Named with a leading dot to reduce the chance of spurious # results due to being mistaken for the virtualenv package. venv = Path('.virtualenv') # The root of a directory tree to be used arbitrarily by tests scratch = Path('scratch') exe = sys.platform == 'win32' and '.exe' or '' verbose = False def __init__(self, environ=None, use_distribute=None, sitecustomize=None): self.root_path = Path(tempfile.mkdtemp('-piptest')) # We will set up a virtual environment at root_path. self.scratch_path = self.root_path / self.scratch self.venv_path = self.root_path / self.venv if not environ: environ = os.environ.copy() environ = clear_environ(environ) environ['PIP_DOWNLOAD_CACHE'] = str(download_cache) environ['PIP_NO_INPUT'] = '1' environ['PIP_LOG_FILE'] = str(self.root_path/'pip-log.txt') super(TestPipEnvironment, self).__init__( self.root_path, ignore_hidden=False, environ=environ, split_cmd=False, start_clear=False, cwd=self.scratch_path, capture_temp=True, assert_no_temp=True) demand_dirs(self.venv_path) demand_dirs(self.scratch_path) if use_distribute is None: use_distribute = os.environ.get('PIP_TEST_USE_DISTRIBUTE', False) self.use_distribute = use_distribute # Create a virtualenv and remember where it's putting things. virtualenv_paths = create_virtualenv(self.venv_path, distribute=self.use_distribute) assert self.venv_path == virtualenv_paths[0] # sanity check for id, path in zip(('venv', 'lib', 'include', 'bin'), virtualenv_paths): #fix for virtualenv issue #306 if hasattr(sys, "pypy_version_info") and id == 'lib': path = os.path.join(self.venv_path, 'lib-python', pyversion) setattr(self, id+'_path', Path(path)) setattr(self, id, relpath(self.root_path, path)) assert self.venv == TestPipEnvironment.venv # sanity check if hasattr(sys, "pypy_version_info"): self.site_packages = self.venv/'site-packages' else: self.site_packages = self.lib/'site-packages' self.user_base_path = self.venv_path/'user' self.user_site_path = self.venv_path/'user'/site_packages_suffix self.user_site = relpath(self.root_path, self.user_site_path) demand_dirs(self.user_site_path) self.environ["PYTHONUSERBASE"] = self.user_base_path # create easy-install.pth in user_site, so we always have it updated instead of created open(self.user_site_path/'easy-install.pth', 'w').close() # put the test-scratch virtualenv's bin dir first on the PATH self.environ['PATH'] = Path.pathsep.join((self.bin_path, self.environ['PATH'])) # test that test-scratch virtualenv creation produced sensible venv python result = self.run('python', '-c', 'import sys; print(sys.executable)') pythonbin = result.stdout.strip() if Path(pythonbin).noext != self.bin_path/'python': raise RuntimeError( "Oops! 'python' in our test environment runs %r" " rather than expected %r" % (pythonbin, self.bin_path/'python')) # make sure we have current setuptools to avoid svn incompatibilities if not self.use_distribute: install_setuptools(self) # Uninstall whatever version of pip came with the virtualenv. # Earlier versions of pip were incapable of # self-uninstallation on Windows, so we use the one we're testing. self.run('python', '-c', '"import sys; sys.path.insert(0, %r); import pip; sys.exit(pip.main());"' % os.path.dirname(here), 'uninstall', '-vvv', '-y', 'pip') # Install this version instead self.run('python', 'setup.py', 'install', cwd=src_folder, expect_stderr=True) #create sitecustomize.py and add patches self._create_empty_sitecustomize() self._use_cached_pypi_server() if sitecustomize: self._add_to_sitecustomize(sitecustomize) # Ensure that $TMPDIR exists (because we use start_clear=False, it's not created for us) if self.temp_path and not os.path.exists(self.temp_path): os.makedirs(self.temp_path) def _ignore_file(self, fn): if fn.endswith('__pycache__') or fn.endswith(".pyc"): result = True else: result = super(TestPipEnvironment, self)._ignore_file(fn) return result def run(self, *args, **kw): if self.verbose: print('>> running %s %s' % (args, kw)) cwd = kw.pop('cwd', None) run_from = kw.pop('run_from', None) assert not cwd or not run_from, "Don't use run_from; it's going away" cwd = Path.string(cwd or run_from or self.cwd) assert not isinstance(cwd, Path) return TestPipResult(super(TestPipEnvironment, self).run(cwd=cwd, *args, **kw), verbose=self.verbose) def __del__(self): rmtree(str(self.root_path), ignore_errors=True) def _use_cached_pypi_server(self): # previously, this was handled in a pth file, and not in sitecustomize.py # pth processing happens during the construction of sys.path. # 'import pypi_server' ultimately imports pkg_resources (which intializes pkg_resources.working_set based on the current state of sys.path) # pkg_resources.get_distribution (used in pip.req) requires an accurate pkg_resources.working_set # therefore, 'import pypi_server' shouldn't occur in a pth file. patch = """ import sys sys.path.insert(0, %r) import pypi_server pypi_server.PyPIProxy.setup() sys.path.remove(%r)""" % (str(here), str(here)) self._add_to_sitecustomize(patch) def _create_empty_sitecustomize(self): "Create empty sitecustomize.py." sitecustomize_path = self.lib_path / 'sitecustomize.py' sitecustomize = open(sitecustomize_path, 'w') sitecustomize.close() def _add_to_sitecustomize(self, snippet): "Adds a python code snippet to sitecustomize.py." sitecustomize_path = self.lib_path / 'sitecustomize.py' sitecustomize = open(sitecustomize_path, 'a') sitecustomize.write(textwrap.dedent(''' %s ''' %snippet)) sitecustomize.close() fast_test_env_root = here / 'tests_cache' / 'test_ws' fast_test_env_backup = here / 'tests_cache' / 'test_ws_backup' class FastTestPipEnvironment(TestPipEnvironment): def __init__(self, environ=None, sitecustomize=None): import virtualenv self.root_path = fast_test_env_root self.backup_path = fast_test_env_backup self.scratch_path = self.root_path / self.scratch # We will set up a virtual environment at root_path. self.venv_path = self.root_path / self.venv if not environ: environ = os.environ.copy() environ = clear_environ(environ) environ['PIP_DOWNLOAD_CACHE'] = str(download_cache) environ['PIP_NO_INPUT'] = '1' environ['PIP_LOG_FILE'] = str(self.root_path/'pip-log.txt') TestFileEnvironment.__init__(self, self.root_path, ignore_hidden=False, environ=environ, split_cmd=False, start_clear=False, cwd=self.scratch_path, capture_temp=True, assert_no_temp=True) virtualenv_paths = virtualenv.path_locations(self.venv_path) for id, path in zip(('venv', 'lib', 'include', 'bin'), virtualenv_paths): #fix for virtualenv issue #306 if hasattr(sys, "pypy_version_info") and id == 'lib': path = os.path.join(self.venv_path, 'lib-python', pyversion) setattr(self, id+'_path', Path(path)) setattr(self, id, relpath(self.root_path, path)) assert self.venv == TestPipEnvironment.venv # sanity check if hasattr(sys, "pypy_version_info"): self.site_packages = self.venv/'site-packages' else: self.site_packages = self.lib/'site-packages' self.user_base_path = self.venv_path/'user' self.user_site_path = self.venv_path/'user'/'lib'/self.lib.name/'site-packages' self.user_site = relpath(self.root_path, self.user_site_path) self.environ["PYTHONUSERBASE"] = self.user_base_path # put the test-scratch virtualenv's bin dir first on the PATH self.environ['PATH'] = Path.pathsep.join((self.bin_path, self.environ['PATH'])) self.use_distribute = os.environ.get('PIP_TEST_USE_DISTRIBUTE', False) if self.root_path.exists: rmtree(self.root_path) if self.backup_path.exists: shutil.copytree(self.backup_path, self.root_path, True) else: demand_dirs(self.venv_path) demand_dirs(self.scratch_path) # Create a virtualenv and remember where it's putting things. create_virtualenv(self.venv_path, distribute=self.use_distribute) demand_dirs(self.user_site_path) # create easy-install.pth in user_site, so we always have it updated instead of created open(self.user_site_path/'easy-install.pth', 'w').close() # test that test-scratch virtualenv creation produced sensible venv python result = self.run('python', '-c', 'import sys; print(sys.executable)') pythonbin = result.stdout.strip() if Path(pythonbin).noext != self.bin_path/'python': raise RuntimeError( "Oops! 'python' in our test environment runs %r" " rather than expected %r" % (pythonbin, self.bin_path/'python')) # make sure we have current setuptools to avoid svn incompatibilities if not self.use_distribute: install_setuptools(self) # Uninstall whatever version of pip came with the virtualenv. # Earlier versions of pip were incapable of # self-uninstallation on Windows, so we use the one we're testing. self.run('python', '-c', '"import sys; sys.path.insert(0, %r); import pip; sys.exit(pip.main());"' % os.path.dirname(here), 'uninstall', '-vvv', '-y', 'pip') # Install this version instead self.run('python', 'setup.py', 'install', cwd=src_folder, expect_stderr=True) shutil.copytree(self.root_path, self.backup_path, True) #create sitecustomize.py and add patches self._create_empty_sitecustomize() self._use_cached_pypi_server() if sitecustomize: self._add_to_sitecustomize(sitecustomize) assert self.root_path.exists # Ensure that $TMPDIR exists (because we use start_clear=False, it's not created for us) if self.temp_path and not os.path.exists(self.temp_path): os.makedirs(self.temp_path) def __del__(self): pass # shutil.rmtree(str(self.root_path), ignore_errors=True) def run_pip(*args, **kw): result = env.run('pip', *args, **kw) ignore = [] for path, f in result.files_before.items(): # ignore updated directories, often due to .pyc or __pycache__ if (path in result.files_updated and isinstance(result.files_updated[path], FoundDir)): ignore.append(path) for path in ignore: del result.files_updated[path] return result def write_file(filename, text, dest=None): """Write a file in the dest (default=env.scratch_path) """ env = get_env() if dest: complete_path = dest/ filename else: complete_path = env.scratch_path/ filename f = open(complete_path, 'w') f.write(text) f.close() def mkdir(dirname): os.mkdir(os.path.join(get_env().scratch_path, dirname)) def get_env(): if env is None: reset_env() return env # FIXME ScriptTest does something similar, but only within a single # ProcResult; this generalizes it so states can be compared across # multiple commands. Maybe should be rolled into ScriptTest? def diff_states(start, end, ignore=None): """ Differences two "filesystem states" as represented by dictionaries of FoundFile and FoundDir objects. Returns a dictionary with following keys: ``deleted`` Dictionary of files/directories found only in the start state. ``created`` Dictionary of files/directories found only in the end state. ``updated`` Dictionary of files whose size has changed (FIXME not entirely reliable, but comparing contents is not possible because FoundFile.bytes is lazy, and comparing mtime doesn't help if we want to know if a file has been returned to its earlier state). Ignores mtime and other file attributes; only presence/absence and size are considered. """ ignore = ignore or [] def prefix_match(path, prefix): if path == prefix: return True prefix = prefix.rstrip(os.path.sep) + os.path.sep return path.startswith(prefix) start_keys = set([k for k in start.keys() if not any([prefix_match(k, i) for i in ignore])]) end_keys = set([k for k in end.keys() if not any([prefix_match(k, i) for i in ignore])]) deleted = dict([(k, start[k]) for k in start_keys.difference(end_keys)]) created = dict([(k, end[k]) for k in end_keys.difference(start_keys)]) updated = {} for k in start_keys.intersection(end_keys): if (start[k].size != end[k].size): updated[k] = end[k] return dict(deleted=deleted, created=created, updated=updated) def assert_all_changes(start_state, end_state, expected_changes): """ Fails if anything changed that isn't listed in the expected_changes. start_state is either a dict mapping paths to scripttest.[FoundFile|FoundDir] objects or a TestPipResult whose files_before we'll test. end_state is either a similar dict or a TestPipResult whose files_after we'll test. Note: listing a directory means anything below that directory can be expected to have changed. """ start_files = start_state end_files = end_state if isinstance(start_state, TestPipResult): start_files = start_state.files_before if isinstance(end_state, TestPipResult): end_files = end_state.files_after diff = diff_states(start_files, end_files, ignore=expected_changes) if list(diff.values()) != [{}, {}, {}]: raise TestFailure('Unexpected changes:\n' + '\n'.join( [k + ': ' + ', '.join(v.keys()) for k, v in diff.items()])) # Don't throw away this potentially useful information return diff def _create_test_package(env): mkdir('version_pkg') version_pkg_path = env.scratch_path/'version_pkg' write_file('version_pkg.py', textwrap.dedent('''\ def main(): print('0.1') '''), version_pkg_path) write_file('setup.py', textwrap.dedent('''\ from setuptools import setup, find_packages setup(name='version_pkg', version='0.1', packages=find_packages(), py_modules=['version_pkg'], entry_points=dict(console_scripts=['version_pkg=version_pkg:main'])) '''), version_pkg_path) env.run('git', 'init', cwd=version_pkg_path) env.run('git', 'add', '.', cwd=version_pkg_path) env.run('git', 'commit', '-q', '--author', 'Pip <[email protected]>', '-am', 'initial version', cwd=version_pkg_path) return version_pkg_path def _change_test_package_version(env, version_pkg_path): write_file('version_pkg.py', textwrap.dedent('''\ def main(): print("some different version")'''), version_pkg_path) env.run('git', 'clean', '-qfdx', cwd=version_pkg_path, expect_stderr=True) env.run('git', 'commit', '-q', '--author', 'Pip <[email protected]>', '-am', 'messed version', cwd=version_pkg_path, expect_stderr=True) if __name__ == '__main__': sys.stderr.write("Run pip's tests using nosetests. Requires virtualenv, ScriptTest, mock, and nose.\n") sys.exit(1)
# Author: Jean-Remi King, <[email protected]> # Marijn van Vliet, <[email protected]> # # License: BSD (3-clause) import numpy as np from numpy.testing import (assert_array_equal, assert_array_almost_equal, assert_equal) import pytest from mne.fixes import is_regressor, is_classifier from mne.utils import requires_version, check_version from mne.decoding.base import (_get_inverse_funcs, LinearModel, get_coef, cross_val_multiscore) from mne.decoding.search_light import SlidingEstimator from mne.decoding import Scaler def _make_data(n_samples=1000, n_features=5, n_targets=3): """Generate some testing data. Parameters ---------- n_samples : int The number of samples. n_features : int The number of features. n_targets : int The number of targets. Returns ------- X : ndarray, shape (n_samples, n_features) The measured data. Y : ndarray, shape (n_samples, n_targets) The latent variables generating the data. A : ndarray, shape (n_features, n_targets) The forward model, mapping the latent variables (=Y) to the measured data (=X). """ # Define Y latent factors np.random.seed(0) cov_Y = np.eye(n_targets) * 10 + np.random.rand(n_targets, n_targets) cov_Y = (cov_Y + cov_Y.T) / 2. mean_Y = np.random.rand(n_targets) Y = np.random.multivariate_normal(mean_Y, cov_Y, size=n_samples) # The Forward model A = np.random.randn(n_features, n_targets) X = Y.dot(A.T) X += np.random.randn(n_samples, n_features) # add noise X += np.random.rand(n_features) # Put an offset return X, Y, A @requires_version('sklearn', '0.17') def test_get_coef(): """Test getting linear coefficients (filters/patterns) from estimators.""" from sklearn.base import TransformerMixin, BaseEstimator from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.linear_model import Ridge, LinearRegression lm = LinearModel() assert (is_classifier(lm)) lm = LinearModel(Ridge()) assert (is_regressor(lm)) # Define a classifier, an invertible transformer and an non-invertible one. class Clf(BaseEstimator): def fit(self, X, y): return self class NoInv(TransformerMixin): def fit(self, X, y): return self def transform(self, X): return X class Inv(NoInv): def inverse_transform(self, X): return X X, y, A = _make_data(n_samples=2000, n_features=3, n_targets=1) # I. Test inverse function # Check that we retrieve the right number of inverse functions even if # there are nested pipelines good_estimators = [ (1, make_pipeline(Inv(), Clf())), (2, make_pipeline(Inv(), Inv(), Clf())), (3, make_pipeline(Inv(), make_pipeline(Inv(), Inv()), Clf())), ] for expected_n, est in good_estimators: est.fit(X, y) assert (expected_n == len(_get_inverse_funcs(est))) bad_estimators = [ Clf(), # no preprocessing Inv(), # final estimator isn't classifier make_pipeline(NoInv(), Clf()), # first step isn't invertible make_pipeline(Inv(), make_pipeline( Inv(), NoInv()), Clf()), # nested step isn't invertible ] for est in bad_estimators: est.fit(X, y) invs = _get_inverse_funcs(est) assert_equal(invs, list()) # II. Test get coef for simple estimator and pipelines for clf in (lm, make_pipeline(StandardScaler(), lm)): clf.fit(X, y) # Retrieve final linear model filters = get_coef(clf, 'filters_', False) if hasattr(clf, 'steps'): coefs = clf.steps[-1][-1].model.coef_ else: coefs = clf.model.coef_ assert_array_equal(filters, coefs[0]) patterns = get_coef(clf, 'patterns_', False) assert (filters[0] != patterns[0]) n_chans = X.shape[1] assert_array_equal(filters.shape, patterns.shape, [n_chans, n_chans]) # Inverse transform linear model filters_inv = get_coef(clf, 'filters_', True) assert (filters[0] != filters_inv[0]) patterns_inv = get_coef(clf, 'patterns_', True) assert (patterns[0] != patterns_inv[0]) # Check with search_light and combination of preprocessing ending with sl: slider = SlidingEstimator(make_pipeline(StandardScaler(), lm)) X = np.transpose([X, -X], [1, 2, 0]) # invert X across 2 time samples clfs = (make_pipeline(Scaler(None, scalings='mean'), slider), slider) for clf in clfs: clf.fit(X, y) for inverse in (True, False): patterns = get_coef(clf, 'patterns_', inverse) filters = get_coef(clf, 'filters_', inverse) assert_array_equal(filters.shape, patterns.shape, X.shape[1:]) # the two time samples get inverted patterns assert_equal(patterns[0, 0], -patterns[0, 1]) for t in [0, 1]: assert_array_equal(get_coef(clf.estimators_[t], 'filters_', False), filters[:, t]) # Check patterns with more than 1 regressor for n_features in [1, 5]: for n_targets in [1, 3]: X, Y, A = _make_data(n_samples=5000, n_features=5, n_targets=3) lm = LinearModel(LinearRegression()).fit(X, Y) assert_array_equal(lm.filters_.shape, lm.patterns_.shape) assert_array_equal(lm.filters_.shape, [3, 5]) assert_array_almost_equal(A, lm.patterns_.T, decimal=2) lm = LinearModel(Ridge(alpha=1)).fit(X, Y) assert_array_almost_equal(A, lm.patterns_.T, decimal=2) # Check can pass fitting parameters lm.fit(X, Y, sample_weight=np.ones(len(Y))) @requires_version('sklearn', '0.15') def test_linearmodel(): """Test LinearModel class for computing filters and patterns.""" from sklearn.linear_model import LinearRegression np.random.seed(42) clf = LinearModel() n, n_features = 20, 3 X = np.random.rand(n, n_features) y = np.arange(n) % 2 clf.fit(X, y) assert_equal(clf.filters_.shape, (n_features,)) assert_equal(clf.patterns_.shape, (n_features,)) pytest.raises(ValueError, clf.fit, np.random.rand(n, n_features, 99), y) # check multi-target fit n_targets = 5 clf = LinearModel(LinearRegression()) Y = np.random.rand(n, n_targets) clf.fit(X, Y) assert_equal(clf.filters_.shape, (n_targets, n_features)) assert_equal(clf.patterns_.shape, (n_targets, n_features)) pytest.raises(ValueError, clf.fit, X, np.random.rand(n, n_features, 99)) @requires_version('sklearn', '0.18') def test_cross_val_multiscore(): """Test cross_val_multiscore for computing scores on decoding over time.""" from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score from sklearn.linear_model import LogisticRegression, LinearRegression if check_version('sklearn', '0.20'): logreg = LogisticRegression(solver='liblinear', random_state=0) else: logreg = LogisticRegression(random_state=0) # compare to cross-val-score X = np.random.rand(20, 3) y = np.arange(20) % 2 cv = KFold(2, random_state=0) clf = logreg assert_array_equal(cross_val_score(clf, X, y, cv=cv), cross_val_multiscore(clf, X, y, cv=cv)) # Test with search light X = np.random.rand(20, 4, 3) y = np.arange(20) % 2 clf = SlidingEstimator(logreg, scoring='accuracy') scores_acc = cross_val_multiscore(clf, X, y, cv=cv) assert_array_equal(np.shape(scores_acc), [2, 3]) # check values scores_acc_manual = list() for train, test in cv.split(X, y): clf.fit(X[train], y[train]) scores_acc_manual.append(clf.score(X[test], y[test])) assert_array_equal(scores_acc, scores_acc_manual) # check scoring metric # raise an error if scoring is defined at cross-val-score level and # search light, because search light does not return a 1-dimensional # prediction. pytest.raises(ValueError, cross_val_multiscore, clf, X, y, cv=cv, scoring='roc_auc') clf = SlidingEstimator(logreg, scoring='roc_auc') scores_auc = cross_val_multiscore(clf, X, y, cv=cv, n_jobs=1) scores_auc_manual = list() for train, test in cv.split(X, y): clf.fit(X[train], y[train]) scores_auc_manual.append(clf.score(X[test], y[test])) assert_array_equal(scores_auc, scores_auc_manual) # indirectly test that cross_val_multiscore rightly detects the type of # estimator and generates a StratifiedKFold for classiers and a KFold # otherwise X = np.random.randn(1000, 3) y = np.ones(1000, dtype=int) y[::2] = 0 clf = logreg reg = LinearRegression() for cross_val in (cross_val_score, cross_val_multiscore): manual = cross_val(clf, X, y, cv=StratifiedKFold(2)) auto = cross_val(clf, X, y, cv=2) assert_array_equal(manual, auto) manual = cross_val(reg, X, y, cv=KFold(2)) auto = cross_val(reg, X, y, cv=2) assert_array_equal(manual, auto)
# testing/assertsql.py # Copyright (C) 2005-2015 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from ..engine.default import DefaultDialect from .. import util import re import collections import contextlib from .. import event from sqlalchemy.schema import _DDLCompiles from sqlalchemy.engine.util import _distill_params class AssertRule(object): is_consumed = False errormessage = None consume_statement = True def process_statement(self, execute_observed): pass def no_more_statements(self): assert False, 'All statements are complete, but pending '\ 'assertion rules remain' class SQLMatchRule(AssertRule): pass class CursorSQL(SQLMatchRule): consume_statement = False def __init__(self, statement, params=None): self.statement = statement self.params = params def process_statement(self, execute_observed): stmt = execute_observed.statements[0] if self.statement != stmt.statement or ( self.params is not None and self.params != stmt.parameters): self.errormessage = \ "Testing for exact SQL %s parameters %s received %s %s" % ( self.statement, self.params, stmt.statement, stmt.parameters ) else: execute_observed.statements.pop(0) self.is_consumed = True if not execute_observed.statements: self.consume_statement = True class CompiledSQL(SQLMatchRule): def __init__(self, statement, params=None): self.statement = statement self.params = params def _compare_sql(self, execute_observed, received_statement): stmt = re.sub(r'[\n\t]', '', self.statement) return received_statement == stmt def _compile_dialect(self, execute_observed): return DefaultDialect() def _received_statement(self, execute_observed): """reconstruct the statement and params in terms of a target dialect, which for CompiledSQL is just DefaultDialect.""" context = execute_observed.context compare_dialect = self._compile_dialect(execute_observed) if isinstance(context.compiled.statement, _DDLCompiles): compiled = \ context.compiled.statement.compile(dialect=compare_dialect) else: compiled = ( context.compiled.statement.compile( dialect=compare_dialect, column_keys=context.compiled.column_keys, inline=context.compiled.inline) ) _received_statement = re.sub(r'[\n\t]', '', util.text_type(compiled)) parameters = execute_observed.parameters if not parameters: _received_parameters = [compiled.construct_params()] else: _received_parameters = [ compiled.construct_params(m) for m in parameters] return _received_statement, _received_parameters def process_statement(self, execute_observed): context = execute_observed.context _received_statement, _received_parameters = \ self._received_statement(execute_observed) params = self._all_params(context) equivalent = self._compare_sql(execute_observed, _received_statement) if equivalent: if params is not None: all_params = list(params) all_received = list(_received_parameters) while all_params and all_received: param = dict(all_params.pop(0)) for idx, received in enumerate(list(all_received)): # do a positive compare only for param_key in param: # a key in param did not match current # 'received' if param_key not in received or \ received[param_key] != param[param_key]: break else: # all keys in param matched 'received'; # onto next param del all_received[idx] break else: # param did not match any entry # in all_received equivalent = False break if all_params or all_received: equivalent = False if equivalent: self.is_consumed = True self.errormessage = None else: self.errormessage = self._failure_message(params) % { 'received_statement': _received_statement, 'received_parameters': _received_parameters } def _all_params(self, context): if self.params: if util.callable(self.params): params = self.params(context) else: params = self.params if not isinstance(params, list): params = [params] return params else: return None def _failure_message(self, expected_params): return ( 'Testing for compiled statement %r partial params %r, ' 'received %%(received_statement)r with params ' '%%(received_parameters)r' % ( self.statement, expected_params ) ) class RegexSQL(CompiledSQL): def __init__(self, regex, params=None): SQLMatchRule.__init__(self) self.regex = re.compile(regex) self.orig_regex = regex self.params = params def _failure_message(self, expected_params): return ( 'Testing for compiled statement ~%r partial params %r, ' 'received %%(received_statement)r with params ' '%%(received_parameters)r' % ( self.orig_regex, expected_params ) ) def _compare_sql(self, execute_observed, received_statement): return bool(self.regex.match(received_statement)) class DialectSQL(CompiledSQL): def _compile_dialect(self, execute_observed): return execute_observed.context.dialect def _compare_no_space(self, real_stmt, received_stmt): stmt = re.sub(r'[\n\t]', '', real_stmt) return received_stmt == stmt def _received_statement(self, execute_observed): received_stmt, received_params = super(DialectSQL, self).\ _received_statement(execute_observed) # TODO: why do we need this part? for real_stmt in execute_observed.statements: if self._compare_no_space(real_stmt.statement, received_stmt): break else: raise AssertionError( "Can't locate compiled statement %r in list of " "statements actually invoked" % received_stmt) return received_stmt, execute_observed.context.compiled_parameters def _compare_sql(self, execute_observed, received_statement): stmt = re.sub(r'[\n\t]', '', self.statement) # convert our comparison statement to have the # paramstyle of the received paramstyle = execute_observed.context.dialect.paramstyle if paramstyle == 'pyformat': stmt = re.sub( r':([\w_]+)', r"%(\1)s", stmt) else: # positional params repl = None if paramstyle == 'qmark': repl = "?" elif paramstyle == 'format': repl = r"%s" elif paramstyle == 'numeric': repl = None stmt = re.sub(r':([\w_]+)', repl, stmt) return received_statement == stmt class CountStatements(AssertRule): def __init__(self, count): self.count = count self._statement_count = 0 def process_statement(self, execute_observed): self._statement_count += 1 def no_more_statements(self): if self.count != self._statement_count: assert False, 'desired statement count %d does not match %d' \ % (self.count, self._statement_count) class AllOf(AssertRule): def __init__(self, *rules): self.rules = set(rules) def process_statement(self, execute_observed): for rule in list(self.rules): rule.errormessage = None rule.process_statement(execute_observed) if rule.is_consumed: self.rules.discard(rule) if not self.rules: self.is_consumed = True break elif not rule.errormessage: # rule is not done yet self.errormessage = None break else: self.errormessage = list(self.rules)[0].errormessage class Or(AllOf): def process_statement(self, execute_observed): for rule in self.rules: rule.process_statement(execute_observed) if rule.is_consumed: self.is_consumed = True break else: self.errormessage = list(self.rules)[0].errormessage class SQLExecuteObserved(object): def __init__(self, context, clauseelement, multiparams, params): self.context = context self.clauseelement = clauseelement self.parameters = _distill_params(multiparams, params) self.statements = [] class SQLCursorExecuteObserved( collections.namedtuple( "SQLCursorExecuteObserved", ["statement", "parameters", "context", "executemany"]) ): pass class SQLAsserter(object): def __init__(self): self.accumulated = [] def _close(self): self._final = self.accumulated del self.accumulated def assert_(self, *rules): rules = list(rules) observed = list(self._final) while observed and rules: rule = rules[0] rule.process_statement(observed[0]) if rule.is_consumed: rules.pop(0) elif rule.errormessage: assert False, rule.errormessage if rule.consume_statement: observed.pop(0) if not observed and rules: rules[0].no_more_statements() elif not rules and observed: assert False, "Additional SQL statements remain" @contextlib.contextmanager def assert_engine(engine): asserter = SQLAsserter() orig = [] @event.listens_for(engine, "before_execute") def connection_execute(conn, clauseelement, multiparams, params): # grab the original statement + params before any cursor # execution orig[:] = clauseelement, multiparams, params @event.listens_for(engine, "after_cursor_execute") def cursor_execute(conn, cursor, statement, parameters, context, executemany): if not context: return # then grab real cursor statements and associate them all # around a single context if asserter.accumulated and \ asserter.accumulated[-1].context is context: obs = asserter.accumulated[-1] else: obs = SQLExecuteObserved(context, orig[0], orig[1], orig[2]) asserter.accumulated.append(obs) obs.statements.append( SQLCursorExecuteObserved( statement, parameters, context, executemany) ) try: yield asserter finally: event.remove(engine, "after_cursor_execute", cursor_execute) event.remove(engine, "before_execute", connection_execute) asserter._close()
#!/usr/bin/env python # Taken from https://gist.github.com/yudanta/ba476ba184652afc077a import os from wand.image import Image from wand.color import Color #create class for get exif data from image class ExifData: key_exif = ['date:create', 'date:modify', 'exif:ApertureValue', 'exif:BrightnessValue', 'exif:ColorSpace', 'exif:ComponentsConfiguration', 'exif:Compression', 'exif:DateTime', 'exif:DateTimeDigitized', 'exif:DateTimeOriginal', 'exif:ExifImageLength', 'exif:ExifImageWidth', 'exif:ExifOffset', 'exif:ExifVersion', 'exif:ExposureMode', 'exif:ExposureProgram', 'exif:ExposureTime', 'exif:Flash', 'exif:FlashPixVersion', 'exif:FNumber', 'exif:FocalLength', 'exif:FocalLengthIn35mmFilm', 'exif:ISOSpeedRatings', 'exif:JPEGInterchangeFormat', 'exif:JPEGInterchangeFormatLength', 'exif:Make', 'exif:MeteringMode', 'exif:Model', 'exif:Orientation', 'exif:ResolutionUnit', 'exif:SceneCaptureType', 'exif:SceneType', 'exif:SensingMethod', 'exif:ShutterSpeedValue', 'exif:Software', 'exif:SubjectArea', 'exif:SubSecTimeDigitized', 'exif:SubSecTimeOriginal', 'exif:WhiteBalance', 'exif:XResolution', 'exif:YCbCrPositioning', 'exif:YResolution', 'jpeg:colorspace', 'jpeg:sampling-factor'] exif_orientation_column = [{"top":[6, 5]}, {"bottom":[7, 8]}, {"left":[1, 4]}, {"right":[2, 3]}] exif_orientation_row = [{"top":[1, 3]}, {"bottom":[3, 4]}, {"left":[5, 8]}, {"right":[6, 7]}] exif_data = {} def __init__(self): return None def get_exif_data(self, img_path): #read image img = Image(filename=img_path) img_exif = img.metadata for key in self.key_exif: self.exif_data[key] = img_exif[key] return self.exif_data def check_orientation(self, img): exif = img.metadata #print exif['exif:Orientation'] return exif['exif:Orientation'] class ImageResizer: #predefine image size #square size square_150x150 = '150x150^' square_320x320 = '320x320^' square_500x500 = '500x500^' square_640x640 = '640x640^' square_150x150_size = [150, 150] square_320x320_size = [320, 320] square_500x500_size = [500, 500] square_640x640_size = [640, 640] square_150x150_name = 'square_150x150' square_320x320_name = 'square_320x320' square_500x500_name = 'square_500x500' square_640x640_name = 'square_640x640' #non_square_size small_240x180 = '240x180^' small_320x240 = '320x240^' medium_640x480 = '640x480^' medium_800x600 = '800x600^' large_1024x768 = '1024x768^' large_1600x1200 = '1600x1200^' small_240x180_size = [240, 180] small_320x240_size = [320, 240] medium_640x480_size = [640, 480] medium_800x600_size = [800, 600] large_1024x768_size = [1024, 768] large_1600x1200_size = [1600, 1200] small_240x180_name = 'small_240x180' small_320x240_name = 'small_320x240' medium_640x480_name = 'medium_640x480' medium_800x600_name = 'medium_800x600' large_1024x768_name = 'large_1024x768' large_1600x1200_name = 'large_1600x1200' def __init__(self): return None def generate_square_img(self, img_path, size_config, size_img, size_name, dest_path): #open_image img = Image(filename=img_path) #transform with resize scale config img.transform(resize=size_config) #try to crop, calculate width crop first target_size = size_img[1] #use one because its square width, height = img.size #print "width, height ", width, height crop_start, crop_end = [0, 0] #add new size params #calculate crop_start = (width - target_size) / 2 crop_end = crop_start + target_size #print crop_start, crop_end, target_size, (crop_end - crop_start) ''' exProcessor = ExifData() #rotate image if necessary if exProcessor.check_orientation(img) in [6, 7]: img.rotate(90) img.metadata['exif:Orientation'] = 1 if exProcessor.check_orientation(img) in [6, 8]: img.rotate(-90) img.metadata['exif:Orientation'] = 1 if exProcessor.check_orientation(img) in [3, 4]: img.rotate(180) img.metadata['exif:Orientation'] = 1 ''' #do cropping with img[crop_start:crop_end, :] as square_image: #save square_image.save(filename=''.join([dest_path, size_name, '.jpg'])) def resize_image(self, img_path, size_config, size_name, dest_path, compress=False): #open image img = Image(filename=img_path) #transform using resize config img.transform(resize=size_config) ''' exProcessor = ExifData() #rotate image if necessary if exProcessor.check_orientation(img) in [6, 7]: img.rotate(90) img.metadata['exif:Orientation'] = 1 if exProcessor.check_orientation(img) in [6, 8]: img.rotate(-90) img.metadata['exif:Orientation'] = 1 if exProcessor.check_orientation(img) in [3, 4]: img.rotate(180) img.metadata['exif:Orientation'] = 1 ''' # Detect file extention fileName, fileExtension = os.path.splitext(img_path) #save img fileName = ''.join([fileName, '_', size_name, fileExtension]) fileName = os.path.basename(fileName) fileName = os.path.abspath(os.path.join(dest_path, fileName)) # Compress option? if compress: img.compression_quality = 70 img.save(filename=fileName) return fileName def generate_all_image(self, image_path, dest_path): #generate square image self.generate_square_img(image_path, self.square_150x150, self.square_150x150_size, self.square_150x150_name, dest_path) self.generate_square_img(image_path, self.square_320x320, self.square_320x320_size, self.square_320x320_name, dest_path) self.generate_square_img(image_path, self.square_500x500, self.square_500x500_size, self.square_500x500_name, dest_path) self.generate_square_img(image_path, self.square_640x640, self.square_640x640_size, self.square_640x640_name, dest_path) #generate non square image self.resize_image(image_path, self.small_240x180, self.small_240x180_name, dest_path) self.resize_image(image_path, self.small_320x240, self.small_320x240_name, dest_path) self.resize_image(image_path, self.medium_640x480, self.medium_640x480_name, dest_path) self.resize_image(image_path, self.medium_800x600, self.medium_800x600_name, dest_path) self.resize_image(image_path, self.large_1024x768, self.large_1024x768_name, dest_path) self.resize_image(image_path, self.large_1600x1200, self.large_1600x1200_name, dest_path) return None
from plotly.basedatatypes import BaseLayoutHierarchyType as _BaseLayoutHierarchyType import copy as _copy class Rangeselector(_BaseLayoutHierarchyType): # class properties # -------------------- _parent_path_str = "layout.xaxis" _path_str = "layout.xaxis.rangeselector" _valid_props = { "activecolor", "bgcolor", "bordercolor", "borderwidth", "buttondefaults", "buttons", "font", "visible", "x", "xanchor", "y", "yanchor", } # activecolor # ----------- @property def activecolor(self): """ Sets the background color of the active range selector button. The 'activecolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str """ return self["activecolor"] @activecolor.setter def activecolor(self, val): self["activecolor"] = val # bgcolor # ------- @property def bgcolor(self): """ Sets the background color of the range selector buttons. The 'bgcolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str """ return self["bgcolor"] @bgcolor.setter def bgcolor(self, val): self["bgcolor"] = val # bordercolor # ----------- @property def bordercolor(self): """ Sets the color of the border enclosing the range selector. The 'bordercolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str """ return self["bordercolor"] @bordercolor.setter def bordercolor(self, val): self["bordercolor"] = val # borderwidth # ----------- @property def borderwidth(self): """ Sets the width (in px) of the border enclosing the range selector. The 'borderwidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["borderwidth"] @borderwidth.setter def borderwidth(self, val): self["borderwidth"] = val # buttons # ------- @property def buttons(self): """ Sets the specifications for each buttons. By default, a range selector comes with no buttons. The 'buttons' property is a tuple of instances of Button that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.xaxis.rangeselector.Button - A list or tuple of dicts of string/value properties that will be passed to the Button constructor Supported dict properties: count Sets the number of steps to take to update the range. Use with `step` to specify the update interval. label Sets the text label to appear on the button. name When used in a template, named items are created in the output figure in addition to any items the figure already has in this array. You can modify these items in the output figure by making your own item with `templateitemname` matching this `name` alongside your modifications (including `visible: false` or `enabled: false` to hide it). Has no effect outside of a template. step The unit of measurement that the `count` value will set the range by. stepmode Sets the range update mode. If "backward", the range update shifts the start of range back "count" times "step" milliseconds. If "todate", the range update shifts the start of range back to the first timestamp from "count" times "step" milliseconds back. For example, with `step` set to "year" and `count` set to 1 the range update shifts the start of the range back to January 01 of the current year. Month and year "todate" are currently available only for the built-in (Gregorian) calendar. templateitemname Used to refer to a named item in this array in the template. Named items from the template will be created even without a matching item in the input figure, but you can modify one by making an item with `templateitemname` matching its `name`, alongside your modifications (including `visible: false` or `enabled: false` to hide it). If there is no template or no matching item, this item will be hidden unless you explicitly show it with `visible: true`. visible Determines whether or not this button is visible. Returns ------- tuple[plotly.graph_objs.layout.xaxis.rangeselector.Button] """ return self["buttons"] @buttons.setter def buttons(self, val): self["buttons"] = val # buttondefaults # -------------- @property def buttondefaults(self): """ When used in a template (as layout.template.layout.xaxis.rangeselector.buttondefaults), sets the default property values to use for elements of layout.xaxis.rangeselector.buttons The 'buttondefaults' property is an instance of Button that may be specified as: - An instance of :class:`plotly.graph_objs.layout.xaxis.rangeselector.Button` - A dict of string/value properties that will be passed to the Button constructor Supported dict properties: Returns ------- plotly.graph_objs.layout.xaxis.rangeselector.Button """ return self["buttondefaults"] @buttondefaults.setter def buttondefaults(self, val): self["buttondefaults"] = val # font # ---- @property def font(self): """ Sets the font of the range selector button text. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.layout.xaxis.rangeselector.Font` - A dict of string/value properties that will be passed to the Font constructor Supported dict properties: color family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". size Returns ------- plotly.graph_objs.layout.xaxis.rangeselector.Font """ return self["font"] @font.setter def font(self, val): self["font"] = val # visible # ------- @property def visible(self): """ Determines whether or not this range selector is visible. Note that range selectors are only available for x axes of `type` set to or auto-typed to "date". The 'visible' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["visible"] @visible.setter def visible(self, val): self["visible"] = val # x # - @property def x(self): """ Sets the x position (in normalized coordinates) of the range selector. The 'x' property is a number and may be specified as: - An int or float in the interval [-2, 3] Returns ------- int|float """ return self["x"] @x.setter def x(self, val): self["x"] = val # xanchor # ------- @property def xanchor(self): """ Sets the range selector's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the range selector. The 'xanchor' property is an enumeration that may be specified as: - One of the following enumeration values: ['auto', 'left', 'center', 'right'] Returns ------- Any """ return self["xanchor"] @xanchor.setter def xanchor(self, val): self["xanchor"] = val # y # - @property def y(self): """ Sets the y position (in normalized coordinates) of the range selector. The 'y' property is a number and may be specified as: - An int or float in the interval [-2, 3] Returns ------- int|float """ return self["y"] @y.setter def y(self, val): self["y"] = val # yanchor # ------- @property def yanchor(self): """ Sets the range selector's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the range selector. The 'yanchor' property is an enumeration that may be specified as: - One of the following enumeration values: ['auto', 'top', 'middle', 'bottom'] Returns ------- Any """ return self["yanchor"] @yanchor.setter def yanchor(self, val): self["yanchor"] = val # Self properties description # --------------------------- @property def _prop_descriptions(self): return """\ activecolor Sets the background color of the active range selector button. bgcolor Sets the background color of the range selector buttons. bordercolor Sets the color of the border enclosing the range selector. borderwidth Sets the width (in px) of the border enclosing the range selector. buttons Sets the specifications for each buttons. By default, a range selector comes with no buttons. buttondefaults When used in a template (as layout.template.layout.xaxi s.rangeselector.buttondefaults), sets the default property values to use for elements of layout.xaxis.rangeselector.buttons font Sets the font of the range selector button text. visible Determines whether or not this range selector is visible. Note that range selectors are only available for x axes of `type` set to or auto-typed to "date". x Sets the x position (in normalized coordinates) of the range selector. xanchor Sets the range selector's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the range selector. y Sets the y position (in normalized coordinates) of the range selector. yanchor Sets the range selector's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the range selector. """ def __init__( self, arg=None, activecolor=None, bgcolor=None, bordercolor=None, borderwidth=None, buttons=None, buttondefaults=None, font=None, visible=None, x=None, xanchor=None, y=None, yanchor=None, **kwargs ): """ Construct a new Rangeselector object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.layout.xaxis.Rangeselector` activecolor Sets the background color of the active range selector button. bgcolor Sets the background color of the range selector buttons. bordercolor Sets the color of the border enclosing the range selector. borderwidth Sets the width (in px) of the border enclosing the range selector. buttons Sets the specifications for each buttons. By default, a range selector comes with no buttons. buttondefaults When used in a template (as layout.template.layout.xaxi s.rangeselector.buttondefaults), sets the default property values to use for elements of layout.xaxis.rangeselector.buttons font Sets the font of the range selector button text. visible Determines whether or not this range selector is visible. Note that range selectors are only available for x axes of `type` set to or auto-typed to "date". x Sets the x position (in normalized coordinates) of the range selector. xanchor Sets the range selector's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the range selector. y Sets the y position (in normalized coordinates) of the range selector. yanchor Sets the range selector's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the range selector. Returns ------- Rangeselector """ super(Rangeselector, self).__init__("rangeselector") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.layout.xaxis.Rangeselector constructor must be a dict or an instance of :class:`plotly.graph_objs.layout.xaxis.Rangeselector`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) # Populate data dict with properties # ---------------------------------- _v = arg.pop("activecolor", None) _v = activecolor if activecolor is not None else _v if _v is not None: self["activecolor"] = _v _v = arg.pop("bgcolor", None) _v = bgcolor if bgcolor is not None else _v if _v is not None: self["bgcolor"] = _v _v = arg.pop("bordercolor", None) _v = bordercolor if bordercolor is not None else _v if _v is not None: self["bordercolor"] = _v _v = arg.pop("borderwidth", None) _v = borderwidth if borderwidth is not None else _v if _v is not None: self["borderwidth"] = _v _v = arg.pop("buttons", None) _v = buttons if buttons is not None else _v if _v is not None: self["buttons"] = _v _v = arg.pop("buttondefaults", None) _v = buttondefaults if buttondefaults is not None else _v if _v is not None: self["buttondefaults"] = _v _v = arg.pop("font", None) _v = font if font is not None else _v if _v is not None: self["font"] = _v _v = arg.pop("visible", None) _v = visible if visible is not None else _v if _v is not None: self["visible"] = _v _v = arg.pop("x", None) _v = x if x is not None else _v if _v is not None: self["x"] = _v _v = arg.pop("xanchor", None) _v = xanchor if xanchor is not None else _v if _v is not None: self["xanchor"] = _v _v = arg.pop("y", None) _v = y if y is not None else _v if _v is not None: self["y"] = _v _v = arg.pop("yanchor", None) _v = yanchor if yanchor is not None else _v if _v is not None: self["yanchor"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from __future__ import absolute_import import os import posixpath import sys from pyarrow.util import implements from pyarrow.filesystem import FileSystem import pyarrow.lib as lib class HadoopFileSystem(lib.HadoopFileSystem, FileSystem): """ FileSystem interface for HDFS cluster. See pyarrow.hdfs.connect for full connection details """ def __init__(self, host="default", port=0, user=None, kerb_ticket=None, driver='libhdfs', extra_conf=None): if driver == 'libhdfs': _maybe_set_hadoop_classpath() self._connect(host, port, user, kerb_ticket, driver, extra_conf) def __reduce__(self): return (HadoopFileSystem, (self.host, self.port, self.user, self.kerb_ticket, self.driver, self.extra_conf)) def _isfilestore(self): """ Returns True if this FileSystem is a unix-style file store with directories. """ return True @implements(FileSystem.isdir) def isdir(self, path): return super(HadoopFileSystem, self).isdir(path) @implements(FileSystem.isfile) def isfile(self, path): return super(HadoopFileSystem, self).isfile(path) @implements(FileSystem.delete) def delete(self, path, recursive=False): return super(HadoopFileSystem, self).delete(path, recursive) def mkdir(self, path, **kwargs): """ Create directory in HDFS Parameters ---------- path : string Directory path to create, including any parent directories Notes ----- libhdfs does not support create_parents=False, so we ignore this here """ return super(HadoopFileSystem, self).mkdir(path) @implements(FileSystem.rename) def rename(self, path, new_path): return super(HadoopFileSystem, self).rename(path, new_path) @implements(FileSystem.exists) def exists(self, path): return super(HadoopFileSystem, self).exists(path) def ls(self, path, detail=False): """ Retrieve directory contents and metadata, if requested. Parameters ---------- path : HDFS path detail : boolean, default False If False, only return list of paths Returns ------- result : list of dicts (detail=True) or strings (detail=False) """ return super(HadoopFileSystem, self).ls(path, detail) def walk(self, top_path): """ Directory tree generator for HDFS, like os.walk Parameters ---------- top_path : string Root directory for tree traversal Returns ------- Generator yielding 3-tuple (dirpath, dirnames, filename) """ contents = self.ls(top_path, detail=True) directories, files = _libhdfs_walk_files_dirs(top_path, contents) yield top_path, directories, files for dirname in directories: for tup in self.walk(self._path_join(top_path, dirname)): yield tup def _maybe_set_hadoop_classpath(): import re if re.search(r'hadoop-common[^/]+.jar', os.environ.get('CLASSPATH', '')): return if 'HADOOP_HOME' in os.environ: if sys.platform != 'win32': classpath = _derive_hadoop_classpath() else: hadoop_bin = '{0}/bin/hadoop'.format(os.environ['HADOOP_HOME']) classpath = _hadoop_classpath_glob(hadoop_bin) else: classpath = _hadoop_classpath_glob('hadoop') os.environ['CLASSPATH'] = classpath.decode('utf-8') def _derive_hadoop_classpath(): import subprocess find_args = ('find', '-L', os.environ['HADOOP_HOME'], '-name', '*.jar') find = subprocess.Popen(find_args, stdout=subprocess.PIPE) xargs_echo = subprocess.Popen(('xargs', 'echo'), stdin=find.stdout, stdout=subprocess.PIPE) jars = subprocess.check_output(('tr', "' '", "':'"), stdin=xargs_echo.stdout) hadoop_conf = os.environ["HADOOP_CONF_DIR"] \ if "HADOOP_CONF_DIR" in os.environ \ else os.environ["HADOOP_HOME"] + "/etc/hadoop" return (hadoop_conf + ":").encode("utf-8") + jars def _hadoop_classpath_glob(hadoop_bin): import subprocess hadoop_classpath_args = (hadoop_bin, 'classpath', '--glob') return subprocess.check_output(hadoop_classpath_args) def _libhdfs_walk_files_dirs(top_path, contents): files = [] directories = [] for c in contents: scrubbed_name = posixpath.split(c['name'])[1] if c['kind'] == 'file': files.append(scrubbed_name) else: directories.append(scrubbed_name) return directories, files def connect(host="default", port=0, user=None, kerb_ticket=None, driver='libhdfs', extra_conf=None): """ Connect to an HDFS cluster. All parameters are optional and should only be set if the defaults need to be overridden. Authentication should be automatic if the HDFS cluster uses Kerberos. However, if a username is specified, then the ticket cache will likely be required. Parameters ---------- host : NameNode. Set to "default" for fs.defaultFS from core-site.xml. port : NameNode's port. Set to 0 for default or logical (HA) nodes. user : Username when connecting to HDFS; None implies login user. kerb_ticket : Path to Kerberos ticket cache. driver : {'libhdfs', 'libhdfs3'}, default 'libhdfs' Connect using libhdfs (JNI-based) or libhdfs3 (3rd-party C++ library from Apache HAWQ (incubating) ) extra_conf : dict, default None extra Key/Value pairs for config; Will override any hdfs-site.xml properties Notes ----- The first time you call this method, it will take longer than usual due to JNI spin-up time. Returns ------- filesystem : HadoopFileSystem """ fs = HadoopFileSystem(host=host, port=port, user=user, kerb_ticket=kerb_ticket, driver=driver, extra_conf=extra_conf) return fs
"""Constants for the Xiaomi Miio component.""" from miio.vacuum import ( ROCKROBO_S5, ROCKROBO_S6, ROCKROBO_S6_MAXV, ROCKROBO_S7, ROCKROBO_V1, ) DOMAIN = "xiaomi_miio" # Config flow CONF_FLOW_TYPE = "config_flow_device" CONF_GATEWAY = "gateway" CONF_DEVICE = "device" CONF_MODEL = "model" CONF_MAC = "mac" CONF_CLOUD_USERNAME = "cloud_username" CONF_CLOUD_PASSWORD = "cloud_password" CONF_CLOUD_COUNTRY = "cloud_country" CONF_MANUAL = "manual" # Options flow CONF_CLOUD_SUBDEVICES = "cloud_subdevices" # Keys KEY_COORDINATOR = "coordinator" KEY_DEVICE = "device" # Attributes ATTR_AVAILABLE = "available" # Status SUCCESS = ["ok"] # Cloud SERVER_COUNTRY_CODES = ["cn", "de", "i2", "ru", "sg", "us"] DEFAULT_CLOUD_COUNTRY = "cn" # Exceptions class AuthException(Exception): """Exception indicating an authentication error.""" class SetupException(Exception): """Exception indicating a failure during setup.""" # Fan Models MODEL_AIRPURIFIER_2H = "zhimi.airpurifier.mc2" MODEL_AIRPURIFIER_2S = "zhimi.airpurifier.mc1" MODEL_AIRPURIFIER_3 = "zhimi.airpurifier.ma4" MODEL_AIRPURIFIER_3C = "zhimi.airpurifier.mb4" MODEL_AIRPURIFIER_3H = "zhimi.airpurifier.mb3" MODEL_AIRPURIFIER_M1 = "zhimi.airpurifier.m1" MODEL_AIRPURIFIER_M2 = "zhimi.airpurifier.m2" MODEL_AIRPURIFIER_MA1 = "zhimi.airpurifier.ma1" MODEL_AIRPURIFIER_MA2 = "zhimi.airpurifier.ma2" MODEL_AIRPURIFIER_PRO = "zhimi.airpurifier.v6" MODEL_AIRPURIFIER_PROH = "zhimi.airpurifier.va1" MODEL_AIRPURIFIER_PRO_V7 = "zhimi.airpurifier.v7" MODEL_AIRPURIFIER_SA1 = "zhimi.airpurifier.sa1" MODEL_AIRPURIFIER_SA2 = "zhimi.airpurifier.sa2" MODEL_AIRPURIFIER_V1 = "zhimi.airpurifier.v1" MODEL_AIRPURIFIER_V2 = "zhimi.airpurifier.v2" MODEL_AIRPURIFIER_V3 = "zhimi.airpurifier.v3" MODEL_AIRPURIFIER_V5 = "zhimi.airpurifier.v5" MODEL_AIRHUMIDIFIER_V1 = "zhimi.humidifier.v1" MODEL_AIRHUMIDIFIER_CA1 = "zhimi.humidifier.ca1" MODEL_AIRHUMIDIFIER_CA4 = "zhimi.humidifier.ca4" MODEL_AIRHUMIDIFIER_CB1 = "zhimi.humidifier.cb1" MODEL_AIRHUMIDIFIER_JSQ = "deerma.humidifier.jsq" MODEL_AIRHUMIDIFIER_JSQ1 = "deerma.humidifier.jsq1" MODEL_AIRHUMIDIFIER_MJJSQ = "deerma.humidifier.mjjsq" MODEL_AIRFRESH_VA2 = "zhimi.airfresh.va2" MODEL_FAN_1C = "dmaker.fan.1c" MODEL_FAN_P10 = "dmaker.fan.p10" MODEL_FAN_P11 = "dmaker.fan.p11" MODEL_FAN_P5 = "dmaker.fan.p5" MODEL_FAN_P9 = "dmaker.fan.p9" MODEL_FAN_SA1 = "zhimi.fan.sa1" MODEL_FAN_V2 = "zhimi.fan.v2" MODEL_FAN_V3 = "zhimi.fan.v3" MODEL_FAN_ZA1 = "zhimi.fan.za1" MODEL_FAN_ZA3 = "zhimi.fan.za3" MODEL_FAN_ZA4 = "zhimi.fan.za4" MODEL_FAN_ZA5 = "zhimi.fan.za5" MODELS_FAN_MIIO = [ MODEL_FAN_P5, MODEL_FAN_SA1, MODEL_FAN_V2, MODEL_FAN_V3, MODEL_FAN_ZA1, MODEL_FAN_ZA3, MODEL_FAN_ZA4, ] MODELS_FAN_MIOT = [ MODEL_FAN_1C, MODEL_FAN_P10, MODEL_FAN_P11, MODEL_FAN_P9, MODEL_FAN_ZA5, ] MODELS_PURIFIER_MIOT = [ MODEL_AIRPURIFIER_3, MODEL_AIRPURIFIER_3C, MODEL_AIRPURIFIER_3H, MODEL_AIRPURIFIER_PROH, ] MODELS_PURIFIER_MIIO = [ MODEL_AIRPURIFIER_V1, MODEL_AIRPURIFIER_V2, MODEL_AIRPURIFIER_V3, MODEL_AIRPURIFIER_V5, MODEL_AIRPURIFIER_PRO, MODEL_AIRPURIFIER_PRO_V7, MODEL_AIRPURIFIER_M1, MODEL_AIRPURIFIER_M2, MODEL_AIRPURIFIER_MA1, MODEL_AIRPURIFIER_MA2, MODEL_AIRPURIFIER_SA1, MODEL_AIRPURIFIER_SA2, MODEL_AIRPURIFIER_2S, MODEL_AIRPURIFIER_2H, MODEL_AIRFRESH_VA2, ] MODELS_HUMIDIFIER_MIIO = [ MODEL_AIRHUMIDIFIER_V1, MODEL_AIRHUMIDIFIER_CA1, MODEL_AIRHUMIDIFIER_CB1, ] MODELS_HUMIDIFIER_MIOT = [MODEL_AIRHUMIDIFIER_CA4] MODELS_HUMIDIFIER_MJJSQ = [ MODEL_AIRHUMIDIFIER_JSQ, MODEL_AIRHUMIDIFIER_JSQ1, MODEL_AIRHUMIDIFIER_MJJSQ, ] # AirQuality Models MODEL_AIRQUALITYMONITOR_V1 = "zhimi.airmonitor.v1" MODEL_AIRQUALITYMONITOR_B1 = "cgllc.airmonitor.b1" MODEL_AIRQUALITYMONITOR_S1 = "cgllc.airmonitor.s1" MODEL_AIRQUALITYMONITOR_CGDN1 = "cgllc.airm.cgdn1" MODELS_AIR_QUALITY_MONITOR = [ MODEL_AIRQUALITYMONITOR_V1, MODEL_AIRQUALITYMONITOR_B1, MODEL_AIRQUALITYMONITOR_S1, MODEL_AIRQUALITYMONITOR_CGDN1, ] # Light Models MODELS_LIGHT_EYECARE = ["philips.light.sread1"] MODELS_LIGHT_CEILING = ["philips.light.ceiling", "philips.light.zyceiling"] MODELS_LIGHT_MOON = ["philips.light.moonlight"] MODELS_LIGHT_BULB = [ "philips.light.bulb", "philips.light.candle", "philips.light.candle2", "philips.light.downlight", ] MODELS_LIGHT_MONO = ["philips.light.mono1"] # Model lists MODELS_GATEWAY = ["lumi.gateway", "lumi.acpartner"] MODELS_SWITCH = [ "chuangmi.plug.v1", "chuangmi.plug.v3", "chuangmi.plug.hmi208", "qmi.powerstrip.v1", "zimi.powerstrip.v2", "chuangmi.plug.m1", "chuangmi.plug.m3", "chuangmi.plug.v2", "chuangmi.plug.hmi205", "chuangmi.plug.hmi206", ] MODELS_FAN = ( MODELS_PURIFIER_MIIO + MODELS_PURIFIER_MIOT + MODELS_FAN_MIIO + MODELS_FAN_MIOT ) MODELS_HUMIDIFIER = ( MODELS_HUMIDIFIER_MIOT + MODELS_HUMIDIFIER_MIIO + MODELS_HUMIDIFIER_MJJSQ ) MODELS_LIGHT = ( MODELS_LIGHT_EYECARE + MODELS_LIGHT_CEILING + MODELS_LIGHT_MOON + MODELS_LIGHT_BULB + MODELS_LIGHT_MONO ) MODELS_VACUUM = [ROCKROBO_V1, ROCKROBO_S5, ROCKROBO_S6, ROCKROBO_S6_MAXV, ROCKROBO_S7] MODELS_VACUUM_WITH_MOP = [ROCKROBO_S5, ROCKROBO_S6, ROCKROBO_S6_MAXV, ROCKROBO_S7] MODELS_AIR_MONITOR = [ MODEL_AIRQUALITYMONITOR_V1, MODEL_AIRQUALITYMONITOR_B1, MODEL_AIRQUALITYMONITOR_S1, MODEL_AIRQUALITYMONITOR_CGDN1, ] MODELS_ALL_DEVICES = ( MODELS_SWITCH + MODELS_VACUUM + MODELS_AIR_MONITOR + MODELS_FAN + MODELS_HUMIDIFIER + MODELS_LIGHT ) MODELS_ALL = MODELS_ALL_DEVICES + MODELS_GATEWAY # Fan/Humidifier Services SERVICE_SET_FAVORITE_LEVEL = "fan_set_favorite_level" SERVICE_SET_FAN_LEVEL = "fan_set_fan_level" SERVICE_SET_VOLUME = "fan_set_volume" SERVICE_RESET_FILTER = "fan_reset_filter" SERVICE_SET_EXTRA_FEATURES = "fan_set_extra_features" SERVICE_SET_DRY = "set_dry" SERVICE_SET_MOTOR_SPEED = "fan_set_motor_speed" # Light Services SERVICE_SET_SCENE = "light_set_scene" SERVICE_SET_DELAYED_TURN_OFF = "light_set_delayed_turn_off" SERVICE_REMINDER_ON = "light_reminder_on" SERVICE_REMINDER_OFF = "light_reminder_off" SERVICE_NIGHT_LIGHT_MODE_ON = "light_night_light_mode_on" SERVICE_NIGHT_LIGHT_MODE_OFF = "light_night_light_mode_off" SERVICE_EYECARE_MODE_ON = "light_eyecare_mode_on" SERVICE_EYECARE_MODE_OFF = "light_eyecare_mode_off" # Remote Services SERVICE_LEARN = "remote_learn_command" SERVICE_SET_REMOTE_LED_ON = "remote_set_led_on" SERVICE_SET_REMOTE_LED_OFF = "remote_set_led_off" # Switch Services SERVICE_SET_WIFI_LED_ON = "switch_set_wifi_led_on" SERVICE_SET_WIFI_LED_OFF = "switch_set_wifi_led_off" SERVICE_SET_POWER_MODE = "switch_set_power_mode" SERVICE_SET_POWER_PRICE = "switch_set_power_price" # Vacuum Services SERVICE_MOVE_REMOTE_CONTROL = "vacuum_remote_control_move" SERVICE_MOVE_REMOTE_CONTROL_STEP = "vacuum_remote_control_move_step" SERVICE_START_REMOTE_CONTROL = "vacuum_remote_control_start" SERVICE_STOP_REMOTE_CONTROL = "vacuum_remote_control_stop" SERVICE_CLEAN_SEGMENT = "vacuum_clean_segment" SERVICE_CLEAN_ZONE = "vacuum_clean_zone" SERVICE_GOTO = "vacuum_goto" # Features FEATURE_SET_BUZZER = 1 FEATURE_SET_LED = 2 FEATURE_SET_CHILD_LOCK = 4 FEATURE_SET_LED_BRIGHTNESS = 8 FEATURE_SET_FAVORITE_LEVEL = 16 FEATURE_SET_AUTO_DETECT = 32 FEATURE_SET_LEARN_MODE = 64 FEATURE_SET_VOLUME = 128 FEATURE_RESET_FILTER = 256 FEATURE_SET_EXTRA_FEATURES = 512 FEATURE_SET_TARGET_HUMIDITY = 1024 FEATURE_SET_DRY = 2048 FEATURE_SET_FAN_LEVEL = 4096 FEATURE_SET_MOTOR_SPEED = 8192 FEATURE_SET_CLEAN = 16384 FEATURE_SET_OSCILLATION_ANGLE = 32768 FEATURE_SET_DELAY_OFF_COUNTDOWN = 65536 FEATURE_SET_LED_BRIGHTNESS_LEVEL = 131072 FEATURE_SET_FAVORITE_RPM = 262144 FEATURE_SET_IONIZER = 524288 FEATURE_FLAGS_AIRPURIFIER_MIIO = ( FEATURE_SET_BUZZER | FEATURE_SET_CHILD_LOCK | FEATURE_SET_LED | FEATURE_SET_FAVORITE_LEVEL | FEATURE_SET_LEARN_MODE | FEATURE_RESET_FILTER | FEATURE_SET_EXTRA_FEATURES ) FEATURE_FLAGS_AIRPURIFIER_MIOT = ( FEATURE_SET_BUZZER | FEATURE_SET_CHILD_LOCK | FEATURE_SET_FAVORITE_LEVEL | FEATURE_SET_FAN_LEVEL | FEATURE_SET_LED_BRIGHTNESS ) FEATURE_FLAGS_AIRPURIFIER_3C = ( FEATURE_SET_BUZZER | FEATURE_SET_CHILD_LOCK | FEATURE_SET_LED_BRIGHTNESS_LEVEL | FEATURE_SET_FAVORITE_RPM ) FEATURE_FLAGS_AIRPURIFIER_PRO = ( FEATURE_SET_CHILD_LOCK | FEATURE_SET_LED | FEATURE_SET_FAVORITE_LEVEL | FEATURE_SET_VOLUME ) FEATURE_FLAGS_AIRPURIFIER_PRO_V7 = ( FEATURE_SET_CHILD_LOCK | FEATURE_SET_LED | FEATURE_SET_FAVORITE_LEVEL | FEATURE_SET_VOLUME ) FEATURE_FLAGS_AIRPURIFIER_2S = ( FEATURE_SET_BUZZER | FEATURE_SET_CHILD_LOCK | FEATURE_SET_LED | FEATURE_SET_FAVORITE_LEVEL ) FEATURE_FLAGS_AIRPURIFIER_V1 = FEATURE_FLAGS_AIRPURIFIER_MIIO | FEATURE_SET_AUTO_DETECT FEATURE_FLAGS_AIRPURIFIER_V3 = ( FEATURE_SET_BUZZER | FEATURE_SET_CHILD_LOCK | FEATURE_SET_LED ) FEATURE_FLAGS_AIRHUMIDIFIER = ( FEATURE_SET_BUZZER | FEATURE_SET_CHILD_LOCK | FEATURE_SET_TARGET_HUMIDITY ) FEATURE_FLAGS_AIRHUMIDIFIER_CA_AND_CB = FEATURE_FLAGS_AIRHUMIDIFIER | FEATURE_SET_DRY FEATURE_FLAGS_AIRHUMIDIFIER_MJSSQ = ( FEATURE_SET_BUZZER | FEATURE_SET_LED | FEATURE_SET_TARGET_HUMIDITY ) FEATURE_FLAGS_AIRHUMIDIFIER_CA4 = ( FEATURE_SET_BUZZER | FEATURE_SET_CHILD_LOCK | FEATURE_SET_TARGET_HUMIDITY | FEATURE_SET_DRY | FEATURE_SET_MOTOR_SPEED | FEATURE_SET_CLEAN ) FEATURE_FLAGS_AIRFRESH = ( FEATURE_SET_BUZZER | FEATURE_SET_CHILD_LOCK | FEATURE_SET_LED | FEATURE_SET_LED_BRIGHTNESS | FEATURE_RESET_FILTER | FEATURE_SET_EXTRA_FEATURES ) FEATURE_FLAGS_FAN_P5 = ( FEATURE_SET_BUZZER | FEATURE_SET_CHILD_LOCK | FEATURE_SET_OSCILLATION_ANGLE | FEATURE_SET_LED | FEATURE_SET_DELAY_OFF_COUNTDOWN ) FEATURE_FLAGS_FAN = ( FEATURE_SET_BUZZER | FEATURE_SET_CHILD_LOCK | FEATURE_SET_OSCILLATION_ANGLE | FEATURE_SET_LED_BRIGHTNESS | FEATURE_SET_DELAY_OFF_COUNTDOWN ) FEATURE_FLAGS_FAN_ZA5 = ( FEATURE_SET_BUZZER | FEATURE_SET_CHILD_LOCK | FEATURE_SET_OSCILLATION_ANGLE | FEATURE_SET_LED_BRIGHTNESS | FEATURE_SET_DELAY_OFF_COUNTDOWN | FEATURE_SET_IONIZER ) FEATURE_FLAGS_FAN_1C = ( FEATURE_SET_BUZZER | FEATURE_SET_CHILD_LOCK | FEATURE_SET_LED | FEATURE_SET_DELAY_OFF_COUNTDOWN ) FEATURE_FLAGS_FAN_P9 = ( FEATURE_SET_BUZZER | FEATURE_SET_CHILD_LOCK | FEATURE_SET_OSCILLATION_ANGLE | FEATURE_SET_LED | FEATURE_SET_DELAY_OFF_COUNTDOWN ) FEATURE_FLAGS_FAN_P10_P11 = ( FEATURE_SET_BUZZER | FEATURE_SET_CHILD_LOCK | FEATURE_SET_OSCILLATION_ANGLE | FEATURE_SET_LED | FEATURE_SET_DELAY_OFF_COUNTDOWN )
from __future__ import absolute_import # Copyright (c) 2010-2015 openpyxl import pytest import codecs from io import BytesIO from zipfile import ZipFile # package imports from openpyxl.reader.excel import load_workbook from openpyxl.utils.indexed_list import IndexedList from openpyxl.styles.styleable import StyleArray from openpyxl.xml.functions import fromstring from openpyxl.styles import ( borders, numbers, Color, Font, PatternFill, GradientFill, Border, Side, Alignment, Protection, ) from openpyxl.xml.functions import Element @pytest.fixture def StyleReader(): from ..style import SharedStylesParser return SharedStylesParser @pytest.mark.parametrize("value, expected", [ ('f', False), ('0', False), ('false', False), ('1', True), ('t', True), ('true', True), ('anyvalue', True), ]) def test_bool_attrib(value, expected): from .. style import bool_attrib el = Element("root", value=value) assert bool_attrib(el, "value") is expected def test_unprotected_cell(StyleReader, datadir): datadir.chdir() with open ("worksheet_unprotected_style.xml") as src: reader = StyleReader(src.read()) from openpyxl.styles import Font reader.font_list = IndexedList([Font(), Font(), Font(), Font(), Font()]) reader.protections = IndexedList([Protection()]) reader.parse_cell_styles() styles = reader.cell_styles assert len(styles) == 3 # default is cells are locked assert styles[0] == StyleArray() assert styles[1] == StyleArray([4,0,0,0,0,0,0,0,0]) assert styles[2] == StyleArray([3,0,0,0,1,0,0,0,0]) def test_read_cell_style(datadir, StyleReader): datadir.chdir() with open("empty-workbook-styles.xml") as content: reader = StyleReader(content.read()) reader.parse() styles = reader.cell_styles assert len(styles) == 2 assert reader.cell_styles[0] == StyleArray() assert reader.cell_styles[1] == StyleArray([0,0,0,9,0,0,0,0,1]) def test_read_xf_no_number_format(datadir, StyleReader): datadir.chdir() with open("no_number_format.xml") as src: reader = StyleReader(src.read()) from openpyxl.styles import Font reader.font_list = [Font(), Font()] reader.parse_cell_styles() styles = reader.cell_styles assert len(styles) == 3 assert styles[0] == StyleArray() assert styles[1] == StyleArray([1,0,1,0,0,0,0,0,0]) assert styles[2] == StyleArray([0,0,0,14,0,0,0,0,0]) def test_read_complex_style_mappings(datadir, StyleReader): datadir.chdir() with open("complex-styles.xml") as content: reader = StyleReader(content.read()) reader.parse() styles = reader.cell_styles assert len(styles) == 29 assert styles[-1] == StyleArray([6,5,0,0,0,0,0,0,0]) def test_read_complex_fonts(datadir, StyleReader): from openpyxl.styles import Font datadir.chdir() with open("complex-styles.xml") as content: reader = StyleReader(content.read()) fonts = list(reader.parse_fonts()) assert len(fonts) == 8 assert fonts[7] == Font(size=12, color=Color(theme=9), name="Calibri", scheme="minor") def test_read_complex_fills(datadir, StyleReader): datadir.chdir() with open("complex-styles.xml") as content: reader = StyleReader(content.read()) fills = list(reader.parse_fills()) assert len(fills) == 6 def test_read_complex_borders(datadir, StyleReader): datadir.chdir() with open("complex-styles.xml") as content: reader = StyleReader(content.read()) borders = list(reader.parse_borders()) assert len(borders) == 7 def test_read_simple_style_mappings(datadir, StyleReader): datadir.chdir() with open("simple-styles.xml") as content: reader = StyleReader(content.read()) reader.parse() styles = reader.cell_styles assert len(styles) == 4 assert styles[1].numFmtId == 9 assert styles[2].numFmtId == 164 def test_read_complex_style(datadir): datadir.chdir() wb = load_workbook("complex-styles.xlsx") ws = wb.active assert ws.column_dimensions['A'].width == 31.1640625 #assert ws.column_dimensions['I'].font == Font(sz=12.0, color='FF3300FF', scheme='minor') assert ws.column_dimensions['I'].fill == PatternFill(patternType='solid', fgColor='FF006600', bgColor=Color(indexed=64)) assert ws['A2'].font == Font(sz=10, name='Arial', color=Color(theme=1)) assert ws['A3'].font == Font(sz=12, name='Arial', bold=True, color=Color(theme=1)) assert ws['A4'].font == Font(sz=14, name='Arial', italic=True, color=Color(theme=1)) assert ws['A5'].font.color.value == 'FF3300FF' assert ws['A6'].font.color.value == 9 assert ws['A7'].fill.start_color.value == 'FFFFFF66' assert ws['A8'].fill.start_color.value == 8 assert ws['A9'].alignment.horizontal == 'left' assert ws['A10'].alignment.horizontal == 'right' assert ws['A11'].alignment.horizontal == 'center' assert ws['A12'].alignment.vertical == 'top' assert ws['A13'].alignment.vertical == 'center' assert ws['A15'].number_format == '0.00' assert ws['A16'].number_format == 'mm-dd-yy' assert ws['A17'].number_format == '0.00%' assert 'A18:B18' in ws._merged_cells assert ws['A19'].border == Border( left=Side(style='thin', color='FF006600'), top=Side(style='thin', color='FF006600'), right=Side(style='thin', color='FF006600'), bottom=Side(style='thin', color='FF006600'), ) assert ws['A21'].border == Border( left=Side(style='double', color=Color(theme=7)), top=Side(style='double', color=Color(theme=7)), right=Side(style='double', color=Color(theme=7)), bottom=Side(style='double', color=Color(theme=7)), ) assert ws['A23'].fill == PatternFill(patternType='solid', start_color='FFCCCCFF', end_color=(Color(indexed=64))) assert ws['A23'].border.top == Side(style='mediumDashed', color=Color(theme=6)) assert 'A23:B24' in ws._merged_cells assert ws['A25'].alignment == Alignment(wrapText=True) assert ws['A26'].alignment == Alignment(shrinkToFit=True) def test_none_values(datadir, StyleReader): datadir.chdir() with open("none_value_styles.xml") as src: reader = StyleReader(src.read()) fonts = tuple(reader.parse_fonts()) assert fonts[0].scheme is None assert fonts[0].vertAlign is None assert fonts[1].u is None def test_alignment(datadir, StyleReader): datadir.chdir() with open("alignment_styles.xml") as src: reader = StyleReader(src.read()) reader.parse_cell_styles() styles = reader.cell_styles assert len(styles) == 3 assert styles[2] == StyleArray([0,0,0,0,0,2,0,0,0]) assert reader.alignments == [ Alignment(), Alignment(textRotation=180), Alignment(vertical='top', textRotation=255), ] def test_style_names(datadir, StyleReader): datadir.chdir() with open("complex-styles.xml") as src: reader = StyleReader(src.read()) def sorter(value): return value.name names = reader._parse_style_names() references = [dict(style) for style in sorted(names.values(), key=sorter)] assert references == [ {'builtinId': '9', 'name': 'Followed Hyperlink', 'xfId': '10', 'hidden':'1'}, {'builtinId': '8', 'name': 'Hyperlink', 'xfId': '9', 'hidden':'1'}, {'builtinId': '0', 'name': 'Normal', 'xfId': '0'} ] def test_named_styles(datadir, StyleReader): from openpyxl.styles.named_styles import NamedStyle from openpyxl.styles.fonts import DEFAULT_FONT from openpyxl.styles.fills import DEFAULT_EMPTY_FILL datadir.chdir() with open("complex-styles.xml") as src: reader = StyleReader(src.read()) reader.border_list = list(reader.parse_borders()) reader.fill_list = list(reader.parse_fills()) reader.font_list = list(reader.parse_fonts()) reader.parse_named_styles() assert set(reader.named_styles.keys()) == set(['Followed Hyperlink', 'Hyperlink', 'Normal']) followed = reader.named_styles['Followed Hyperlink'] assert followed.name == "Followed Hyperlink" assert followed.font == reader.font_list[2] assert followed.fill == DEFAULT_EMPTY_FILL assert followed.border == Border() link = reader.named_styles['Hyperlink'] assert link.name == "Hyperlink" assert link.font == reader.font_list[1] assert link.fill == DEFAULT_EMPTY_FILL assert link.border == Border() normal = reader.named_styles['Normal'] assert normal.name == "Normal" assert normal.font == reader.font_list[0] assert normal.fill == DEFAULT_EMPTY_FILL assert normal.border == Border() def test_no_styles(): from .. style import read_style_table archive = ZipFile(BytesIO(), "a") assert read_style_table(archive) is None def test_rgb_colors(StyleReader, datadir): datadir.chdir() with open("rgb_colors.xml") as src: reader = StyleReader(src.read()) reader.parse_color_index() assert len(reader.color_index) == 64 assert reader.color_index[0] == "00000000" assert reader.color_index[-1] == "00333333" def test_custom_number_formats(StyleReader, datadir): datadir.chdir() with codecs.open("styles_number_formats.xml", encoding="utf-8") as src: content = src.read().encode("utf8") # Python 2.6, Windows reader = StyleReader(content) reader.parse_custom_num_formats() assert reader.custom_number_formats == { 43:'_ * #,##0.00_ ;_ * \-#,##0.00_ ;_ * "-"??_ ;_ @_ ', 176: "#,##0.00_ ", 180: "yyyy/m/d;@", 181: "0.00000_ " } assert reader.number_formats == [ '_ * #,##0.00_ ;_ * \-#,##0.00_ ;_ * "-"??_ ;_ @_ ', "#,##0.00_ ", "yyyy/m/d;@", "0.00000_ " ] def test_assign_number_formats(StyleReader): reader = StyleReader("<root />") reader.custom_number_formats = {43:'_ * #,##0.00_ ;_ * \-#,##0.00_ ;_ * "-"??_ ;_ @_ '} reader.number_formats = IndexedList(['_ * #,##0.00_ ;_ * \-#,##0.00_ ;_ * "-"??_ ;_ @_ ']) node = fromstring(""" <xf xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" numFmtId="43" fontId="2" fillId="0" borderId="0" applyFont="0" applyFill="0" applyBorder="0" applyAlignment="0" applyProtection="0"> <alignment vertical="center"/> </xf> """) styles = reader._parse_xfs(node) assert styles[0] == StyleArray([2, 0, 0, 164, 0, 1, 0, 0, 0]) #StyleId(numFmtId=164, fontId=2, alignmentId=1)
""" mlperf inference benchmarking tool """ from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import array import collections import json import logging import os import sys import threading import time from queue import Queue import mlperf_loadgen as lg import numpy as np import dataset import imagenet import coco logging.basicConfig(level=logging.INFO) log = logging.getLogger("main") NANO_SEC = 1e9 MILLI_SEC = 1000 # pylint: disable=missing-docstring # the datasets we support SUPPORTED_DATASETS = { "imagenet": (imagenet.Imagenet, dataset.pre_process_vgg, dataset.PostProcessCommon(offset=-1), {"image_size": [224, 224, 3]}), "imagenet_ncore": (imagenet.Imagenet, dataset.pre_process_vgg, dataset.PostProcessCommon(offset=-1), {"image_size": [224, 224, 3]}), "imagenet_mobilenet": (imagenet.Imagenet, dataset.pre_process_mobilenet, dataset.PostProcessArgMax(offset=-1), {"image_size": [224, 224, 3]}), "imagenet_mobilenet_ncore": (imagenet.Imagenet, dataset.pre_process_mobilenet_uint8, dataset.PostProcessArgMax(offset=-1), {"image_size": [224, 224, 3]}), "coco-300": (coco.Coco, dataset.pre_process_coco_mobilenet, coco.PostProcessCoco(), {"image_size": [300, 300, 3]}), "coco-300-ncore": (coco.Coco, dataset.pre_process_coco_mobilenet, coco.PostProcessCoco(), {"image_size": [300, 300, 3]}), "coco-300-pt": (coco.Coco, dataset.pre_process_coco_pt_mobilenet, coco.PostProcessCocoPt(False,0.3), {"image_size": [300, 300, 3]}), "coco-1200": (coco.Coco, dataset.pre_process_coco_resnet34, coco.PostProcessCoco(), {"image_size": [1200, 1200, 3]}), "coco-1200-onnx": (coco.Coco, dataset.pre_process_coco_resnet34, coco.PostProcessCocoOnnx(), {"image_size": [1200, 1200, 3]}), "coco-1200-pt": (coco.Coco, dataset.pre_process_coco_resnet34, coco.PostProcessCocoPt(True,0.05), {"image_size": [1200, 1200, 3],"use_label_map": True}), "coco-1200-tf": (coco.Coco, dataset.pre_process_coco_resnet34, coco.PostProcessCocoTf(), {"image_size": [1200, 1200, 3],"use_label_map": False}), } # pre-defined command line options so simplify things. They are used as defaults and can be # overwritten from command line SUPPORTED_PROFILES = { "defaults": { "dataset": "imagenet", "backend": "tensorflow", "cache": 0, "max-batchsize": 32, }, # resnet "resnet50-tf-calibrate": { "inputs": "input_tensor:0", "outputs": "ArgMax:0", "dataset": "imagenet", "backend": "tflite-calibrate", "model-name": "resnet50", }, "resnet50-tf-ncore": { "inputs": "input_tensor:0", "outputs": "ArgMax:0", "dataset": "imagenet_ncore", "backend": "tflite-ncore", "model-name": "resnet50", }, "resnet50-tf-ncore-offline": { "inputs": "input_tensor:0", "outputs": "ArgMax:0", "dataset": "imagenet_ncore", "backend": "tflite-ncore-offline-imagenet", "model-name": "resnet50", }, "resnet50-onnxruntime": { "dataset": "imagenet", "outputs": "ArgMax:0", "backend": "onnxruntime", "model-name": "resnet50", }, # mobilenet "mobilenet-tf": { "inputs": "input:0", "outputs": "MobilenetV1/Predictions/Reshape_1:0", "dataset": "imagenet_mobilenet", "backend": "tensorflow", "model-name": "mobilenet", }, "mobilenet-tf-ncore": { "inputs": "input:0", "outputs": "MobilenetV1/Predictions/Reshape_1:0", "dataset": "imagenet_mobilenet_ncore", "backend": "tflite-ncore", "model-name": "mobilenet", }, "mobilenet-tf-ncore-offline": { "inputs": "input:0", "outputs": "MobilenetV1/Predictions/Reshape_1:0", "dataset": "imagenet_mobilenet_ncore", "backend": "tflite-ncore-offline-imagenet", "model-name": "mobilenet", }, "mobilenet-onnxruntime": { "dataset": "imagenet_mobilenet", "outputs": "MobilenetV1/Predictions/Reshape_1:0", "backend": "onnxruntime", "model-name": "mobilenet", }, # ssd-mobilenet "ssd-mobilenet-tf": { "inputs": "image_tensor:0", "outputs": "num_detections:0,detection_boxes:0,detection_scores:0,detection_classes:0", "dataset": "coco-300", "backend": "tensorflow", "model-name": "ssd-mobilenet", }, "ssd-mobilenet-tflite": { "inputs": "image_tensor:0", "outputs": "detection_boxes:0,detection_classes:0,detection_scores:0,num_detections:0", "dataset": "coco-300", "backend": "tensorflow", "model-name": "ssd-mobilenet", }, "ssd-mobilenet-tf-ncore": { "inputs": "image_tensor:0", "outputs": "detection_boxes:0,detection_classes:0,detection_scores:0,num_detections:0", "dataset": "coco-300", "backend": "tflite-ncore", "model-name": "ssd-mobilenet", }, "ssd-mobilenet-tf-ncore-offline": { "inputs": "image_tensor:0", "outputs": "detection_boxes:0,detection_classes:0,detection_scores:0,num_detections:0", "dataset": "coco-300", "backend": "tflite-ncore-offline-ssd", "model-name": "ssd-mobilenet", }, "ssd-mobilenet-pytorch": { "inputs": "image", "outputs": "bboxes,labels,scores", "dataset": "coco-300-pt", "backend": "pytorch-native", "model-name": "ssd-mobilenet", }, "ssd-mobilenet-onnxruntime": { "dataset": "coco-300", "outputs": "num_detections:0,detection_boxes:0,detection_scores:0,detection_classes:0", "backend": "onnxruntime", "data-format": "NHWC", "model-name": "ssd-mobilenet", }, # ssd-resnet34 "ssd-resnet34-tf": { "inputs": "image:0", "outputs": "detection_bboxes:0,detection_classes:0,detection_scores:0", "dataset": "coco-1200-tf", "backend": "tensorflow", "data-format": "NCHW", "model-name": "ssd-resnet34", }, "ssd-resnet34-pytorch": { "inputs": "image", "outputs": "bboxes,labels,scores", "dataset": "coco-1200-pt", "backend": "pytorch-native", "model-name": "ssd-resnet34", }, "ssd-resnet34-onnxruntime": { "dataset": "coco-1200-onnx", "inputs": "image", "outputs": "bboxes,labels,scores", "backend": "onnxruntime", "data-format": "NCHW", "max-batchsize": 1, "model-name": "ssd-resnet34", }, "ssd-resnet34-onnxruntime-tf": { "dataset": "coco-1200-tf", "inputs": "image:0", "outputs": "detection_bboxes:0,detection_classes:0,detection_scores:0", "backend": "onnxruntime", "data-format": "NHWC", "model-name": "ssd-resnet34", }, } SCENARIO_MAP = { "SingleStream": lg.TestScenario.SingleStream, "MultiStream": lg.TestScenario.MultiStream, "Server": lg.TestScenario.Server, "Offline": lg.TestScenario.Offline, } last_timeing = [] def get_args(): """Parse commandline.""" parser = argparse.ArgumentParser() parser.add_argument("--dataset", choices=SUPPORTED_DATASETS.keys(), help="dataset") parser.add_argument("--dataset-path", required=True, help="path to the dataset") parser.add_argument("--dataset-list", help="path to the dataset list") parser.add_argument("--data-format", choices=["NCHW", "NHWC"], help="data format") parser.add_argument("--profile", choices=SUPPORTED_PROFILES.keys(), help="standard profiles") parser.add_argument("--scenario", default="SingleStream", help="mlperf benchmark scenario, one of " + str(list(SCENARIO_MAP.keys()))) parser.add_argument("--max-batchsize", type=int, help="max batch size in a single inference") parser.add_argument("--model", required=True, help="model file") parser.add_argument("--output", help="test results") parser.add_argument("--inputs", help="model inputs") parser.add_argument("--outputs", help="model outputs") parser.add_argument("--backend", help="runtime to use") parser.add_argument("--model-name", help="name of the mlperf model, ie. resnet50") parser.add_argument("--threads", default=os.cpu_count(), type=int, help="threads") parser.add_argument("--qps", type=int, help="target qps") parser.add_argument("--cache", type=int, default=0, help="use cache") parser.add_argument("--accuracy", action="store_true", help="enable accuracy pass") parser.add_argument("--find-peak-performance", action="store_true", help="enable finding peak performance pass") # file to use mlperf rules compliant parameters parser.add_argument("--config", default="../mlperf.conf", help="mlperf rules config") # below will override mlperf rules compliant settings - don't use for official submission parser.add_argument("--time", type=int, help="time to scan in seconds") parser.add_argument("--count", type=int, help="dataset items to use") parser.add_argument("--max-latency", type=float, help="mlperf max latency in pct tile") parser.add_argument("--samples-per-query", type=int, help="mlperf multi-stream sample per query") parser.add_argument("--enable-trace", action="store_true", help="enable mlperf log trace") args = parser.parse_args() # don't use defaults in argparser. Instead we default to a dict, override that with a profile # and take this as default unless command line give defaults = SUPPORTED_PROFILES["defaults"] if args.profile: profile = SUPPORTED_PROFILES[args.profile] defaults.update(profile) for k, v in defaults.items(): kc = k.replace("-", "_") if getattr(args, kc) is None: setattr(args, kc, v) if args.inputs: args.inputs = args.inputs.split(",") if args.outputs: args.outputs = args.outputs.split(",") if args.scenario not in SCENARIO_MAP: parser.error("valid scanarios:" + str(list(SCENARIO_MAP.keys()))) return args def get_backend(backend): if backend == "tensorflow": from backend_tf import BackendTensorflow backend = BackendTensorflow() elif backend == "onnxruntime": from backend_onnxruntime import BackendOnnxruntime backend = BackendOnnxruntime() elif backend == "null": from backend_null import BackendNull backend = BackendNull() elif backend == "pytorch": from backend_pytorch import BackendPytorch backend = BackendPytorch() elif backend == "pytorch-native": from backend_pytorch_native import BackendPytorchNative backend = BackendPytorchNative() elif backend == "tflite": from backend_tflite import BackendTflite backend = BackendTflite() elif backend == "tflite-calibrate": from backend_tflite_calibrate import BackendTflite backend = BackendTflite() elif backend == "tflite-ncore": from backend_tflite_ncore import BackendTfliteNcore backend = BackendTfliteNcore() elif backend == "tflite-ncore-offline-imagenet": from backend_tflite_ncore_offline_imagenet import BackendTfliteNcoreOfflineImagenet backend = BackendTfliteNcoreOfflineImagenet() elif backend == "tflite-ncore-offline-ssd": from backend_tflite_ncore_offline_ssd import BackendTfliteNcoreOfflineSSD backend = BackendTfliteNcoreOfflineSSD() else: raise ValueError("unknown backend: " + backend) return backend class Item: """An item that we queue for processing by the thread pool.""" def __init__(self, query_id, content_id, img, label=None): self.query_id = query_id self.content_id = content_id self.img = img self.label = label self.start = time.time() class RunnerBase: def __init__(self, model, ds, threads, post_proc=None, max_batchsize=128): self.take_accuracy = False self.ds = ds self.model = model self.post_process = post_proc self.threads = threads self.take_accuracy = False self.max_batchsize = max_batchsize self.result_timing = [] def handle_tasks(self, tasks_queue): pass def start_run(self, result_dict, take_accuracy): self.result_dict = result_dict self.result_timing = [] self.take_accuracy = take_accuracy self.post_process.start() def run_one_item(self, qitem): # run the prediction processed_results = [] try: for i in range(len(qitem.query_id)): results = self.model.predict({self.model.inputs[0]: qitem.img}) processed_results.extend(self.post_process(results, qitem.content_id, qitem.label, self.result_dict)) if self.take_accuracy: self.post_process.add_results(processed_results) self.result_timing.append(time.time() - qitem.start) except Exception as ex: # pylint: disable=broad-except src = [self.ds.get_item_loc(i) for i in qitem.content_id] log.error("thread: failed on contentid=%s, %s", src, ex) # since post_process will not run, fake empty responses processed_results = [[]] * len(qitem.query_id) finally: response_array_refs = [] response = [] for idx, query_id in enumerate(qitem.query_id): response_array = array.array("B", np.array(processed_results[idx], np.float32).tobytes()) response_array_refs.append(response_array) bi = response_array.buffer_info() response.append(lg.QuerySampleResponse(query_id, bi[0], bi[1])) lg.QuerySamplesComplete(response) def enqueue(self, query_samples): idx = [q.index for q in query_samples] query_id = [q.id for q in query_samples] if len(query_samples) < self.max_batchsize: data, label = self.ds.get_samples(idx) self.run_one_item(Item(query_id, idx, data, label)) else: bs = self.max_batchsize for i in range(0, len(idx), bs): data, label = self.ds.get_samples(idx[i:i+bs]) self.run_one_item(Item(query_id[i:i+bs], idx[i:i+bs], data, label)) def finish(self): pass class QueueRunner(RunnerBase): def __init__(self, model, ds, threads, post_proc=None, max_batchsize=128): super().__init__(model, ds, threads, post_proc, max_batchsize) self.tasks = Queue(maxsize=threads * 4) self.workers = [] self.result_dict = {} for _ in range(self.threads): worker = threading.Thread(target=self.handle_tasks, args=(self.tasks,)) worker.daemon = True self.workers.append(worker) worker.start() def handle_tasks(self, tasks_queue): """Worker thread.""" while True: qitem = tasks_queue.get() if qitem is None: # None in the queue indicates the parent want us to exit tasks_queue.task_done() break self.run_one_item(qitem) tasks_queue.task_done() def enqueue(self, query_samples): idx = [q.index for q in query_samples] query_id = [q.id for q in query_samples] if len(query_samples) < self.max_batchsize: data, label = self.ds.get_samples(idx) self.tasks.put(Item(query_id, idx, data, label)) else: bs = self.max_batchsize for i in range(0, len(idx), bs): ie = i + bs data, label = self.ds.get_samples(idx[i:ie]) self.tasks.put(Item(query_id[i:ie], idx[i:ie], data, label)) def finish(self): # exit all threads for _ in self.workers: self.tasks.put(None) for worker in self.workers: worker.join() def add_results(final_results, name, result_dict, result_list, took, show_accuracy=False): percentiles = [50., 80., 90., 95., 99., 99.9] buckets = np.percentile(result_list, percentiles).tolist() buckets_str = ",".join(["{}:{:.4f}".format(p, b) for p, b in zip(percentiles, buckets)]) if result_dict["total"] == 0: result_dict["total"] = len(result_list) # this is what we record for each run result = { "took": took, "mean": np.mean(result_list), "percentiles": {str(k): v for k, v in zip(percentiles, buckets)}, "qps": len(result_list) / took, "count": len(result_list), "good_items": result_dict["good"], "total_items": result_dict["total"], } acc_str = "" if show_accuracy: result["accuracy"] = 100. * result_dict["good"] / result_dict["total"] acc_str = ", acc={:.3f}%".format(result["accuracy"]) if "mAP" in result_dict: result["mAP"] = 100. * result_dict["mAP"] acc_str += ", mAP={:.3f}%".format(result["mAP"]) # add the result to the result dict final_results[name] = result # to stdout print("{} qps={:.2f}, mean={:.4f}, time={:.3f}{}, queries={}, tiles={}".format( name, result["qps"], result["mean"], took, acc_str, len(result_list), buckets_str)) def main(): global last_timeing args = get_args() log.info(args) # find backend backend = get_backend(args.backend) # override image format if given image_format = args.data_format if args.data_format else backend.image_format() # --count applies to accuracy mode only and can be used to limit the number of images # for testing. For perf model we always limit count to 200. count_override = False count = args.count if count: count_override = True # dataset to use wanted_dataset, pre_proc, post_proc, kwargs = SUPPORTED_DATASETS[args.dataset] ds = wanted_dataset(data_path=args.dataset_path, image_list=args.dataset_list, name=args.dataset, image_format=image_format, pre_process=pre_proc, use_cache=args.cache, count=count, **kwargs) # load model to backend model = backend.load(args.model, inputs=args.inputs, outputs=args.outputs) final_results = { "runtime": model.name(), "version": model.version(), "time": int(time.time()), "cmdline": str(args), } config = os.path.abspath(args.config) if not os.path.exists(config): log.error("{} not found".format(config)) sys.exit(1) if args.output: output_dir = os.path.abspath(args.output) os.makedirs(output_dir, exist_ok=True) os.chdir(output_dir) # # make one pass over the dataset to validate accuracy # count = ds.get_item_count() # warmup warmup_queries = range(args.max_batchsize) ds.load_query_samples(warmup_queries) for _ in range(2): img, _ = ds.get_samples(warmup_queries) _ = backend.predict({backend.inputs[0]: img}) ds.unload_query_samples(None) scenario = SCENARIO_MAP[args.scenario] runner_map = { lg.TestScenario.SingleStream: RunnerBase, lg.TestScenario.MultiStream: QueueRunner, lg.TestScenario.Server: QueueRunner, lg.TestScenario.Offline: QueueRunner } runner = runner_map[scenario](model, ds, args.threads, post_proc=post_proc, max_batchsize=args.max_batchsize) def issue_queries(query_samples): runner.enqueue(query_samples) def flush_queries(): pass def process_latencies(latencies_ns): # called by loadgen to show us the recorded latencies global last_timeing last_timeing = [t / NANO_SEC for t in latencies_ns] settings = lg.TestSettings() settings.FromConfig(config, args.model_name, args.scenario) settings.scenario = scenario settings.mode = lg.TestMode.PerformanceOnly if args.accuracy: settings.mode = lg.TestMode.AccuracyOnly if args.find_peak_performance: settings.mode = lg.TestMode.FindPeakPerformance if args.time: # override the time we want to run settings.min_duration_ms = args.time * MILLI_SEC settings.max_duration_ms = args.time * MILLI_SEC if args.qps: qps = float(args.qps) settings.server_target_qps = qps settings.offline_expected_qps = qps if count_override: settings.min_query_count = count settings.max_query_count = count if args.samples_per_query: settings.multi_stream_samples_per_query = args.samples_per_query if args.max_latency: settings.server_target_latency_ns = int(args.max_latency * NANO_SEC) settings.multi_stream_target_latency_ns = int(args.max_latency * NANO_SEC) # override target latency when it needs to be less than 1ms if args.model_name == "mobilenet": settings.single_stream_expected_latency_ns = 200000 elif args.model_name == "resnet50": settings.single_stream_expected_latency_ns = 900000 elif args.model_name == "ssd-mobilenet": settings.single_stream_expected_latency_ns = 1000000 sut = lg.ConstructSUT(issue_queries, flush_queries, process_latencies) #qsl = lg.ConstructQSL(count, min(count, 500), ds.load_query_samples, ds.unload_query_samples) qsl = lg.ConstructQSL(count, min(count, 1024), ds.load_query_samples, ds.unload_query_samples) log.info("starting {}".format(scenario)) result_dict = {"good": 0, "total": 0, "scenario": str(scenario)} runner.start_run(result_dict, args.accuracy) if args.enable_trace: lg.StartTest(sut, qsl, settings) else: logsettings = lg.LogSettings() logsettings.enable_trace = False lg.StartTestWithLogSettings(sut, qsl, settings, logsettings) if not last_timeing: last_timeing = runner.result_timing if args.accuracy: post_proc.finalize(result_dict, ds, output_dir=args.output) add_results(final_results, "{}".format(scenario), result_dict, last_timeing, time.time() - ds.last_loaded, args.accuracy) runner.finish() lg.DestroyQSL(qsl) lg.DestroySUT(sut) # # write final results # if args.output: with open("results.json", "w") as f: json.dump(final_results, f, sort_keys=True, indent=4) if __name__ == "__main__": main()
# Copyright 2018 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. # ============================================================================== """Keras-like layers and utilities that implement Spectral Normalization. Based on "Spectral Normalization for Generative Adversarial Networks" by Miyato, et al in ICLR 2018. https://openreview.net/pdf?id=B1QRgziT- """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import contextlib import numbers import re from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.keras.engine import base_layer_utils as keras_base_layer_utils from tensorflow.python.ops import array_ops from tensorflow.python.ops import init_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn from tensorflow.python.ops import variable_scope from tensorflow.python.platform import tf_logging as logging __all__ = [ 'compute_spectral_norm', 'spectral_normalize', 'spectral_norm_regularizer', 'spectral_normalization_custom_getter', 'keras_spectral_normalization' ] # tf.bfloat16 should work, but tf.matmul converts those to tf.float32 which then # can't directly be assigned back to the tf.bfloat16 variable. _OK_DTYPES_FOR_SPECTRAL_NORM = (dtypes.float16, dtypes.float32, dtypes.float64) _PERSISTED_U_VARIABLE_SUFFIX = 'spectral_norm_u' def compute_spectral_norm(w_tensor, power_iteration_rounds=1, name=None): """Estimates the largest singular value in the weight tensor. Args: w_tensor: The weight matrix whose spectral norm should be computed. power_iteration_rounds: The number of iterations of the power method to perform. A higher number yeilds a better approximation. name: An optional scope name. Returns: The largest singular value (the spectral norm) of w. """ with variable_scope.variable_scope(name, 'spectral_norm'): # The paper says to flatten convnet kernel weights from # (C_out, C_in, KH, KW) to (C_out, C_in * KH * KW). But TensorFlow's Conv2D # kernel weight shape is (KH, KW, C_in, C_out), so it should be reshaped to # (KH * KW * C_in, C_out), and similarly for other layers that put output # channels as last dimension. # n.b. this means that w here is equivalent to w.T in the paper. w = array_ops.reshape(w_tensor, (-1, w_tensor.get_shape()[-1])) # Persisted approximation of first left singular vector of matrix `w`. u_var = variable_scope.get_variable( _PERSISTED_U_VARIABLE_SUFFIX, shape=(w.shape[0], 1), dtype=w.dtype, initializer=init_ops.random_normal_initializer(), trainable=False) u = u_var # Use power iteration method to approximate spectral norm. for _ in range(power_iteration_rounds): # `v` approximates the first right singular vector of matrix `w`. v = nn.l2_normalize(math_ops.matmul(array_ops.transpose(w), u)) u = nn.l2_normalize(math_ops.matmul(w, v)) # Update persisted approximation. with ops.control_dependencies([u_var.assign(u, name='update_u')]): u = array_ops.identity(u) u = array_ops.stop_gradient(u) v = array_ops.stop_gradient(v) # Largest singular value of `w`. spectral_norm = math_ops.matmul( math_ops.matmul(array_ops.transpose(u), w), v) spectral_norm.shape.assert_is_fully_defined() spectral_norm.shape.assert_is_compatible_with([1, 1]) return spectral_norm[0][0] def spectral_normalize(w, power_iteration_rounds=1, name=None): """Normalizes a weight matrix by its spectral norm. Args: w: The weight matrix to be normalized. power_iteration_rounds: The number of iterations of the power method to perform. A higher number yeilds a better approximation. name: An optional scope name. Returns: A normalized weight matrix tensor. """ with variable_scope.variable_scope(name, 'spectral_normalize'): w_normalized = w / compute_spectral_norm( w, power_iteration_rounds=power_iteration_rounds) return array_ops.reshape(w_normalized, w.get_shape()) def spectral_norm_regularizer(scale, power_iteration_rounds=1, scope=None): """Returns a functions that can be used to apply spectral norm regularization. Small spectral norms enforce a small Lipschitz constant, which is necessary for Wasserstein GANs. Args: scale: A scalar multiplier. 0.0 disables the regularizer. power_iteration_rounds: The number of iterations of the power method to perform. A higher number yeilds a better approximation. scope: An optional scope name. Returns: A function with the signature `sn(weights)` that applies spectral norm regularization. Raises: ValueError: If scale is negative or if scale is not a float. """ if isinstance(scale, numbers.Integral): raise ValueError('scale cannot be an integer: %s' % scale) if isinstance(scale, numbers.Real): if scale < 0.0: raise ValueError( 'Setting a scale less than 0 on a regularizer: %g' % scale) if scale == 0.0: logging.info('Scale of 0 disables regularizer.') return lambda _: None def sn(weights, name=None): """Applies spectral norm regularization to weights.""" with ops.name_scope(scope, 'SpectralNormRegularizer', [weights]) as name: scale_t = ops.convert_to_tensor( scale, dtype=weights.dtype.base_dtype, name='scale') return math_ops.multiply( scale_t, compute_spectral_norm( weights, power_iteration_rounds=power_iteration_rounds), name=name) return sn def _default_name_filter(name): """A filter function to identify common names of weight variables. Args: name: The variable name. Returns: Whether `name` is a standard name for a weight/kernel variables used in the Keras, tf.layers, tf.contrib.layers or tf.contrib.slim libraries. """ match = re.match(r'(.*\/)?(depthwise_|pointwise_)?(weights|kernel)$', name) return match is not None def spectral_normalization_custom_getter(name_filter=_default_name_filter, power_iteration_rounds=1): """Custom getter that performs Spectral Normalization on a weight tensor. Specifically it divides the weight tensor by its largest singular value. This is intended to stabilize GAN training, by making the discriminator satisfy a local 1-Lipschitz constraint. Based on [Spectral Normalization for Generative Adversarial Networks][sn-gan]. [sn-gan]: https://openreview.net/forum?id=B1QRgziT- To reproduce an SN-GAN, apply this custom_getter to every weight tensor of your discriminator. The last dimension of the weight tensor must be the number of output channels. Apply this to layers by supplying this as the `custom_getter` of a `tf.variable_scope`. For example: with tf.variable_scope('discriminator', custom_getter=spectral_norm_getter()): net = discriminator_fn(net) IMPORTANT: Keras does not respect the custom_getter supplied by the VariableScope, so Keras users should use `keras_spectral_normalization` instead of (or in addition to) this approach. It is important to carefully select to which weights you want to apply Spectral Normalization. In general you want to normalize the kernels of convolution and dense layers, but you do not want to normalize biases. You also want to avoid normalizing batch normalization (and similar) variables, but in general such layers play poorly with Spectral Normalization, since the gamma can cancel out the normalization in other layers. By default we supply a filter that matches the kernel variable names of the dense and convolution layers of the tf.layers, tf.contrib.layers, tf.keras and tf.contrib.slim libraries. If you are using anything else you'll need a custom `name_filter`. This custom getter internally creates a variable used to compute the spectral norm by power iteration. It will update every time the variable is accessed, which means the normalized discriminator weights may change slightly whilst training the generator. Whilst unusual, this matches how the paper's authors implement it, and in general additional rounds of power iteration can't hurt. Args: name_filter: Optionally, a method that takes a Variable name as input and returns whether this Variable should be normalized. power_iteration_rounds: The number of iterations of the power method to perform per step. A higher number yeilds a better approximation of the true spectral norm. Returns: A custom getter function that applies Spectral Normalization to all Variables whose names match `name_filter`. Raises: ValueError: If name_filter is not callable. """ if not callable(name_filter): raise ValueError('name_filter must be callable') def _internal_getter(getter, name, *args, **kwargs): """A custom getter function that applies Spectral Normalization. Args: getter: The true getter to call. name: Name of new/existing variable, in the same format as tf.get_variable. *args: Other positional arguments, in the same format as tf.get_variable. **kwargs: Keyword arguments, in the same format as tf.get_variable. Returns: The return value of `getter(name, *args, **kwargs)`, spectrally normalized. Raises: ValueError: If used incorrectly, or if `dtype` is not supported. """ if not name_filter(name): return getter(name, *args, **kwargs) if name.endswith(_PERSISTED_U_VARIABLE_SUFFIX): raise ValueError( 'Cannot apply Spectral Normalization to internal variables created ' 'for Spectral Normalization. Tried to normalized variable [%s]' % name) if kwargs['dtype'] not in _OK_DTYPES_FOR_SPECTRAL_NORM: raise ValueError('Disallowed data type {}'.format(kwargs['dtype'])) # This layer's weight Variable/PartitionedVariable. w_tensor = getter(name, *args, **kwargs) if len(w_tensor.get_shape()) < 2: raise ValueError( 'Spectral norm can only be applied to multi-dimensional tensors') return spectral_normalize( w_tensor, power_iteration_rounds=power_iteration_rounds, name=(name + '/spectral_normalize')) return _internal_getter @contextlib.contextmanager def keras_spectral_normalization(name_filter=_default_name_filter, power_iteration_rounds=1): """A context manager that enables Spectral Normalization for Keras. Keras doesn't respect the `custom_getter` in the VariableScope, so this is a bit of a hack to make things work. Usage: with keras_spectral_normalization(): net = discriminator_fn(net) Args: name_filter: Optionally, a method that takes a Variable name as input and returns whether this Variable should be normalized. power_iteration_rounds: The number of iterations of the power method to perform per step. A higher number yeilds a better approximation of the true spectral norm. Yields: A context manager that wraps the standard Keras variable creation method with the `spectral_normalization_custom_getter`. """ original_make_variable = keras_base_layer_utils.make_variable sn_getter = spectral_normalization_custom_getter( name_filter=name_filter, power_iteration_rounds=power_iteration_rounds) def make_variable_wrapper(name, *args, **kwargs): return sn_getter(original_make_variable, name, *args, **kwargs) keras_base_layer_utils.make_variable = make_variable_wrapper yield keras_base_layer_utils.make_variable = original_make_variable
# -*- coding: utf-8 -*- # # Copyright (C) 2006-2008 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://genshi.edgewall.org/wiki/License. # # This software consists of voluntary contributions made by many # individuals. For the exact contribution history, see the revision # history and logs, available at http://genshi.edgewall.org/log/. import doctest import unittest import sys from genshi.core import Attrs, Markup, QName, Stream from genshi.input import HTML, XML from genshi.output import DocType, XMLSerializer, XHTMLSerializer, \ HTMLSerializer, EmptyTagFilter class XMLSerializerTestCase(unittest.TestCase): def test_with_xml_decl(self): stream = Stream([(Stream.XML_DECL, ('1.0', None, -1), (None, -1, -1))]) output = stream.render(XMLSerializer, doctype='xhtml', encoding=None) self.assertEqual('<?xml version="1.0"?>\n' '<!DOCTYPE html PUBLIC ' '"-//W3C//DTD XHTML 1.0 Strict//EN" ' '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n', output) def test_doctype_in_stream(self): stream = Stream([(Stream.DOCTYPE, DocType.HTML_STRICT, (None, -1, -1))]) output = stream.render(XMLSerializer, encoding=None) self.assertEqual('<!DOCTYPE html PUBLIC ' '"-//W3C//DTD HTML 4.01//EN" ' '"http://www.w3.org/TR/html4/strict.dtd">\n', output) def test_doctype_in_stream_no_sysid(self): stream = Stream([(Stream.DOCTYPE, ('html', '-//W3C//DTD HTML 4.01//EN', None), (None, -1, -1))]) output = stream.render(XMLSerializer, encoding=None) self.assertEqual('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">\n', output) def test_doctype_in_stream_no_pubid(self): stream = Stream([ (Stream.DOCTYPE, ('html', None, 'http://www.w3.org/TR/html4/strict.dtd'), (None, -1, -1)) ]) output = stream.render(XMLSerializer, encoding=None) self.assertEqual('<!DOCTYPE html SYSTEM ' '"http://www.w3.org/TR/html4/strict.dtd">\n', output) def test_doctype_in_stream_no_pubid_or_sysid(self): stream = Stream([(Stream.DOCTYPE, ('html', None, None), (None, -1, -1))]) output = stream.render(XMLSerializer, encoding=None) self.assertEqual('<!DOCTYPE html>\n', output) def test_serializer_doctype(self): stream = Stream([]) output = stream.render(XMLSerializer, doctype=DocType.HTML_STRICT, encoding=None) self.assertEqual('<!DOCTYPE html PUBLIC ' '"-//W3C//DTD HTML 4.01//EN" ' '"http://www.w3.org/TR/html4/strict.dtd">\n', output) def test_doctype_one_and_only(self): stream = Stream([ (Stream.DOCTYPE, ('html', None, None), (None, -1, -1)) ]) output = stream.render(XMLSerializer, doctype=DocType.HTML_STRICT, encoding=None) self.assertEqual('<!DOCTYPE html PUBLIC ' '"-//W3C//DTD HTML 4.01//EN" ' '"http://www.w3.org/TR/html4/strict.dtd">\n', output) def test_comment(self): stream = Stream([(Stream.COMMENT, 'foo bar', (None, -1, -1))]) output = stream.render(XMLSerializer, encoding=None) self.assertEqual('<!--foo bar-->', output) def test_processing_instruction(self): stream = Stream([(Stream.PI, ('python', 'x = 2'), (None, -1, -1))]) output = stream.render(XMLSerializer, encoding=None) self.assertEqual('<?python x = 2?>', output) def test_nested_default_namespaces(self): stream = Stream([ (Stream.START_NS, ('', 'http://example.org/'), (None, -1, -1)), (Stream.START, (QName('http://example.org/}div'), Attrs()), (None, -1, -1)), (Stream.TEXT, '\n ', (None, -1, -1)), (Stream.START_NS, ('', 'http://example.org/'), (None, -1, -1)), (Stream.START, (QName('http://example.org/}p'), Attrs()), (None, -1, -1)), (Stream.END, QName('http://example.org/}p'), (None, -1, -1)), (Stream.END_NS, '', (None, -1, -1)), (Stream.TEXT, '\n ', (None, -1, -1)), (Stream.START_NS, ('', 'http://example.org/'), (None, -1, -1)), (Stream.START, (QName('http://example.org/}p'), Attrs()), (None, -1, -1)), (Stream.END, QName('http://example.org/}p'), (None, -1, -1)), (Stream.END_NS, '', (None, -1, -1)), (Stream.TEXT, '\n ', (None, -1, -1)), (Stream.END, QName('http://example.org/}div'), (None, -1, -1)), (Stream.END_NS, '', (None, -1, -1)) ]) output = stream.render(XMLSerializer, encoding=None) self.assertEqual("""<div xmlns="http://example.org/"> <p/> <p/> </div>""", output) def test_nested_bound_namespaces(self): stream = Stream([ (Stream.START_NS, ('x', 'http://example.org/'), (None, -1, -1)), (Stream.START, (QName('http://example.org/}div'), Attrs()), (None, -1, -1)), (Stream.TEXT, '\n ', (None, -1, -1)), (Stream.START_NS, ('x', 'http://example.org/'), (None, -1, -1)), (Stream.START, (QName('http://example.org/}p'), Attrs()), (None, -1, -1)), (Stream.END, QName('http://example.org/}p'), (None, -1, -1)), (Stream.END_NS, 'x', (None, -1, -1)), (Stream.TEXT, '\n ', (None, -1, -1)), (Stream.START_NS, ('x', 'http://example.org/'), (None, -1, -1)), (Stream.START, (QName('http://example.org/}p'), Attrs()), (None, -1, -1)), (Stream.END, QName('http://example.org/}p'), (None, -1, -1)), (Stream.END_NS, 'x', (None, -1, -1)), (Stream.TEXT, '\n ', (None, -1, -1)), (Stream.END, QName('http://example.org/}div'), (None, -1, -1)), (Stream.END_NS, 'x', (None, -1, -1)) ]) output = stream.render(XMLSerializer, encoding=None) self.assertEqual("""<x:div xmlns:x="http://example.org/"> <x:p/> <x:p/> </x:div>""", output) def test_multiple_default_namespaces(self): stream = Stream([ (Stream.START, (QName('div'), Attrs()), (None, -1, -1)), (Stream.TEXT, '\n ', (None, -1, -1)), (Stream.START_NS, ('', 'http://example.org/'), (None, -1, -1)), (Stream.START, (QName('http://example.org/}p'), Attrs()), (None, -1, -1)), (Stream.END, QName('http://example.org/}p'), (None, -1, -1)), (Stream.END_NS, '', (None, -1, -1)), (Stream.TEXT, '\n ', (None, -1, -1)), (Stream.START_NS, ('', 'http://example.org/'), (None, -1, -1)), (Stream.START, (QName('http://example.org/}p'), Attrs()), (None, -1, -1)), (Stream.END, QName('http://example.org/}p'), (None, -1, -1)), (Stream.END_NS, '', (None, -1, -1)), (Stream.TEXT, '\n ', (None, -1, -1)), (Stream.END, QName('div'), (None, -1, -1)), ]) output = stream.render(XMLSerializer, encoding=None) self.assertEqual("""<div> <p xmlns="http://example.org/"/> <p xmlns="http://example.org/"/> </div>""", output) def test_multiple_bound_namespaces(self): stream = Stream([ (Stream.START, (QName('div'), Attrs()), (None, -1, -1)), (Stream.TEXT, '\n ', (None, -1, -1)), (Stream.START_NS, ('x', 'http://example.org/'), (None, -1, -1)), (Stream.START, (QName('http://example.org/}p'), Attrs()), (None, -1, -1)), (Stream.END, QName('http://example.org/}p'), (None, -1, -1)), (Stream.END_NS, 'x', (None, -1, -1)), (Stream.TEXT, '\n ', (None, -1, -1)), (Stream.START_NS, ('x', 'http://example.org/'), (None, -1, -1)), (Stream.START, (QName('http://example.org/}p'), Attrs()), (None, -1, -1)), (Stream.END, QName('http://example.org/}p'), (None, -1, -1)), (Stream.END_NS, 'x', (None, -1, -1)), (Stream.TEXT, '\n ', (None, -1, -1)), (Stream.END, QName('div'), (None, -1, -1)), ]) output = stream.render(XMLSerializer, encoding=None) self.assertEqual("""<div> <x:p xmlns:x="http://example.org/"/> <x:p xmlns:x="http://example.org/"/> </div>""", output) def test_atom_with_xhtml(self): text = """<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"> <id>urn:uuid:c60843aa-0da8-4fa6-bbe5-98007bc6774e</id> <updated>2007-01-28T11:36:02.807108-06:00</updated> <title type="xhtml"> <div xmlns="http://www.w3.org/1999/xhtml">Example</div> </title> <subtitle type="xhtml"> <div xmlns="http://www.w3.org/1999/xhtml">Bla bla bla</div> </subtitle> <icon/> </feed>""" output = XML(text).render(XMLSerializer, encoding=None) self.assertEqual(text, output) class XHTMLSerializerTestCase(unittest.TestCase): def test_xml_decl_dropped(self): stream = Stream([(Stream.XML_DECL, ('1.0', None, -1), (None, -1, -1))]) output = stream.render(XHTMLSerializer, doctype='xhtml', encoding=None) self.assertEqual('<!DOCTYPE html PUBLIC ' '"-//W3C//DTD XHTML 1.0 Strict//EN" ' '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n', output) def test_xml_decl_included(self): stream = Stream([(Stream.XML_DECL, ('1.0', None, -1), (None, -1, -1))]) output = stream.render(XHTMLSerializer, doctype='xhtml', drop_xml_decl=False, encoding=None) self.assertEqual('<?xml version="1.0"?>\n' '<!DOCTYPE html PUBLIC ' '"-//W3C//DTD XHTML 1.0 Strict//EN" ' '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n', output) def test_xml_lang(self): text = '<p xml:lang="en">English text</p>' output = XML(text).render(XHTMLSerializer, encoding=None) self.assertEqual('<p lang="en" xml:lang="en">English text</p>', output) def test_xml_lang_nodup(self): text = '<p xml:lang="en" lang="en">English text</p>' output = XML(text).render(XHTMLSerializer, encoding=None) self.assertEqual('<p xml:lang="en" lang="en">English text</p>', output) def test_textarea_whitespace(self): content = '\nHey there. \n\n I am indented.\n' stream = XML('<textarea name="foo">%s</textarea>' % content) output = stream.render(XHTMLSerializer, encoding=None) self.assertEqual('<textarea name="foo">%s</textarea>' % content, output) def test_pre_whitespace(self): content = '\nHey <em>there</em>. \n\n I am indented.\n' stream = XML('<pre>%s</pre>' % content) output = stream.render(XHTMLSerializer, encoding=None) self.assertEqual('<pre>%s</pre>' % content, output) def test_xml_space(self): text = '<foo xml:space="preserve"> Do not mess \n\n with me </foo>' output = XML(text).render(XHTMLSerializer, encoding=None) self.assertEqual('<foo> Do not mess \n\n with me </foo>', output) def test_empty_script(self): text = """<html xmlns="http://www.w3.org/1999/xhtml"> <script src="foo.js" /> </html>""" output = XML(text).render(XHTMLSerializer, encoding=None) self.assertEqual("""<html xmlns="http://www.w3.org/1999/xhtml"> <script src="foo.js"></script> </html>""", output) def test_script_escaping(self): text = """<script>/*<![CDATA[*/ if (1 < 2) { alert("Doh"); } /*]]>*/</script>""" output = XML(text).render(XHTMLSerializer, encoding=None) self.assertEqual(text, output) def test_script_escaping_with_namespace(self): text = """<script xmlns="http://www.w3.org/1999/xhtml">/*<![CDATA[*/ if (1 < 2) { alert("Doh"); } /*]]>*/</script>""" output = XML(text).render(XHTMLSerializer, encoding=None) self.assertEqual(text, output) def test_style_escaping(self): text = """<style>/*<![CDATA[*/ html > body { display: none; } /*]]>*/</style>""" output = XML(text).render(XHTMLSerializer, encoding=None) self.assertEqual(text, output) def test_style_escaping_with_namespace(self): text = """<style xmlns="http://www.w3.org/1999/xhtml">/*<![CDATA[*/ html > body { display: none; } /*]]>*/</style>""" output = XML(text).render(XHTMLSerializer, encoding=None) self.assertEqual(text, output) def test_embedded_svg(self): text = """<html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg"> <body> <button> <svg:svg width="600px" height="400px"> <svg:polygon id="triangle" points="50,50 50,300 300,300"></svg:polygon> </svg:svg> </button> </body> </html>""" output = XML(text).render(XHTMLSerializer, encoding=None) self.assertEqual(text, output) def test_xhtml_namespace_prefix(self): text = """<div xmlns="http://www.w3.org/1999/xhtml"> <strong>Hello</strong> </div>""" output = XML(text).render(XHTMLSerializer, encoding=None) self.assertEqual(text, output) def test_nested_default_namespaces(self): stream = Stream([ (Stream.START_NS, ('', 'http://example.org/'), (None, -1, -1)), (Stream.START, (QName('div'), Attrs()), (None, -1, -1)), (Stream.TEXT, '\n ', (None, -1, -1)), (Stream.START_NS, ('', 'http://example.org/'), (None, -1, -1)), (Stream.START, (QName('p'), Attrs()), (None, -1, -1)), (Stream.END, QName('p'), (None, -1, -1)), (Stream.END_NS, '', (None, -1, -1)), (Stream.TEXT, '\n ', (None, -1, -1)), (Stream.START_NS, ('', 'http://example.org/'), (None, -1, -1)), (Stream.START, (QName('p'), Attrs()), (None, -1, -1)), (Stream.END, QName('p'), (None, -1, -1)), (Stream.END_NS, '', (None, -1, -1)), (Stream.TEXT, '\n ', (None, -1, -1)), (Stream.END, QName('div'), (None, -1, -1)), (Stream.END_NS, '', (None, -1, -1)) ]) output = stream.render(XHTMLSerializer, encoding=None) self.assertEqual("""<div xmlns="http://example.org/"> <p></p> <p></p> </div>""", output) def test_nested_bound_namespaces(self): stream = Stream([ (Stream.START_NS, ('x', 'http://example.org/'), (None, -1, -1)), (Stream.START, (QName('div'), Attrs()), (None, -1, -1)), (Stream.TEXT, '\n ', (None, -1, -1)), (Stream.START_NS, ('x', 'http://example.org/'), (None, -1, -1)), (Stream.START, (QName('p'), Attrs()), (None, -1, -1)), (Stream.END, QName('p'), (None, -1, -1)), (Stream.END_NS, 'x', (None, -1, -1)), (Stream.TEXT, '\n ', (None, -1, -1)), (Stream.START_NS, ('x', 'http://example.org/'), (None, -1, -1)), (Stream.START, (QName('p'), Attrs()), (None, -1, -1)), (Stream.END, QName('p'), (None, -1, -1)), (Stream.END_NS, 'x', (None, -1, -1)), (Stream.TEXT, '\n ', (None, -1, -1)), (Stream.END, QName('div'), (None, -1, -1)), (Stream.END_NS, 'x', (None, -1, -1)) ]) output = stream.render(XHTMLSerializer, encoding=None) self.assertEqual("""<div xmlns:x="http://example.org/"> <p></p> <p></p> </div>""", output) def test_html5_doctype(self): stream = HTML('<html></html>') output = stream.render(XHTMLSerializer, doctype=DocType.HTML5, encoding=None) self.assertEqual('<!DOCTYPE html>\n<html></html>', output) def test_ignorable_space(self): text = '<foo> Mess \n\n\n with me! </foo>' output = XML(text).render(XMLSerializer, encoding=None) self.assertEqual('<foo> Mess\n with me! </foo>', output) def test_cache_markup(self): loc = (None, -1, -1) stream = Stream([(Stream.START, (QName('foo'), Attrs()), loc), (Stream.TEXT, '&hellip;', loc), (Stream.END, QName('foo'), loc), (Stream.START, (QName('bar'), Attrs()), loc), (Stream.TEXT, Markup('&hellip;'), loc), (Stream.END, QName('bar'), loc)]) output = stream.render(XMLSerializer, encoding=None, strip_whitespace=False) self.assertEqual('<foo>&amp;hellip;</foo><bar>&hellip;</bar>', output) class HTMLSerializerTestCase(unittest.TestCase): def test_xml_lang(self): text = '<p xml:lang="en">English text</p>' output = XML(text).render(HTMLSerializer, encoding=None) self.assertEqual('<p lang="en">English text</p>', output) def test_xml_lang_nodup(self): text = '<p lang="en" xml:lang="en">English text</p>' output = XML(text).render(HTMLSerializer, encoding=None) self.assertEqual('<p lang="en">English text</p>', output) def test_textarea_whitespace(self): content = '\nHey there. \n\n I am indented.\n' stream = XML('<textarea name="foo">%s</textarea>' % content) output = stream.render(HTMLSerializer, encoding=None) self.assertEqual('<textarea name="foo">%s</textarea>' % content, output) def test_pre_whitespace(self): content = '\nHey <em>there</em>. \n\n I am indented.\n' stream = XML('<pre>%s</pre>' % content) output = stream.render(HTMLSerializer, encoding=None) self.assertEqual('<pre>%s</pre>' % content, output) def test_xml_space(self): text = '<foo xml:space="preserve"> Do not mess \n\n with me </foo>' output = XML(text).render(HTMLSerializer, encoding=None) self.assertEqual('<foo> Do not mess \n\n with me </foo>', output) def test_empty_script(self): text = '<script src="foo.js" />' output = XML(text).render(HTMLSerializer, encoding=None) self.assertEqual('<script src="foo.js"></script>', output) def test_script_escaping(self): text = '<script>if (1 &lt; 2) { alert("Doh"); }</script>' output = XML(text).render(HTMLSerializer, encoding=None) self.assertEqual('<script>if (1 < 2) { alert("Doh"); }</script>', output) def test_script_escaping_with_namespace(self): text = """<script xmlns="http://www.w3.org/1999/xhtml"> if (1 &lt; 2) { alert("Doh"); } </script>""" output = XML(text).render(HTMLSerializer, encoding=None) self.assertEqual("""<script> if (1 < 2) { alert("Doh"); } </script>""", output) def test_style_escaping(self): text = '<style>html &gt; body { display: none; }</style>' output = XML(text).render(HTMLSerializer, encoding=None) self.assertEqual('<style>html > body { display: none; }</style>', output) def test_style_escaping_with_namespace(self): text = """<style xmlns="http://www.w3.org/1999/xhtml"> html &gt; body { display: none; } </style>""" output = XML(text).render(HTMLSerializer, encoding=None) self.assertEqual("""<style> html > body { display: none; } </style>""", output) def test_html5_doctype(self): stream = HTML('<html></html>') output = stream.render(HTMLSerializer, doctype=DocType.HTML5, encoding=None) self.assertEqual('<!DOCTYPE html>\n<html></html>', output) class EmptyTagFilterTestCase(unittest.TestCase): def test_empty(self): stream = XML('<elem></elem>') | EmptyTagFilter() self.assertEqual([EmptyTagFilter.EMPTY], [ev[0] for ev in stream]) def test_text_content(self): stream = XML('<elem>foo</elem>') | EmptyTagFilter() self.assertEqual([Stream.START, Stream.TEXT, Stream.END], [ev[0] for ev in stream]) def test_elem_content(self): stream = XML('<elem><sub /><sub /></elem>') | EmptyTagFilter() self.assertEqual([Stream.START, EmptyTagFilter.EMPTY, EmptyTagFilter.EMPTY, Stream.END], [ev[0] for ev in stream]) def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(XMLSerializerTestCase, 'test')) suite.addTest(unittest.makeSuite(XHTMLSerializerTestCase, 'test')) suite.addTest(unittest.makeSuite(HTMLSerializerTestCase, 'test')) suite.addTest(unittest.makeSuite(EmptyTagFilterTestCase, 'test')) suite.addTest(doctest.DocTestSuite(XMLSerializer.__module__)) return suite if __name__ == '__main__': unittest.main(defaultTest='suite')
#!/usr/bin/env python """ seedBank setup tool Copyright 2009-2011 Jasper Poppe <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. This tool downloads the needed netboot tarballs from the internet and extracts the needed files to the right place, it's also able to integrate the 'non free' firmware files into the Debian netboot initrd. """ __author__ = 'Jasper Poppe <[email protected]>' __copyright__ = 'Copyright (c) 2009-2011 Jasper Poppe' __credits__ = '' __license__ = 'Apache License, Version 2.0' __version__ = '1.0.0' __maintainer__ = 'Jasper Poppe' __email__ = '[email protected]' __status__ = 'release candidate' import fnmatch import optparse import os import seedlib import shutil import sys import tarfile sys.path.append('/etc/seedbank') from settings import setup_dists, setup_urls, sp_paths class SetupNetboot(object): """manage the netboot system files""" def __init__(self): self.temp = '/tmp/seedbank' def _untar_files(self, archive, files): """deletes seedbank temp directory, create directory and untar selected files from a gzipped tarball""" if not seedlib.rmtree(self.temp): return elif not seedlib.makedirs(self.temp): return try: os.chdir(self.temp) t = tarfile.open(archive, 'r:gz') t.extractall('', members=(t.getmember(m) for m in files)) t.close() except IOError: print ('error: failed to extract "%s" to "%s"' % (archive, self.temp)) else: print ('info: extracted files to "%s"' % (self.temp)) return True def _untar_all(self, archive, destination): """extract all files from a gzipped tarball""" try: t = tarfile.open(archive, 'r:gz') t.extractall(destination) t.close() except IOError: print ('error: failed to extract "%s" to "%s"' % (archive, destination)) else: print ('info: extracted files to "%s"' % (destination)) return True def _move(self, destination): """search and move all files from a given directory""" if os.path.isdir(destination): print ('info: "%s" already exists, files will be overwritten' % destination) elif not seedlib.makedirs(destination): return files = (os.path.join(root, filename) for root, _, files in os.walk(self.temp) if files for filename in files) for source in files: try: shutil.copy2(source, destination) except IOError: print ('error: unable to copy "%s" to "%s"' % (source, destination)) return print ('info: moved files to "%s"' % destination) seedlib.rmtree(self.temp) return True def _download(self, source, destination): """download a file via wget""" sourcefile = os.path.basename(source) target = os.path.join(destination, sourcefile) command = ['/usr/bin/wget', '--tries=3', '--timeout=15', source, '-P', destination] if os.path.isfile(target): print ('info: "%s" is already in "%s"' % (sourcefile, destination)) return True elif not seedlib.makedirs(destination): return print ('info: starting download for "%s"' % source) print (command) result = seedlib.run(command, True) if result.retcode: print ('error: failed to download "%s"' % source) return else: print ('info: downloaded "%s"' % source) return True def _extract(self, prefix, files, source, destination, target): """extact files to the seedbank temp directory and move those""" archive = os.path.join(destination, os.path.basename(source)) files = (os.path.join(prefix, filename) for filename in files) if not self._untar_files(archive, files): return elif not self._move(target): return else: return True def _extract_debs(self, directory): """extract files from all debian packages in a directory""" os.chdir(directory) for file in os.listdir(directory): if fnmatch.fnmatch(file, '*.deb'): command = ['/usr/bin/dpkg', '-x', file, 'temp'] result = seedlib.run(command) if result.retcode: return print ('info: extracted "%s"' % file) return True def _extract_initrd(self, initrd, temp_initrd): """extract an initrd image""" os.chdir(temp_initrd) result = seedlib.run_pipe('/bin/zcat %s | /bin/cpio -iv' % initrd) if not result.retcode: print ('info: extracted "%s" to "%s"' % (initrd, temp_initrd)) return True def _create_initrd(self, initrd, temp_initrd): """create an initrd image""" os.chdir(temp_initrd) result = seedlib.run_pipe('find . -print0 | cpio -0 -H newc -ov | ' 'gzip -c > %s' % initrd) if not result.retcode: print ('info: created "%s" from "%s"' % (initrd, temp_initrd)) return True def _merge_directories(self, source, destination): source = os.path.join(source, 'lib/firmware') destination = '/tmp/seedbank/initrd/lib/firmware' result = seedlib.move(source, destination) return result def _pxe_default(self): """manage the pxelinux.cfg default file""" source = os.path.join(sp_paths['templates'], 'pxe-default') directory = os.path.join(sp_paths['tftpboot'], 'pxelinux.cfg') destination = os.path.join(directory, 'default') if os.path.isfile(destination): print ('info: default pxelinux.cfg file "%s" found, will not ' 'overwrite' % destination) return True else: print ('info: no default pxelinux.cfg file "%s" found, will ' 'generate' % destination) if not os.path.isdir(directory): seedlib.makedirs(directory) try: shutil.copy2(source, destination) except IOError: print ('error: unable to copy "%s" to "%s"' % (source, destination)) else: return True def _disable_usb(self, temp_initrd): """remove usb storage support from initrd""" for root, _, _ in os.walk(temp_initrd): if 'kernel/drivers/usb/storage' in root: try: shutil.rmtree(root) except IOError: print ('error: unable to copy "%s" to "%s"' % root) else: print ('info: usb storage support is now disabled in ' 'initrd image (fixes "root partition not found" error)') return True sys.exit() def syslinux(self, destination): """download syslinux and extract needed files""" files = ('core/pxelinux.0', 'com32/menu/menu.c32', 'com32/menu/vesamenu.c32') prefix = os.path.basename(setup_urls['syslinux']).rstrip('.tar.gz') if not self._download(setup_urls['syslinux'], destination): return elif not self._extract(prefix, files, setup_urls['syslinux'], destination, sp_paths['tftpboot']): return elif not self._pxe_default(): return else: return True def debian_firmware(self, selection, release): """download and integrate the debian non free firmware""" destination = os.path.join(sp_paths['archives'], 'firmware-' + release) temp_initrd = os.path.join(self.temp, 'initrd') temp_firmware = os.path.join(self.temp, 'firmware') firmware = os.path.join(destination, 'firmware.tar.gz') initrd = os.path.join(sp_paths['tftpboot'], 'seedbank', selection, 'initrd.gz') url = setup_urls['firmware'].replace('${release}', release) if not self._download(url, destination): print ('error: failed to download "%s"' % url) return elif not self._untar_all(firmware, temp_firmware): print ('error: failed to extract "%s"' % firmware) return elif not self._extract_debs(temp_firmware): print ('error: failed to extract debs in "%s"' % temp_firmware) return elif not seedlib.makedirs(temp_initrd): print ('error: failed to create directory "%s"' % temp_initrd) return elif not self._extract_initrd(initrd, temp_initrd): print ('error: failed to extract "%s"' % temp_initrd) return elif not self._merge_directories(os.path.join(temp_firmware, 'temp'), temp_initrd): print ('error: failed to merge firmware files into initrd') return elif not self._disable_usb(temp_initrd): print ('error: failed to disable USB bug in "%s"' % temp_initrd) return elif not self._create_initrd(initrd, temp_initrd): print ('error: failed to build initrd "%s"' % initrd) return else: seedlib.rmtree(self.temp) return True def netboot(self, selection, dist, release, arch): """download a netboot tarball""" source = '%s/%s/dists/%s/main/installer-%s/current/images/netboot/' \ 'netboot.tar.gz' % (setup_urls[dist], dist, release, arch) destination = os.path.join(sp_paths['archives'], selection) prefix = os.path.join('./%s-installer' % dist, arch) files = ('initrd.gz', 'linux') target = os.path.join(sp_paths['tftpboot'], 'seedbank', selection) if not self._download(source, destination): return elif not self._extract(prefix, files, source, destination, target): return else: return True def list_releases(): """list alll avaliable releases""" for dist in setup_dists['releases']: print (dist) def main(): """the main application""" base_dir = os.path.dirname(os.path.abspath(__file__)) for path in sp_paths: if not sp_paths[path].startswith('/'): sp_paths[path] = os.path.join(base_dir, sp_paths[path]) parser = optparse.OptionParser(prog='seedbank_setup', version=__version__) parser.set_description('seedBank setup - (c) 2009-2011 Jasper Poppe ' '<[email protected]>') parser.set_usage('%prog [-h|-l|-i|-s] | [-r] <release>') parser.add_option('-l', '--list', dest='list', help='list available releases', action='store_true') parser.add_option('-s', '--syslinux', dest='syslinux', help='download and install ' 'syslinux pxe files', action='store_true') parser.add_option('-i', '--installed', dest='installed', help='list installed releases', action='store_true') parser.add_option('-r', '--remove', dest='remove', help='remove an installed release', action='store_true') (opts, args) = parser.parse_args() if not os.geteuid() == 0: parser.error('only root can run this script') install = SetupNetboot() if opts.list: list_releases() elif opts.installed: list = seedlib.FormatListDir('releases') list.listdir(os.path.join(sp_paths['tftpboot'], 'seedbank'), 'dirs') list.show() elif opts.syslinux: install.syslinux(os.path.join(sp_paths['archives'], 'syslinux')) elif not args: parser.print_help() sys.exit(0) elif len(args) != 1: parser.error('specify a release eg.: debian-lenny-amd64 (use -l to ' 'list available releases)') elif opts.remove: if not args[0]: parser.error('no distro specified') distro = os.path.join(sp_paths['tftpboot'], 'seedbank', args[0]) if not os.path.isdir(distro): parser.error('distro "%s" not found') seedlib.rmtree(distro) seedlib.rmtree(os.path.join(sp_paths['archives'], args[0])) release = args[0].split('-')[1] firmware = os.path.join(sp_paths['archives'], 'firmware-' + release) if os.path.isdir(firmware): seedlib.rmtree(firmware) else: selection = args[0] if not selection in setup_dists['releases']: parser.error('"%s" is an unknown release (use -l to list available ' 'releases)' % (selection)) else: try: dist, release, arch = selection.split('-') except ValueError: parser.error('"%s" is a known but invalid release (check ' 'settings.py)' % (selection)) if not install.netboot(selection, dist, release, arch): return if selection in setup_dists['firmwares']: install.debian_firmware(selection, release) if __name__ == '__main__': main()
import logging import json import redis from django.contrib.auth.models import User from django.conf import settings from django.conf.urls import url from django.shortcuts import get_object_or_404 from django.core.cache import cache from tastypie import fields from tastypie.authorization import DjangoAuthorization from tastypie.constants import ALL_WITH_RELATIONS, ALL from tastypie.resources import ModelResource from tastypie.http import HttpCreated, HttpApplicationError from tastypie.utils import dict_strip_unicode_keys, trailing_slash from readthedocs.builds.constants import LATEST from readthedocs.builds.models import Build, Version from readthedocs.core.utils import trigger_build from readthedocs.projects.models import Project, ImportedFile from readthedocs.restapi.views.footer_views import get_version_compare_data from .utils import SearchMixin, PostAuthentication log = logging.getLogger(__name__) class ProjectResource(ModelResource, SearchMixin): users = fields.ToManyField('readthedocs.api.base.UserResource', 'users') class Meta(object): include_absolute_url = True allowed_methods = ['get', 'post', 'put'] queryset = Project.objects.api() authentication = PostAuthentication() authorization = DjangoAuthorization() excludes = ['path', 'featured', 'programming_language'] filtering = { "users": ALL_WITH_RELATIONS, "slug": ALL_WITH_RELATIONS, } def get_object_list(self, request): self._meta.queryset = Project.objects.api(user=request.user) return super(ProjectResource, self).get_object_list(request) def dehydrate(self, bundle): bundle.data['subdomain'] = "http://%s/" % bundle.obj.subdomain bundle.data['downloads'] = bundle.obj.get_downloads() return bundle def post_list(self, request, **kwargs): """ Creates a new resource/object with the provided data. Calls ``obj_create`` with the provided data and returns a response with the new resource's location. If a new resource is created, return ``HttpCreated`` (201 Created). """ deserialized = self.deserialize( request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json') ) # Force this in an ugly way, at least should do "reverse" deserialized["users"] = ["/api/v1/user/%s/" % request.user.id] bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized), request=request) self.is_valid(bundle) updated_bundle = self.obj_create(bundle, request=request) return HttpCreated(location=self.get_resource_uri(updated_bundle)) def sync_versions(self, request, **kwargs): """ Sync the version data in the repo (on the build server) with what we have in the database. Returns the identifiers for the versions that have been deleted. """ project = get_object_or_404(Project, pk=kwargs['pk']) try: post_data = self.deserialize( request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json') ) data = json.loads(post_data) self.method_check(request, allowed=['post']) self.is_authenticated(request) self.throttle_check(request) self.log_throttled_access(request) self._sync_versions(project, data['tags']) self._sync_versions(project, data['branches']) deleted_versions = self._delete_versions(project, data) except Exception as e: return self.create_response( request, {'exception': e.message}, response_class=HttpApplicationError, ) return self.create_response(request, deleted_versions) def override_urls(self): return [ url(r"^(?P<resource_name>%s)/schema/$" % self._meta.resource_name, self.wrap_view('get_schema'), name="api_get_schema"), url(r"^(?P<resource_name>%s)/search%s$" % ( self._meta.resource_name, trailing_slash()), self.wrap_view('get_search'), name="api_get_search"), url(r"^(?P<resource_name>%s)/(?P<pk>\d+)/sync_versions%s$" % ( self._meta.resource_name, trailing_slash()), self.wrap_view('sync_versions'), name="api_sync_versions"), url((r"^(?P<resource_name>%s)/(?P<slug>[a-z-_]+)/$") % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"), ] class VersionResource(ModelResource): project = fields.ForeignKey(ProjectResource, 'project', full=True) class Meta(object): allowed_methods = ['get', 'put', 'post'] always_return_data = True queryset = Version.objects.api() authentication = PostAuthentication() authorization = DjangoAuthorization() filtering = { "project": ALL_WITH_RELATIONS, "slug": ALL_WITH_RELATIONS, "active": ALL, } # Find a better name for this before including it. # def dehydrate(self, bundle): # bundle.data['subdomain'] = "http://%s/en/%s/" % ( # bundle.obj.project.subdomain, bundle.obj.slug # ) # return bundle def get_object_list(self, request): self._meta.queryset = Version.objects.api(user=request.user) return super(VersionResource, self).get_object_list(request) def version_compare(self, request, project_slug, base=None, **kwargs): project = get_object_or_404(Project, slug=project_slug) if base and base != LATEST: try: base_version = project.versions.get(slug=base) except (Version.DoesNotExist, TypeError): base_version = None else: base_version = None ret_val = get_version_compare_data(project, base_version) return self.create_response(request, ret_val) def build_version(self, request, **kwargs): project = get_object_or_404(Project, slug=kwargs['project_slug']) version = kwargs.get('version_slug', LATEST) version_obj = project.versions.get(slug=version) trigger_build(project=project, version=version_obj) return self.create_response(request, {'building': True}) def override_urls(self): return [ url(r"^(?P<resource_name>%s)/schema/$" % self._meta.resource_name, self.wrap_view('get_schema'), name="api_get_schema"), url((r"^(?P<resource_name>%s)/(?P<project_slug>[a-z-_]+)/highest/" r"(?P<base>.+)/$") % self._meta.resource_name, self.wrap_view('version_compare'), name="version_compare"), url(r"^(?P<resource_name>%s)/(?P<project_slug>[a-z-_]+)/highest/$" % self._meta.resource_name, self.wrap_view('version_compare'), name="version_compare"), url(r"^(?P<resource_name>%s)/(?P<project__slug>[a-z-_]+[a-z0-9-_]+)/$" # noqa % self._meta.resource_name, self.wrap_view('dispatch_list'), name="api_version_list"), url((r"^(?P<resource_name>%s)/(?P<project_slug>[a-z-_]+)/(?P" r"<version_slug>[a-z0-9-_.]+)/build/$") % self._meta.resource_name, self.wrap_view('build_version'), name="api_version_build_slug"), ] class FileResource(ModelResource, SearchMixin): project = fields.ForeignKey(ProjectResource, 'project', full=True) class Meta(object): allowed_methods = ['get', 'post'] queryset = ImportedFile.objects.all() excludes = ['md5', 'slug'] include_absolute_url = True authentication = PostAuthentication() authorization = DjangoAuthorization() search_facets = ['project'] def override_urls(self): return [ url(r"^(?P<resource_name>%s)/schema/$" % self._meta.resource_name, self.wrap_view('get_schema'), name="api_get_schema"), url(r"^(?P<resource_name>%s)/search%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('get_search'), name="api_get_search"), url(r"^(?P<resource_name>%s)/anchor%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('get_anchor'), name="api_get_anchor"), ] def get_anchor(self, request, **kwargs): self.method_check(request, allowed=['get']) self.is_authenticated(request) self.throttle_check(request) query = request.GET.get('q', '') try: redis_client = cache.get_client(None) redis_data = redis_client.keys("*redirects:v4*%s*" % query) except (AttributeError, redis.exceptions.ConnectionError): redis_data = [] # -2 because http: urls = [''.join(data.split(':')[6:]) for data in redis_data if 'http://' in data] object_list = {'objects': urls} self.log_throttled_access(request) return self.create_response(request, object_list) class UserResource(ModelResource): class Meta(object): allowed_methods = ['get'] queryset = User.objects.all() fields = ['username', 'first_name', 'last_name', 'last_login', 'id'] filtering = { 'username': 'exact', } def override_urls(self): return [ url(r"^(?P<resource_name>%s)/schema/$" % self._meta.resource_name, self.wrap_view('get_schema'), name="api_get_schema"), url(r"^(?P<resource_name>%s)/(?P<username>[a-z-_]+)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"), ]
#!/usr/bin/env python # # Copyright 2009 Facebook # # 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 simple template system that compiles templates to Python code. Basic usage looks like:: t = template.Template("<html>{{ myvalue }}</html>") print t.generate(myvalue="XXX") `Loader` is a class that loads templates from a root directory and caches the compiled templates:: loader = template.Loader("/home/btaylor") print loader.load("test.html").generate(myvalue="XXX") We compile all templates to raw Python. Error-reporting is currently... uh, interesting. Syntax for the templates:: ### base.html <html> <head> <title>{% block title %}Default title{% end %}</title> </head> <body> <ul> {% for student in students %} {% block student %} <li>{{ escape(student.name) }}</li> {% end %} {% end %} </ul> </body> </html> ### bold.html {% extends "base.html" %} {% block title %}A bolder title{% end %} {% block student %} <li><span style="bold">{{ escape(student.name) }}</span></li> {% end %} Unlike most other template systems, we do not put any restrictions on the expressions you can include in your statements. ``if`` and ``for`` blocks get translated exactly into Python, so you can do complex expressions like:: {% for student in [p for p in people if p.student and p.age > 23] %} <li>{{ escape(student.name) }}</li> {% end %} Translating directly to Python means you can apply functions to expressions easily, like the ``escape()`` function in the examples above. You can pass functions in to your template just like any other variable (In a `.RequestHandler`, override `.RequestHandler.get_template_namespace`):: ### Python code def add(x, y): return x + y template.execute(add=add) ### The template {{ add(1, 2) }} We provide the functions `escape() <.xhtml_escape>`, `.url_escape()`, `.json_encode()`, and `.squeeze()` to all templates by default. Typical applications do not create `Template` or `Loader` instances by hand, but instead use the `~.RequestHandler.render` and `~.RequestHandler.render_string` methods of `tornado.web.RequestHandler`, which load templates automatically based on the ``template_path`` `.Application` setting. Variable names beginning with ``_tt_`` are reserved by the template system and should not be used by application code. Syntax Reference ---------------- Template expressions are surrounded by double curly braces: ``{{ ... }}``. The contents may be any python expression, which will be escaped according to the current autoescape setting and inserted into the output. Other template directives use ``{% %}``. These tags may be escaped as ``{{!`` and ``{%!`` if you need to include a literal ``{{`` or ``{%`` in the output. To comment out a section so that it is omitted from the output, surround it with ``{# ... #}``. ``{% apply *function* %}...{% end %}`` Applies a function to the output of all template code between ``apply`` and ``end``:: {% apply linkify %}{{name}} said: {{message}}{% end %} Note that as an implementation detail apply blocks are implemented as nested functions and thus may interact strangely with variables set via ``{% set %}``, or the use of ``{% break %}`` or ``{% continue %}`` within loops. ``{% autoescape *function* %}`` Sets the autoescape mode for the current file. This does not affect other files, even those referenced by ``{% include %}``. Note that autoescaping can also be configured globally, at the `.Application` or `Loader`.:: {% autoescape xhtml_escape %} {% autoescape None %} ``{% block *name* %}...{% end %}`` Indicates a named, replaceable block for use with ``{% extends %}``. Blocks in the parent template will be replaced with the contents of the same-named block in a child template.:: <!-- base.html --> <title>{% block title %}Default title{% end %}</title> <!-- mypage.html --> {% extends "base.html" %} {% block title %}My page title{% end %} ``{% comment ... %}`` A comment which will be removed from the template output. Note that there is no ``{% end %}`` tag; the comment goes from the word ``comment`` to the closing ``%}`` tag. ``{% extends *filename* %}`` Inherit from another template. Templates that use ``extends`` should contain one or more ``block`` tags to replace content from the parent template. Anything in the child template not contained in a ``block`` tag will be ignored. For an example, see the ``{% block %}`` tag. ``{% for *var* in *expr* %}...{% end %}`` Same as the python ``for`` statement. ``{% break %}`` and ``{% continue %}`` may be used inside the loop. ``{% from *x* import *y* %}`` Same as the python ``import`` statement. ``{% if *condition* %}...{% elif *condition* %}...{% else %}...{% end %}`` Conditional statement - outputs the first section whose condition is true. (The ``elif`` and ``else`` sections are optional) ``{% import *module* %}`` Same as the python ``import`` statement. ``{% include *filename* %}`` Includes another template file. The included file can see all the local variables as if it were copied directly to the point of the ``include`` directive (the ``{% autoescape %}`` directive is an exception). Alternately, ``{% module Template(filename, **kwargs) %}`` may be used to include another template with an isolated namespace. ``{% module *expr* %}`` Renders a `~tornado.web.UIModule`. The output of the ``UIModule`` is not escaped:: {% module Template("foo.html", arg=42) %} ``UIModules`` are a feature of the `tornado.web.RequestHandler` class (and specifically its ``render`` method) and will not work when the template system is used on its own in other contexts. ``{% raw *expr* %}`` Outputs the result of the given expression without autoescaping. ``{% set *x* = *y* %}`` Sets a local variable. ``{% try %}...{% except %}...{% else %}...{% finally %}...{% end %}`` Same as the python ``try`` statement. ``{% while *condition* %}... {% end %}`` Same as the python ``while`` statement. ``{% break %}`` and ``{% continue %}`` may be used inside the loop. """ from __future__ import absolute_import, division, print_function, with_statement import datetime import linecache import os.path import posixpath import re import threading from tornado import escape from tornado.log import app_log from tornado.util import ObjectDict, exec_in, unicode_type try: from cStringIO import StringIO # py2 except ImportError: from io import StringIO # py3 _DEFAULT_AUTOESCAPE = "xhtml_escape" _UNSET = object() class Template(object): """A compiled template. We compile into Python from the given template_string. You can generate the template from variables with generate(). """ # note that the constructor's signature is not extracted with # autodoc because _UNSET looks like garbage. When changing # this signature update website/sphinx/template.rst too. def __init__(self, template_string, name="<string>", loader=None, compress_whitespace=None, autoescape=_UNSET): self.name = name if compress_whitespace is None: compress_whitespace = name.endswith(".html") or \ name.endswith(".js") if autoescape is not _UNSET: self.autoescape = autoescape elif loader: self.autoescape = loader.autoescape else: self.autoescape = _DEFAULT_AUTOESCAPE self.namespace = loader.namespace if loader else {} reader = _TemplateReader(name, escape.native_str(template_string)) self.file = _File(self, _parse(reader, self)) self.code = self._generate_python(loader, compress_whitespace) self.loader = loader try: # Under python2.5, the fake filename used here must match # the module name used in __name__ below. # The dont_inherit flag prevents template.py's future imports # from being applied to the generated code. self.compiled = compile( escape.to_unicode(self.code), "%s.generated.py" % self.name.replace('.', '_'), "exec", dont_inherit=True) except Exception: formatted_code = _format_code(self.code).rstrip() app_log.error("%s code:\n%s", self.name, formatted_code) raise def generate(self, **kwargs): """Generate this template with the given arguments.""" namespace = { "escape": escape.xhtml_escape, "xhtml_escape": escape.xhtml_escape, "url_escape": escape.url_escape, "json_encode": escape.json_encode, "squeeze": escape.squeeze, "linkify": escape.linkify, "datetime": datetime, "_tt_utf8": escape.utf8, # for internal use "_tt_string_types": (unicode_type, bytes), # __name__ and __loader__ allow the traceback mechanism to find # the generated source code. "__name__": self.name.replace('.', '_'), "__loader__": ObjectDict(get_source=lambda name: self.code), } namespace.update(self.namespace) namespace.update(kwargs) exec_in(self.compiled, namespace) execute = namespace["_tt_execute"] # Clear the traceback module's cache of source data now that # we've generated a new template (mainly for this module's # unittests, where different tests reuse the same name). linecache.clearcache() return execute() def _generate_python(self, loader, compress_whitespace): buffer = StringIO() try: # named_blocks maps from names to _NamedBlock objects named_blocks = {} ancestors = self._get_ancestors(loader) ancestors.reverse() for ancestor in ancestors: ancestor.find_named_blocks(loader, named_blocks) writer = _CodeWriter(buffer, named_blocks, loader, ancestors[0].template, compress_whitespace) ancestors[0].generate(writer) return buffer.getvalue() finally: buffer.close() def _get_ancestors(self, loader): ancestors = [self.file] for chunk in self.file.body.chunks: if isinstance(chunk, _ExtendsBlock): if not loader: raise ParseError("{% extends %} block found, but no " "template loader") template = loader.load(chunk.name, self.name) ancestors.extend(template._get_ancestors(loader)) return ancestors class BaseLoader(object): """Base class for template loaders. You must use a template loader to use template constructs like ``{% extends %}`` and ``{% include %}``. The loader caches all templates after they are loaded the first time. """ def __init__(self, autoescape=_DEFAULT_AUTOESCAPE, namespace=None): """``autoescape`` must be either None or a string naming a function in the template namespace, such as "xhtml_escape". """ self.autoescape = autoescape self.namespace = namespace or {} self.templates = {} # self.lock protects self.templates. It's a reentrant lock # because templates may load other templates via `include` or # `extends`. Note that thanks to the GIL this code would be safe # even without the lock, but could lead to wasted work as multiple # threads tried to compile the same template simultaneously. self.lock = threading.RLock() def reset(self): """Resets the cache of compiled templates.""" with self.lock: self.templates = {} def resolve_path(self, name, parent_path=None): """Converts a possibly-relative path to absolute (used internally).""" raise NotImplementedError() def load(self, name, parent_path=None): """Loads a template.""" name = self.resolve_path(name, parent_path=parent_path) with self.lock: if name not in self.templates: self.templates[name] = self._create_template(name) return self.templates[name] def _create_template(self, name): raise NotImplementedError() class Loader(BaseLoader): """A template loader that loads from a single root directory. """ def __init__(self, root_directory, **kwargs): super(Loader, self).__init__(**kwargs) self.root = os.path.abspath(root_directory) def resolve_path(self, name, parent_path=None): if parent_path and not parent_path.startswith("<") and \ not parent_path.startswith("/") and \ not name.startswith("/"): current_path = os.path.join(self.root, parent_path) file_dir = os.path.dirname(os.path.abspath(current_path)) relative_path = os.path.abspath(os.path.join(file_dir, name)) if relative_path.startswith(self.root): name = relative_path[len(self.root) + 1:] return name def _create_template(self, name): path = os.path.join(self.root, name) with open(path, "rb") as f: template = Template(f.read(), name=name, loader=self) return template class DictLoader(BaseLoader): """A template loader that loads from a dictionary.""" def __init__(self, dict, **kwargs): super(DictLoader, self).__init__(**kwargs) self.dict = dict def resolve_path(self, name, parent_path=None): if parent_path and not parent_path.startswith("<") and \ not parent_path.startswith("/") and \ not name.startswith("/"): file_dir = posixpath.dirname(parent_path) name = posixpath.normpath(posixpath.join(file_dir, name)) return name def _create_template(self, name): return Template(self.dict[name], name=name, loader=self) class _Node(object): def each_child(self): return () def generate(self, writer): raise NotImplementedError() def find_named_blocks(self, loader, named_blocks): for child in self.each_child(): child.find_named_blocks(loader, named_blocks) class _File(_Node): def __init__(self, template, body): self.template = template self.body = body self.line = 0 def generate(self, writer): writer.write_line("def _tt_execute():", self.line) with writer.indent(): writer.write_line("_tt_buffer = []", self.line) writer.write_line("_tt_append = _tt_buffer.append", self.line) self.body.generate(writer) writer.write_line("return _tt_utf8('').join(_tt_buffer)", self.line) def each_child(self): return (self.body,) class _ChunkList(_Node): def __init__(self, chunks): self.chunks = chunks def generate(self, writer): for chunk in self.chunks: chunk.generate(writer) def each_child(self): return self.chunks class _NamedBlock(_Node): def __init__(self, name, body, template, line): self.name = name self.body = body self.template = template self.line = line def each_child(self): return (self.body,) def generate(self, writer): block = writer.named_blocks[self.name] with writer.include(block.template, self.line): block.body.generate(writer) def find_named_blocks(self, loader, named_blocks): named_blocks[self.name] = self _Node.find_named_blocks(self, loader, named_blocks) class _ExtendsBlock(_Node): def __init__(self, name): self.name = name class _IncludeBlock(_Node): def __init__(self, name, reader, line): self.name = name self.template_name = reader.name self.line = line def find_named_blocks(self, loader, named_blocks): included = loader.load(self.name, self.template_name) included.file.find_named_blocks(loader, named_blocks) def generate(self, writer): included = writer.loader.load(self.name, self.template_name) with writer.include(included, self.line): included.file.body.generate(writer) class _ApplyBlock(_Node): def __init__(self, method, line, body=None): self.method = method self.line = line self.body = body def each_child(self): return (self.body,) def generate(self, writer): method_name = "_tt_apply%d" % writer.apply_counter writer.apply_counter += 1 writer.write_line("def %s():" % method_name, self.line) with writer.indent(): writer.write_line("_tt_buffer = []", self.line) writer.write_line("_tt_append = _tt_buffer.append", self.line) self.body.generate(writer) writer.write_line("return _tt_utf8('').join(_tt_buffer)", self.line) writer.write_line("_tt_append(_tt_utf8(%s(%s())))" % ( self.method, method_name), self.line) class _ControlBlock(_Node): def __init__(self, statement, line, body=None): self.statement = statement self.line = line self.body = body def each_child(self): return (self.body,) def generate(self, writer): writer.write_line("%s:" % self.statement, self.line) with writer.indent(): self.body.generate(writer) # Just in case the body was empty writer.write_line("pass", self.line) class _IntermediateControlBlock(_Node): def __init__(self, statement, line): self.statement = statement self.line = line def generate(self, writer): # In case the previous block was empty writer.write_line("pass", self.line) writer.write_line("%s:" % self.statement, self.line, writer.indent_size() - 1) class _Statement(_Node): def __init__(self, statement, line): self.statement = statement self.line = line def generate(self, writer): writer.write_line(self.statement, self.line) class _Expression(_Node): def __init__(self, expression, line, raw=False): self.expression = expression self.line = line self.raw = raw def generate(self, writer): writer.write_line("_tt_tmp = %s" % self.expression, self.line) writer.write_line("if isinstance(_tt_tmp, _tt_string_types):" " _tt_tmp = _tt_utf8(_tt_tmp)", self.line) writer.write_line("else: _tt_tmp = _tt_utf8(str(_tt_tmp))", self.line) if not self.raw and writer.current_template.autoescape is not None: # In python3 functions like xhtml_escape return unicode, # so we have to convert to utf8 again. writer.write_line("_tt_tmp = _tt_utf8(%s(_tt_tmp))" % writer.current_template.autoescape, self.line) writer.write_line("_tt_append(_tt_tmp)", self.line) class _Module(_Expression): def __init__(self, expression, line): super(_Module, self).__init__("_tt_modules." + expression, line, raw=True) class _Text(_Node): def __init__(self, value, line): self.value = value self.line = line def generate(self, writer): value = self.value # Compress lots of white space to a single character. If the whitespace # breaks a line, have it continue to break a line, but just with a # single \n character if writer.compress_whitespace and "<pre>" not in value: value = re.sub(r"([\t ]+)", " ", value) value = re.sub(r"(\s*\n\s*)", "\n", value) if value: writer.write_line('_tt_append(%r)' % escape.utf8(value), self.line) class ParseError(Exception): """Raised for template syntax errors.""" pass class _CodeWriter(object): def __init__(self, file, named_blocks, loader, current_template, compress_whitespace): self.file = file self.named_blocks = named_blocks self.loader = loader self.current_template = current_template self.compress_whitespace = compress_whitespace self.apply_counter = 0 self.include_stack = [] self._indent = 0 def indent_size(self): return self._indent def indent(self): class Indenter(object): def __enter__(_): self._indent += 1 return self def __exit__(_, *args): assert self._indent > 0 self._indent -= 1 return Indenter() def include(self, template, line): self.include_stack.append((self.current_template, line)) self.current_template = template class IncludeTemplate(object): def __enter__(_): return self def __exit__(_, *args): self.current_template = self.include_stack.pop()[0] return IncludeTemplate() def write_line(self, line, line_number, indent=None): if indent is None: indent = self._indent line_comment = ' # %s:%d' % (self.current_template.name, line_number) if self.include_stack: ancestors = ["%s:%d" % (tmpl.name, lineno) for (tmpl, lineno) in self.include_stack] line_comment += ' (via %s)' % ', '.join(reversed(ancestors)) print(" " * indent + line + line_comment, file=self.file) class _TemplateReader(object): def __init__(self, name, text): self.name = name self.text = text self.line = 1 self.pos = 0 def find(self, needle, start=0, end=None): assert start >= 0, start pos = self.pos start += pos if end is None: index = self.text.find(needle, start) else: end += pos assert end >= start index = self.text.find(needle, start, end) if index != -1: index -= pos return index def consume(self, count=None): if count is None: count = len(self.text) - self.pos newpos = self.pos + count self.line += self.text.count("\n", self.pos, newpos) s = self.text[self.pos:newpos] self.pos = newpos return s def remaining(self): return len(self.text) - self.pos def __len__(self): return self.remaining() def __getitem__(self, key): if type(key) is slice: size = len(self) start, stop, step = key.indices(size) if start is None: start = self.pos else: start += self.pos if stop is not None: stop += self.pos return self.text[slice(start, stop, step)] elif key < 0: return self.text[key] else: return self.text[self.pos + key] def __str__(self): return self.text[self.pos:] def _format_code(code): lines = code.splitlines() format = "%%%dd %%s\n" % len(repr(len(lines) + 1)) return "".join([format % (i + 1, line) for (i, line) in enumerate(lines)]) def _parse(reader, template, in_block=None, in_loop=None): body = _ChunkList([]) while True: # Find next template directive curly = 0 while True: curly = reader.find("{", curly) if curly == -1 or curly + 1 == reader.remaining(): # EOF if in_block: raise ParseError("Missing {%% end %%} block for %s" % in_block) body.chunks.append(_Text(reader.consume(), reader.line)) return body # If the first curly brace is not the start of a special token, # start searching from the character after it if reader[curly + 1] not in ("{", "%", "#"): curly += 1 continue # When there are more than 2 curlies in a row, use the # innermost ones. This is useful when generating languages # like latex where curlies are also meaningful if (curly + 2 < reader.remaining() and reader[curly + 1] == '{' and reader[curly + 2] == '{'): curly += 1 continue break # Append any text before the special token if curly > 0: cons = reader.consume(curly) body.chunks.append(_Text(cons, reader.line)) start_brace = reader.consume(2) line = reader.line # Template directives may be escaped as "{{!" or "{%!". # In this case output the braces and consume the "!". # This is especially useful in conjunction with jquery templates, # which also use double braces. if reader.remaining() and reader[0] == "!": reader.consume(1) body.chunks.append(_Text(start_brace, line)) continue # Comment if start_brace == "{#": end = reader.find("#}") if end == -1: raise ParseError("Missing end expression #} on line %d" % line) contents = reader.consume(end).strip() reader.consume(2) continue # Expression if start_brace == "{{": end = reader.find("}}") if end == -1: raise ParseError("Missing end expression }} on line %d" % line) contents = reader.consume(end).strip() reader.consume(2) if not contents: raise ParseError("Empty expression on line %d" % line) body.chunks.append(_Expression(contents, line)) continue # Block assert start_brace == "{%", start_brace end = reader.find("%}") if end == -1: raise ParseError("Missing end block %%} on line %d" % line) contents = reader.consume(end).strip() reader.consume(2) if not contents: raise ParseError("Empty block tag ({%% %%}) on line %d" % line) operator, space, suffix = contents.partition(" ") suffix = suffix.strip() # Intermediate ("else", "elif", etc) blocks intermediate_blocks = { "else": set(["if", "for", "while", "try"]), "elif": set(["if"]), "except": set(["try"]), "finally": set(["try"]), } allowed_parents = intermediate_blocks.get(operator) if allowed_parents is not None: if not in_block: raise ParseError("%s outside %s block" % (operator, allowed_parents)) if in_block not in allowed_parents: raise ParseError("%s block cannot be attached to %s block" % (operator, in_block)) body.chunks.append(_IntermediateControlBlock(contents, line)) continue # End tag elif operator == "end": if not in_block: raise ParseError("Extra {%% end %%} block on line %d" % line) return body elif operator in ("extends", "include", "set", "import", "from", "comment", "autoescape", "raw", "module"): if operator == "comment": continue if operator == "extends": suffix = suffix.strip('"').strip("'") if not suffix: raise ParseError("extends missing file path on line %d" % line) block = _ExtendsBlock(suffix) elif operator in ("import", "from"): if not suffix: raise ParseError("import missing statement on line %d" % line) block = _Statement(contents, line) elif operator == "include": suffix = suffix.strip('"').strip("'") if not suffix: raise ParseError("include missing file path on line %d" % line) block = _IncludeBlock(suffix, reader, line) elif operator == "set": if not suffix: raise ParseError("set missing statement on line %d" % line) block = _Statement(suffix, line) elif operator == "autoescape": fn = suffix.strip() if fn == "None": fn = None template.autoescape = fn continue elif operator == "raw": block = _Expression(suffix, line, raw=True) elif operator == "module": block = _Module(suffix, line) body.chunks.append(block) continue elif operator in ("apply", "block", "try", "if", "for", "while"): # parse inner body recursively if operator in ("for", "while"): block_body = _parse(reader, template, operator, operator) elif operator == "apply": # apply creates a nested function so syntactically it's not # in the loop. block_body = _parse(reader, template, operator, None) else: block_body = _parse(reader, template, operator, in_loop) if operator == "apply": if not suffix: raise ParseError("apply missing method name on line %d" % line) block = _ApplyBlock(suffix, line, block_body) elif operator == "block": if not suffix: raise ParseError("block missing name on line %d" % line) block = _NamedBlock(suffix, block_body, template, line) else: block = _ControlBlock(contents, line, block_body) body.chunks.append(block) continue elif operator in ("break", "continue"): if not in_loop: raise ParseError("%s outside %s block" % (operator, set(["for", "while"]))) body.chunks.append(_Statement(contents, line)) continue else: raise ParseError("unknown operator: %r" % operator)
from __future__ import print_function from __future__ import unicode_literals from inspect import getdoc from operator import attrgetter import logging import re import signal import sys from docker.errors import APIError import dockerpty from .. import __version__ from .. import legacy from ..const import DEFAULT_TIMEOUT from ..project import NoSuchService, ConfigurationError from ..service import BuildError, NeedsBuildError from ..config import parse_environment from .command import Command from .docopt_command import NoSuchCommand from .errors import UserError from .formatter import Formatter from .log_printer import LogPrinter from .utils import yesno, get_version_info log = logging.getLogger(__name__) def main(): setup_logging() try: command = TopLevelCommand() command.sys_dispatch() except KeyboardInterrupt: log.error("\nAborting.") sys.exit(1) except (UserError, NoSuchService, ConfigurationError, legacy.LegacyContainersError) as e: log.error(e.msg) sys.exit(1) except NoSuchCommand as e: log.error("No such command: %s", e.command) log.error("") log.error("\n".join(parse_doc_section("commands:", getdoc(e.supercommand)))) sys.exit(1) except APIError as e: log.error(e.explanation) sys.exit(1) except BuildError as e: log.error("Service '%s' failed to build: %s" % (e.service.name, e.reason)) sys.exit(1) except NeedsBuildError as e: log.error("Service '%s' needs to be built, but --no-build was passed." % e.service.name) sys.exit(1) def setup_logging(): console_handler = logging.StreamHandler(sys.stderr) console_handler.setFormatter(logging.Formatter()) console_handler.setLevel(logging.INFO) root_logger = logging.getLogger() root_logger.addHandler(console_handler) root_logger.setLevel(logging.DEBUG) # Disable requests logging logging.getLogger("requests").propagate = False # stolen from docopt master def parse_doc_section(name, source): pattern = re.compile('^([^\n]*' + name + '[^\n]*\n?(?:[ \t].*?(?:\n|$))*)', re.IGNORECASE | re.MULTILINE) return [s.strip() for s in pattern.findall(source)] class TopLevelCommand(Command): """Define and run multi-container applications with Docker. Usage: docker-compose [options] [COMMAND] [ARGS...] docker-compose -h|--help Options: -f, --file FILE Specify an alternate compose file (default: docker-compose.yml) -p, --project-name NAME Specify an alternate project name (default: directory name) --tls=BOOL Use TLS; implied by --tlsverify --tlscacert=FILE Trust certs signed only by this ca (default: ~/.docker/ca.pem) --tlscert=FILE Path to tls certificate file (default: ~/.docker/cert.pem) --tlskey=FILE Path to tls key file (default: ~/.docker/key.pem) --tlsverify=BOOL Use TLS and verify the remote --verbose Show more output -v, --version Print version and exit Commands: build Build or rebuild services help Get help on a command kill Kill containers logs View output from containers port Print the public port for a port binding ps List containers pull Pulls service images restart Restart services rm Remove stopped containers run Run a one-off command scale Set number of containers for a service start Start services stop Stop services up Create and start containers migrate-to-labels Recreate containers to add labels version Show the Docker-Compose version information """ def docopt_options(self): options = super(TopLevelCommand, self).docopt_options() options['version'] = get_version_info('compose') return options def build(self, project, options): """ Build or rebuild services. Services are built once and then tagged as `project_service`, e.g. `composetest_db`. If you change a service's `Dockerfile` or the contents of its build directory, you can run `docker-compose build` to rebuild it. Usage: build [options] [SERVICE...] Options: --no-cache Do not use cache when building the image. """ no_cache = bool(options.get('--no-cache', False)) project.build(service_names=options['SERVICE'], no_cache=no_cache) def help(self, project, options): """ Get help on a command. Usage: help COMMAND """ command = options['COMMAND'] if not hasattr(self, command): raise NoSuchCommand(command, self) raise SystemExit(getdoc(getattr(self, command))) def kill(self, project, options): """ Force stop service containers. Usage: kill [options] [SERVICE...] Options: -s SIGNAL SIGNAL to send to the container. Default signal is SIGKILL. """ signal = options.get('-s', 'SIGKILL') project.kill(service_names=options['SERVICE'], signal=signal) def logs(self, project, options): """ View output from containers. Usage: logs [options] [SERVICE...] Options: --no-color Produce monochrome output. """ containers = project.containers(service_names=options['SERVICE'], stopped=True) monochrome = options['--no-color'] print("Attaching to", list_containers(containers)) LogPrinter(containers, attach_params={'logs': True}, monochrome=monochrome).run() def port(self, project, options): """ Print the public port for a port binding. Usage: port [options] SERVICE PRIVATE_PORT Options: --protocol=proto tcp or udp [default: tcp] --index=index index of the container if there are multiple instances of a service [default: 1] """ index = int(options.get('--index')) service = project.get_service(options['SERVICE']) try: container = service.get_container(number=index) except ValueError as e: raise UserError(str(e)) print(container.get_local_port( options['PRIVATE_PORT'], protocol=options.get('--protocol') or 'tcp') or '') def ps(self, project, options): """ List containers. Usage: ps [options] [SERVICE...] Options: -q Only display IDs """ containers = sorted( project.containers(service_names=options['SERVICE'], stopped=True) + project.containers(service_names=options['SERVICE'], one_off=True), key=attrgetter('name')) if options['-q']: for container in containers: print(container.id) else: headers = [ 'Name', 'Command', 'State', 'Ports', ] rows = [] for container in containers: command = container.human_readable_command if len(command) > 30: command = '%s ...' % command[:26] rows.append([ container.name, command, container.human_readable_state, container.human_readable_ports, ]) print(Formatter().table(headers, rows)) def pull(self, project, options): """ Pulls images for services. Usage: pull [options] [SERVICE...] Options: --allow-insecure-ssl Allow insecure connections to the docker registry """ insecure_registry = options['--allow-insecure-ssl'] project.pull( service_names=options['SERVICE'], insecure_registry=insecure_registry ) def rm(self, project, options): """ Remove stopped service containers. Usage: rm [options] [SERVICE...] Options: -f, --force Don't ask to confirm removal -v Remove volumes associated with containers """ all_containers = project.containers(service_names=options['SERVICE'], stopped=True) stopped_containers = [c for c in all_containers if not c.is_running] if len(stopped_containers) > 0: print("Going to remove", list_containers(stopped_containers)) if options.get('--force') \ or yesno("Are you sure? [yN] ", default=False): project.remove_stopped( service_names=options['SERVICE'], v=options.get('-v', False) ) else: print("No stopped containers") def run(self, project, options): """ Run a one-off command on a service. For example: $ docker-compose run web python manage.py shell By default, linked services will be started, unless they are already running. If you do not want to start linked services, use `docker-compose run --no-deps SERVICE COMMAND [ARGS...]`. Usage: run [options] [-e KEY=VAL...] SERVICE [COMMAND] [ARGS...] Options: --allow-insecure-ssl Allow insecure connections to the docker registry -d Detached mode: Run container in the background, print new container name. --entrypoint CMD Override the entrypoint of the image. -e KEY=VAL Set an environment variable (can be used multiple times) -u, --user="" Run as specified username or uid --no-deps Don't start linked services. --rm Remove container after run. Ignored in detached mode. --service-ports Run command with the service's ports enabled and mapped to the host. -T Disable pseudo-tty allocation. By default `docker-compose run` allocates a TTY. """ service = project.get_service(options['SERVICE']) insecure_registry = options['--allow-insecure-ssl'] if not options['--no-deps']: deps = service.get_linked_names() if len(deps) > 0: project.up( service_names=deps, start_deps=True, allow_recreate=False, insecure_registry=insecure_registry, ) tty = True if options['-d'] or options['-T'] or not sys.stdin.isatty(): tty = False if options['COMMAND']: command = [options['COMMAND']] + options['ARGS'] else: command = service.options.get('command') container_options = { 'command': command, 'tty': tty, 'stdin_open': not options['-d'], 'detach': options['-d'], } if options['-e']: container_options['environment'] = parse_environment(options['-e']) if options['--entrypoint']: container_options['entrypoint'] = options.get('--entrypoint') if options['--rm']: container_options['restart'] = None if options['--user']: container_options['user'] = options.get('--user') if not options['--service-ports']: container_options['ports'] = [] container = service.create_container( quiet=True, one_off=True, insecure_registry=insecure_registry, **container_options ) if options['-d']: service.start_container(container) print(container.name) else: dockerpty.start(project.client, container.id, interactive=not options['-T']) exit_code = container.wait() if options['--rm']: project.client.remove_container(container.id) sys.exit(exit_code) def scale(self, project, options): """ Set number of containers to run for a service. Numbers are specified in the form `service=num` as arguments. For example: $ docker-compose scale web=2 worker=3 Usage: scale [SERVICE=NUM...] """ for s in options['SERVICE=NUM']: if '=' not in s: raise UserError('Arguments to scale should be in the form service=num') service_name, num = s.split('=', 1) try: num = int(num) except ValueError: raise UserError('Number of containers for service "%s" is not a ' 'number' % service_name) project.get_service(service_name).scale(num) def start(self, project, options): """ Start existing containers. Usage: start [SERVICE...] """ project.start(service_names=options['SERVICE']) def stop(self, project, options): """ Stop running containers without removing them. They can be started again with `docker-compose start`. Usage: stop [options] [SERVICE...] Options: -t, --timeout TIMEOUT Specify a shutdown timeout in seconds. (default: 10) """ timeout = float(options.get('--timeout') or DEFAULT_TIMEOUT) project.stop(service_names=options['SERVICE'], timeout=timeout) def restart(self, project, options): """ Restart running containers. Usage: restart [options] [SERVICE...] Options: -t, --timeout TIMEOUT Specify a shutdown timeout in seconds. (default: 10) """ timeout = float(options.get('--timeout') or DEFAULT_TIMEOUT) project.restart(service_names=options['SERVICE'], timeout=timeout) def up(self, project, options): """ Build, (re)create, start and attach to containers for a service. By default, `docker-compose up` will aggregate the output of each container, and when it exits, all containers will be stopped. If you run `docker-compose up -d`, it'll start the containers in the background and leave them running. If there are existing containers for a service, `docker-compose up` will stop and recreate them (preserving mounted volumes with volumes-from), so that changes in `docker-compose.yml` are picked up. If you do not want existing containers to be recreated, `docker-compose up --no-recreate` will re-use existing containers. Usage: up [options] [SERVICE...] Options: --allow-insecure-ssl Allow insecure connections to the docker registry -d Detached mode: Run containers in the background, print new container names. --no-color Produce monochrome output. --no-deps Don't start linked services. --x-smart-recreate Only recreate containers whose configuration or image needs to be updated. (EXPERIMENTAL) --no-recreate If containers already exist, don't recreate them. --no-build Don't build an image, even if it's missing -t, --timeout TIMEOUT Use this timeout in seconds for container shutdown when attached or when containers are already running. (default: 10) """ insecure_registry = options['--allow-insecure-ssl'] detached = options['-d'] monochrome = options['--no-color'] start_deps = not options['--no-deps'] allow_recreate = not options['--no-recreate'] smart_recreate = options['--x-smart-recreate'] service_names = options['SERVICE'] timeout = float(options.get('--timeout') or DEFAULT_TIMEOUT) project.up( service_names=service_names, start_deps=start_deps, allow_recreate=allow_recreate, smart_recreate=smart_recreate, insecure_registry=insecure_registry, do_build=not options['--no-build'], timeout=timeout ) to_attach = [c for s in project.get_services(service_names) for c in s.containers()] if not detached: print("Attaching to", list_containers(to_attach)) log_printer = LogPrinter(to_attach, attach_params={"logs": True}, monochrome=monochrome) try: log_printer.run() finally: def handler(signal, frame): project.kill(service_names=service_names) sys.exit(0) signal.signal(signal.SIGINT, handler) print("Gracefully stopping... (press Ctrl+C again to force)") project.stop(service_names=service_names, timeout=timeout) def migrate_to_labels(self, project, _options): """ Recreate containers to add labels Usage: migrate-to-labels """ legacy.migrate_project_to_labels(project) def version(self, project, options): """ Show version informations Usage: version [--short] Options: --short Shows only Compose's version number. """ if options['--short']: print(__version__) else: print(get_version_info('full')) def list_containers(containers): return ", ".join(c.name for c in containers)
from django.core.exceptions import ObjectDoesNotExist from django.http import Http404 from hyperadmin.links import LinkPrototype from hyperadmin.resources.endpoints import ResourceEndpoint class ListLinkPrototype(LinkPrototype): """ Resource Item Listing """ def get_link_kwargs(self, **kwargs): link_kwargs = {'url': self.get_url(), 'prompt': 'List %s' % self.resource.get_prompt(), 'rel': 'list', } link_kwargs.update(kwargs) return super(ListLinkPrototype, self).get_link_kwargs(**link_kwargs) class CreateLinkPrototype(LinkPrototype): """ Create Resource Item """ def show_link(self, **kwargs): return self.resource.has_create_permission() def get_link_kwargs(self, **kwargs): kwargs = super(CreateLinkPrototype, self).get_link_kwargs(**kwargs) link_kwargs = {'url': self.get_url(), 'on_submit': self.handle_submission, 'method': 'POST', 'form_class': self.get_form_class(), 'prompt': 'Create %s' % self.resource.get_prompt(), 'rel': 'create', } link_kwargs.update(kwargs) return super(CreateLinkPrototype, self).get_link_kwargs(**link_kwargs) def on_success(self, item): return self.resource.on_create_success(item) or super(CreateLinkPrototype, self).on_success(item) class DetailLinkPrototype(LinkPrototype): """ Display Resource Item """ def show_link(self, **kwargs): #TODO view permsions on links return True def get_link_kwargs(self, **kwargs): kwargs = super(DetailLinkPrototype, self).get_link_kwargs(**kwargs) item = kwargs['item'] link_kwargs = {'url': self.get_url(item=item), 'prompt': item.get_prompt(), 'rel': 'detail', } link_kwargs.update(kwargs) return super(DetailLinkPrototype, self).get_link_kwargs(**link_kwargs) class UpdateLinkPrototype(LinkPrototype): """ Update Resource Item """ def show_link(self, **kwargs): return self.resource.has_update_permission(item=kwargs.get('item', None)) def get_link_kwargs(self, **kwargs): kwargs = super(UpdateLinkPrototype, self).get_link_kwargs(**kwargs) item = kwargs['item'] link_kwargs = {'url': self.get_url(item=item), 'on_submit': self.handle_submission, 'method': 'POST', 'form_class': item.get_form_class(), 'prompt': 'Update %s' % item.get_prompt(), 'rel': 'update', } link_kwargs.update(kwargs) return super(UpdateLinkPrototype, self).get_link_kwargs(**link_kwargs) def on_success(self, item): return self.resource.on_update_success(item) or super(UpdateLinkPrototype, self).on_success(item) class DeleteLinkPrototype(LinkPrototype): """ Delete Resource Item """ def show_link(self, **kwargs): return self.resource.has_delete_permission(item=kwargs.get('item', None)) def get_link_kwargs(self, **kwargs): kwargs = super(DeleteLinkPrototype, self).get_link_kwargs(**kwargs) item = kwargs['item'] link_kwargs = {'url': self.get_url(item=item), 'on_submit': self.handle_submission, 'method': 'POST', 'prompt': 'Delete %s' % item.get_prompt(), 'rel': 'delete', } link_kwargs.update(kwargs) return super(DeleteLinkPrototype, self).get_link_kwargs(**link_kwargs) def handle_submission(self, link, submit_kwargs): item = self.resource.state.item instance = item.instance instance.delete() return self.on_success(item) def on_success(self, item): return self.resource.on_delete_success(item) or super(DeleteLinkPrototype, self).on_success() class IndexMixin(object): index_name = 'primary' def get_index(self): if self.api_request: if 'index' not in self.state: self.state['index'] = self.resource.get_index(self.index_name) self.state['index'].populate_state() return self.state['index'] else: return self.resource.get_index(self.index_name) class ListEndpoint(IndexMixin, ResourceEndpoint): endpoint_class = 'change_list' name_suffix = 'list' url_suffix = r'^$' prototype_method_map = { 'GET': 'list', 'POST': 'rest-create', } list_prototype = ListLinkPrototype create_prototype = CreateLinkPrototype def post(self, api_request): mt = api_request.get_request_media_type() has_perm = self.resource.has_create_permission() and self.resource.has_update_permission() if (has_perm and hasattr(mt, 'get_datatap') and hasattr(api_request, 'get_django_request')): #use the request payload as an instream for our resource's datatap request = api_request.get_django_request() instream = mt.get_datatap(request) datatap = self.get_datatap(instream=instream) datatap.commit() return self.get_link() return self.handle_link_submission(api_request) def get_link_prototypes(self): return [ (self.list_prototype, {'name':'list'}), (self.create_prototype, {'name':'rest-create'}), ] def get_outbound_links(self): links = self.create_link_collection() links.add_link('create', link_factor='LO') return links def get_filter_links(self): links = self.create_link_collection() index = self.get_index() links.extend(index.get_filter_links(rel='filter')) return links def get_pagination_links(self): links = self.create_link_collection() index = self.get_index() links.extend(index.get_pagination_links(rel='paginate')) return links def get_instances(self): #CONSIDER view currently determines this index = self.get_index() page = index.get_page() return page.object_list def get_resource_item(self, instance, **kwargs): kwargs.setdefault('endpoint', self) return self.resource.get_list_resource_item(instance, **kwargs) def get_meta(self): resource_item = self.resource.get_list_resource_item(instance=None) form = resource_item.get_form() data = dict() data['display_fields'] = list() for field in form: data['display_fields'].append({'prompt': field.label}) return data def get_common_state_data(self): data = super(ListEndpoint, self).get_common_state_data() index = self.get_index() paginator = index.get_paginator() data['paginator'] = paginator data['index'] = index self.state.meta['object_count'] = paginator.count self.state.meta['number_of_pages'] = paginator.num_pages return data class CreateEndpoint(ResourceEndpoint): endpoint_class = 'change_form' endpoint_classes = ['add_form'] name_suffix = 'add' url_suffix = r'^add/$' prototype_method_map = { 'GET': 'create', 'POST': 'create', } create_prototype = CreateLinkPrototype def get_link_prototypes(self): return [ (self.create_prototype, {'name':'create'}), ] def get_breadcrumbs(self): breadcrumbs = super(CreateEndpoint, self).get_breadcrumbs() breadcrumbs.add_link('create', rel='breadcrumb', link_factor='LO') return breadcrumbs def get_resource_items(self): return [] class DetailMixin(IndexMixin): url_param_map = {} def get_object(self): if not hasattr(self, 'object'): try: self.object = self.get_index().get(**self.kwargs) except ObjectDoesNotExist as error: raise Http404(str(error)) return self.object def get_item(self): return self.get_resource_item(self.get_object()) def get_common_state_data(self): data = super(DetailMixin, self).get_common_state_data() data['item'] = self.get_item() return data def get_url_param_map(self): return dict(self.url_param_map) def get_url_params_from_item(self, item): param_map = self.get_url_param_map() return self.get_index().get_url_params_from_item(item, param_map) def get_url_suffix(self): param_map = self.get_url_param_map() url_suffix = '/'.join(self.get_index().get_url_params(param_map)) url_suffix = '^%s%s' % (url_suffix, self.url_suffix) return url_suffix def get_url(self, item): params = self.get_url_params_from_item(item) return super(DetailMixin, self).get_url(**params) class DetailEndpoint(DetailMixin, ResourceEndpoint): endpoint_class = 'change_form' name_suffix = 'detail' url_suffix = r'/$' prototype_method_map = { 'GET': 'update', #'GET': 'detail', 'POST': 'update', 'PUT': 'rest-update', 'DELETE': 'rest-delete', } update_prototype = UpdateLinkPrototype detail_prototype = DetailLinkPrototype delete_prototype = DeleteLinkPrototype def get_link_prototype_for_method(self, method): """ Returns a detail link based on whether a client can edit or view the objects """ if method == 'GET' and not self.resource.has_update_permission(): name = 'detail' else: name = self.prototype_method_map.get(method) return self.link_prototypes.get(name) def get_link_prototypes(self): return [ (self.update_prototype, {'name':'update'}), (self.detail_prototype, {'name':'detail'}), (self.update_prototype, {'name':'rest-update', 'link_kwargs':{'method':'PUT'}}), (self.delete_prototype, {'name':'rest-delete', 'link_kwargs':{'method':'DELETE'}}), ] def get_item_outbound_links(self, item): links = self.create_link_collection() links.add_link('delete', item=item, link_factor='LO') return links def get_breadcrumbs(self): breadcrumbs = super(DetailEndpoint, self).get_breadcrumbs() breadcrumbs.add_link('detail', item=self.common_state.item, rel='breadcrumb', link_factor='LO') return breadcrumbs class DeleteEndpoint(DetailMixin, ResourceEndpoint): endpoint_class = 'delete_confirmation' name_suffix = 'delete' url_suffix = r'/delete/$' prototype_method_map = { 'GET': 'delete', 'POST': 'delete', } delete_prototype = DeleteLinkPrototype def get_link_prototypes(self): return [ (self.delete_prototype, {'name':'delete'}), ] def get_breadcrumbs(self): breadcrumbs = super(DeleteEndpoint, self).get_breadcrumbs() breadcrumbs.add_link('update', item=self.common_state.item, rel='breadcrumb', link_factor='LO') breadcrumbs.add_link('delete', item=self.common_state.item, rel='breadcrumb', link_factor='LO') return breadcrumbs
#! /usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division import datetime import logging import numbers import os import sys from collections import defaultdict import Bio import configargparse import networkx from Bio import SeqIO from Bio.Alphabet import generic_dna from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord sys.path.append(os.path.dirname(os.path.abspath(__file__))) sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) import camsa from camsa.core.io import read_pairs, read_seqi_from_input_sources from camsa.core.data_structures import get_scaffold_edges, Sequence from camsa.utils.fasta.data_structures import IntraGapFilling, FlankingGapFilling def get_scaffold_name_from_vertex(v): return v[:-1] def reverse_or(orientaiton): return "+" if orientaiton == "-" else "-" def reverse_ap(f1, f1_or, f2, f2_or): return f2, reverse_or(orientaiton=f2_or), f1, reverse_or(orientaiton=f1_or) def get_assembly_edge(graph): for edge in graph.edges(): v1, v2 = edge if v1[:-1] != v2[:-1]: return edge return None, None def get_sequence_of_fragments_from_path(path, assembly_points_by_edges): path, path_type = path if len(path) < 2: logger.error("A sequence resembling an assembly points, that contains less than two scaffolds. Something went wrong.") exit(1) result = [] for frag_extremity_v1, frag_extremity_v2 in zip(path[1::2], path[2::2]): f1_or = "+" if frag_extremity_v1.endswith("h") else "-" f2_or = "-" if frag_extremity_v2.endswith("h") else "+" ap = assembly_points_by_edges[tuple(sorted([frag_extremity_v1, frag_extremity_v2]))] gap_size = ap.gap_size result.append((get_scaffold_name_from_vertex(v=frag_extremity_v1), f1_or, get_scaffold_name_from_vertex(v=frag_extremity_v2), f2_or, gap_size)) return result if __name__ == "__main__": full_description = camsa.full_description_template.format( names=camsa.CAMSA_AUTHORS, affiliations=camsa.AFFILIATIONS, dummy=" ", tool="Converting CAMSA formatted scaffolding results into FASTA files.", information="For more information refer to {docs}".format(docs=camsa.CAMSA_DOCS_URL), contact=camsa.CONTACT) full_description = "=" * 80 + "\n" + full_description + "=" * 80 + "\n" parser = configargparse.ArgParser(description=full_description, formatter_class=configargparse.RawTextHelpFormatter, default_config_files=[os.path.join(camsa.root_dir, "utils", "fasta", "camsa_points2fasta.ini"), os.path.join(camsa.root_dir, "logging.ini")]) parser.add_argument("-c", "--config", is_config_file=True, help="Config file overwriting some of the default settings as well as any flag starting with \"--\".") parser.add_argument("--version", action="version", version=camsa.VERSION) parser.add_argument("--fasta", type=configargparse.FileType("rt"), required=True, help="A stream of fasta formatted sequences of scaffolds, that participate in the scaffold assembly represented in form of CAMSA points") parser.add_argument("--points", type=configargparse.FileType("rt"), required=True, help="A stream of CAMSA formatted assembly points, representing a scaffold assembly, that is converted into FASTA formatted sequences") parser.add_argument("--allow-singletons", action="store_true", dest="allow_singletons", default=False, help="Whether to include scaffolds, that were not mentioned in the CAMSA formatted assembly points\nDEFAULT: False") parser.add_argument("--c-sep", type=str, help="A symbol, that is used to indicate gaps between scaffolds in the translated assemblies\nDEFAULT: N") parser.add_argument("--c-sep-length", type=int, help="A default length, that is used for the gap size between scaffolds in the translated assemblies. Used in case, when gap-size column has \"?\" value\nDEFAULT: 20") parser.add_argument("--scaffold-name-template", type=str, help="Python string template for the scaffold ids, in the produced FASTA formatted sequences. \"cnt\" attribute can be utilized\nDEFAULT: scaffold_{cnt}") parser.add_argument("-o", "--output", type=configargparse.FileType("wt"), default=sys.stdout, help="A stream to which the FASTA formatted converted sequence, representing the CAMSA formatted scaffold assembly, is output\nDEFAULT: stdout") parser.add_argument("--c-logging-level", dest="logging_level", default=logging.INFO, type=int, choices=[logging.NOTSET, logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL], help="Logging level for the converter.\nDEFAULT: {info}".format(info=logging.INFO)) parser.add_argument("--c-logging-formatter-entry", help="Format string for python logger.") args = parser.parse_args() start_time = datetime.datetime.now() logger = logging.getLogger("CAMSA.utils.camsa_points2fasta") ch = logging.StreamHandler() ch.setLevel(args.logging_level) logger.setLevel(args.logging_level) logger.addHandler(ch) logger.info(full_description) logger.info(parser.format_values()) ch.setFormatter(logging.Formatter(args.c_logging_formatter_entry)) logger.info("Starting the converting process") logger.info("Reading assembly points") assembly_points_by_sources = defaultdict(list) read_pairs(source=args.points, destination=assembly_points_by_sources) assembly_points_by_sources = [ap for ap_list in assembly_points_by_sources.values() for ap in ap_list] logger.info("A total of {ap_cnt} assembly points was obtained".format(ap_cnt=len(assembly_points_by_sources))) assembly_graph = networkx.Graph() scaffold_edges = get_scaffold_edges(assembly_points=assembly_points_by_sources) assembly_graph.add_edges_from(scaffold_edges) assembly_points_by_edges = {} for ap in assembly_points_by_sources: for (u, v, weight) in ap.get_edges(sort=True, weight=True): assembly_graph.add_edge(u, v) assembly_points_by_edges[tuple(sorted([u, v]))] = ap logger.debug("Checking that there are no in(semi)conflicting assembly points") for vertex in assembly_graph.nodes(): degree = assembly_graph.degree[vertex] if degree > 2: scaffold_name = get_scaffold_name_from_vertex(v=vertex) logger.error("Supplied assembly contained a conflict.") logger.error("Scaffold {scaffold_name} by its extremity {extremity_name} is reported as adjacent to more than one other scaffold's extremity" "".format(scaffold_name=scaffold_name, extremity_name=vertex)) exit(1) logger.debug("All clear, no (semi)conflicts, we can proceed") logger.info("Processing assemblies constructed from obtained assembly points") logger.debug("Extracting paths from assembly graph") paths = [] for cc in networkx.connected_components(G=assembly_graph): cc = assembly_graph.subgraph(cc).copy() origins = [v for v in cc.nodes() if cc.degree[v] == 1] if len(origins) == 2: path = networkx.shortest_path(G=cc, source=origins[0], target=origins[1]) logger.debug("Extracted a linear scaffold of length {scaffold_length}, staring with {s_v} and ending with {e_v}" "".format(scaffold_length=int(len(path) / 2), s_v=get_scaffold_name_from_vertex(v=origins[0]), e_v=get_scaffold_name_from_vertex(v=origins[1]))) paths.append((path, "l")) if len(origins) == 1: logger.error("Something is wrong with the assembly graph. We have a connected component with a single vertex of degree 1.") exit(1) if len(origins) == 0: logger.debug("Encountered a circular chromosome. Splitting it at random assembly point") assembly_edge = get_assembly_edge(graph=cc) if assembly_edge[0] is None or assembly_edge[1] is None: logger.error("Something is wrong with the assembly graph. Couldn't find a scaffold edge in a circular scaffold.") exit(1) cc.remove_edge(u=assembly_edge[0], v=assembly_edge[1]) path = networkx.shortest_path(G=cc, source=assembly_edge[0], target=assembly_edge[1]) paths.append((path, "c")) logger.debug("Total number of extracted paths is {path_cnt}".format(path_cnt=len(paths))) logger.debug("Out of which {linear_cnt} are linear, and {circular_cnt} are circular" "".format(linear_cnt=len([p for p in paths if p[1] == "l"]), circular_cnt=len([p for p in paths if p[1] == "c"]))) fragments = [get_sequence_of_fragments_from_path(path=p, assembly_points_by_edges=assembly_points_by_edges) for p in paths] logger.info("Total number of {scaffold_cnt} scaffolds was obtained from observed assembly points".format(scaffold_cnt=len(fragments))) logger.info("Reading fasta of contigs/scaffolds from {file}".format(file=args.fasta)) frag_fasta_by_id = {} s_cnt = 0 for record in SeqIO.parse(args.fasta, "fasta"): frag_fasta_by_id[record.id] = record s_cnt += 1 logger.debug("Processed {cnt} records from fasta file \"{file_name}\"".format(cnt=s_cnt, file_name=args.fasta)) logger.info("Total number of contig/scaffold sequences is {seq_cnt}".format(seq_cnt=len(frag_fasta_by_id))) for fragment_aps in fragments: for f1, f1_or, f2, f2_or, gap_size in fragment_aps: if f1 not in frag_fasta_by_id or f2 not in frag_fasta_by_id: logging.critical("Fragment {f1} or {f2} which is present assembly points is not present in supplied fasta file. Exiting.".format(f1=f1, f2=f2)) exit(1) used_fragments = set() logger.info("Outputting new scaffolds. Data is written to {file_name}".format(file_name=args.output)) for s_cnt, fragment_aps in enumerate(fragments): current = Seq("") for f_cnt, (f1, f1_or, f2, f2_or, gap_size) in enumerate(fragment_aps): used_fragments.add(f1) used_fragments.add(f2) if f1_or == "+": current += frag_fasta_by_id[f1].seq else: current += frag_fasta_by_id[f1].reverse_complement().seq sep_length = gap_size if isinstance(gap_size, numbers.Number) else args.c_sep_length if sep_length <= 0: sep_length = args.c_sep_length current += Seq(args.c_sep * int(sep_length)) if f_cnt == len(fragment_aps) - 1: if f2_or == "+": current += frag_fasta_by_id[f2].seq else: current += frag_fasta_by_id[f2].reverse_complement().seq name = args.scaffold_name_template.format(cnt=s_cnt) seq_record = SeqRecord(seq=current, id=name, description="") SeqIO.write(sequences=seq_record, handle=args.output, format="fasta") if args.allow_singletons: logger.info("Adding singleton fragments, that did not participate in any assembly points to the resulting assmebly") for f_id, fragment in frag_fasta_by_id.items(): if f_id not in used_fragments: SeqIO.write(sequences=fragment, handle=args.output, format="fasta") logger.info("All done!") logger.info("Elapsed time: {el_time}".format(el_time=str(datetime.datetime.now() - start_time)))
""" This module tests converting ordinal parameters to ordinal parameters. """ import unittest import sqlparams class OrdinalToOrdinal(unittest.TestCase): """ The :class:`OrdinalToOrdinal` class tests converting ordina parameters to ordinal parameters. From: format, qmark. To: format, qmark. """ def test_1_format_to_qmark(self): """ Test converting from:: ... WHERE name = %s to:: ... WHERE name = ? """ # Create instance. query = sqlparams.SQLParams('format', 'qmark') # Source SQL and params. src_sql = """ SELECT * FROM users WHERE id = %s OR name = %s; """ id, name = 2, "Balin" seq_params = [id, name] int_params = {0: id, 1: name} str_params = {'0': id, '1': name} # Desired SQL and params. dest_sql = """ SELECT * FROM users WHERE id = ? OR name = ?; """ dest_params = [id, name] for src_params, src in zip([seq_params, int_params, str_params], ['seq', 'int', 'str']): with self.subTest(src=src): # Format SQL with params. sql, params = query.format(src_sql, src_params) # Make sure desired SQL and parameters are created. self.assertEqual(sql, dest_sql) self.assertEqual(params, dest_params) def test_1_format_to_qmark_many(self): """ Test converting from:: ... WHERE name = %s to:: ... WHERE name = ? """ # Create instance. query = sqlparams.SQLParams('format', 'qmark') # Source SQL and params. src_sql = """ SELECT * FROM users WHERE id = %s OR name = %s; """ base_params = [ {'id': 4, 'name': "Fili"}, {'id': 9, 'name': "Gloin"}, ] seq_params = [[__row['id'], __row['name']] for __row in base_params] int_params = [{0: __row['id'], 1: __row['name']} for __row in base_params] str_params = [{'0': __row['id'], '1': __row['name']} for __row in base_params] # Desired SQL and params. dest_sql = """ SELECT * FROM users WHERE id = ? OR name = ?; """ dest_params = [[__row['id'], __row['name']] for __row in base_params] for src_params, src in zip([seq_params, int_params, str_params], ['seq', 'int', 'str']): with self.subTest(src=src): # Format SQL with params. sql, many_params = query.formatmany(src_sql, src_params) # Make sure desired SQL and parameters are created. self.assertEqual(sql, dest_sql) self.assertEqual(many_params, dest_params) def test_1_qmark_to_format(self): """ Test converting from:: ... WHERE name = ? to:: ... WHERE name = %s """ # Create instance. query = sqlparams.SQLParams('qmark', 'format') # Source SQL and params. src_sql = """ SELECT * FROM users WHERE name = ? OR id = ?; """ id, name = 13, "Thorin" seq_params = [name, id] int_params = {1: id, 0: name} str_params = {'1': id, '0': name} # Desired SQL and params. dest_sql = """ SELECT * FROM users WHERE name = %s OR id = %s; """ dest_params = [name, id] for src_params, src in zip([seq_params, int_params, str_params], ['seq', 'int', 'str']): with self.subTest(src=src): # Format SQL with params. sql, params = query.format(src_sql, src_params) # Make sure desired SQL and parameters are created. self.assertEqual(sql, dest_sql) self.assertEqual(params, dest_params) def test_1_qmark_to_format_many(self): """ Test converting from:: ... WHERE name = ? to:: ... WHERE name = %s """ # Create instance. query = sqlparams.SQLParams('qmark', 'format') # Source SQL and params. src_sql = """ SELECT * FROM users WHERE name = ? OR id = ?; """ base_params = [ {'id': 13, 'name': "Thorin"}, {'id': 8, 'name': "Oin"}, {'id': 12, 'name': "Bombur"}, ] seq_params = [[__row['name'], __row['id']] for __row in base_params] int_params = [{1: __row['id'], 0: __row['name']} for __row in base_params] str_params = [{'1': __row['id'], '0': __row['name']} for __row in base_params] # Desired SQL and params. dest_sql = """ SELECT * FROM users WHERE name = %s OR id = %s; """ dest_params = [[__row['name'], __row['id']] for __row in base_params] for src_params, src in zip([seq_params, int_params, str_params], ['seq', 'int', 'str']): with self.subTest(src=src): # Format SQL with params. sql, many_params = query.formatmany(src_sql, src_params) # Make sure desired SQL and parameters are created. self.assertEqual(sql, dest_sql) self.assertEqual(many_params, dest_params) def test_2_expand_tuples(self): """ Test expanding tuples. """ # Create instance. query = sqlparams.SQLParams('qmark', 'qmark', expand_tuples=True) # Source SQL and params. src_sql = """ SELECT * FROM users WHERE race = ? AND name IN ?; """ names, race = ("Kili", "Fili"), "Dwarf" seq_params = [race, names] int_params = {0: race, 1: names} str_params = {'0': race, '1': names} # Desired SQL and params. dest_sql = """ SELECT * FROM users WHERE race = ? AND name IN (?,?); """ dest_params = [race] + list(names) for src_params, src in zip([seq_params, int_params, str_params], ['seq', 'int', 'str']): with self.subTest(src=src): # Format SQL with params. sql, params = query.format(src_sql, src_params) # Make sure desired SQL and parameters are created. self.assertEqual(sql, dest_sql) self.assertEqual(params, dest_params) def test_2_expand_tuples_default(self): """ Test the default behavior for expanding tuples. An ordinal out-style should be enabled by default. """ # Create instance. query = sqlparams.SQLParams('qmark', 'qmark') # Source SQL and params. src_sql = """ SELECT * FROM users WHERE race = ? AND name IN ?; """ names, race = ("Kili", "Fili"), "Dwarf" seq_params = [race, names] int_params = {0: race, 1: names} str_params = {'0': race, '1': names} # Desired SQL and params. dest_sql = """ SELECT * FROM users WHERE race = ? AND name IN (?,?); """ dest_params = [race] + list(names) for src_params, src in zip([seq_params, int_params, str_params], ['seq', 'int', 'str']): with self.subTest(src=src): # Format SQL with params. sql, params = query.format(src_sql, src_params) # Make sure desired SQL and parameters are created. self.assertEqual(sql, dest_sql) self.assertEqual(params, dest_params) def test_2_expand_tuples_disabled(self): """ Test expanding tuples. """ # Create instance. query = sqlparams.SQLParams('qmark', 'qmark', expand_tuples=False) # Source SQL and params. src_sql = """ SELECT * FROM users WHERE race = ? AND name IN ?; """ names, race = ("Kili", "Fili"), "Dwarf" seq_params = [race, names] int_params = {0: race, 1: names} str_params = {'0': race, '1': names} # Desired SQL and params. dest_sql = """ SELECT * FROM users WHERE race = ? AND name IN ?; """ dest_params = [race, names[:]] for src_params, src in zip([seq_params, int_params, str_params], ['seq', 'int', 'str']): with self.subTest(src=src): # Format SQL with params. sql, params = query.format(src_sql, src_params) # Make sure desired SQL and parameters are created. self.assertEqual(sql, dest_sql) self.assertEqual(params, dest_params) def test_2_expand_tuples_many(self): """ Test expanding many tuples. """ # Create instance. query = sqlparams.SQLParams('qmark', 'qmark', expand_tuples=True) # Source SQL and params. src_sql = """ SELECT * FROM users WHERE race = ? AND name IN ?; """ base_params = [ {'names': ("Dwalin", "Balin"), 'race': "Dwarf"}, {'names': ("Kili", "Fili"), 'race': "Dwarf"}, {'names': ("Oin", "Gloin"), 'race': "Dwarf"}, ] seq_params = [[__row['race'], __row['names']] for __row in base_params] int_params = [{0: __row['race'], 1: __row['names']} for __row in base_params] str_params = [{'0': __row['race'], '1': __row['names']} for __row in base_params] # Desired SQL and params. dest_sql = """ SELECT * FROM users WHERE race = ? AND name IN (?,?); """ dest_params = [[__row['race']] + list(__row['names']) for __row in base_params] for src_params, src in zip([seq_params, int_params, str_params], ['seq', 'int', 'str']): with self.subTest(src=src): # Format SQL with params. sql, many_params = query.formatmany(src_sql, src_params) # Make sure desired SQL and parameters are created. self.assertEqual(sql, dest_sql) self.assertEqual(many_params, dest_params) def test_2_expand_tuples_many_fail_length(self): """ Test many tuples with differing lengths. """ # Create instance. query = sqlparams.SQLParams('qmark', 'qmark', expand_tuples=True) # Source SQL and params. src_sql = """ SELECT * FROM users WHERE race = ? AND name IN ?; """ base_params = [ {'names': ("Dori", "Ori", "Nori"), 'race': "Dwarf"}, {'names': ("Thorin",), 'race': "Dwarf"}, ] seq_params = [[__row['race'], __row['names']] for __row in base_params] int_params = [{0: __row['race'], 1: __row['names']} for __row in base_params] str_params = [{'0': __row['race'], '1': __row['names']} for __row in base_params] for src_params, src in zip([seq_params, int_params, str_params], ['seq', 'int', 'str']): with self.subTest(src=src): # Format SQL with params. with self.assertRaisesRegex(ValueError, "length was expected to be 3.$"): query.formatmany(src_sql, src_params) def test_2_expand_tuples_many_fail_type(self): """ Test many tuples with wrong types. """ # Create instance. query = sqlparams.SQLParams('qmark', 'qmark', expand_tuples=True) # Source SQL and params. src_sql = """ SELECT * FROM users WHERE race = ? AND name IN ?; """ base_params = [ {'names': ("Dori", "Ori", "Nori"), 'race': "Dwarf"}, {'names': "Thorin", 'race': "Dwarf"}, ] seq_params = [[__row['race'], __row['names']] for __row in base_params] int_params = [{0: __row['race'], 1: __row['names']} for __row in base_params] str_params = [{'0': __row['race'], '1': __row['names']} for __row in base_params] for src_params, src in zip([seq_params, int_params, str_params], ['seq', 'int', 'str']): with self.subTest(src=src): # Format SQL with params. with self.assertRaisesRegex(TypeError, "was expected to be a tuple.$"): query.formatmany(src_sql, src_params) def test_3_multiple(self): """ Test converting a ordinal parameter where it occurs multiple times. """ # Create instance. query = sqlparams.SQLParams('qmark', 'qmark') # Source SQL and params. src_sql = """ SELECT * FROM users WHERE id = ? OR name = ? OR altid = ? OR altname = ?; """ id, name = 3, "Kili" seq_params = [id, name, id, name] int_params = {0: id, 1: name, 2: id, 3: name} str_params = {'0': id, '1': name, '2': id, '3': name} # Desired SQL and params. dest_sql = """ SELECT * FROM users WHERE id = ? OR name = ? OR altid = ? OR altname = ?; """ dest_params = [id, name, id, name] for src_params, src in zip([seq_params, int_params, str_params], ['seq', 'int', 'str']): with self.subTest(src=src): # Format SQL with params. sql, params = query.format(src_sql, src_params) # Make sure desired SQL and parameters are created. self.assertEqual(sql, dest_sql) self.assertEqual(params, dest_params) def test_3_multiple_many(self): """ Test converting a numeric parameter where it occurs multiple times. """ # Create instance. query = sqlparams.SQLParams('qmark', 'qmark') # Source SQL and params. src_sql = """ SELECT * FROM users WHERE id = ? OR name = ? OR altid = ? OR altname = ?; """ base_params = [ {'id': 11, 'name': "Bofur"}, {'id': 12, 'name': "Bombur"}, {'id': 9, 'name': "Gloin"}, ] seq_params = [[__row['id'], __row['name'], __row['id'], __row['name']] for __row in base_params] int_params = [{0: __row['id'], 1: __row['name'], 2: __row['id'], 3: __row['name']} for __row in base_params] str_params = [{'0': __row['id'], '1': __row['name'], '2': __row['id'], '3': __row['name']} for __row in base_params] # Desired SQL and params. dest_sql = """ SELECT * FROM users WHERE id = ? OR name = ? OR altid = ? OR altname = ?; """ dest_params = [[__row['id'], __row['name'], __row['id'], __row['name']] for __row in base_params] for src_params, src in zip([seq_params, int_params, str_params], ['seq', 'int', 'str']): with self.subTest(src=src): # Format SQL with params. sql, many_params = query.formatmany(src_sql, src_params) # Make sure desired SQL and parameters are created. self.assertEqual(sql, dest_sql) self.assertEqual(many_params, dest_params) def test_4_format_escape_char(self): """ Test escaping a format parameter. """ # Create instance. query = sqlparams.SQLParams('format', 'qmark', escape_char=True) # Source SQL and params. src_sql = """ SELECT * FROM users WHERE name = %s AND tag IN ('%%Y2941', '%%2941', '%%s'); """ name = "Bilbo" src_params = [name] # Desired SQL and params. dest_sql = """ SELECT * FROM users WHERE name = ? AND tag IN ('%Y2941', '%2941', '%s'); """ dest_params = [name] # Format SQL with params. sql, params = query.format(src_sql, src_params) # Make sure desired SQL and parameters are created. self.assertEqual(sql, dest_sql) self.assertEqual(params, dest_params) def test_4_format_escape_char_disabled(self): """ Test disabling escaping of a format parameter. """ # Create instance. query = sqlparams.SQLParams('format', 'qmark', escape_char=False) # Source SQL and params. src_sql = """ SELECT * FROM users WHERE name = %s AND tag IN ('%Y2941', '%2941', '%%s'); """ name = "Bilbo" src_params = [name] # Desired SQL and params. dest_sql = """ SELECT * FROM users WHERE name = ? AND tag IN ('%Y2941', '%2941', '%%s'); """ dest_params = [name] # Format SQL with params. sql, params = query.format(src_sql, src_params) # Make sure desired SQL and parameters are created. self.assertEqual(sql, dest_sql) self.assertEqual(params, dest_params) def test_4_qmark_escape_char(self): """ Test escaping a qmark parameter. """ # Create instance. query = sqlparams.SQLParams('qmark', 'qmark', escape_char=True) # Source SQL and params. src_sql = """ SELECT * FROM users WHERE name = ? AND tag IN ('??Y2941', '??2941', '??'); """ name = "Bilbo" src_params = [name] # Desired SQL and params. dest_sql = """ SELECT * FROM users WHERE name = ? AND tag IN ('?Y2941', '?2941', '?'); """ dest_params = [name] # Format SQL with params. sql, params = query.format(src_sql, src_params) # Make sure desired SQL and parameters are created. self.assertEqual(sql, dest_sql) self.assertEqual(params, dest_params) def test_4_qmark_escape_char_disabled(self): """ Test disabling escaping of a qmark parameter. """ # Create instance. query = sqlparams.SQLParams('qmark', 'qmark', escape_char=False) # Source SQL and params. src_sql = """ SELECT * FROM users WHERE name = ? AND tag IN ('??Y2941', '??2941', '??'); """ name = "Bilbo" src_params = [name] # Desired SQL and params. dest_sql = """ SELECT * FROM users WHERE name = ? AND tag IN ('??Y2941', '??2941', '??'); """ dest_params = [name] # Format SQL with params. sql, params = query.format(src_sql, src_params) # Make sure desired SQL and parameters are created. self.assertEqual(sql, dest_sql) self.assertEqual(params, dest_params)
from operator import itemgetter import gym from gym import spaces from gym.utils import seeding from .game import Game from .card import Card from .player import PlayerAction, PlayerTools from .agents.random import AgentRandom class LoveLetterEnv(gym.Env): """Love Letter Game Environment The goal of hotter colder is to guess closer to a randomly selected number After each step the agent receives an observation of: 0 - No guess yet submitted (only after reset) 1 - Guess is lower than the target 2 - Guess is equal to the target 3 - Guess is higher than the target The rewards is calculated as: (min(action, self.number) + self.range) / (max(action, self.number) + self.range) Ideally an agent will be able to recognize the 'scent' of a higher reward and increase the rate in which is guesses in that direction until the reward reaches its maximum """ def __init__(self, agent_other, seed=451): self.action_space = spaces.Discrete(15) self.observation_space = spaces.Box(low=0, high=1, shape=(24,)) self._agent_other = AgentRandom( seed) if agent_other is None else agent_other self._seed(seed) self._reset() self._game = Game.new(4, self.np_random.random_integers(5000000)) def _seed(self, seed=None): self.np_random, seed = seeding.np_random(seed) return [seed] def _step(self, action): assert self.action_space.contains(action) player_action = self.action_from_index(action) if player_action is None: return self._game.state(), -1, False, {"round": self._game.round()} self._game, reward = LoveLetterEnv.advance_game( self._game, player_action, self._agent_other) done = self._game.over() or not PlayerTools.is_playing( self._game.players()[0]) return self._game.state(), reward, done, {"round": self._game.round()} def _reset(self): self._game = Game.new(4, self.np_random.random_integers(5000000)) return self._game.state() def force(self, game): """Force the environment to a certain game state""" self._game = game return game.state() @staticmethod def advance_game(game, action, agent): """Advance a game with an action * Play an action * Advance the game using the agent * Return the game pending for the same player turn _unless_ the game ends returns <game, reward> """ if not game.is_action_valid(action): return game, -1 player_idx = game.player_turn() game_current, _ = game.move(action) while game_current.active(): if not game_current.is_current_player_playing(): game_current = game_current.skip_eliminated_player() elif game_current.player_turn() != player_idx: game_current, _ = game_current.move(agent.move(game_current)) else: break # print("Round", game.round(), '->', game_current.round(), ':', 'OVER' if game_current.over() else 'RUNN') if game_current.over(): if game_current.winner() == player_idx: return game_current, 15 else: return game_current, -5 return game_current, 0 def action_by_score(self, scores, game=None): """ Returns best action based on assigned scores return (action, score, idx) """ if len(scores) != 15: raise Exception("Invalid scores length: {}".format(len(scores))) game = self._game if game is None else game assert game.active() actions_possible = self.actions_set(game) actions = [(action, score, idx) for action, score, idx in zip(actions_possible, scores, range(len(actions_possible))) if game.is_action_valid(action)] action = max(actions, key=itemgetter(2)) return action def action_from_index(self, action_index, game=None): """Returns valid action based on index and game""" game = self._game if game is None else game action_candidates = self.actions_set(game) actions = [(idx, action) for idx, action in enumerate(action_candidates) if game.is_action_valid(action) and idx == action_index] return actions[0][1] if len(actions) == 1 else None def actions_possible(self, game=None): """Returns valid (idx, actions) based on a current game""" game = self._game if game is None else game action_candidates = self.actions_set(game) actions = [(idx, action) for idx, action in enumerate(action_candidates) if game.is_action_valid(action)] return actions def actions_set(self, game=None): """Returns all actions for a game""" game = self._game if game is None else game player_self = game.player_turn() opponents = game.opponent_turn() actions_possible = [ PlayerAction(Card.guard, self.np_random.choice(opponents), Card.priest, Card.noCard), PlayerAction(Card.guard, self.np_random.choice(opponents), Card.baron, Card.noCard), PlayerAction(Card.guard, self.np_random.choice(opponents), Card.handmaid, Card.noCard), PlayerAction(Card.guard, self.np_random.choice(opponents), Card.prince, Card.noCard), PlayerAction(Card.guard, self.np_random.choice(opponents), Card.king, Card.noCard), PlayerAction(Card.guard, self.np_random.choice(opponents), Card.countess, Card.noCard), PlayerAction(Card.guard, self.np_random.choice(opponents), Card.princess, Card.noCard), PlayerAction(Card.priest, self.np_random.choice(opponents), Card.noCard, Card.noCard), PlayerAction(Card.baron, self.np_random.choice(opponents), Card.noCard, Card.noCard), PlayerAction(Card.king, self.np_random.choice(opponents), Card.noCard, Card.noCard), PlayerAction(Card.prince, self.np_random.choice(opponents), Card.noCard, Card.noCard), PlayerAction(Card.prince, player_self, Card.noCard, Card.noCard), PlayerAction(Card.handmaid, player_self, Card.noCard, Card.noCard), PlayerAction(Card.countess, player_self, Card.noCard, Card.noCard), PlayerAction(Card.princess, player_self, Card.noCard, Card.noCard) ] return actions_possible
from __future__ import absolute_import import itertools import json import os import zipfile from collections import defaultdict from six import StringIO from datetime import datetime from slyd.projecttemplates import templates import six REQUIRED_FILES = {'setup.py', 'scrapy.cfg', 'extractors.json', 'items.json', 'project.json', 'spiders/__init__.py', 'spiders/settings.py'} FILE_TEMPLATES = { 'extractors.json': '{}', 'items.json': '{}', 'project.json': templates['PROJECT'], 'scrapy.cfg': templates['SCRAPY'], 'setup.py': templates['SETUP'], 'spiders/__init__.py': '', 'spiders/settings.py': templates['SETTINGS'] } class ProjectArchiver(object): required_files = frozenset(REQUIRED_FILES) file_templates = FILE_TEMPLATES def __init__(self, project, version=None, required_files=None): if version is None: version = (0, 10) self.separator = os.path.sep self.version = version self.project = project if required_files is not None: self.required_files = required_files def archive(self, spiders=None): """ Zip the contents or a subset of the contents in this project together """ zbuff = StringIO() self._archive = zipfile.ZipFile(zbuff, "w", zipfile.ZIP_DEFLATED) self._add_files(spiders) self._archive.close() zbuff.seek(0) return zbuff def _add_files(self, spiders): """ Add all selected spiders and other files to the project """ now = datetime.now().timetuple()[:6] extractors = self.read_file('extractors.json', deserialize=True) or {} files, all_files, spider_templates = self._paths(spiders) seen_files = set() for file_path in files: if file_path in seen_files: continue if (file_path.startswith('spiders/') and file_path.endswith('.json')): path, contents, added = self._add_spider(file_path, spider_templates, extractors) seen_files.update(added) if contents is not None: self._add_file(file_path, contents, now) else: self._add_file(file_path, self.read_file(file_path), now) seen_files.add(file_path) missing = (set(self.file_templates) & self.required_files) - seen_files for file_path in missing: self._add_file(file_path, self.file_templates[file_path], now) def _add_file(self, filename, contents, tstamp): """ Add a file to the zip archive. """ if filename is None or contents in (None, 'null'): return fileinfo = zipfile.ZipInfo(filename, tstamp) fileinfo.external_attr = 0o666 << 16 self._archive.writestr(fileinfo, contents, zipfile.ZIP_DEFLATED) def _add_spider(self, file_path, templates, extractors): """ Add a spider or template to the archive. If the slybot version is less than 0.10 a spider and all of its templates are added as a single file. """ if self.version > (0, 9): data = self.read_file(file_path, deserialize=True) added = {file_path} else: file_path, data, added = self._add_legacy_spider(file_path, templates, extractors) if data is not None and data.get('deleted'): return self._deleted_spider(file_path, data, templates) spider_content = json.dumps(data, sort_keys=True, indent=4) return file_path, spider_content, added def _add_legacy_spider(self, file_path, templates, extractors): """ Build a legacy spider and add all templates to a single spider object """ spider = self._spider_name(file_path) file_path = self._spider_path(file_path) spider_data = self.read_file(file_path, deserialize=True) if spider_data is None or spider_data.get('deleted'): return file_path, spider_data, {file_path} names = set(spider_data.pop('template_names', [])) spider_templates = [tp for tp in templates.get(spider, []) if self._name(tp) in names] loaded_templates, added = self._spider_templates(spider_templates, extractors) added.add(file_path) spider_data['templates'] = loaded_templates return file_path, spider_data, added def _deleted_spider(self, file_path, spider_data, templates): """ Add information about a deleted spider. """ spider = self._spider_name(file_path) file_path = self._spider_path(file_path) added = {file_path} added.update(set(templates.get(spider, []))) if self.ignore_deleted: return None, None, added spider_content = json.dumps(spider_data, sort_keys=True, indent=4) return file_path, spider_content, added def _spider_templates(self, spider_templates, extractors): """ Find all templates for a legacy spider and combine them into a single list. """ templates, added = [], set() for template_path in spider_templates: added.add(template_path) existing = {} template = self.read_file(template_path, deserialize=True) if template is None: continue template_extractors = template.get('extractors', {}) for field, eids in template_extractors.items(): existing[field] = [eid for eid in eids if eid in extractors] template['extractors'] = existing templates.append(template) return templates, added def _spider_name(self, file_path): """ Get the name of a spider for a template or spider path. """ split = file_path.split(self.separator) if len(split) > 2: return split[1] return split[1][:-5] def _name(self, file_path): """ Get the name for the current json path """ split = file_path.split(self.separator) if split[-1].endswith('.json'): return split[-1][:-5] return '' def _spider_path(self, file_path): if len(file_path.split(self.separator)) > 2: return 'spiders/%s.json' % self._spider_name(file_path) return file_path def _paths(self, spiders): """ Build a collection of paths needed to build the archive. """ if spiders is None or spiders == '*': all_files = self.list_files() return all_files, all_files, self._template_paths(None, all_files) if isinstance(spiders, six.string_types): spiders = [spiders] spider_paths = set('spiders/%s.json' % spider for spider in spiders) all_files = self.list_files() template_paths = self._template_paths(spiders, all_files) if self.version > (0, 9): templates = set(itertools.chain(*template_paths.values())) spider_paths = spider_paths | templates files = list(set(spider_paths) | self.required_files) return files, all_files, template_paths def _template_paths(self, spiders, files): """ Map all template paths to the corresponding spider. """ spider_templates = defaultdict(list) for file_path in files: split_file_path = file_path.split('/') if len(split_file_path) > 2 and (spiders is None or split_file_path[1] in spiders): spider_templates[split_file_path[1]].append(file_path) return spider_templates def list_files(self): raise NotImplementedError def read_file(self, filename, deserialize=False): raise NotImplementedError class FileSystemProjectArchiver(ProjectArchiver): def __init__(self, project, version=None, required_files=None, base_dir='.'): self.base_dir = os.path.join(base_dir, '') super(FileSystemProjectArchiver, self).__init__(project, version, required_files) self.separator = os.path.sep def list_files(self): file_paths = [] project_dir = os.path.join(self.base_dir, self.project) for dir, _, files in os.walk(project_dir): dir = dir.split(project_dir)[1] dir = dir[1:] if dir.startswith(os.path.sep) else dir for filename in files: if filename.endswith(('.json', '.cfg', '.py')): file_paths.append(os.path.join(dir, filename)) return file_paths def read_file(self, filename, deserialize=False): file_path = os.path.join(self.base_dir, self.project, filename) if not os.path.isfile(file_path): return with open(file_path, 'r') as f: contents = f.read() if deserialize and contents: return json.loads(contents) return contents class GitProjectArchiver(ProjectArchiver): def __init__(self, project, version=None, ignore_deleted=True, required_files=None, branch='master'): self.branch = branch self.ignore_deleted = ignore_deleted super(GitProjectArchiver, self).__init__(project, version, required_files) self.separator = '/' def list_files(self): return list(set(self.project.list_files_for_branch('master')) | set(self.project.list_files_for_branch(self.branch))) def read_file(self, filename, deserialize=False): contents = self.project.file_contents_for_branch(filename, self.branch) if contents is None and self.branch != 'master': contents = self.project.file_contents_for_branch(filename, 'master') if contents is None and not self.ignore_deleted: contents = json.dumps({'deleted': True}) if deserialize and contents is not None: return json.loads(contents) return contents
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Generic, List, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class ContactProfilesOperations: """ContactProfilesOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure_orbital.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def get( self, resource_group_name: str, contact_profile_name: str, **kwargs: Any ) -> "_models.ContactProfile": """Gets the specified contact Profile in a specified resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param contact_profile_name: Contact Profile Name. :type contact_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ContactProfile, or the result of cls(response) :rtype: ~azure_orbital.models.ContactProfile :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ContactProfile"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-04-04-preview" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'contactProfileName': self._serialize.url("contact_profile_name", contact_profile_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ContactProfile', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}'} # type: ignore async def _create_or_update_initial( self, resource_group_name: str, contact_profile_name: str, location: str, tags: Optional[Dict[str, str]] = None, minimum_viable_contact_duration: Optional[str] = None, minimum_elevation_degrees: Optional[float] = None, auto_tracking_configuration: Optional[Union[str, "_models.AutoTrackingConfiguration"]] = None, links: Optional[List["_models.ContactProfileLink"]] = None, **kwargs: Any ) -> "_models.ContactProfile": cls = kwargs.pop('cls', None) # type: ClsType["_models.ContactProfile"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _parameters = _models.ContactProfile(tags=tags, location=location, minimum_viable_contact_duration=minimum_viable_contact_duration, minimum_elevation_degrees=minimum_elevation_degrees, auto_tracking_configuration=auto_tracking_configuration, links=links) api_version = "2021-04-04-preview" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_or_update_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'contactProfileName': self._serialize.url("contact_profile_name", contact_profile_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(_parameters, 'ContactProfile') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('ContactProfile', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('ContactProfile', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}'} # type: ignore async def begin_create_or_update( self, resource_group_name: str, contact_profile_name: str, location: str, tags: Optional[Dict[str, str]] = None, minimum_viable_contact_duration: Optional[str] = None, minimum_elevation_degrees: Optional[float] = None, auto_tracking_configuration: Optional[Union[str, "_models.AutoTrackingConfiguration"]] = None, links: Optional[List["_models.ContactProfileLink"]] = None, **kwargs: Any ) -> AsyncLROPoller["_models.ContactProfile"]: """Creates or updates a contact profile. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param contact_profile_name: Contact Profile Name. :type contact_profile_name: str :param location: The geo-location where the resource lives. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param minimum_viable_contact_duration: Minimum viable contact duration in ISO 8601 format. :type minimum_viable_contact_duration: str :param minimum_elevation_degrees: Minimum viable elevation for the contact in decimal degrees. :type minimum_elevation_degrees: float :param auto_tracking_configuration: Auto track configuration. :type auto_tracking_configuration: str or ~azure_orbital.models.AutoTrackingConfiguration :param links: Links of the Contact Profile. :type links: list[~azure_orbital.models.ContactProfileLink] :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either ContactProfile or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure_orbital.models.ContactProfile] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.ContactProfile"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, contact_profile_name=contact_profile_name, location=location, tags=tags, minimum_viable_contact_duration=minimum_viable_contact_duration, minimum_elevation_degrees=minimum_elevation_degrees, auto_tracking_configuration=auto_tracking_configuration, links=links, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('ContactProfile', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'contactProfileName': self._serialize.url("contact_profile_name", contact_profile_name, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}'} # type: ignore async def _delete_initial( self, resource_group_name: str, contact_profile_name: str, **kwargs: Any ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-04-04-preview" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'contactProfileName': self._serialize.url("contact_profile_name", contact_profile_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}'} # type: ignore async def begin_delete( self, resource_group_name: str, contact_profile_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes a specified contact profile resource. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param contact_profile_name: Contact Profile Name. :type contact_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, contact_profile_name=contact_profile_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'contactProfileName': self._serialize.url("contact_profile_name", contact_profile_name, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}'} # type: ignore async def update_tags( self, resource_group_name: str, contact_profile_name: str, parameters: "_models.TagsObject", **kwargs: Any ) -> "_models.ContactProfile": """Updates the specified contact profile tags. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param contact_profile_name: Contact Profile Name. :type contact_profile_name: str :param parameters: Parameters supplied to update contact profile tags. :type parameters: ~azure_orbital.models.TagsObject :keyword callable cls: A custom type or function that will be passed the direct response :return: ContactProfile, or the result of cls(response) :rtype: ~azure_orbital.models.ContactProfile :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ContactProfile"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-04-04-preview" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.update_tags.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'contactProfileName': self._serialize.url("contact_profile_name", contact_profile_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'TagsObject') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ContactProfile', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update_tags.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}'} # type: ignore def list_by_subscription( self, **kwargs: Any ) -> AsyncIterable["_models.ContactProfileListResult"]: """Returns list of contact profiles. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ContactProfileListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure_orbital.models.ContactProfileListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ContactProfileListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-04-04-preview" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_subscription.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('ContactProfileListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Orbital/contactProfiles'} # type: ignore def list( self, resource_group_name: str, **kwargs: Any ) -> AsyncIterable["_models.ContactProfileListResult"]: """Returns list of contact profiles. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ContactProfileListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure_orbital.models.ContactProfileListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ContactProfileListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-04-04-preview" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('ContactProfileListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles'} # type: ignore
from jsonrpc import ServiceProxy import sys import string # ===== BEGIN USER SETTINGS ===== # if you do not set these you will be prompted for a password for every command rpcuser = "" rpcpass = "" # ====== END USER SETTINGS ====== if rpcpass == "": access = ServiceProxy("http://127.0.0.1:9332") else: access = ServiceProxy("http://"+rpcuser+":"+rpcpass+"@127.0.0.1:9332") cmd = sys.argv[1].lower() if cmd == "backupwallet": try: path = raw_input("Enter destination path/filename: ") print access.backupwallet(path) except: print "\n---An error occurred---\n" elif cmd == "getaccount": try: addr = raw_input("Enter a compucoin address: ") print access.getaccount(addr) except: print "\n---An error occurred---\n" elif cmd == "getaccountaddress": try: acct = raw_input("Enter an account name: ") print access.getaccountaddress(acct) except: print "\n---An error occurred---\n" elif cmd == "getaddressesbyaccount": try: acct = raw_input("Enter an account name: ") print access.getaddressesbyaccount(acct) except: print "\n---An error occurred---\n" elif cmd == "getbalance": try: acct = raw_input("Enter an account (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getbalance(acct, mc) except: print access.getbalance() except: print "\n---An error occurred---\n" elif cmd == "getblockbycount": try: height = raw_input("Height: ") print access.getblockbycount(height) except: print "\n---An error occurred---\n" elif cmd == "getblockcount": try: print access.getblockcount() except: print "\n---An error occurred---\n" elif cmd == "getblocknumber": try: print access.getblocknumber() except: print "\n---An error occurred---\n" elif cmd == "getconnectioncount": try: print access.getconnectioncount() except: print "\n---An error occurred---\n" elif cmd == "getdifficulty": try: print access.getdifficulty() except: print "\n---An error occurred---\n" elif cmd == "getgenerate": try: print access.getgenerate() except: print "\n---An error occurred---\n" elif cmd == "gethashespersec": try: print access.gethashespersec() except: print "\n---An error occurred---\n" elif cmd == "getinfo": try: print access.getinfo() except: print "\n---An error occurred---\n" elif cmd == "getnewaddress": try: acct = raw_input("Enter an account name: ") try: print access.getnewaddress(acct) except: print access.getnewaddress() except: print "\n---An error occurred---\n" elif cmd == "getreceivedbyaccount": try: acct = raw_input("Enter an account (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getreceivedbyaccount(acct, mc) except: print access.getreceivedbyaccount() except: print "\n---An error occurred---\n" elif cmd == "getreceivedbyaddress": try: addr = raw_input("Enter a compucoin address (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getreceivedbyaddress(addr, mc) except: print access.getreceivedbyaddress() except: print "\n---An error occurred---\n" elif cmd == "gettransaction": try: txid = raw_input("Enter a transaction ID: ") print access.gettransaction(txid) except: print "\n---An error occurred---\n" elif cmd == "getwork": try: data = raw_input("Data (optional): ") try: print access.gettransaction(data) except: print access.gettransaction() except: print "\n---An error occurred---\n" elif cmd == "help": try: cmd = raw_input("Command (optional): ") try: print access.help(cmd) except: print access.help() except: print "\n---An error occurred---\n" elif cmd == "listaccounts": try: mc = raw_input("Minimum confirmations (optional): ") try: print access.listaccounts(mc) except: print access.listaccounts() except: print "\n---An error occurred---\n" elif cmd == "listreceivedbyaccount": try: mc = raw_input("Minimum confirmations (optional): ") incemp = raw_input("Include empty? (true/false, optional): ") try: print access.listreceivedbyaccount(mc, incemp) except: print access.listreceivedbyaccount() except: print "\n---An error occurred---\n" elif cmd == "listreceivedbyaddress": try: mc = raw_input("Minimum confirmations (optional): ") incemp = raw_input("Include empty? (true/false, optional): ") try: print access.listreceivedbyaddress(mc, incemp) except: print access.listreceivedbyaddress() except: print "\n---An error occurred---\n" elif cmd == "listtransactions": try: acct = raw_input("Account (optional): ") count = raw_input("Number of transactions (optional): ") frm = raw_input("Skip (optional):") try: print access.listtransactions(acct, count, frm) except: print access.listtransactions() except: print "\n---An error occurred---\n" elif cmd == "move": try: frm = raw_input("From: ") to = raw_input("To: ") amt = raw_input("Amount:") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") try: print access.move(frm, to, amt, mc, comment) except: print access.move(frm, to, amt) except: print "\n---An error occurred---\n" elif cmd == "sendfrom": try: frm = raw_input("From: ") to = raw_input("To: ") amt = raw_input("Amount:") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") commentto = raw_input("Comment-to (optional): ") try: print access.sendfrom(frm, to, amt, mc, comment, commentto) except: print access.sendfrom(frm, to, amt) except: print "\n---An error occurred---\n" elif cmd == "sendmany": try: frm = raw_input("From: ") to = raw_input("To (in format address1:amount1,address2:amount2,...): ") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") try: print access.sendmany(frm,to,mc,comment) except: print access.sendmany(frm,to) except: print "\n---An error occurred---\n" elif cmd == "sendtoaddress": try: to = raw_input("To (in format address1:amount1,address2:amount2,...): ") amt = raw_input("Amount:") comment = raw_input("Comment (optional): ") commentto = raw_input("Comment-to (optional): ") try: print access.sendtoaddress(to,amt,comment,commentto) except: print access.sendtoaddress(to,amt) except: print "\n---An error occurred---\n" elif cmd == "setaccount": try: addr = raw_input("Address: ") acct = raw_input("Account:") print access.setaccount(addr,acct) except: print "\n---An error occurred---\n" elif cmd == "setgenerate": try: gen= raw_input("Generate? (true/false): ") cpus = raw_input("Max processors/cores (-1 for unlimited, optional):") try: print access.setgenerate(gen, cpus) except: print access.setgenerate(gen) except: print "\n---An error occurred---\n" elif cmd == "settxfee": try: amt = raw_input("Amount:") print access.settxfee(amt) except: print "\n---An error occurred---\n" elif cmd == "stop": try: print access.stop() except: print "\n---An error occurred---\n" elif cmd == "validateaddress": try: addr = raw_input("Address: ") print access.validateaddress(addr) except: print "\n---An error occurred---\n" elif cmd == "walletpassphrase": try: pwd = raw_input("Enter wallet passphrase: ") access.walletpassphrase(pwd, 60) print "\n---Wallet unlocked---\n" except: print "\n---An error occurred---\n" elif cmd == "walletpassphrasechange": try: pwd = raw_input("Enter old wallet passphrase: ") pwd2 = raw_input("Enter new wallet passphrase: ") access.walletpassphrasechange(pwd, pwd2) print print "\n---Passphrase changed---\n" except: print print "\n---An error occurred---\n" print else: print "Command not found or not supported"
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2015 Thomas Voegtlin # # 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 os import ast import threading import json import copy import re import stat import pbkdf2, hmac, hashlib import base64 import zlib from .util import PrintError, profiler from .plugins import run_hook, plugin_loaders from .keystore import bip44_derivation from . import bitcoin # seed_version is now used for the version of the wallet file OLD_SEED_VERSION = 4 # electrum versions < 2.0 NEW_SEED_VERSION = 11 # electrum versions >= 2.0 FINAL_SEED_VERSION = 16 # electrum >= 2.7 will set this to prevent # old versions from overwriting new format def multisig_type(wallet_type): '''If wallet_type is mofn multi-sig, return [m, n], otherwise return None.''' match = re.match('(\d+)of(\d+)', wallet_type) if match: match = [int(x) for x in match.group(1, 2)] return match class WalletStorage(PrintError): def __init__(self, path, manual_upgrades=False): self.print_error("wallet path", path) self.manual_upgrades = manual_upgrades self.lock = threading.RLock() self.data = {} self.path = path self.modified = False self.pubkey = None if self.file_exists(): with open(self.path, "r") as f: self.raw = f.read() if not self.is_encrypted(): self.load_data(self.raw) else: # avoid new wallets getting 'upgraded' self.put('seed_version', FINAL_SEED_VERSION) def load_data(self, s): try: self.data = json.loads(s) except: try: d = ast.literal_eval(s) labels = d.get('labels', {}) except Exception as e: raise IOError("Cannot read wallet file '%s'" % self.path) self.data = {} for key, value in d.items(): try: json.dumps(key) json.dumps(value) except: self.print_error('Failed to convert label to json format', key) continue self.data[key] = value # check here if I need to load a plugin t = self.get('wallet_type') l = plugin_loaders.get(t) if l: l() if not self.manual_upgrades: if self.requires_split(): raise BaseException("This wallet has multiple accounts and must be split") if self.requires_upgrade(): self.upgrade() def is_encrypted(self): try: return base64.b64decode(self.raw)[0:4] == b'BIE1' except: return False def file_exists(self): return self.path and os.path.exists(self.path) def get_key(self, password): secret = pbkdf2.PBKDF2(password, '', iterations = 1024, macmodule = hmac, digestmodule = hashlib.sha512).read(64) ec_key = bitcoin.EC_KEY(secret) return ec_key def decrypt(self, password): ec_key = self.get_key(password) s = zlib.decompress(ec_key.decrypt_message(self.raw)) if self.raw else None self.pubkey = ec_key.get_public_key() s = s.decode('utf8') self.load_data(s) def set_password(self, password, encrypt): self.put('use_encryption', bool(password)) if encrypt and password: ec_key = self.get_key(password) self.pubkey = ec_key.get_public_key() else: self.pubkey = None def get(self, key, default=None): with self.lock: v = self.data.get(key) if v is None: v = default else: v = copy.deepcopy(v) return v def put(self, key, value): try: json.dumps(key) json.dumps(value) except: self.print_error("json error: cannot save", key) return with self.lock: if value is not None: if self.data.get(key) != value: self.modified = True self.data[key] = copy.deepcopy(value) elif key in self.data: self.modified = True self.data.pop(key) @profiler def write(self): with self.lock: self._write() def _write(self): if threading.currentThread().isDaemon(): self.print_error('warning: daemon thread cannot write wallet') return if not self.modified: return s = json.dumps(self.data, indent=4, sort_keys=True) if self.pubkey: s = bytes(s, 'utf8') c = zlib.compress(s) s = bitcoin.encrypt_message(c, self.pubkey) s = s.decode('utf8') temp_path = "%s.tmp.%s" % (self.path, os.getpid()) with open(temp_path, "w") as f: f.write(s) f.flush() os.fsync(f.fileno()) mode = os.stat(self.path).st_mode if os.path.exists(self.path) else stat.S_IREAD | stat.S_IWRITE # perform atomic write on POSIX systems try: os.rename(temp_path, self.path) except: os.remove(self.path) os.rename(temp_path, self.path) os.chmod(self.path, mode) self.print_error("saved", self.path) self.modified = False def requires_split(self): d = self.get('accounts', {}) return len(d) > 1 def split_accounts(storage): result = [] # backward compatibility with old wallets d = storage.get('accounts', {}) if len(d) < 2: return wallet_type = storage.get('wallet_type') if wallet_type == 'old': assert len(d) == 2 storage1 = WalletStorage(storage.path + '.deterministic') storage1.data = copy.deepcopy(storage.data) storage1.put('accounts', {'0': d['0']}) storage1.upgrade() storage1.write() storage2 = WalletStorage(storage.path + '.imported') storage2.data = copy.deepcopy(storage.data) storage2.put('accounts', {'/x': d['/x']}) storage2.put('seed', None) storage2.put('seed_version', None) storage2.put('master_public_key', None) storage2.put('wallet_type', 'imported') storage2.upgrade() storage2.write() result = [storage1.path, storage2.path] elif wallet_type in ['bip44', 'trezor', 'keepkey', 'ledger', 'btchip', 'digitalbitbox']: mpk = storage.get('master_public_keys') for k in d.keys(): i = int(k) x = d[k] if x.get("pending"): continue xpub = mpk["x/%d'"%i] new_path = storage.path + '.' + k storage2 = WalletStorage(new_path) storage2.data = copy.deepcopy(storage.data) # save account, derivation and xpub at index 0 storage2.put('accounts', {'0': x}) storage2.put('master_public_keys', {"x/0'": xpub}) storage2.put('derivation', bip44_derivation(k)) storage2.upgrade() storage2.write() result.append(new_path) else: raise BaseException("This wallet has multiple accounts and must be split") return result def requires_upgrade(self): return self.file_exists() and self.get_seed_version() < FINAL_SEED_VERSION def upgrade(self): self.print_error('upgrading wallet format') self.convert_imported() self.convert_wallet_type() self.convert_account() self.convert_version_13_b() self.convert_version_14() self.convert_version_15() self.convert_version_16() self.put('seed_version', FINAL_SEED_VERSION) # just to be sure self.write() def convert_wallet_type(self): wallet_type = self.get('wallet_type') if wallet_type == 'btchip': wallet_type = 'ledger' if self.get('keystore') or self.get('x1/') or wallet_type=='imported': return False assert not self.requires_split() seed_version = self.get_seed_version() seed = self.get('seed') xpubs = self.get('master_public_keys') xprvs = self.get('master_private_keys', {}) mpk = self.get('master_public_key') keypairs = self.get('keypairs') key_type = self.get('key_type') if seed_version == OLD_SEED_VERSION or wallet_type == 'old': d = { 'type': 'old', 'seed': seed, 'mpk': mpk, } self.put('wallet_type', 'standard') self.put('keystore', d) elif key_type == 'imported': d = { 'type': 'imported', 'keypairs': keypairs, } self.put('wallet_type', 'standard') self.put('keystore', d) elif wallet_type in ['xpub', 'standard']: xpub = xpubs["x/"] xprv = xprvs.get("x/") d = { 'type': 'bip32', 'xpub': xpub, 'xprv': xprv, 'seed': seed, } self.put('wallet_type', 'standard') self.put('keystore', d) elif wallet_type in ['bip44']: xpub = xpubs["x/0'"] xprv = xprvs.get("x/0'") d = { 'type': 'bip32', 'xpub': xpub, 'xprv': xprv, } self.put('wallet_type', 'standard') self.put('keystore', d) elif wallet_type in ['trezor', 'keepkey', 'ledger', 'digitalbitbox']: xpub = xpubs["x/0'"] derivation = self.get('derivation', bip44_derivation(0)) d = { 'type': 'hardware', 'hw_type': wallet_type, 'xpub': xpub, 'derivation': derivation, } self.put('wallet_type', 'standard') self.put('keystore', d) elif (wallet_type == '2fa') or multisig_type(wallet_type): for key in xpubs.keys(): d = { 'type': 'bip32', 'xpub': xpubs[key], 'xprv': xprvs.get(key), } if key == 'x1/' and seed: d['seed'] = seed self.put(key, d) else: raise # remove junk self.put('master_public_key', None) self.put('master_public_keys', None) self.put('master_private_keys', None) self.put('derivation', None) self.put('seed', None) self.put('keypairs', None) self.put('key_type', None) def convert_version_13_b(self): # version 13 is ambiguous, and has an earlier and a later structure if not self._is_upgrade_method_needed(0, 13): return if self.get('wallet_type') == 'standard': if self.get('keystore').get('type') == 'imported': pubkeys = self.get('keystore').get('keypairs').keys() d = {'change': []} receiving_addresses = [] for pubkey in pubkeys: addr = bitcoin.pubkey_to_address('p2pkh', pubkey) receiving_addresses.append(addr) d['receiving'] = receiving_addresses self.put('addresses', d) self.put('pubkeys', None) self.put('seed_version', 13) def convert_version_14(self): # convert imported wallets for 3.0 if not self._is_upgrade_method_needed(13, 13): return if self.get('wallet_type') =='imported': addresses = self.get('addresses') if type(addresses) is list: addresses = dict([(x, None) for x in addresses]) self.put('addresses', addresses) elif self.get('wallet_type') == 'standard': if self.get('keystore').get('type')=='imported': addresses = set(self.get('addresses').get('receiving')) pubkeys = self.get('keystore').get('keypairs').keys() assert len(addresses) == len(pubkeys) d = {} for pubkey in pubkeys: addr = bitcoin.pubkey_to_address('p2pkh', pubkey) assert addr in addresses d[addr] = { 'pubkey': pubkey, 'redeem_script': None, 'type': 'p2pkh' } self.put('addresses', d) self.put('pubkeys', None) self.put('wallet_type', 'imported') self.put('seed_version', 14) def convert_version_15(self): if not self._is_upgrade_method_needed(14, 14): return assert self.get('seed_type') != 'segwit' # unsupported derivation self.put('seed_version', 15) def convert_version_16(self): # fixes issue #3193 for Imported_Wallets with addresses # also, previous versions allowed importing any garbage as an address # which we now try to remove, see pr #3191 if not self._is_upgrade_method_needed(15, 15): return def remove_address(addr): def remove_from_dict(dict_name): d = self.get(dict_name, None) if d is not None: d.pop(addr, None) self.put(dict_name, d) def remove_from_list(list_name): lst = self.get(list_name, None) if lst is not None: s = set(lst) s -= {addr} self.put(list_name, list(s)) # note: we don't remove 'addr' from self.get('addresses') remove_from_dict('addr_history') remove_from_dict('labels') remove_from_dict('payment_requests') remove_from_list('frozen_addresses') if self.get('wallet_type') == 'imported': addresses = self.get('addresses') assert isinstance(addresses, dict) addresses_new = dict() for address, details in addresses.items(): if not bitcoin.is_address(address): remove_address(address) continue if details is None: addresses_new[address] = {} else: addresses_new[address] = details self.put('addresses', addresses_new) self.put('seed_version', 16) def convert_imported(self): # '/x' is the internal ID for imported accounts d = self.get('accounts', {}).get('/x', {}).get('imported',{}) if not d: return False addresses = [] keypairs = {} for addr, v in d.items(): pubkey, privkey = v if privkey: keypairs[pubkey] = privkey else: addresses.append(addr) if addresses and keypairs: raise BaseException('mixed addresses and privkeys') elif addresses: self.put('addresses', addresses) self.put('accounts', None) elif keypairs: self.put('wallet_type', 'standard') self.put('key_type', 'imported') self.put('keypairs', keypairs) self.put('accounts', None) else: raise BaseException('no addresses or privkeys') def convert_account(self): self.put('accounts', None) def _is_upgrade_method_needed(self, min_version, max_version): cur_version = self.get_seed_version() if cur_version > max_version: return False elif cur_version < min_version: raise BaseException( ('storage upgrade: unexpected version %d (should be %d-%d)' % (cur_version, min_version, max_version))) else: return True def get_action(self): action = run_hook('get_action', self) if action: return action if not self.file_exists(): return 'new' def get_seed_version(self): seed_version = self.get('seed_version') if not seed_version: seed_version = OLD_SEED_VERSION if len(self.get('master_public_key','')) == 128 else NEW_SEED_VERSION if seed_version > FINAL_SEED_VERSION: raise BaseException('This version of Electrum is too old to open this wallet') if seed_version==14 and self.get('seed_type') == 'segwit': self.raise_unsupported_version(seed_version) if seed_version >=12: return seed_version if seed_version not in [OLD_SEED_VERSION, NEW_SEED_VERSION]: self.raise_unsupported_version(seed_version) return seed_version def raise_unsupported_version(self, seed_version): msg = "Your wallet has an unsupported seed version." msg += '\n\nWallet file: %s' % os.path.abspath(self.path) if seed_version in [5, 7, 8, 9, 10, 14]: msg += "\n\nTo open this wallet, try 'git checkout seed_v%d'"%seed_version if seed_version == 6: # version 1.9.8 created v6 wallets when an incorrect seed was entered in the restore dialog msg += '\n\nThis file was created because of a bug in version 1.9.8.' if self.get('master_public_keys') is None and self.get('master_private_keys') is None and self.get('imported_keys') is None: # pbkdf2 was not included with the binaries, and wallet creation aborted. msg += "\nIt does not contain any keys, and can safely be removed." else: # creation was complete if electrum was run from source msg += "\nPlease open this file with Electrum 1.9.8, and move your coins to a new wallet." raise BaseException(msg)
from xml.dom import minidom import shared import templates import classes import c import collections import sys from event import * from actions import * StreamonLogo = """ _____ _ __ __ ____ _ _ / ____| | | \/ |/ __ \| \ | | | (___ | |_ _ __ ___ __ _| \ / | | | | \| | \___ \| __| '__/ _ \/ _` | |\/| | | | | . ` | ____) | |_| | | __/ (_| | | | | |__| | |\ | |_____/ \__|_| \___|\__,_|_| |_|\____/|_| \_| """ print StreamonLogo print "" queue_num = 6 core_num = 1 sourceType="pcap" if sourceType=="pcap": core_num=1; #queues numeber for core qpb = queue_num/core_num if queue_num%core_num!=0: print "Queues distribution is not uniform" quit() if len(sys.argv) < 2: print "No config file defined." quit() print "[LOADING]", sys.argv[1], "..." try: Config = minidom.parse(sys.argv[1]) except IOError as e: print e quit(-1) Source = Config.getElementsByTagName('source')[0] Publisher = Config.getElementsByTagName('publisher')[0] Blocks = Config.getElementsByTagName('additional_block') Metrics = Config.getElementsByTagName('metric') Tables = Config.getElementsByTagName('table') Features = Config.getElementsByTagName('feature') Events = Config.getElementsByTagName('event') TemplateVars = dict() MonstreamLibRows = [templates.BotstreamLibHeader] TableLibRows = [templates.TableLibHeader] EventNameArray = [] print"[THREAD_POOLS]" tpl=[templates.ThreadPoolTemplate.format(i) for i in range(core_num)]#thread Pool List print "[METRICS]" MetricConnections = [] LastMetricName = "" MetricHardware = [] #MetricObjects = [] MetricBlocks= [] for Index, Metric in enumerate(Metrics): m = classes.Metric(Metric) for i in range(core_num): if m.source == 'hw': entry = "<entry hid='{0}' sid='{1}' />".format(m.hw_id, m.metric_id) MetricHardware.append(entry) print entry else: shared.metrics[m.name] = Index MetricConnText = templates.ConnectionTemplate.format(LastMetricName+str(i),"out_Metric_Block", m.name+str(i),"in_Metric_Block") #m.name=m.name+i m.values['name'] = m.name+str(i) #m.name=m.name+"1" #print m.values['name'] MetricConnections.append( MetricConnText ) #MetricObjects.append(m) MetricBlocks.append(str(m)) LastMetricName = m.name #Connection LastMetricBlock to FeatureBlock for i in range(core_num): MetricConnText = templates.ConnectionTemplate.format(LastMetricName+str(i),"out_Metric_Block", "FeatureBlock"+str(i),"in_FeatureBlock") MetricConnections.append( MetricConnText ) print "[SOURCE]" sniffer_list=[] TemplatePcapVars=dict() if sourceType=="pfq": sniffer_list=[templates.SnifferTemplate.format(j,"".join([ """<queue number="{0}"/>""".format(i) for i in range(qpb*j,(j+1)*qpb) ])) for j in range(core_num)] else: Source.type = Source.getAttribute('type') Source.name = Source.getAttribute('name') TemplatePcapVars["source_type"] = Source.type TemplatePcapVars["source_name"] = Source.name TemplatePcapVars["hw_metrics"] = "\n".join(MetricHardware) sniffer_list=templates.SnifferPcapTemplate.format(**TemplatePcapVars) print "[PUBLISHER]" Exporters_list = [] TemplateExporter = dict() TemplateExporter["protocol"] = Publisher.getAttribute('protocol') TemplateExporter["ip"] = Publisher.getAttribute('ip') TemplateExporter["port"] = Publisher.getAttribute('port') Exporters_list = templates.ExporterBlockTemplate.format(**TemplateExporter) #print Publisher.protocol, Publisher.ip, Publisher.port #MetricBlocks = [ str(x) for x in MetricObjects ] PrimaryKeyBlock = [] for Index, Table in enumerate(Tables): t = shared.Table(Table) PrimaryKeyBlock.append( str(t) ) # MonstreamLibRows.append( t.get_code() ) DEPRECATED TableLibRows.append(shared.Table.declaration()) TableLibRows.append(shared.Table.reset_codes()) print "[FEATURES]" for Index, Feature in enumerate(Features): f = c.Feature(Feature, classes.Metric.Table) shared.features[f.name] = Index MonstreamLibRows.append( str(f) ) #MonstreamLibRows.append(templates.FeatureListTemplate.format(", \n\t".join( x[0] for x in c.Feature.Table), StateName)) print "[STATES]" StatesTable = collections.OrderedDict() # dict() States = Config.getElementsByTagName('statedef') state_count = 0 # StatesList = [] #code = '''std::map<std::string, std::string> m = {{0}};''' for State in States: StateName = State.getAttribute('id') StateExpire = State.getAttribute('timeout') StateOnTimeout = State.getAttribute('next_state') if not StateExpire: StateExpire = 0 else: StateExpire = int(StateExpire)*1000000 if not StateOnTimeout: StateOnTimeout = 0 if StateName not in StatesTable: StatesTable[ StateName ] = (state_count, StateExpire, StateOnTimeout) state_count += 1 #MonstreamLibRows.append(','.join(code)) StatesTable[""] = (-1, 0, 0) print "[ADDITIONAL BLOCKS]" AdditionalBlocks = [] AdditionalConnections = [] LastBlockName = "FilteringBlock0" LastGateName = "out_FilteringBlock" _attacks_num = 0 for Block in Blocks: name = Block.getAttribute('name') params = "" if name == "Forwarder": sock = Block.getElementsByTagName("socket") if not sock: raise Exception("FORWARDER: socket must be specified.") feeds = Block.getElementsByTagName("feed") export_to_int = { "always":"0", "on_suspect":"1" } sock_path = sock[0].getAttribute("path") if not sock_path: raise Exception("FORWARDER: need url in socket!") params += "<socket path=\"{0}\" />".format(sock_path) for f in feeds: atype = f.getAttribute("atype") if atype not in shared.attacks: shared.attacks[atype] = _attacks_num _attacks_num += 1 name_id = shared.tokens[ f.getAttribute("name") ] content_s = f.getAttribute("content") content_attr_name = None if content_s in shared.tokens: content_id = shared.tokens[ f.getAttribute("content") ] content_attr_name = "content" elif content_s in shared.metrics: content_id = shared.metrics[ f.getAttribute("content") ] content_attr_name = "metric" export = f.getAttribute("export") f.setAttribute("name", str(name_id) ) f.setAttribute(content_attr_name, str(content_id) ) f.setAttribute("export", export_to_int[export] ) params += f.toxml() + "\n" print params print shared.attacks print "[BLOCK] ", name AdditionalBlocks.append("""<block id="{0}" type="{0}"> <params> {1} </params> </block>""".format(name, params) ) AdditionalConnections.append("""<connection src_block="{0}" src_gate="{1}" dst_block="{2}" dst_gate="in_gate" />""".format(LastBlockName, LastGateName, name) ) LastBlockName = name LastGateName = "out_gate" print "[TIMEOUTS]" c.Timeout.fill_from_events(Events) print "[EVENTS]" for Ev in Events: # e = classes.Event(Ev) e = Event.parse(Ev) MonstreamLibRows.append( "/*### START EVENT_ID {0} ###*/\n".format( Event.last() ) ) # PrimaryKeyBlock.append( str(e) ) LocalStates = dict() # WARNING: THIS NEED MORE CHECKS!!! code = [] level = [] description =[] if Ev.getAttribute('type') == 'packet': MonstreamLibRows.append( '''std::string getStateCode(const struct pptags* Tags);\n''') MonstreamLibRows.append( '''std::string getStateLevel(const struct pptags* Tags);\n''') MonstreamLibRows.append( '''std::string getStateDescription(const struct pptags* Tags);\n''') mapp = "std::map<std::string,std::string> {0} = {{{1}}};\n" for s in Ev.getElementsByTagName('state'): LocalStates[ s.getAttribute('id') ] = s #LocalStates = set( [ s.getAttribute('id') for s in Ev.getElementsByTagName('state') ] ) StateArray = [] for StateName, StateData in StatesTable.iteritems(): StateId, Timeout, StateOnTimeout = StateData # Timeout = StateData[1] if StateOnTimeout not in StatesTable: StateOnTimeout = 0 else: StateOnTimeout = StatesTable[StateOnTimeout][0] if StateName in LocalStates: State = LocalStates[StateName] if Ev.getAttribute('type') == 'packet': StateCode = State.getAttribute('code') StateLevel = State.getAttribute('level') StateDescription = State.getAttribute('description') code.append("{{\"{0}\",\"{1}\"}}".format(StateId, StateCode)) level.append("{{\"{0}\",\"{1}\"}}".format(StateId, StateLevel)) description.append("{{\"{0}\",\"{1}\"}}".format(StateId, StateDescription)) classes.MetricOp.reset() c.Condition.reset() RandToken = shared.GetRandomString() #print "Timeout => ", Timeout MetricOps = State.getElementsByTagName("use-metric") for mop in MetricOps: m = classes.MetricOp(mop, classes.Metric.D) MonstreamLibRows.append( classes.MetricOp.getCode(RandToken) ) #print " -> condition" Conditions = State.getElementsByTagName("condition") for Index, Condition in enumerate(Conditions): cc = c.Condition(Condition, c.Feature.Table, StatesTable) MonstreamLibRows.extend( cc.actions() ) # generate names # add code to lib rows # CREATE Post Condition ActionList PostActionNodes = State.getElementsByTagName("post-condition-action") if PostActionNodes: PostActionNode = PostActionNodes[0] PostTimeout = PostActionNode.getElementsByTagName("timeout_set") PostActionStr = PostActionNode.getAttribute("do") for Arg, Index in c.Feature.Table: if Arg in PostActionStr: c.Condition.FeatureSet.append("{{ {0}, {1} }}".format(Index, Arg)) pnames, pbodies = Actions.parse(PostActionStr) tnames, tbodies = c.Timeout.parse_all(PostTimeout) ActionStr, pdecl = Actions.generate(pnames+tnames) MonstreamLibRows.extend(pbodies+tbodies) MonstreamLibRows.append(pdecl) else: ActionStr = "NULL" LocalFeatureList = c.Condition.get_features_code(RandToken) MonstreamLibRows.append( LocalFeatureList ) MonstreamLibRows.append( c.Condition.get_condition_code(RandToken) ) # construct state tuple # in format { feature, condition, action } if LocalFeatureList: FeatureListName = "FeatureList_{0}".format(RandToken) else: FeatureListName = "NULL" ConditionListName = "ConditionList_{0}".format(RandToken) StateArray.append( "{{ {0}, {1}, {2}, {3}, {4}, {5}, {6} }}".format( StateId, classes.MetricOp.LastGenerated, FeatureListName, ConditionListName, ActionStr, Timeout, StateOnTimeout) ) else: StateArray.append( "{{ {0}, NULL, NULL, NULL, NULL, 0, 0 }}".format(StateId) ) if Ev.getAttribute('type') == 'packet': MonstreamLibRows.append( mapp.format('code_map', ",".join(code))) MonstreamLibRows.append( mapp.format('level_map', ",".join(level))) MonstreamLibRows.append( mapp.format('description_map', ",".join(description))) getStateFunc = \ '''std::string {0}(const struct pptags* Tags) {{ return {1}[std::to_string(Tags->State->Id)]; }}\n''' MonstreamLibRows.append( getStateFunc.format('getStateCode', 'code_map')) MonstreamLibRows.append( getStateFunc.format('getStateLevel', 'level_map')) MonstreamLibRows.append( getStateFunc.format('getStateDescription', 'description_map')) MonstreamLibRows.append( templates.StatusTemplate.format(Event.last(), ", \n\t".join(StateArray)) ) EventNameArray.append(e) # EventName) MonstreamLibRows.append( "/*### END EVENT_ID {0} ###*/\n".format( Event.last() ) ) # REPLACE WITH event Events array of structs #MonstreamLibRows.append( "state_tuple* Events[] = {{ {0} }};\n".format(", ".join(EventNameArray) ) ) PrimaryKeyBlock.append( shared.tokens.getAdditionalXml() ) MonstreamLibRows.append( templates.EventTemplate.format( ",\n\t".join( EventNameArray ) ) ) MonstreamLibRows.append( templates.BotstreamLibFooter ) #MonstreamLibRows.append(templates.FeatureByStatus.format(", \n\t".join(FeaturesArray))) #MonstreamLibRows.append(templates.ConditionByStatus.format(", \n\t".join(ConditionArray))) # generate template vars print "[WRITE] app config" #Generation core_num EventFactory Blocks EventFactoryVars = dict() EventFactoryVars["timeout_classes"] = len(shared.timeouts) EventFactoryVars["Fields"] = shared.tokens.toxml() EventFactoryVars["KeyRules"] = "".join(PrimaryKeyBlock) EventFactory=[] for k in range (core_num): EventFactoryVars["id"]=k EventFactory.append(templates.EventFactoryTemplate.format(**EventFactoryVars)) #Generation core_num FeatureBlocks FeatureBlocks_list=[] for k in range (core_num): FeatureBlocks_list.append(templates.FeatureBlockTemplate.format(k)) #Generation core_num FilteringBlocks FilteringBlocks_list=[] for k in range (core_num): FilteringBlocks_list.append(templates.FilteringBlockTemplate.format(k)) #Generation core_num Exporters # Exporters_list=[] # for k in range (core_num): # Exporters_list.append(templates.ExporterBlockTemplate.format(k)) #Connection Sniffer-EventFactory ConnectionList=[] for i in range(core_num): ConnectionList.append(templates.ConnectionTemplate.format("Sniffer"+str(i),"sniffer_out","Factory"+str(i),"in_Factory")) #Connection EventFactory-firstMetric for i in range(core_num): ConnectionList.append(templates.ConnectionTemplate.format("Factory"+str(i),"out_Factory",Metrics[0].getAttribute('name')+str(i),"in_Metric_Block")) #Connection Feature-Filtering ConnectionListFeatureFiltering=[] for i in range(core_num): ConnectionListFeatureFiltering.append(templates.ConnectionTemplate.format("FeatureBlock"+str(i),"out_FeatureBlock","FilteringBlock"+str(i),"in_FilteringBlock")) #Connection Filtering-Exporter ConnectionListFilteringExporter=[] for i in range(core_num): ConnectionListFilteringExporter.append(templates.ConnectionTemplate.format("FilteringBlock"+str(i),"out_FilteringBlock","ExporterBlock"+str(i),"in_gate")) TemplateVars["appname"] = "botstream" #TemplateVars["source_type"] = Source.type #TemplateVars["source_name"] = Source.name #TemplateVars["hw_metrics"] = "\n".join(MetricHardware) TemplateVars["MetricBlock"] = "".join(MetricBlocks) TemplateVars["AdditionalBlocks"] = "\n".join(AdditionalBlocks) #TemplateVars["first_metric_name"] = Metrics[0].getAttribute('name') TemplateVars["MetricConnections"] = "".join(MetricConnections[i] for i in xrange(core_num, len(MetricConnections))) #TemplateVars["last_metric_name"] = LastMetricName TemplateVars["filter_string"] = "" #" or ".join(FilterList) TemplateVars["AdditionalConnections"] = "\n".join(AdditionalConnections) TemplateVars["ThreadPools"] = "".join(tpl) TemplateVars["Sniffers"] = "".join(sniffer_list) TemplateVars["Events"]="\n".join(EventFactory) TemplateVars["Feature"]="\n".join(FeatureBlocks_list) TemplateVars["Filtering"]="\n".join(FilteringBlocks_list) TemplateVars["Exporter"]=Exporters_list TemplateVars["SnifferFactoryConnections"]="".join(ConnectionList) TemplateVars["FeatureFilteringConnections"]="".join(ConnectionListFeatureFiltering) TemplateVars["FilteringExporterConnections"]="".join(ConnectionListFilteringExporter) # open Template and do XML output with open('template.xml') as TemplateFile: TemplateTxt = "".join(TemplateFile.readlines()) with open('{0}.xml'.format(TemplateVars["appname"]), 'w') as BlockmonFile: BlockmonFile.write(TemplateTxt.format(**TemplateVars)) print "[WRITE] table-include" with open('tables.hpp', 'w') as TableFile: TableFile.writelines(TableLibRows) print "[WRITE] monstream-lib" with open('featurelib.cpp', 'w') as LibFile: LibFile.writelines(MonstreamLibRows) #print "Done"
# Copyright 2011 Justin Santa Barbara # 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. """The volumes snapshots api.""" import webob from webob import exc from cinder.api import common from cinder.api.openstack import wsgi from cinder.api.v2 import volumes from cinder.api import xmlutil from cinder import exception from cinder.openstack.common import log as logging from cinder.openstack.common import strutils from cinder import utils from cinder import volume LOG = logging.getLogger(__name__) def _translate_snapshot_detail_view(context, snapshot): """Maps keys for snapshots details view.""" d = _translate_snapshot_summary_view(context, snapshot) # NOTE(gagupta): No additional data / lookups at the moment return d def _translate_snapshot_summary_view(context, snapshot): """Maps keys for snapshots summary view.""" d = {} d['id'] = snapshot['id'] d['created_at'] = snapshot['created_at'] d['name'] = snapshot['display_name'] d['description'] = snapshot['display_description'] d['volume_id'] = snapshot['volume_id'] d['status'] = snapshot['status'] d['size'] = snapshot['volume_size'] if snapshot.get('snapshot_metadata'): metadata = snapshot.get('snapshot_metadata') d['metadata'] = dict((item['key'], item['value']) for item in metadata) # avoid circular ref when vol is a Volume instance elif snapshot.get('metadata') and isinstance(snapshot.get('metadata'), dict): d['metadata'] = snapshot['metadata'] else: d['metadata'] = {} return d def make_snapshot(elem): elem.set('id') elem.set('status') elem.set('size') elem.set('created_at') elem.set('name') elem.set('description') elem.set('volume_id') elem.append(common.MetadataTemplate()) class SnapshotTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('snapshot', selector='snapshot') make_snapshot(root) return xmlutil.MasterTemplate(root, 1) class SnapshotsTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('snapshots') elem = xmlutil.SubTemplateElement(root, 'snapshot', selector='snapshots') make_snapshot(elem) return xmlutil.MasterTemplate(root, 1) class SnapshotsController(wsgi.Controller): """The Volumes API controller for the OpenStack API.""" def __init__(self, ext_mgr=None): self.volume_api = volume.API() self.ext_mgr = ext_mgr super(SnapshotsController, self).__init__() @wsgi.serializers(xml=SnapshotTemplate) def show(self, req, id): """Return data about the given snapshot.""" context = req.environ['cinder.context'] try: vol = self.volume_api.get_snapshot(context, id) except exception.NotFound: msg = _("Snapshot could not be found") raise exc.HTTPNotFound(explanation=msg) return {'snapshot': _translate_snapshot_detail_view(context, vol)} def delete(self, req, id): """Delete a snapshot.""" context = req.environ['cinder.context'] LOG.audit(_("Delete snapshot with id: %s"), id, context=context) try: snapshot = self.volume_api.get_snapshot(context, id) self.volume_api.delete_snapshot(context, snapshot) except exception.NotFound: msg = _("Snapshot could not be found") raise exc.HTTPNotFound(explanation=msg) return webob.Response(status_int=202) @wsgi.serializers(xml=SnapshotsTemplate) def index(self, req): """Returns a summary list of snapshots.""" return self._items(req, entity_maker=_translate_snapshot_summary_view) @wsgi.serializers(xml=SnapshotsTemplate) def detail(self, req): """Returns a detailed list of snapshots.""" return self._items(req, entity_maker=_translate_snapshot_detail_view) def _items(self, req, entity_maker): """Returns a list of snapshots, transformed through entity_maker.""" context = req.environ['cinder.context'] #pop out limit and offset , they are not search_opts search_opts = req.GET.copy() search_opts.pop('limit', None) search_opts.pop('offset', None) #filter out invalid option allowed_search_options = ('status', 'volume_id', 'name') volumes.remove_invalid_options(context, search_opts, allowed_search_options) # NOTE(thingee): v2 API allows name instead of display_name if 'name' in search_opts: search_opts['display_name'] = search_opts['name'] del search_opts['name'] snapshots = self.volume_api.get_all_snapshots(context, search_opts=search_opts) limited_list = common.limited(snapshots, req) res = [entity_maker(context, snapshot) for snapshot in limited_list] return {'snapshots': res} @wsgi.response(202) @wsgi.serializers(xml=SnapshotTemplate) def create(self, req, body): """Creates a new snapshot.""" kwargs = {} context = req.environ['cinder.context'] if not self.is_valid_body(body, 'snapshot'): msg = (_("Missing required element '%s' in request body") % 'snapshot') raise exc.HTTPBadRequest(explanation=msg) snapshot = body['snapshot'] kwargs['metadata'] = snapshot.get('metadata', None) volume_id = snapshot['volume_id'] volume = self.volume_api.get(context, volume_id) force = snapshot.get('force', False) msg = _("Create snapshot from volume %s") LOG.audit(msg, volume_id, context=context) # NOTE(thingee): v2 API allows name instead of display_name if 'name' in snapshot: snapshot['display_name'] = snapshot.get('name') del snapshot['name'] if not utils.is_valid_boolstr(force): msg = _("Invalid value '%s' for force. ") % force raise exception.InvalidParameterValue(err=msg) if strutils.bool_from_string(force): new_snapshot = self.volume_api.create_snapshot_force( context, volume, snapshot.get('display_name'), snapshot.get('description'), **kwargs) else: new_snapshot = self.volume_api.create_snapshot( context, volume, snapshot.get('display_name'), snapshot.get('description'), **kwargs) retval = _translate_snapshot_detail_view(context, new_snapshot) return {'snapshot': retval} @wsgi.serializers(xml=SnapshotTemplate) def update(self, req, id, body): """Update a snapshot.""" context = req.environ['cinder.context'] if not body: msg = _("Missing request body") raise exc.HTTPBadRequest(explanation=msg) if 'snapshot' not in body: msg = (_("Missing required element '%s' in request body") % 'snapshot') raise exc.HTTPBadRequest(explanation=msg) snapshot = body['snapshot'] update_dict = {} valid_update_keys = ( 'name', 'description', 'display_name', 'display_description', ) # NOTE(thingee): v2 API allows name instead of display_name if 'name' in snapshot: snapshot['display_name'] = snapshot['name'] del snapshot['name'] # NOTE(thingee): v2 API allows description instead of # display_description if 'description' in snapshot: snapshot['display_description'] = snapshot['description'] del snapshot['description'] for key in valid_update_keys: if key in snapshot: update_dict[key] = snapshot[key] try: snapshot = self.volume_api.get_snapshot(context, id) self.volume_api.update_snapshot(context, snapshot, update_dict) except exception.NotFound: msg = _("Snapshot could not be found") raise exc.HTTPNotFound(explanation=msg) snapshot.update(update_dict) return {'snapshot': _translate_snapshot_detail_view(context, snapshot)} def create_resource(ext_mgr): return wsgi.Resource(SnapshotsController(ext_mgr))
# -*- coding: utf-8 -*- """WebSocketBaseTestCase is based on combination of Tornado and Django test systems. It require to use decorator '@gen.coroutine' for each test case method( see documentation: http://www.tornadoweb.org/en/stable/testing.html). It requires implementation of 'get_app' method to initialize tornado application and launch it. """ from __future__ import absolute_import from __future__ import print_function import time import ujson from django.conf import settings from django.http import HttpRequest, HttpResponse from django.db import close_old_connections from django.core import signals from tornado.gen import Return from tornado.httpclient import HTTPRequest, HTTPResponse from zerver.lib.test_helpers import POSTRequestMock from zerver.lib.test_classes import ZulipTestCase from zerver.models import UserProfile, get_client from tornado import gen from tornado.testing import AsyncHTTPTestCase, gen_test from tornado.web import Application from tornado.websocket import websocket_connect from zerver.tornado.application import create_tornado_application from zerver.tornado import event_queue from zerver.tornado.event_queue import fetch_events, \ allocate_client_descriptor, process_event from zerver.tornado.views import get_events_backend from six.moves.http_cookies import SimpleCookie from six.moves import urllib_parse from typing import Any, Callable, Dict, Generator, Optional, Text, List, cast class TornadoWebTestCase(AsyncHTTPTestCase, ZulipTestCase): def setUp(self): # type: () -> None super(TornadoWebTestCase, self).setUp() signals.request_started.disconnect(close_old_connections) signals.request_finished.disconnect(close_old_connections) self.session_cookie = None # type: Optional[Dict[Text, Text]] def tearDown(self): # type: () -> None super(TornadoWebTestCase, self).tearDown() self.session_cookie = None # type: Optional[Dict[Text, Text]] def get_app(self): # type: () -> Application return create_tornado_application() def client_get(self, path, **kwargs): # type: (Text, **Any) -> HTTPResponse self.add_session_cookie(kwargs) self.set_http_host(kwargs) if 'HTTP_HOST' in kwargs: kwargs['headers']['Host'] = kwargs['HTTP_HOST'] del kwargs['HTTP_HOST'] return self.fetch(path, method='GET', **kwargs) def fetch_async(self, method, path, **kwargs): # type: (Text, Text, **Any) -> None self.add_session_cookie(kwargs) self.set_http_host(kwargs) if 'HTTP_HOST' in kwargs: kwargs['headers']['Host'] = kwargs['HTTP_HOST'] del kwargs['HTTP_HOST'] self.http_client.fetch( self.get_url(path), self.stop, method=method, **kwargs ) def client_get_async(self, path, **kwargs): # type: (Text, **Any) -> None self.set_http_host(kwargs) self.fetch_async('GET', path, **kwargs) def login(self, *args, **kwargs): # type: (*Any, **Any) -> None super(TornadoWebTestCase, self).login(*args, **kwargs) session_cookie = settings.SESSION_COOKIE_NAME session_key = self.client.session.session_key self.session_cookie = { "Cookie": "{}={}".format(session_cookie, session_key) } def get_session_cookie(self): # type: () -> Dict[Text, Text] return {} if self.session_cookie is None else self.session_cookie def add_session_cookie(self, kwargs): # type: (Dict[str, Any]) -> None # TODO: Currently only allows session cookie headers = kwargs.get('headers', {}) headers.update(self.get_session_cookie()) kwargs['headers'] = headers def create_queue(self, **kwargs): # type: (**Any) -> str response = self.client_get('/json/events?dont_block=true', subdomain="zulip") self.assertEqual(response.code, 200) body = ujson.loads(response.body) self.assertEqual(body['events'], []) self.assertIn('queue_id', body) return body['queue_id'] class EventsTestCase(TornadoWebTestCase): def test_create_queue(self): # type: () -> None self.login(self.example_email('hamlet')) queue_id = self.create_queue() self.assertIn(queue_id, event_queue.clients) def test_events_async(self): # type: () -> None user_profile = self.example_user('hamlet') self.login(user_profile.email) event_queue_id = self.create_queue() data = { 'queue_id': event_queue_id, 'last_event_id': 0, } path = '/json/events?{}'.format(urllib_parse.urlencode(data)) self.client_get_async(path) def process_events(): # type: () -> None users = [user_profile.id] event = dict( type='test', data='test data', ) process_event(event, users) self.io_loop.call_later(0.1, process_events) response = self.wait() data = ujson.loads(response.body) events = data['events'] events = cast(List[Dict[str, Any]], events) self.assertEqual(len(events), 1) self.assertEqual(events[0]['data'], 'test data') self.assertEqual(data['result'], 'success') class WebSocketBaseTestCase(AsyncHTTPTestCase, ZulipTestCase): def setUp(self): # type: () -> None settings.RUNNING_INSIDE_TORNADO = True super(WebSocketBaseTestCase, self).setUp() def tearDown(self): # type: () -> None super(WebSocketBaseTestCase, self).setUp() settings.RUNNING_INSIDE_TORNADO = False @gen.coroutine def ws_connect(self, path, cookie_header, compression_options=None): # type: (str, str, Optional[Any]) -> Generator[Any, Callable[[HTTPRequest, Optional[Any]], Any], None] request = HTTPRequest(url='ws://127.0.0.1:%d%s' % (self.get_http_port(), path)) request.headers.add('Cookie', cookie_header) ws = yield websocket_connect( request, compression_options=compression_options) raise gen.Return(ws) @gen.coroutine def close(self, ws): # type: (Any) -> None """Close a websocket connection and wait for the server side. If we don't wait here, there are sometimes leak warnings in the tests. """ ws.close() self.wait() class TornadoTestCase(WebSocketBaseTestCase): def get_app(self): # type: () -> Application """ Return tornado app to launch for test cases """ return create_tornado_application() @staticmethod def tornado_call(view_func, user_profile, post_data): # type: (Callable[[HttpRequest, UserProfile], HttpResponse], UserProfile, Dict[str, Any]) -> HttpResponse request = POSTRequestMock(post_data, user_profile) return view_func(request, user_profile) @staticmethod def get_cookie_header(cookies): # type: (Dict[Any, Any]) -> str return ';'.join( ["{}={}".format(name, value.value) for name, value in cookies.items()]) def _get_cookies(self, user_profile): # type: (UserProfile) -> SimpleCookie resp = self.login_with_return(user_profile.email) return resp.cookies @gen.coroutine def _websocket_auth(self, ws, queue_events_data, cookies): # type: (Any, Dict[str, Dict[str, str]], SimpleCookie) -> Generator[str, str, None] auth_queue_id = ':'.join((queue_events_data['response']['queue_id'], '0')) message = { "req_id": auth_queue_id, "type": "auth", "request": { "csrf_token": cookies.get('csrftoken').coded_value, "queue_id": queue_events_data['response']['queue_id'], "status_inquiries": [] } } auth_frame_str = ujson.dumps(message) ws.write_message(ujson.dumps([auth_frame_str])) response_ack = yield ws.read_message() response_message = yield ws.read_message() raise gen.Return([response_ack, response_message]) @staticmethod def _get_queue_events_data(email): # type: (Text) -> Dict[str, Dict[str, str]] user_profile = UserProfile.objects.filter(email=email).first() events_query = { 'queue_id': None, 'narrow': [], 'handler_id': 0, 'user_profile_email': user_profile.email, 'all_public_streams': False, 'client_type_name': 'website', 'new_queue_data': { 'apply_markdown': True, 'narrow': [], 'user_profile_email': user_profile.email, 'all_public_streams': False, 'realm_id': user_profile.realm_id, 'client_type_name': 'website', 'event_types': None, 'user_profile_id': user_profile.id, 'queue_timeout': 0, 'last_connection_time': time.time()}, 'last_event_id': -1, 'event_types': None, 'user_profile_id': user_profile.id, 'dont_block': True, 'lifespan_secs': 0 } result = fetch_events(events_query) return result def _check_message_sending(self, request_id, ack_resp, msg_resp, profile, queue_events_data): # type: (str, str, str, UserProfile, Dict[str, Dict[str, str]]) -> None self.assertEqual(ack_resp[0], 'a') self.assertEqual( ujson.loads(ack_resp[1:]), [ { "type": "ack", "req_id": request_id } ]) self.assertEqual(msg_resp[0], 'a') result = self.tornado_call(get_events_backend, profile, {"queue_id": queue_events_data['response']['queue_id'], "user_client": "website", "last_event_id": -1, "dont_block": ujson.dumps(True), }) result_content = ujson.loads(result.content) self.assertEqual(len(result_content['events']), 1) message_id = result_content['events'][0]['message']['id'] self.assertEqual( ujson.loads(msg_resp[1:]), [ { "type": "response", "response": { "result": "success", "id": message_id, "msg": "" }, "req_id": request_id } ]) @gen_test def test_tornado_connect(self): # type: () -> Generator[str, Any, None] user_profile = self.example_user('hamlet') cookies = self._get_cookies(user_profile) cookie_header = self.get_cookie_header(cookies) ws = yield self.ws_connect('/sockjs/366/v8nw22qe/websocket', cookie_header=cookie_header) response = yield ws.read_message() self.assertEqual(response, 'o') self.close(ws) @gen_test def test_tornado_auth(self): # type: () -> Generator[str, TornadoTestCase, None] user_profile = self.example_user('hamlet') cookies = self._get_cookies(user_profile) cookie_header = self.get_cookie_header(cookies) ws = yield self.ws_connect('/sockjs/366/v8nw22qe/websocket', cookie_header=cookie_header) yield ws.read_message() queue_events_data = self._get_queue_events_data(user_profile.email) request_id = ':'.join((queue_events_data['response']['queue_id'], '0')) response = yield self._websocket_auth(ws, queue_events_data, cookies) self.assertEqual(response[0][0], 'a') self.assertEqual( ujson.loads(response[0][1:]), [ { "type": "ack", "req_id": request_id } ]) self.assertEqual(response[1][0], 'a') self.assertEqual( ujson.loads(response[1][1:]), [ {"req_id": request_id, "response": { "result": "success", "status_inquiries": {}, "msg": "" }, "type": "response"} ]) self.close(ws) @gen_test def test_sending_private_message(self): # type: () -> Generator[str, Any, None] user_profile = self.example_user('hamlet') cookies = self._get_cookies(user_profile) cookie_header = self.get_cookie_header(cookies) queue_events_data = self._get_queue_events_data(user_profile.email) ws = yield self.ws_connect('/sockjs/366/v8nw22qe/websocket', cookie_header=cookie_header) yield ws.read_message() yield self._websocket_auth(ws, queue_events_data, cookies) request_id = ':'.join((queue_events_data['response']['queue_id'], '1')) user_message = { "req_id": request_id, "type": "request", "request": { "client": "website", "type": "private", "subject": "(no topic)", "stream": "", "private_message_recipient": self.example_email('othello'), "content": "hello", "sender_id": user_profile.id, "queue_id": queue_events_data['response']['queue_id'], "to": ujson.dumps([self.example_email('othello')]), "reply_to": self.example_email('hamlet'), "local_id": -1 } } user_message_str = ujson.dumps(user_message) ws.write_message(ujson.dumps([user_message_str])) ack_resp = yield ws.read_message() msg_resp = yield ws.read_message() self._check_message_sending(request_id, ack_resp, msg_resp, user_profile, queue_events_data) self.close(ws) @gen_test def test_sending_stream_message(self): # type: () -> Generator[str, Any, None] user_profile = self.example_user('hamlet') cookies = self._get_cookies(user_profile) cookie_header = self.get_cookie_header(cookies) queue_events_data = self._get_queue_events_data(user_profile.email) ws = yield self.ws_connect('/sockjs/366/v8nw22qe/websocket', cookie_header=cookie_header) yield ws.read_message() yield self._websocket_auth(ws, queue_events_data, cookies) request_id = ':'.join((queue_events_data['response']['queue_id'], '1')) user_message = { "req_id": request_id, "type": "request", "request": { "client": "website", "type": "stream", "subject": "Stream message", "stream": "Denmark", "private_message_recipient": "", "content": "hello", "sender_id": user_profile.id, "queue_id": queue_events_data['response']['queue_id'], "to": ujson.dumps(["Denmark"]), "reply_to": self.example_email('hamlet'), "local_id": -1 } } user_message_str = ujson.dumps(user_message) ws.write_message(ujson.dumps([user_message_str])) ack_resp = yield ws.read_message() msg_resp = yield ws.read_message() self._check_message_sending(request_id, ack_resp, msg_resp, user_profile, queue_events_data) self.close(ws)
# Copyright (C) 2013-2015 MetaMorph Software, Inc # Permission is hereby granted, free of charge, to any person obtaining a # copy of this data, including any software or models in source or binary # form, as well as any drawings, specifications, and documentation # (collectively "the Data"), to deal in the Data without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Data, and to # permit persons to whom the Data 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 Data. # THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA. # ======================= # This version of the META tools is a fork of an original version produced # by Vanderbilt University's Institute for Software Integrated Systems (ISIS). # Their license statement: # Copyright (C) 2011-2014 Vanderbilt University # Developed with the sponsorship of the Defense Advanced Research Projects # Agency (DARPA) and delivered to the U.S. Government with Unlimited Rights # as defined in DFARS 252.227-7013. # Permission is hereby granted, free of charge, to any person obtaining a # copy of this data, including any software or models in source or binary # form, as well as any drawings, specifications, and documentation # (collectively "the Data"), to deal in the Data without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Data, and to # permit persons to whom the Data 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 Data. # THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA. from numpy import * import params import pearscdf import jsonout from mvncdf import mvstdnormcdf import estimate_complexity import itertools #for fullfact function from model_calls import run_list def UP_FFNI(driver): # Uses the FFNI method for UP # ---------------------- Setup --------------------------- methd = 'FFNI' method = 4 mu = [inp.get_I_mu() for inp in driver.inputs] I_sigma = [inp.get_I_sigma() for inp in driver.inputs] inpt = len(driver.inputs) input = driver.inputNames krig = driver.krig limstate= driver.limstate lrflag = driver.lrflag n_meta = driver.n_meta nEFAST = driver.nEFAST nSOBOL = driver.nSOBOL nMCS = driver.nMCS numbins = driver.numbins nodes = driver.nodes order = driver.order otpt = len(driver.outputNames) output = driver.outputNames p = driver.p plotf = 0 r = driver.r simple = driver.simple stvars = driver.stvars node,w = params.params(method, nodes, inpt, stvars) # Do I need to transpose these matrices? #[quadpts] = params(method, nodes, inpt, stvars) # ---------------------- Model --------------------------- # Create full factorial experiment from individual nodes and weights j = fullfact(nodes) pts = shape(j)[0] x=zeros((pts,inpt)) wj=zeros((pts,inpt)) for y in range(pts): for i in range(inpt): x[y][i] = node[i][j[y][i]] wj[y][i] = w[i][j[y][i]] weight = prod(wj, 1) if krig == 1: load("dmodel") G_s = predictor(x, dmodel) else: # G_s = zeros((pts, otpt)) # for i in range(pts): # print 'Running simulation',i+1,'of',pts # G_s[i] = run_model(driver, x[i]) # G_s[i] = modelica.RunModelica(x[i], modelname, properties) G_s = run_list(driver, x) G_mean = zeros(otpt) G_kurt = zeros(otpt) G_skew = zeros(otpt) covar_m = zeros((otpt,otpt)) for k in range(otpt): G_mean[k] = sum(weight * G_s[:, k]) for k in range(otpt): for j in range(otpt): covar_m[k, j] = sum(weight * (G_s[:, k] - G_mean[k]) * (G_s[:, j] - G_mean[j])) covar_m[j, k] = covar_m[k, j] G_skew[k] = sum(weight * (G_s[:, k] - G_mean[k]) ** 3) / covar_m[k, k] ** 1.5 G_kurt[k] = sum(weight * (G_s[:, k] - G_mean[k]) ** 4) / covar_m[k, k] ** 2 CovarianceMatrix = covar_m.transpose() Moments = {'Mean': G_mean, 'Variance': diag(CovarianceMatrix), 'Skewness': G_skew, 'Kurtosis': G_kurt} # ---------------------- Analyze --------------------------- # Calculate the PCC for the FFNI method if otpt>1: PCC = [0]*(otpt+1) else: PCC = [0]*otpt dtype = [0]*otpt Inv1 = [0]*otpt Inv2 = [0]*otpt m1 = [0]*otpt m2 = [0]*otpt a1 = [0]*otpt a2 = [0]*otpt alph = [0]*otpt beta = [0]*otpt lo = [0]*otpt hi = [0]*otpt C_Y_pdf = [0]*otpt if any(Moments['Variance']==0): print "Warning: One or more outputs does not vary over given parameter variation." for k in range(0,otpt): PCC[k],dtype[k],Inv1[k],m1[k],m2[k],a1[k],a2[k],alph[k],beta[k],lo[k],hi[k] = pearscdf.pearscdf(limstate[k], Moments['Mean'][k], sqrt(CovarianceMatrix[k, k]), Moments['Skewness'][k], Moments['Kurtosis'][k], methd, k, output) if dtype[k] != None: if iscomplex(a1[k]): a1[k] = [a1[k].real, a1[k].imag] if iscomplex(a2[k]): a2[k] = [a2[k].real, a2[k].imag] C_Y_pdf[k] = estimate_complexity.with_distribution(dtype[k],limstate[k],Moments['Mean'][k],Moments['Variance'][k],numbins) sigma_mat=matrix(sqrt(diag(CovarianceMatrix))) seterr(invalid='ignore') #ignore problems with divide-by-zero, just give us 'nan' as usual CorrelationMatrix= CovarianceMatrix/multiply(sigma_mat,sigma_mat.transpose()) Distribution = {'PearsonType': dtype, 'm1': m1, 'm2': m2, 'a1': a1, 'a2': a2, 'Complexity': C_Y_pdf} Plotting = {'alpha': alph, 'beta': beta, 'lo': lo, 'hi': hi} CorrelationMatrix=where(isnan(CorrelationMatrix), None, CorrelationMatrix) if otpt > 1 and not 0 in PCC[0:otpt]: lower = zeros(otpt)-inf PCC[otpt] = mvstdnormcdf(lower, Inv1, CorrelationMatrix) Results = {'Moments': Moments, 'CorrelationMatrix': CorrelationMatrix, 'CovarianceMatrix': CovarianceMatrix, 'Distribution': Distribution, 'Plotting': Plotting, 'PCC': PCC} return Results #duplicates matlab fullfact function def fullfact(levels): args = [] for l in levels: args.append(range(0,l)) ff = itertools.product(*args) return array(list(ff)) # if we're supposed to close the plot window autoomatically on # completion, quit. # if autoClose == 1 # Copyright (c) 2011. # Developed with the sponsorship of the Defense Advanced Research Projects Agency (DARPA). # Permission is hereby granted, free of charge, to any person obtaining a copy of this data, # including any software or models in source or binary form, as well as any drawings, # specifications, and documentation (collectively "the Data"), # to deal in the Data without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Data, # and to permit persons to whom the Data 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 Data. # THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, # 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """fbscraper package. This module is used for parsing or dumping a FB JSON (see help command for further details). Examples -------- Using the CLI: $ ./fbscraper.py dumper -s 10000 -c request_data.txt $ ./fbscraper.py parser -m dl -d all -i output/*/complete.json -c request_data.txt Using as the module: >>> from fbscraper.parser import FBParser >>> fb_parserr = FBParser('complete.json', 'dl', 'pictures') >>> fb_parser.parse(to_stdout=True) """ import argparse import sys from fbscraper.dumper import FBDumper from fbscraper.lib import FBDataTypes, FBParserMode, FBResponseError, \ OUTPUT_DEFAULT_FOLDER, \ format_convers_metadata, \ build_fmt_str_from_enum from fbscraper.parser import FBParser def check_positive_int(value): """Check positive int.""" ivalue = int(value) if ivalue < 0: raise argparse.ArgumentTypeError("{} is an invalid positive" "int value".format(value)) return ivalue def check_positive_and_not_zero_int(value): """Check positive and not zero int.""" ivalue = int(value) if ivalue <= 0: raise argparse.ArgumentTypeError("{} is an invalid positive" "int value".format(value)) return ivalue def check_positive_float(value): """Check positive float.""" fvalue = float(value) if fvalue < 0: raise argparse.ArgumentTypeError("{} is an invalid positive" "float value".format(value)) return fvalue def main(): """Main function. This method will parse arguments and depending on which tool is selected (**dumper** or **parser**) and executed the corresponding main function (`dumper_tool_main` or `parser_tool_main`). Returns ------- int 0 on success. See Also -------- dumper_tool_main : method executed for the **dumper** tool. parser_tool_main : method executed for the **parser** tool. Notes ----- See usages at the top of the module. Use the help command for more information. """ parser = argparse.ArgumentParser(description="Script for parsing a FB" " JSON conversation and ") subparsers = parser.add_subparsers(help='Tool to use') dumper_parser = subparsers.add_parser('dumper', help='Dumper tool. ' 'See help: fbscraper dumper -h') parser_parser = subparsers.add_parser('parser', help='Parser tool. ' 'See help: fbscraper parser -h') dumper_parser.add_argument('-id', "--convers-id", nargs='*', help="Conversation IDs to dump") dumper_parser.add_argument('-s', "--size", type=check_positive_int, default=2000, help="Number of messages to retrieve for " "each request") dumper_parser.add_argument('-off', "--offset", type=check_positive_int, default=0, help="Do not retrieve the last 'n' messages'") dumper_parser.add_argument('-t', "--timer", type=check_positive_float, default=1, help="Do not retrieve the last 'n' messages'") dumper_parser.add_argument('-meta', '--metadata', action="store_true", help="If this option is used, conversations " " not dumped. Conversations metadata " "are printed") parser_parser.add_argument('-m', '--mode', required=True, type=FBParserMode, help="Report mode only save URLs inside files. " "The dl mode additionnaly download it. " "MODE may be one of " + build_fmt_str_from_enum(FBParserMode)) parser_parser.add_argument("-d", "--data", nargs="+", type=FBDataTypes, default=[FBDataTypes.ALL], help="Data to retrieve from the --infile file. " "DATA may be one or many of " + build_fmt_str_from_enum(FBDataTypes)) parser_parser.add_argument("-i", "--infile", nargs='+', help="File to parse and try to retrieve data " "from the --data types") parser_parser.add_argument('-t', "--threads", type=check_positive_and_not_zero_int, default=4, help="Number of threads for dl mode") dumper_parser.set_defaults(func=dumper_tool_main) parser_parser.set_defaults(func=parser_tool_main) for subparser in [dumper_parser, parser_parser]: subparser.add_argument("-c", "--cookie", type=argparse.FileType("r"), required=True, help="File to parse for retrieving" "headers and post data for " "intializing the scraper") subparser.add_argument("-v", "--verbose", action="store_true", help="Increase output verbosity") subparser.add_argument('-o', "--output", default=OUTPUT_DEFAULT_FOLDER, help="Output folder where to save data." "This folder may be common to all ID" "conversations dumped or parsed." "The creation of a folder with the" "conversation ID is automatically " "created") args = parser.parse_args() if hasattr(args, "func"): if args.verbose: print("[+] - Args: " + str(args)) try: return args.func(args) except KeyError as e: print("[+] - KeyError exception generated. It is probably due " "to a change in the JSON conversation format. Please open " "an issue on the Github repository, with your JSON file " "attached.\nException : {0!r}".format(e)) return 1 else: parser.print_usage() def dumper_tool_main(args): """Main function for the **dumper** tool. Parameters ---------- args : Namespace Arguments passed by the `ArgumentParser`. This method will dump a Facebook conversation and save it to two JSON formatted files (one for JSON, one for 'pretty' JSON) depending on the arguments passed. See Also -------- main : method used for parsing arguments dump : method executed for the **dumper** tool. """ with args.cookie as f: user_post_data = f.read() fb_dumper = FBDumper(args.convers_id, user_raw_data=user_post_data, chunk_size=args.size, timer=args.timer, output=args.output) if args.metadata: print("[+] - Printing conversations metadata (total: {})" .format(len(fb_dumper.convers))) print(format_convers_metadata(fb_dumper.convers, fb_dumper.participants)) return 0 if args.convers_id: print("[+] - Dumping JSON from {} conversations" .format(len(args.convers_id))) else: print("[+] - Dumping JSON from all conversations (total: {})" .format(len(fb_dumper.convers))) try: fb_dumper.dump(to_stdout=True, verbose=args.verbose) except FBResponseError as e: print("[+] - Error Occured, Facebook error summary : '{}'" .format(e)) return 0 def parser_tool_main(args): """Main function for the **parser** tool. This method will parse a JSON formatted Facebook conversation, reports informations and retrieve data from it, depending on the arguments passed. Parameters ---------- args : Namespace (dict-like) Arguments passed by the `ArgumentParser`. See Also -------- FBParser: Class used for the **parser** tool. main : method used for parsing arguments """ with args.cookie as f: user_raw_data = f.read() print("[+] - Parsing JSON for {} files".format(len(args.infile))) data_formatted = build_fmt_str_from_enum(args.data) print("[+] - Parsing JSON to retrieve {}".format(data_formatted)) fb_parser = FBParser(user_raw_data, infile_json=args.infile, mode=args.mode, data=args.data, output=args.output, threads=args.threads) fb_parser.parse(to_stdout=True, verbose=args.verbose) print("[+] - JSON parsed succesfully, saving results " "inside folder '" + str(args.output) + "'") return 0 if __name__ == '__main__': sys.exit(main())
# # 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 ceilometerclient import exc as ceil_exc from ceilometerclient.openstack.common.apiclient import exceptions as c_a_exc from cinderclient import exceptions as cinder_exc from glanceclient import exc as glance_exc from glanceclient.openstack.common.apiclient import exceptions as g_a_exc from heatclient import client as heatclient from heatclient import exc as heat_exc from keystoneclient.auth.identity import v3 from keystoneclient import exceptions as keystone_exc from manilaclient import exceptions as manila_exc import mock from neutronclient.common import exceptions as neutron_exc from oslo_config import cfg from saharaclient.api import base as sahara_base import six from swiftclient import exceptions as swift_exc from testtools import testcase from troveclient import client as troveclient from zaqarclient.transport import errors as zaqar_exc from heat.common import exception from heat.engine import clients from heat.engine.clients import client_plugin from heat.tests import common from heat.tests import fakes from heat.tests.openstack.nova import fakes as fakes_nova from heat.tests import utils class ClientsTest(common.HeatTestCase): def test_bad_cloud_backend(self): con = mock.Mock() cfg.CONF.set_override('cloud_backend', 'some.weird.object') exc = self.assertRaises(exception.Invalid, clients.Clients, con) self.assertIn('Invalid cloud_backend setting in heat.conf detected', six.text_type(exc)) cfg.CONF.set_override('cloud_backend', 'heat.engine.clients.Clients') exc = self.assertRaises(exception.Invalid, clients.Clients, con) self.assertIn('Invalid cloud_backend setting in heat.conf detected', six.text_type(exc)) def test_clients_get_heat_url(self): con = mock.Mock() con.tenant_id = "b363706f891f48019483f8bd6503c54b" c = clients.Clients(con) con.clients = c obj = c.client_plugin('heat') obj._get_client_option = mock.Mock() obj._get_client_option.return_value = None obj.url_for = mock.Mock(name="url_for") obj.url_for.return_value = "url_from_keystone" self.assertEqual("url_from_keystone", obj.get_heat_url()) heat_url = "http://0.0.0.0:8004/v1/%(tenant_id)s" obj._get_client_option.return_value = heat_url tenant_id = "b363706f891f48019483f8bd6503c54b" result = heat_url % {"tenant_id": tenant_id} self.assertEqual(result, obj.get_heat_url()) obj._get_client_option.return_value = result self.assertEqual(result, obj.get_heat_url()) def _client_cfn_url(self): con = mock.Mock() c = clients.Clients(con) con.clients = c obj = c.client_plugin('heat') obj._get_client_option = mock.Mock() obj._get_client_option.return_value = None obj.url_for = mock.Mock(name="url_for") obj.url_for.return_value = "http://0.0.0.0:8000/v1/" return obj def test_clients_get_heat_cfn_url(self): obj = self._client_cfn_url() self.assertEqual("http://0.0.0.0:8000/v1/", obj.get_heat_cfn_url()) def test_clients_get_heat_cfn_metadata_url(self): obj = self._client_cfn_url() self.assertEqual("http://0.0.0.0:8000/v1/", obj.get_cfn_metadata_server_url()) def test_clients_get_heat_cfn_metadata_url_conf(self): cfg.CONF.set_override('heat_metadata_server_url', 'http://server.test:123') obj = self._client_cfn_url() self.assertEqual("http://server.test:123/v1/", obj.get_cfn_metadata_server_url()) @mock.patch.object(heatclient, 'Client') def test_clients_heat(self, mock_call): self.stub_keystoneclient() con = mock.Mock() con.auth_url = "http://auth.example.com:5000/v2.0" con.tenant_id = "b363706f891f48019483f8bd6503c54b" con.auth_token = "3bcc3d3a03f44e3d8377f9247b0ad155" c = clients.Clients(con) con.clients = c obj = c.client_plugin('heat') obj.url_for = mock.Mock(name="url_for") obj.url_for.return_value = "url_from_keystone" obj.client() self.assertEqual('url_from_keystone', obj.get_heat_url()) @mock.patch.object(heatclient, 'Client') def test_clients_heat_no_auth_token(self, mock_call): con = mock.Mock() con.auth_url = "http://auth.example.com:5000/v2.0" con.tenant_id = "b363706f891f48019483f8bd6503c54b" con.auth_token = None con.auth_plugin = fakes.FakeAuth(auth_token='anewtoken') self.stub_keystoneclient(context=con) c = clients.Clients(con) con.clients = c obj = c.client_plugin('heat') obj.url_for = mock.Mock(name="url_for") obj.url_for.return_value = "url_from_keystone" self.assertEqual('anewtoken', c.client('keystone').auth_token) @mock.patch.object(heatclient, 'Client') def test_clients_heat_cached(self, mock_call): self.stub_auth() con = mock.Mock() con.auth_url = "http://auth.example.com:5000/v2.0" con.tenant_id = "b363706f891f48019483f8bd6503c54b" con.auth_token = "3bcc3d3a03f44e3d8377f9247b0ad155" con.trust_id = None c = clients.Clients(con) con.clients = c obj = c.client_plugin('heat') obj.get_heat_url = mock.Mock(name="get_heat_url") obj.get_heat_url.return_value = None obj.url_for = mock.Mock(name="url_for") obj.url_for.return_value = "url_from_keystone" obj._client = None heat = obj.client() heat_cached = obj.client() self.assertEqual(heat, heat_cached) class FooClientsPlugin(client_plugin.ClientPlugin): def _create(self): pass @property def auth_token(self): return '5678' class ClientPluginTest(common.HeatTestCase): def test_get_client_option(self): con = mock.Mock() con.auth_url = "http://auth.example.com:5000/v2.0" con.tenant_id = "b363706f891f48019483f8bd6503c54b" con.auth_token = "3bcc3d3a03f44e3d8377f9247b0ad155" c = clients.Clients(con) con.clients = c plugin = FooClientsPlugin(con) cfg.CONF.set_override('ca_file', '/tmp/bar', group='clients_heat') cfg.CONF.set_override('ca_file', '/tmp/foo', group='clients') cfg.CONF.set_override('endpoint_type', 'internalURL', group='clients') # check heat group self.assertEqual('/tmp/bar', plugin._get_client_option('heat', 'ca_file')) # check fallback clients group for known client self.assertEqual('internalURL', plugin._get_client_option('glance', 'endpoint_type')) # check fallback clients group for unknown client foo self.assertEqual('/tmp/foo', plugin._get_client_option('foo', 'ca_file')) def test_get_client_args(self): ctxt = mock.Mock() plugin = FooClientsPlugin(ctxt) plugin.url_for = mock.Mock(return_value='sample_endpoint_url') plugin.context.auth_url = 'sample_auth_url' plugin.context.tenant_id = 'sample_project_id' mock_args = { 'endpoint_type': 'internalURL', 'ca_file': '/tmp/ca_file', 'cert_file': '/tmp/cert_file', 'key_file': '/tmp/key_file', 'insecure': True } def _side_effect(service_name, arg_name): return mock_args[arg_name] plugin._get_client_option = mock.Mock(side_effect=_side_effect) args = plugin._get_client_args('sample_service', 'foo_type') self.assertEqual('foo_type', args['service_type'], 'invalid service_type') self.assertEqual('sample_auth_url', args['auth_url'], 'invalid auth_url') self.assertEqual('sample_project_id', args['project_id'], 'invalid project_id') self.assertEqual('5678', args['token'](), 'invalid auth_token') self.assertEqual('sample_endpoint_url', args['os_endpoint'], 'invalid os_endpoint') self.assertEqual('internalURL', args['endpoint_type'], 'invalid endpoint_type') self.assertEqual('/tmp/ca_file', args['cacert'], 'invalid cacert') self.assertEqual('/tmp/cert_file', args['cert_file'], 'invalid cert_file') self.assertEqual('/tmp/key_file', args['key_file'], 'invalid key_file') self.assertTrue(args['insecure'], 'invalid insecure') def test_auth_token(self): con = mock.Mock() con.auth_token = "1234" con.trust_id = None c = clients.Clients(con) con.clients = c plugin = FooClientsPlugin(con) # assert token is from plugin rather than context # even though both are set self.assertEqual('5678', plugin.auth_token) def test_url_for(self): con = mock.Mock() con.auth_token = "1234" con.trust_id = None c = clients.Clients(con) con.clients = c con.auth_plugin = mock.Mock(name="auth_plugin") con.auth_plugin.get_endpoint = mock.Mock(name="get_endpoint") con.auth_plugin.get_endpoint.return_value = 'http://192.0.2.1/foo' plugin = FooClientsPlugin(con) self.assertEqual('http://192.0.2.1/foo', plugin.url_for(service_type='foo')) self.assertTrue(con.auth_plugin.get_endpoint.called) @mock.patch.object(v3, "Token", name="v3_token") def test_get_missing_service_catalog(self, mock_v3): class FakeKeystone(fakes.FakeKeystoneClient): def __init__(self): super(FakeKeystone, self).__init__() self.client = self self.version = 'v3' self.stub_keystoneclient(fake_client=FakeKeystone()) con = mock.MagicMock(auth_token="1234", trust_id=None) c = clients.Clients(con) con.clients = c con.auth_plugin = mock.Mock(name="auth_plugin") get_endpoint_side_effects = [ keystone_exc.EmptyCatalog(), None, 'http://192.0.2.1/bar'] con.auth_plugin.get_endpoint = mock.Mock( name="get_endpoint", side_effect=get_endpoint_side_effects) mock_token_obj = mock.Mock() mock_token_obj.get_auth_ref.return_value = {'catalog': 'foo'} mock_v3.return_value = mock_token_obj plugin = FooClientsPlugin(con) self.assertEqual('http://192.0.2.1/bar', plugin.url_for(service_type='bar')) @mock.patch.object(v3, "Token", name="v3_token") def test_endpoint_not_found(self, mock_v3): class FakeKeystone(fakes.FakeKeystoneClient): def __init__(self): super(FakeKeystone, self).__init__() self.client = self self.version = 'v3' self.stub_keystoneclient(fake_client=FakeKeystone()) con = mock.MagicMock(auth_token="1234", trust_id=None) c = clients.Clients(con) con.clients = c con.auth_plugin = mock.Mock(name="auth_plugin") get_endpoint_side_effects = [keystone_exc.EmptyCatalog(), None] con.auth_plugin.get_endpoint = mock.Mock( name="get_endpoint", side_effect=get_endpoint_side_effects) mock_token_obj = mock.Mock() mock_v3.return_value = mock_token_obj mock_token_obj.get_auth_ref.return_value = {'no_catalog': 'without'} plugin = FooClientsPlugin(con) self.assertRaises(keystone_exc.EndpointNotFound, plugin.url_for, service_type='nonexistent') def test_abstract_create(self): con = mock.Mock() c = clients.Clients(con) con.clients = c self.assertRaises(TypeError, client_plugin.ClientPlugin, c) def test_create_client_on_token_expiration(self): cfg.CONF.set_override('reauthentication_auth_method', 'trusts') con = mock.Mock() con.auth_plugin.auth_ref.will_expire_soon.return_value = False plugin = FooClientsPlugin(con) plugin._create = mock.Mock() plugin.client() self.assertEqual(1, plugin._create.call_count) plugin.client() self.assertEqual(1, plugin._create.call_count) con.auth_plugin.auth_ref.will_expire_soon.return_value = True plugin.client() self.assertEqual(2, plugin._create.call_count) def test_create_client_on_invalidate(self): con = mock.Mock() plugin = FooClientsPlugin(con) plugin._create = mock.Mock() plugin.client() self.assertEqual(1, plugin._create.call_count) plugin.client() self.assertEqual(1, plugin._create.call_count) plugin.invalidate() plugin.client() self.assertEqual(2, plugin._create.call_count) class TestClientPluginsInitialise(common.HeatTestCase): @testcase.skip('skipped until keystone can read context auth_ref') def test_create_all_clients(self): con = mock.Mock() con.auth_url = "http://auth.example.com:5000/v2.0" con.tenant_id = "b363706f891f48019483f8bd6503c54b" con.auth_token = "3bcc3d3a03f44e3d8377f9247b0ad155" c = clients.Clients(con) con.clients = c for plugin_name in clients._mgr.names(): self.assertTrue(clients.has_client(plugin_name)) c.client(plugin_name) def test_create_all_client_plugins(self): plugin_types = clients._mgr.names() self.assertIsNotNone(plugin_types) con = mock.Mock() c = clients.Clients(con) con.clients = c for plugin_name in plugin_types: plugin = c.client_plugin(plugin_name) self.assertIsNotNone(plugin) self.assertEqual(c, plugin.clients) self.assertEqual(con, plugin.context) self.assertIsNone(plugin._client) self.assertTrue(clients.has_client(plugin_name)) self.assertIsInstance(plugin.service_types, list) self.assertTrue(len(plugin.service_types) >= 1, 'service_types is not defined for plugin') @mock.patch.object(client_plugin.ClientPlugin, 'invalidate') def test_invalidate_all_clients(self, mock_invalidate): plugin_types = clients._mgr.names() con = mock.Mock() c = clients.Clients(con) con.clients = c for plugin_name in plugin_types: plugin = c.client_plugin(plugin_name) self.assertIsNotNone(plugin) c.invalidate_plugins() self.assertEqual(len(plugin_types), mock_invalidate.call_count) class TestIsNotFound(common.HeatTestCase): scenarios = [ ('ceilometer_not_found', dict( is_not_found=True, is_over_limit=False, is_client_exception=True, is_conflict=False, plugin='ceilometer', exception=lambda: ceil_exc.HTTPNotFound(details='gone'), )), ('ceilometer_not_found_apiclient', dict( is_not_found=True, is_over_limit=False, is_client_exception=True, is_conflict=False, plugin='ceilometer', exception=lambda: c_a_exc.NotFound(details='gone'), )), ('ceilometer_exception', dict( is_not_found=False, is_over_limit=False, is_client_exception=False, is_conflict=False, plugin='ceilometer', exception=lambda: Exception() )), ('ceilometer_overlimit', dict( is_not_found=False, is_over_limit=True, is_client_exception=True, is_conflict=False, plugin='ceilometer', exception=lambda: ceil_exc.HTTPOverLimit(details='over'), )), ('ceilometer_conflict', dict( is_not_found=False, is_over_limit=False, is_client_exception=True, is_conflict=True, plugin='ceilometer', exception=lambda: ceil_exc.HTTPConflict(), )), ('cinder_not_found', dict( is_not_found=True, is_over_limit=False, is_client_exception=True, is_conflict=False, plugin='cinder', exception=lambda: cinder_exc.NotFound(code=404), )), ('cinder_exception', dict( is_not_found=False, is_over_limit=False, is_client_exception=False, is_conflict=False, plugin='cinder', exception=lambda: Exception() )), ('cinder_overlimit', dict( is_not_found=False, is_over_limit=True, is_client_exception=True, is_conflict=False, plugin='cinder', exception=lambda: cinder_exc.OverLimit(code=413), )), ('cinder_conflict', dict( is_not_found=False, is_over_limit=False, is_client_exception=True, is_conflict=True, plugin='cinder', exception=lambda: cinder_exc.ClientException( code=409, message='conflict'), )), ('glance_not_found_1', dict( is_not_found=True, is_over_limit=False, is_client_exception=True, is_conflict=False, plugin='glance', exception=lambda: g_a_exc.NotFound(), )), ('glance_not_found_2', dict( is_not_found=True, is_over_limit=False, is_client_exception=True, is_conflict=False, plugin='glance', exception=lambda: glance_exc.HTTPNotFound(), )), ('glance_exception', dict( is_not_found=False, is_over_limit=False, is_client_exception=False, is_conflict=False, plugin='glance', exception=lambda: Exception() )), ('glance_overlimit', dict( is_not_found=False, is_over_limit=True, is_client_exception=True, is_conflict=False, plugin='glance', exception=lambda: glance_exc.HTTPOverLimit(details='over'), )), ('glance_conflict_1', dict( is_not_found=False, is_over_limit=False, is_client_exception=True, is_conflict=True, plugin='glance', exception=lambda: g_a_exc.Conflict(), )), ('glance_conflict_1', dict( is_not_found=False, is_over_limit=False, is_client_exception=True, is_conflict=True, plugin='glance', exception=lambda: glance_exc.Conflict(), )), ('heat_not_found', dict( is_not_found=True, is_over_limit=False, is_client_exception=True, is_conflict=False, plugin='heat', exception=lambda: heat_exc.HTTPNotFound(message='gone'), )), ('heat_exception', dict( is_not_found=False, is_over_limit=False, is_client_exception=False, is_conflict=False, plugin='heat', exception=lambda: Exception() )), ('heat_overlimit', dict( is_not_found=False, is_over_limit=True, is_client_exception=True, is_conflict=False, plugin='heat', exception=lambda: heat_exc.HTTPOverLimit(message='over'), )), ('heat_conflict', dict( is_not_found=False, is_over_limit=False, is_client_exception=True, is_conflict=True, plugin='heat', exception=lambda: heat_exc.HTTPConflict(), )), ('keystone_not_found', dict( is_not_found=True, is_over_limit=False, is_client_exception=True, is_conflict=False, plugin='keystone', exception=lambda: keystone_exc.NotFound(details='gone'), )), ('keystone_exception', dict( is_not_found=False, is_over_limit=False, is_client_exception=False, is_conflict=False, plugin='keystone', exception=lambda: Exception() )), ('keystone_overlimit', dict( is_not_found=False, is_over_limit=True, is_client_exception=True, is_conflict=False, plugin='keystone', exception=lambda: keystone_exc.RequestEntityTooLarge( details='over'), )), ('keystone_conflict', dict( is_not_found=False, is_over_limit=False, is_client_exception=True, is_conflict=True, plugin='keystone', exception=lambda: keystone_exc.Conflict( message='Conflict'), )), ('neutron_not_found', dict( is_not_found=True, is_over_limit=False, is_client_exception=True, is_conflict=False, plugin='neutron', exception=lambda: neutron_exc.NotFound, )), ('neutron_network_not_found', dict( is_not_found=True, is_over_limit=False, is_client_exception=True, is_conflict=False, plugin='neutron', exception=lambda: neutron_exc.NetworkNotFoundClient(), )), ('neutron_port_not_found', dict( is_not_found=True, is_over_limit=False, is_client_exception=True, is_conflict=False, plugin='neutron', exception=lambda: neutron_exc.PortNotFoundClient(), )), ('neutron_status_not_found', dict( is_not_found=True, is_over_limit=False, is_client_exception=True, is_conflict=False, plugin='neutron', exception=lambda: neutron_exc.NeutronClientException( status_code=404), )), ('neutron_exception', dict( is_not_found=False, is_over_limit=False, is_client_exception=False, is_conflict=False, plugin='neutron', exception=lambda: Exception() )), ('neutron_overlimit', dict( is_not_found=False, is_over_limit=True, is_client_exception=True, is_conflict=False, plugin='neutron', exception=lambda: neutron_exc.NeutronClientException( status_code=413), )), ('neutron_conflict', dict( is_not_found=False, is_over_limit=False, is_client_exception=True, is_conflict=True, plugin='neutron', exception=lambda: neutron_exc.Conflict(), )), ('nova_not_found', dict( is_not_found=True, is_over_limit=False, is_client_exception=True, is_conflict=False, is_unprocessable_entity=False, plugin='nova', exception=lambda: fakes_nova.fake_exception(), )), ('nova_exception', dict( is_not_found=False, is_over_limit=False, is_client_exception=False, is_conflict=False, is_unprocessable_entity=False, plugin='nova', exception=lambda: Exception() )), ('nova_overlimit', dict( is_not_found=False, is_over_limit=True, is_client_exception=True, is_conflict=False, is_unprocessable_entity=False, plugin='nova', exception=lambda: fakes_nova.fake_exception(413), )), ('nova_unprocessable_entity', dict( is_not_found=False, is_over_limit=False, is_client_exception=True, is_conflict=False, is_unprocessable_entity=True, plugin='nova', exception=lambda: fakes_nova.fake_exception(422), )), ('nova_conflict', dict( is_not_found=False, is_over_limit=False, is_client_exception=True, is_conflict=True, is_unprocessable_entity=False, plugin='nova', exception=lambda: fakes_nova.fake_exception(409), )), ('swift_not_found', dict( is_not_found=True, is_over_limit=False, is_client_exception=True, is_conflict=False, plugin='swift', exception=lambda: swift_exc.ClientException( msg='gone', http_status=404), )), ('swift_exception', dict( is_not_found=False, is_over_limit=False, is_client_exception=False, is_conflict=False, plugin='swift', exception=lambda: Exception() )), ('swift_overlimit', dict( is_not_found=False, is_over_limit=True, is_client_exception=True, is_conflict=False, plugin='swift', exception=lambda: swift_exc.ClientException( msg='ouch', http_status=413), )), ('swift_conflict', dict( is_not_found=False, is_over_limit=False, is_client_exception=True, is_conflict=True, plugin='swift', exception=lambda: swift_exc.ClientException( msg='conflict', http_status=409), )), ('trove_not_found', dict( is_not_found=True, is_over_limit=False, is_client_exception=True, is_conflict=False, plugin='trove', exception=lambda: troveclient.exceptions.NotFound(message='gone'), )), ('trove_exception', dict( is_not_found=False, is_over_limit=False, is_client_exception=False, is_conflict=False, plugin='trove', exception=lambda: Exception() )), ('trove_overlimit', dict( is_not_found=False, is_over_limit=True, is_client_exception=True, is_conflict=False, plugin='trove', exception=lambda: troveclient.exceptions.RequestEntityTooLarge( message='over'), )), ('trove_conflict', dict( is_not_found=False, is_over_limit=False, is_client_exception=True, is_conflict=True, plugin='trove', exception=lambda: troveclient.exceptions.Conflict( message='Conflict'), )), ('sahara_not_found', dict( is_not_found=True, is_over_limit=False, is_client_exception=True, is_conflict=False, plugin='sahara', exception=lambda: sahara_base.APIException( error_message='gone1', error_code=404), )), ('sahara_exception', dict( is_not_found=False, is_over_limit=False, is_client_exception=False, is_conflict=False, plugin='sahara', exception=lambda: Exception() )), ('sahara_overlimit', dict( is_not_found=False, is_over_limit=True, is_client_exception=True, is_conflict=False, plugin='sahara', exception=lambda: sahara_base.APIException( error_message='over1', error_code=413), )), ('sahara_conflict', dict( is_not_found=False, is_over_limit=False, is_client_exception=True, is_conflict=True, plugin='sahara', exception=lambda: sahara_base.APIException( error_message='conflict1', error_code=409), )), ('zaqar_not_found', dict( is_not_found=True, is_over_limit=False, is_client_exception=True, is_conflict=False, plugin='zaqar', exception=lambda: zaqar_exc.ResourceNotFound(), )), ('manila_not_found', dict( is_not_found=True, is_over_limit=False, is_client_exception=True, is_conflict=False, plugin='manila', exception=lambda: manila_exc.NotFound(), )), ('manila_exception', dict( is_not_found=False, is_over_limit=False, is_client_exception=False, is_conflict=False, plugin='manila', exception=lambda: Exception() )), ('manila_overlimit', dict( is_not_found=False, is_over_limit=True, is_client_exception=True, is_conflict=False, plugin='manila', exception=lambda: manila_exc.RequestEntityTooLarge(), )), ('manila_conflict', dict( is_not_found=False, is_over_limit=False, is_client_exception=True, is_conflict=True, plugin='manila', exception=lambda: manila_exc.Conflict(), )), ] def test_is_not_found(self): con = mock.Mock() c = clients.Clients(con) client_plugin = c.client_plugin(self.plugin) try: raise self.exception() except Exception as e: if self.is_not_found != client_plugin.is_not_found(e): raise def test_ignore_not_found(self): con = mock.Mock() c = clients.Clients(con) client_plugin = c.client_plugin(self.plugin) try: exp = self.exception() exp_class = exp.__class__ raise exp except Exception as e: if self.is_not_found: client_plugin.ignore_not_found(e) else: self.assertRaises(exp_class, client_plugin.ignore_not_found, e) def test_ignore_not_found_context_manager(self): con = mock.Mock() c = clients.Clients(con) client_plugin = c.client_plugin(self.plugin) exp = self.exception() exp_class = exp.__class__ def try_raise(): with client_plugin.ignore_not_found: raise exp if self.is_not_found: try_raise() else: self.assertRaises(exp_class, try_raise) def test_ignore_conflict_and_not_found(self): con = mock.Mock() c = clients.Clients(con) client_plugin = c.client_plugin(self.plugin) try: exp = self.exception() exp_class = exp.__class__ raise exp except Exception as e: if self.is_conflict or self.is_not_found: client_plugin.ignore_conflict_and_not_found(e) else: self.assertRaises(exp_class, client_plugin.ignore_conflict_and_not_found, e) def test_ignore_conflict_and_not_found_context_manager(self): con = mock.Mock() c = clients.Clients(con) client_plugin = c.client_plugin(self.plugin) exp = self.exception() exp_class = exp.__class__ def try_raise(): with client_plugin.ignore_conflict_and_not_found: raise exp if self.is_conflict or self.is_not_found: try_raise() else: self.assertRaises(exp_class, try_raise) def test_is_over_limit(self): con = mock.Mock() c = clients.Clients(con) client_plugin = c.client_plugin(self.plugin) try: raise self.exception() except Exception as e: if self.is_over_limit != client_plugin.is_over_limit(e): raise def test_is_client_exception(self): con = mock.Mock() c = clients.Clients(con) client_plugin = c.client_plugin(self.plugin) try: raise self.exception() except Exception as e: ice = self.is_client_exception actual = client_plugin.is_client_exception(e) if ice != actual: raise def test_is_conflict(self): con = mock.Mock() c = clients.Clients(con) client_plugin = c.client_plugin(self.plugin) try: raise self.exception() except Exception as e: if self.is_conflict != client_plugin.is_conflict(e): raise def test_is_unprocessable_entity(self): con = mock.Mock() c = clients.Clients(con) # only 'nova' client plugin need to check this exception if self.plugin == 'nova': client_plugin = c.client_plugin(self.plugin) try: raise self.exception() except Exception as e: iue = self.is_unprocessable_entity if iue != client_plugin.is_unprocessable_entity(e): raise class ClientAPIVersionTest(common.HeatTestCase): def test_cinder_api_v1_and_v2(self): self.stub_auth() ctx = utils.dummy_context() client = clients.Clients(ctx).client('cinder') self.assertEqual(2, client.volume_api_version) def test_cinder_api_v1_only(self): self.stub_auth(only_services=['volume']) ctx = utils.dummy_context() client = clients.Clients(ctx).client('cinder') self.assertEqual(1, client.volume_api_version) def test_cinder_api_v2_only(self): self.stub_auth(only_services=['volumev2']) ctx = utils.dummy_context() client = clients.Clients(ctx).client('cinder') self.assertEqual(2, client.volume_api_version)
"""Base class for sparse matrix formats using compressed storage.""" from __future__ import division, print_function, absolute_import __all__ = [] from warnings import warn import operator import numpy as np from scipy._lib.six import zip as izip, xrange from scipy._lib._util import _prune_array from .base import spmatrix, isspmatrix, SparseEfficiencyWarning from .data import _data_matrix, _minmax_mixin from .dia import dia_matrix from . import _sparsetools from ._sparsetools import (get_csr_submatrix, csr_sample_offsets, csr_todense, csr_sample_values, csr_row_index, csr_row_slice, csr_column_index1, csr_column_index2) from ._index import IndexMixin from .sputils import (upcast, upcast_char, to_native, isdense, isshape, getdtype, isscalarlike, isintlike, get_index_dtype, downcast_intp_index, get_sum_dtype, check_shape, matrix, asmatrix) class _cs_matrix(_data_matrix, _minmax_mixin, IndexMixin): """base matrix class for compressed row- and column-oriented matrices""" def __init__(self, arg1, shape=None, dtype=None, copy=False): _data_matrix.__init__(self) if isspmatrix(arg1): if arg1.format == self.format and copy: arg1 = arg1.copy() else: arg1 = arg1.asformat(self.format) self._set_self(arg1) elif isinstance(arg1, tuple): if isshape(arg1): # It's a tuple of matrix dimensions (M, N) # create empty matrix self._shape = check_shape(arg1) M, N = self.shape # Select index dtype large enough to pass array and # scalar parameters to sparsetools idx_dtype = get_index_dtype(maxval=max(M, N)) self.data = np.zeros(0, getdtype(dtype, default=float)) self.indices = np.zeros(0, idx_dtype) self.indptr = np.zeros(self._swap((M, N))[0] + 1, dtype=idx_dtype) else: if len(arg1) == 2: # (data, ij) format from .coo import coo_matrix other = self.__class__(coo_matrix(arg1, shape=shape)) self._set_self(other) elif len(arg1) == 3: # (data, indices, indptr) format (data, indices, indptr) = arg1 # Select index dtype large enough to pass array and # scalar parameters to sparsetools maxval = None if shape is not None: maxval = max(shape) idx_dtype = get_index_dtype((indices, indptr), maxval=maxval, check_contents=True) self.indices = np.array(indices, copy=copy, dtype=idx_dtype) self.indptr = np.array(indptr, copy=copy, dtype=idx_dtype) self.data = np.array(data, copy=copy, dtype=dtype) else: raise ValueError("unrecognized {}_matrix " "constructor usage".format(self.format)) else: # must be dense try: arg1 = np.asarray(arg1) except Exception: raise ValueError("unrecognized {}_matrix constructor usage" "".format(self.format)) from .coo import coo_matrix self._set_self(self.__class__(coo_matrix(arg1, dtype=dtype))) # Read matrix dimensions given, if any if shape is not None: self._shape = check_shape(shape) else: if self.shape is None: # shape not already set, try to infer dimensions try: major_dim = len(self.indptr) - 1 minor_dim = self.indices.max() + 1 except Exception: raise ValueError('unable to infer matrix dimensions') else: self._shape = check_shape(self._swap((major_dim, minor_dim))) if dtype is not None: self.data = np.asarray(self.data, dtype=dtype) self.check_format(full_check=False) def getnnz(self, axis=None): if axis is None: return int(self.indptr[-1]) else: if axis < 0: axis += 2 axis, _ = self._swap((axis, 1 - axis)) _, N = self._swap(self.shape) if axis == 0: return np.bincount(downcast_intp_index(self.indices), minlength=N) elif axis == 1: return np.diff(self.indptr) raise ValueError('axis out of bounds') getnnz.__doc__ = spmatrix.getnnz.__doc__ def _set_self(self, other, copy=False): """take the member variables of other and assign them to self""" if copy: other = other.copy() self.data = other.data self.indices = other.indices self.indptr = other.indptr self._shape = check_shape(other.shape) def check_format(self, full_check=True): """check whether the matrix format is valid Parameters ---------- full_check : bool, optional If `True`, rigorous check, O(N) operations. Otherwise basic check, O(1) operations (default True). """ # use _swap to determine proper bounds major_name, minor_name = self._swap(('row', 'column')) major_dim, minor_dim = self._swap(self.shape) # index arrays should have integer data types if self.indptr.dtype.kind != 'i': warn("indptr array has non-integer dtype ({})" "".format(self.indptr.dtype.name), stacklevel=3) if self.indices.dtype.kind != 'i': warn("indices array has non-integer dtype ({})" "".format(self.indices.dtype.name), stacklevel=3) idx_dtype = get_index_dtype((self.indptr, self.indices)) self.indptr = np.asarray(self.indptr, dtype=idx_dtype) self.indices = np.asarray(self.indices, dtype=idx_dtype) self.data = to_native(self.data) # check array shapes for x in [self.data.ndim, self.indices.ndim, self.indptr.ndim]: if x != 1: raise ValueError('data, indices, and indptr should be 1-D') # check index pointer if (len(self.indptr) != major_dim + 1): raise ValueError("index pointer size ({}) should be ({})" "".format(len(self.indptr), major_dim + 1)) if (self.indptr[0] != 0): raise ValueError("index pointer should start with 0") # check index and data arrays if (len(self.indices) != len(self.data)): raise ValueError("indices and data should have the same size") if (self.indptr[-1] > len(self.indices)): raise ValueError("Last value of index pointer should be less than " "the size of index and data arrays") self.prune() if full_check: # check format validity (more expensive) if self.nnz > 0: if self.indices.max() >= minor_dim: raise ValueError("{} index values must be < {}" "".format(minor_name, minor_dim)) if self.indices.min() < 0: raise ValueError("{} index values must be >= 0" "".format(minor_name)) if np.diff(self.indptr).min() < 0: raise ValueError("index pointer values must form a " "non-decreasing sequence") # if not self.has_sorted_indices(): # warn('Indices were not in sorted order. Sorting indices.') # self.sort_indices() # assert(self.has_sorted_indices()) # TODO check for duplicates? ####################### # Boolean comparisons # ####################### def _scalar_binopt(self, other, op): """Scalar version of self._binopt, for cases in which no new nonzeros are added. Produces a new spmatrix in canonical form. """ self.sum_duplicates() res = self._with_data(op(self.data, other), copy=True) res.eliminate_zeros() return res def __eq__(self, other): # Scalar other. if isscalarlike(other): if np.isnan(other): return self.__class__(self.shape, dtype=np.bool_) if other == 0: warn("Comparing a sparse matrix with 0 using == is inefficient" ", try using != instead.", SparseEfficiencyWarning, stacklevel=3) all_true = self.__class__(np.ones(self.shape, dtype=np.bool_)) inv = self._scalar_binopt(other, operator.ne) return all_true - inv else: return self._scalar_binopt(other, operator.eq) # Dense other. elif isdense(other): return self.todense() == other # Sparse other. elif isspmatrix(other): warn("Comparing sparse matrices using == is inefficient, try using" " != instead.", SparseEfficiencyWarning, stacklevel=3) # TODO sparse broadcasting if self.shape != other.shape: return False elif self.format != other.format: other = other.asformat(self.format) res = self._binopt(other, '_ne_') all_true = self.__class__(np.ones(self.shape, dtype=np.bool_)) return all_true - res else: return False def __ne__(self, other): # Scalar other. if isscalarlike(other): if np.isnan(other): warn("Comparing a sparse matrix with nan using != is" " inefficient", SparseEfficiencyWarning, stacklevel=3) all_true = self.__class__(np.ones(self.shape, dtype=np.bool_)) return all_true elif other != 0: warn("Comparing a sparse matrix with a nonzero scalar using !=" " is inefficient, try using == instead.", SparseEfficiencyWarning, stacklevel=3) all_true = self.__class__(np.ones(self.shape), dtype=np.bool_) inv = self._scalar_binopt(other, operator.eq) return all_true - inv else: return self._scalar_binopt(other, operator.ne) # Dense other. elif isdense(other): return self.todense() != other # Sparse other. elif isspmatrix(other): # TODO sparse broadcasting if self.shape != other.shape: return True elif self.format != other.format: other = other.asformat(self.format) return self._binopt(other, '_ne_') else: return True def _inequality(self, other, op, op_name, bad_scalar_msg): # Scalar other. if isscalarlike(other): if 0 == other and op_name in ('_le_', '_ge_'): raise NotImplementedError(" >= and <= don't work with 0.") elif op(0, other): warn(bad_scalar_msg, SparseEfficiencyWarning) other_arr = np.empty(self.shape, dtype=np.result_type(other)) other_arr.fill(other) other_arr = self.__class__(other_arr) return self._binopt(other_arr, op_name) else: return self._scalar_binopt(other, op) # Dense other. elif isdense(other): return op(self.todense(), other) # Sparse other. elif isspmatrix(other): # TODO sparse broadcasting if self.shape != other.shape: raise ValueError("inconsistent shapes") elif self.format != other.format: other = other.asformat(self.format) if op_name not in ('_ge_', '_le_'): return self._binopt(other, op_name) warn("Comparing sparse matrices using >= and <= is inefficient, " "using <, >, or !=, instead.", SparseEfficiencyWarning) all_true = self.__class__(np.ones(self.shape, dtype=np.bool_)) res = self._binopt(other, '_gt_' if op_name == '_le_' else '_lt_') return all_true - res else: raise ValueError("Operands could not be compared.") def __lt__(self, other): return self._inequality(other, operator.lt, '_lt_', "Comparing a sparse matrix with a scalar " "greater than zero using < is inefficient, " "try using >= instead.") def __gt__(self, other): return self._inequality(other, operator.gt, '_gt_', "Comparing a sparse matrix with a scalar " "less than zero using > is inefficient, " "try using <= instead.") def __le__(self, other): return self._inequality(other, operator.le, '_le_', "Comparing a sparse matrix with a scalar " "greater than zero using <= is inefficient, " "try using > instead.") def __ge__(self, other): return self._inequality(other, operator.ge, '_ge_', "Comparing a sparse matrix with a scalar " "less than zero using >= is inefficient, " "try using < instead.") ################################# # Arithmetic operator overrides # ################################# def _add_dense(self, other): if other.shape != self.shape: raise ValueError('Incompatible shapes.') dtype = upcast_char(self.dtype.char, other.dtype.char) order = self._swap('CF')[0] result = np.array(other, dtype=dtype, order=order, copy=True) M, N = self._swap(self.shape) y = result if result.flags.c_contiguous else result.T csr_todense(M, N, self.indptr, self.indices, self.data, y) return matrix(result, copy=False) def _add_sparse(self, other): return self._binopt(other, '_plus_') def _sub_sparse(self, other): return self._binopt(other, '_minus_') def multiply(self, other): """Point-wise multiplication by another matrix, vector, or scalar. """ # Scalar multiplication. if isscalarlike(other): return self._mul_scalar(other) # Sparse matrix or vector. if isspmatrix(other): if self.shape == other.shape: other = self.__class__(other) return self._binopt(other, '_elmul_') # Single element. elif other.shape == (1, 1): return self._mul_scalar(other.toarray()[0, 0]) elif self.shape == (1, 1): return other._mul_scalar(self.toarray()[0, 0]) # A row times a column. elif self.shape[1] == 1 and other.shape[0] == 1: return self._mul_sparse_matrix(other.tocsc()) elif self.shape[0] == 1 and other.shape[1] == 1: return other._mul_sparse_matrix(self.tocsc()) # Row vector times matrix. other is a row. elif other.shape[0] == 1 and self.shape[1] == other.shape[1]: other = dia_matrix((other.toarray().ravel(), [0]), shape=(other.shape[1], other.shape[1])) return self._mul_sparse_matrix(other) # self is a row. elif self.shape[0] == 1 and self.shape[1] == other.shape[1]: copy = dia_matrix((self.toarray().ravel(), [0]), shape=(self.shape[1], self.shape[1])) return other._mul_sparse_matrix(copy) # Column vector times matrix. other is a column. elif other.shape[1] == 1 and self.shape[0] == other.shape[0]: other = dia_matrix((other.toarray().ravel(), [0]), shape=(other.shape[0], other.shape[0])) return other._mul_sparse_matrix(self) # self is a column. elif self.shape[1] == 1 and self.shape[0] == other.shape[0]: copy = dia_matrix((self.toarray().ravel(), [0]), shape=(self.shape[0], self.shape[0])) return copy._mul_sparse_matrix(other) else: raise ValueError("inconsistent shapes") # Assume other is a dense matrix/array, which produces a single-item # object array if other isn't convertible to ndarray. other = np.atleast_2d(other) if other.ndim != 2: return np.multiply(self.toarray(), other) # Single element / wrapped object. if other.size == 1: return self._mul_scalar(other.flat[0]) # Fast case for trivial sparse matrix. elif self.shape == (1, 1): return np.multiply(self.toarray()[0, 0], other) from .coo import coo_matrix ret = self.tocoo() # Matching shapes. if self.shape == other.shape: data = np.multiply(ret.data, other[ret.row, ret.col]) # Sparse row vector times... elif self.shape[0] == 1: if other.shape[1] == 1: # Dense column vector. data = np.multiply(ret.data, other) elif other.shape[1] == self.shape[1]: # Dense matrix. data = np.multiply(ret.data, other[:, ret.col]) else: raise ValueError("inconsistent shapes") row = np.repeat(np.arange(other.shape[0]), len(ret.row)) col = np.tile(ret.col, other.shape[0]) return coo_matrix((data.view(np.ndarray).ravel(), (row, col)), shape=(other.shape[0], self.shape[1]), copy=False) # Sparse column vector times... elif self.shape[1] == 1: if other.shape[0] == 1: # Dense row vector. data = np.multiply(ret.data[:, None], other) elif other.shape[0] == self.shape[0]: # Dense matrix. data = np.multiply(ret.data[:, None], other[ret.row]) else: raise ValueError("inconsistent shapes") row = np.repeat(ret.row, other.shape[1]) col = np.tile(np.arange(other.shape[1]), len(ret.col)) return coo_matrix((data.view(np.ndarray).ravel(), (row, col)), shape=(self.shape[0], other.shape[1]), copy=False) # Sparse matrix times dense row vector. elif other.shape[0] == 1 and self.shape[1] == other.shape[1]: data = np.multiply(ret.data, other[:, ret.col].ravel()) # Sparse matrix times dense column vector. elif other.shape[1] == 1 and self.shape[0] == other.shape[0]: data = np.multiply(ret.data, other[ret.row].ravel()) else: raise ValueError("inconsistent shapes") ret.data = data.view(np.ndarray).ravel() return ret ########################### # Multiplication handlers # ########################### def _mul_vector(self, other): M, N = self.shape # output array result = np.zeros(M, dtype=upcast_char(self.dtype.char, other.dtype.char)) # csr_matvec or csc_matvec fn = getattr(_sparsetools, self.format + '_matvec') fn(M, N, self.indptr, self.indices, self.data, other, result) return result def _mul_multivector(self, other): M, N = self.shape n_vecs = other.shape[1] # number of column vectors result = np.zeros((M, n_vecs), dtype=upcast_char(self.dtype.char, other.dtype.char)) # csr_matvecs or csc_matvecs fn = getattr(_sparsetools, self.format + '_matvecs') fn(M, N, n_vecs, self.indptr, self.indices, self.data, other.ravel(), result.ravel()) return result def _mul_sparse_matrix(self, other): M, K1 = self.shape K2, N = other.shape major_axis = self._swap((M, N))[0] other = self.__class__(other) # convert to this format idx_dtype = get_index_dtype((self.indptr, self.indices, other.indptr, other.indices), maxval=M*N) indptr = np.empty(major_axis + 1, dtype=idx_dtype) fn = getattr(_sparsetools, self.format + '_matmat_pass1') fn(M, N, np.asarray(self.indptr, dtype=idx_dtype), np.asarray(self.indices, dtype=idx_dtype), np.asarray(other.indptr, dtype=idx_dtype), np.asarray(other.indices, dtype=idx_dtype), indptr) nnz = indptr[-1] idx_dtype = get_index_dtype((self.indptr, self.indices, other.indptr, other.indices), maxval=nnz) indptr = np.asarray(indptr, dtype=idx_dtype) indices = np.empty(nnz, dtype=idx_dtype) data = np.empty(nnz, dtype=upcast(self.dtype, other.dtype)) fn = getattr(_sparsetools, self.format + '_matmat_pass2') fn(M, N, np.asarray(self.indptr, dtype=idx_dtype), np.asarray(self.indices, dtype=idx_dtype), self.data, np.asarray(other.indptr, dtype=idx_dtype), np.asarray(other.indices, dtype=idx_dtype), other.data, indptr, indices, data) return self.__class__((data, indices, indptr), shape=(M, N)) def diagonal(self, k=0): rows, cols = self.shape if k <= -rows or k >= cols: raise ValueError("k exceeds matrix dimensions") fn = getattr(_sparsetools, self.format + "_diagonal") y = np.empty(min(rows + min(k, 0), cols - max(k, 0)), dtype=upcast(self.dtype)) fn(k, self.shape[0], self.shape[1], self.indptr, self.indices, self.data, y) return y diagonal.__doc__ = spmatrix.diagonal.__doc__ ##################### # Other binary ops # ##################### def _maximum_minimum(self, other, npop, op_name, dense_check): if isscalarlike(other): if dense_check(other): warn("Taking maximum (minimum) with > 0 (< 0) number results" " to a dense matrix.", SparseEfficiencyWarning, stacklevel=3) other_arr = np.empty(self.shape, dtype=np.asarray(other).dtype) other_arr.fill(other) other_arr = self.__class__(other_arr) return self._binopt(other_arr, op_name) else: self.sum_duplicates() new_data = npop(self.data, np.asarray(other)) mat = self.__class__((new_data, self.indices, self.indptr), dtype=new_data.dtype, shape=self.shape) return mat elif isdense(other): return npop(self.todense(), other) elif isspmatrix(other): return self._binopt(other, op_name) else: raise ValueError("Operands not compatible.") def maximum(self, other): return self._maximum_minimum(other, np.maximum, '_maximum_', lambda x: np.asarray(x) > 0) maximum.__doc__ = spmatrix.maximum.__doc__ def minimum(self, other): return self._maximum_minimum(other, np.minimum, '_minimum_', lambda x: np.asarray(x) < 0) minimum.__doc__ = spmatrix.minimum.__doc__ ##################### # Reduce operations # ##################### def sum(self, axis=None, dtype=None, out=None): """Sum the matrix over the given axis. If the axis is None, sum over both rows and columns, returning a scalar. """ # The spmatrix base class already does axis=0 and axis=1 efficiently # so we only do the case axis=None here if (not hasattr(self, 'blocksize') and axis in self._swap(((1, -1), (0, 2)))[0]): # faster than multiplication for large minor axis in CSC/CSR res_dtype = get_sum_dtype(self.dtype) ret = np.zeros(len(self.indptr) - 1, dtype=res_dtype) major_index, value = self._minor_reduce(np.add) ret[major_index] = value ret = asmatrix(ret) if axis % 2 == 1: ret = ret.T if out is not None and out.shape != ret.shape: raise ValueError('dimensions do not match') return ret.sum(axis=(), dtype=dtype, out=out) # spmatrix will handle the remaining situations when axis # is in {None, -1, 0, 1} else: return spmatrix.sum(self, axis=axis, dtype=dtype, out=out) sum.__doc__ = spmatrix.sum.__doc__ def _minor_reduce(self, ufunc, data=None): """Reduce nonzeros with a ufunc over the minor axis when non-empty Can be applied to a function of self.data by supplying data parameter. Warning: this does not call sum_duplicates() Returns ------- major_index : array of ints Major indices where nonzero value : array of self.dtype Reduce result for nonzeros in each major_index """ if data is None: data = self.data major_index = np.flatnonzero(np.diff(self.indptr)) value = ufunc.reduceat(data, downcast_intp_index(self.indptr[major_index])) return major_index, value ####################### # Getting and Setting # ####################### def _get_intXint(self, row, col): M, N = self._swap(self.shape) major, minor = self._swap((row, col)) indptr, indices, data = get_csr_submatrix( M, N, self.indptr, self.indices, self.data, major, major + 1, minor, minor + 1) return data.sum(dtype=self.dtype) def _get_sliceXslice(self, row, col): major, minor = self._swap((row, col)) if major.step in (1, None) and minor.step in (1, None): return self._get_submatrix(major, minor, copy=True) return self._major_slice(major)._minor_slice(minor) def _get_arrayXarray(self, row, col): # inner indexing idx_dtype = self.indices.dtype M, N = self._swap(self.shape) major, minor = self._swap((row, col)) major = np.asarray(major, dtype=idx_dtype) minor = np.asarray(minor, dtype=idx_dtype) val = np.empty(major.size, dtype=self.dtype) csr_sample_values(M, N, self.indptr, self.indices, self.data, major.size, major.ravel(), minor.ravel(), val) if major.ndim == 1: return asmatrix(val) return self.__class__(val.reshape(major.shape)) def _get_columnXarray(self, row, col): # outer indexing major, minor = self._swap((row, col)) return self._major_index_fancy(major)._minor_index_fancy(minor) def _major_index_fancy(self, idx): """Index along the major axis where idx is an array of ints. """ idx_dtype = self.indices.dtype indices = np.asarray(idx, dtype=idx_dtype).ravel() _, N = self._swap(self.shape) M = len(indices) new_shape = self._swap((M, N)) if M == 0: return self.__class__(new_shape) row_nnz = np.diff(self.indptr) idx_dtype = self.indices.dtype res_indptr = np.zeros(M+1, dtype=idx_dtype) np.cumsum(row_nnz[idx], out=res_indptr[1:]) nnz = res_indptr[-1] res_indices = np.empty(nnz, dtype=idx_dtype) res_data = np.empty(nnz, dtype=self.dtype) csr_row_index(M, indices, self.indptr, self.indices, self.data, res_indices, res_data) return self.__class__((res_data, res_indices, res_indptr), shape=new_shape, copy=False) def _major_slice(self, idx, copy=False): """Index along the major axis where idx is a slice object. """ if idx == slice(None): return self.copy() if copy else self M, N = self._swap(self.shape) start, stop, step = idx.indices(M) M = len(xrange(start, stop, step)) new_shape = self._swap((M, N)) if M == 0: return self.__class__(new_shape) row_nnz = np.diff(self.indptr) idx_dtype = self.indices.dtype res_indptr = np.zeros(M+1, dtype=idx_dtype) np.cumsum(row_nnz[idx], out=res_indptr[1:]) if step == 1: all_idx = slice(self.indptr[start], self.indptr[stop]) res_indices = np.array(self.indices[all_idx], copy=copy) res_data = np.array(self.data[all_idx], copy=copy) else: nnz = res_indptr[-1] res_indices = np.empty(nnz, dtype=idx_dtype) res_data = np.empty(nnz, dtype=self.dtype) csr_row_slice(start, stop, step, self.indptr, self.indices, self.data, res_indices, res_data) return self.__class__((res_data, res_indices, res_indptr), shape=new_shape, copy=False) def _minor_index_fancy(self, idx): """Index along the minor axis where idx is an array of ints. """ idx_dtype = self.indices.dtype idx = np.asarray(idx, dtype=idx_dtype).ravel() M, N = self._swap(self.shape) k = len(idx) new_shape = self._swap((M, k)) if k == 0: return self.__class__(new_shape) # pass 1: count idx entries and compute new indptr col_offsets = np.zeros(N, dtype=idx_dtype) res_indptr = np.empty_like(self.indptr) csr_column_index1(k, idx, M, N, self.indptr, self.indices, col_offsets, res_indptr) # pass 2: copy indices/data for selected idxs col_order = np.argsort(idx).astype(idx_dtype, copy=False) nnz = res_indptr[-1] res_indices = np.empty(nnz, dtype=idx_dtype) res_data = np.empty(nnz, dtype=self.dtype) csr_column_index2(col_order, col_offsets, len(self.indices), self.indices, self.data, res_indices, res_data) return self.__class__((res_data, res_indices, res_indptr), shape=new_shape, copy=False) def _minor_slice(self, idx, copy=False): """Index along the minor axis where idx is a slice object. """ if idx == slice(None): return self.copy() if copy else self M, N = self._swap(self.shape) start, stop, step = idx.indices(N) N = len(xrange(start, stop, step)) if N == 0: return self.__class__(self._swap((M, N))) if step == 1: return self._get_submatrix(minor=idx, copy=copy) # TODO: don't fall back to fancy indexing here return self._minor_index_fancy(np.arange(start, stop, step)) def _get_submatrix(self, major=None, minor=None, copy=False): """Return a submatrix of this matrix. major, minor: None, int, or slice with step 1 """ M, N = self._swap(self.shape) i0, i1 = _process_slice(major, M) j0, j1 = _process_slice(minor, N) if i0 == 0 and j0 == 0 and i1 == M and j1 == N: return self.copy() if copy else self indptr, indices, data = get_csr_submatrix( M, N, self.indptr, self.indices, self.data, i0, i1, j0, j1) shape = self._swap((i1 - i0, j1 - j0)) return self.__class__((data, indices, indptr), shape=shape, dtype=self.dtype, copy=False) def _set_intXint(self, row, col, x): i, j = self._swap((row, col)) self._set_many(i, j, x) def _set_arrayXarray(self, row, col, x): i, j = self._swap((row, col)) self._set_many(i, j, x) def _set_arrayXarray_sparse(self, row, col, x): # clear entries that will be overwritten self._zero_many(*self._swap((row, col))) M, N = row.shape # matches col.shape broadcast_row = M != 1 and x.shape[0] == 1 broadcast_col = N != 1 and x.shape[1] == 1 r, c = x.row, x.col x = np.asarray(x.data, dtype=self.dtype) if broadcast_row: r = np.repeat(np.arange(M), len(r)) c = np.tile(c, M) x = np.tile(x, M) if broadcast_col: r = np.repeat(r, N) c = np.tile(np.arange(N), len(c)) x = np.repeat(x, N) # only assign entries in the new sparsity structure i, j = self._swap((row[r, c], col[r, c])) self._set_many(i, j, x) def _setdiag(self, values, k): if 0 in self.shape: return M, N = self.shape broadcast = (values.ndim == 0) if k < 0: if broadcast: max_index = min(M + k, N) else: max_index = min(M + k, N, len(values)) i = np.arange(max_index, dtype=self.indices.dtype) j = np.arange(max_index, dtype=self.indices.dtype) i -= k else: if broadcast: max_index = min(M, N - k) else: max_index = min(M, N - k, len(values)) i = np.arange(max_index, dtype=self.indices.dtype) j = np.arange(max_index, dtype=self.indices.dtype) j += k if not broadcast: values = values[:len(i)] self[i, j] = values def _prepare_indices(self, i, j): M, N = self._swap(self.shape) def check_bounds(indices, bound): idx = indices.max() if idx >= bound: raise IndexError('index (%d) out of range (>= %d)' % (idx, bound)) idx = indices.min() if idx < -bound: raise IndexError('index (%d) out of range (< -%d)' % (idx, bound)) i = np.array(i, dtype=self.indices.dtype, copy=False, ndmin=1).ravel() j = np.array(j, dtype=self.indices.dtype, copy=False, ndmin=1).ravel() check_bounds(i, M) check_bounds(j, N) return i, j, M, N def _set_many(self, i, j, x): """Sets value at each (i, j) to x Here (i,j) index major and minor respectively, and must not contain duplicate entries. """ i, j, M, N = self._prepare_indices(i, j) x = np.array(x, dtype=self.dtype, copy=False, ndmin=1).ravel() n_samples = x.size offsets = np.empty(n_samples, dtype=self.indices.dtype) ret = csr_sample_offsets(M, N, self.indptr, self.indices, n_samples, i, j, offsets) if ret == 1: # rinse and repeat self.sum_duplicates() csr_sample_offsets(M, N, self.indptr, self.indices, n_samples, i, j, offsets) if -1 not in offsets: # only affects existing non-zero cells self.data[offsets] = x return else: warn("Changing the sparsity structure of a {}_matrix is expensive." " lil_matrix is more efficient.".format(self.format), SparseEfficiencyWarning, stacklevel=3) # replace where possible mask = offsets > -1 self.data[offsets[mask]] = x[mask] # only insertions remain mask = ~mask i = i[mask] i[i < 0] += M j = j[mask] j[j < 0] += N self._insert_many(i, j, x[mask]) def _zero_many(self, i, j): """Sets value at each (i, j) to zero, preserving sparsity structure. Here (i,j) index major and minor respectively. """ i, j, M, N = self._prepare_indices(i, j) n_samples = len(i) offsets = np.empty(n_samples, dtype=self.indices.dtype) ret = csr_sample_offsets(M, N, self.indptr, self.indices, n_samples, i, j, offsets) if ret == 1: # rinse and repeat self.sum_duplicates() csr_sample_offsets(M, N, self.indptr, self.indices, n_samples, i, j, offsets) # only assign zeros to the existing sparsity structure self.data[offsets[offsets > -1]] = 0 def _insert_many(self, i, j, x): """Inserts new nonzero at each (i, j) with value x Here (i,j) index major and minor respectively. i, j and x must be non-empty, 1d arrays. Inserts each major group (e.g. all entries per row) at a time. Maintains has_sorted_indices property. Modifies i, j, x in place. """ order = np.argsort(i, kind='mergesort') # stable for duplicates i = i.take(order, mode='clip') j = j.take(order, mode='clip') x = x.take(order, mode='clip') do_sort = self.has_sorted_indices # Update index data type idx_dtype = get_index_dtype((self.indices, self.indptr), maxval=(self.indptr[-1] + x.size)) self.indptr = np.asarray(self.indptr, dtype=idx_dtype) self.indices = np.asarray(self.indices, dtype=idx_dtype) i = np.asarray(i, dtype=idx_dtype) j = np.asarray(j, dtype=idx_dtype) # Collate old and new in chunks by major index indices_parts = [] data_parts = [] ui, ui_indptr = np.unique(i, return_index=True) ui_indptr = np.append(ui_indptr, len(j)) new_nnzs = np.diff(ui_indptr) prev = 0 for c, (ii, js, je) in enumerate(izip(ui, ui_indptr, ui_indptr[1:])): # old entries start = self.indptr[prev] stop = self.indptr[ii] indices_parts.append(self.indices[start:stop]) data_parts.append(self.data[start:stop]) # handle duplicate j: keep last setting uj, uj_indptr = np.unique(j[js:je][::-1], return_index=True) if len(uj) == je - js: indices_parts.append(j[js:je]) data_parts.append(x[js:je]) else: indices_parts.append(j[js:je][::-1][uj_indptr]) data_parts.append(x[js:je][::-1][uj_indptr]) new_nnzs[c] = len(uj) prev = ii # remaining old entries start = self.indptr[ii] indices_parts.append(self.indices[start:]) data_parts.append(self.data[start:]) # update attributes self.indices = np.concatenate(indices_parts) self.data = np.concatenate(data_parts) nnzs = np.empty(self.indptr.shape, dtype=idx_dtype) nnzs[0] = idx_dtype(0) indptr_diff = np.diff(self.indptr) indptr_diff[ui] += new_nnzs nnzs[1:] = indptr_diff self.indptr = np.cumsum(nnzs, out=nnzs) if do_sort: # TODO: only sort where necessary self.has_sorted_indices = False self.sort_indices() self.check_format(full_check=False) ###################### # Conversion methods # ###################### def tocoo(self, copy=True): major_dim, minor_dim = self._swap(self.shape) minor_indices = self.indices major_indices = np.empty(len(minor_indices), dtype=self.indices.dtype) _sparsetools.expandptr(major_dim, self.indptr, major_indices) row, col = self._swap((major_indices, minor_indices)) from .coo import coo_matrix return coo_matrix((self.data, (row, col)), self.shape, copy=copy, dtype=self.dtype) tocoo.__doc__ = spmatrix.tocoo.__doc__ def toarray(self, order=None, out=None): if out is None and order is None: order = self._swap('cf')[0] out = self._process_toarray_args(order, out) if not (out.flags.c_contiguous or out.flags.f_contiguous): raise ValueError('Output array must be C or F contiguous') # align ideal order with output array order if out.flags.c_contiguous: x = self.tocsr() y = out else: x = self.tocsc() y = out.T M, N = x._swap(x.shape) csr_todense(M, N, x.indptr, x.indices, x.data, y) return out toarray.__doc__ = spmatrix.toarray.__doc__ ############################################################## # methods that examine or modify the internal data structure # ############################################################## def eliminate_zeros(self): """Remove zero entries from the matrix This is an *in place* operation """ M, N = self._swap(self.shape) _sparsetools.csr_eliminate_zeros(M, N, self.indptr, self.indices, self.data) self.prune() # nnz may have changed def __get_has_canonical_format(self): """Determine whether the matrix has sorted indices and no duplicates Returns - True: if the above applies - False: otherwise has_canonical_format implies has_sorted_indices, so if the latter flag is False, so will the former be; if the former is found True, the latter flag is also set. """ # first check to see if result was cached if not getattr(self, '_has_sorted_indices', True): # not sorted => not canonical self._has_canonical_format = False elif not hasattr(self, '_has_canonical_format'): self.has_canonical_format = _sparsetools.csr_has_canonical_format( len(self.indptr) - 1, self.indptr, self.indices) return self._has_canonical_format def __set_has_canonical_format(self, val): self._has_canonical_format = bool(val) if val: self.has_sorted_indices = True has_canonical_format = property(fget=__get_has_canonical_format, fset=__set_has_canonical_format) def sum_duplicates(self): """Eliminate duplicate matrix entries by adding them together The is an *in place* operation """ if self.has_canonical_format: return self.sort_indices() M, N = self._swap(self.shape) _sparsetools.csr_sum_duplicates(M, N, self.indptr, self.indices, self.data) self.prune() # nnz may have changed self.has_canonical_format = True def __get_sorted(self): """Determine whether the matrix has sorted indices Returns - True: if the indices of the matrix are in sorted order - False: otherwise """ # first check to see if result was cached if not hasattr(self, '_has_sorted_indices'): self._has_sorted_indices = _sparsetools.csr_has_sorted_indices( len(self.indptr) - 1, self.indptr, self.indices) return self._has_sorted_indices def __set_sorted(self, val): self._has_sorted_indices = bool(val) has_sorted_indices = property(fget=__get_sorted, fset=__set_sorted) def sorted_indices(self): """Return a copy of this matrix with sorted indices """ A = self.copy() A.sort_indices() return A # an alternative that has linear complexity is the following # although the previous option is typically faster # return self.toother().toother() def sort_indices(self): """Sort the indices of this matrix *in place* """ if not self.has_sorted_indices: _sparsetools.csr_sort_indices(len(self.indptr) - 1, self.indptr, self.indices, self.data) self.has_sorted_indices = True def prune(self): """Remove empty space after all non-zero elements. """ major_dim = self._swap(self.shape)[0] if len(self.indptr) != major_dim + 1: raise ValueError('index pointer has invalid length') if len(self.indices) < self.nnz: raise ValueError('indices array has fewer than nnz elements') if len(self.data) < self.nnz: raise ValueError('data array has fewer than nnz elements') self.indices = _prune_array(self.indices[:self.nnz]) self.data = _prune_array(self.data[:self.nnz]) def resize(self, *shape): shape = check_shape(shape) if hasattr(self, 'blocksize'): bm, bn = self.blocksize new_M, rm = divmod(shape[0], bm) new_N, rn = divmod(shape[1], bn) if rm or rn: raise ValueError("shape must be divisible into %s blocks. " "Got %s" % (self.blocksize, shape)) M, N = self.shape[0] // bm, self.shape[1] // bn else: new_M, new_N = self._swap(shape) M, N = self._swap(self.shape) if new_M < M: self.indices = self.indices[:self.indptr[new_M]] self.data = self.data[:self.indptr[new_M]] self.indptr = self.indptr[:new_M + 1] elif new_M > M: self.indptr = np.resize(self.indptr, new_M + 1) self.indptr[M + 1:].fill(self.indptr[M]) if new_N < N: mask = self.indices < new_N if not np.all(mask): self.indices = self.indices[mask] self.data = self.data[mask] major_index, val = self._minor_reduce(np.add, mask) self.indptr.fill(0) self.indptr[1:][major_index] = val np.cumsum(self.indptr, out=self.indptr) self._shape = shape resize.__doc__ = spmatrix.resize.__doc__ ################### # utility methods # ################### # needed by _data_matrix def _with_data(self, data, copy=True): """Returns a matrix with the same sparsity structure as self, but with different data. By default the structure arrays (i.e. .indptr and .indices) are copied. """ if copy: return self.__class__((data, self.indices.copy(), self.indptr.copy()), shape=self.shape, dtype=data.dtype) else: return self.__class__((data, self.indices, self.indptr), shape=self.shape, dtype=data.dtype) def _binopt(self, other, op): """apply the binary operation fn to two sparse matrices.""" other = self.__class__(other) # e.g. csr_plus_csr, csr_minus_csr, etc. fn = getattr(_sparsetools, self.format + op + self.format) maxnnz = self.nnz + other.nnz idx_dtype = get_index_dtype((self.indptr, self.indices, other.indptr, other.indices), maxval=maxnnz) indptr = np.empty(self.indptr.shape, dtype=idx_dtype) indices = np.empty(maxnnz, dtype=idx_dtype) bool_ops = ['_ne_', '_lt_', '_gt_', '_le_', '_ge_'] if op in bool_ops: data = np.empty(maxnnz, dtype=np.bool_) else: data = np.empty(maxnnz, dtype=upcast(self.dtype, other.dtype)) fn(self.shape[0], self.shape[1], np.asarray(self.indptr, dtype=idx_dtype), np.asarray(self.indices, dtype=idx_dtype), self.data, np.asarray(other.indptr, dtype=idx_dtype), np.asarray(other.indices, dtype=idx_dtype), other.data, indptr, indices, data) A = self.__class__((data, indices, indptr), shape=self.shape) A.prune() return A def _divide_sparse(self, other): """ Divide this matrix by a second sparse matrix. """ if other.shape != self.shape: raise ValueError('inconsistent shapes') r = self._binopt(other, '_eldiv_') if np.issubdtype(r.dtype, np.inexact): # Eldiv leaves entries outside the combined sparsity # pattern empty, so they must be filled manually. # Everything outside of other's sparsity is NaN, and everything # inside it is either zero or defined by eldiv. out = np.empty(self.shape, dtype=self.dtype) out.fill(np.nan) row, col = other.nonzero() out[row, col] = 0 r = r.tocoo() out[r.row, r.col] = r.data out = matrix(out) else: # integers types go with nan <-> 0 out = r return out def _process_slice(sl, num): if sl is None: i0, i1 = 0, num elif isinstance(sl, slice): i0, i1, stride = sl.indices(num) if stride != 1: raise ValueError('slicing with step != 1 not supported') i0 = min(i0, i1) # give an empty slice when i0 > i1 elif isintlike(sl): if sl < 0: sl += num i0, i1 = sl, sl + 1 if i0 < 0 or i1 > num: raise IndexError('index out of bounds: 0 <= %d < %d <= %d' % (i0, i1, num)) else: raise TypeError('expected slice or scalar') return i0, i1
import os import unittest import tempfile from diff_rulekeys import * class MockFile(object): def __init__(self, lines): self._lines = lines def readlines(self): return self._lines class TestRuleKeyDiff(unittest.TestCase): def test_key_value_diff(self): list_diff = KeyValueDiff() list_diff.append('l', 'r') self.assertEqual(list_diff.diff(), ['-[l]', '+[r]']) def test_key_value_diff_with_common_elements(self): list_diff = KeyValueDiff() l = ['a', 'b', 'c'] r = ['b', 'd', 'c'] for l, r in map(None, l, r): list_diff.append(l, r) self.assertEqual(list_diff.diff(), ['-[a]', '+[d]']) def test_key_value_diff_with_common_elements_and_sort_issue(self): list_diff = KeyValueDiff() l = ['a', 'b', 'c'] r = ['c', 'd', 'b'] for l, r in map(None, l, r): list_diff.append(l, r) self.assertEqual( list_diff.diff(), ['-[a]', '+[d]', 'Only order of remaining entries differs: [b, c] vs [c, b].']) def test_key_value_diff_with_common_elements_repetitions(self): list_diff = KeyValueDiff() l = ['a', 'b', 'b', 'c'] r = ['c', 'b', 'b', 'b'] for l, r in map(None, l, r): list_diff.append(l, r) self.assertEqual( list_diff.diff(), ['-[a]', 'Order and repetition count of remaining entries differs: ' + '[b, c] vs [c, b, b].']) def test_key_value_diff_sort(self): list_diff = KeyValueDiff() list_diff.append('1', '2') list_diff.append('2', '1') self.assertEqual( list_diff.diff(), ["Only order of entries differs: [1, 2] vs [2, 1]."]) def test_key_value_diff_case(self): list_diff = KeyValueDiff() list_diff.append('B', 'a') list_diff.append('a', 'b') self.assertEqual( list_diff.diff(), ["Only order and letter casing (Upper Case vs lower case) of " + "entries differs:", '-[B]', '+[b]']) def test_key_value_diff_paths(self): list_diff = KeyValueDiff() list_diff.append('path(a.java:123)', 'path(a.java:322)') list_diff.append('path(C.java:123)', 'path(c.java:123)') list_diff.diff() self.assertEqual( set(list_diff.getInterestingPaths()), set(['a.java', 'c.java', 'C.java'])) def test_structure_info(self): line = ("[v] RuleKey 00aa=string(\"//:rule\"):key(name):" + "number(1):key(version):string(\"Rule\"):key(buck.type):") info = RuleKeyStructureInfo(MockFile([line])) self.assertEqual(info.getNameForKey("00aa"), "//:rule") def test_structure_info_list(self): line = ("[v] RuleKey 00aa=string(\"//:rule\"):key(name):" + "number(1):key(version):string(\"Rule\"):key(buck.type):" + "number(1):key(num):number(2):key(num):") info = RuleKeyStructureInfo(MockFile([line])) self.assertEqual( info.getByKey("00aa")['num'], ["number(2)", "number(1)"]) def test_simple_diff(self): name = "//:lib" result = diff(name, RuleKeyStructureInfo(MockFile([ makeRuleKeyLine( name=name, key="aabb", srcs={'JavaLib1.java': 'aabb'} ), ])), RuleKeyStructureInfo(MockFile([ makeRuleKeyLine( name=name, key="cabb", srcs={'JavaLib1.java': 'cabb'} ), ])), verbose=False) expected = [ 'Change details for [//:lib]', ' (srcs):', ' -[path(JavaLib1.java:aabb)]', ' +[path(JavaLib1.java:cabb)]'] self.assertEqual(result, expected) def test_diff_deps_order(self): result = diff("//:top", RuleKeyStructureInfo(MockFile([ makeRuleKeyLine( name="//:top", key="aa", deps=["00", "10"], ), makeRuleKeyLine( name="//:Zero", key="00", srcs={"Zero": "0"} ), makeRuleKeyLine( name="//:One", key="10", srcs={"One": "0"} ), ])), RuleKeyStructureInfo(MockFile([ makeRuleKeyLine( name="//:top", key="bb", deps=["11", "01"], ), makeRuleKeyLine( name="//:Zero", key="01", srcs={"Zero": "0"} ), makeRuleKeyLine( name="//:One", key="11", srcs={"One": "1"} ), ])), verbose=False) expected = [ 'Change details for [//:top]', ' (deps): order of deps was name-aligned.', 'Change details for [//:One]', ' (srcs):', ' -[path(One:0)]', ' +[path(One:1)]', ] self.assertEqual(result, expected) def test_diff_deps_count(self): result = diff("//:top", RuleKeyStructureInfo(MockFile([ makeRuleKeyLine( name="//:top", key="aa", deps=["00"], ), makeRuleKeyLine( name="//:Zero", key="00", srcs={"Zero": "0"} ), ])), RuleKeyStructureInfo(MockFile([ makeRuleKeyLine( name="//:top", key="bb", deps=["11", "01"], ), makeRuleKeyLine( name="//:Zero", key="01", srcs={"Zero": "0"} ), makeRuleKeyLine( name="//:One", key="11", srcs={"One": "1"} ), ])), verbose=False) expected = [ 'Change details for [//:top]', ' (deps):', ' -[<missing>]', ' +["//:One"@ruleKey(sha1=11)]', ] self.assertEqual(result, expected) def test_simple_diff_with_custom_names(self): line = ("[v] RuleKey {key}=string(\"//:lib\"):key(name):" + "path(JavaLib1.java:{hash}):key(srcs):" + "string(\"t\"):key(buck.type):") left_line = line.format(key="aabb", hash="ll") right_line = line.format(key="aabb", hash="rr") result = diff("//:lib", RuleKeyStructureInfo(MockFile([left_line])), RuleKeyStructureInfo(MockFile([right_line])), verbose=False, format_tuple=('l(%s)', 'r{%s}'), check_paths=True) expected = [ 'Change details for [//:lib]', ' (srcs):', ' l(path(JavaLib1.java:ll))', ' r{path(JavaLib1.java:rr)}', 'Information on paths the script has seen:', ' JavaLib1.java does not exist'] self.assertEqual(result, expected) def test_length_diff(self): line = ("[v] RuleKey {key}=string(\"//:lib\"):key(name):" + "{srcs}:" + "string(\"t\"):key(buck.type):") left_srcs = ["path(%s):key(srcs)" % p for p in ['a:1', 'b:2', 'c:3']] left_line = line.format(key="aabb", srcs=":".join(left_srcs)) right_srcs = left_srcs[:-1] right_line = line.format(key="axbb", srcs=":".join(right_srcs)) result = diff("//:lib", RuleKeyStructureInfo(MockFile([left_line])), RuleKeyStructureInfo(MockFile([right_line])), verbose=False) expected = [ 'Change details for [//:lib]', ' (srcs):', ' -[path(c:3)]', ' +[<missing>]'] self.assertEqual(result, expected) def test_interesting_path_report(self): temp_file = None try: temp_file = tempfile.NamedTemporaryFile(delete=False) temp_file.close() dirpath = os.getcwd() filepath = temp_file.name empty_hash = 'da39a3ee5e6b4b0d3255bfef95601890afd80709' self.assertEqual( reportOnInterestingPaths([dirpath, filepath]), [' %s is not a file' % dirpath, ' %s exists and hashes to %s' % (filepath, empty_hash)]) self.assertEqual( reportOnInterestingPaths(['no/suchfile', dirpath]), [' no/suchfile does not exist', ' %s is not a file' % dirpath]) finally: if temp_file is not None: os.unlink(temp_file.name) def makeRuleKeyLine(key="aabb", name="//:name", srcs=None, ruleType="java_library", deps=None): srcs = srcs or {'JavaLib1.java': 'aabb'} deps = deps or [] srcs_t = ":".join(['path({p}:{h}):key(srcs)'.format(p=p, h=h) for p, h in srcs.iteritems()]) deps_t = ":".join(['ruleKey(sha1={h}):key(deps)'.format(h=h) for h in deps]) template = ("[v] RuleKey {key}=string(\"{name}\"):key(name):" + "{srcs_t}:" "string(\"{ruleType}\"):key(buck.type):" + "{deps_t}:") return template.format(key=key, name=name, srcs_t=srcs_t, ruleType=ruleType, deps_t=deps_t) if __name__ == '__main__': unittest.main()
# .\_eda.py # -*- coding: utf-8 -*- # PyXB bindings for NM:9f5b2e4c02a063822535af58fedb94550ecc79cc # Generated 2014-11-18 14:25:23.927000 by PyXB version 1.2.3 # Namespace eda [xmlns:eda] import pyxb import pyxb.binding import pyxb.binding.saxer import io import pyxb.utils.utility import pyxb.utils.domutils import sys # Unique identifier for bindings created at the same time _GenerationUID = pyxb.utils.utility.UniqueIdentifier('urn:uuid:0613818f-6f61-11e4-85c1-542696dd94ef') # Version of PyXB used to generate the bindings _PyXBVersion = '1.2.3' # Generated bindings are not compatible across PyXB versions if pyxb.__version__ != _PyXBVersion: raise pyxb.PyXBVersionError(_PyXBVersion) # Import bindings for namespaces imported into schema import avm.schematic as _ImportedBinding__schematic import avm as _ImportedBinding__avm import pyxb.binding.datatypes # NOTE: All namespace declarations are reserved within the binding Namespace = pyxb.namespace.NamespaceForURI(u'eda', create_if_missing=True) Namespace.configureCategories(['typeBinding', 'elementBinding']) def CreateFromDocument (xml_text, default_namespace=None, location_base=None): """Parse the given XML and use the document element to create a Python instance. @param xml_text An XML document. This should be data (Python 2 str or Python 3 bytes), or a text (Python 2 unicode or Python 3 str) in the L{pyxb._InputEncoding} encoding. @keyword default_namespace The L{pyxb.Namespace} instance to use as the default namespace where there is no default namespace in scope. If unspecified or C{None}, the namespace of the module containing this function will be used. @keyword location_base: An object to be recorded as the base of all L{pyxb.utils.utility.Location} instances associated with events and objects handled by the parser. You might pass the URI from which the document was obtained. """ if pyxb.XMLStyle_saxer != pyxb._XMLStyle: dom = pyxb.utils.domutils.StringToDOM(xml_text) return CreateFromDOM(dom.documentElement) if default_namespace is None: default_namespace = Namespace.fallbackNamespace() saxer = pyxb.binding.saxer.make_parser(fallback_namespace=default_namespace, location_base=location_base) handler = saxer.getContentHandler() xmld = xml_text if isinstance(xmld, unicode): xmld = xmld.encode(pyxb._InputEncoding) saxer.parse(io.BytesIO(xmld)) instance = handler.rootObject() return instance def CreateFromDOM (node, default_namespace=None): """Create a Python instance from the given DOM node. The node tag must correspond to an element declaration in this module. @deprecated: Forcing use of DOM interface is unnecessary; use L{CreateFromDocument}.""" if default_namespace is None: default_namespace = Namespace.fallbackNamespace() return pyxb.binding.basis.element.AnyCreateFromDOM(node, default_namespace) # List simple type: [anonymous] # superclasses pyxb.binding.datatypes.anySimpleType class STD_ANON (pyxb.binding.basis.STD_list): """Simple type that is a list of pyxb.binding.datatypes.anyURI.""" _ExpandedName = None _XSDLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 63, 10) _Documentation = None _ItemType = pyxb.binding.datatypes.anyURI STD_ANON._InitializeFacetMap() # List simple type: [anonymous] # superclasses pyxb.binding.datatypes.anySimpleType class STD_ANON_ (pyxb.binding.basis.STD_list): """Simple type that is a list of pyxb.binding.datatypes.anyURI.""" _ExpandedName = None _XSDLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 76, 10) _Documentation = None _ItemType = pyxb.binding.datatypes.anyURI STD_ANON_._InitializeFacetMap() # Atomic simple type: {eda}RotationEnum class RotationEnum (pyxb.binding.datatypes.string, pyxb.binding.basis.enumeration_mixin): """An atomic simple type.""" _ExpandedName = pyxb.namespace.ExpandedName(Namespace, u'RotationEnum') _XSDLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 84, 2) _Documentation = None RotationEnum._CF_enumeration = pyxb.binding.facets.CF_enumeration(value_datatype=RotationEnum, enum_prefix=None) RotationEnum.r0 = RotationEnum._CF_enumeration.addEnumeration(unicode_value=u'r0', tag=u'r0') RotationEnum.r90 = RotationEnum._CF_enumeration.addEnumeration(unicode_value=u'r90', tag=u'r90') RotationEnum.r180 = RotationEnum._CF_enumeration.addEnumeration(unicode_value=u'r180', tag=u'r180') RotationEnum.r270 = RotationEnum._CF_enumeration.addEnumeration(unicode_value=u'r270', tag=u'r270') RotationEnum._InitializeFacetMap(RotationEnum._CF_enumeration) Namespace.addCategoryObject('typeBinding', u'RotationEnum', RotationEnum) # Atomic simple type: {eda}LayerEnum class LayerEnum (pyxb.binding.datatypes.string, pyxb.binding.basis.enumeration_mixin): """An atomic simple type.""" _ExpandedName = pyxb.namespace.ExpandedName(Namespace, u'LayerEnum') _XSDLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 92, 2) _Documentation = None LayerEnum._CF_enumeration = pyxb.binding.facets.CF_enumeration(value_datatype=LayerEnum, enum_prefix=None) LayerEnum.Top = LayerEnum._CF_enumeration.addEnumeration(unicode_value=u'Top', tag=u'Top') LayerEnum.Bottom = LayerEnum._CF_enumeration.addEnumeration(unicode_value=u'Bottom', tag=u'Bottom') LayerEnum._InitializeFacetMap(LayerEnum._CF_enumeration) Namespace.addCategoryObject('typeBinding', u'LayerEnum', LayerEnum) # Atomic simple type: {eda}LayerRangeEnum class LayerRangeEnum (pyxb.binding.datatypes.string, pyxb.binding.basis.enumeration_mixin): """An atomic simple type.""" _ExpandedName = pyxb.namespace.ExpandedName(Namespace, u'LayerRangeEnum') _XSDLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 98, 2) _Documentation = None LayerRangeEnum._CF_enumeration = pyxb.binding.facets.CF_enumeration(value_datatype=LayerRangeEnum, enum_prefix=None) LayerRangeEnum.Either = LayerRangeEnum._CF_enumeration.addEnumeration(unicode_value=u'Either', tag=u'Either') LayerRangeEnum.Top = LayerRangeEnum._CF_enumeration.addEnumeration(unicode_value=u'Top', tag=u'Top') LayerRangeEnum.Bottom = LayerRangeEnum._CF_enumeration.addEnumeration(unicode_value=u'Bottom', tag=u'Bottom') LayerRangeEnum._InitializeFacetMap(LayerRangeEnum._CF_enumeration) Namespace.addCategoryObject('typeBinding', u'LayerRangeEnum', LayerRangeEnum) # Complex type {eda}Parameter with content type ELEMENT_ONLY class Parameter_ (_ImportedBinding__avm.DomainModelParameter_): """Complex type {eda}Parameter with content type ELEMENT_ONLY""" _TypeDefinition = None _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_ELEMENT_ONLY _Abstract = False _ExpandedName = pyxb.namespace.ExpandedName(Namespace, u'Parameter') _XSDLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 25, 2) _ElementMap = _ImportedBinding__avm.DomainModelParameter_._ElementMap.copy() _AttributeMap = _ImportedBinding__avm.DomainModelParameter_._AttributeMap.copy() # Base type is _ImportedBinding__avm.DomainModelParameter_ # Element Value uses Python identifier Value __Value = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(None, u'Value'), 'Value', '__eda_Parameter__Value', False, pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 29, 10), ) Value = property(__Value.value, __Value.set, None, None) # Attribute Notes inherited from {avm}DomainModelParameter # Attribute XPosition inherited from {avm}DomainModelParameter # Attribute YPosition inherited from {avm}DomainModelParameter # Attribute Locator uses Python identifier Locator __Locator = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, u'Locator'), 'Locator', '__eda_Parameter__Locator', pyxb.binding.datatypes.string, required=True) __Locator._DeclarationLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 31, 8) __Locator._UseLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 31, 8) Locator = property(__Locator.value, __Locator.set, None, None) _ElementMap.update({ __Value.name() : __Value }) _AttributeMap.update({ __Locator.name() : __Locator }) Namespace.addCategoryObject('typeBinding', u'Parameter', Parameter_) # Complex type {eda}PcbLayoutConstraint with content type EMPTY class PcbLayoutConstraint_ (_ImportedBinding__avm.ContainerFeature_): """Complex type {eda}PcbLayoutConstraint with content type EMPTY""" _TypeDefinition = None _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_EMPTY _Abstract = True _ExpandedName = pyxb.namespace.ExpandedName(Namespace, u'PcbLayoutConstraint') _XSDLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 35, 2) _ElementMap = _ImportedBinding__avm.ContainerFeature_._ElementMap.copy() _AttributeMap = _ImportedBinding__avm.ContainerFeature_._AttributeMap.copy() # Base type is _ImportedBinding__avm.ContainerFeature_ # Attribute XPosition uses Python identifier XPosition __XPosition = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, u'XPosition'), 'XPosition', '__eda_PcbLayoutConstraint__XPosition', pyxb.binding.datatypes.unsignedInt) __XPosition._DeclarationLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 38, 8) __XPosition._UseLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 38, 8) XPosition = property(__XPosition.value, __XPosition.set, None, None) # Attribute YPosition uses Python identifier YPosition __YPosition = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, u'YPosition'), 'YPosition', '__eda_PcbLayoutConstraint__YPosition', pyxb.binding.datatypes.unsignedInt) __YPosition._DeclarationLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 39, 8) __YPosition._UseLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 39, 8) YPosition = property(__YPosition.value, __YPosition.set, None, None) _ElementMap.update({ }) _AttributeMap.update({ __XPosition.name() : __XPosition, __YPosition.name() : __YPosition }) Namespace.addCategoryObject('typeBinding', u'PcbLayoutConstraint', PcbLayoutConstraint_) # Complex type {eda}EDAModel with content type ELEMENT_ONLY class EDAModel_ (_ImportedBinding__schematic.SchematicModel_): """Complex type {eda}EDAModel with content type ELEMENT_ONLY""" _TypeDefinition = None _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_ELEMENT_ONLY _Abstract = False _ExpandedName = pyxb.namespace.ExpandedName(Namespace, u'EDAModel') _XSDLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 11, 2) _ElementMap = _ImportedBinding__schematic.SchematicModel_._ElementMap.copy() _AttributeMap = _ImportedBinding__schematic.SchematicModel_._AttributeMap.copy() # Base type is _ImportedBinding__schematic.SchematicModel_ # Element Parameter uses Python identifier Parameter __Parameter = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(None, u'Parameter'), 'Parameter', '__eda_EDAModel__Parameter', True, pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 15, 10), ) Parameter = property(__Parameter.value, __Parameter.set, None, None) # Element Pin (Pin) inherited from {schematic}SchematicModel # Attribute UsesResource inherited from {avm}DomainModel # Attribute Author inherited from {avm}DomainModel # Attribute Notes inherited from {avm}DomainModel # Attribute XPosition inherited from {avm}DomainModel # Attribute YPosition inherited from {avm}DomainModel # Attribute Name inherited from {avm}DomainModel # Attribute Library uses Python identifier Library __Library = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, u'Library'), 'Library', '__eda_EDAModel__Library', pyxb.binding.datatypes.string) __Library._DeclarationLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 17, 8) __Library._UseLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 17, 8) Library = property(__Library.value, __Library.set, None, None) # Attribute DeviceSet uses Python identifier DeviceSet __DeviceSet = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, u'DeviceSet'), 'DeviceSet', '__eda_EDAModel__DeviceSet', pyxb.binding.datatypes.string) __DeviceSet._DeclarationLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 18, 8) __DeviceSet._UseLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 18, 8) DeviceSet = property(__DeviceSet.value, __DeviceSet.set, None, None) # Attribute Device uses Python identifier Device __Device = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, u'Device'), 'Device', '__eda_EDAModel__Device', pyxb.binding.datatypes.string) __Device._DeclarationLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 19, 8) __Device._UseLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 19, 8) Device = property(__Device.value, __Device.set, None, None) # Attribute Package uses Python identifier Package __Package = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, u'Package'), 'Package', '__eda_EDAModel__Package', pyxb.binding.datatypes.string) __Package._DeclarationLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 20, 8) __Package._UseLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 20, 8) Package = property(__Package.value, __Package.set, None, None) # Attribute HasMultiLayerFootprint uses Python identifier HasMultiLayerFootprint __HasMultiLayerFootprint = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, u'HasMultiLayerFootprint'), 'HasMultiLayerFootprint', '__eda_EDAModel__HasMultiLayerFootprint', pyxb.binding.datatypes.boolean, unicode_default=u'false') __HasMultiLayerFootprint._DeclarationLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 21, 8) __HasMultiLayerFootprint._UseLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 21, 8) HasMultiLayerFootprint = property(__HasMultiLayerFootprint.value, __HasMultiLayerFootprint.set, None, None) _ElementMap.update({ __Parameter.name() : __Parameter }) _AttributeMap.update({ __Library.name() : __Library, __DeviceSet.name() : __DeviceSet, __Device.name() : __Device, __Package.name() : __Package, __HasMultiLayerFootprint.name() : __HasMultiLayerFootprint }) Namespace.addCategoryObject('typeBinding', u'EDAModel', EDAModel_) # Complex type {eda}ExactLayoutConstraint with content type EMPTY class ExactLayoutConstraint_ (PcbLayoutConstraint_): """Complex type {eda}ExactLayoutConstraint with content type EMPTY""" _TypeDefinition = None _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_EMPTY _Abstract = False _ExpandedName = pyxb.namespace.ExpandedName(Namespace, u'ExactLayoutConstraint') _XSDLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 43, 2) _ElementMap = PcbLayoutConstraint_._ElementMap.copy() _AttributeMap = PcbLayoutConstraint_._AttributeMap.copy() # Base type is PcbLayoutConstraint_ # Attribute XPosition inherited from {eda}PcbLayoutConstraint # Attribute YPosition inherited from {eda}PcbLayoutConstraint # Attribute X uses Python identifier X __X = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, u'X'), 'X', '__eda_ExactLayoutConstraint__X', pyxb.binding.datatypes.double, required=True) __X._DeclarationLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 46, 8) __X._UseLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 46, 8) X = property(__X.value, __X.set, None, None) # Attribute Y uses Python identifier Y __Y = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, u'Y'), 'Y', '__eda_ExactLayoutConstraint__Y', pyxb.binding.datatypes.double, required=True) __Y._DeclarationLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 47, 8) __Y._UseLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 47, 8) Y = property(__Y.value, __Y.set, None, None) # Attribute Layer uses Python identifier Layer __Layer = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, u'Layer'), 'Layer', '__eda_ExactLayoutConstraint__Layer', LayerEnum, unicode_default=u'Top') __Layer._DeclarationLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 48, 8) __Layer._UseLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 48, 8) Layer = property(__Layer.value, __Layer.set, None, None) # Attribute Rotation uses Python identifier Rotation __Rotation = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, u'Rotation'), 'Rotation', '__eda_ExactLayoutConstraint__Rotation', RotationEnum) __Rotation._DeclarationLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 49, 8) __Rotation._UseLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 49, 8) Rotation = property(__Rotation.value, __Rotation.set, None, None) # Attribute ConstraintTarget uses Python identifier ConstraintTarget __ConstraintTarget = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, u'ConstraintTarget'), 'ConstraintTarget', '__eda_ExactLayoutConstraint__ConstraintTarget', pyxb.binding.datatypes.anyURI, required=True) __ConstraintTarget._DeclarationLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 50, 8) __ConstraintTarget._UseLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 50, 8) ConstraintTarget = property(__ConstraintTarget.value, __ConstraintTarget.set, None, None) _ElementMap.update({ }) _AttributeMap.update({ __X.name() : __X, __Y.name() : __Y, __Layer.name() : __Layer, __Rotation.name() : __Rotation, __ConstraintTarget.name() : __ConstraintTarget }) Namespace.addCategoryObject('typeBinding', u'ExactLayoutConstraint', ExactLayoutConstraint_) # Complex type {eda}RangeLayoutConstraint with content type EMPTY class RangeLayoutConstraint_ (PcbLayoutConstraint_): """Complex type {eda}RangeLayoutConstraint with content type EMPTY""" _TypeDefinition = None _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_EMPTY _Abstract = False _ExpandedName = pyxb.namespace.ExpandedName(Namespace, u'RangeLayoutConstraint') _XSDLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 54, 2) _ElementMap = PcbLayoutConstraint_._ElementMap.copy() _AttributeMap = PcbLayoutConstraint_._AttributeMap.copy() # Base type is PcbLayoutConstraint_ # Attribute XPosition inherited from {eda}PcbLayoutConstraint # Attribute YPosition inherited from {eda}PcbLayoutConstraint # Attribute XRangeMin uses Python identifier XRangeMin __XRangeMin = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, u'XRangeMin'), 'XRangeMin', '__eda_RangeLayoutConstraint__XRangeMin', pyxb.binding.datatypes.double) __XRangeMin._DeclarationLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 57, 8) __XRangeMin._UseLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 57, 8) XRangeMin = property(__XRangeMin.value, __XRangeMin.set, None, None) # Attribute XRangeMax uses Python identifier XRangeMax __XRangeMax = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, u'XRangeMax'), 'XRangeMax', '__eda_RangeLayoutConstraint__XRangeMax', pyxb.binding.datatypes.double) __XRangeMax._DeclarationLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 58, 8) __XRangeMax._UseLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 58, 8) XRangeMax = property(__XRangeMax.value, __XRangeMax.set, None, None) # Attribute YRangeMin uses Python identifier YRangeMin __YRangeMin = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, u'YRangeMin'), 'YRangeMin', '__eda_RangeLayoutConstraint__YRangeMin', pyxb.binding.datatypes.double) __YRangeMin._DeclarationLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 59, 8) __YRangeMin._UseLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 59, 8) YRangeMin = property(__YRangeMin.value, __YRangeMin.set, None, None) # Attribute YRangeMax uses Python identifier YRangeMax __YRangeMax = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, u'YRangeMax'), 'YRangeMax', '__eda_RangeLayoutConstraint__YRangeMax', pyxb.binding.datatypes.double) __YRangeMax._DeclarationLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 60, 8) __YRangeMax._UseLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 60, 8) YRangeMax = property(__YRangeMax.value, __YRangeMax.set, None, None) # Attribute LayerRange uses Python identifier LayerRange __LayerRange = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, u'LayerRange'), 'LayerRange', '__eda_RangeLayoutConstraint__LayerRange', LayerRangeEnum, unicode_default=u'Either') __LayerRange._DeclarationLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 61, 8) __LayerRange._UseLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 61, 8) LayerRange = property(__LayerRange.value, __LayerRange.set, None, None) # Attribute ConstraintTarget uses Python identifier ConstraintTarget __ConstraintTarget = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, u'ConstraintTarget'), 'ConstraintTarget', '__eda_RangeLayoutConstraint__ConstraintTarget', STD_ANON, required=True) __ConstraintTarget._DeclarationLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 62, 8) __ConstraintTarget._UseLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 62, 8) ConstraintTarget = property(__ConstraintTarget.value, __ConstraintTarget.set, None, None) _ElementMap.update({ }) _AttributeMap.update({ __XRangeMin.name() : __XRangeMin, __XRangeMax.name() : __XRangeMax, __YRangeMin.name() : __YRangeMin, __YRangeMax.name() : __YRangeMax, __LayerRange.name() : __LayerRange, __ConstraintTarget.name() : __ConstraintTarget }) Namespace.addCategoryObject('typeBinding', u'RangeLayoutConstraint', RangeLayoutConstraint_) # Complex type {eda}RelativeLayoutConstraint with content type EMPTY class RelativeLayoutConstraint_ (PcbLayoutConstraint_): """Complex type {eda}RelativeLayoutConstraint with content type EMPTY""" _TypeDefinition = None _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_EMPTY _Abstract = False _ExpandedName = pyxb.namespace.ExpandedName(Namespace, u'RelativeLayoutConstraint') _XSDLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 70, 2) _ElementMap = PcbLayoutConstraint_._ElementMap.copy() _AttributeMap = PcbLayoutConstraint_._AttributeMap.copy() # Base type is PcbLayoutConstraint_ # Attribute XPosition inherited from {eda}PcbLayoutConstraint # Attribute YPosition inherited from {eda}PcbLayoutConstraint # Attribute XOffset uses Python identifier XOffset __XOffset = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, u'XOffset'), 'XOffset', '__eda_RelativeLayoutConstraint__XOffset', pyxb.binding.datatypes.double) __XOffset._DeclarationLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 73, 8) __XOffset._UseLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 73, 8) XOffset = property(__XOffset.value, __XOffset.set, None, None) # Attribute YOffset uses Python identifier YOffset __YOffset = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, u'YOffset'), 'YOffset', '__eda_RelativeLayoutConstraint__YOffset', pyxb.binding.datatypes.double) __YOffset._DeclarationLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 74, 8) __YOffset._UseLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 74, 8) YOffset = property(__YOffset.value, __YOffset.set, None, None) # Attribute ConstraintTarget uses Python identifier ConstraintTarget __ConstraintTarget = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, u'ConstraintTarget'), 'ConstraintTarget', '__eda_RelativeLayoutConstraint__ConstraintTarget', STD_ANON_, required=True) __ConstraintTarget._DeclarationLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 75, 8) __ConstraintTarget._UseLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 75, 8) ConstraintTarget = property(__ConstraintTarget.value, __ConstraintTarget.set, None, None) # Attribute Origin uses Python identifier Origin __Origin = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, u'Origin'), 'Origin', '__eda_RelativeLayoutConstraint__Origin', pyxb.binding.datatypes.anyURI, required=True) __Origin._DeclarationLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 80, 8) __Origin._UseLocation = pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 80, 8) Origin = property(__Origin.value, __Origin.set, None, None) _ElementMap.update({ }) _AttributeMap.update({ __XOffset.name() : __XOffset, __YOffset.name() : __YOffset, __ConstraintTarget.name() : __ConstraintTarget, __Origin.name() : __Origin }) Namespace.addCategoryObject('typeBinding', u'RelativeLayoutConstraint', RelativeLayoutConstraint_) Parameter = pyxb.binding.basis.element(pyxb.namespace.ExpandedName(Namespace, u'Parameter'), Parameter_, location=pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 6, 2)) Namespace.addCategoryObject('elementBinding', Parameter.name().localName(), Parameter) PcbLayoutConstraint = pyxb.binding.basis.element(pyxb.namespace.ExpandedName(Namespace, u'PcbLayoutConstraint'), PcbLayoutConstraint_, location=pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 7, 2)) Namespace.addCategoryObject('elementBinding', PcbLayoutConstraint.name().localName(), PcbLayoutConstraint) EDAModel = pyxb.binding.basis.element(pyxb.namespace.ExpandedName(Namespace, u'EDAModel'), EDAModel_, location=pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 5, 2)) Namespace.addCategoryObject('elementBinding', EDAModel.name().localName(), EDAModel) ExactLayoutConstraint = pyxb.binding.basis.element(pyxb.namespace.ExpandedName(Namespace, u'ExactLayoutConstraint'), ExactLayoutConstraint_, location=pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 8, 2)) Namespace.addCategoryObject('elementBinding', ExactLayoutConstraint.name().localName(), ExactLayoutConstraint) RangeLayoutConstraint = pyxb.binding.basis.element(pyxb.namespace.ExpandedName(Namespace, u'RangeLayoutConstraint'), RangeLayoutConstraint_, location=pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 9, 2)) Namespace.addCategoryObject('elementBinding', RangeLayoutConstraint.name().localName(), RangeLayoutConstraint) RelativeLayoutConstraint = pyxb.binding.basis.element(pyxb.namespace.ExpandedName(Namespace, u'RelativeLayoutConstraint'), RelativeLayoutConstraint_, location=pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 10, 2)) Namespace.addCategoryObject('elementBinding', RelativeLayoutConstraint.name().localName(), RelativeLayoutConstraint) Parameter_._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, u'Value'), _ImportedBinding__avm.Value_, scope=Parameter_, location=pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 29, 10))) def _BuildAutomaton (): # Remove this helper function from the namespace after it is invoked global _BuildAutomaton del _BuildAutomaton import pyxb.utils.fac as fac counters = set() cc_0 = fac.CounterCondition(min=0L, max=1, metadata=pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 29, 10)) counters.add(cc_0) states = [] final_update = set() final_update.add(fac.UpdateInstruction(cc_0, False)) symbol = pyxb.binding.content.ElementUse(Parameter_._UseForTag(pyxb.namespace.ExpandedName(None, u'Value')), pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 29, 10)) st_0 = fac.State(symbol, is_initial=True, final_update=final_update, is_unordered_catenation=False) states.append(st_0) transitions = [] transitions.append(fac.Transition(st_0, [ fac.UpdateInstruction(cc_0, True) ])) st_0._set_transitionSet(transitions) return fac.Automaton(states, counters, True, containing_state=None) Parameter_._Automaton = _BuildAutomaton() EDAModel_._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, u'Parameter'), Parameter_, scope=EDAModel_, location=pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 15, 10))) def _BuildAutomaton_ (): # Remove this helper function from the namespace after it is invoked global _BuildAutomaton_ del _BuildAutomaton_ import pyxb.utils.fac as fac counters = set() cc_0 = fac.CounterCondition(min=0L, max=None, metadata=pyxb.utils.utility.Location(u'avm.schematic.xsd', 10, 10)) counters.add(cc_0) cc_1 = fac.CounterCondition(min=0L, max=None, metadata=pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 15, 10)) counters.add(cc_1) states = [] final_update = set() final_update.add(fac.UpdateInstruction(cc_0, False)) symbol = pyxb.binding.content.ElementUse(EDAModel_._UseForTag(pyxb.namespace.ExpandedName(None, u'Pin')), pyxb.utils.utility.Location(u'avm.schematic.xsd', 10, 10)) st_0 = fac.State(symbol, is_initial=True, final_update=final_update, is_unordered_catenation=False) states.append(st_0) final_update = set() final_update.add(fac.UpdateInstruction(cc_1, False)) symbol = pyxb.binding.content.ElementUse(EDAModel_._UseForTag(pyxb.namespace.ExpandedName(None, u'Parameter')), pyxb.utils.utility.Location(u'avm.schematic.eda.xsd', 15, 10)) st_1 = fac.State(symbol, is_initial=True, final_update=final_update, is_unordered_catenation=False) states.append(st_1) transitions = [] transitions.append(fac.Transition(st_0, [ fac.UpdateInstruction(cc_0, True) ])) transitions.append(fac.Transition(st_1, [ fac.UpdateInstruction(cc_0, False) ])) st_0._set_transitionSet(transitions) transitions = [] transitions.append(fac.Transition(st_1, [ fac.UpdateInstruction(cc_1, True) ])) st_1._set_transitionSet(transitions) return fac.Automaton(states, counters, True, containing_state=None) EDAModel_._Automaton = _BuildAutomaton_()
import csv class Student: def __init__(self, fields): self.fields = fields # hash table of user fields students = [] # a list of dicts that describe a student language_prof = {"elementary": 1, "limited": 2, "intermediate": 3, "nearly_proficient": 4} def lookup(proficiency): return language_prof[proficiency] # setup function to read the user csv # and initialize hash table of student objects def setup(): with open("script/newsheet.csv", "r") as users: reader = csv.DictReader(users) for row in reader: fields = { 'id': row['id'], 'name': row['first_name'] + row['last_name'], 'gender': row['gender'], 'academic_title': row['academic_title'], 'residency': row['residency'], 'gender_preference': row['gender_preference'], 'fluent_languages': row['fluent_languages'], 'lang_additional_info': row['lang_additional_info'], 'first_lang_preference': row['first_lang_preference'], 'first_lang_proficiency': lookup(row['first_lang_proficiency']), 'second_lang_preference': row['second_lang_preference'], 'second_lang_proficiency': lookup(row['second_lang_proficiency']), 'time_preference': row['time_preference'], 'hours_per_week': row['hours_per_week'], 'id': row['id'], 'sid': row['sid'] } s = Student(fields) students.append(extract_student_info(s)) users.close() # a score is a tuple of (gender, gender_preference) def gender_score(score1, score2): if score1[1] == "Indifferent" and score2[1] == 'Indifferent': return 1 if score1[1] == score2[0] and score2[1] == score1[0]: return 3 if (score1[1] == score2[0] and score2[1] == 'Indifferent') or (score1[0] == score2[1] and score1[1] == 'Indifferent'): return 2 else: return 0 # languages = list of tuples: (language_preference, language_proficiency) def data_clean(languages): cleaned = [] ls = [] for (l, p) in languages: if type(l) == list: for i in xrange(len(l)): if l[i] != '' and l[i] not in ls: cleaned.append((l[i], p[i])) ls.append(l[i]) else: if l != '' and l not in ls: if p !='': cleaned.append((l, p)) ls.append(l) return cleaned # def get_profi(student): # na = student[9].split(",") # sn = [] # for nai in na: # sni = 5 # if nai == student[14]: # if student[15] != '': # sni = student[15] # elif nai == student[16]: # if student[17] != '': # sni = student[17] # sn.append(sni) # return sn def mutual_interest(sn, si, pn, pi): total = 0 st, pt = False, False for (sl, spro) in sn: for (pl, ppro) in pi: if sl == pl: st = True total -= abs(spro-ppro)*0.25 for (pl, ppro) in pn: for (sl, spro) in si: if sl == pl: pt = True total -= abs(spro-ppro)*0.25 if st and pt: total+=15 return (True, total) return (False, 0) def same_interest(si, pi): total = 0 languages = [] for (sl, sp) in si: for (pl, pp) in pi: if sl == pl: languages.append(sl) total += 5 - abs(sp-pp)*0.5 return total def one_interest(sn, si, pn, pi): total = 0 for (s1_lang, s1_proficiency) in sn: for (s2_lang, s2_proficiency) in pi: if s1_lang == s2_lang: total += 3 - abs(s1_proficiency-s2_proficiency)*0.5 for (s2_lang, s2_proficiency) in pn: for (s1_lang, s1_proficiency) in si: if s1_lang == s2_lang: total += 3 - abs(s1_proficiency-s2_proficiency)*0.5 return total def language_score(student, potential): final = 0 sn, si = student pn, pi = potential if sn[0] != pn[0]: final += 1 mi, mi_score = mutual_interest(sn, si, pn, pi) si_score = same_interest(si, pi) if not mi: final += one_interest(sn, si, pn, pi) final += mi_score + si_score return final def time_score(s1_time, s2_time, s1_hour, s2_hour): total = 0.0 for s1_day in s1_time: for s2_day in s2_time: if s1_day == s2_day: total += 1 if s1_hour == s2_hour: total += 0.5 return total def meetup(s1_time, s2_time): meetup_time = [] s1_time = s1_time.replace('"', '').strip('[]').split(',') s2_time = s2_time.replace('"', '').strip('[]').split(',') for s1_day in s1_time: for s2_day in s2_time: if s1_day == s2_day: meetup_time.append(s1_day) return ','.join(meetup_time) def language_detection(language_pair): student1, student2 = language_pair s1_lang_to_teach, s1_lang_to_learn = student1 s2_lang_to_teach, s2_lang_to_learn = student2 languages = [] for (lang1, proficiency1) in s1_lang_to_teach: for (lang2, proficiency2) in s2_lang_to_learn: if lang1 == lang2 and lang1 not in languages: languages.append(lang1) for (lang1, proficiency1) in s1_lang_to_learn: for (lang2, proficiency2) in s2_lang_to_teach: if lang1 == lang2 and lang1 not in languages: languages.append(lang1) for (lang1, proficiency1) in s1_lang_to_learn: for (lang2, proficiency2) in s2_lang_to_learn: if lang1 == lang2 and lang1 not in languages: languages.append(lang1) return str(languages).strip('[]') def extract_student_info(student): info = {} info['id'] = student.fields['id'] info['name'] = student.fields['name'] info['sid'] = student.fields['sid'] info['academic'] = student.fields['academic_title'] info['residency'] = student.fields['residency'] info['gender'] = (student.fields['gender'], student.fields['gender_preference']) info['lang_to_teach'] = [(x[2:len(x)-2], 4) for x in student.fields['fluent_languages'].split(",")] info['lang_to_learn'] = data_clean([(student.fields['first_lang_preference'], student.fields['first_lang_proficiency']), (student.fields['second_lang_preference'], student.fields['second_lang_proficiency'])]) info['time'] = student.fields['time_preference'] info['hour'] = student.fields['hours_per_week'] return info def calculate_match_score(student1, student2): score = 0.0 # Add in the score for residency # It is more preferable to match domestic with international students if student1['residency'] != student2['residency']: score += 0.5 # Take into account gender preferences score += gender_score(student1['gender'], student2['gender']) # Take into account time and hour preferences score += time_score(student1['time'], student2['time'], student1['hour'], student2['hour']) score += abs(int(student1['hour'])+int(student2['hour']))*0.5 - abs(int(student1['hour'])-int(student2['hour']))*0.5 # Take into account language matchings # This is the most important thing to consider and should be weighted accordingly score += language_score((student1['lang_to_teach'], student1['lang_to_learn']), (student2['lang_to_teach'], student2['lang_to_learn'])) return score setup() pairs = open('script/final_pairs.csv', 'w') fields = ['partner1', 'partner2', 'language(s)', 'possible meetup time', 'stability'] writer = csv.DictWriter(pairs, fieldnames=fields) writer.writeheader() # attempt to pair every student with another student while len(students) != 0: if len(students) == 1: student = students.pop() writer.writerow({'partner1': student['id']}) break final = 0.0 # Find the best match amoung all of the students for student1 in students: final = 0.0 for student2 in students: highest = 0.0 if student2 != student1: score = calculate_match_score(student1, student2) if highest < score: highest = score best = student2 languages = (student2['lang_to_teach'], student2['lang_to_learn']) if final < highest: final = highest best_pair = (student1, best) languages = ((student1['lang_to_teach'], student1['lang_to_learn']), languages) partner1 = best_pair[0] partner2 = best_pair[1] language = language_detection(languages) meetup_days = meetup(partner1['time'], partner2['time']) writer.writerow({'partner1': partner1['id'], 'partner2': partner2['id'], 'language(s)': language, 'possible meetup time': meetup_days, 'stability': str(final)}) students.remove(partner1) students.remove(partner2) #need to check if the student put the right ID number
import logging import multiprocessing import re import gevent import gevent.server import gevent.event import exceptions __all__ = [ 'Server', 'BackgroundServer', ] logger = logging.getLogger('pubres') class Client(object): def __init__(self, socket): self._socket = socket self._fp = socket.makefile() # Docs claim socket.getpeername() does not work on all platforms. self.peername = socket.getpeername() def send(self, s): self._fp.write(s) self._fp.flush() def send_line(self, s): self.send(s + '\n') def readline(self): return self._fp.readline() # TODO length limit def fail(self, ex): self.send_line(ex.message) raise ex def ensure(self, proposition, ex): if not proposition: self.fail(ex) def block_and_disconnect(self): # TODO doc exception self._fp.read(1) self._socket.close() def disconnect(self): self._socket.close() class CallbackStreamServer(gevent.server.StreamServer): """A StreamServer that calls a callback when it finished starting so that code that starts it using serve_forever doesn't have to wait some arbitrary time for the socket to get bound. """ def __init__(self, *args, **kwargs): # Extract the started_callback and don't pass it to the StreamServer constructor other_kwargs = kwargs.copy() self._started_callback = other_kwargs.pop('started_callback', None) super(CallbackStreamServer, self).__init__(*args, **other_kwargs) def pre_start(self, *args, **kwargs): # See http://www.gevent.org/gevent.baseserver.html#gevent.baseserver.BaseServer.pre_start super(CallbackStreamServer, self).pre_start(*args, **kwargs) if self._started_callback: self._started_callback() class Server(object): def __init__(self, host='localhost', port=5555): self.host = host self.port = port self.mapping = {} self._mp_server_stop_event = multiprocessing.Event() def run_until_stop(self, started_callback=None, poll_time=0.001): """Starts the server. Blocks until stop() is called (possibly from another process). Does a gevent.sleep(1ms) loop as actually wait()ing for a multiprocessing.Event would block all gevent activity, so we have to poll. This sleeping time can be overridden with the poll_time parameter (in seconds). """ gevent_server = CallbackStreamServer((self.host, self.port), self.on_connection, started_callback=started_callback) gevent_server.start() while not self._mp_server_stop_event.is_set(): gevent.sleep(poll_time) gevent_server.stop() def stop(self): """Stops the server. Does not block. """ self._mp_server_stop_event.set() def on_connection(self, socket, address): logger.debug("connection from %s", address) client = Client(socket) try: client.send_line("pubres ready") self.handle_client(client) except exceptions.ClientException as e: logger.warning("%s - %s", client.peername, e.message) def handle_client(self, client): # TODO timeout line = client.readline().strip() action, param_str = first_word_and_rest(line) invalid_action_fn = lambda: client.fail(exceptions.InvalidAction()) { 'pub': lambda: self.client_pub(client, param_str), 'query': lambda: self.client_query(client, param_str), 'list': lambda: self.client_list(client, param_str), }.get(action, invalid_action_fn)() def client_pub(self, client, param_str): client.ensure(' ' in param_str, exceptions.MalformedPub()) key, val = first_word_and_rest(param_str) client.ensure(is_key(key), exceptions.InvalidKey()) client.ensure(is_value(val), exceptions.InvalidValue()) ok = self.pub(key, val) if not ok: client.fail(exceptions.KeyInUse()) # The client is now connected. We keep the connection open # until it disconnects (or sends something). try: client.send_line('ok') client.block_and_disconnect() finally: # Unsubscribe whatever happens and then re-raise the exception self.unpub(key) def client_query(self, client, param_str): key = param_str.strip() client.ensure(is_key(key), exceptions.InvalidKey()) val = self.query(key) client.ensure(val is not None, exceptions.KeyNotFound()) client.send_line('ok') client.send_line(val) client.disconnect() def client_list(self, client, param_str): # TODO use param_str for custom query / prefix selection l = self.list() client.send_line('ok') client.send_line(l) client.disconnect() def pub(self, key, val): if key in self.mapping: logger.info("pub denied %s (exists)", {key: val}) return False logger.info("pub %s", {key: val}) self.mapping[key] = val return True def unpub(self, key): logger.info("unpub %s", key) del self.mapping[key] def query(self, key): return self.mapping.get(key) def list(self): return ' '.join(sorted(self.mapping.keys())) class BackgroundServer(Server): """A pubres server that forks off to the background. Can be started with start(), stopped with stop(), and used in a with statement. """ def __init__(self, *args, **kwargs): super(BackgroundServer, self).__init__(*args, **kwargs) self._server_process = None # Just for fail-early assertions self._running = False # TODO use exceptions instead of assertions def start(self): """Starts the server in a multiprocessing.Process. Blocks until the server is accepting connections so that callers don't need to wait before using it. The server must not be running already; must only be called once. """ # Server should not be running assert self._server_process is None started_event = multiprocessing.Event() def work(): self.run_until_stop(started_callback=started_event.set) self._server_process = multiprocessing.Process(target=work) self._server_process.start() # Wait for the server to be started # Use this wait() loop to terminate early when the _server_process # fails with an error; if that happens, the started_event would not # be set and we would wait forever. while not started_event.is_set() and self._server_process.is_alive(): started_event.wait(0.01) self._running = True def stop(self, timeout=None): """Stops the server process. If timeout is given, returns True iff the server exited within the timeout. If timeout is None, the server process is guaranteed to exit (possibly waiting indefinitely) and True is returned. Must only be called after having called start(); must not be called after the server exited (it returned True). Note that when calling this, the server might already have exited (e.g. erratically.) """ assert self._running # Stop server (does not block) super(BackgroundServer, self).stop() # Wait for server process to finish # This is critical for coverage; if we don't do this, # the whole programm will usually exit before the coverage # data of the process can be written self._server_process.join(timeout) if self._server_process.is_alive(): return False else: # Guard against repeated calls when server has exited self._running = False return True def __enter__(self): self.start() return self def __exit__(self, type, value, traceback): self.stop() def first_word_and_rest(line): # str.split always returns at least one element: # ''.split(' ', 1) == [''] split = map(str.strip, line.split(' ', 1)) return split if len(split) > 1 else split + [''] KEY_RE = re.compile(r'\w+(\.\w+)*') # At xx, xx.ab and so on def is_key(key): return KEY_RE.match(key) is not None def is_value(value): return True
# Copyright 2019 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. # ============================================================================== """Helpers to convert variables to constants in TensorFlow 2.0.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import numpy as np from tensorflow.core.framework import attr_value_pb2 from tensorflow.core.framework import graph_pb2 from tensorflow.core.framework import tensor_shape_pb2 from tensorflow.core.framework import variable_pb2 from tensorflow.core.protobuf import config_pb2 from tensorflow.core.protobuf import meta_graph_pb2 from tensorflow.core.protobuf import rewriter_config_pb2 from tensorflow.python.framework import dtypes from tensorflow.python.framework import graph_util from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_util from tensorflow.python.grappler import tf_optimizer from tensorflow.python.ops import array_ops from tensorflow.python.training.saver import export_meta_graph from tensorflow.python.util import lazy_loader from tensorflow.python.util import object_identity # Lazy load the single eager module to avoid introducing new dependencies for # graph_util:convert_variables_to_constants (eg in # tensorflow/contrib/session_bundle:session_bundle_py_test). wrap_function = lazy_loader.LazyLoader( "wrap_function", globals(), "tensorflow.python.eager.wrap_function") _CONDITIONAL_OPS = set(["If", "StatelessIf"]) _LOOP_OPS = set(["While", "StatelessWhile"]) _CONTROL_FLOW_OPS = _CONDITIONAL_OPS.union(_LOOP_OPS) class _TensorData( collections.namedtuple("_TensorData", ["numpy", "dtype", "index"])): """Data about a tensor that was converted to a constant.""" __slots__ = () @property def dtype_attr(self): return attr_value_pb2.AttrValue(type=self.dtype) class _EndPoint(collections.namedtuple("_EndPoint", ["convertible", "index"])): """An endpoint in a graph.""" __slots__ = () def __str__(self): return "{}[{}]".format(self.convertible, self.index) class _Edge(collections.namedtuple("_Edge", ["source", "destination"])): """A directed graph edge.""" __slots__ = () def __str__(self): return "{} -> {}".format(self.source, self.destination) class _Convertible(object): """An entity that can have variables converted to constants.""" def __init__(self, enclosing_graph): self._enclosing_graph = enclosing_graph self._outgoing_edges = [] self._converted_self = None def converted_self(self): """A copy of this Convertible to be modified during conversion. Returns: Implementations should return the copied instance, which in turn should be contained in converted_enclosing_graph(). This instance is the one that will be modified during conversion. Its main use will be in the implementations of convert_variable_to_constant(). """ raise NotImplementedError() def convert_variable_to_constant(self, incoming_edge, tensor_data): """Converts a variable in this Convertible and its dependencies. This method should make sure that a converted copy of itself is present in the converted graph, and that all Convertibles depending on this one also go through the same process. Args: incoming_edge: The graph edge into this Convertible that is being converted to a constant. tensor_data: The tensor representing the constant. """ raise NotImplementedError() def create_edges(self): """Calls add_outgoing_edge for all edges known to this Convertible. This is used to build the graph dependencies, so that conversion of variables to constants can be properly propagated through the graph. Usually this method will call add_outgoing_edge() to all the Convertible inputs. """ raise NotImplementedError() def add_outgoing_edge(self, edge): """Adds an outgoing edge to the Convertible's list of edges. Args: edge: The outgoing edge (its source should be 'self'). """ self._outgoing_edges.append(edge) @property def converted_enclosing_graph(self): """The graph being converted.""" return self._enclosing_graph.converted_self() @property def outgoing_edges(self): """The list of edges starting at this Convertible.""" return self._outgoing_edges class _Function(_Convertible): """A library function Convertible. Edges into functions are edges from node _inputs_ into function _inputs_: Functions get their input from their callers, not from node outputs, and the callers in turn get those values as inputs. """ def __init__(self, function, enclosing_graph): super(_Function, self).__init__(enclosing_graph) self._function = function self._nodes = { n.name: _Node.new(node=n, function=self, enclosing_graph=enclosing_graph) for n in function.node_def } def __str__(self): return self.function.signature.name @property def function(self): return self._function @property def nodes(self): return self._nodes def converted_self(self): """The Function copy to be converted. The copy will be renamed according to the graph's converted_function_name map, to ensure the name does not match anything currently in TensorFlow's function cache. Returns: The function instance to be converted. """ if self._converted_self is None: old_name = self.function.signature.name new_name = self._enclosing_graph.converted_function_names[old_name] self.converted_enclosing_graph.rename_function(old_name, new_name) self._converted_self = self.converted_enclosing_graph.functions[new_name] return self._converted_self def convert_variable_to_constant(self, incoming_edge, tensor_data): """Converts one function argument into a constant. Args: incoming_edge: The edge into the argument to be converted. tensor_data: The constant value. """ function = self.converted_self().function index = incoming_edge.destination.index function.signature.input_arg[index].type = tensor_data.dtype for edge in self.outgoing_edges: if edge.source.index == index: edge.destination.convertible.convert_variable_to_constant( edge, tensor_data) def create_edges(self): for n in self._nodes.values(): n.create_edges() class _Node(_Convertible): """A Convertible NodeDef.""" def __init__(self, node, function, enclosing_graph): super(_Node, self).__init__(enclosing_graph) self._node = node self._function = function def __str__(self): return self._node.name @staticmethod def new(node, function, enclosing_graph): """Creates a new _Node base on its operation type.""" if node.op in ["VariableV2", "VarHandleOp", "Placeholder"]: return _VarHandle(node, function, enclosing_graph) elif node.op == "Case": return _Case(node, function, enclosing_graph) elif node.op == "Merge": return _Merge(node, function, enclosing_graph) elif node.op == "PartitionedCall": return _PartitionedCall(node, function, enclosing_graph) elif node.op == "ReadVariableOp": return _ReadVariable(node, function, enclosing_graph) elif node.op == "ResourceGather": return _ResourceGather(node, function, enclosing_graph) elif node.op == "ResourceGatherNd": return _ResourceGatherNd(node, function, enclosing_graph) elif node.op in ["If", "StatelessIf"]: return _If(node, function, enclosing_graph) elif node.op in ["While", "StatelessWhile"]: return _While(node, function, enclosing_graph) elif node.op in [ "Enter", "Exit", "Identity", "NextIteration", "Switch", "_SwitchN"]: return _Intermediate(node, function, enclosing_graph) else: return _Node(node, function, enclosing_graph) @property def node(self): return self._node @property def container(self): """The node container (either a graph or a function).""" if self._function is not None: return self._function.function return self._enclosing_graph.graph_def def converted_self(self): """The NodeDef to be converted. Returns: The NodeDef to be converted, which can come from either a graph for a function. Derived classes should call this (via 'super') to make sure the node is retrieved from the right place. """ if self._converted_self is None: source = self._function or self._enclosing_graph self._converted_self = source.converted_self().nodes[self._node.name] return self._converted_self def convert_variable_to_constant(self, incoming_edge, tensor_data): pass def create_edges(self): for index, name in enumerate(self._node.input): # Discard edges from control inputs. if name[0] == "^": continue source = self.resolve_input(name) source.convertible.add_outgoing_edge( _Edge(source, _EndPoint(self, index))) def resolve_input(self, input_name): """Resolves an input into its _EndPoint. A NodeDef's input name can refer to either global NodeDefs (in the GraphDef's node list), a NodeDef in a function's node list, or a Function (in the GraphDef's function library). The name can also carry semantic information, depending on whether it starts with "^". This method handles all that logic in order to find the object to which the input name refers to. Args: input_name: The input name to resolve. Returns: The object referred to by 'input_name'. """ # The logic below oversimplifes the semantics, but is good enough for the # purposes of converting to constants. The introduction of new types of # operations may change this, forcing the code to be more generic. # # In particular, we are assuming that the lack of an index suffix means # ":0", when it could mean "all the outputs of a node." This works now # because converting to constants relies very little on output types, and # when it does it specializes its treatment in dedicated classes. name_elts = input_name.split(":") source_name = name_elts[0] if source_name[0] == "^": source_name = source_name[1:] source_index = 0 if len(name_elts) > 1 and name_elts[-1].isnumeric(): source_index = int(name_elts[-1]) if self._function is None: return _EndPoint(self._enclosing_graph.nodes[source_name], source_index) if source_index != 0 or source_name in self._function.nodes: return _EndPoint(self._function.nodes[source_name], source_index) inputs = [i.name for i in self._function.function.signature.input_arg] return _EndPoint(self._function, inputs.index(source_name)) def update_dtype(self, attr_name, index, dtype): """Changes the type of a given input. Args: attr_name: The NodeDef attribute containing the type to change. index: The index of the input type to change. dtype: The type to change to. """ attr = self._node.attr[attr_name] num_types = 0 # Check for various 'oneof' possibilities, and update the type if # index in range. if attr.HasField("list"): types = attr.list.type num_types = len(types) if num_types > index: types[index] = dtype return elif attr.HasField("type"): num_types = 1 if index == 0: attr.type = dtype return raise ValueError( "Index %d out of range for node(%s).attr(%s), which has %d elements." % (index, self._node.name, attr_name, num_types)) class _Intermediate(_Node): """Specialization of _Node to intermediate ops.""" def convert_variable_to_constant(self, incoming_edge, tensor_data): node = self.converted_self() node.update_dtype("T", incoming_edge.destination.index, tensor_data.dtype) if "_output_shapes" in node.node.attr: del node.node.attr["_output_shapes"] for edge in self.outgoing_edges: edge.destination.convertible.convert_variable_to_constant( edge, tensor_data) class _Merge(_Node): """Specialization of _Node to Merge ops.""" def convert_variable_to_constant(self, incoming_edge, tensor_data): # The Merge operation has a single type for all its inputs, the number of # which is reflected in the "N" attribute. For the time being, we assume # that unilaterally changing all of them at once is ok. super(_Merge, self).convert_variable_to_constant( _Edge(incoming_edge.source, _Edge(incoming_edge.destination.convertible, 0)), tensor_data) class _VarHandle(_Node): """Specialization of _Node to VarHandleOp.""" def convert_variable_to_constant(self, incoming_edge, tensor_data): tensor_proto = tensor_util.make_tensor_proto(tensor_data.numpy, tensor_data.dtype, tensor_data.numpy.shape) node = self.converted_self().node node.Clear() node.name = self._node.name node.op = "Const" node.attr["dtype"].CopyFrom(tensor_data.dtype_attr) node.attr["value"].tensor.CopyFrom(tensor_proto) for edge in self.outgoing_edges: edge.destination.convertible.convert_variable_to_constant( edge, tensor_data) class _ResourceGather(_Node): """Specialization of _Node to ResourceGather.""" def convert_variable_to_constant(self, incoming_edge, tensor_data): # We currently skip the conversion if this is inside a function. if self._function is not None: return if self._node.attr["batch_dims"].i != 0: raise ValueError("batch_dims != 0 is not supported by freeze_graph.") axis_node_name = self._node.name + "/axis" axis_dtype = self._node.attr["Tindices"] axis_data = np.array(self._node.attr["batch_dims"].i) output_axis_node = self.converted_self().container.node.add() output_axis_node.name = axis_node_name output_axis_node.op = "Const" output_axis_node.attr["dtype"].CopyFrom(axis_dtype) tensor = tensor_util.make_tensor_proto( axis_data, dtype=axis_dtype.type, shape=axis_data.shape) output_axis_node.attr["value"].tensor.CopyFrom(tensor) output_node = self.converted_self().node output_node.Clear() output_node.name = self._node.name output_node.op = "GatherV2" output_node.input.extend( [self._node.input[0], self._node.input[1], axis_node_name]) output_node.attr["Tparams"].CopyFrom(self._node.attr["dtype"]) output_node.attr["Tindices"].CopyFrom(self._node.attr["Tindices"]) output_node.attr["Taxis"].CopyFrom(axis_dtype) if "_class" in self._node.attr: output_node.attr["_class"].CopyFrom(self._node.attr["_class"]) class _ResourceGatherNd(_Node): """Specialization of _Node to ResourceGatherNd.""" def convert_variable_to_constant(self, incoming_edge, tensor_data): output_node = self.converted_self().node output_node.Clear() output_node.name = self._node.name output_node.op = "GatherNd" output_node.input.extend([self._node.input[0], self._node.input[1]]) output_node.attr["Tparams"].CopyFrom(self._node.attr["dtype"]) output_node.attr["Tindices"].CopyFrom(self._node.attr["Tindices"]) if "_class" in self._node.attr: output_node.attr["_class"].CopyFrom(self._node.attr["_class"]) class _ReadVariable(_Node): """Specialization of _Node to ReadVariableOp.""" def convert_variable_to_constant(self, incoming_edge, tensor_data): node = self.converted_self().node node.Clear() node.name = self._node.name node.op = "Identity" node.input.append(self._node.input[0]) node.attr["T"].CopyFrom(self._node.attr["dtype"]) if "_class" in self._node.attr: node.attr["_class"].CopyFrom(self._node.attr["_class"]) # If the ReadVariableOp is part of a function, then every node having the # ReadVariableOp one as its input will refer to it using a ":value" # syntax. We need to change that to ":output". if self._function is not None: for edge in self.outgoing_edges: index = edge.destination.index dest = edge.destination.convertible.converted_self() if isinstance(dest, _Node): input_name_parts = dest.node.input[index].split(":") if len(input_name_parts) > 1 and input_name_parts[1] == "value": input_name_parts[1] = "output" dest.node.input[index] = ":".join(input_name_parts) class _FunctionCaller(_Node): """A base class for Convertibles that reference functions.""" def __init__(self, node, function, enclosing_graph, first_function_input, type_attribute, function_attributes): """Initializes a _FunctionCaller. Args: node: As in _Node. function: As in _Node. enclosing_graph: As in _Node. first_function_input: The index of the first NodeDef input that is tied to the function inputs. It is assumed that the rest of the NodeDef inputs map one to one to function inputs. type_attribute: The name of the NodeDef attribute that defines the input types. It is assumed that the types listed here map one-to-one with the function inputs (that is, they do _not_ specify types for inputs that are not passed to functions). function_attributes: The names of the NodeDef attributes containing references to functions. """ super(_FunctionCaller, self).__init__(node, function, enclosing_graph) self._first_function_input = first_function_input self._type_attribute = type_attribute self._function_attributes = function_attributes def converted_self(self): if self._converted_self is None: node = super(_FunctionCaller, self).converted_self().node converted_names = self._enclosing_graph.converted_function_names for attr_name in self._function_attributes: attr = node.attr[attr_name] if attr.HasField("func"): attr.func.name = converted_names[attr.func.name] elif attr.HasField("list"): for func in attr.list.func: func.name = converted_names[func.name] return self._converted_self def convert_variable_to_constant(self, incoming_edge, tensor_data): node = self.converted_self() index = incoming_edge.destination.index if index >= self._first_function_input: node.update_dtype(self._type_attribute, index - self._first_function_input, tensor_data.dtype) # The loop below is reasonable but not correct in general: # The outgoing edges going into the functions are correct, because the # inputs map to the function inputs. But the edges going into other nodes do # not take into account the logic of the body function, which may do # arbitrary things to the node's output: # # while x < 0: # return y # # In this case, the node's ":0" output may map to its ":1 input". For the # time being, then, we only process edges into functions. for edge in self.outgoing_edges: dest = edge.destination.convertible if edge.source.index == index and isinstance(dest, _Function): dest.convert_variable_to_constant(edge, tensor_data) def create_edges(self): """Creates edges related to a function caller. Edges from a function caller to its called functions are always edges from _inputs_ to _inputs_: a FunctionDef input is given by the caller, based on its own inputs. """ super(_FunctionCaller, self).create_edges() for attr_name in self._function_attributes: attr = self._node.attr[attr_name] if attr.HasField("func"): function = self._enclosing_graph.functions[attr.func.name] for index in range(len(self._node.input) - self._first_function_input): self.add_outgoing_edge( _Edge( _EndPoint(self, index + self._first_function_input), _EndPoint(function, index))) elif attr.HasField("list"): for func in attr.list.func: function = self._enclosing_graph.functions[func.name] for index in range( len(self._node.input) - self._first_function_input): self.add_outgoing_edge( _Edge( _EndPoint(self, index + self._first_function_input), _EndPoint(function, index))) class _If(_FunctionCaller): """Specialization of _Node to If-like operations.""" def __init__(self, node, function, enclosing_graph): super(_If, self).__init__( node, function, enclosing_graph, first_function_input=1, type_attribute="Tin", function_attributes=["then_branch", "else_branch"]) class _Case(_FunctionCaller): """Specialization of _Node to Case-like operations.""" def __init__(self, node, function, enclosing_graph): super(_Case, self).__init__( node, function, enclosing_graph, first_function_input=1, type_attribute="Tin", function_attributes=["branches"]) class _PartitionedCall(_FunctionCaller): """Specialization of _Node to PartitionedCall-like operations.""" def __init__(self, node, function, enclosing_graph): super(_PartitionedCall, self).__init__( node, function, enclosing_graph, first_function_input=0, type_attribute="Tin", function_attributes=["f"]) class _While(_FunctionCaller): """Specialization of _Node to While-like operations.""" def __init__(self, node, function, enclosing_graph): super(_While, self).__init__( node, function, enclosing_graph, first_function_input=0, type_attribute="T", function_attributes=["body", "cond"]) def convert_variable_to_constant(self, incoming_edge, tensor_data): super(_While, self).convert_variable_to_constant(incoming_edge, tensor_data) node = self.converted_self() if node.node.attr["output_shapes"].list.shape: node.node.attr["output_shapes"].list.shape[ incoming_edge.destination.index].CopyFrom( tensor_shape_pb2.TensorShapeProto(dim=[ tensor_shape_pb2.TensorShapeProto.Dim(size=dim) for dim in tensor_data.numpy.shape ])) # The while's body inputs and outputs have the same type, so here we can go # ahead and change that function's output type. body_name = self._node.attr["body"].func.name body = self._enclosing_graph.functions[body_name].converted_self().function body.signature.output_arg[ incoming_edge.destination.index].type = tensor_data.dtype class _GraphDef(_Convertible): """A convertible GraphDef.""" def __init__(self, graph_def): super(_GraphDef, self).__init__(enclosing_graph=None) self._graph_def = graph_def self._nodes = { n.name: _Node.new(node=n, function=None, enclosing_graph=self) for n in graph_def.node } self._functions = { f.signature.name: _Function(f, enclosing_graph=self) for f in graph_def.library.function } self.create_edges() self._converted_function_names = None @property def graph_def(self): return self._graph_def @property def nodes(self): return self._nodes @property def functions(self): return self._functions @property def converted_function_names(self): """Map from original to new function names. In order to avoid conflicts (two functions with the same name, one converted and one not), we need to change the name of every converted function to something that is hopefully unique. Returns: Map from original to new suggested function names. """ if self._converted_function_names is None: parsed_names = [] # List of (id, base_name, original_name) for name in self.functions: elements = name.rsplit("_", 1) if len(elements) == 2 and elements[1].isnumeric(): parsed_names.append((int(elements[1]), elements[0], name)) else: parsed_names.append((-1, name, name)) self._converted_function_names = { name: "{}_frozen_{}".format(base_name, ops.uid()) for (_, base_name, name) in sorted(parsed_names) } return self._converted_function_names def rename_function(self, old_name, new_name): func = self.functions.pop(old_name) func.function.signature.name = new_name self.functions[new_name] = func def converted_self(self): if self._converted_self is None: copied_graph = graph_pb2.GraphDef() copied_graph.CopyFrom(self._graph_def) self._converted_self = _GraphDef(copied_graph) return self._converted_self def create_edges(self): for n in self._nodes.values(): n.create_edges() for f in self._functions.values(): f.create_edges() class _ConverterData(object): """Container for constant conversion supporting data. The data includes the graph being converted, and the pre-converted tensors. This class will be specialized for ConcreteFunction and Session-based conversions, as the means to obtain that data is different for each case. """ def __init__(self, graph_def, variable_names_allowlist=None, variable_names_denylist=None): self._graph_def = graph_def self._tensor_data = {} self._build_node_defs_list() self._variable_names_allowlist = variable_names_allowlist self._variable_names_denylist = variable_names_denylist @property def graph_def(self): """The graph to be converted.""" return self._graph_def @property def node_defs(self): """All the node defs in the graph to be converted. Returns: A map from node name to the NodeDef for all NodeDefs in the graph, as well as all control flow NodeDefs in the functions. """ return self._node_defs @property def tensor_data(self): """A map from tensor name to its converted _TensorData.""" return self._tensor_data def _should_convert(self, name): """Checks whether to convert the given variable name to a constant.""" return (self._variable_names_allowlist is None or name in self._variable_names_allowlist) and ( self._variable_names_denylist is None or name not in self._variable_names_denylist) def _build_node_defs_list(self): """Builds the list of NodeDefs in the GraphDef. This list consists of all NodeDefs in the main graph as well as all control flow NodeDefs in the functions. The remaining NodeDefs in the functions are not included because the op names are not unique and the variables are handled differently than the main graph. The control flow ops need to be extracted because they are need their attributes to be updated similar to the control flow ops in the main graph. """ self._node_defs = {node.name: node for node in self._graph_def.node} if self._graph_def.library: for func in self._graph_def.library.function: self._node_defs.update({ node.name: node for node in func.node_def if node.op in _CONTROL_FLOW_OPS }) class _FunctionConverterData(_ConverterData): """Container for ConcreteFunction-based conversion data.""" def __init__(self, func, lower_control_flow, aggressive_inlining, variable_names_allowlist=None, variable_names_denylist=None): """Creates the conversion data for the given function. Args: func: ConcreteFunction. lower_control_flow: Boolean indicating whether or not to lower control flow ops such as If and While. aggressive_inlining: Boolean indicating whether or not to to aggressive function inlining (might be unsafe if function has stateful ops, not properly connected to control outputs). variable_names_allowlist: The set of variable names to convert (by default, all variables are converted). variable_names_denylist: The set of variable names to omit converting to constants. """ self._func = func # Inline the graph in order to remove functions when possible. graph_def = _run_inline_graph_optimization(func, lower_control_flow, aggressive_inlining) super(_FunctionConverterData, self).__init__( graph_def, variable_names_allowlist=variable_names_allowlist, variable_names_denylist=variable_names_denylist) self._build_tensor_data() def _build_tensor_data(self): """Caches the tensor data for all Placeholders in the given function.""" map_index_to_variable = {} for var in self._func.graph.variables: for idx, captured_input in enumerate(self._func.captured_inputs): if var.handle is captured_input: # pylint: disable=protected-access map_index_to_variable[idx] = var break # Iterates through all captures which are represented as Placeholders. for idx, (val_tensor, name_tensor) in enumerate(self._func.graph.captures): tensor_name = name_tensor.name.split(":")[0] if not self._should_convert(tensor_name): continue if idx in map_index_to_variable: data = map_index_to_variable[idx].numpy() else: data = val_tensor.numpy() self._tensor_data[tensor_name] = _TensorData( numpy=data, dtype=dtypes.as_dtype(data.dtype).as_datatype_enum, index=idx) # Get data for VariableV2 ops (reference variables) that cannot be lifted. for node in self.node_defs.values(): if node.op == "VariableV2": if not self._should_convert(node.name): continue if node.name not in self.tensor_data: with self._func.graph.as_default(): identity_node = array_ops.identity( self._func.graph.as_graph_element(node.name + ":0")) pruned_graph = self._func.prune([], [identity_node.name])()[0] self._tensor_data[node.name] = _TensorData( numpy=pruned_graph.numpy(), dtype=node.attr["dtype"].type, index=None) class _SessionConverterData(_ConverterData): """Container for Session-based conversion data.""" def __init__(self, session, graph_def, output_node_names, variable_names_allowlist=None, variable_names_denylist=None): graph_def = graph_util.extract_sub_graph(graph_def, output_node_names) super(_SessionConverterData, self).__init__( graph_def, variable_names_allowlist=variable_names_allowlist, variable_names_denylist=variable_names_denylist) nodes_to_convert = [] tensor_names_to_convert = [] for node in self.graph_def.node: if node.op in ["Variable", "VariableV2", "VarHandleOp"]: tensor_name = node.name if not self._should_convert(tensor_name): continue if node.op == "VarHandleOp": tensor_name = tensor_name + "/Read/ReadVariableOp" nodes_to_convert.append(node) tensor_names_to_convert.append(tensor_name + ":0") if tensor_names_to_convert: converted_tensors = session.run(tensor_names_to_convert) for node, tensor_value in zip(nodes_to_convert, converted_tensors): self._tensor_data[node.name] = _TensorData( numpy=tensor_value, dtype=node.attr["dtype"].type, index=None) def disable_lower_using_switch_merge(graph_def): """Set '_lower_using_switch_merge' attributes to False. Sets the attribute to False in the NodeDefs in the main graph and the NodeDefs in each function's graph. Args: graph_def: GraphDef proto. Returns: GraphDef """ output_graph_def = graph_pb2.GraphDef() output_graph_def.CopyFrom(graph_def) def disable_control_flow_lowering(node): if node.op in _CONTROL_FLOW_OPS: node.attr["_lower_using_switch_merge"].b = False for node in output_graph_def.node: disable_control_flow_lowering(node) if output_graph_def.library: for func in output_graph_def.library.function: for node in func.node_def: disable_control_flow_lowering(node) return output_graph_def def _run_inline_graph_optimization(func, lower_control_flow, aggressive_inlining): """Apply function inline optimization to the graph. Returns the GraphDef after Grappler's function inlining optimization is applied. This optimization does not work on models with control flow. Args: func: ConcreteFunction. lower_control_flow: Boolean indicating whether or not to lower control flow ops such as If and While. (default True) aggressive_inlining: Boolean indicating whether or not to to aggressive function inlining (might be unsafe if function has stateful ops not properly connected to control outputs). Returns: GraphDef """ graph_def = func.graph.as_graph_def() if not lower_control_flow: graph_def = disable_lower_using_switch_merge(graph_def) # In some cases, a secondary implementation of the function (e.g. for GPU) is # written to the "api_implements" attribute. (e.g. `tf.keras.layers.LSTM` in # TF2 produces a CuDNN-based RNN for GPU). # This function suppose to inline all functions calls, but "api_implements" # prevents this from happening. Removing the attribute solves the problem. # To learn more about "api_implements", see: # tensorflow/core/grappler/optimizers/implementation_selector.h for function in graph_def.library.function: if "api_implements" in function.attr: del function.attr["api_implements"] meta_graph = export_meta_graph(graph_def=graph_def, graph=func.graph) # Clear the initializer_name for the variables collections, since they are not # needed after saved to saved_model. for name in [ "variables", "model_variables", "trainable_variables", "local_variables" ]: raw_list = [] for raw in meta_graph.collection_def["variables"].bytes_list.value: variable = variable_pb2.VariableDef() variable.ParseFromString(raw) variable.ClearField("initializer_name") raw_list.append(variable.SerializeToString()) meta_graph.collection_def[name].bytes_list.value[:] = raw_list # Add a collection 'train_op' so that Grappler knows the outputs. fetch_collection = meta_graph_pb2.CollectionDef() for array in func.inputs + func.outputs: fetch_collection.node_list.value.append(array.name) meta_graph.collection_def["train_op"].CopyFrom(fetch_collection) # Initialize RewriterConfig with everything disabled except function inlining. config = config_pb2.ConfigProto() rewrite_options = config.graph_options.rewrite_options rewrite_options.min_graph_nodes = -1 # do not skip small graphs rewrite_options.optimizers.append("function") if aggressive_inlining: rewrite_options.function_optimization =\ rewriter_config_pb2.RewriterConfig.AGGRESSIVE return tf_optimizer.OptimizeGraph(config, meta_graph) def _construct_concrete_function(func, output_graph_def, converted_input_indices): """Constructs a concrete function from the `output_graph_def`. Args: func: ConcreteFunction output_graph_def: GraphDef proto. converted_input_indices: Set of integers of input indices that were converted to constants. Returns: ConcreteFunction. """ # Create a ConcreteFunction from the new GraphDef. input_tensors = func.graph.internal_captures converted_inputs = object_identity.ObjectIdentitySet( [input_tensors[index] for index in converted_input_indices]) not_converted_inputs = [ tensor for tensor in func.inputs if tensor not in converted_inputs ] not_converted_inputs_map = { tensor.name: tensor for tensor in not_converted_inputs } new_input_names = [tensor.name for tensor in not_converted_inputs] new_output_names = [tensor.name for tensor in func.outputs] new_func = wrap_function.function_from_graph_def(output_graph_def, new_input_names, new_output_names) # Manually propagate shape for input tensors where the shape is not correctly # propagated. Scalars shapes are lost when wrapping the function. for input_tensor in new_func.inputs: input_tensor.set_shape(not_converted_inputs_map[input_tensor.name].shape) return new_func def _replace_variables_by_constants(converter_data): """Replaces variables by constants on a given graph. Given a _ConverterData instance with converted variables in its tensor_data field, create a new graph where the respective variables are replaced with the converted constants. Args: converter_data: A pre-populated _ConverterData instance. Returns: The converted graph. """ input_graph = _GraphDef(converter_data.graph_def) for tensor_name, tensor_data in converter_data.tensor_data.items(): input_graph.nodes[tensor_name].convert_variable_to_constant( None, tensor_data) converted_graph = input_graph.converted_self().graph_def converted_input_indices = { t.index for t in converter_data.tensor_data.values() if t.index is not None } return converted_graph, converted_input_indices def convert_variables_to_constants_v2(func, lower_control_flow=True, aggressive_inlining=False): """Replaces all the variables in a graph with constants of the same values. TensorFlow 2.0 function for converting all Variable ops into Const ops holding the same values. This makes it possible to describe the network fully with a single GraphDef file, and allows the removal of a lot of ops related to loading and saving the variables. This function runs Grappler's function inlining optimization in order to return a single subgraph. The current implementation only works for graphs that do not contain any control flow or embedding related ops. Args: func: ConcreteFunction. lower_control_flow: Boolean indicating whether or not to lower control flow ops such as If and While. (default True) aggressive_inlining: Boolean indicating whether or not to to aggressive function inlining (might be unsafe if function has stateful ops, not properly connected to control outputs). (default False) Returns: ConcreteFunction containing a simplified version of the original. """ converter_data = _FunctionConverterData( func=func, lower_control_flow=lower_control_flow, aggressive_inlining=aggressive_inlining) output_graph_def, converted_input_indices = _replace_variables_by_constants( converter_data=converter_data) return _construct_concrete_function(func, output_graph_def, converted_input_indices) def convert_variables_to_constants_v2_as_graph(func, lower_control_flow=True, aggressive_inlining=False): """Replaces all the variables in a graph with constants of the same values. This function works as same as convert_variables_to_constants_v2, but it returns the intermediate `GraphDef` as well. This `GraphDef` contains all the debug information after all the transformations in the frozen phase. Args: func: ConcreteFunction. lower_control_flow: Boolean indicating whether or not to lower control flow ops such as If and While. (default True) aggressive_inlining: Boolean indicating whether or not to to aggressive function inlining (might be unsafe if function has stateful ops, not properly connected to control outputs). Returns: ConcreteFunction containing a simplified version of the original, and also the intermediate GraphDef containing the node debug information for the transformations in the frozen phase. """ converter_data = _FunctionConverterData( func=func, lower_control_flow=lower_control_flow, aggressive_inlining=aggressive_inlining) output_graph_def, converted_input_indices = _replace_variables_by_constants( converter_data=converter_data) frozen_func = _construct_concrete_function(func, output_graph_def, converted_input_indices) return frozen_func, output_graph_def def convert_variables_to_constants_from_session_graph( session, graph_def, output_node_names, variable_names_allowlist=None, variable_names_denylist=None): """Replaces all the variables in a graph with constants of the same values. This function works similarly to convert_variables_to_constants_v2, but it retrieves the constant values from a Session instead of from a ConcreteFunction. This is useful when converting graphs generated from TensorFlow V1, where ConcreteFunctions are not available. This also differs from graph_util.convert_variables_to_constants in that it supports resource variables when V2 control flow constructions are present. Args: session: Active TensorFlow session containing the variables. graph_def: A GraphDef to convert. output_node_names: List of name strings for the result nodes of the graph. variable_names_allowlist: The set of variable names to convert (by default, all variables are converted). variable_names_denylist: The set of variable names to omit converting to constants. Returns: An optimized GraphDef. """ graph_def, _ = _replace_variables_by_constants( converter_data=_SessionConverterData( session=session, graph_def=graph_def, output_node_names=output_node_names, variable_names_allowlist=variable_names_allowlist, variable_names_denylist=variable_names_denylist)) return graph_def
#!/usr/bin/python # # Copyright (c) 2019 Zim Kalinowski, (@zikalino) # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: azure_rm_mysqlconfiguration version_added: "2.8" short_description: Manage Configuration instance description: - Create, update and delete instance of Configuration. options: resource_group: description: - The name of the resource group that contains the resource. required: True server_name: description: - The name of the server. required: True name: description: - The name of the server configuration. required: True value: description: - Value of the configuration. state: description: - Assert the state of the MySQL configuration. Use C(present) to update setting, or C(absent) to reset to default value. default: present choices: - absent - present extends_documentation_fragment: - azure author: - Zim Kalinowski (@zikalino) ''' EXAMPLES = ''' - name: Update SQL Server setting azure_rm_mysqlconfiguration: resource_group: myResourceGroup server_name: myServer name: event_scheduler value: "ON" ''' RETURN = ''' id: description: - Resource ID. returned: always type: str sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DBforMySQL/servers/myServer/confi gurations/event_scheduler" ''' import time from ansible.module_utils.azure_rm_common import AzureRMModuleBase try: from msrestazure.azure_exceptions import CloudError from msrest.polling import LROPoller from azure.mgmt.rdbms.mysql import MySQLManagementClient from msrest.serialization import Model except ImportError: # This is handled in azure_rm_common pass class Actions: NoAction, Create, Update, Delete = range(4) class AzureRMMySqlConfiguration(AzureRMModuleBase): def __init__(self): self.module_arg_spec = dict( resource_group=dict( type='str', required=True ), server_name=dict( type='str', required=True ), name=dict( type='str', required=True ), value=dict( type='str' ), state=dict( type='str', default='present', choices=['present', 'absent'] ) ) self.resource_group = None self.server_name = None self.name = None self.value = None self.results = dict(changed=False) self.state = None self.to_do = Actions.NoAction super(AzureRMMySqlConfiguration, self).__init__(derived_arg_spec=self.module_arg_spec, supports_check_mode=True, supports_tags=False) def exec_module(self, **kwargs): for key in list(self.module_arg_spec.keys()): if hasattr(self, key): setattr(self, key, kwargs[key]) old_response = None response = None old_response = self.get_configuration() if not old_response: self.log("Configuration instance doesn't exist") if self.state == 'absent': self.log("Old instance didn't exist") else: self.to_do = Actions.Create else: self.log("Configuration instance already exists") if self.state == 'absent' and old_response['source'] == 'user-override': self.to_do = Actions.Delete elif self.state == 'present': self.log("Need to check if Configuration instance has to be deleted or may be updated") if self.value != old_response.get('value'): self.to_do = Actions.Update if (self.to_do == Actions.Create) or (self.to_do == Actions.Update): self.log("Need to Create / Update the Configuration instance") if self.check_mode: self.results['changed'] = True return self.results response = self.create_update_configuration() self.results['changed'] = True self.log("Creation / Update done") elif self.to_do == Actions.Delete: self.log("Configuration instance deleted") self.results['changed'] = True if self.check_mode: return self.results self.delete_configuration() else: self.log("Configuration instance unchanged") self.results['changed'] = False response = old_response if response: self.results["id"] = response["id"] return self.results def create_update_configuration(self): self.log("Creating / Updating the Configuration instance {0}".format(self.name)) try: response = self.mysql_client.configurations.create_or_update(resource_group_name=self.resource_group, server_name=self.server_name, configuration_name=self.name, value=self.value, source='user-override') if isinstance(response, LROPoller): response = self.get_poller_result(response) except CloudError as exc: self.log('Error attempting to create the Configuration instance.') self.fail("Error creating the Configuration instance: {0}".format(str(exc))) return response.as_dict() def delete_configuration(self): self.log("Deleting the Configuration instance {0}".format(self.name)) try: response = self.mysql_client.configurations.create_or_update(resource_group_name=self.resource_group, server_name=self.server_name, configuration_name=self.name, source='system-default') except CloudError as e: self.log('Error attempting to delete the Configuration instance.') self.fail("Error deleting the Configuration instance: {0}".format(str(e))) return True def get_configuration(self): self.log("Checking if the Configuration instance {0} is present".format(self.name)) found = False try: response = self.mysql_client.configurations.get(resource_group_name=self.resource_group, server_name=self.server_name, configuration_name=self.name) found = True self.log("Response : {0}".format(response)) self.log("Configuration instance : {0} found".format(response.name)) except CloudError as e: self.log('Did not find the Configuration instance.') if found is True: return response.as_dict() return False def main(): """Main execution""" AzureRMMySqlConfiguration() if __name__ == '__main__': main()
# 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. from __future__ import division from .base import Layout class _BspNode(): def __init__(self, parent=None): self.parent = parent self.children = [] self.split_horizontal = None self.split_ratio = 50 self.client = None self.x = self.y = 0 self.w = 16 self.h = 9 def __iter__(self): yield self for child in self.children: for c in child: yield c def clients(self): if self.client: yield self.client else: for child in self.children: for c in child.clients(): yield c def _shortest(self, l): if len(self.children) == 0: return self, l else: c0, l0 = self.children[0]._shortest(l + 1) c1, l1 = self.children[1]._shortest(l + 1) return (c1, l1) if l1 < l0 else (c0, l0) def get_shortest(self): return self._shortest(0)[0] def insert(self, client, idx, ratio): if self.client is None: self.client = client return self self.children = [_BspNode(self), _BspNode(self)] self.children[1 - idx].client = self.client self.children[idx].client = client self.client = None self.split_horizontal = True if self.w > self.h * ratio else False return self.children[idx] def remove(self, child): keep = self.children[1 if child is self.children[0] else 0] self.children = keep.children for c in self.children: c.parent = self self.split_horizontal = keep.split_horizontal self.split_ratio = keep.split_ratio self.client = keep.client return self def distribute(self): if len(self.children) == 0: return 1, 1 h0, v0 = self.children[0].distribute() h1, v1 = self.children[1].distribute() if self.split_horizontal: h = h0 + h1 v = max(v0, v1) self.split_ratio = 100 * h0 / h else: h = max(h0, h1) v = v0 + v1 self.split_ratio = 100 * v0 / v return h, v def calc_geom(self, x, y, w, h): self.x = x self.y = y self.w = w self.h = h if len(self.children) > 1: if self.split_horizontal: w0 = int(self.split_ratio * w * 0.01 + 0.5) self.children[0].calc_geom(x, y, w0, h) self.children[1].calc_geom(x + w0, y, w - w0, h) else: h0 = int(self.split_ratio * h * 0.01 + 0.5) self.children[0].calc_geom(x, y, w, h0) self.children[1].calc_geom(x, y + h0, w, h - h0) class Bsp(Layout): """This layout is inspired by bspwm, but it does not try to copy its features. The first client occupies the entire srceen space. When a new client is created, the selected space is partitioned in 2 and the new client occupies one of those subspaces, leaving the old client with the other. The partition can be either horizontal or vertical according to the dimensions of the current space: if its width/height ratio is above a pre-configured value, the subspaces are created side-by-side, otherwise, they are created on top of each other. The partition direction can be freely toggled. All subspaces can be resized and clients can be shuffled around. An example key configuration is:: Key([mod], "j", lazy.layout.down()), Key([mod], "k", lazy.layout.up()), Key([mod], "h", lazy.layout.left()), Key([mod], "l", lazy.layout.right()), Key([mod, "shift"], "j", lazy.layout.shuffle_down()), Key([mod, "shift"], "k", lazy.layout.shuffle_up()), Key([mod, "shift"], "h", lazy.layout.shuffle_left()), Key([mod, "shift"], "l", lazy.layout.shuffle_right()), Key([mod, "mod1"], "j", lazy.layout.flip_down()), Key([mod, "mod1"], "k", lazy.layout.flip_up()), Key([mod, "mod1"], "h", lazy.layout.flip_left()), Key([mod, "mod1"], "l", lazy.layout.flip_right()), Key([mod, "control"], "j", lazy.layout.grow_down()), Key([mod, "control"], "k", lazy.layout.grow_up()), Key([mod, "control"], "h", lazy.layout.grow_left()), Key([mod, "control"], "l", lazy.layout.grow_right()), Key([mod, "shift"], "n", lazy.layout.normalize()), Key([mod], "Return", lazy.layout.toggle_split()), """ defaults = [ ("name", "bsp", "Name of this layout."), ("border_focus", "#881111", "Border colour for the focused window."), ("border_normal", "#220000", "Border colour for un-focused windows."), ("border_width", 2, "Border width."), ("margin", 0, "Margin of the layout."), ("ratio", 1.6, "Width/height ratio that defines the partition direction."), ("grow_amount", 10, "Amount by which to grow a window/column."), ("lower_right", True, "New client occupies lower or right subspace."), ("fair", True, "New clients are inserted in the shortest branch."), ] def __init__(self, **config): Layout.__init__(self, **config) self.add_defaults(Bsp.defaults) self.root = _BspNode() self.current = self.root def clone(self, group): c = Layout.clone(self, group) c.root = _BspNode() c.current = c.root return c def info(self): return dict( name=self.name, clients=[c.name for c in self.root.clients()]) def get_node(self, client): for node in self.root: if client is node.client: return node def focus(self, client): self.current = self.get_node(client) def add(self, client): node = self.root.get_shortest() if self.fair else self.current self.current = node.insert(client, int(self.lower_right), self.ratio) def remove(self, client): node = self.get_node(client) if node.parent: node = node.parent.remove(node) newclient = next(node.clients(), None) if newclient is None: self.current = self.root return newclient node.client = None self.current = self.root def configure(self, client, screen): self.root.calc_geom(screen.x, screen.y, screen.width, screen.height) node = self.get_node(client) color = self.group.qtile.colorPixel( self.border_focus if client.has_focus else self.border_normal) border = 0 if node is self.root else self.border_width client.place( node.x, node.y, node.w - 2 * border, node.h - 2 * border, border, color, margin=self.margin) client.unhide() def cmd_toggle_split(self): if self.current.parent: self.current.parent.split_horizontal = not self.current.parent.split_horizontal self.group.layoutAll() def focus_first(self): return next(self.root.clients(), None) def focus_last(self): clients = list(self.root.clients()) return clients[-1] if len(clients) else None def focus_next(self, client): clients = list(self.root.clients()) if client in clients: idx = clients.index(client) if idx + 1 < len(clients): return clients[idx + 1] def focus_previous(self, client): clients = list(self.root.clients()) if client in clients: idx = clients.index(client) if idx > 0: return clients[idx - 1] def cmd_next(self): client = self.focus_next(self.current) if client: self.group.focus(client, True) def cmd_previous(self): client = self.focus_previous(self.current) if client: self.group.focus(client, True) def find_left(self): child = self.current parent = child.parent while parent: if parent.split_horizontal and child is parent.children[1]: neighbor = parent.children[0] center = self.current.y + self.current.h * 0.5 while neighbor.client is None: if neighbor.split_horizontal or neighbor.children[1].y < center: neighbor = neighbor.children[1] else: neighbor = neighbor.children[0] return neighbor child = parent parent = child.parent def find_right(self): child = self.current parent = child.parent while parent: if parent.split_horizontal and child is parent.children[0]: neighbor = parent.children[1] center = self.current.y + self.current.h * 0.5 while neighbor.client is None: if neighbor.split_horizontal or neighbor.children[1].y > center: neighbor = neighbor.children[0] else: neighbor = neighbor.children[1] return neighbor child = parent parent = child.parent def find_up(self): child = self.current parent = child.parent while parent: if not parent.split_horizontal and child is parent.children[1]: neighbor = parent.children[0] center = self.current.x + self.current.w * 0.5 while neighbor.client is None: if not neighbor.split_horizontal or neighbor.children[1].x < center: neighbor = neighbor.children[1] else: neighbor = neighbor.children[0] return neighbor child = parent parent = child.parent def find_down(self): child = self.current parent = child.parent while parent: if not parent.split_horizontal and child is parent.children[0]: neighbor = parent.children[1] center = self.current.x + self.current.w * 0.5 while neighbor.client is None: if not neighbor.split_horizontal or neighbor.children[1].x > center: neighbor = neighbor.children[0] else: neighbor = neighbor.children[1] return neighbor child = parent parent = child.parent def cmd_left(self): node = self.find_left() if node: self.group.focus(node.client, True) def cmd_right(self): node = self.find_right() if node: self.group.focus(node.client, True) def cmd_up(self): node = self.find_up() if node: self.group.focus(node.client, True) def cmd_down(self): node = self.find_down() if node: self.group.focus(node.client, True) def cmd_shuffle_left(self): node = self.find_left() if node: node.client, self.current.client = self.current.client, node.client self.current = node self.group.layoutAll() elif self.current is not self.root: node = self.current self.remove(node.client) newroot = _BspNode() newroot.split_horizontal = True newroot.children = [node, self.root] self.root.parent = newroot node.parent = newroot self.root = newroot self.current = node self.group.layoutAll() def cmd_shuffle_right(self): node = self.find_right() if node: node.client, self.current.client = self.current.client, node.client self.current = node self.group.layoutAll() elif self.current is not self.root: node = self.current self.remove(node.client) newroot = _BspNode() newroot.split_horizontal = True newroot.children = [self.root, node] self.root.parent = newroot node.parent = newroot self.root = newroot self.current = node self.group.layoutAll() def cmd_shuffle_up(self): node = self.find_up() if node: node.client, self.current.client = self.current.client, node.client self.current = node self.group.layoutAll() elif self.current is not self.root: node = self.current self.remove(node.client) newroot = _BspNode() newroot.split_horizontal = False newroot.children = [node, self.root] self.root.parent = newroot node.parent = newroot self.root = newroot self.current = node self.group.layoutAll() def cmd_shuffle_down(self): node = self.find_down() if node: node.client, self.current.client = self.current.client, node.client self.current = node self.group.layoutAll() elif self.current is not self.root: node = self.current self.remove(node.client) newroot = _BspNode() newroot.split_horizontal = False newroot.children = [self.root, node] self.root.parent = newroot node.parent = newroot self.root = newroot self.current = node self.group.layoutAll() def cmd_grow_left(self): child = self.current parent = child.parent while parent: if parent.split_horizontal and child is parent.children[1]: parent.split_ratio = max(5, parent.split_ratio - self.grow_amount) self.group.layoutAll() break child = parent parent = child.parent def cmd_grow_right(self): child = self.current parent = child.parent while parent: if parent.split_horizontal and child is parent.children[0]: parent.split_ratio = min(95, parent.split_ratio + self.grow_amount) self.group.layoutAll() break child = parent parent = child.parent def cmd_grow_up(self): child = self.current parent = child.parent while parent: if not parent.split_horizontal and child is parent.children[1]: parent.split_ratio = max(5, parent.split_ratio - self.grow_amount) self.group.layoutAll() break child = parent parent = child.parent def cmd_grow_down(self): child = self.current parent = child.parent while parent: if not parent.split_horizontal and child is parent.children[0]: parent.split_ratio = min(95, parent.split_ratio + self.grow_amount) self.group.layoutAll() break child = parent parent = child.parent def cmd_flip_left(self): child = self.current parent = child.parent while parent: if parent.split_horizontal and child is parent.children[1]: parent.children = parent.children[::-1] self.group.layoutAll() break child = parent parent = child.parent def cmd_flip_right(self): child = self.current parent = child.parent while parent: if parent.split_horizontal and child is parent.children[0]: parent.children = parent.children[::-1] self.group.layoutAll() break child = parent parent = child.parent def cmd_flip_up(self): child = self.current parent = child.parent while parent: if not parent.split_horizontal and child is parent.children[1]: parent.children = parent.children[::-1] self.group.layoutAll() break child = parent parent = child.parent def cmd_flip_down(self): child = self.current parent = child.parent while parent: if not parent.split_horizontal and child is parent.children[0]: parent.children = parent.children[::-1] self.group.layoutAll() break child = parent parent = child.parent def cmd_normalize(self): distribute = True for node in self.root: if node.split_ratio != 50: node.split_ratio = 50 distribute = False if distribute: self.root.distribute() self.group.layoutAll()
# coding=utf-8 r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from tests import IntegrationTestCase from tests.holodeck import Request from twilio.base.exceptions import TwilioException from twilio.http.response import Response class BindingTestCase(IntegrationTestCase): def test_fetch_request(self): self.holodeck.mock(Response(500, '')) with self.assertRaises(TwilioException): self.client.notify.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ .bindings("BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() self.holodeck.assert_has_request(Request( 'get', 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings/BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', )) def test_fetch_response(self): self.holodeck.mock(Response( 200, ''' { "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "address": "a7c658f4111ec4ff5a1a647f9d0edd819025b9f20522d2fae897049f32873e73", "binding_type": "apn", "credential_sid": null, "date_created": "2015-07-30T20:00:00Z", "date_updated": "2015-07-30T20:00:00Z", "endpoint": "26607274", "identity": "24987039", "notification_protocol_version": "3", "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "sid": "BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "tags": [ "26607274" ], "links": { "user": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/24987039" }, "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings/BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" } ''' )) actual = self.client.notify.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ .bindings("BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() self.assertIsNotNone(actual) def test_delete_request(self): self.holodeck.mock(Response(500, '')) with self.assertRaises(TwilioException): self.client.notify.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ .bindings("BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() self.holodeck.assert_has_request(Request( 'delete', 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings/BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', )) def test_delete_response(self): self.holodeck.mock(Response( 204, None, )) actual = self.client.notify.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ .bindings("BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() self.assertTrue(actual) def test_create_request(self): self.holodeck.mock(Response(500, '')) with self.assertRaises(TwilioException): self.client.notify.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ .bindings.create(identity="identity", binding_type="apn", address="address") values = {'Identity': "identity", 'BindingType': "apn", 'Address': "address", } self.holodeck.assert_has_request(Request( 'post', 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings', data=values, )) def test_create_response(self): self.holodeck.mock(Response( 201, ''' { "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "address": "a7c658f4111ec4ff5a1a647f9d0edd819025b9f20522d2fae897049f32873e73", "binding_type": "apn", "credential_sid": null, "date_created": "2015-07-30T20:00:00Z", "date_updated": "2015-07-30T20:00:00Z", "endpoint": "26607274", "identity": "24987039", "notification_protocol_version": "3", "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "sid": "BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "tags": [ "26607274" ], "links": { "user": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/24987039" }, "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings/BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" } ''' )) actual = self.client.notify.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ .bindings.create(identity="identity", binding_type="apn", address="address") self.assertIsNotNone(actual) def test_list_request(self): self.holodeck.mock(Response(500, '')) with self.assertRaises(TwilioException): self.client.notify.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ .bindings.list() self.holodeck.assert_has_request(Request( 'get', 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings', )) def test_read_empty_response(self): self.holodeck.mock(Response( 200, ''' { "bindings": [], "meta": { "first_page_url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings?Tag=tag&Identity=identity&PageSize=50&Page=0", "key": "bindings", "next_page_url": null, "page": 0, "page_size": 50, "previous_page_url": null, "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings?Tag=tag&Identity=identity&PageSize=50&Page=0" } } ''' )) actual = self.client.notify.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ .bindings.list() self.assertIsNotNone(actual) def test_read_full_response(self): self.holodeck.mock(Response( 200, ''' { "bindings": [ { "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "address": "a7c658f4111ec4ff5a1a647f9d0edd819025b9f20522d2fae897049f32873e73", "binding_type": "apn", "credential_sid": null, "date_created": "2015-07-30T20:00:00Z", "date_updated": "2015-07-30T20:00:00Z", "endpoint": "26607274", "identity": "24987039", "notification_protocol_version": "3", "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "sid": "BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "tags": [ "26607274" ], "links": { "user": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/24987039" }, "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings/BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" } ], "meta": { "first_page_url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings?Tag=tag&Identity=identity&PageSize=50&Page=0", "key": "bindings", "next_page_url": null, "page": 0, "page_size": 50, "previous_page_url": null, "url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings?Tag=tag&Identity=identity&PageSize=50&Page=0" } } ''' )) actual = self.client.notify.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ .bindings.list() self.assertIsNotNone(actual)
# coding=utf-8 # Copyright 2020 The TF-Agents 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 # # https://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. # Lint as: python2, python3 r"""Train and Eval TD3. To run: ```bash tensorboard --logdir $HOME/tmp/td3/gym/HalfCheetah-v2/ --port 2223 & python tf_agents/agents/td3/examples/v2/train_eval.py \ --root_dir=$HOME/tmp/td3/gym/HalfCheetah-v2/ \ --num_iterations=2000000 \ --alsologtostderr ``` """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import time from absl import app from absl import flags from absl import logging import gin from six.moves import range import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import from tf_agents.agents.ddpg import actor_network from tf_agents.agents.ddpg import critic_network from tf_agents.agents.td3 import td3_agent from tf_agents.drivers import dynamic_step_driver from tf_agents.environments import suite_mujoco from tf_agents.environments import tf_py_environment from tf_agents.eval import metric_utils from tf_agents.metrics import tf_metrics from tf_agents.replay_buffers import tf_uniform_replay_buffer from tf_agents.utils import common flags.DEFINE_string('root_dir', os.getenv('TEST_UNDECLARED_OUTPUTS_DIR'), 'Root directory for writing logs/summaries/checkpoints.') flags.DEFINE_integer('num_iterations', 100000, 'Total number train/eval iterations to perform.') flags.DEFINE_multi_string('gin_file', None, 'Paths to the gin-config files.') flags.DEFINE_multi_string('gin_param', None, 'Gin binding parameters.') FLAGS = flags.FLAGS @gin.configurable def train_eval( root_dir, env_name='HalfCheetah-v2', num_iterations=2000000, actor_fc_layers=(400, 300), critic_obs_fc_layers=(400,), critic_action_fc_layers=None, critic_joint_fc_layers=(300,), # Params for collect initial_collect_steps=1000, collect_steps_per_iteration=1, replay_buffer_capacity=100000, exploration_noise_std=0.1, # Params for target update target_update_tau=0.05, target_update_period=5, # Params for train train_steps_per_iteration=1, batch_size=64, actor_update_period=2, actor_learning_rate=1e-4, critic_learning_rate=1e-3, td_errors_loss_fn=tf.compat.v1.losses.huber_loss, gamma=0.995, reward_scale_factor=1.0, gradient_clipping=None, use_tf_functions=True, # Params for eval num_eval_episodes=10, eval_interval=10000, # Params for checkpoints, summaries, and logging log_interval=1000, summary_interval=1000, summaries_flush_secs=10, debug_summaries=False, summarize_grads_and_vars=False, eval_metrics_callback=None): """A simple train and eval for TD3.""" root_dir = os.path.expanduser(root_dir) train_dir = os.path.join(root_dir, 'train') eval_dir = os.path.join(root_dir, 'eval') train_summary_writer = tf.compat.v2.summary.create_file_writer( train_dir, flush_millis=summaries_flush_secs * 1000) train_summary_writer.set_as_default() eval_summary_writer = tf.compat.v2.summary.create_file_writer( eval_dir, flush_millis=summaries_flush_secs * 1000) eval_metrics = [ tf_metrics.AverageReturnMetric(buffer_size=num_eval_episodes), tf_metrics.AverageEpisodeLengthMetric(buffer_size=num_eval_episodes) ] global_step = tf.compat.v1.train.get_or_create_global_step() with tf.compat.v2.summary.record_if( lambda: tf.math.equal(global_step % summary_interval, 0)): tf_env = tf_py_environment.TFPyEnvironment(suite_mujoco.load(env_name)) eval_tf_env = tf_py_environment.TFPyEnvironment(suite_mujoco.load(env_name)) actor_net = actor_network.ActorNetwork( tf_env.time_step_spec().observation, tf_env.action_spec(), fc_layer_params=actor_fc_layers, ) critic_net_input_specs = (tf_env.time_step_spec().observation, tf_env.action_spec()) critic_net = critic_network.CriticNetwork( critic_net_input_specs, observation_fc_layer_params=critic_obs_fc_layers, action_fc_layer_params=critic_action_fc_layers, joint_fc_layer_params=critic_joint_fc_layers, ) tf_agent = td3_agent.Td3Agent( tf_env.time_step_spec(), tf_env.action_spec(), actor_network=actor_net, critic_network=critic_net, actor_optimizer=tf.compat.v1.train.AdamOptimizer( learning_rate=actor_learning_rate), critic_optimizer=tf.compat.v1.train.AdamOptimizer( learning_rate=critic_learning_rate), exploration_noise_std=exploration_noise_std, target_update_tau=target_update_tau, target_update_period=target_update_period, actor_update_period=actor_update_period, td_errors_loss_fn=td_errors_loss_fn, gamma=gamma, reward_scale_factor=reward_scale_factor, gradient_clipping=gradient_clipping, debug_summaries=debug_summaries, summarize_grads_and_vars=summarize_grads_and_vars, train_step_counter=global_step, ) tf_agent.initialize() train_metrics = [ tf_metrics.NumberOfEpisodes(), tf_metrics.EnvironmentSteps(), tf_metrics.AverageReturnMetric(), tf_metrics.AverageEpisodeLengthMetric(), ] eval_policy = tf_agent.policy collect_policy = tf_agent.collect_policy replay_buffer = tf_uniform_replay_buffer.TFUniformReplayBuffer( tf_agent.collect_data_spec, batch_size=tf_env.batch_size, max_length=replay_buffer_capacity) initial_collect_driver = dynamic_step_driver.DynamicStepDriver( tf_env, collect_policy, observers=[replay_buffer.add_batch], num_steps=initial_collect_steps) collect_driver = dynamic_step_driver.DynamicStepDriver( tf_env, collect_policy, observers=[replay_buffer.add_batch] + train_metrics, num_steps=collect_steps_per_iteration) if use_tf_functions: initial_collect_driver.run = common.function(initial_collect_driver.run) collect_driver.run = common.function(collect_driver.run) tf_agent.train = common.function(tf_agent.train) # Collect initial replay data. logging.info( 'Initializing replay buffer by collecting experience for %d steps with ' 'a random policy.', initial_collect_steps) initial_collect_driver.run() results = metric_utils.eager_compute( eval_metrics, eval_tf_env, eval_policy, num_episodes=num_eval_episodes, train_step=global_step, summary_writer=eval_summary_writer, summary_prefix='Metrics', ) if eval_metrics_callback is not None: eval_metrics_callback(results, global_step.numpy()) metric_utils.log_metrics(eval_metrics) time_step = None policy_state = collect_policy.get_initial_state(tf_env.batch_size) timed_at_step = global_step.numpy() time_acc = 0 # Dataset generates trajectories with shape [Bx2x...] dataset = replay_buffer.as_dataset( num_parallel_calls=3, sample_batch_size=batch_size, num_steps=2).prefetch(3) iterator = iter(dataset) def train_step(): experience, _ = next(iterator) return tf_agent.train(experience) if use_tf_functions: train_step = common.function(train_step) for _ in range(num_iterations): start_time = time.time() time_step, policy_state = collect_driver.run( time_step=time_step, policy_state=policy_state, ) for _ in range(train_steps_per_iteration): train_loss = train_step() time_acc += time.time() - start_time if global_step.numpy() % log_interval == 0: logging.info('step = %d, loss = %f', global_step.numpy(), train_loss.loss) steps_per_sec = (global_step.numpy() - timed_at_step) / time_acc logging.info('%.3f steps/sec', steps_per_sec) tf.compat.v2.summary.scalar( name='global_steps_per_sec', data=steps_per_sec, step=global_step) timed_at_step = global_step.numpy() time_acc = 0 for train_metric in train_metrics: train_metric.tf_summaries( train_step=global_step, step_metrics=train_metrics[:2]) if global_step.numpy() % eval_interval == 0: results = metric_utils.eager_compute( eval_metrics, eval_tf_env, eval_policy, num_episodes=num_eval_episodes, train_step=global_step, summary_writer=eval_summary_writer, summary_prefix='Metrics', ) if eval_metrics_callback is not None: eval_metrics_callback(results, global_step.numpy()) metric_utils.log_metrics(eval_metrics) return train_loss def main(_): tf.compat.v1.enable_v2_behavior() logging.set_verbosity(logging.INFO) gin.parse_config_files_and_bindings(FLAGS.gin_file, FLAGS.gin_param) train_eval(FLAGS.root_dir, num_iterations=FLAGS.num_iterations) if __name__ == '__main__': flags.mark_flag_as_required('root_dir') app.run(main)
""" SlipStream Client ===== Copyright (C) 2015 SixSq Sarl (sixsq.com) ===== 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 time import slipstream.util as util import slipstream.exceptions.Exceptions as Exceptions from slipstream.util import override from slipstream.cloudconnectors.BaseCloudConnector import BaseCloudConnector from slipstream.utils.ssh import generate_keypair from slipstream.UserInfo import UserInfo from slipstream.ConfigHolder import ConfigHolder import os import xmlrpclib import ssl import urllib import re import base64 try: import xml.etree.cElementTree as eTree # c-version, faster except ImportError: import xml.etree.ElementTree as eTree # python version def getConnector(config_holder): return getConnectorClass()(config_holder) def getConnectorClass(): return OpenNebulaClientCloud def searchInObjectList(list_, property_name, property_value): for element in list_: if isinstance(element, dict): if element.get(property_name) == property_value: return element else: if getattr(element, property_name) == property_value: return element return None def instantiate_from_cimi(cimi_connector, cimi_cloud_credential): user_info = UserInfo(cimi_connector['instanceName']) cloud_params = { UserInfo.CLOUD_USERNAME_KEY: cimi_cloud_credential['key'], UserInfo.CLOUD_PASSWORD_KEY: cimi_cloud_credential['secret'], 'endpoint': cimi_connector.get('endpoint') } user_info.set_cloud_params(cloud_params) config_holder = ConfigHolder(options={'verboseLevel': 0, 'retry': False}) os.environ['SLIPSTREAM_CONNECTOR_INSTANCE'] = cimi_connector['instanceName'] connector_instance = OpenNebulaClientCloud(config_holder) connector_instance._initialization(user_info) return connector_instance class OpenNebulaClientCloud(BaseCloudConnector): VM_STATE = [ 'Init', # 0 'Pending', # 1 'Hold', # 2 'Active', # 3 'Stopped', # 4 'Suspended', # 5 'Done', # 6 '//Failed', # 7 'Poweroff', # 8 'Undeployed' # 9 ] VM_LCM_STATE = [ 'Lcm init', # 0 'Prolog', # 1 'Boot', # 2 'Running', # 3 'Migrate', # 4 'Save stop', # 5 'Save suspend', # 6 'Save migrate', # 7 'Prolog migrate', # 8 'Prolog resume', # 9 'Epilog stop', # 10 'Epilog', # 11 'Shutdown', # 12 '//Cancel', # 13 '//Failure', # 14 'Cleanup resubmit', # 15 'Unknown', # 16 'Hotplug', # 17 'Shutdown poweroff', # 18 'Boot unknown', # 19 'Boot poweroff', # 20 'Boot suspended', # 21 'Boot stopped', # 22 'Cleanup delete', # 23 'Hotplug snapshot', # 24 'Hotplug nic', # 25 'Hotplug saveas', # 26 'Hotplug saveas poweroff', # 27 'Hotplug saveas suspended', # 28 'Shutdown undeploy', # 29 'Epilog undeploy', # 30 'Prolog undeploy', # 31 'Boot undeploy', # 32 'Hotplug prolog poweroff', # 33 'Hotplug epilog poweroff', # 34 'Boot migrate', # 35 'Boot failure', # 36 'Boot migrate failure', # 37 'Prolog migrate failure', # 38 'Prolog failure', # 39 'Epilog failure', # 40 'Epilog stop failure', # 41 'Epilog undeploy failure', # 42 'Prolog migrate poweroff', # 43 'Prolog migrate poweroff failure', # 44 'Prolog migrate suspend', # 45 'Prolog migrate suspend failure', # 46 'Boot undeploy failure', # 47 'Boot stopped failure', # 48 'Prolog resume failure', # 49 'Prolog undeploy failure', # 50 'Disk snapshot poweroff', # 51 'Disk snapshot revert poweroff', # 52 'Disk snapshot delete poweroff', # 53 'Disk snapshot suspended', # 54 'Disk snapshot revert suspended', # 55 'Disk snapshot delete suspended', # 56 'Disk snapshot', # 57 'Disk snapshot revert', # 58 'Disk snapshot delete', # 59 'Prolog migrate unknown', # 60 'Prolog migrate unknown failure' # 61 ] IMAGE_STATE = [ 'Init', # 0 'Ready', # 1 'Used', # 2 'Disabled', # 3 'Locked', # 4 'Error', # 5 'Clone', # 6 'Delete', # 7 'Used_pers' # 8 ] def _resize(self, node_instance): raise Exceptions.ExecutionException( '{0} doesn\'t implement resize feature.'.format(self.__class__.__name__)) def _detach_disk(self, node_instance): raise Exceptions.ExecutionException( '{0} doesn\'t implement detach disk feature.'.format(self.__class__.__name__)) def _attach_disk(self, node_instance): raise Exceptions.ExecutionException( '{0} doesn\'t implement attach disk feature.'.format(self.__class__.__name__)) cloudName = 'opennebula' def __init__(self, config_holder): super(OpenNebulaClientCloud, self).__init__(config_holder) self._set_capabilities(contextualization=True, direct_ip_assignment=True, orchestrator_can_kill_itself_or_its_vapp=True) self.user_info = None def _rpc_execute(self, command, *args): proxy = self._create_rpc_connection() remote_function = getattr(proxy, command) success, output_or_error_msg, err_code = \ remote_function(self._create_session_string(), *args) if not success: raise Exceptions.ExecutionException(output_or_error_msg) return output_or_error_msg @override def _initialization(self, user_info, **kwargs): util.printStep('Initialize the OpenNebula connector.') self.user_info = user_info if self.is_build_image(): self.tmp_private_key, self.tmp_public_key = generate_keypair() self.user_info.set_private_key(self.tmp_private_key) def format_instance_name(self, name): new_name = self.remove_bad_char_in_instance_name(name) return self.truncate_instance_name(new_name) @staticmethod def truncate_instance_name(name): if len(name) <= 128: return name else: return name[:63] + '-' + name[-63:] @staticmethod def remove_bad_char_in_instance_name(name): return re.sub('[^a-zA-Z0-9-]', '', name) def _set_instance_name(self, vm_name): return 'NAME = {0}'.format(self.format_instance_name(vm_name)) def _set_disks(self, image_id, disk_size_gb): try: img_id = int(image_id) except: raise Exception('Something is wrong with image ID : {0}!'.format(image_id)) disk = 'IMAGE_ID = {0:d}'.format(img_id) if disk_size_gb is None: return 'DISK = [ {} ]'.format(disk) else: try: disk_size_mb = int(float(disk_size_gb) * 1024) except: raise Exception('Something is wrong with root disk size : {0}!'.format(disk_size_gb)) return 'DISK = [ {0}, SIZE={1:d} ]'.format(disk, disk_size_mb) def _set_additionnal_disks(self, disk_size_gb): if disk_size_gb is None: return '' try: disk_size_mb = int(float(disk_size_gb) * 1024) except: raise Exception('Something wrong with additionnal disk size : {0}!'.format(disk_size_gb)) return 'DISK = [ FORMAT = "ext4", SIZE="{0:d}", TYPE="fs", IO="native" ]'.format(disk_size_mb) def _set_cpu(self, vm_vcpu, cpu_ratio): try: number_vcpu = int(vm_vcpu) ratio = float(cpu_ratio) except: raise Exception('Something wrong with CPU size: cpu = {0} and cpu ratio = {1} !'.format(vm_vcpu, cpu_ratio)) return 'VCPU = {0:d} CPU = {1:f}'.format(number_vcpu, ratio) def _set_ram(self, vm_ram_gbytes): try: ram = int(float(vm_ram_gbytes) * 1024) except ValueError: raise Exception('Something wrong with RAM size : {0}!'.format(vm_ram_gbytes)) return 'MEMORY = {0:d}'.format(ram) def _set_nics(self, requested_network_type, public_network_id, private_network_id): # extract mappings for Public and Private networks from the connector instance if requested_network_type.upper() == 'PUBLIC': try: network_id = int(public_network_id) except ValueError: raise Exception('Something wrong with specified Public Network ID : {0}!'.format(public_network_id)) elif requested_network_type.upper() == 'PRIVATE': try: network_id = int(private_network_id) except ValueError: raise Exception('Something wrong with specified Private Network ID : {0}!'.format(private_network_id)) else: return '' return 'NIC = [ NETWORK_ID = {0:d}, MODEL = "virtio" ]'.format(network_id) def _set_specific_nic(self, network_specific_name): network_infos = network_specific_name.split(';') nic = 'NETWORK = {0}, MODEL = "virtio"'.format(network_infos[0]) if len(network_infos) == 1: return 'NIC = [ {} ]'.format(nic) elif len(network_infos) == 2: return 'NIC = [ {0}, NETWORK_UNAME = {1} ]'.format(nic, network_infos[1]) else: raise Exception('Something wrong with specified Network name : {0}!'.format(network_specific_name)) def _set_contextualization(self, contextualization_type, public_ssh_key, contextualization_script): if contextualization_type != 'cloud-init': return 'CONTEXT = [ NETWORK = "YES", SSH_PUBLIC_KEY = "{0}", ' \ 'START_SCRIPT_BASE64 = "{1}"]'.format(public_ssh_key, base64.b64encode(contextualization_script)) else: return 'CONTEXT = [ PUBLIC_IP = "$NIC[IP]", SSH_PUBLIC_KEY = "{0}", USERDATA_ENCODING = "base64", ' \ 'USER_DATA = "{1}"]'.format(public_ssh_key, base64.b64encode(contextualization_script)) @override def _start_image(self, user_info, node_instance, vm_name): return self._start_image_on_opennebula(user_info, node_instance, vm_name) def _start_image_on_opennebula(self, user_info, node_instance, vm_name): instance_name = self._set_instance_name(vm_name) ram = self._set_ram(node_instance.get_ram()) cpu = self._set_cpu(node_instance.get_cpu(), user_info.get_cloud('cpuRatio')) disks = self._set_disks(node_instance.get_image_id(), node_instance.get_root_disk_size()) additionnal_disks = self._set_additionnal_disks(node_instance.get_volatile_extra_disk_size()) try: network_specific_name = node_instance.get_cloud_parameter('network.specific.name').strip() except: network_specific_name = '' if network_specific_name: nics = self._set_specific_nic(network_specific_name) else: nics = self._set_nics(node_instance.get_network_type(), user_info.get_public_network_name(), user_info.get_private_network_name()) if self.is_build_image(): context = self._set_contextualization(node_instance.get_cloud_parameter('contextualization.type'), self.tmp_public_key, '') else: context = self._set_contextualization(node_instance.get_cloud_parameter('contextualization.type'), self.user_info.get_public_keys(), self._get_bootstrap_script(node_instance)) custom_vm_template = node_instance.get_cloud_parameter('custom.vm.template') or '' template = ' '.join([instance_name, cpu, ram, disks, additionnal_disks, nics, context, custom_vm_template]) vm_id = self._rpc_execute('one.vm.allocate', template, False) vm = self._rpc_execute('one.vm.info', vm_id) return eTree.fromstring(vm) @override def list_instances(self): vms = eTree.fromstring(self._rpc_execute('one.vmpool.info', -3, -1, -1, -1)) return vms.findall('VM') @override def _stop_deployment(self): for _, vm in self.get_vms().items(): self._rpc_execute('one.vm.action', 'delete', int(vm.findtext('ID'))) @override def _stop_vms_by_ids(self, ids): for _id in map(int, ids): self._rpc_execute('one.vm.action', 'delete', _id) @override def _build_image(self, user_info, node_instance): return self._build_image_on_opennebula(user_info, node_instance) def _build_image_on_opennebula(self, user_info, node_instance): listener = self._get_listener() machine_name = node_instance.get_name() vm = self._get_vm(machine_name) ip_address = self._vm_get_ip(vm) vm_id = int(self._vm_get_id(vm)) self._wait_vm_in_state(vm_id, 'Active', time_out=300, time_sleep=10) self._build_image_increment(user_info, node_instance, ip_address) util.printStep('Creation of the new Image.') self._rpc_execute('one.vm.action', 'poweroff', vm_id) self._wait_vm_in_state(vm_id, 'Poweroff', time_out=300, time_sleep=10) listener.write_for(machine_name, 'Saving the image') new_image_name = node_instance.get_image_short_name() + time.strftime("_%Y%m%d-%H%M%S") new_image_id = int(self._rpc_execute( 'one.vm.disksaveas', vm_id, 0, new_image_name, '', -1)) self._wait_image_in_state(new_image_id, 'Ready', time_out=1800, time_sleep=30) listener.write_for(machine_name, 'Image saved !') self._rpc_execute('one.vm.action', 'resume', vm_id) self._wait_vm_in_state(vm_id, 'Active', time_out=300, time_sleep=10) return str(new_image_id) def _get_vm_state(self, vm_id): vm = self._rpc_execute('one.vm.info', vm_id) return int(eTree.fromstring(vm).findtext('STATE')) def _wait_vm_in_state(self, vm_id, state, time_out, time_sleep=30): time_stop = time.time() + time_out current_state = self._get_vm_state(vm_id) while current_state != self.VM_STATE.index(state): if time.time() > time_stop: raise Exceptions.ExecutionException( 'Timed out while waiting VM {0} to enter in state {1}'.format(vm_id, state)) time.sleep(time_sleep) current_state = self._get_vm_state(vm_id) return current_state def _get_image_state(self, image_id): image = self._rpc_execute('one.image.info', image_id) return int(eTree.fromstring(image).findtext('STATE')) def _wait_image_in_state(self, image_id, state, time_out, time_sleep=30): time_stop = time.time() + time_out current_state = self._get_image_state(image_id) while current_state != self.IMAGE_STATE.index(state): if time.time() > time_stop: raise Exceptions.ExecutionException( 'Timed out while waiting for image {0} to be in state {1}'.format(image_id, state)) time.sleep(time_sleep) current_state = self._get_image_state(image_id) return current_state def _wait_image_not_in_state(self, image_id, state, time_out, time_sleep=30): time_stop = time.time() + time_out current_state = self._get_image_state(image_id) while current_state == self.IMAGE_STATE.index(state): if time.time() > time_stop: raise Exceptions.ExecutionException( 'Timed out while waiting for image {0} to be in state {1}'.format(image_id, state)) time.sleep(time_sleep) current_state = self._get_image_state(image_id) return current_state def _create_session_string(self): quoted_username = urllib.quote(self.user_info.get_cloud_username(), '') quoted_password = urllib.quote(self.user_info.get_cloud_password(), '') return '{0}:{1}'.format(quoted_username, quoted_password) def _create_rpc_connection(self): protocol_separator = '://' parts = self.user_info.get_cloud_endpoint().split(protocol_separator) url = parts[0] + protocol_separator + self._create_session_string() \ + "@" + ''.join(parts[1:]) no_certif_check = hasattr(ssl, '_create_unverified_context') and ssl._create_unverified_context() or None try: return xmlrpclib.ServerProxy(url, context=no_certif_check) except TypeError: return xmlrpclib.ServerProxy(url) @override def _vm_get_ip(self, vm): return vm.findtext('TEMPLATE/NIC/IP') @override def _vm_get_id(self, vm): return vm.findtext('ID') @override def _vm_get_state(self, vm): vm_state = int(vm.findtext('STATE')) if vm_state == OpenNebulaClientCloud.VM_STATE.index('Active'): return OpenNebulaClientCloud.VM_LCM_STATE[int(vm.findtext('LCM_STATE'))] return OpenNebulaClientCloud.VM_STATE[vm_state] @override def _vm_get_id_from_list_instances(self, vm): return self._vm_get_id(vm) @override def _vm_get_ip_from_list_instances(self, vm_instance): return self._vm_get_ip(vm_instance) @override def _vm_get_cpu(self, vm_instance): return vm_instance.findtext('TEMPLATE/VCPU') @override def _vm_get_ram(self, vm_instance): return vm_instance.findtext('TEMPLATE/MEMORY') @override def _vm_get_root_disk(self, vm_instance): return format(int(vm_instance.findtext('TEMPLATE/DISK/SIZE')) / 1024.0, '.3f') @override def _vm_get_instance_type(self, vm_instance): return vm_instance.findtext('USER_TEMPLATE/INSTANCE_TYPE')
# Copyright 2013 Hewlett-Packard Development Company, L.P. # # 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 logging from django.conf import settings from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import messages from horizon import workflows from openstack_dashboard import api from openstack_dashboard.dashboards.identity.domains import constants from openstack_dashboard.utils.identity import IdentityMixIn LOG = logging.getLogger(__name__) class CreateDomainInfoAction(workflows.Action): name = forms.CharField(label=_("Name")) description = forms.CharField(widget=forms.widgets.Textarea( attrs={'rows': 4}), label=_("Description"), required=False) enabled = forms.BooleanField(label=_("Enabled"), required=False, initial=True) class Meta(object): name = _("Domain Information") slug = "create_domain" help_text = _("Domains provide separation between users and " "infrastructure used by different organizations.") class CreateDomainInfo(workflows.Step): action_class = CreateDomainInfoAction contributes = ("domain_id", "name", "description", "enabled") class UpdateDomainUsersAction(workflows.MembershipAction): def __init__(self, request, *args, **kwargs): super(UpdateDomainUsersAction, self).__init__(request, *args, **kwargs) domain_id = self.initial.get("domain_id", '') # Get the default role try: default_role = api.keystone.get_default_role(self.request) # Default role is necessary to add members to a domain if default_role is None: default = getattr(settings, "OPENSTACK_KEYSTONE_DEFAULT_ROLE", None) msg = (_('Could not find default role "%s" in Keystone') % default) raise exceptions.NotFound(msg) except Exception: exceptions.handle(self.request, _('Unable to find default role.'), redirect=reverse(constants.DOMAINS_INDEX_URL)) default_role_name = self.get_default_role_field_name() self.fields[default_role_name] = forms.CharField(required=False) self.fields[default_role_name].initial = default_role.id # Get list of available users all_users = [] try: all_users = api.keystone.user_list(request, domain=domain_id) except Exception: exceptions.handle(request, _('Unable to retrieve user list.')) users_list = [(user.id, user.name) for user in all_users] # Get list of roles role_list = [] try: role_list = api.keystone.role_list(request) except Exception: exceptions.handle(request, _('Unable to retrieve role list.'), redirect=reverse(constants.DOMAINS_INDEX_URL)) for role in role_list: field_name = self.get_member_field_name(role.id) label = role.name self.fields[field_name] = forms.MultipleChoiceField(required=False, label=label) self.fields[field_name].choices = users_list self.fields[field_name].initial = [] # Figure out users & roles if domain_id: try: users_roles = api.keystone.get_domain_users_roles(request, domain_id) except Exception: exceptions.handle(request, _('Unable to retrieve user domain role ' 'assignments.'), redirect=reverse( constants.DOMAINS_INDEX_URL)) for user_id in users_roles: roles_ids = users_roles[user_id] for role_id in roles_ids: field_name = self.get_member_field_name(role_id) self.fields[field_name].initial.append(user_id) class Meta(object): name = _("Domain Members") slug = constants.DOMAIN_USER_MEMBER_SLUG class UpdateDomainUsers(workflows.UpdateMembersStep): action_class = UpdateDomainUsersAction available_list_title = _("All Users") members_list_title = _("Domain Members") no_available_text = _("No users found.") no_members_text = _("No users.") def contribute(self, data, context): context = super(UpdateDomainUsers, self).contribute(data, context) if data: try: roles = api.keystone.role_list(self.workflow.request) except Exception: exceptions.handle(self.workflow.request, _('Unable to retrieve role list.'), redirect=reverse( constants.DOMAINS_INDEX_URL)) post = self.workflow.request.POST for role in roles: field = self.get_member_field_name(role.id) context[field] = post.getlist(field) return context class UpdateDomainGroupsAction(workflows.MembershipAction): def __init__(self, request, *args, **kwargs): super(UpdateDomainGroupsAction, self).__init__(request, *args, **kwargs) err_msg = _('Unable to retrieve group list. Please try again later.') domain_id = self.initial.get("domain_id", '') # Get the default role try: default_role = api.keystone.get_default_role(self.request) # Default role is necessary to add members to a domain if default_role is None: default = getattr(settings, "OPENSTACK_KEYSTONE_DEFAULT_ROLE", None) msg = (_('Could not find default role "%s" in Keystone') % default) raise exceptions.NotFound(msg) except Exception: exceptions.handle(self.request, err_msg, redirect=reverse(constants.DOMAINS_INDEX_URL)) default_role_name = self.get_default_role_field_name() self.fields[default_role_name] = forms.CharField(required=False) self.fields[default_role_name].initial = default_role.id # Get list of available groups all_groups = [] try: all_groups = api.keystone.group_list(request, domain=domain_id) except Exception: exceptions.handle(request, err_msg) groups_list = [(group.id, group.name) for group in all_groups] # Get list of roles role_list = [] try: role_list = api.keystone.role_list(request) except Exception: exceptions.handle(request, err_msg, redirect=reverse(constants.DOMAINS_INDEX_URL)) for role in role_list: field_name = self.get_member_field_name(role.id) label = role.name self.fields[field_name] = forms.MultipleChoiceField(required=False, label=label) self.fields[field_name].choices = groups_list self.fields[field_name].initial = [] # Figure out groups & roles if domain_id: for group in all_groups: try: roles = api.keystone.roles_for_group(self.request, group=group.id, domain=domain_id) except Exception: exceptions.handle(request, err_msg, redirect=reverse( constants.DOMAINS_INDEX_URL)) for role in roles: field_name = self.get_member_field_name(role.id) self.fields[field_name].initial.append(group.id) class Meta(object): name = _("Domain Groups") slug = constants.DOMAIN_GROUP_MEMBER_SLUG class UpdateDomainGroups(workflows.UpdateMembersStep): action_class = UpdateDomainGroupsAction available_list_title = _("All Groups") members_list_title = _("Domain Groups") no_available_text = _("No groups found.") no_members_text = _("No groups.") def contribute(self, data, context): context = super(UpdateDomainGroups, self).contribute(data, context) if data: try: roles = api.keystone.role_list(self.workflow.request) except Exception: exceptions.handle(self.workflow.request, _('Unable to retrieve role list.')) post = self.workflow.request.POST for role in roles: field = self.get_member_field_name(role.id) context[field] = post.getlist(field) return context class CreateDomain(workflows.Workflow): slug = "create_domain" name = _("Create Domain") finalize_button_name = _("Create Domain") success_message = _('Created new domain "%s".') failure_message = _('Unable to create domain "%s".') success_url = constants.DOMAINS_INDEX_URL default_steps = (CreateDomainInfo, ) def format_status_message(self, message): return message % self.context.get('name', 'unknown domain') def handle(self, request, data): # create the domain try: LOG.info('Creating domain with name "%s"' % data['name']) desc = data['description'] api.keystone.domain_create(request, name=data['name'], description=desc, enabled=data['enabled']) except Exception: exceptions.handle(request, ignore=True) return False return True class UpdateDomainInfoAction(CreateDomainInfoAction): class Meta(object): name = _("Domain Information") slug = 'update_domain' help_text = _("Domains provide separation between users and " "infrastructure used by different organizations. " "Edit the domain details to add or remove " "groups in the domain.") class UpdateDomainInfo(workflows.Step): action_class = UpdateDomainInfoAction depends_on = ("domain_id",) contributes = ("name", "description", "enabled") class UpdateDomain(workflows.Workflow, IdentityMixIn): slug = "update_domain" name = _("Edit Domain") finalize_button_name = _("Save") success_message = _('Modified domain "%s".') failure_message = _('Unable to modify domain "%s".') success_url = constants.DOMAINS_INDEX_URL default_steps = (UpdateDomainInfo, UpdateDomainUsers, UpdateDomainGroups) def format_status_message(self, message): return message % self.context.get('name', 'unknown domain') def _update_domain_members(self, request, domain_id, data): # update domain members users_to_modify = 0 # Project-user member step member_step = self.get_step(constants.DOMAIN_USER_MEMBER_SLUG) try: # Get our role options available_roles = api.keystone.role_list(request) # Get the users currently associated with this domain so we # can diff against it. users_roles = api.keystone.get_domain_users_roles(request, domain=domain_id) users_to_modify = len(users_roles) for user_id in users_roles.keys(): # Check if there have been any changes in the roles of # Existing domain members. current_role_ids = list(users_roles[user_id]) for role in available_roles: field_name = member_step.get_member_field_name(role.id) # Check if the user is in the list of users with this role. if user_id in data[field_name]: # Add it if necessary if role.id not in current_role_ids: # user role has changed api.keystone.add_domain_user_role( request, domain=domain_id, user=user_id, role=role.id) else: # User role is unchanged, so remove it from the # remaining roles list to avoid removing it later. index = current_role_ids.index(role.id) current_role_ids.pop(index) # Prevent admins from doing stupid things to themselves. is_current_user = user_id == request.user.id # TODO(lcheng) When Horizon moves to Domain scoped token for # invoking identity operation, replace this with: # domain_id == request.user.domain_id is_current_domain = True available_admin_role_ids = [ role.id for role in available_roles if role.name.lower() in self.get_admin_roles() ] admin_role_ids = [role for role in current_role_ids if role in available_admin_role_ids] if len(admin_role_ids): removing_admin = any([role in current_role_ids for role in admin_role_ids]) else: removing_admin = False if is_current_user and is_current_domain and removing_admin: # Cannot remove "admin" role on current(admin) domain msg = _('You cannot revoke your administrative privileges ' 'from the domain you are currently logged into. ' 'Please switch to another domain with ' 'administrative privileges or remove the ' 'administrative role manually via the CLI.') messages.warning(request, msg) # Otherwise go through and revoke any removed roles. else: for id_to_delete in current_role_ids: api.keystone.remove_domain_user_role( request, domain=domain_id, user=user_id, role=id_to_delete) users_to_modify -= 1 # Grant new roles on the domain. for role in available_roles: field_name = member_step.get_member_field_name(role.id) # Count how many users may be added for exception handling. users_to_modify += len(data[field_name]) for role in available_roles: users_added = 0 field_name = member_step.get_member_field_name(role.id) for user_id in data[field_name]: if user_id not in users_roles: api.keystone.add_domain_user_role(request, domain=domain_id, user=user_id, role=role.id) users_added += 1 users_to_modify -= users_added return True except Exception: exceptions.handle(request, _('Failed to modify %s project ' 'members and update domain groups.') % users_to_modify) return False def _update_domain_groups(self, request, domain_id, data): # update domain groups groups_to_modify = 0 member_step = self.get_step(constants.DOMAIN_GROUP_MEMBER_SLUG) try: # Get our role options available_roles = api.keystone.role_list(request) # Get the groups currently associated with this domain so we # can diff against it. domain_groups = api.keystone.group_list(request, domain=domain_id) groups_to_modify = len(domain_groups) for group in domain_groups: # Check if there have been any changes in the roles of # Existing domain members. current_roles = api.keystone.roles_for_group( self.request, group=group.id, domain=domain_id) current_role_ids = [role.id for role in current_roles] for role in available_roles: # Check if the group is in the list of groups with # this role. field_name = member_step.get_member_field_name(role.id) if group.id in data[field_name]: # Add it if necessary if role.id not in current_role_ids: # group role has changed api.keystone.add_group_role( request, role=role.id, group=group.id, domain=domain_id) else: # Group role is unchanged, so remove it from # the remaining roles list to avoid removing it # later index = current_role_ids.index(role.id) current_role_ids.pop(index) # Revoke any removed roles. for id_to_delete in current_role_ids: api.keystone.remove_group_role(request, role=id_to_delete, group=group.id, domain=domain_id) groups_to_modify -= 1 # Grant new roles on the domain. for role in available_roles: field_name = member_step.get_member_field_name(role.id) # Count how many groups may be added for error handling. groups_to_modify += len(data[field_name]) for role in available_roles: groups_added = 0 field_name = member_step.get_member_field_name(role.id) for group_id in data[field_name]: if not filter(lambda x: group_id == x.id, domain_groups): api.keystone.add_group_role(request, role=role.id, group=group_id, domain=domain_id) groups_added += 1 groups_to_modify -= groups_added return True except Exception: exceptions.handle(request, _('Failed to modify %s domain groups.') % groups_to_modify) return False def handle(self, request, data): domain_id = data.pop('domain_id') try: LOG.info('Updating domain with name "%s"' % data['name']) api.keystone.domain_update(request, domain_id=domain_id, name=data['name'], description=data['description'], enabled=data['enabled']) except Exception: exceptions.handle(request, ignore=True) return False if not self._update_domain_members(request, domain_id, data): return False if not self._update_domain_groups(request, domain_id, data): return False return True
#! /usr/bin/env python import re import math import collections import numpy as np import time import operator from scipy.io import mmread, mmwrite from random import randint from sklearn import cross_validation from sklearn import linear_model from sklearn.grid_search import GridSearchCV from sklearn import preprocessing as pp from sklearn.svm import SVR from sklearn.ensemble import GradientBoostingRegressor, GradientBoostingClassifier from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier from sklearn.ensemble import ExtraTreesRegressor from sklearn.decomposition import ProbabilisticPCA, KernelPCA from sklearn.decomposition import NMF from sklearn.pipeline import Pipeline from sklearn.svm import LinearSVC from sklearn.linear_model import LogisticRegression, Ridge, Lasso, ElasticNet import scipy.stats as stats from sklearn import tree from sklearn.feature_selection import f_regression from sklearn.metrics import precision_recall_curve from sklearn.metrics import auc, f1_score from sklearn.gaussian_process import GaussianProcess import features # working directory dir = '.' label_index = 770 # load train data def load_train_fs(): # In the validation process, the training data was randomly shuffled firstly. # For the prediction process, there is no need to shuffle the dataset. # Owing to out of memory problem, Gaussian process only use part of training data, the prediction of gaussian process # may be a little different from the model,which the training data was shuffled. train_fs = np.genfromtxt(open(dir + '/train_v2_gp_5000.csv','rb'), delimiter=',', skip_header=1) col_mean = stats.nanmean(train_fs, axis=0) inds = np.where(np.isnan(train_fs)) train_fs[inds] = np.take(col_mean, inds[1]) train_fs[np.isinf(train_fs)] = 0 return train_fs # load test data def load_test_fs(): test_fs = np.genfromtxt(open(dir + '/train_v2.csv','rb'), delimiter=',', skip_header = 1) col_mean = stats.nanmean(test_fs, axis=0) inds = np.where(np.isnan(test_fs)) test_fs[inds] = np.take(col_mean, inds[1]) test_fs[np.isinf(test_fs)] = 0 return test_fs # extract features from test data def test_type(test_fs): x_Test = test_fs[:,range(1, label_index)] return x_Test # extract features from train data def train_type(train_fs): train_x = train_fs[:,range(1, label_index)] train_y= train_fs[:,-1] return train_x, train_y # transform the loss to the binary form def toLabels(train_y): labels = np.zeros(len(train_y)) labels[train_y>0] = 1 return labels # generate the output file based to the predictions def output_preds(preds): out_file = dir + '/output_gp_5000.csv' fs = open(out_file,'w') fs.write('id,loss\n') for i in range(len(preds)): if preds[i] > 100: preds[i] = 100 elif preds[i] < 0: preds[i] = 0 strs = str(i+105472) + ',' + str(np.float(preds[i])) fs.write(strs + '\n'); fs.close() return # get the top feature indexes by invoking f_regression def getTopFeatures(train_x, train_y, n_features=100): f_val, p_val = f_regression(train_x,train_y) f_val_dict = {} p_val_dict = {} for i in range(len(f_val)): if math.isnan(f_val[i]): f_val[i] = 0.0 f_val_dict[i] = f_val[i] if math.isnan(p_val[i]): p_val[i] = 0.0 p_val_dict[i] = p_val[i] sorted_f = sorted(f_val_dict.iteritems(), key=operator.itemgetter(1),reverse=True) sorted_p = sorted(p_val_dict.iteritems(), key=operator.itemgetter(1),reverse=True) feature_indexs = [] for i in range(0,n_features): feature_indexs.append(sorted_f[i][0]) return feature_indexs # generate the new data, based on which features are generated, and used def get_data(train_x, feature_indexs, feature_minus_pair_list=[], feature_plus_pair_list=[], feature_mul_pair_list=[], feature_divide_pair_list = [], feature_pair_sub_mul_list=[], feature_pair_plus_mul_list = [],feature_pair_sub_divide_list = [], feature_minus2_pair_list = [],feature_mul2_pair_list=[], feature_sub_square_pair_list=[], feature_square_sub_pair_list=[],feature_square_plus_pair_list=[]): sub_train_x = train_x[:,feature_indexs] for i in range(len(feature_minus_pair_list)): ind_i = feature_minus_pair_list[i][0] ind_j = feature_minus_pair_list[i][1] sub_train_x = np.column_stack((sub_train_x, train_x[:,ind_i]-train_x[:,ind_j])) for i in range(len(feature_plus_pair_list)): ind_i = feature_plus_pair_list[i][0] ind_j = feature_plus_pair_list[i][1] sub_train_x = np.column_stack((sub_train_x, train_x[:,ind_i] + train_x[:,ind_j])) for i in range(len(feature_mul_pair_list)): ind_i = feature_mul_pair_list[i][0] ind_j = feature_mul_pair_list[i][1] sub_train_x = np.column_stack((sub_train_x, train_x[:,ind_i] * train_x[:,ind_j])) for i in range(len(feature_divide_pair_list)): ind_i = feature_divide_pair_list[i][0] ind_j = feature_divide_pair_list[i][1] sub_train_x = np.column_stack((sub_train_x, train_x[:,ind_i] / train_x[:,ind_j])) for i in range(len(feature_pair_sub_mul_list)): ind_i = feature_pair_sub_mul_list[i][0] ind_j = feature_pair_sub_mul_list[i][1] ind_k = feature_pair_sub_mul_list[i][2] sub_train_x = np.column_stack((sub_train_x, (train_x[:,ind_i]-train_x[:,ind_j]) * train_x[:,ind_k])) return sub_train_x # use gbm classifier to predict whether the loan defaults or not def gbc_classify(train_x, train_y): feature_indexs = getTopFeatures(train_x, train_y) sub_x_Train = get_data(train_x, feature_indexs[:16], features.feature_pair_sub_list ,features.feature_pair_plus_list, features.feature_pair_mul_list, features.feature_pair_divide_list[:20], features.feature_pair_sub_mul_list[:20]) labels = toLabels(train_y) gbc = GradientBoostingClassifier(n_estimators=3000, max_depth=8) gbc.fit(sub_x_Train, labels) return gbc # use svm to predict the loss, based on the result of gbm classifier def gbc_svr_predict_part(gbc, train_x, train_y, test_x, feature_pair_sub_list, feature_pair_plus_list, feature_pair_mul_list, feature_pair_divide_list, feature_pair_sub_mul_list, feature_pair_sub_list_sf, feature_pair_plus_list2): feature_indexs = getTopFeatures(train_x, train_y) sub_x_Train = get_data(train_x, feature_indexs[:16], feature_pair_sub_list ,feature_pair_plus_list, feature_pair_mul_list, feature_pair_divide_list[:20], feature_pair_sub_mul_list[:20]) sub_x_Test = get_data(test_x, feature_indexs[:16], feature_pair_sub_list ,feature_pair_plus_list, feature_pair_mul_list, feature_pair_divide_list[:20], feature_pair_sub_mul_list[:20]) pred_labels = gbc.predict(sub_x_Test) pred_probs = gbc.predict_proba(sub_x_Test)[:,1] ind_test = np.where(pred_probs>0.55)[0] ind_train = np.where(train_y > 0)[0] ind_train0 = np.where(train_y == 0)[0] preds_all = np.zeros([len(sub_x_Test)]) flag = (sub_x_Test[:,16] >= 1) ind_tmp0 = np.where(flag)[0] ind_tmp = np.where(~flag)[0] sub_x_Train = get_data(train_x, feature_indexs[:100], feature_pair_sub_list_sf ,feature_pair_plus_list2[:100], feature_pair_mul_list[:40], feature_pair_divide_list, feature_pair_sub_mul_list) sub_x_Test = get_data(test_x, feature_indexs[:100], feature_pair_sub_list_sf ,feature_pair_plus_list2[:100], feature_pair_mul_list[:40], feature_pair_divide_list, feature_pair_sub_mul_list) sub_x_Train[:,101] = np.log(1-sub_x_Train[:,101]) sub_x_Test[ind_tmp,101] = np.log(1-sub_x_Test[ind_tmp,101]) scaler = pp.StandardScaler() scaler.fit(sub_x_Train) sub_x_Train = scaler.transform(sub_x_Train) sub_x_Test[ind_tmp] = scaler.transform(sub_x_Test[ind_tmp]) svr = SVR(C=16, kernel='rbf', gamma = 0.000122) svr.fit(sub_x_Train[ind_train], np.log(train_y[ind_train])) preds = svr.predict(sub_x_Test[ind_test]) preds_all[ind_test] = np.power(np.e, preds) preds_all[ind_tmp0] = 0 return preds_all # use gbm regression to predict the loss, based on the result of gbm classifier def gbc_gbr_predict_part(gbc, train_x, train_y, test_x, feature_pair_sub_list, feature_pair_plus_list, feature_pair_mul_list, feature_pair_divide_list, feature_pair_sub_mul_list, feature_pair_sub_list2): feature_indexs = getTopFeatures(train_x, train_y) sub_x_Train = get_data(train_x, feature_indexs[:16], feature_pair_sub_list ,feature_pair_plus_list, feature_pair_mul_list, feature_pair_divide_list[:20],feature_pair_sub_mul_list[:20]) sub_x_Test = get_data(test_x, feature_indexs[:16], feature_pair_sub_list ,feature_pair_plus_list, feature_pair_mul_list, feature_pair_divide_list[:20], feature_pair_sub_mul_list[:20]) pred_labels = gbc.predict(sub_x_Test) pred_probs = gbc.predict_proba(sub_x_Test)[:,1] ind_test = np.where(pred_probs>0.55)[0] ind_train = np.where(train_y > 0)[0] ind_train0 = np.where(train_y == 0)[0] preds_all = np.zeros([len(sub_x_Test)]) flag = (sub_x_Test[:,16] >= 1) ind_tmp0 = np.where(flag)[0] ind_tmp = np.where(~flag)[0] sub_x_Train = get_data(train_x, feature_indexs[:16], feature_pair_sub_list2[:70] ,feature_pair_plus_list, feature_pair_mul_list, feature_pair_divide_list, feature_pair_sub_mul_list) sub_x_Test = get_data(test_x, feature_indexs[:16], feature_pair_sub_list2[:70] ,feature_pair_plus_list, feature_pair_mul_list, feature_pair_divide_list, feature_pair_sub_mul_list) scaler = pp.StandardScaler() scaler.fit(sub_x_Train) sub_x_Train = scaler.transform(sub_x_Train) sub_x_Test[ind_tmp] = scaler.transform(sub_x_Test[ind_tmp]) gbr1000 = GradientBoostingRegressor(n_estimators=1300, max_depth=4, subsample=0.5, learning_rate=0.05) gbr1000.fit(sub_x_Train[ind_train], np.log(train_y[ind_train])) preds = gbr1000.predict(sub_x_Test[ind_test]) preds_all[ind_test] = np.power(np.e, preds) preds_all[ind_tmp0] = 0 return preds_all # predict the loss based on the Gaussian process regressor, which has been trained def gp_predict(clf, x_Test): size = len(x_Test) part_size = 3000 cnt = (size-1) / part_size + 1 preds = [] for i in range(cnt): if i < cnt - 1: pred_part = clf.predict(x_Test[i*part_size: (i+1) * part_size]) else: pred_part = clf.predict(x_Test[i*part_size: size]) preds.extend(pred_part) return np.power(np.e,preds) # train the gaussian process regressor def gbc_gp_predict_part(sub_x_Train, train_y, sub_x_Test_part): #Owing to out of memory, the model was trained by part of training data #Attention, this part was trained on the ram of more than 96G sub_x_Train[:,16] = np.log(1-sub_x_Train[:,16]) scaler = pp.StandardScaler() scaler.fit(sub_x_Train) sub_x_Train = scaler.transform(sub_x_Train) ind_train = np.where(train_y>0)[0] part_size= int(0.7 * len(ind_train)) gp = GaussianProcess(theta0=1e-3, thetaL=1e-5, thetaU=10, corr= 'absolute_exponential') gp.fit(sub_x_Train[ind_train[:part_size]], np.log(train_y[ind_train[:part_size]])) flag = (sub_x_Test_part[:,16] >= 1) ind_tmp0 = np.where(flag)[0] ind_tmp = np.where(~flag)[0] sub_x_Test_part[ind_tmp,16] = np.log(1-sub_x_Test_part[ind_tmp,16]) sub_x_Test_part[ind_tmp] = scaler.transform(sub_x_Test_part[ind_tmp]) gp_preds_tmp = gp_predict(gp, sub_x_Test_part[ind_tmp]) gp_preds = np.zeros(len(sub_x_Test_part)) gp_preds[ind_tmp] = gp_preds_tmp return gp_preds # use gbm classifier to predict whether the loan defaults or not, then invoke the function gbc_gp_predict_part def gbc_gp_predict(train_x, train_y, test_x): feature_indexs = getTopFeatures(train_x, train_y) sub_x_Train = get_data(train_x, feature_indexs[:16], features.feature_pair_sub_list ,features.feature_pair_plus_list, features.feature_pair_mul_list, features.feature_pair_divide_list[:20]) sub_x_Test = get_data(test_x, feature_indexs[:16], features.feature_pair_sub_list ,features.feature_pair_plus_list, features.feature_pair_mul_list, features.feature_pair_divide_list[:20]) labels = toLabels(train_y) gbc = GradientBoostingClassifier(n_estimators=3000, max_depth=9) gbc.fit(sub_x_Train, labels) pred_probs = gbc.predict_proba(sub_x_Test)[:,1] ind_test = np.where(pred_probs>0.55)[0] gp_preds_part = gbc_gp_predict_part(sub_x_Train, train_y, sub_x_Test[ind_test]) gp_preds = np.zeros(len(test_x)) gp_preds[ind_test] = gp_preds_part return gp_preds # invoke the function gbc_svr_predict_part def gbc_svr_predict(gbc, train_x, train_y, test_x): svr_preds = gbc_svr_predict_part(gbc, train_x, train_y, test_x, features.feature_pair_sub_list, features.feature_pair_plus_list, features.feature_pair_mul_list, features.feature_pair_divide_list, features.feature_pair_sub_mul_list, features.feature_pair_sub_list_sf, features.feature_pair_plus_list2) return svr_preds # invoke the function gbc_gbr_predict_part def gbc_gbr_predict(gbc, train_x, train_y, test_x): gbr_preds = gbc_gbr_predict_part(gbc, train_x, train_y, test_x, features.feature_pair_sub_list, features.feature_pair_plus_list, features.feature_pair_mul_list, features.feature_pair_divide_list, features.feature_pair_sub_mul_list, features.feature_pair_sub_list2) return gbr_preds # the main function if __name__ == '__main__': train_fs = load_train_fs() test_fs = load_test_fs() train_x, train_y = train_type(train_fs) test_x = test_type(test_fs) gbc = gbc_classify(train_x, train_y) # svr_preds = gbc_svr_predict(gbc, train_x, train_y, test_x) #gbr_preds = gbc_gbr_predict(gbc, train_x, train_y, test_x) gp_preds = gbc_gp_predict(train_x, train_y, test_x) #preds_all = svr_preds * 0.4 + gp_preds * 0.25 + gbr_preds * 0.35 output_preds(gp_preds)
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Shows how to use the AWS SDK for Python (Boto3) with the Flask web framework to create a web application that manages work items in a DynamoDB table and sends email reports by using Amazon SES. """ from datetime import datetime import logging import boto3 from flask import Flask, render_template, redirect, url_for, request, flash from report import Report, ReportError from storage import Storage, StorageError logger = logging.getLogger(__name__) def create_app(test_config=None): """ Creates the Flask app, which responds to HTTP requests through its routes. The app is configured by settings in an optional config.py file. Config options are: * SECRET_KEY The secret key Flask uses for sessions. * TABLE_NAME The name of an existing DynamoDB table that stores work items. * ITEM_TRACKER_PROFILE The optional name of an IAM role that grants restricted permissions used by the app. When this option is set, Boto3 assumes the specified role and the app is authorized to make only requests allowed by the role. Otherwise, the app runs with the permissions of the default user. """ app = Flask(__name__) app.config.from_mapping( SECRET_KEY='change-for-production!', TABLE_NAME='doc-example-work-item-tracker', ITEM_TRACKER_PROFILE=None) if test_config is None: app.config.from_pyfile("config.py", silent=True) else: app.config.update(test_config) restricted_profile = app.config.get('ITEM_TRACKER_PROFILE') if restricted_profile is not None: logger.info("Using credentials from restricted profile %s.", restricted_profile) boto3.setup_default_session(profile_name=restricted_profile) else: logger.info("Using default credentials.") def add_formatted_date(work_item): """ Adds a formatted date to a work item. :param work_item: The work item to add the date to. """ work_item['formatted_date'] = datetime.fromisoformat( work_item['created_date']).strftime('%b %d %Y') def get_work_items(storage, status_filter): """ Gets work items from storage. :param storage: A Storage object that can get items from the DynamoDB table. :param status_filter: When specified, only items with this status are returned. :return: The requested work items and any error that occurred. """ work_items = [] error = None try: work_items = storage.get_items(status_filter) except StorageError as err: error = str(err) for work_item in work_items: add_formatted_date(work_item) return work_items, error @app.route('/') @app.route('/items') def items(): """ A route that gets work items currently stored in the table. :return: A rendered page that displays the current table of work items. When `status_filter` is specified in the query parameters, the returned list of items contains only items with the specified status. """ storage = Storage.from_context() logger.info("Getting items for table %s.", storage.table.name) status_filter = request.args.get('status_filter', 'All') work_items, error = get_work_items(storage, status_filter) return render_template( 'items.html', table=storage.table.name, items=work_items, status_filter=status_filter, error=error) @app.route('/item/', methods=['GET', 'POST']) @app.route('/item/<item_id>', methods=['GET', 'POST']) def item(item_id=None): """ A route that handles an individual item. GET <item_id> When item_id is not specified, renders an empty form that can be used to add a work item. When item_id is specified, renders a form that contains the specified work item's data. The form can be used to edit the work item. POST <item_id> When item_id is not specified, adds a work item to the table. When item_id is specified, updates the work item. After a POST, redirects to the /items/ route. """ storage = Storage.from_context() if request.method == 'GET': work_item = {'item_id': item_id} error = None if item_id is not None: try: work_item = storage.get_item(item_id) add_formatted_date(work_item) except StorageError as err: error = str(err) return render_template('item.html', **work_item, action='get', error=error) elif request.method == 'POST': work_item = { 'item_id': item_id, 'name': request.form.get('name'), 'description': request.form.get('description'), 'status': request.form.get('status')} try: storage.add_or_update_item(work_item) except StorageError as err: return render_template( 'item.html', **work_item, action='add or update', error=err) else: return redirect(url_for('items')) @app.route('/items/delete/<item_id>') def delete_item(item_id): """ A route that deletes a work item from the table. :param item_id: The ID of the work item to delete. :return: Redirects to the /items/ route. """ storage = Storage.from_context() try: storage.delete_item(item_id) except StorageError as err: flash(f"Couldn't delete item '{item_id}'.") flash(str(err)) return redirect(url_for('items')) @app.route('/report/<status_filter>', methods=['GET', 'POST']) def report(status_filter): """ A route that handles sending email reports. GET Renders a form that can be used to send an email report of work items. Before the form is rendered, the current list of work items is retrieved from the table. POST Sends an email report to the email recipient specified in the form. Both the sender and recipient email addresses must be verified with Amazon SES. Redirects to the /items/ route. :param status_filter: When specified, only work items with the specified status are included in the report. """ storage = Storage.from_context() work_items, error = get_work_items(storage, status_filter) if request.method == 'GET': return render_template( 'report.html', status_filter=status_filter, table=storage.table.name, items=work_items, error=error) elif request.method == 'POST': reporter = Report.from_context() message = request.form.get('message') text_report = render_template( 'email.txt', message=message, items=work_items) html_report = render_template( 'email.html', message=message, items=work_items) try: reporter.send( request.form.get('sender'), request.form.get('recipient'), f"Report for items with status '{status_filter}'", text_report, html_report) except ReportError as err: error = str(err) if not error: flash(f"Report sent.") if error: flash("Report not sent!") flash(str(error)) return redirect(url_for('items')) return app if __name__ == '__main__': logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') create_app().run(debug=True)
#!/usr/bin/python # Copyright 2012 Jurko Gospodnetic # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) # Temporarily enabled dummy test that always fails and is used to collect # extra debugging information from Boost Build test runner sites. import BoostBuild import os import re import sys ############################################################################### # # Public interface. # ############################################################################### def collectDebugInfo(): t = _init() global tag tag = "Python version" try: _info(sys.version) except: _info_exc() tag = "Python platform" try: _info(sys.platform) except: _info_exc() tag = "Boost Jam/Build version" try: _infoX(_getJamVersionInfo(t)) except: _info_exc() #_collectDebugInfo_environ() # Report prepared annotations. t.fail_test(1, dump_difference=False, dump_stdio=False, dump_stack=False) ############################################################################### # # Private interface. # ############################################################################### varSeparator = "###$^%~~~" def _collect(results, prefix, name, t): results.append("%s - %s - os.getenv(): %r" % (prefix, name, os.getenv( name))) results.append("%s - %s - os.environ.get(): %r" % (prefix, name, os.environ.get(name))) external_values = _getExternalValues(t, name) results.append("%s - %s - external: %r" % (prefix, name, external_values[name])) def _collectDebugInfo_environ(t): dummyVars = ["WOOF_WOOFIE_%d" % x for x in xrange(4)] global tag tag = "XXX in os.environ" try: def f(name): return "%s: %s" % (name, name in os.environ) _infoX(f(x) for x in dummyVars) except: _info_exc() tag = "os.environ[XXX]" try: def f(name): try: result = os.environ[name] except: result = _str_exc() return "%s: %r" % (name, result) _infoX(f(x) for x in dummyVars) except: _info_exc() tag = "os.environ.get(XXX)" try: def f(name): return "%s: %r" % (name, os.environ.get(name)) _infoX(f(x) for x in dummyVars) except: _info_exc() tag = "os.getenv(XXX)" try: def f(name): return "%s: %r" % (name, os.getenv(name)) _infoX(f(x) for x in dummyVars) except: _info_exc() name = dummyVars[0] value = "foo" tag = "os.putenv(%s) to %r" % (name, value) try: results = [] _collect(results, "before", name, t) os.putenv(name, value) _collect(results, "after", name, t) _infoX(results) except: _info_exc() name = dummyVars[1] value = "bar" tag = "os.environ[%s] to %r" % (name, value) try: results = [] _collect(results, "before", name, t) os.environ[name] = value _collect(results, "after", name, t) _infoX(results) except: _info_exc() name = dummyVars[1] value = "baz" tag = "os.putenv(%s) to %r" % (name, value) try: results = [] _collect(results, "before", name, t) os.putenv(name, value) _collect(results, "after", name, t) _infoX(results) except: _info_exc() name = dummyVars[1] value = "" tag = "os.putenv(%s) to %r" % (name, value) try: results = [] _collect(results, "before", name, t) os.putenv(name, value) _collect(results, "after", name, t) _infoX(results) except: _info_exc() name = dummyVars[2] value = "foo" tag = "os.unsetenv(%s) from %r" % (name, value) try: results = [] os.environ[name] = value _collect(results, "before", name, t) os.unsetenv(name) _collect(results, "after", name, t) _infoX(results) except: _info_exc() name = dummyVars[2] value = "foo" tag = "del os.environ[%s] from %r" % (name, value) try: results = [] os.environ[name] = value _collect(results, "before", name, t) del os.environ[name] _collect(results, "after", name, t) _infoX(results) except: _info_exc() name = dummyVars[2] value = "foo" tag = "os.environ.pop(%s) from %r" % (name, value) try: results = [] os.environ[name] = value _collect(results, "before", name, t) os.environ.pop(name) _collect(results, "after", name, t) _infoX(results) except: _info_exc() name = dummyVars[2] value1 = "foo" value2 = "" tag = "os.environ[%s] to %r from %r" % (name, value2, value1) try: results = [] os.environ[name] = value1 _collect(results, "before", name, t) os.environ[name] = value2 _collect(results, "after", name, t) _infoX(results) except: _info_exc() name = dummyVars[3] value = '""' tag = "os.environ[%s] to %r" % (name, value) try: results = [] _collect(results, "before", name, t) os.environ[name] = value _collect(results, "after", name, t) _infoX(results) except: _info_exc() def _getExternalValues(t, *args): t.run_build_system(["---var-name=%s" % x for x in args]) result = dict() for x in args: m = re.search(r"^\*\*\*ENV\*\*\* %s: '(.*)' \*\*\*$" % x, t.stdout(), re.MULTILINE) if m: result[x] = m.group(1) else: result[x] = None return result def _getJamVersionInfo(t): result = [] # JAM version variables. t.run_build_system(["---version"]) for m in re.finditer(r"^\*\*\*VAR\*\*\* ([^:]*): (.*)\*\*\*$", t.stdout(), re.MULTILINE): name = m.group(1) value = m.group(2) if not value: value = [] elif value[-1] == ' ': value = value[:-1].split(varSeparator) else: value = "!!!INVALID!!! - '%s'" % value result.append("%s = %s" % (name, value)) result.append("") # bjam -v output. t.run_build_system(["-v"]) result.append("--- output for 'bjam -v' ---") result.append(t.stdout()) # bjam --version output. t.run_build_system(["--version"], status=1) result.append("--- output for 'bjam --version' ---") result.append(t.stdout()) return result def _init(): toolsetName = "__myDummyToolset__" t = BoostBuild.Tester(["toolset=%s" % toolsetName], pass_toolset=False, use_test_config=False) # Prepare a dummy toolset so we do not get errors in case the default one # is not found. t.write(toolsetName + ".jam", """\ import feature ; feature.extend toolset : %s ; rule init ( ) { } """ % toolsetName ) # Python version of the same dummy toolset. t.write(toolsetName + ".py", """\ from b2.build import feature feature.extend('toolset', ['%s']) def init(): pass """ % toolsetName ) t.write("jamroot.jam", """\ import os ; .argv = [ modules.peek : ARGV ] ; local names = [ MATCH ^---var-name=(.*) : $(.argv) ] ; for x in $(names) { value = [ os.environ $(x) ] ; ECHO ***ENV*** $(x): '$(value)' *** ; } if ---version in $(.argv) { for x in JAMVERSION JAM_VERSION JAMUNAME JAM_TIMESTAMP_RESOLUTION OS { v = [ modules.peek : $(x) ] ; ECHO ***VAR*** $(x): "$(v:J=%s)" *** ; } } """ % varSeparator) return t def _info(*values): values = list(values) + [""] BoostBuild.annotation(tag, "\n".join(str(x) for x in values)) def _infoX(values): _info(*values) def _info_exc(): _info(_str_exc()) def _str_exc(): exc_type, exc_value = sys.exc_info()[0:2] if exc_type is None: exc_type_name = "None" else: exc_type_name = exc_type.__name__ return "*** EXCEPTION *** %s - %s ***" % (exc_type_name, exc_value) ############################################################################### # # main() # ------ # ############################################################################### collectDebugInfo()
''' ''' from __future__ import absolute_import, division from collections import defaultdict import numpy as np import pandas as pd from bokeh.charts import DEFAULT_PALETTE from bokeh.core.enums import DashPattern from bokeh.models.glyphs import Arc, Line, Patches, Rect, Segment from bokeh.models.renderers import GlyphRenderer from bokeh.core.properties import Any, Angle, Bool, Color, Datetime, Either, Enum, Float, List, Override, Instance, Int, String from .data_source import ChartDataSource from .models import CompositeGlyph from .properties import Column, EitherColumn from .stats import BinnedStat, Bins, Histogram, Max, Min, Quantile, Stat, stats, Sum from .utils import generate_patch_base, label_from_index_dict, marker_types class NestedCompositeGlyph(CompositeGlyph): """A composite glyph that consists of other composite glyphs. An important responsibility of any `CompositeGlyph` is to understand the bounds of the glyph renderers that make it up. This class is used to provide convenient properties that return the bounds from the child `CompositeGlyphs`. """ children = List(Instance(CompositeGlyph)) @property def y_max(self): return max([renderer.y_max for renderer in self.children]) @property def y_min(self): return min([renderer.y_min for renderer in self.children]) @property def x_min(self): return min([renderer.x_min for renderer in self.children]) @property def x_max(self): return max([renderer.x_max for renderer in self.children]) class XyGlyph(CompositeGlyph): """Composite glyph that plots in cartesian coordinates.""" x = EitherColumn(String, Column(Float), Column(String), Column(Datetime), Column(Bool)) y = EitherColumn(String, Column(Float), Column(String), Column(Datetime), Column(Bool)) def build_source(self): labels = self._build_label_array(('x', 'y'), self.label) str_labels = [str(label) for label in labels] if self.x is None: data = dict(x_values=str_labels, y_values=self.y) elif self.y is None: data = dict(x_values=self.x, y_values=str_labels) else: data = dict(x_values=self.x, y_values=self.y) return data def _build_label_array(self, props, value): for prop in props: if getattr(self, prop) is not None: return [value] * len(getattr(self, prop)) @property def x_max(self): # TODO(fpliger): since CompositeGlyphs are not exposed in general we # should expect to always have a Series but in case # it's not we just use the default min/max instead # of just failing. When/If we end up exposing # CompositeGlyphs we should consider making this # more robust (either enforcing data or checking) try: return self.source.data['x_values'].max() except AttributeError: return max(self.source.data['x_values']) @property def x_min(self): try: return self.source.data['x_values'].min() except AttributeError: return min(self.source.data['x_values']) @property def y_max(self): try: return self.source.data['y_values'].max() except AttributeError: return max(self.source.data['y_values']) @property def y_min(self): try: return self.source.data['y_values'].min() except AttributeError: return min(self.source.data['y_values']) class PointGlyph(XyGlyph): """A set of glyphs placed in x,y coordinates with the same attributes.""" fill_color = Override(default=DEFAULT_PALETTE[1]) fill_alpha = Override(default=0.7) marker = String(default='circle') size = Float(default=8) def __init__(self, x=None, y=None, color=None, line_color=None, fill_color=None, marker=None, size=None, **kwargs): kwargs['x'] = x kwargs['y'] = y if marker is not None: kwargs['marker'] = marker if size is not None: kwargs['size'] = size if color: line_color = color fill_color = color kwargs['line_color'] = line_color kwargs['fill_color'] = fill_color super(PointGlyph, self).__init__(**kwargs) self.setup() def get_glyph(self): return marker_types[self.marker] def build_renderers(self): glyph_type = self.get_glyph() glyph = glyph_type(x='x_values', y='y_values', line_color=self.line_color, fill_color=self.fill_color, size=self.size, fill_alpha=self.fill_alpha, line_alpha=self.line_alpha) yield GlyphRenderer(glyph=glyph) class LineGlyph(XyGlyph): """Represents a group of data as a line.""" width = Int(default=2) dash = Enum(DashPattern, default='solid') def __init__(self, x=None, y=None, color=None, line_color=None, width=None, dash=None, **kwargs): kwargs['x'] = x kwargs['y'] = y if color is not None and line_color is None: line_color = color if dash is not None: kwargs['dash'] = dash if width is not None: kwargs['width'] = width if line_color is not None: kwargs['line_color'] = line_color super(LineGlyph, self).__init__(**kwargs) self.setup() def build_source(self): if self.x is None: x = self.y.index data = dict(x_values=x, y_values=self.y) elif self.y is None: y = self.x.index data = dict(x_values=self.x, y_values=y) else: data = dict(x_values=self.x, y_values=self.y) return data def build_renderers(self): """Yield a `GlyphRenderer` for the group of data.""" glyph = Line(x='x_values', y='y_values', line_color=self.line_color, line_alpha=self.line_alpha, line_width=self.width, line_dash=self.dash) yield GlyphRenderer(glyph=glyph) class AreaGlyph(LineGlyph): # ToDo: should these be added to composite glyph? stack = Bool(default=False) dodge = Bool(default=False) base = Float(default=0.0, help="""Lower bound of area.""") def __init__(self, **kwargs): line_color = kwargs.get('line_color') fill_color = kwargs.get('fill_color') color = kwargs.get('color') if color is not None: # apply color to line and fill kwargs['fill_color'] = color kwargs['line_color'] = color elif line_color is not None and fill_color is None: # apply line color to fill color by default kwargs['fill_color'] = line_color super(AreaGlyph, self).__init__(**kwargs) self.setup() def build_source(self): data = super(AreaGlyph, self).build_source() x0, y0 = generate_patch_base(pd.Series(list(data['x_values'])), pd.Series(list(data['y_values']))) data['x_values'] = [x0] data['y_values'] = [y0] return data def build_renderers(self): # parse all series. We exclude the first attr as it's the x values # added for the index glyph = Patches( xs='x_values', ys='y_values', fill_alpha=self.fill_alpha, fill_color=self.fill_color, line_color=self.line_color ) renderer = GlyphRenderer(data_source=self.source, glyph=glyph) yield renderer def __stack__(self, glyphs): # ToDo: need to handle case of non-aligned indices, see pandas concat # ToDo: need to address how to aggregate on an index when required # build a list of series areas = [] for glyph in glyphs: areas.append(pd.Series(glyph.source.data['y_values'][0], index=glyph.source.data['x_values'][0])) # concat the list of indexed y values into dataframe df = pd.concat(areas, axis=1) # calculate stacked values along the rows stacked_df = df.cumsum(axis=1) # lower bounds of each area series are diff between stacked and orig values lower_bounds = stacked_df - df # reverse the df so the patch is drawn in correct order lower_bounds = lower_bounds.iloc[::-1] # concat the upper and lower bounds together stacked_df = pd.concat([stacked_df, lower_bounds]) # update the data in the glyphs for i, glyph in enumerate(glyphs): glyph.source.data['x_values'] = [stacked_df.index.values] glyph.source.data['y_values'] = [stacked_df.ix[:, i].values] def get_nested_extent(self, col, func): return [getattr(arr, func)() for arr in self.source.data[col]] @property def x_max(self): return max(self.get_nested_extent('x_values', 'max')) @property def x_min(self): return min(self.get_nested_extent('x_values', 'min')) @property def y_max(self): return max(self.get_nested_extent('y_values', 'max')) @property def y_min(self): return min(self.get_nested_extent('y_values', 'min')) class HorizonGlyph(AreaGlyph): num_folds = Int(default=3, help="""The count of times the data is overlapped.""") series = Int(default=0, help="""The id of the series as the order it will appear, starting from 0.""") series_count = Int() fold_height = Float(help="""The height of one fold.""") bins = List(Float, help="""The binedges calculated from the number of folds, and the maximum value of the entire source data.""") graph_ratio = Float(help="""Scales heights of each series based on number of folds and the number of total series being plotted. """) pos_color = Color("#006400", help="""The color used for positive values.""") neg_color = Color("#6495ed", help="""The color used for negative values.""") flip_neg = Bool(default=True, help="""When True, the negative values will be plotted as their absolute value, then their individual axes is flipped. If False, then the negative values will still be taken as their absolute value, but the base of their shape will start from the same origin as the positive values. """) def __init__(self, bins=None, **kwargs): # fill alpha depends on how many folds will be layered kwargs['fill_alpha'] = 1.0/kwargs['num_folds'] if bins is not None: kwargs['bins'] = bins # each series is shifted up to a synthetic y-axis kwargs['base'] = kwargs['series'] * max(bins) / kwargs['series_count'] kwargs['graph_ratio'] = float(kwargs['num_folds'])/float(kwargs['series_count']) super(HorizonGlyph, self).__init__(**kwargs) def build_source(self): data = {} # Build columns for the positive values pos_y = self.y.copy() pos_y[pos_y < 0] = 0 xs, ys = self._build_dims(self.x, pos_y) # list of positive colors and alphas colors = [self.pos_color] * len(ys) alphas = [(bin_idx * self.fill_alpha) for bin_idx in range(0, len(self.bins))] # If we have negative values at all, add the values for those as well if self.y.min() < 0: neg_y = self.y.copy() neg_y[neg_y > 0] = 0 neg_y = abs(neg_y) neg_xs, neg_ys = self._build_dims(self.x, neg_y, self.flip_neg) xs += neg_xs ys += neg_ys colors += ([self.neg_color] * len(neg_ys)) alphas += alphas # create clipped representation of each band data['x_values'] = xs data['y_values'] = ys data['fill_color'] = colors data['fill_alpha'] = colors data['line_color'] = colors return data def _build_dims(self, x, y, flip=False): """ Creates values needed to plot each fold of the horizon glyph. Bins the data based on the binning passed into the glyph, then copies and clips the values for each bin. Args: x (`pandas.Series`): array of x values y (`pandas.Series`): array of y values flip (bool): whether to flip values, used when handling negative values Returns: tuple(list(`numpy.ndarray`), list(`numpy.ndarray`)): returns a list of arrays for the x values and list of arrays for the y values. The data has been folded and transformed so the patches glyph presents the data in a way that looks like an area chart. """ # assign bins to each y value bin_idx = pd.cut(y, bins=self.bins, labels=False, include_lowest=True) xs, ys = [], [] for idx, bin in enumerate(self.bins[0:-1]): # subtract off values associated with lower bins, to get into this bin temp_vals = y.copy() - (idx * self.fold_height) # clip the values between the fold range and zero temp_vals[bin_idx > idx] = self.fold_height * self.graph_ratio temp_vals[bin_idx < idx] = 0 temp_vals[bin_idx == idx] = self.graph_ratio * temp_vals[bin_idx == idx] # if flipping, we must start the values from the top of each fold's range if flip: temp_vals = (self.fold_height * self.graph_ratio) - temp_vals base = self.base + (self.fold_height * self.graph_ratio) else: base = self.base # shift values up based on index of series temp_vals += self.base val_idx = temp_vals > 0 if pd.Series.any(val_idx): ys.append(temp_vals) xs.append(x) # transform clipped data so it always starts and ends at its base value if len(ys) > 0: xs, ys = map(list, zip(*[generate_patch_base(xx, yy, base=base) for xx, yy in zip(xs, ys)])) return xs, ys def build_renderers(self): # parse all series. We exclude the first attr as it's the x values # added for the index glyph = Patches( xs='x_values', ys='y_values', fill_alpha=self.fill_alpha, fill_color='fill_color', line_color='line_color' ) renderer = GlyphRenderer(data_source=self.source, glyph=glyph) yield renderer class StepGlyph(LineGlyph): """Represents a group of data as a stepped line.""" def build_source(self): x = self.x y = self.y if self.x is None: x = self.y.index elif self.y is None: y = self.x.index dtype = x.dtype if hasattr(x, 'dtype') else np.int xs = np.empty(2*len(x)-1, dtype=dtype) xs[::2] = x[:] xs[1::2] = x[1:] dtype = y.dtype if hasattr(y, 'dtype') else np.float64 ys = np.empty(2*len(y)-1, dtype=dtype) ys[::2] = y[:] ys[1::2] = y[:-1] data = dict(x_values=xs, y_values=ys) return data class AggregateGlyph(NestedCompositeGlyph): """A base composite glyph for aggregating an array. Implements default stacking and dodging behavior that other composite glyphs can inherit. """ x_label = String() x_label_value = Any() stack_label = String() stack_shift = Float(default=0.0) dodge_label = String(help="""Where on the scale the glyph should be placed.""") dodge_shift = Float(default=None) agg = Instance(Stat, default=Sum()) span = Float(help="""The range of values represented by the aggregate.""") def __init__(self, x_label=None, **kwargs): label = kwargs.get('label') if x_label is not None: kwargs['x_label_value'] = x_label if not isinstance(x_label, str): x_label = str(x_label) kwargs['x_label'] = x_label elif label is not None: kwargs['x_label'] = str(label) super(AggregateGlyph, self).__init__(**kwargs) def get_dodge_label(self, shift=0.0): """Generate the label defining an offset in relation to a position on a scale.""" if self.dodge_shift is None: shift_str = ':' + str(0.5 + shift) elif self.dodge_shift is not None: shift_str = ':' + str(self.dodge_shift + shift) else: shift_str = '' return str(label_from_index_dict(self.x_label)) + shift_str def filter_glyphs(self, glyphs): """Return only the glyphs that are of the same class.""" return [glyph for glyph in glyphs if isinstance(glyph, self.__class__)] @staticmethod def groupby(glyphs, prop): """Returns a dict of `CompositeGlyph`s, grouped by unique values of prop. For example, if all glyphs had a value of 'a' or 'b' for glyph.prop, the dict would contain two keys, 'a' and 'b', where each value is a list of the glyphs that had each of the values. """ grouped = defaultdict(list) labels = [getattr(glyph, prop) for glyph in glyphs] labels = [tuple(label.values()) if isinstance(label, dict) else label for label in labels] [grouped[label].append(glyph) for label, glyph in zip(labels, glyphs)] labels = pd.Series(labels).drop_duplicates().values return labels, grouped def __stack__(self, glyphs): """Apply relative shifts to the composite glyphs for stacking.""" filtered_glyphs = self.filter_glyphs(glyphs) labels, grouped = self.groupby(filtered_glyphs, 'x_label') for label in labels: group = grouped[label] # separate the negative and positive aggregates into separate groups neg_group = [glyph for glyph in group if glyph.span < 0] pos_group = [glyph for glyph in group if glyph.span >= 0] # apply stacking to each group separately for group in [neg_group, pos_group]: shift = [] for i, glyph in enumerate(group): # save off the top of each rect's height shift.append(glyph.span) if i > 0: glyph.stack_shift = sum(shift[0:i]) glyph.refresh() def __dodge__(self, glyphs): """Apply relative shifts to the composite glyphs for dodging.""" if self.dodge_label is not None: filtered_glyphs = self.filter_glyphs(glyphs) labels, grouped = self.groupby(filtered_glyphs, 'dodge_label') # calculate transformations step = np.linspace(0, 1.0, len(grouped.keys()) + 1, endpoint=False) width = min(0.2, (1. / len(grouped.keys())) ** 1.1) # set bar attributes and re-aggregate for i, label in enumerate(labels): group = grouped[label] for glyph in group: glyph.dodge_shift = step[i + 1] glyph.width = width glyph.refresh() class Interval(AggregateGlyph): """A rectangle representing aggregated values. The interval is a rect glyph where two of the parallel sides represent a summary of values. Each of the two sides is derived from a separate aggregation of the values provided to the interval. .. note:: A bar is a special case interval where one side is pinned and used to communicate a value relative to it. """ width = Float(default=0.8) start_agg = Either(Instance(Stat), Enum(*list(stats.keys())), default=Min(), help=""" The stat used to derive the starting point of the composite glyph.""") end_agg = Either(Instance(Stat), Enum(*list(stats.keys())), default=Max(), help=""" The stat used to derive the end point of the composite glyph.""") start = Float(default=0.0) end = Float() def __init__(self, label, values, **kwargs): kwargs['label'] = label kwargs['values'] = values super(Interval, self).__init__(**kwargs) self.setup() def get_start(self): """Get the value for the start of the glyph.""" if len(self.values.index) == 1: self.start_agg = None return self.values[0] elif isinstance(self.start_agg, str): self.start_agg = stats[self.start_agg]() self.start_agg.set_data(self.values) return self.start_agg.value def get_end(self): """Get the value for the end of the glyph.""" if isinstance(self.end_agg, str): self.end_agg = stats[self.end_agg]() self.end_agg.set_data(self.values) return self.end_agg.value def get_span(self): """The total range between the start and end.""" return self.end - self.start def build_source(self): # ToDo: Handle rotation self.start = self.get_start() self.end = self.get_end() self.span = self.get_span() width = [self.width] if self.dodge_shift is not None: x = [self.get_dodge_label()] else: x = [self.x_label] height = [self.span] y = [self.stack_shift + (self.span / 2.0) + self.start] color = [self.color] fill_alpha = [self.fill_alpha] line_color = [self.line_color] line_alpha = [self.line_alpha] label = [self.label] return dict(x=x, y=y, width=width, height=height, color=color, fill_alpha=fill_alpha, line_color=line_color, line_alpha=line_alpha, label=label) @property def x_max(self): """The maximum extent of the glyph in x. .. note:: Dodging the glyph can affect the value. """ return (self.dodge_shift or self.x_label_value) + (self.width / 2.0) @property def x_min(self): """The maximum extent of the glyph in y. .. note:: Dodging the glyph can affect the value. """ return (self.dodge_shift or self.x_label_value) - (self.width / 2.0) @property def y_max(self): """Maximum extent of all `Glyph`s. How much we are stacking + the height of the interval + the base of the interval .. note:: the start and end of the glyph can swap between being associated with the min and max when the glyph end represents a negative value. """ return max(self.bottom, self.top) @property def y_min(self): """The minimum extent of all `Glyph`s in y. .. note:: the start and end of the glyph can swap between being associated with the min and max when the glyph end represents a negative value. """ return min(self.bottom, self.top) @property def bottom(self): """The value associated with the start of the stacked glyph.""" return self.stack_shift + self.start @property def top(self): """The value associated with the end of the stacked glyph.""" return self.stack_shift + self.span + self.start def build_renderers(self): """Yields a `GlyphRenderer` associated with a `Rect` glyph.""" glyph = Rect(x='x', y='y', width='width', height='height', fill_color='color', fill_alpha='fill_alpha', line_color='line_color') yield GlyphRenderer(glyph=glyph) class BarGlyph(Interval): """Special case of Interval where the span represents a value. A bar always begins from 0, or the value that is being compared to, and extends to some positive or negative value. """ def __init__(self, label, values, agg='sum', **kwargs): kwargs['end_agg'] = agg kwargs['start_agg'] = None super(BarGlyph, self).__init__(label, values, **kwargs) self.setup() def get_start(self): return 0.0 class DotGlyph(Interval): """Special case of Interval where the span represents a value. A bar always begins from 0, or the value that is being compared to, and extends to some positive or negative value. """ marker = String(default='circle') size = Float(default=8) stem = Bool(False, help=""" Whether to draw a stem from each do to the axis. """) stem_line_width = Float(default=1) stem_color = String(default='black') def __init__(self, label, values, agg='sum', **kwargs): kwargs['end_agg'] = agg super(DotGlyph, self).__init__(label, values, **kwargs) self.setup() def get_start(self): return 0.0 def get_glyph(self): return marker_types[self.marker] def build_renderers(self): if self.stem: yield GlyphRenderer(glyph=Segment( x0='x', y0=0, x1='x', y1='height', line_width=self.stem_line_width, line_color=self.stem_color, line_alpha='fill_alpha') ) glyph_type = self.get_glyph() glyph = glyph_type(x='x', y='height', line_color=self.line_color, fill_color=self.color, size=self.size, fill_alpha='fill_alpha', line_alpha='line_alpha' ) yield GlyphRenderer(glyph=glyph) class QuartileGlyph(Interval): """An interval that has start and end aggregations of quartiles.""" def __init__(self, label, values, interval1, interval2, **kwargs): kwargs['label'] = label kwargs['values'] = values kwargs['start_agg'] = Quantile(interval=interval1) kwargs['end_agg'] = Quantile(interval=interval2) super(QuartileGlyph, self).__init__(**kwargs) self.setup() class BoxGlyph(AggregateGlyph): """Summarizes the distribution with a collection of glyphs. A box glyph produces one "box" for a given array of vales. The box is made up of multiple other child composite glyphs (intervals, scatter) and directly produces glyph renderers for the whiskers, as well. """ q1 = Float(help="""Derived value for 25% of all values.""") q2 = Float(help="""Derived value for 50% of all values.""") q3 = Float(help="""Derived value for 75% of all values.""") iqr = Float() w0 = Float(help='Lower whisker') w1 = Float(help='Upper whisker') q2_glyph = Instance(QuartileGlyph) q3_glyph = Instance(QuartileGlyph) whisker_glyph = Instance(GlyphRenderer) outliers = Either(Bool, Instance(PointGlyph)) marker = String(default='circle') whisker_width = Float(default=0.3) whisker_line_width = Float(default=2) whisker_span_line_width = Float(default=2) whisker_color = String(default='black') outlier_fill_color = String(default='red') outlier_line_color = String(default='red') outlier_size = Float(default=5) bar_color = String(default='DimGrey') def __init__(self, label, values, outliers=True, **kwargs): width = kwargs.pop('width', None) bar_color = kwargs.pop('color', None) or kwargs.get('bar_color') or self.lookup('bar_color').class_default() kwargs['outliers'] = kwargs.pop('outliers', None) or outliers kwargs['label'] = label kwargs['values'] = values x_label = kwargs.get('x_label') kwargs['q2_glyph'] = QuartileGlyph(label=label, x_label=x_label, values=values, interval1=0.25, interval2=0.5, width=width, color=bar_color) kwargs['q3_glyph'] = QuartileGlyph(label=label, x_label=x_label, values=values, interval1=0.5, interval2=0.75, width=width, color=bar_color) super(BoxGlyph, self).__init__(**kwargs) self.setup() def build_renderers(self): """Yields all renderers that make up the BoxGlyph.""" self.calc_quartiles() outlier_values = self.values[((self.values < self.w0) | (self.values > self.w1))] self.whisker_glyph = GlyphRenderer(glyph=Segment(x0='x0s', y0='y0s', x1='x1s', y1='y1s', line_width=self.whisker_line_width, line_color=self.whisker_color)) if len(outlier_values) > 0 and self.outliers: self.outliers = PointGlyph(label=self.label, y=outlier_values, x=[self.get_dodge_label()] * len(outlier_values), line_color=self.outlier_line_color, fill_color=self.outlier_fill_color, size=self.outlier_size, marker=self.marker) for comp_glyph in self.composite_glyphs: for renderer in comp_glyph.renderers: yield renderer yield self.whisker_glyph def calc_quartiles(self): """Sets all derived stat properties of the BoxGlyph.""" self.q1 = self.q2_glyph.start self.q2 = self.q2_glyph.end self.q3 = self.q3_glyph.end self.iqr = self.q3 - self.q1 mx = Max() mx.set_data(self.values) mn = Min() mn.set_data(self.values) self.w0 = max(self.q1 - (1.5 * self.iqr), mn.value) self.w1 = min(self.q3 + (1.5 * self.iqr), mx.value) def build_source(self): """Calculate stats and builds and returns source for whiskers.""" self.calc_quartiles() x_label = self.get_dodge_label() x_w0_label = self.get_dodge_label(shift=(self.whisker_width / 2.0)) x_w1_label = self.get_dodge_label(shift=-(self.whisker_width / 2.0)) # span0, whisker bar0, span1, whisker bar1 x0s = [x_label, x_w0_label, x_label, x_w0_label] y0s = [self.w0, self.w0, self.q3, self.w1] x1s = [x_label, x_w1_label, x_label, x_w1_label] y1s = [self.q1, self.w0, self.w1, self.w1] return dict(x0s=x0s, y0s=y0s, x1s=x1s, y1s=y1s) def _set_sources(self): """Set the column data source on the whisker glyphs.""" self.whisker_glyph.data_source = self.source def get_extent(self, func, prop_name): return func([getattr(renderer, prop_name) for renderer in self.composite_glyphs]) @property def composite_glyphs(self): """Returns list of composite glyphs, excluding the regular glyph renderers.""" comp_glyphs = [self.q2_glyph, self.q3_glyph] if isinstance(self.outliers, PointGlyph): comp_glyphs.append(self.outliers) return comp_glyphs @property def x_max(self): return self.get_extent(max, 'x_max') + self.right_buffer @property def x_min(self): return self.get_extent(min, 'x_min') - self.left_buffer @property def y_max(self): return max(self.w1, self.get_extent(max, 'y_max')) + self.top_buffer @property def y_min(self): return min(self.w0, self.get_extent(min, 'y_min')) - self.bottom_buffer class HistogramGlyph(AggregateGlyph): """Depicts the distribution of values using rectangles created by binning. The histogram represents a distribution, so will likely include other options for displaying it, such as KDE and cumulative density. """ # derived models bins = Instance(BinnedStat, help="""A stat used to calculate the bins. The bins stat includes attributes about each composite bin.""") bars = List(Instance(BarGlyph), help="""The histogram is comprised of many BarGlyphs that are derived from the values.""") density = Bool(False, help=""" Whether to normalize the histogram. If True, the result is the value of the probability *density* function at the bin, normalized such that the *integral* over the range is 1. If False, the result will contain the number of samples in each bin. For more info check :class:`~bokeh.charts.stats.Histogram` documentation. (default: False) """) def __init__(self, values, label=None, color=None, bins=None, **kwargs): if label is not None: kwargs['label'] = label kwargs['values'] = values if color is not None: kwargs['color'] = color # remove width, since this is handled automatically kwargs.pop('width', None) # keep original bins setting private since it just needs to be # delegated to the Histogram stat self._bins = bins super(HistogramGlyph, self).__init__(**kwargs) self.setup() def _set_sources(self): # No need to set sources, since composite glyphs handle this pass def build_source(self): # No need to build source, since composite glyphs handle this return None def build_renderers(self): """Yield a bar glyph for each bin.""" # TODO(fpliger): We should expose the bin stat class so we could let # users specify other bins other the Histogram Stat self.bins = Histogram(values=self.values, bins=self._bins, density=self.density) bars = [] for bin in self.bins.bins: bars.append(BarGlyph(label=bin.label[0], x_label=bin.center, values=bin.values, color=self.color, fill_alpha=self.fill_alpha, agg=bin.stat, width=bin.width)) # provide access to bars as children for bounds properties self.bars = self.children = bars for comp_glyph in self.bars: for renderer in comp_glyph.renderers: yield renderer @property def y_min(self): return 0.0 class BinGlyph(XyGlyph): """Represents a group of data that was aggregated and is represented by a glyph. """ bins = Instance(Bins) column = String() stat = String() glyph_name = String() width = Float() height = Float() def __init__(self, x, y, values, column=None, stat='count', glyph='rect', width=1, height=1, **kwargs): df = pd.DataFrame(dict(x_vals=x, y_vals=y, values_vals=values)) df.drop_duplicates(inplace=True) kwargs['x'] = df.x_vals kwargs['y'] = df.y_vals kwargs['values'] = df.values_vals kwargs['column'] = column kwargs['stat'] = stat kwargs['glyph_name'] = glyph kwargs['height'] = height kwargs['width'] = width if 'glyphs' not in kwargs: kwargs['glyphs'] = {'rect': Rect} super(XyGlyph, self).__init__(**kwargs) self.setup() def build_source(self): return {'x': self.x, 'y': self.y, 'values': self.values} def build_renderers(self): glyph_class = self.glyphs[self.glyph_name] glyph = glyph_class(x='x', y='y', height=self.height, width=self.width, fill_color=self.fill_color, line_color=self.line_color, dilate=True) yield GlyphRenderer(glyph=glyph) @property def x_max(self): return self.get_data_range('x')[1] + self.width / 2.0 @property def x_min(self): return self.get_data_range('x')[0] - self.width / 2.0 @property def y_max(self): return self.get_data_range('y')[1] + self.height / 2.0 @property def y_min(self): return self.get_data_range('y')[0] - self.height / 2.0 def get_data_range(self, col): data = self.source.data[col] if ChartDataSource.is_number(data): return min(data), max(data) else: return 1, len(data.drop_duplicates()) class ArcGlyph(LineGlyph): """Represents a group of data as an arc.""" start_angle = Angle() end_angle = Angle() def __init__(self, **kwargs): super(self.__class__, self).__init__(**kwargs) self.setup() def build_renderers(self): """Yield a `GlyphRenderer` for the group of data.""" glyph = Arc(x='x', y='y', radius=1, start_angle='_end_angle', end_angle='_start_angle', line_color='line_color') yield GlyphRenderer(glyph=glyph)
from nose.tools import assert_equals, assert_almost_equals, assert_raises, assert_true from scikits.crab.similarities.basic_similarities import UserSimilarity from scikits.crab.metrics.pairwise import euclidean_distances, jaccard_coefficient from scikits.crab.models.classes import MatrixPreferenceDataModel, \ MatrixBooleanPrefDataModel from scikits.crab.recommenders.knn import UserBasedRecommender from scikits.crab.metrics.classes import CfEvaluator from scikits.crab.recommenders.knn.neighborhood_strategies import NearestNeighborsStrategy movies = {'Marcel Caraciolo': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5, 'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5, 'The Night Listener': 3.0}, 'Luciana Nunes': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.5, 'Just My Luck': 1.5, 'Superman Returns': 5.0, 'The Night Listener': 3.0, 'You, Me and Dupree': 3.5}, 'Leopoldo Pires': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.0, 'Superman Returns': 3.5, 'The Night Listener': 4.0}, 'Lorena Abreu': {'Snakes on a Plane': 3.5, 'Just My Luck': 3.0, 'The Night Listener': 4.5, 'Superman Returns': 4.0, 'You, Me and Dupree': 2.5}, 'Steve Gates': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0, 'Just My Luck': 2.0, 'Superman Returns': 3.0, 'The Night Listener': 3.0, 'You, Me and Dupree': 2.0}, 'Sheldom': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0, 'The Night Listener': 3.0, 'Superman Returns': 5.0, 'You, Me and Dupree': 3.5}, 'Penny Frewman': {'Snakes on a Plane': 4.5, 'You, Me and Dupree': 1.0, 'Superman Returns': 4.0}, 'Maria Gabriela': {}} model = MatrixPreferenceDataModel(movies) boolean_model = MatrixBooleanPrefDataModel(movies) similarity = UserSimilarity(model, euclidean_distances) boolean_similarity = UserSimilarity(boolean_model, jaccard_coefficient) neighborhood = NearestNeighborsStrategy() recsys = UserBasedRecommender(model, similarity, neighborhood) boolean_recsys = UserBasedRecommender(boolean_model, boolean_similarity, neighborhood) def test_root_CfEvaluator_evaluate(): """Check evaluate method in CfEvaluator """ evaluator = CfEvaluator() #Test with invalid metric assert_raises(ValueError, evaluator.evaluate, recsys, 'rank') #Test with specified metric rmse = evaluator.evaluate(recsys, 'rmse', permutation=False) assert_true(rmse['rmse'] >= 0.0 and rmse['rmse'] <= 1.0) mae = evaluator.evaluate(recsys, 'mae', permutation=False) assert_true(mae['mae'] >= 0.0 and mae['mae'] <= 1.0) nmae = evaluator.evaluate(recsys, 'nmae', permutation=False) assert_true(nmae['nmae'] >= 0.0 and nmae['nmae'] <= 1.0) precision = evaluator.evaluate(recsys, 'precision', permutation=False) assert_true(precision['precision'] >= 0.0 and precision['precision'] <= 1.0) recall = evaluator.evaluate(recsys, 'recall', permutation=False) assert_true(recall['recall'] >= 0.0 and recall['recall'] <= 1.0) f1score = evaluator.evaluate(recsys, 'f1score', permutation=False) assert_true(f1score['f1score'] >= 0.0 and f1score['f1score'] <= 1.0) all_scores = evaluator.evaluate(recsys, permutation=False) assert_true(all_scores['f1score'] >= 0.0 and all_scores['f1score'] <= 1.0) assert_true(all_scores['recall'] >= 0.0 and all_scores['recall'] <= 1.0) assert_true(all_scores['precision'] >= 0.0 and all_scores['precision'] <= 1.0) assert_true(all_scores['nmae'] >= 0.0 and all_scores['nmae'] <= 1.0) assert_true(all_scores['mae'] >= 0.0 and all_scores['mae'] <= 1.0) assert_true(all_scores['rmse'] >= 0.0 and all_scores['rmse'] <= 1.0) #With values at sampling. nmae = evaluator.evaluate(recsys, 'nmae', permutation=False, sampling_users=0.6, sampling_ratings=0.6) assert_true(nmae['nmae'] >= 0.0 and nmae['nmae'] <= 1.0) #Test with boolean recsys assert_raises(ValueError, evaluator.evaluate, boolean_recsys, 'rank') #Test with specified metric rmse = evaluator.evaluate(boolean_recsys, 'rmse', permutation=False) assert_true(rmse['rmse'] >= 0.0 and rmse['rmse'] <= 1.0) mae = evaluator.evaluate(boolean_recsys, 'mae', permutation=False) assert_true(mae['mae'] >= 0.0 and mae['mae'] <= 1.0) nmae = evaluator.evaluate(boolean_recsys, 'nmae', permutation=False) assert_true(nmae['nmae'] >= 0.0 and nmae['nmae'] <= 1.0) precision = evaluator.evaluate(boolean_recsys, 'precision', permutation=False) assert_true(precision['precision'] >= 0.0 and precision['precision'] <= 1.0) recall = evaluator.evaluate(boolean_recsys, 'recall', permutation=False) assert_true(recall['recall'] >= 0.0 and recall['recall'] <= 1.0) f1score = evaluator.evaluate(boolean_recsys, 'f1score', permutation=False) assert_true(f1score['f1score'] >= 0.0 and f1score['f1score'] <= 1.0) all_scores = evaluator.evaluate(recsys, permutation=False) assert_true(all_scores['f1score'] >= 0.0 and all_scores['f1score'] <= 1.0) assert_true(all_scores['recall'] >= 0.0 and all_scores['recall'] <= 1.0) assert_true(all_scores['precision'] >= 0.0 and all_scores['precision'] <= 1.0) assert_true(all_scores['nmae'] >= 0.0 and all_scores['nmae'] <= 1.0) assert_true(all_scores['mae'] >= 0.0 and all_scores['mae'] <= 1.0) assert_true(all_scores['rmse'] >= 0.0 and all_scores['rmse'] <= 1.0) #With values at sampling. nmae = evaluator.evaluate(boolean_recsys, 'nmae', permutation=False, sampling_users=0.6, sampling_ratings=0.6) assert_true(nmae['nmae'] >= 0.0 and nmae['nmae'] <= 1.0) def test_root_CfEvaluator_evaluate_on_split(): """Check evaluate_on_split method in CfEvaluator """ evaluator = CfEvaluator() #Test with invalid metric assert_raises(ValueError, evaluator.evaluate_on_split, recsys, 'rank') #Test with specified metric rmse = evaluator.evaluate_on_split(recsys, 'rmse', permutation=False) for p in rmse[0]['error']: assert_true(p['rmse'] >= 0.0 and p['rmse'] <= 1.0) assert_true(rmse[1]['final_error']['avg']['rmse'] >= 0.0 and rmse[1]['final_error']['stdev']['rmse'] <= 1.0) mae = evaluator.evaluate_on_split(recsys, 'mae', permutation=False) for p in mae[0]['error']: assert_true(p['mae'] >= 0.0 and p['mae'] <= 1.0) assert_true(mae[1]['final_error']['avg']['mae'] >= 0.0 and mae[1]['final_error']['stdev']['mae'] <= 1.0) nmae = evaluator.evaluate_on_split(recsys, 'nmae', permutation=False) for p in nmae[0]['error']: assert_true(p['nmae'] >= 0.0 and p['nmae'] <= 1.0) assert_true(nmae[1]['final_error']['avg']['nmae'] >= 0.0 and nmae[1]['final_error']['stdev']['nmae'] <= 1.0) #Test with IR statistics precision = evaluator.evaluate_on_split(recsys, 'precision', permutation=False) for p in precision[0]['ir']: assert_true(p['precision'] >= 0.0 and p['precision'] <= 1.0) assert_true(precision[1]['final_error']['avg']['precision'] >= 0.0 and precision[1]['final_error']['stdev']['precision'] <= 1.0) recall = evaluator.evaluate_on_split(recsys, 'recall', permutation=False) for p in recall[0]['ir']: assert_true(p['recall'] >= 0.0 and p['recall'] <= 1.0) assert_true(recall[1]['final_error']['avg']['recall'] >= 0.0 and recall[1]['final_error']['stdev']['recall'] <= 1.0) f1score = evaluator.evaluate_on_split(recsys, 'f1score', permutation=False) for p in f1score[0]['ir']: assert_true(p['f1score'] >= 0.0 and p['f1score'] <= 1.0) assert_true(f1score[1]['final_error']['avg']['f1score'] >= 0.0 and f1score[1]['final_error']['stdev']['f1score'] <= 1.0) all_scores = evaluator.evaluate_on_split(recsys, permutation=False) for p in all_scores[0]['ir']: assert_true(p['f1score'] >= 0.0 and p['f1score'] <= 1.0) assert_true(p['recall'] >= 0.0 and p['recall'] <= 1.0) assert_true(p['precision'] >= 0.0 and p['precision'] <= 1.0) for p in all_scores[0]['error']: assert_true(p['mae'] >= 0.0 and p['mae'] <= 1.0) assert_true(p['rmse'] >= 0.0 and p['rmse'] <= 1.0) assert_true(p['nmae'] >= 0.0 and p['nmae'] <= 1.0) assert_true(all_scores[1]['final_error']['avg']['f1score'] >= 0.0 and all_scores[1]['final_error']['stdev']['f1score'] <= 1.0) assert_true(all_scores[1]['final_error']['avg']['recall'] >= 0.0 and all_scores[1]['final_error']['stdev']['recall'] <= 1.0) assert_true(all_scores[1]['final_error']['avg']['precision'] >= 0.0 and all_scores[1]['final_error']['stdev']['precision'] <= 1.0) assert_true(all_scores[1]['final_error']['avg']['rmse'] >= 0.0 and all_scores[1]['final_error']['stdev']['rmse'] <= 1.0) assert_true(all_scores[1]['final_error']['avg']['mae'] >= 0.0 and all_scores[1]['final_error']['stdev']['mae'] <= 1.0) assert_true(all_scores[1]['final_error']['avg']['nmae'] >= 0.0 and all_scores[1]['final_error']['stdev']['nmae'] <= 1.0) #Test with boolean model #Test with invalid metric assert_raises(ValueError, evaluator.evaluate_on_split, boolean_recsys, 'rank') #Test with specified metric rmse = evaluator.evaluate_on_split(boolean_recsys, 'rmse', permutation=False) for p in rmse[0]['error']: assert_true(p['rmse'] >= 0.0 and p['rmse'] <= 1.0) assert_true(rmse[1]['final_error']['avg']['rmse'] >= 0.0 and rmse[1]['final_error']['stdev']['rmse'] <= 1.0) mae = evaluator.evaluate_on_split(boolean_recsys, 'mae', permutation=False) for p in mae[0]['error']: assert_true(p['mae'] >= 0.0 and p['mae'] <= 1.0) assert_true(mae[1]['final_error']['avg']['mae'] >= 0.0 and mae[1]['final_error']['stdev']['mae'] <= 1.0) nmae = evaluator.evaluate_on_split(boolean_recsys, 'nmae', permutation=False) for p in nmae[0]['error']: assert_true(p['nmae'] >= 0.0 and p['nmae'] <= 1.0) assert_true(nmae[1]['final_error']['avg']['nmae'] >= 0.0 and nmae[1]['final_error']['stdev']['nmae'] <= 1.0) #Test with IR statistics precision = evaluator.evaluate_on_split(boolean_recsys, 'precision', permutation=False) for p in precision[0]['ir']: assert_true(p['precision'] >= 0.0 and p['precision'] <= 1.0) assert_true(precision[1]['final_error']['avg']['precision'] >= 0.0 and precision[1]['final_error']['stdev']['precision'] <= 1.0) recall = evaluator.evaluate_on_split(boolean_recsys, 'recall', permutation=False) for p in recall[0]['ir']: assert_true(p['recall'] >= 0.0 and p['recall'] <= 1.0) assert_true(recall[1]['final_error']['avg']['recall'] >= 0.0 and recall[1]['final_error']['stdev']['recall'] <= 1.0) f1score = evaluator.evaluate_on_split(boolean_recsys, 'f1score', permutation=False) for p in f1score[0]['ir']: assert_true(p['f1score'] >= 0.0 and p['f1score'] <= 1.0) assert_true(f1score[1]['final_error']['avg']['f1score'] >= 0.0 and f1score[1]['final_error']['stdev']['f1score'] <= 1.0) all_scores = evaluator.evaluate_on_split(boolean_recsys, permutation=False) for p in all_scores[0]['ir']: assert_true(p['f1score'] >= 0.0 and p['f1score'] <= 1.0) assert_true(p['recall'] >= 0.0 and p['recall'] <= 1.0) assert_true(p['precision'] >= 0.0 and p['precision'] <= 1.0) for p in all_scores[0]['error']: assert_true(p['mae'] >= 0.0 and p['mae'] <= 1.0) assert_true(p['rmse'] >= 0.0 and p['rmse'] <= 1.0) assert_true(p['nmae'] >= 0.0 and p['nmae'] <= 1.0) assert_true(all_scores[1]['final_error']['avg']['f1score'] >= 0.0 and all_scores[1]['final_error']['stdev']['f1score'] <= 1.0) assert_true(all_scores[1]['final_error']['avg']['recall'] >= 0.0 and all_scores[1]['final_error']['stdev']['recall'] <= 1.0) assert_true(all_scores[1]['final_error']['avg']['precision'] >= 0.0 and all_scores[1]['final_error']['stdev']['precision'] <= 1.0) assert_true(all_scores[1]['final_error']['avg']['rmse'] >= 0.0 and all_scores[1]['final_error']['stdev']['rmse'] <= 1.0) assert_true(all_scores[1]['final_error']['avg']['mae'] >= 0.0 and all_scores[1]['final_error']['stdev']['mae'] <= 1.0) assert_true(all_scores[1]['final_error']['avg']['nmae'] >= 0.0 and all_scores[1]['final_error']['stdev']['nmae'] <= 1.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. # ============================================================================== """Simple, end-to-end, LeNet-5-like convolutional MNIST model example. This should achieve a test error of 0.7%. Please keep this model as simple and linear as possible, it is meant as a tutorial for simple convolutional models. Run with --self_test on the command line to execute a short self-test. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import gzip import os import sys import time import numpy from six.moves import urllib from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf SOURCE_URL = 'http://yann.lecun.com/exdb/mnist/' WORK_DIRECTORY = 'data' IMAGE_SIZE = 28 NUM_CHANNELS = 1 PIXEL_DEPTH = 255 NUM_LABELS = 10 VALIDATION_SIZE = 5000 # Size of the validation set. SEED = 66478 # Set to None for random seed. BATCH_SIZE = 64 NUM_EPOCHS = 10 EVAL_BATCH_SIZE = 64 EVAL_FREQUENCY = 100 # Number of steps between evaluations. tf.app.flags.DEFINE_boolean("self_test", False, "True if running a self test.") FLAGS = tf.app.flags.FLAGS def maybe_download(filename): """Download the data from Yann's website, unless it's already here.""" if not tf.gfile.Exists(WORK_DIRECTORY): tf.gfile.MakeDirs(WORK_DIRECTORY) filepath = os.path.join(WORK_DIRECTORY, filename) if not tf.gfile.Exists(filepath): filepath, _ = urllib.request.urlretrieve(SOURCE_URL + filename, filepath) with tf.gfile.GFile(filepath) as f: size = f.Size() print('Successfully downloaded', filename, size, 'bytes.') return filepath def extract_data(filename, num_images): """Extract the images into a 4D tensor [image index, y, x, channels]. Values are rescaled from [0, 255] down to [-0.5, 0.5]. """ print('Extracting', filename) with gzip.open(filename) as bytestream: bytestream.read(16) buf = bytestream.read(IMAGE_SIZE * IMAGE_SIZE * num_images) data = numpy.frombuffer(buf, dtype=numpy.uint8).astype(numpy.float32) data = (data - (PIXEL_DEPTH / 2.0)) / PIXEL_DEPTH data = data.reshape(num_images, IMAGE_SIZE, IMAGE_SIZE, 1) return data def extract_labels(filename, num_images): """Extract the labels into a vector of int64 label IDs.""" print('Extracting', filename) with gzip.open(filename) as bytestream: bytestream.read(8) buf = bytestream.read(1 * num_images) labels = numpy.frombuffer(buf, dtype=numpy.uint8).astype(numpy.int64) return labels def fake_data(num_images): """Generate a fake dataset that matches the dimensions of MNIST.""" data = numpy.ndarray( shape=(num_images, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS), dtype=numpy.float32) labels = numpy.zeros(shape=(num_images,), dtype=numpy.int64) for image in xrange(num_images): label = image % 2 data[image, :, :, 0] = label - 0.5 labels[image] = label return data, labels def error_rate(predictions, labels): """Return the error rate based on dense predictions and sparse labels.""" return 100.0 - ( 100.0 * numpy.sum(numpy.argmax(predictions, 1) == labels) / predictions.shape[0]) def main(argv=None): # pylint: disable=unused-argument if FLAGS.self_test: print('Running self-test.') train_data, train_labels = fake_data(256) validation_data, validation_labels = fake_data(EVAL_BATCH_SIZE) test_data, test_labels = fake_data(EVAL_BATCH_SIZE) num_epochs = 1 else: # Get the data. train_data_filename = maybe_download('train-images-idx3-ubyte.gz') train_labels_filename = maybe_download('train-labels-idx1-ubyte.gz') test_data_filename = maybe_download('t10k-images-idx3-ubyte.gz') test_labels_filename = maybe_download('t10k-labels-idx1-ubyte.gz') # Extract it into numpy arrays. train_data = extract_data(train_data_filename, 60000) train_labels = extract_labels(train_labels_filename, 60000) test_data = extract_data(test_data_filename, 10000) test_labels = extract_labels(test_labels_filename, 10000) # Generate a validation set. validation_data = train_data[:VALIDATION_SIZE, ...] validation_labels = train_labels[:VALIDATION_SIZE] train_data = train_data[VALIDATION_SIZE:, ...] train_labels = train_labels[VALIDATION_SIZE:] num_epochs = NUM_EPOCHS train_size = train_labels.shape[0] # This is where training samples and labels are fed to the graph. # These placeholder nodes will be fed a batch of training data at each # training step using the {feed_dict} argument to the Run() call below. train_data_node = tf.placeholder( tf.float32, shape=(BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS)) train_labels_node = tf.placeholder(tf.int64, shape=(BATCH_SIZE,)) eval_data = tf.placeholder( tf.float32, shape=(EVAL_BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS)) # The variables below hold all the trainable weights. They are passed an # initial value which will be assigned when we call: # {tf.initialize_all_variables().run()} conv1_weights = tf.Variable( tf.truncated_normal([5, 5, NUM_CHANNELS, 32], # 5x5 filter, depth 32. stddev=0.1, seed=SEED)) conv1_biases = tf.Variable(tf.zeros([32])) conv2_weights = tf.Variable( tf.truncated_normal([5, 5, 32, 64], stddev=0.1, seed=SEED)) conv2_biases = tf.Variable(tf.constant(0.1, shape=[64])) fc1_weights = tf.Variable( # fully connected, depth 512. tf.truncated_normal( [IMAGE_SIZE // 4 * IMAGE_SIZE // 4 * 64, 512], stddev=0.1, seed=SEED)) fc1_biases = tf.Variable(tf.constant(0.1, shape=[512])) fc2_weights = tf.Variable( tf.truncated_normal([512, NUM_LABELS], stddev=0.1, seed=SEED)) fc2_biases = tf.Variable(tf.constant(0.1, shape=[NUM_LABELS])) # We will replicate the model structure for the training subgraph, as well # as the evaluation subgraphs, while sharing the trainable parameters. def model(data, train=False): """The Model definition.""" # 2D convolution, with 'SAME' padding (i.e. the output feature map has # the same size as the input). Note that {strides} is a 4D array whose # shape matches the data layout: [image index, y, x, depth]. conv = tf.nn.conv2d(data, conv1_weights, strides=[1, 1, 1, 1], padding='SAME') # Bias and rectified linear non-linearity. relu = tf.nn.relu(tf.nn.bias_add(conv, conv1_biases)) # Max pooling. The kernel size spec {ksize} also follows the layout of # the data. Here we have a pooling window of 2, and a stride of 2. pool = tf.nn.max_pool(relu, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') conv = tf.nn.conv2d(pool, conv2_weights, strides=[1, 1, 1, 1], padding='SAME') relu = tf.nn.relu(tf.nn.bias_add(conv, conv2_biases)) pool = tf.nn.max_pool(relu, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') # Reshape the feature map cuboid into a 2D matrix to feed it to the # fully connected layers. pool_shape = pool.get_shape().as_list() reshape = tf.reshape( pool, [pool_shape[0], pool_shape[1] * pool_shape[2] * pool_shape[3]]) # Fully connected layer. Note that the '+' operation automatically # broadcasts the biases. hidden = tf.nn.relu(tf.matmul(reshape, fc1_weights) + fc1_biases) # Add a 50% dropout during training only. Dropout also scales # activations such that no rescaling is needed at evaluation time. if train: hidden = tf.nn.dropout(hidden, 0.5, seed=SEED) return tf.matmul(hidden, fc2_weights) + fc2_biases # Training computation: logits + cross-entropy loss. logits = model(train_data_node, True) loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits( logits, train_labels_node)) # L2 regularization for the fully connected parameters. regularizers = (tf.nn.l2_loss(fc1_weights) + tf.nn.l2_loss(fc1_biases) + tf.nn.l2_loss(fc2_weights) + tf.nn.l2_loss(fc2_biases)) # Add the regularization term to the loss. loss += 5e-4 * regularizers # Optimizer: set up a variable that's incremented once per batch and # controls the learning rate decay. batch = tf.Variable(0) # Decay once per epoch, using an exponential schedule starting at 0.01. learning_rate = tf.train.exponential_decay( 0.01, # Base learning rate. batch * BATCH_SIZE, # Current index into the dataset. train_size, # Decay step. 0.95, # Decay rate. staircase=True) # Use simple momentum for the optimization. optimizer = tf.train.MomentumOptimizer(learning_rate, 0.9).minimize(loss, global_step=batch) # Predictions for the current training minibatch. train_prediction = tf.nn.softmax(logits) # Predictions for the test and validation, which we'll compute less often. eval_prediction = tf.nn.softmax(model(eval_data)) # Small utility function to evaluate a dataset by feeding batches of data to # {eval_data} and pulling the results from {eval_predictions}. # Saves memory and enables this to run on smaller GPUs. def eval_in_batches(data, sess): """Get all predictions for a dataset by running it in small batches.""" size = data.shape[0] if size < EVAL_BATCH_SIZE: raise ValueError("batch size for evals larger than dataset: %d" % size) predictions = numpy.ndarray(shape=(size, NUM_LABELS), dtype=numpy.float32) for begin in xrange(0, size, EVAL_BATCH_SIZE): end = begin + EVAL_BATCH_SIZE if end <= size: predictions[begin:end, :] = sess.run( eval_prediction, feed_dict={eval_data: data[begin:end, ...]}) else: batch_predictions = sess.run( eval_prediction, feed_dict={eval_data: data[-EVAL_BATCH_SIZE:, ...]}) predictions[begin:, :] = batch_predictions[begin - size:, :] return predictions # Create a local session to run the training. start_time = time.time() with tf.Session() as sess: # Run all the initializers to prepare the trainable parameters. tf.initialize_all_variables().run() print('Initialized!') # Loop through training steps. for step in xrange(int(num_epochs * train_size) // BATCH_SIZE): # Compute the offset of the current minibatch in the data. # Note that we could use better randomization across epochs. offset = (step * BATCH_SIZE) % (train_size - BATCH_SIZE) batch_data = train_data[offset:(offset + BATCH_SIZE), ...] batch_labels = train_labels[offset:(offset + BATCH_SIZE)] # This dictionary maps the batch data (as a numpy array) to the # node in the graph it should be fed to. feed_dict = {train_data_node: batch_data, train_labels_node: batch_labels} # Run the graph and fetch some of the nodes. _, l, lr, predictions = sess.run( [optimizer, loss, learning_rate, train_prediction], feed_dict=feed_dict) if step % EVAL_FREQUENCY == 0: elapsed_time = time.time() - start_time start_time = time.time() print('Step %d (epoch %.2f), %.1f ms' % (step, float(step) * BATCH_SIZE / train_size, 1000 * elapsed_time / EVAL_FREQUENCY)) print('Minibatch loss: %.3f, learning rate: %.6f' % (l, lr)) print('Minibatch error: %.1f%%' % error_rate(predictions, batch_labels)) print('Validation error: %.1f%%' % error_rate( eval_in_batches(validation_data, sess), validation_labels)) sys.stdout.flush() # Finally print the result! test_error = error_rate(eval_in_batches(test_data, sess), test_labels) print('Test error: %.1f%%' % test_error) if FLAGS.self_test: print('test_error', test_error) assert test_error == 0.0, 'expected 0.0 test_error, got %.2f' % ( test_error,) if __name__ == '__main__': tf.app.run()
#!/usr/bin/env python # coding:utf-8 import urlparse import os import cgi import time import hashlib from xlog import getLogger xlog = getLogger("x_tunnel") import simple_http_server import global_var as g import proxy_session current_path = os.path.dirname(os.path.abspath(__file__)) root_path = os.path.abspath(os.path.join(current_path, os.pardir, os.pardir)) web_ui_path = os.path.join(current_path, os.path.pardir, "web_ui") class ControlHandler(simple_http_server.HttpServerHandler): def __init__(self, client_address, headers, command, path, rfile, wfile): self.client_address = client_address self.headers = headers self.command = command self.path = path self.rfile = rfile self.wfile = wfile def do_GET(self): path = urlparse.urlparse(self.path).path if path == "/log": return self.req_log_handler() elif path == "/debug": data = g.session.status() return self.send_response('text/html', data) elif path == "/info": return self.req_info_handler() elif path == "/get_history": return self.req_get_history_handler() else: xlog.warn('Control Req %s %s %s ', self.address_string(), self.command, self.path) def do_POST(self): xlog.debug('x-tunnel web_control %s %s %s ', self.address_string(), self.command, self.path) try: ctype, pdict = cgi.parse_header(self.headers.getheader('content-type')) if ctype == 'multipart/form-data': self.postvars = cgi.parse_multipart(self.rfile, pdict) elif ctype == 'application/x-www-form-urlencoded': length = int(self.headers.getheader('content-length')) self.postvars = urlparse.parse_qs(self.rfile.read(length), keep_blank_values=1) else: self.postvars = {} except: self.postvars = {} path = urlparse.urlparse(self.path).path if path == '/login': return self.req_login_handler() elif path == "/logout": return self.req_logout_handler() elif path == "/register": return self.req_login_handler() elif path == "/order": return self.req_order_handler() elif path == "/transfer": return self.req_transfer_handler() else: xlog.info('%s "%s %s HTTP/1.1" 404 -', self.address_string(), self.command, self.path) return self.send_not_found() def req_log_handler(self): req = urlparse.urlparse(self.path).query reqs = urlparse.parse_qs(req, keep_blank_values=True) data = '' if reqs["cmd"]: cmd = reqs["cmd"][0] else: cmd = "get_last" if cmd == "set_buffer_size": if not reqs["buffer_size"]: data = '{"res":"fail", "reason":"size not set"}' mimetype = 'text/plain' self.send_response(mimetype, data) return buffer_size = reqs["buffer_size"][0] xlog.set_buffer_size(buffer_size) elif cmd == "get_last": max_line = int(reqs["max_line"][0]) data = xlog.get_last_lines(max_line) elif cmd == "get_new": last_no = int(reqs["last_no"][0]) data = xlog.get_new_lines(last_no) else: xlog.error('xtunnel log cmd:%s', cmd) mimetype = 'text/plain' self.send_response(mimetype, data) def req_info_handler(self): if len(g.config.login_account) == 0 or len(g.config.login_password) == 0: return self.response_json({ "res": "logout" }) req = urlparse.urlparse(self.path).query reqs = urlparse.parse_qs(req, keep_blank_values=True) force = False if 'force' in reqs: force = 1 time_now = time.time() if force or time_now - g.last_refresh_time > 3600 or \ (g.last_api_error.startswith("status:") and (time_now - g.last_refresh_time > 30)): xlog.debug("x_tunnel force update info") g.last_refresh_time = time_now if g.session.running: update_server = False else: update_server = True res, reason = proxy_session.request_balance( g.config.login_account, g.config.login_password, is_register=False, update_server=update_server) if res: if g.quota and not g.session.running: g.session.start() if len(g.last_api_error) and g.last_api_error != 'balance not enough': res_arr = { "res": "fail", "login_account": "%s" % (g.config.login_account), "reason": g.last_api_error } else: res_arr = { "res": "success", "login_account": "%s" % (g.config.login_account), "balance": "%f" % (g.balance), "quota": "%d" % (g.quota), "quota_list": g.quota_list, "traffic": g.session.traffic, "last_fail": g.last_api_error } self.response_json(res_arr) def req_login_handler(self): def check_email(email): import re if not re.match(r"[^@]+@[^@]+\.[^@]+", email): return False else: return True username = str(self.postvars['username'][0]) password = str(self.postvars['password'][0]) is_register = int(self.postvars['is_register'][0]) pa = check_email(username) if not pa: return self.response_json({ "res": "fail", "reason": "Invalid email." }) elif len(password) < 6: return self.response_json({ "res": "fail", "reason": "Password needs at least 6 charactors." }) password_hash = str(hashlib.sha256(password).hexdigest()) res, reason = proxy_session.request_balance(username, password_hash, is_register, update_server=True) if res: g.config.login_account = username g.config.login_password = password_hash g.config.save() res_arr = { "res": "success", "balance": float(g.balance) } g.last_refresh_time = time.time() g.session.start() else: res_arr = { "res": "fail", "reason": reason } return self.response_json(res_arr) def req_logout_handler(self): g.config.login_account = "" g.config.login_password = "" g.config.save() g.session.stop() return self.response_json({"res": "success"}) def req_order_handler(self): product = self.postvars['product'][0] if product != 'x_tunnel': xlog.warn("x_tunnel order product %s not support", product) return self.response_json({ "res": "fail", "reason": "product %s not support" % product }) plan = self.postvars['plan'][0] if plan not in ["quarterly", "yearly"]: xlog.warn("x_tunnel order plan %s not support", plan) return self.response_json({ "res": "fail", "reason": "plan %s not support" % plan }) res, info = proxy_session.call_api("order", { "account": g.config.login_account, "password": g.config.login_password, "product": "x_tunnel", "plan": plan }) if not res: xlog.warn("order fail:%s", info) return self.response_json({"res": "fail", "reason": info}) self.response_json({"res": "success"}) def req_transfer_handler(self): to_account = self.postvars['to_account'][0] amount = float(self.postvars['amount'][0]) transfer_type = self.postvars['transfer_type'][0] if transfer_type == 'balance': if amount > g.balance: reason = "balance not enough" xlog.warn("transfer fail:%s", reason) return self.response_json({"res": "fail", "reason": reason}) end_time = 0 elif transfer_type == "quota": end_time = int(self.postvars['end_time'][0]) else: reason = "transfer type not support:%s" % transfer_type xlog.warn("transfer fail:%s", reason) return self.response_json({"res": "fail", "reason": reason}) req_info = { "account": g.config.login_account, "password": g.config.login_password, "transfer_type": transfer_type, "end_time": end_time, "to_account": to_account, "amount": amount } res, info = proxy_session.call_api("transfer", req_info) if not res: xlog.warn("transfer fail:%s", info) return self.response_json({ "res": "fail", "reason": info }) self.response_json({"res": "success"}) def req_get_history_handler(self): req = urlparse.urlparse(self.path).query reqs = urlparse.parse_qs(req, keep_blank_values=True) req_info = { "account": g.config.login_account, "password": g.config.login_password, "start": int(reqs['start'][0]), "end": int(reqs['end'][0]), "limit": int(reqs['limit'][0]) } res, info = proxy_session.call_api("get_history", req_info) if not res: xlog.warn("get history fail:%s", info) return self.response_json({ "res": "fail", "reason": info }) self.response_json({ "res": "success", "history": info["history"] })
#!/usr/bin/env python # # Copyright 2009 Facebook # # 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. """HTTP utility code shared by clients and servers.""" import logging import urllib.request, urllib.parse, urllib.error import re from tornado.util import b, ObjectDict class HTTPHeaders(dict): """A dictionary that maintains Http-Header-Case for all keys. Supports multiple values per key via a pair of new methods, add() and get_list(). The regular dictionary interface returns a single value per key, with multiple values joined by a comma. >>> h = HTTPHeaders({"content-type": "text/html"}) >>> list(h.keys()) ['Content-Type'] >>> h["Content-Type"] 'text/html' >>> h.add("Set-Cookie", "A=B") >>> h.add("Set-Cookie", "C=D") >>> h["set-cookie"] 'A=B,C=D' >>> h.get_list("set-cookie") ['A=B', 'C=D'] >>> for (k,v) in sorted(h.get_all()): ... print('%s: %s' % (k,v)) ... Content-Type: text/html Set-Cookie: A=B Set-Cookie: C=D """ def __init__(self, *args, **kwargs): # Don't pass args or kwargs to dict.__init__, as it will bypass # our __setitem__ dict.__init__(self) self._as_list = {} self._last_key = None self.update(*args, **kwargs) # new public methods def add(self, name, value): """Adds a new value for the given key.""" norm_name = HTTPHeaders._normalize_name(name) self._last_key = norm_name if norm_name in self: # bypass our override of __setitem__ since it modifies _as_list dict.__setitem__(self, norm_name, self[norm_name] + ',' + value) self._as_list[norm_name].append(value) else: self[norm_name] = value def get_list(self, name): """Returns all values for the given header as a list.""" norm_name = HTTPHeaders._normalize_name(name) return self._as_list.get(norm_name, []) def get_all(self): """Returns an iterable of all (name, value) pairs. If a header has multiple values, multiple pairs will be returned with the same name. """ for name, list in self._as_list.items(): for value in list: yield (name, value) def parse_line(self, line): """Updates the dictionary with a single header line. >>> h = HTTPHeaders() >>> h.parse_line("Content-Type: text/html") >>> h.get('content-type') 'text/html' """ if line[0].isspace(): # continuation of a multi-line header new_part = ' ' + line.lstrip() self._as_list[self._last_key][-1] += new_part dict.__setitem__(self, self._last_key, self[self._last_key] + new_part) else: name, value = line.split(":", 1) self.add(name, value.strip()) @classmethod def parse(cls, headers): """Returns a dictionary from HTTP header text. >>> h = HTTPHeaders.parse("Content-Type: text/html\\r\\nContent-Length: 42\\r\\n") >>> sorted(h.items()) [('Content-Length', '42'), ('Content-Type', 'text/html')] """ h = cls() for line in headers.splitlines(): if line: h.parse_line(line) return h # dict implementation overrides def __setitem__(self, name, value): norm_name = HTTPHeaders._normalize_name(name) dict.__setitem__(self, norm_name, value) self._as_list[norm_name] = [value] def __getitem__(self, name): return dict.__getitem__(self, HTTPHeaders._normalize_name(name)) def __delitem__(self, name): norm_name = HTTPHeaders._normalize_name(name) dict.__delitem__(self, norm_name) del self._as_list[norm_name] def __contains__(self, name): norm_name = HTTPHeaders._normalize_name(name) return dict.__contains__(self, norm_name) def get(self, name, default=None): return dict.get(self, HTTPHeaders._normalize_name(name), default) def update(self, *args, **kwargs): # dict.update bypasses our __setitem__ for k, v in dict(*args, **kwargs).items(): self[k] = v _NORMALIZED_HEADER_RE = re.compile(r'^[A-Z0-9][a-z0-9]*(-[A-Z0-9][a-z0-9]*)*$') _normalized_headers = {} @staticmethod def _normalize_name(name): """Converts a name to Http-Header-Case. >>> HTTPHeaders._normalize_name("coNtent-TYPE") 'Content-Type' """ try: return HTTPHeaders._normalized_headers[name] except KeyError: if HTTPHeaders._NORMALIZED_HEADER_RE.match(name): normalized = name else: normalized = "-".join([w.capitalize() for w in name.split("-")]) HTTPHeaders._normalized_headers[name] = normalized return normalized def url_concat(url, args): """Concatenate url and argument dictionary regardless of whether url has existing query parameters. >>> url_concat("http://example.com/foo?a=b", dict(c="d")) 'http://example.com/foo?a=b&c=d' """ if not args: return url if url[-1] not in ('?', '&'): url += '&' if ('?' in url) else '?' return url + urllib.parse.urlencode(args) class HTTPFile(ObjectDict): """Represents an HTTP file. For backwards compatibility, its instance attributes are also accessible as dictionary keys. :ivar filename: :ivar body: :ivar content_type: The content_type comes from the provided HTTP header and should not be trusted outright given that it can be easily forged. """ pass def parse_multipart_form_data(boundary, data, arguments, files): """Parses a multipart/form-data body. The boundary and data parameters are both byte strings. The dictionaries given in the arguments and files parameters will be updated with the contents of the body. """ # The standard allows for the boundary to be quoted in the header, # although it's rare (it happens at least for google app engine # xmpp). I think we're also supposed to handle backslash-escapes # here but I'll save that until we see a client that uses them # in the wild. if boundary.startswith(b('"')) and boundary.endswith(b('"')): boundary = boundary[1:-1] if data.endswith(b("\r\n")): footer_length = len(boundary) + 6 else: footer_length = len(boundary) + 4 parts = data[:-footer_length].split(b("--") + boundary + b("\r\n")) for part in parts: if not part: continue eoh = part.find(b("\r\n\r\n")) if eoh == -1: logging.warning("multipart/form-data missing headers") continue headers = HTTPHeaders.parse(part[:eoh].decode("utf-8")) disp_header = headers.get("Content-Disposition", "") disposition, disp_params = _parse_header(disp_header) if disposition != "form-data" or not part.endswith(b("\r\n")): logging.warning("Invalid multipart/form-data") continue value = part[eoh + 4:-2] if not disp_params.get("name"): logging.warning("multipart/form-data value missing name") continue name = disp_params["name"] if disp_params.get("filename"): ctype = headers.get("Content-Type", "application/unknown") files.setdefault(name, []).append(HTTPFile( filename=disp_params["filename"], body=value, content_type=ctype)) else: arguments.setdefault(name, []).append(value) # _parseparam and _parse_header are copied and modified from python2.7's cgi.py # The original 2.7 version of this code did not correctly support some # combinations of semicolons and double quotes. def _parseparam(s): while s[:1] == ';': s = s[1:] end = s.find(';') while end > 0 and (s.count('"', 0, end) - s.count('\\"', 0, end)) % 2: end = s.find(';', end + 1) if end < 0: end = len(s) f = s[:end] yield f.strip() s = s[end:] def _parse_header(line): """Parse a Content-type like header. Return the main content-type and a dictionary of options. """ parts = _parseparam(';' + line) key = next(parts) pdict = {} for p in parts: i = p.find('=') if i >= 0: name = p[:i].strip().lower() value = p[i+1:].strip() if len(value) >= 2 and value[0] == value[-1] == '"': value = value[1:-1] value = value.replace('\\\\', '\\').replace('\\"', '"') pdict[name] = value return key, pdict def doctests(): import doctest return doctest.DocTestSuite() if __name__ == "__main__": import doctest doctest.testmod()
from UnitTest import UnitTest from ClassTest import PassMeAClass from ClassTest import ExampleChildClass from ClassTest import ExampleMultiSuperclassParent1 import Factory2 import imports.decors # must be in this form class Handler: def __init__(self, x): self._x = x def handle(self, y): return self._x is y def aProcedure(): x = 1 if x is 2: # a return statement which is not reached return "something" #this is a comment def aFunctionWithOnlyDoc(): """Only a doc string""" def aFunctionReturningNone(): return None def aFunctionReturningParam(param): return param def aFunctionReturningFunction(): return aFunctionReturningParam def aFunctionReturningGlobalX1(): return x def aFunctionReturningGlobalX2(): return x def aFunctionReturningGlobalX3(): a = x return a def aFunctionReturningLocalX(): x = 'local test' return x def aFunctionReturningArgX(x): return x x = 'global test' name = 'mapping-test' def call(default, arguments, this): return (name, default, arguments, this) def functionDefaults(s = "", l = []): n = len(l) s = s + "%d" % n l.append(n) return s, l class FunctionTest(UnitTest): def testLambda(self): f = lambda x: x self.assertEqual(f(1), 1) f = lambda x=1: x self.assertEqual(f(), 1) self.assertEqual(f(2), 2) f = lambda x, y: x*y self.assertEqual(f(2,3), 6) f = lambda x, y=4: x*y self.assertEqual(f(2), 8) h = Handler(5) f = lambda x: h.handle(x) self.assertTrue(f(5)) self.assertFalse(f(4)) f = lambda a, b=1, **kw: (a,b,kw) v = f(b = 2, c = 3, a = 1) self.assertEqual(v[0], 1) self.assertEqual(v[1], 2) self.assertEqual(v[2]['c'], 3) f = lambda a, b=1, *args: (a, b, args) v = f(1,2,3,4) self.assertEqual(v[2][0], 3) self.assertEqual(v[2][1], 4) def testProcedure(self): self.assertTrue(aFunctionReturningNone() is None, "Function should return None") self.assertTrue(aProcedure() is None, "Procedures should always return None") def testVariableFunction(self): self.assertEqual((aFunctionReturningParam)("foo"), "foo") self.assertEqual(aFunctionReturningFunction()("foo"), "foo") def testLookup(self): expected_result1 = 'global test' expected_result2 = 'local test' self.assertEqual(aFunctionReturningGlobalX1(), expected_result1) self.assertEqual(aFunctionReturningGlobalX2(), expected_result1) self.assertEqual(aFunctionReturningGlobalX3(), expected_result1) self.assertEqual(aFunctionReturningLocalX(), expected_result2) self.assertEqual(aFunctionReturningArgX('test'), 'test') def testNameMapping(self): r = call(1, 2, 3) self.assertEqual(r[0], 'mapping-test') self.assertEqual(r[1], 1) self.assertEqual(r[2], 2) self.assertEqual(r[3], 3) def testFactory(self): Factory2.gregister("passme", PassMeAClass) Factory2.gregister("exchild", ExampleChildClass) Factory2.gregister("mscp1", ExampleMultiSuperclassParent1) pmc = Factory2.ggetObject("passme") self.assertEqual(pmc.foo(), "foo in PassMeAClass") try: pmc = Factory2.ggetObject("mscp1", 5) except: self.assertEqual(False, True, "Exception indicates bug in compiler: 'Error: uncaught exception: ExampleMultiSuperclassParent1() arguments after ** must be a dictionary 5'") else: self.assertEqual(pmc.x, 5) try: pmc = Factory2.ggetObject("exchild", 5, 7) # 5 is ignored except: self.assertEqual(False, True, "Exception indicates bug in compiler: 'Error: uncaught exception: ExampleChildClass() arguments after ** must be a dictionary 7'") else: self.assertEqual(pmc.prop_a, 1) self.assertEqual(pmc.prop_b, 7) def testSliceFunc(self): s = "123 " s = s[1:].rstrip() self.assertEqual(s, "23") def testFunctionDefaults(self): s, l = functionDefaults() self.assertEqual(s, '0') self.assertTrue(l == [0], "First mutable default mismatch") s, l = functionDefaults() #self.assertEqual(s, '1') # can be enabled when the next line is fixed self.assertTrue(l == [0, 1], "Second mutable default mismatch bug #214") inittest = 1 def f(inittest = inittest): return inittest self.assertEqual(f(), inittest) def testKwargs(self): def f(**kwargs): return kwargs self.assertEqual(f(), {}) self.assertEqual(f(a=1), dict(a=1)) def testFunctionDecorating(self): log = [] def deco1(f): def fn(*args, **kwargs): log.append("deco1 begin") res = f(*args, **kwargs) log.append("deco1 end") return res return fn def deco2(f): def fn(*args, **kwargs): log.append("deco2 begin") res = f(*args, **kwargs) log.append("deco2 end") return res return fn @deco1 def fn1(a, b = 0): return a, b @deco1 @deco2 def fn2(a, b = 0): return a, b res = fn1(1,2) self.assertEqual(res[0], 1) self.assertEqual(res[1], 2) self.assertEqual(len(log), 2) self.assertEqual(log[0], "deco1 begin") self.assertEqual(log[1], "deco1 end") log = [] res = fn2(a=3) self.assertEqual(res[0], 3) self.assertEqual(res[1], 0) self.assertEqual(len(log), 4) self.assertEqual(log[0], "deco1 begin") self.assertEqual(log[1], "deco2 begin") self.assertEqual(log[2], "deco2 end") self.assertEqual(log[3], "deco1 end") @imports.decors.othermoduledeco1 def fn3(x): return "b" self.assertEqual(fn3("b"), "abc") def testTopLevelContionalFunction(self): self.assertEqual(imports.conditional_func(), "overridden")
""" Test of the classical LM model for language modelling """ from groundhog.datasets import LMIterator from groundhog.trainer.SGD_momentum import SGD as SGD_m from groundhog.trainer.SGD import SGD from groundhog.mainLoop import MainLoop from groundhog.layers import MultiLayer, \ RecurrentMultiLayer, \ RecurrentMultiLayerInp, \ RecurrentMultiLayerShortPath, \ RecurrentMultiLayerShortPathInp, \ RecurrentMultiLayerShortPathInpAll, \ SoftmaxLayer, \ LastState,\ UnaryOp, \ DropOp, \ Operator, \ Shift, \ GaussianNoise, \ SigmoidLayer from groundhog.layers import maxpool, \ maxpool_ntimes, \ last, \ last_ntimes,\ tanh, \ sigmoid, \ rectifier,\ hard_sigmoid, \ hard_tanh from groundhog.models import LM_Model from theano.sandbox.scan import scan import numpy import theano import theano.tensor as TT linear = lambda x:x rect = lambda x:TT.maximum(0., x) theano.config.allow_gc = False def get_text_data(state): def out_format (x, y, r): return {'x':x, 'y' :y, 'reset': r} def out_format_valid (x, y, r): return {'x':x, 'y' :y, 'reset': r} train_data = LMIterator( batch_size=state['bs'], path = state['path'], stop=-1, seq_len = state['seqlen'], mode="train", chunks=state['chunks'], shift = state['shift'], output_format = out_format, can_fit=True) valid_data = LMIterator( batch_size=state['bs'], path=state['path'], stop=-1, use_infinite_loop=False, allow_short_sequences = True, seq_len= state['seqlen'], mode="valid", reset =state['reset'], chunks=state['chunks'], shift = state['shift'], output_format = out_format_valid, can_fit=True) test_data = LMIterator( batch_size=state['bs'], path = state['path'], stop=-1, use_infinite_loop=False, allow_short_sequences=True, seq_len= state['seqlen'], mode="test", chunks=state['chunks'], shift = state['shift'], output_format = out_format_valid, can_fit=True) if 'wiki' in state['path']: test_data = None return train_data, valid_data, test_data def jobman(state, channel): # load dataset rng = numpy.random.RandomState(state['seed']) # declare the dimensionalies of the input and output if state['chunks'] == 'words': state['n_in'] = 10000 state['n_out'] = 10000 else: state['n_in'] = 50 state['n_out'] = 50 train_data, valid_data, test_data = get_text_data(state) ## BEGIN Tutorial ### Define Theano Input Variables x = TT.lvector('x') y = TT.lvector('y') h0 = theano.shared(numpy.zeros((eval(state['nhids'])[-1],), dtype='float32')) ### Neural Implementation of the Operators: \oplus #### Word Embedding emb_words = MultiLayer( rng, n_in=state['n_in'], n_hids=eval(state['inp_nhids']), activation=eval(state['inp_activ']), init_fn='sample_weights_classic', weight_noise=state['weight_noise'], rank_n_approx = state['rank_n_approx'], scale=state['inp_scale'], sparsity=state['inp_sparse'], learn_bias = True, bias_scale=eval(state['inp_bias']), name='emb_words') #### Deep Transition Recurrent Layer rec = eval(state['rec_layer'])( rng, eval(state['nhids']), activation = eval(state['rec_activ']), #activation = 'TT.nnet.sigmoid', bias_scale = eval(state['rec_bias']), scale=eval(state['rec_scale']), sparsity=eval(state['rec_sparse']), init_fn=eval(state['rec_init']), weight_noise=state['weight_noise'], name='rec') #### Stiching them together ##### (1) Get the embedding of a word x_emb = emb_words(x, no_noise_bias=state['no_noise_bias']) ##### (2) Embedding + Hidden State via DT Recurrent Layer reset = TT.scalar('reset') rec_layer = rec(x_emb, n_steps=x.shape[0], init_state=h0*reset, no_noise_bias=state['no_noise_bias'], truncate_gradient=state['truncate_gradient'], batch_size=1) ## BEGIN Exercise: DOT-RNN ### Neural Implementation of the Operators: \lhd #### Exercise (1) #### TODO: Define a layer from the hidden state to the intermediate layer #### Exercise (1) #### TODO: Define a layer from the input to the intermediate Layer #### Hidden State: Combine emb_state and emb_words_out #### Exercise (1) #### TODO: Define an activation layer #### Exercise (2) #### TODO: Define a dropout layer #### Softmax Layer output_layer = SoftmaxLayer( rng, eval(state['dout_nhid']), state['n_out'], scale=state['out_scale'], bias_scale=state['out_bias_scale'], init_fn="sample_weights_classic", weight_noise=state['weight_noise'], sparsity=state['out_sparse'], sum_over_time=True, name='out') ### Few Optional Things #### Direct shortcut from x to y if state['shortcut_inpout']: shortcut = MultiLayer( rng, n_in=state['n_in'], n_hids=eval(state['inpout_nhids']), activations=eval(state['inpout_activ']), init_fn='sample_weights_classic', weight_noise = state['weight_noise'], scale=eval(state['inpout_scale']), sparsity=eval(state['inpout_sparse']), learn_bias=eval(state['inpout_learn_bias']), bias_scale=eval(state['inpout_bias']), name='shortcut') #### Learning rate scheduling (1/(1+n/beta)) state['clr'] = state['lr'] def update_lr(obj, cost): stp = obj.step if isinstance(obj.state['lr_start'], int) and stp > obj.state['lr_start']: time = float(stp - obj.state['lr_start']) new_lr = obj.state['clr']/(1+time/obj.state['lr_beta']) obj.lr = new_lr if state['lr_adapt']: rec.add_schedule(update_lr) ### Neural Implementations of the Language Model #### Training if state['shortcut_inpout']: additional_inputs = [rec_layer, shortcut(x)] else: additional_inputs = [rec_layer] ##### Exercise (1): Compute the output intermediate layer ##### TODO: Compute the output intermediate layer ##### Exercise (2): Apply Dropout ##### TODO: Apply the dropout layer train_model = output_layer(outhid, no_noise_bias=state['no_noise_bias'], additional_inputs=additional_inputs).train(target=y, scale=numpy.float32(1./state['seqlen'])) nw_h0 = rec_layer.out[rec_layer.out.shape[0]-1] if state['carry_h0']: train_model.updates += [(h0, nw_h0)] #### Validation h0val = theano.shared(numpy.zeros((eval(state['nhids'])[-1],), dtype='float32')) rec_layer = rec(emb_words(x, use_noise=False), n_steps = x.shape[0], batch_size=1, init_state=h0val*reset, use_noise=False) nw_h0 = rec_layer.out[rec_layer.out.shape[0]-1] ##### Exercise (1): ##### TODO: Compute the output intermediate layer ##### Exercise (2): Apply Dropout ##### TODO: Apply the dropout layer without noise if state['shortcut_inpout']: additional_inputs=[rec_layer, shortcut(x, use_noise=False)] else: additional_inputs=[rec_layer] valid_model = output_layer(outhid, additional_inputs=additional_inputs, use_noise=False).validate(target=y, sum_over_time=True) valid_updates = [] if state['carry_h0']: valid_updates = [(h0val, nw_h0)] valid_fn = theano.function([x,y, reset], valid_model.cost, name='valid_fn', updates=valid_updates) #### Sampling ##### single-step sampling def sample_fn(word_tm1, h_tm1): x_emb = emb_words(word_tm1, use_noise = False, one_step=True) h0 = rec(x_emb, state_before=h_tm1, one_step=True, use_noise=False)[-1] outhid = outhid_dropout(outhid_activ(emb_state(h0, use_noise=False, one_step=True) + emb_words_out(word_tm1, use_noise=False, one_step=True), one_step=True), use_noise=False, one_step=True) word = output_layer.get_sample(state_below=outhid, additional_inputs=[h0], temp=1.) return word, h0 ##### scan for iterating the single-step sampling multiple times [samples, summaries], updates = scan(sample_fn, states = [ TT.alloc(numpy.int64(0), state['sample_steps']), TT.alloc(numpy.float32(0), 1, eval(state['nhids'])[-1])], n_steps= state['sample_steps'], name='sampler_scan') ##### build a Theano function for sampling sample_fn = theano.function([], [samples], updates=updates, profile=False, name='sample_fn') ##### Load a dictionary dictionary = numpy.load(state['dictionary']) if state['chunks'] == 'chars': dictionary = dictionary['unique_chars'] else: dictionary = dictionary['unique_words'] def hook_fn(): sample = sample_fn()[0] print 'Sample:', if state['chunks'] == 'chars': print "".join(dictionary[sample]) else: for si in sample: print dictionary[si], print ### Build and Train a Model #### Define a model model = LM_Model( cost_layer = train_model, weight_noise_amount=state['weight_noise_amount'], valid_fn = valid_fn, clean_before_noise_fn = False, noise_fn = None, rng = rng) if state['reload']: model.load(state['prefix']+'model.npz') #### Define a trainer ##### Training algorithm (SGD) if state['moment'] < 0: algo = SGD(model, state, train_data) else: algo = SGD_m(model, state, train_data) ##### Main loop of the trainer main = MainLoop(train_data, valid_data, test_data, model, algo, state, channel, train_cost = False, hooks = hook_fn, validate_postprocess = eval(state['validate_postprocess'])) ## Run! main.main() if __name__=='__main__': state = {} # complete path to data (cluster specific) state['seqlen'] = 100 state['path']= "/Users/KyunghyunCho/GroundHog/data/pentree_char_and_word.npz" state['dictionary']= "/Users/KyunghyunCho/GroundHog/data/dictionaries.npz" state['chunks'] = 'chars' state['seed'] = 123 # flag .. don't need to change it. It says what to do if you get cost to # be nan .. you could raise, though I would leave it to this state['on_nan'] = 'warn' # DATA # For wikipedia validation set is extremely large. Is very time # wasteful. This value is only used for validation set, and IMHO should # be something like seqlen * 10000 (i.e. the validation should be only # 10000 steps state['reset'] = -1 # For music/ word level I think 50 is a good idea. For character this # should be at least 100 (I think there are problems with getting state # of the art otherwise). Note most people use 200 ! # The job stops when learning rate declines to this value. It can be # useful, because sometimes is hopeless to wait for validation error to # get below minerr, or for the time to expire state['minlr'] = float(5e-7) # Layers # Input # Input weights are sampled from a gaussian with std=scale; this is the # standard way to initialize state['rank_n_approx'] = 0 state['inp_nhids'] = '[200]' state['inp_activ'] = '[linear]' state['inp_bias'] = '[0.]' state['inp_sparse']= -1 # dense state['inp_scale'] = .1 # This is for the output weights state['out_scale'] = .1 state['out_bias_scale'] = -.5 state['out_sparse'] = -1 state['dout_nhid'] = '200' state['dout_activ'] = '"TT.nnet.sigmoid"' state['dout_sparse']= 20 state['dout_scale'] = 1. state['dout_bias'] = '[0]' state['dout_init'] = "'sample_weights'" state['dout_rank_n_approx'] = 0 state['dropout'] = .5 # HidLayer # Hidden units on for the internal layers of DT-RNN. Having a single # value results in a standard RNN state['nhids'] = '[100, 100]' # Activation of each layer state['rec_activ'] = '"TT.nnet.sigmoid"' state['rec_bias'] = '.0' state['rec_sparse'] ='20' state['rec_scale'] = '1.' # sample_weights - you rescale the weights such that the largest # singular value is scale # sample_weights_classic : just sample weights from a gaussian with std # equal to scale state['rec_init'] = "'sample_weights'" state['rec_layer'] = 'RecurrentMultiLayerShortPathInpAll' # SGD params state['bs'] = 1 # the size of the minibatch state['lr'] = 1. # initial learning rate state['cutoff'] = 1. # threshold for gradient rescaling state['moment'] = 0.995 #-.1 # momentum # Do not optimize these state['weight_noise'] = True # white Gaussian noise in weights state['weight_noise_amount'] = 0.075 # standard deviation # maximal number of updates state['loopIters'] = int(1e8) # maximal number of minutes to wait until killing job state['timeStop'] = 48*60 # 48 hours # Construct linear connections from input to output. These are factored # (like the rank_n) to deal with the possible high dimensionality of the # input, but it is a linear projection that feeds into the softmax state['shortcut_inpout'] = False state['shortcut_rank'] = 200 # Main Loop # Make this to be a decently large value. Otherwise you waste a lot of # memory keeping track of the training error (and other things) at each # step + the stdout becomes extremely large state['trainFreq'] = 100 state['hookFreq'] = 5000 state['validFreq'] = 1000 state['saveFreq'] = 15 # save every 15 minutes state['prefix'] = 'model_' # prefix of the save files state['reload'] = False # reload state['overwrite'] = 1 # Threhold should be 1.004 for PPL, for entropy (which is what # everything returns, it should be much smaller. Running value is 1.0002 # We should not hyperoptimize this state['divide_lr'] = 2. state['cost_threshold'] = 1.0002 state['patience'] = 1 state['validate_postprocess'] = 'lambda x:10**(x/numpy.log(10))' state['truncate_gradient'] = 80 # truncated BPTT state['lr_adapt'] = 0 # 1/(1 + n/n0) scheduling state['lr_beta'] = 10*1900. state['lr_start'] = 'on_error' state['no_noise_bias'] = True # do not use weight noise for biases state['carry_h0'] = True # carry over h0 across updates state['sample_steps'] = 80 # Do not change these state['minerr'] = -1 state['shift'] = 1 # n-step forward prediction state['cutoff_rescale_length'] = False jobman(state, None)
""" SocketIO-based rcstream client. (c) 2014 Merlijn van Deen This file is part of the Pywikibot framework, and is licensed under the MIT license. This module requires socketIO_client to be installed: pip install socketIO_client """ from __future__ import unicode_literals import sys import threading if sys.version_info[0] > 2: from queue import Queue, Empty else: from Queue import Queue, Empty from pywikibot.bot import debug, warning _logger = 'pywikibot.rcstream' class RcListenerThread(threading.Thread): """ Low-level RC Listener Thread, which reads the RC stream and pushes them to it's internal queue. @param wikihost: the hostname of the wiki we want to get changes for. This is passed to rcstream using a 'subscribe' command. Pass '*' to listen to all wikis for a given rc host. @param rchost: the recent changes stream host to connect to. For Wikimedia wikis, this is 'stream.wikimedia.org' @param rcport: the port to connect to (default: 80) @param rcpath: the sockets.io path. For Wikimedia wikis, this is '/rc'. (default: '/rc') @param total: the maximum number of entries to return. The underlying thread is shut down then this number is reached. This part of the rc listener runs in a Thread. It makes the actual socketIO/websockets connection to the rc stream server, subscribes to a single site and pushes those entries into a queue. Usage: >>> t = RcListenerThread('en.wikipedia.org', 'stream.wikimedia.org') >>> t.start() >>> change = t.queue.get() >>> change {'server_name': 'en.wikipedia.org', 'wiki': 'enwiki', 'minor': True, 'length': {'new': 2038, 'old': 2009}, 'timestamp': 1419964350, 'server_script_path': '/w', 'bot': False, 'user': 'Od Mishehu', 'comment': 'stub sorting', 'title': 'Bradwell Bay Wilderness', 'server_url': 'http://en.wikipedia.org', 'id': 703158386, 'revision': {'new': 640271171, 'old': 468264850}, 'type': 'edit', 'namespace': 0} >>> t.stop() # optional, the thread will shut down on exiting python as well """ def __init__(self, wikihost, rchost, rcport=80, rcpath='/rc', total=None): """Constructor for RcListenerThread.""" super(RcListenerThread, self).__init__() self.rchost = rchost self.rcport = rcport self.rcpath = rcpath self.wikihost = wikihost self.daemon = True self.running = False self.queue = Queue() self.warn_queue_length = 100 self.total = total self.count = 0 import socketIO_client debug('Opening connection to %r' % self, _logger) self.client = socketIO_client.SocketIO(rchost, rcport) thread = self class RCListener(socketIO_client.BaseNamespace): def on_change(self, change): debug('Received change %r' % change, _logger) if not thread.running: debug('Thread in shutdown mode; ignoring change.', _logger) return thread.count += 1 thread.queue.put(change) if thread.queue.qsize() > thread.warn_queue_length: warning('%r queue length exceeded %i' % (thread, thread.warn_queue_length), _logger=_logger) thread.warn_queue_length = thread.warn_queue_length + 100 if thread.total is not None and thread.count >= thread.total: thread.stop() return def on_connect(self): debug('Connected to %r; subscribing to %s' % (thread, thread.wikihost), _logger) self.emit('subscribe', thread.wikihost) debug('Subscribed to %s' % thread.wikihost, _logger) def on_reconnect(self): debug('Reconnected to %r' % (thread,), _logger) self.on_connect() class GlobalListener(socketIO_client.BaseNamespace): def on_heartbeat(self): self._transport.send_heartbeat() self.client.define(RCListener, rcpath) self.client.define(GlobalListener) def __repr__(self): """Return representation.""" return "<rcstream for socketio://%s@%s:%s%s>" % ( self.wikihost, self.rchost, self.rcport, self.rcpath ) def run(self): """Threaded function. Runs insided the thread when started with .start().""" self.running = True while self.running: self.client.wait(seconds=0.1) debug('Shut down event loop for %r' % self, _logger) self.client.disconnect() debug('Disconnected %r' % self, _logger) self.queue.put(None) def stop(self): """Stop the thread.""" self.running = False def rc_listener(wikihost, rchost, rcport=80, rcpath='/rc', total=None): """Yield changes received from RCstream. @param wikihost: the hostname of the wiki we want to get changes for. This is passed to rcstream using a 'subscribe' command. Pass '*' to listen to all wikis for a given rc host. @param rchost: the recent changes stream host to connect to. For Wikimedia wikis, this is 'stream.wikimedia.org' @param rcport: the port to connect to (default: 80) @param rcpath: the sockets.io path. For Wikimedia wikis, this is '/rc'. (default: '/rc') @param total: the maximum number of entries to return. The underlying thread is shut down then this number is reached. @yields dict: dict as formatted by MediaWiki's MachineReadableRCFeedFormatter[1], which consists of at least id (recent changes id), type ('edit', 'new', 'log' or 'external'), namespace, title, comment, timestamp, user and bot (bot flag for the change). See [1] for more details. @raises ImportError [1] https://github.com/wikimedia/mediawiki/blob/master/includes/rcfeed/MachineReadableRCFeedFormatter.php """ try: # this is just to test whether socketIO_client is installed or not, # as the ImportError would otherwise pop up in the worker thread # where it's not easily caught. We don't use it, so we silence # flake8 with noqa. import socketIO_client # noqa except ImportError: raise ImportError('socketIO_client is required for the rc stream; ' 'install it with pip install socketIO_client') rc_thread = RcListenerThread( wikihost=wikihost, rchost=rchost, rcport=rcport, rcpath=rcpath, total=total ) debug('Starting rcstream thread %r' % rc_thread, _logger) rc_thread.start() while True: try: element = rc_thread.queue.get(timeout=0.1) except Empty: continue if element is None: return yield element def site_rc_listener(site, total=None): """Yield changes received from RCstream. @param site: the Pywikibot.Site object to yield live recent changes for @type site: Pywikibot.BaseSite @param total: the maximum number of changes to return @type total: int @returns pywikibot.comms.rcstream.rc_listener configured for the given site """ return rc_listener( wikihost=site.hostname(), rchost=site.rcstream_host(), total=total, )
#differential_expressed_gene_analysis.py from Betsy.protocol_utils import Parameter import normalize_file PRETTY_NAME = "Find differentially expressed genes." COMMON = 'Common Parameters' NORMALIZE = 'Normalize Parameters' OPTIONAL = 'Optional Parameters' ILLUMINA = 'Illumina Normalize Parameters' CLASS_NEIGHBORS = 'Class Neighbor Parameters' DIFF = 'Differential expressed parameters' CATEGORIES = [COMMON, NORMALIZE, OPTIONAL, ILLUMINA, CLASS_NEIGHBORS, DIFF] #input datatype INPUTS = ['AgilentFiles', 'ExpressionFiles', 'RenameFile', 'GPRFiles', 'GEOSeries', 'IDATFiles', 'CELFiles', '_SignalFile_Postprocess', 'ClassLabelFile', 'RenameFile', 'GeneListFile'] #output datatype OUTPUTS = 'DiffReportFile' #parameter objects PARAMETERS = [ Parameter('format', pretty_name='File Format', default_value='tdf', choices=['tdf', 'gct'], category=COMMON, description='output file format', datatype='SignalFile'), Parameter('preprocess', pretty_name='Preprocess', choices=normalize_file.PREPROCESS, category=COMMON, description='preprocess method', datatype='SignalFile'), Parameter('missing_algorithm', pretty_name='How to fill missing value', choices=["none", "median_fill", "zero_fill"], category=COMMON, description='method to the fill the missing value', datatype='SignalFile'), Parameter('logged', pretty_name='Logged or Not', default_value='yes', choices=['no', 'yes'], category=COMMON, description='signal is logged or not', datatype='SignalFile'), Parameter('filter', pretty_name='Filter', default_value='no', choices=['yes', 'no'], category=COMMON, description='filter the missing value or not', datatype='SignalFile'), Parameter('quantile_norm', pretty_name='Quantile', choices=['yes', 'no'], category=NORMALIZE, description='normalize by quanitle', datatype='SignalFile'), Parameter('combat_norm', pretty_name='Combat', choices=['yes', 'no'], category=NORMALIZE, description='normalize by combat', datatype='SignalFile'), Parameter('shiftscale_norm', pretty_name='Shiftscale', choices=['yes', 'no'], category=NORMALIZE, description='normalize by shiftscale', datatype='SignalFile'), Parameter('dwd_norm', pretty_name='Dwd', choices=['yes', 'no'], category=NORMALIZE, description='normalize by dwd', datatype='SignalFile'), Parameter('bfrm_norm', pretty_name='BFRM', choices=['yes', 'no'], category=NORMALIZE, description='normalize by bfrm', datatype='SignalFile'), Parameter('predataset', pretty_name='Predataset Process', choices=['yes', 'no'], category=COMMON, description='filter and threshold genes', datatype='SignalFile'), Parameter('gene_center', pretty_name='Gene Center', choices=['mean', 'median', 'no'], category=COMMON, description='gene center method', datatype='SignalFile'), Parameter('gene_normalize', pretty_name='Gene Normalize', choices=['variance', 'sum_of_squares', 'no'], category=COMMON, description='gene normalize method', datatype='SignalFile'), Parameter( 'gene_order', pretty_name='Gene Order', choices=['diff_ttest', 'diff_sam', 'diff_ebayes', 'diff_fold_change'], category=NORMALIZE, description='gene order', datatype='SignalFile'), Parameter('annotate', pretty_name='Annotation', choices=['yes', 'no'], category=OPTIONAL, description='how to annotate the output file', datatype='SignalFile'), Parameter('unique_genes', pretty_name='Unique Genes', choices=['average_genes', 'high_var', 'first_gene', 'no'], category=COMMON, description='how to select unique genes', datatype='SignalFile'), Parameter('duplicate_probe', pretty_name='Duplicate Probe', choices=['high_var_probe', 'closest_probe', 'no'], category=OPTIONAL, description='how to remove duplicate probe', datatype='SignalFile'), Parameter('num_features', pretty_name='Select Gene Number', choices=['yes', 'no'], category=COMMON, description='select num of genes or not', datatype='SignalFile'), Parameter('platform', pretty_name='Platform', choices=['yes', 'no'], category=OPTIONAL, description='output platform', datatype='SignalFile'), Parameter('group_fc', pretty_name='Group Fold Change', choices=['yes', 'no'], category=OPTIONAL, description='filter genes by fold change across classes', datatype='SignalFile'), Parameter('rename_sample', pretty_name='Rename samples', choices=['yes', 'no'], category=OPTIONAL, description='Rename sample name', datatype='SignalFile'), Parameter('contents', pretty_name='Contents', category=OPTIONAL, choices=normalize_file.CONTENTS, description='output group information', datatype='SignalFile'), ###for UserInput Parameter('num_factors', pretty_name='Number of Factors', category=OPTIONAL, description='num of factors for bfrm normalization', datatype='UserInput'), Parameter('filter_value', pretty_name='Filter missing Value by Percentage', category=OPTIONAL, description='percentage to filter the missing value(0-1)', datatype='UserInput'), Parameter('gene_select_threshold', pretty_name='Gene Selection Threshold', category=OPTIONAL, description='gene select threshold', datatype='UserInput'), Parameter( 'platform_name', pretty_name='Platform name', choices=["'HG_U133_Plus_2'", "'HG_U133B'", "'HG_U133A'", "'HG_U133A_2'", "'HG_U95A'", "'HumanHT_12'", "'HumanWG_6'", "'HG_U95Av2'", "'Entrez_ID_human'", "'Entrez_symbol_human'", "'Hu6800'", "'Mouse430A_2'", "'MG_U74Cv2'", "'Mu11KsubB'", "'Mu11KsubA'", "'MG_U74Av2'", "'Mouse430_2'", "'MG_U74Bv2'", "'Entrez_ID_mouse'", "'MouseRef_8'", "'Entrez_symbol_mouse'", "'RG_U34A'", "'RAE230A'", 'unknown_platform'], description='output platform name', datatype='UserInput', category=OPTIONAL), Parameter('num_features_value', pretty_name='Select Gene Number', category=COMMON, description='select num of genes or not', datatype='UserInput'), Parameter('group_fc_num', pretty_name='group_fc value', category=COMMON, description='value for group fold change', datatype='UserInput'), ###illumina related Parameter( 'ill_manifest', pretty_name='Illumina Manifest File', choices= ['HumanHT-12_V3_0_R2_11283641_A.txt', 'HumanHT-12_V4_0_R2_15002873_B.txt', 'HumanHT-12_V3_0_R3_11283641_A.txt', 'HumanHT-12_V4_0_R1_15002873_B.txt', 'HumanMI_V1_R2_XS0000122-MAP.txt', 'HumanMI_V2_R0_XS0000124-MAP.txt', 'HumanRef-8_V2_0_R4_11223162_A.txt', 'HumanRef-8_V3_0_R1_11282963_A_WGDASL.txt', 'HumanRef-8_V3_0_R2_11282963_A.txt', 'HumanRef-8_V3_0_R3_11282963_A.txt', 'HumanWG-6_V2_0_R4_11223189_A.txt', 'HumanWG-6_V3_0_R2_11282955_A.txt', 'HumanWG-6_V3_0_R3_11282955_A.txt', 'MouseMI_V1_R2_XS0000127-MAP.txt', 'MouseMI_V2_R0_XS0000129-MAP.txt', 'MouseRef-8_V1_1_R4_11234312_A.txt', 'MouseRef-8_V2_0_R2_11278551_A.txt', 'MouseRef-8_V2_0_R3_11278551_A.txt', 'MouseWG-6_V1_1_R4_11234304_A.txt', 'MouseWG-6_V2_0_R2_11278593_A.txt', 'MouseWG-6_V2_0_R3_11278593_A.txt', 'RatRef-12_V1_0_R5_11222119_A.txt'], category=ILLUMINA, description='Illumina manifest file in tab-delimited (TXT) format', datatype="ILLUFolder"), Parameter('ill_chip', pretty_name='Illumina chip File', choices=['ilmn_HumanHT_12_V3_0_R3_11283641_A.chip', 'ilmn_HumanHT_12_V4_0_R1_15002873_B.chip', 'ilmn_HumanRef_8_V2_0_R4_11223162_A.chip', 'ilmn_HumanReF_8_V3_0_R1_11282963_A_WGDASL.chip', 'ilmn_HumanRef_8_V3_0_R3_11282963_A.chip', 'ilmn_HumanWG_6_V2_0_R4_11223189_A.chip', 'ilmn_HumanWG_6_V3_0_R3_11282955_A.chip', 'ilmn_MouseRef_8_V1_1_R4_11234312_A.chip', 'ilmn_MouseRef_8_V2_0_R3_11278551_A.chip', 'ilmn_MouseWG_6_V1_1_R4_11234304_A.chip', 'ilmn_MouseWG_6_V2_0_R3_11278593_A.chip', 'ilmn_RatRef_12_V1_0_R5_11222119_A.chip'], category=ILLUMINA, description='CHIP file to map probes to genes.', datatype="ILLUFolder"), Parameter('ill_clm', pretty_name='Illumina clm File', category=ILLUMINA, description='CLM file to map file names to sample names.', datatype="ILLUFolder"), Parameter('ill_custom_chip', pretty_name='Illumina Custom Chip File', category=ILLUMINA, description='Other CHIP file to map probes to genes.', datatype="ILLUFolder"), Parameter('ill_custom_manifest', pretty_name='Illumina Custom Manifest File', category=ILLUMINA, description= 'Other Illumina manifest file in tab-delimited (TXT) format.', datatype="ILLUFolder"), Parameter('ill_bg_mode', pretty_name='Illumina Background Mode', choices=['ill_yes', 'ill_no'], category=ILLUMINA, description='Perform background subtraction.', datatype="ILLUFolder"), Parameter( 'ill_coll_mode', pretty_name='Illumina Coll Mode', choices=['none', 'max', 'median'], category=ILLUMINA, description= 'Collapse probes to genes based on the manifest or CHIP file (if provided).', datatype="ILLUFolder"), #class neighbors Parameter('cn_mean_or_median', pretty_name='cn mean or median', category=CLASS_NEIGHBORS, choices=['mean', 'median'], description='use mean or median for feature selection', datatype='GeneListFile'), Parameter('cn_ttest_or_snr', pretty_name='cn ttest or snr', category=CLASS_NEIGHBORS, choices=['t_test', 'snr'], description='use signal-to-noise or t-test to select neighbors', datatype='GeneListFile'), Parameter('cn_filter_data', choices=['yes', 'no'], category=CLASS_NEIGHBORS, pretty_name='cn filter data', description='if no, values below will be ignored', datatype='GeneListFile'), Parameter('cn_num_neighbors', pretty_name='cn num neighbors', category=CLASS_NEIGHBORS, description='number of neighbors to find', datatype='UserInput'), Parameter('cn_num_perm', pretty_name='cn num permutations', category=CLASS_NEIGHBORS, description='number of permutations in permutation test', datatype='UserInput'), Parameter('cn_user_pval', pretty_name='cn user pval', category=CLASS_NEIGHBORS, description='user-set significance value for permutation test', datatype='UserInput'), Parameter('cn_min_threshold', category=CLASS_NEIGHBORS, pretty_name='cn min threshold', description='minimum threshold for data', datatype='UserInput'), Parameter('cn_max_threshold', category=CLASS_NEIGHBORS, pretty_name='cn max threshold', description='maximum threshold for data', datatype='UserInput'), Parameter('cn_min_folddiff', category=CLASS_NEIGHBORS, pretty_name='cn min fold diff', description='minimum fold difference for filtering genes', datatype='UserInput'), Parameter('cn_abs_diff', category=CLASS_NEIGHBORS, pretty_name='cn abs diff', description='minimum absolute difference for filtering genes', datatype='UserInput'), #diffenet_expr related Parameter('diffexp_foldchange_value', pretty_name='Diffexp Fold Change', category=DIFF, description='diff exp fold change number e.g. 1.0', datatype='UserInput'), Parameter('sam_foldchange_value', pretty_name='Sam Fold Change', category=DIFF, description='sam fold change number e.g. 1.0', datatype='UserInput'), Parameter('sam_delta_value', pretty_name='Sam delta', category=DIFF, description='sam delta e.g 1.0', datatype='UserInput'), Parameter('select_gene_by_foldchange', pretty_name='Select Gene by Foldchange', category=DIFF, description='select gene by foldchange value,etc.5', datatype='UserInput'), Parameter('select_gene_by_p_value', pretty_name='Select Gene by p_value', category=DIFF, description='select gene by p-value value, etc. 0.05', datatype='UserInput'), Parameter('select_gene_by_fdr', pretty_name='Select Gene by fdr', category=DIFF, description='select gene by fdr value, etc.0.05', datatype='UserInput'), Parameter('hm_width', pretty_name='heatmap width', category=DIFF, description='heatmap width', datatype='UserInput'), Parameter('hm_height', pretty_name='heatmap height', category=DIFF, description='heatmap height', datatype='UserInput'), ]
import json import time from logger import logger from perfrunner.helpers.cbmonitor import timeit, with_stats from perfrunner.helpers.misc import pretty_dict, read_json from perfrunner.helpers.profiler import with_profiles from perfrunner.tests import PerfTest from perfrunner.tests.analytics import BigFunTest from perfrunner.tests.eventing import EventingTest from perfrunner.tests.fts import FTSTest from perfrunner.tests.n1ql import N1QLTest from perfrunner.tests.rebalance import RebalanceKVTest from perfrunner.tests.tools import BackupRestoreTest from perfrunner.tests.xdcr import SrcTargetIterator, UniDirXdcrInitTest class HighBucketDensityTest(RebalanceKVTest, UniDirXdcrInitTest, N1QLTest, EventingTest, BigFunTest, FTSTest, BackupRestoreTest): COLLECTORS = { 'iostat': True, 'memory': True, 'n1ql_stats': True, 'secondary_stats': True, 'ns_server_system': True, 'xdcr_stats': True, 'analytics': True } SLEEP_TIME_BETWEEN_REBALNCE = 600 def rebalance(self, *args): self.pre_rebalance() rebalance_time = self._rebalance(None) self.post_rebalance() logger.info("Rebalance time: {} min".format(rebalance_time / 60)) def access_and_rebalance(self, src_target_iterator: SrcTargetIterator): time.sleep(self.SLEEP_TIME_BETWEEN_REBALNCE) self.store_plans() src_target_iterator_access = SrcTargetIterator(self.cluster_spec, self.test_config, "access") PerfTest.access_bg(self, target_iterator=src_target_iterator_access) self.access_n1ql_bg() access_settings = self.test_config.access_settings access_settings.spring_batch_size = 5 access_settings.creates = 0 access_settings.updates = 1 access_settings.reads = 3 access_settings.deletes = 1 access_settings.throughput = 5 PerfTest.access_bg(self, settings=access_settings, target_iterator=src_target_iterator) self.rebalance() def add_eventing_functions(self): with open(self.config_file) as f: func = json.load(f) func["settings"]["dcp_stream_boundary"] = "from_now" """ Commenting out as second function deployment is failing MB-32437 for bkt in self.test_config.buckets: func["depcfg"]["source_bucket"] = bkt func["appname"] = bkt + "-test1" self.set_functions_with_config(func=func, override_name=False, wait_for_bootstrap=True) """ func["depcfg"]["source_bucket"] = "bucket-1" func["appname"] = "bucket-1-test1" self.set_functions_with_config(func=func, override_name=False, wait_for_bootstrap=True) @with_stats @with_profiles def init_only_xdcr(self): self.add_remote_cluster() self.create_replication() time.sleep(3600) def create_analytics_datasets(self): logger.info('Creating datasets') for bkt in self.test_config.buckets: statement = "CREATE DATASET `{}` ON `{}` WHERE category > 1;"\ .format(bkt + "-ds1", bkt) logger.info(statement) self.rest.exec_analytics_statement(self.analytics_nodes[0], statement) statement = "CREATE DATASET `{}` ON `{}` WHERE category < 1;" \ .format(bkt + "-ds2", bkt) logger.info(statement) self.rest.exec_analytics_statement(self.analytics_nodes[0], statement) self.connect_buckets() def create_fts_indexes(self): less_words = True for bkt in self.test_config.buckets: definition = read_json(self.access.couchbase_index_configfile) if less_words: name = "fts_less_words" less_words = False else: name = "fts_more_words" less_words = True index_name = bkt + "-" + name definition.update({ 'name': index_name, 'sourceName': bkt, }) mapping = definition["params"]["mapping"]["default_mapping"] prop = definition["params"]["mapping"]["default_mapping"]["properties"] index = prop["fts_less_words"] new_prop = {name: index} mapping.update({ 'properties': new_prop }) index = \ definition["params"]["mapping"]["default_mapping"]["properties"][name]["fields"][0] index.update({ 'name': name }) logger.info('Index definition: {}'.format(pretty_dict(definition))) self.rest.create_fts_index(self.fts_master_node, index_name, definition) self.monitor.monitor_fts_indexing_queue(self.fts_nodes[0], index_name, int(self.test_config.access_settings.items * 0.95)) self.monitor.monitor_fts_index_persistence(self.fts_nodes, index_name, bkt) @timeit def custom_rebalance(self, services, initial_nodes, nodes_after, swap): clusters = self.cluster_spec.clusters for (_, servers), initial_nodes, nodes_after in zip(clusters, initial_nodes, nodes_after): master = servers[0] new_nodes = [] known_nodes = servers[:initial_nodes] ejected_nodes = [] if nodes_after > initial_nodes: # rebalance-in new_nodes = servers[initial_nodes:nodes_after] known_nodes = servers[:nodes_after] elif nodes_after < initial_nodes: # rebalance-out ejected_nodes = servers[nodes_after:initial_nodes] logger.info("ejected_nodes {}".format(ejected_nodes)) elif swap: service = services.split(",")[0] new_nodes = servers[initial_nodes:initial_nodes + swap] known_nodes = servers[:initial_nodes + swap] ejected_nodes = [self.cluster_spec.servers_by_role_from_first_cluster(service)[-1]] if ejected_nodes[0] == new_nodes[0]: ejected_nodes = \ [self.cluster_spec.servers_by_role_from_first_cluster(service)[-2]] logger.info("ejected_nodes {}".format(ejected_nodes)) else: continue for node in new_nodes: logger.info("Adding {} as {}".format(node, services)) self.rest.add_node(master, node, services=services) self.rest.rebalance(master, known_nodes, ejected_nodes) logger.info("Rebalance master: {}".format(master)) self.monitor_progress(master) if swap: time.sleep(self.SLEEP_TIME_BETWEEN_REBALNCE) for node in ejected_nodes: logger.info("Adding {} as {}".format(node, services)) self.rest.add_node(master, node, services=services) logger.info("ejected_nodes {}".format(servers[initial_nodes:initial_nodes + 1])) self.rest.rebalance(master, known_nodes, servers[initial_nodes:initial_nodes + 1]) logger.info("Rebalance master: {}".format(master)) self.monitor_progress(master) break def rebalance_out_node(self, services): logger.info("Rebalancing out {} node".format(services)) rebalance_time = self.custom_rebalance(services, self.rebalance_settings.nodes_after, self.test_config.cluster.initial_nodes, 0) logger.info("Rebalancing out {} node, COMPLETED.".format(services)) logger.info("Rebalance time: {} min".format(rebalance_time / 60)) time.sleep(self.SLEEP_TIME_BETWEEN_REBALNCE) def rebalance_in_node(self, services): logger.info("Rebalancing in {} node, STARTING".format(services)) rebalance_time = self.custom_rebalance(services, self.test_config.cluster.initial_nodes, self.rebalance_settings.nodes_after, 0) logger.info("Rebalancing in {} node, COMPLETED.".format(services)) logger.info("Rebalance time: {} min".format(rebalance_time / 60)) time.sleep(self.SLEEP_TIME_BETWEEN_REBALNCE) def swap_node(self, services): logger.info("Swapping in {} node, STARTING".format(services)) rebalance_time = self.custom_rebalance(services, self.test_config.cluster.initial_nodes, self.test_config.cluster.initial_nodes, 1) logger.info("Swapping in {} node, COMPLETED.".format(services)) logger.info("Rebalance time: {} min".format(rebalance_time / 60)) time.sleep(self.SLEEP_TIME_BETWEEN_REBALNCE) @with_stats def run_kv_rebalance(self): src_target_iterator = SrcTargetIterator(self.cluster_spec, self.test_config, "initial") self.access_and_rebalance(src_target_iterator) self.rebalance_out_node("kv") self.swap_node("kv") @with_stats def run_index_rebalance(self): self.rebalance_in_node("index") self.rebalance_out_node("index") self.swap_node("index,n1ql") @with_stats def run_eventing_rebalance(self): self.rebalance_in_node("eventing") self.rebalance_out_node("eventing") self.swap_node("eventing") @with_stats def run_fts_rebalance(self): self.rebalance_in_node("fts") self.rebalance_out_node("fts") self.swap_node("fts") @with_stats def run_cbas_rebalance(self): self.rebalance_in_node("cbas") self.rebalance_out_node("cbas") self.swap_node("cbas") def run_rebalance_phase(self): self.run_kv_rebalance() self.run_index_rebalance() self.run_eventing_rebalance() self.run_cbas_rebalance() """ Commenting FTS rebalance phase as swap rebalance for FTS always fails - MB-32547 Pushing it as last step in test, we shall uncomment this once above bug is fixed. self.run_fts_rebalance() """ @with_stats @timeit def backup(self, mode=None): super().backup(mode) def back_up(self): self.extract_tools() time_elapsed = self.backup() logger.info("Backup time: {} min".format(time_elapsed / 60)) def run(self): src_target_iterator = SrcTargetIterator(self.cluster_spec, self.test_config, "initial") PerfTest.load(self, target_iterator=src_target_iterator) self.wait_for_persistence() t0 = time.time() self.create_indexes() self.wait_for_indexing() index_build_time = time.time() - t0 logger.info("Index build time: {} min".format(index_build_time / 60)) self.init_only_xdcr() """ Commenting out wait for xdcr init as it is very slow time_elapsed = self.init_xdcr() logger.info("XDCR init time: {} min".format(time_elapsed / 60)) """ self.add_eventing_functions() self.create_fts_indexes() self.create_analytics_datasets() self.run_rebalance_phase() self.back_up() """ Keeping this at end as FTS swap rebalance fails - MB-32547 """ self.run_fts_rebalance() class MultibucketEventing(HighBucketDensityTest): COLLECTORS = { 'iostat': True, 'memory': True, 'ns_server_system': True} def add_eventing_functions(self): with open(self.config_file) as f: func = json.load(f) func["settings"]["dcp_stream_boundary"] = "from_now" """ Commenting out as second function deployment is failing MB-32437 """ for bkt in self.test_config.buckets: func["depcfg"]["source_bucket"] = bkt func["appname"] = bkt + "-test1" self.set_functions_with_config(func=func, override_name=False, wait_for_bootstrap=True) def access_and_rebalance(self, src_target_iterator: SrcTargetIterator): time.sleep(self.SLEEP_TIME_BETWEEN_REBALNCE) src_target_iterator_access = SrcTargetIterator(self.cluster_spec, self.test_config, "access") PerfTest.access_bg(self, target_iterator=src_target_iterator_access) access_settings = self.test_config.access_settings access_settings.spring_batch_size = 5 access_settings.creates = 0 access_settings.updates = 1 access_settings.reads = 3 access_settings.deletes = 1 access_settings.throughput = 5 PerfTest.access_bg(self, settings=access_settings, target_iterator=src_target_iterator) self.rebalance() @with_stats def run_kv_rebalance(self): src_target_iterator = SrcTargetIterator(self.cluster_spec, self.test_config, "initial") self.access_and_rebalance(src_target_iterator) self.rebalance_out_node("kv") self.swap_node("kv") def run(self): src_target_iterator = SrcTargetIterator(self.cluster_spec, self.test_config, "initial") PerfTest.load(self, target_iterator=src_target_iterator) self.wait_for_persistence() self.add_eventing_functions() self.run_kv_rebalance() self.run_eventing_rebalance() class MultibucketGSI(HighBucketDensityTest): COLLECTORS = { 'iostat': True, 'memory': True, 'ns_server_system': True, 'secondary_stats': True} # This is to verify the bug : MB-39144 def run(self): # PerfTest.load(self, target_iterator=src_target_iterator) # self.wait_for_persistence() t0 = time.time() PerfTest.create_indexes(self) self.wait_for_indexing() index_build_time = time.time() - t0 logger.info("Index build time: {} min".format(index_build_time / 60))
# 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. # ============================================================================== """Tests for tf.test.compute_gradient and tf.compute_gradient_error.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import gradient_checker from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn_ops import tensorflow.python.ops.nn_grad # pylint: disable=unused-import from tensorflow.python.platform import test from tensorflow.python.platform import tf_logging @ops.RegisterGradient("BadGrad") def _bad_grad(unused_op, grad): """A gradient that returns the wrong shape.""" return array_ops.transpose(grad) @ops.RegisterGradient("NaNGrad") def _nan_grad(unused_op, grad): """A gradient that returns NaN.""" return np.nan * grad class GradientCheckerTest(test.TestCase): def testAddSimple(self): np.random.seed(1) # Fix seed to avoid flakiness with self.test_session(use_gpu=False): # a test case for Add operation size = (2, 3) x1 = constant_op.constant(2.0, shape=size, name="x1") x2 = constant_op.constant(3.0, shape=size, name="x2") y = math_ops.add(x1, x2, name="y") # checking gradients for x1 error = gradient_checker.compute_gradient_error(x1, size, y, size) tf_logging.info("x1 error = %f", error) assert error < 1e-4 def testAddSimpleGPU(self): np.random.seed(2) # Fix seed to avoid flakiness with self.test_session(use_gpu=True): # a test case for Add operation size = (2, 3) x1 = constant_op.constant(2.0, shape=size, name="x1") x2 = constant_op.constant(3.0, shape=size, name="x2") y = math_ops.add(x1, x2, name="y") # checking gradients for x1 error = gradient_checker.compute_gradient_error(x1, size, y, size) tf_logging.info("x1 error = %f", error) assert error < 1e-4 def testAddCustomized(self): np.random.seed(3) # Fix seed to avoid flakiness with self.test_session(): # a test case for Add operation size = (2, 3) x1 = constant_op.constant( 2.0, shape=size, dtype=dtypes.float64, name="x1") x2 = constant_op.constant( 3.0, shape=size, dtype=dtypes.float64, name="x2") y = math_ops.add(x1, x2, name="y") # checkint gradients for x2 using a special init_value and delta x_init_value = np.asarray(np.arange(6, dtype=np.float64).reshape(2, 3)) error = gradient_checker.compute_gradient_error( x2, size, y, size, x_init_value=x_init_value, delta=1e-2) tf_logging.info("x2 error = %f", error) assert error < 1e-10 def testGather(self): np.random.seed(4) # Fix seed to avoid flakiness with self.test_session(): p_shape = (4, 2) p_size = 8 index_values = [1, 3] y_shape = [2, 2] params = constant_op.constant( np.arange(p_size).astype(np.float), shape=p_shape, name="p") indices = constant_op.constant(index_values, name="i") y = array_ops.gather(params, indices, name="y") error = gradient_checker.compute_gradient_error(params, p_shape, y, y_shape) tf_logging.info("gather error = %f", error) assert error < 1e-4 def testNestedGather(self): np.random.seed(5) # Fix seed to avoid flakiness with self.test_session(): p_shape = (8, 2) p_size = 16 index_values = [1, 3, 5, 6] index_values2 = [0, 2] y2_shape = [2, 2] params = constant_op.constant( np.arange(p_size).astype(np.float), shape=p_shape, name="p") indices = constant_op.constant(index_values, name="i") y = array_ops.gather(params, indices, name="y") indices2 = constant_op.constant(index_values2, name="i2") y2 = array_ops.gather(y, indices2, name="y2") error = gradient_checker.compute_gradient_error(params, p_shape, y2, y2_shape) tf_logging.info("nested gather error = %f", error) assert error < 1e-4 def testComplexMul(self): with self.test_session(): size = () c = constant_op.constant(5 + 7j, dtype=dtypes.complex64) x = constant_op.constant(11 - 13j, dtype=dtypes.complex64) y = c * x analytical, numerical = gradient_checker.compute_gradient(x, size, y, size) correct = np.array([[5, 7], [-7, 5]]) self.assertAllEqual(correct, analytical) self.assertAllClose(correct, numerical, rtol=1e-4) self.assertLess( gradient_checker.compute_gradient_error(x, size, y, size), 2e-4) def testComplexConj(self): with self.test_session(): size = () x = constant_op.constant(11 - 13j, dtype=dtypes.complex64) y = math_ops.conj(x) analytical, numerical = gradient_checker.compute_gradient(x, size, y, size) correct = np.array([[1, 0], [0, -1]]) self.assertAllEqual(correct, analytical) self.assertAllClose(correct, numerical, rtol=2e-5) self.assertLess( gradient_checker.compute_gradient_error(x, size, y, size), 2e-5) def testEmptySucceeds(self): with self.test_session(): x = array_ops.placeholder(dtypes.float32) y = array_ops.identity(x) for grad in gradient_checker.compute_gradient(x, (0, 3), y, (0, 3)): self.assertEqual(grad.shape, (0, 0)) error = gradient_checker.compute_gradient_error(x, (0, 3), y, (0, 3)) self.assertEqual(error, 0) def testEmptyFails(self): with ops.Graph().as_default() as g: with self.test_session(graph=g): x = array_ops.placeholder(dtypes.float32) with g.gradient_override_map({"Identity": "BadGrad"}): y = array_ops.identity(x) bad = r"Empty gradient has wrong shape: expected \(0, 3\), got \(3, 0\)" with self.assertRaisesRegexp(ValueError, bad): gradient_checker.compute_gradient(x, (0, 3), y, (0, 3)) with self.assertRaisesRegexp(ValueError, bad): gradient_checker.compute_gradient_error(x, (0, 3), y, (0, 3)) def testNaNGradFails(self): with ops.Graph().as_default() as g: with self.test_session(graph=g): x = array_ops.placeholder(dtypes.float32) with g.gradient_override_map({"Identity": "NaNGrad"}): y = array_ops.identity(x) error = gradient_checker.compute_gradient_error(x, (), y, ()) # Typical test would assert error < max_err, so assert this test would # raise AssertionError, since NaN is not < 1.0. with self.assertRaisesRegexp(AssertionError, "False is not true"): self.assertTrue(error < 1.0) class MiniMNISTTest(test.TestCase): # Gradient checker for MNIST. def _BuildAndTestMiniMNIST(self, param_index, tag): # Fix seed to avoid occasional flakiness np.random.seed(6) # Hyperparameters batch = 3 inputs = 16 features = 32 classes = 10 # Define the parameters inp_data = np.random.random_sample(inputs * batch) hidden_weight_data = np.random.randn(inputs * features) / np.sqrt(inputs) hidden_bias_data = np.random.random_sample(features) sm_weight_data = np.random.randn(features * classes) / np.sqrt(features) sm_bias_data = np.random.random_sample(classes) # special care for labels since they need to be normalized per batch label_data = np.random.random(batch * classes).reshape((batch, classes)) s = label_data.sum(axis=1) label_data /= s[:, None] with self.test_session(use_gpu=True): # We treat the inputs as "parameters" here inp = constant_op.constant( inp_data.tolist(), shape=[batch, inputs], dtype=dtypes.float64, name="inp") hidden_weight = constant_op.constant( hidden_weight_data.tolist(), shape=[inputs, features], dtype=dtypes.float64, name="hidden_weight") hidden_bias = constant_op.constant( hidden_bias_data.tolist(), shape=[features], dtype=dtypes.float64, name="hidden_bias") softmax_weight = constant_op.constant( sm_weight_data.tolist(), shape=[features, classes], dtype=dtypes.float64, name="softmax_weight") softmax_bias = constant_op.constant( sm_bias_data.tolist(), shape=[classes], dtype=dtypes.float64, name="softmax_bias") # List all the parameter so that we can test them one at a time all_params = [ inp, hidden_weight, hidden_bias, softmax_weight, softmax_bias ] param_sizes = [ [batch, inputs], # inp [inputs, features], # hidden_weight, [features], # hidden_bias [features, classes], # softmax_weight, [classes] ] # softmax_bias # Now, Building MNIST features = nn_ops.relu( nn_ops.xw_plus_b(inp, hidden_weight, hidden_bias), name="features") logits = nn_ops.xw_plus_b( features, softmax_weight, softmax_bias, name="logits") labels = constant_op.constant( label_data.tolist(), shape=[batch, classes], dtype=dtypes.float64, name="labels") cost = nn_ops.softmax_cross_entropy_with_logits( labels=labels, logits=logits, name="cost") # Test the gradients. err = gradient_checker.compute_gradient_error( all_params[param_index], param_sizes[param_index], cost, [batch], delta=1e-5) tf_logging.info("Mini MNIST: %s gradient error = %g", tag, err) return err def testInputGradient(self): self.assertLess(self._BuildAndTestMiniMNIST(0, "input"), 1e-8) def testHiddenWeightGradient(self): self.assertLess(self._BuildAndTestMiniMNIST(1, "hidden_weight"), 1e-8) def testHiddenBiasGradient(self): self.assertLess(self._BuildAndTestMiniMNIST(2, "hidden_bias"), 1e-8) def testSoftmaxWeightGradient(self): self.assertLess(self._BuildAndTestMiniMNIST(3, "softmax_weight"), 1e-8) def testSoftmaxBiasGradient(self): self.assertLess(self._BuildAndTestMiniMNIST(4, "softmax_bias"), 1e-8) if __name__ == "__main__": test.main()
from __future__ import print_function from builtins import map from threeML.io.file_utils import ( sanitize_filename, if_directory_not_existing_then_make, file_existing_and_readable, ) from threeML.config.config import threeML_config from threeML.io.download_from_http import ApacheDirectory, RemoteDirectoryNotFound from threeML.io.dict_with_pretty_print import DictWithPrettyPrint from threeML.exceptions.custom_exceptions import TriggerDoesNotExist import gzip import shutil import os import numpy as np from collections import OrderedDict import re def _validate_fermi_trigger_name(trigger): _trigger_name_match = re.compile("^(bn|grb?)? ?(\d{9})$") _valid_trigger_args = ["080916009", "bn080916009", "GRB080916009"] assert_string = "The trigger %s is not valid. Must be in the form %s" % ( trigger, ", or ".join(_valid_trigger_args), ) assert type(trigger) == str, "triggers must be strings" trigger = trigger.lower() search = _trigger_name_match.match(trigger) assert search is not None, assert_string assert search.group(2) is not None, assert_string trigger = search.group(2) return trigger _detector_list = "n0,n1,n2,n3,n4,n5,n6,n7,n8,n9,na,nb,b0,b1".split(",") def download_GBM_trigger_data( trigger_name, detectors=None, destination_directory=".", compress_tte=True ): """ Download the latest GBM TTE and RSP files from the HEASARC server. Will get the latest file version and prefer RSP2s over RSPs. If the files already exist in your destination directory, they will be skipped in the download process. The output dictionary can be used as input to the FermiGBMTTELike class. example usage: download_GBM_trigger_data('080916009', detectors=['n0','na','b0'], destination_directory='.') :param trigger_name: trigger number (str) e.g. '080916009' or 'bn080916009' or 'GRB080916009' :param detectors: list of detectors, default is all detectors :param destination_directory: download directory :param compress_tte: compress the TTE files via gzip (default True) :return: a dictionary with information about the download """ # Let's doctor up the input just in case the user tried something strange sanitized_trigger_name_ = _validate_fermi_trigger_name(trigger_name) # create output directory if it does not exists destination_directory = sanitize_filename(destination_directory, abspath=True) if_directory_not_existing_then_make(destination_directory) # Sanitize detector list (if any) if detectors is not None: for det in detectors: assert det in _detector_list, ( "Detector %s in the provided list is not a valid detector. " "Valid choices are: %s" % (det, _detector_list) ) else: detectors = list(_detector_list) # Open heasarc web page url = threeML_config["gbm"]["public HTTP location"] year = "20%s" % sanitized_trigger_name_[:2] directory = "/triggers/%s/bn%s/current" % (year, sanitized_trigger_name_) heasarc_web_page_url = "%s/%s" % (url, directory) try: downloader = ApacheDirectory(heasarc_web_page_url) except RemoteDirectoryNotFound: raise TriggerDoesNotExist( "Trigger %s does not exist at %s" % (sanitized_trigger_name_, heasarc_web_page_url) ) # Now select the files we want to download, then we will download them later # We do it in two steps because we want to be able to choose what to download once we # have the complete picture # Get the list of remote files remote_file_list = downloader.files # This is the dictionary to keep track of the classification remote_files_info = DictWithPrettyPrint([(det, {}) for det in detectors]) # Classify the files detector by detector for this_file in remote_file_list: # this_file is something like glg_tte_n9_bn100101988_v00.fit tokens = this_file.split("_") if len(tokens) != 5: # Not a data file continue else: # The "map" is necessary to transform the tokens to normal string (instead of unicode), # because u"b0" != "b0" as a key for a dictionary _, file_type, detname, _, version_ext = list(map(str, tokens)) version, ext = version_ext.split(".") # We do not care here about the other files (tcat, bcat and so on), # nor about files which pertain to other detectors if ( file_type not in ["cspec", "tte"] or ext not in ["rsp", "rsp2", "pha", "fit"] or detname not in detectors ): continue # cspec files can be rsp, rsp2 or pha files. Classify them if file_type == "cspec": if ext == "rsp": remote_files_info[detname]["rsp"] = this_file elif ext == "rsp2": remote_files_info[detname]["rsp2"] = this_file elif ext == "pha": remote_files_info[detname]["cspec"] = this_file else: raise RuntimeError("Should never get here") else: remote_files_info[detname][file_type] = this_file # Now download the files download_info = DictWithPrettyPrint( [(det, DictWithPrettyPrint()) for det in detectors] ) for detector in list(remote_files_info.keys()): remote_detector_info = remote_files_info[detector] local_detector_info = download_info[detector] # Get CSPEC file local_detector_info["cspec"] = downloader.download( remote_detector_info["cspec"], destination_directory, progress=True ) # Get the RSP2 file if it exists, otherwise get the RSP file if "rsp2" in remote_detector_info: local_detector_info["rsp"] = downloader.download( remote_detector_info["rsp2"], destination_directory, progress=True ) else: local_detector_info["rsp"] = downloader.download( remote_detector_info["rsp"], destination_directory, progress=True ) # Get TTE file (compressing it if requested) local_detector_info["tte"] = downloader.download( remote_detector_info["tte"], destination_directory, progress=True, compress=compress_tte, ) return download_info def _get_latest_version(filenames): """ returns the list with only the highest version numbers selected :param filenames: list of GBM data files :return: """ # this holds the version number vn_as_num = OrderedDict() # this holds the extensions extentions = OrderedDict() # this holds the vn string vn_as_string = OrderedDict() for fn in filenames: # get the first part of the file fn_stub, vn_stub = fn.split("_v") # split the vn string and extension vn_string, ext = vn_stub.split(".") # convert the vn to a number vn = 0 for i in vn_string: vn += int(i) # build the dictionaries where keys # are the non-unique file name # and values are extensions and vn vn_as_num.setdefault(fn_stub, []).append(vn) extentions.setdefault(fn_stub, []).append(ext) vn_as_string.setdefault(fn_stub, []).append(vn_string) final_file_names = [] # Now we we go through and make selections for key in list(vn_as_num.keys()): # first we favor RSP2 ext = np.array(extentions[key]) idx = ext == "rsp2" # if there are no rsp2 in the files if idx.sum() == 0: # we can select on all idx = np.ones_like(ext, dtype=bool) ext = ext[idx] vn = np.array(vn_as_num[key])[idx] vn_string = np.array(vn_as_string[key])[idx] # get the latest version max_vn = np.argmax(vn) # create the file name latest_version = "%s_v%s.%s" % (key, vn_string[max_vn], ext[max_vn]) final_file_names.append(latest_version) return final_file_names def cleanup_downloaded_GBM_data(detector_information_dict): """ deletes data downloaded with download_GBM_trigger_data. :param detector_information_dict: the return dictionary from download_GBM_trigger_data """ # go through each detector for detector in list(detector_information_dict.keys()): # for each detector, remove the data file for data_file in list(detector_information_dict[detector].values()): print("Removing: %s" % data_file) os.remove(data_file) print("\n")
#!/usr/bin/env python # coding: utf-8 # In[2]: import numpy as np import matplotlib.pyplot as plt plt.style.use('classic') import matplotlib.dates as dts import fredpy as fp import pandas as pd import runProcs # get_ipython().run_line_magic('matplotlib', 'inline') # In[3]: # 0. Setup: Formatting commands and definitions. # 0.1 general plot settings # Make all plotted axis lables and tick lables bold 15 pt font font = {'weight' : 'bold', 'size' : 15} axes={'labelweight' : 'bold'} plt.rc('font', **font) plt.rc('axes', **axes) # Add some space around the tick lables for better readability plt.rcParams['xtick.major.pad']='8' plt.rcParams['ytick.major.pad']='8' # 0.2 Formatter for inserting commas in y axis labels with magnitudes in the thousands def func(x, pos): # formatter function takes tick label and tick position s = '{:0,d}'.format(int(x)) return s y_format = plt.FuncFormatter(func) # make formatter # 0.3 format the x axis ticksticks years2,years4,years5,years10,years15= dts.YearLocator(2),dts.YearLocator(4),dts.YearLocator(5),dts.YearLocator(10),dts.YearLocator(15) # 0.4 label locator for vertical axes plotting gdp majorLocator_y = plt.MultipleLocator(3) majorLocator_shares = plt.MultipleLocator(0.2) # 0.5 load fred api key fp.api_key = fp.load_api_key('fred_api_key.txt') # In[4]: # 1. Setup for the construction of K and A # 1.1 Parameters for the model alpha = 0.35 # If output_solow == TRUE, then Y = C + I. Else: Y = C + I + G + NX (default) output_solow = False # 1.3 Define the function for computing the capital series def capitalSeries(i,k0,delta): t0 = len(i)-1 k = [k0] for t in range(t0): k.append(i[t]+(1-delta)*k[t]) return np.array(k) # In[ ]: # 2. Import and manage data from FRED # 2.1 Annual data investmentA = fp.series('GPDIA') consumptionA = fp.series('PCECA') governmentA = fp.series('GCEA') exportsA = fp.series('EXPGSA') importsA = fp.series('IMPGSA') netExportsA = fp.series('A019RC1A027NBEA') deflatorA = fp.series('A191RD3A086NBEA') depreciationA = fp.series('Y0000C1A027NBEA') gdpA = fp.series('GDPA') tfpA = fp.series('GDPA') capitalA = fp.series('GDPA') laborA = fp.series('B4701C0A222NBEA')# BEA index: fred('HOANBS') / .quartertoannual(method='AVG') # annualfp.series = [investmentA,consumptionA,governmentA,exportsA,importsA,netExportsA,deflatorA,depreciationA,gdpA,tfpA,capitalA,laborA] investmentA,consumptionA,governmentA,netExportsA,exportsA,importsA,deflatorA,depreciationA,gdpA,tfpA,capitalA,laborA = fp.window_equalize([investmentA,consumptionA,governmentA,netExportsA,exportsA,importsA,deflatorA,depreciationA,gdpA,tfpA,capitalA,laborA]) # 2.2 Compute real annual data fp.series investmentA.data= 100*investmentA.data/deflatorA.data consumptionA.data = 100*consumptionA.data/deflatorA.data governmentA.data = 100*governmentA.data/deflatorA.data exportsA.data = 100*exportsA.data/deflatorA.data importsA.data = 100*importsA.data/deflatorA.data netExportsA.data = 100*netExportsA.data/deflatorA.data gdpA.data= 100*gdpA.data/deflatorA.data TA = len(investmentA.data) # 2.3 Convert labor from millions of hours to billions laborA.data = laborA.data/1000 # 2.4 Quarterly data investmentQ = fp.series('GPDI') investmentQ4 = fp.series('GPDI') consumptionQ = fp.series('PCEC') governmentQ = fp.series('GCE') exportsQ = fp.series('EXPGS') importsQ = fp.series('IMPGS') netExportsQ = fp.series('NETEXP') deflatorQ = fp.series('GDPDEF') gdpQ = fp.series('GDP') tfpQ = fp.series('GDP') capitalQ = fp.series('GDP') laborQ = fp.series('HOANBS') # L = fred('B4701C0A222NBEA') # quarterlyfp.series = [investmentQ,investmentQ4,consumptionQ,governmentQ,exportsQ,importsQ,netExportsQ,deflatorQ,gdpQ,tfpQ,capitalQ,laborQ] investmentQ,investmentQ4,consumptionQ,governmentQ,netExportsQ,exportsQ,importsQ,deflatorQ,gdpQ,tfpQ,capitalQ,laborQ = fp.window_equalize([investmentQ,investmentQ4,consumptionQ,governmentQ,netExportsQ,exportsQ,importsQ,deflatorQ,gdpQ,tfpQ,capitalQ,laborQ]) # 2.5 Compute real annual data fp.series investmentQ.data= 100*investmentQ.data/deflatorQ.data investmentQ4.data= 100*investmentQ4.data/deflatorQ.data consumptionQ.data = 100*consumptionQ.data/deflatorQ.data governmentQ.data = 100*governmentQ.data/deflatorQ.data netExportsQ.data = 100*netExportsQ.data/deflatorQ.data exportsQ.data = 100*exportsQ.data/deflatorQ.data importsQ.data = 100*importsQ.data/deflatorQ.data gdpQ.data= 100*gdpQ.data/deflatorQ.data TQ = len(investmentQ.data) # 2.6 Compute real annual data fp.series. Note that investment is at a quarterly rate investmentQ4.data= investmentQ.data/4 realGdpQ= 100*gdpQ.data/deflatorQ.data # 2.7 Find the base year for the deflator: baseYear = deflatorA.units[6:10] laborBaseYear= laborQ.units[6:10] # In[ ]: # 3. Parameter calibration using the annual series # 3.1 Use Y = C + I as the measure for output if that was requested above if output_solow == True: y0A= consumptionA.data+investmentA.data gdpA.data = y0A y0Q = consumptionQ.data+investmentQ.data gdpQ.data = y0Q # 3.2 form the ratios of depreciation and investment to output # depreciationYRatio= np.mean([d/y for d,y in zip(depreciationA.data,gdpA.data)]) iYRatio = np.mean(investmentA.data/gdpA.data) # 3.3 compute the annual growth rates of output and investment growthY = (gdpA.data[-1]/gdpA.data[0])**(1/(TA-1))-1 growthI = (investmentA.data[-1]/investmentA.data[0])**(1/(TA-1))-1 growthL = (laborA.data[-1]/laborA.data[0])**(1/(TA-1))-1 g = growthY n = growthL # 3.4 Compute delta based on requirement that K/Y = 2.5 delta = iYRatio/2.5-g-n # 3.5 print the computed rates for inspection print('gI:' ,growthI) print('gY:' ,growthY) print('gL:' ,growthL) print('delta:',delta) print('s:', iYRatio) print('g:', g) # In[ ]: # 4. Implement the perpetual inventory method # 4.1 Annual capital series k0A = gdpA.data[0]*iYRatio/(delta + g + n) capitalA.data = capitalSeries(investmentA.data,k0A,delta) # 4.2 Quarterly capital series k0Q = gdpQ.data[0]*iYRatio/(delta + g + n) capitalQ.data = capitalSeries(investmentQ4.data,k0Q,delta/4) # In[ ]: # 5. Plot the capital series. Note that the annual and quarterly series should and do align approximately. fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.plot_date(capitalA.datetimes,capitalA.data/1000,'b-',lw = 3) ax.plot_date(capitalQ.datetimes,capitalQ.data/1000,'r-',lw = 3) ax.xaxis.set_major_locator(years10) ax.set_ylabel('Trillions of \n '+baseYear+' $') capitalA.recessions() fig.autofmt_xdate() plt.title('Capital Stock') ax.legend(['Annual','Quarterly'],loc='upper left') ax.grid(True) # plt.savefig('fig_US_Production_Capital_QA.png',bbox_inches='tight') fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.plot_date(capitalA.datetimes,capitalA.data/1000,'b-',lw = 3) ax.xaxis.set_major_locator(years10) ax.set_ylabel('Trillions of \n '+baseYear+' $') capitalA.recessions() fig.autofmt_xdate() plt.title('Capital Stock: Annual') ax.grid(True) # plt.savefig('fig_US_Production_Capital_A.png',bbox_inches='tight') fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.plot_date(capitalQ.datetimes,capitalQ.data/1000,'b-',lw = 3) ax.xaxis.set_major_locator(years10) ax.set_ylabel('Trillions of \n '+baseYear+' $') capitalA.recessions() fig.autofmt_xdate() plt.title('Capital Stock: Quarterly') ax.grid(True) # plt.savefig('../img/fig_US_Production_Capital_A.png',bbox_inches='tight') # In[ ]: # 6. Save data to csv files # 6.1 Annual data YearA = [a[0:4] for a in capitalA.dates] OutputA = [round(x,1) for x in gdpA.data] ConsumptionA= [round(x,1) for x in consumptionA.data] InvestmentA = [round(x,1) for x in investmentA.data] GovernmentA = [round(x,1) for x in governmentA.data] ImportsA = [round(x,1) for x in importsA.data] ExportsA = [round(x,1) for x in exportsA.data] NetExportsA = [round(x,1) for x in netExportsA.data] CapitalA = [round(x,1) for x in capitalA.data] LaborA = [round(x,4) for x in laborA.data] columnsA = ['Year','GDP [Bil. of '+baseYear+' Dollars]','Consumption [Bil. of '+baseYear+' Dollars]','Investment [Bil. of '+baseYear+' Dollars]','Government Purchases [Bil. of '+baseYear+' Dollars]','Exports [Bil. of '+baseYear+' Dollars]','Imports [Bil. of '+baseYear+' Dollars]','Net Exports [Bil. of '+baseYear+' Dollars]','Capital [Bil. of '+baseYear+' Dollars]','Labor [Bil. of Hours]'] df = pd.DataFrame({ 'Year':YearA, 'GDP [Bil. of '+baseYear+' Dollars]':OutputA, 'Consumption [Bil. of '+baseYear+' Dollars]':ConsumptionA, 'Investment [Bil. of '+baseYear+' Dollars]':InvestmentA, 'Government Purchases [Bil. of '+baseYear+' Dollars]':GovernmentA, 'Exports [Bil. of '+baseYear+' Dollars]':ExportsA, 'Imports [Bil. of '+baseYear+' Dollars]':ImportsA, 'Net Exports [Bil. of '+baseYear+' Dollars]':NetExportsA, 'Capital [Bil. of '+baseYear+' Dollars]':CapitalA, 'Labor [Bil. of Hours]':LaborA}) df = df[columnsA] df.to_csv('../csv/US_Production_A_Data.csv',index=False) # 6.2 Quarterly data DateQ = [a for a in capitalQ.dates] OutputQ = [round(x,1) for x in gdpQ.data] ConsumptionQ= [round(x,1) for x in consumptionQ.data] InvestmentQ = [round(x,1) for x in investmentQ.data] GovernmentQ = [round(x,1) for x in governmentQ.data] ImportsQ = [round(x,1) for x in importsQ.data] ExportsQ = [round(x,1) for x in exportsQ.data] NetExportsQ = [round(x,1) for x in netExportsQ.data] CapitalQ = [round(x,1) for x in capitalQ.data] LaborQ = [round(x,1) for x in laborQ.data] columnsQ = ['Date','GDP [Bil. of '+baseYear+' Dollars]','Consumption [Bil. of '+baseYear+' Dollars]','Investment [Bil. of '+baseYear+' Dollars]','Government Purchases [Bil. of '+baseYear+' Dollars]','Exports [Bil. of '+baseYear+' Dollars]','Imports [Bil. of '+baseYear+' Dollars]','Net Exports [Bil. of '+baseYear+' Dollars]','Capital [Bil. of '+baseYear+' Dollars]','Labor [Index: '+laborBaseYear+'=100]'] df = pd.DataFrame({ 'Date':DateQ, 'GDP [Bil. of '+baseYear+' Dollars]':OutputQ, 'Consumption [Bil. of '+baseYear+' Dollars]':ConsumptionQ, 'Investment [Bil. of '+baseYear+' Dollars]':InvestmentQ, 'Government Purchases [Bil. of '+baseYear+' Dollars]':GovernmentQ, 'Exports [Bil. of '+baseYear+' Dollars]':ExportsQ, 'Imports [Bil. of '+baseYear+' Dollars]':ImportsQ, 'Net Exports [Bil. of '+baseYear+' Dollars]':NetExportsQ, 'Capital [Bil. of '+baseYear+' Dollars]':CapitalQ, 'Labor [Index: '+laborBaseYear+'=100]':LaborQ}) df = df[columnsQ] df.to_csv('../csv/US_Production_Q_Data.csv',index=False) # In[ ]: # 7. Compute the Solow residuals: # 7.1 Annual residual capitalA = capitalA.apc() tfpA = tfpA.apc() laborA = laborA.apc() gdpA = gdpA.apc() consumptionA = consumptionA.apc() investmentA = investmentA.apc() governmentA = governmentA.apc() exportsA = exportsA.apc() importsA = importsA.apc() # netExportsA = netExportsA.apc() gYA = gdpA.data gLA = laborA.data gKA = capitalA.data tfpA.data = gYA - alpha*gKA - (1-alpha)*gLA # 7.2. Compute the Solow residual: Quarterly capitalQ = capitalQ.apc() tfpQ = tfpQ.apc() laborQ = laborQ.apc() gdpQ = gdpQ.apc() consumptionQ = consumptionQ.apc() investmentQ = investmentQ.apc() governmentQ = governmentQ.apc() exportsQ = exportsQ.apc() importsQ = importsQ.apc() netExportsQ.data = np.array(netExportsQ.data) # netExportsQ = netExportsQ.apc() gYQ = gdpQ.data gLQ = laborQ.data gKQ = capitalQ.data tfpQ.data = gYQ - alpha*gKQ - (1-alpha)*gLQ # In[ ]: # 11. Construct some plots fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.plot_date(gdpA.datetimes,gdpA.data,'b-',lw = 3) ax.plot_date(tfpA.datetimes,tfpA.data,'g-',lw = 3) ax.xaxis.set_major_locator(years10) ax.set_ylabel('%') gdpA.recessions() fig.autofmt_xdate() ax.grid(True) ax.legend(['GDP growth','Solow Residual'],bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=3, mode="expand", borderaxespad=0.,fontsize=15) # plt.savefig('fig_US_Production_ya_growth_A.png',bbox_inches='tight') # 11.2 Figure for website: Annual growth in Y, L, K, and A fig = plt.figure(figsize=(10, 6)) ax = fig.add_subplot(2,2,1) ax.plot_date(tfpA.datetimes,tfpA.data,'b-',lw = 3,alpha = 0.75) ax.set_title('TFP Growth') ax.xaxis.set_major_locator(years10) ax.set_ylabel('%') tfpA.recessions() fig.autofmt_xdate() ax.locator_params(axis='y',nbins=6) ax.grid(True) ax = fig.add_subplot(2,2,2) ax.plot_date(gdpA.datetimes,gdpA.data,'b-',lw = 3,alpha = 0.75) ax.set_title('Real GDP Growth') ax.xaxis.set_major_locator(years10) ax.locator_params(axis='y',nbins=6) gdpA.recessions() fig.autofmt_xdate() ax.grid(True) ax = fig.add_subplot(2,2,3) ax.plot_date(laborA.datetimes,laborA.data,'b-',lw = 3,alpha = 0.75) ax.xaxis.set_major_locator(years10) laborA.recessions() ax.set_ylabel('%') ax.set_title('Labor Growth') ax.locator_params(axis='y',nbins=6) fig.autofmt_xdate() ax.grid(True) ax = fig.add_subplot(2,2,4) ax.plot_date(capitalA.datetimes,capitalA.data,'b-',lw = 3,alpha = 0.75) ax.xaxis.set_major_locator(years10) ax.set_title('Capital Growth') ax.locator_params(axis='y',nbins=6) capitalA.recessions() fig.autofmt_xdate() ax.grid(True) plt.savefig('../img/fig_US_Production_A_site.png',bbox_inches='tight') # 11.3 Quarterly GDP growth and the SOlow residual fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.plot_date(gdpQ.datetimes,gdpQ.data,'b-',lw = 3) ax.plot_date(tfpQ.datetimes,tfpQ.data,'g-',lw = 3) ax.xaxis.set_major_locator(years10) ax.set_ylabel('%') gdpQ.recessions() fig.autofmt_xdate() ax.grid(True) ax.legend(['GDP growth','Solow Residual'],bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=3, mode="expand", borderaxespad=0.,fontsize=15) # plt.savefig('../img/fig_US_Production_ya_growth_Q.png',bbox_inches='tight') # In[ ]: # 10. Save growth rate data to csv files # 10.1 Annual data YearA = [a[0:4] for a in tfpA.dates] CapitalA = [round(x,1) for x in capitalA.data] LaborA = [round(x,1) for x in laborA.data] OutputA = [round(x,1) for x in gdpA.data] ConsumptionA = [round(x,1) for x in consumptionA.data] InvestmentA = [round(x,1) for x in investmentA.data] GovernmentA = [round(x,1) for x in governmentA.data] ExportsA = [round(x,1) for x in exportsA.data] ImportsA = [round(x,1) for x in importsA.data] NetExportsA = [round(x,1) for x in netExportsA.data] columnsA = ['Year','GDP Growth','Consumption Growth','Investment Growth','Government Purchases Growth','Exports Growth','Imports Growth','Capital Growth','Labor Growth'] data = [YearA,OutputA,ConsumptionA,InvestmentA,GovernmentA,ExportsA,ImportsA,CapitalA,LaborA] dA ={} for n,c in enumerate(columnsA): dA[columnsA[n]]=data[n] df = pd.DataFrame(dA) df = df[columnsA] df.to_csv('../csv/US_Production_A_Data_Growth_Rates.csv',index=False) # 10.2 Quarterly data DateQ = [a for a in tfpQ.dates] CapitalQ = [round(x,1) for x in capitalQ.data] LaborQ = [round(x,1) for x in laborQ.data] OutputQ = [round(x,1) for x in gdpQ.data] ConsumptionQ = [round(x,1) for x in consumptionQ.data] InvestmentQ = [round(x,1) for x in investmentQ.data] GovernmentQ = [round(x,1) for x in governmentQ.data] ExportsQ = [round(x,1) for x in exportsQ.data] ImportsQ = [round(x,1) for x in importsQ.data] NetExportsQ = [round(x,1) for x in netExportsQ.data] columnsQ = ['Year','GDP Growth','Consumption Growth','Investment Growth','Government Purchases Growth','Exports Growth','Imports Growth','Capital Growth','Labor Growth'] data = [DateQ,OutputQ,ConsumptionQ,InvestmentQ,GovernmentQ,ExportsQ,ImportsQ,CapitalQ,LaborQ] dQ ={} for n,c in enumerate(columnsQ): dQ[columnsQ[n]]=data[n] df = pd.DataFrame(dQ) df = df[columnsQ] df.to_csv('../csv/US_Production_Q_Data_Growth_Rates.csv',index=False) # In[ ]: # 11. Export notebook to python script progName = 'usProductionData' runProcs.exportNb(progName)
# -*- coding: utf-8 -*- """ Database interface for automated ACL queue. Used primarily by ``load_acl`` and ``acl``` commands for manipulating the work queue. >>> from trigger.acl.queue import Queue >>> q = Queue() >>> q.list() (('dc1-abc.net.aol.com', 'datacenter-protect'), ('dc2-abc.net.aol.com', 'datacenter-protect')) """ __author__ = 'Jathan McCollum' __maintainer__ = 'Jathan McCollum' __email__ = '[email protected]' __version__ = '2.0.1' import datetime import os import sys from trigger import exceptions from trigger.conf import settings from trigger.netdevices import NetDevices from trigger.utils import get_user from . import models # Globals QUEUE_NAMES = ('integrated', 'manual') # Exports __all__ = ('Queue',) # Classes class Queue(object): """ Interacts with firewalls database to insert/remove items into the queue. :param verbose: Toggle verbosity :type verbose: Boolean """ def __init__(self, verbose=True): self.nd = NetDevices() self.verbose = verbose self.login = get_user() def vprint(self, msg): """ Print something if ``verbose`` instance variable is set. :param msg: The string to print """ if self.verbose: print msg def get_model(self, queue): """ Given a queue name, return its DB model. :param queue: Name of the queue whose object you want """ return models.MODEL_MAP.get(queue, None) def create_task(self, queue, *args, **kwargs): """ Create a task in the specified queue. :param queue: Name of the queue whose object you want """ model = self.get_model(queue) taskobj = model.create(*args, **kwargs) def _normalize(self, arg, prefix=''): """ Remove ``prefix`` from ``arg``, and set "escalation" bit. :param arg: Arg (typically an ACL filename) to trim :param prefix: Prefix to trim from arg """ if arg.startswith(prefix): arg = arg[len(prefix):] escalation = False if arg.upper().endswith(' ESCALATION'): escalation = True arg = arg[:-11] return (escalation, arg) def insert(self, acl, routers, escalation=False): """ Insert an ACL and associated devices into the ACL load queue. Attempts to insert into integrated queue. If ACL test fails, then item is inserted into manual queue. :param acl: ACL name :param routers: List of device names :param escalation: Whether this is an escalated task """ if not acl: raise exceptions.ACLQueueError('You must specify an ACL to insert into the queue') if not routers: routers = [] escalation, acl = self._normalize(acl) if routers: for router in routers: try: dev = self.nd.find(router) except KeyError: msg = 'Could not find device %s' % router raise exceptions.TriggerError(msg) if acl not in dev.acls: msg = "Could not find %s in ACL list for %s" % (acl, router) raise exceptions.TriggerError(msg) self.create_task(queue='integrated', acl=acl, router=router, escalation=escalation) self.vprint('ACL %s injected into integrated load queue for %s' % (acl, ', '.join(dev[:dev.find('.')] for dev in routers))) else: self.create_task(queue='manual', q_name=acl, login=self.login) self.vprint('"%s" injected into manual load queue' % acl) def delete(self, acl, routers=None, escalation=False): """ Delete an ACL from the firewall database queue. Attempts to delete from integrated queue. If ACL test fails or if routers are not specified, the item is deleted from manual queue. :param acl: ACL name :param routers: List of device names. If this is ommitted, the manual queue is used. :param escalation: Whether this is an escalated task """ if not acl: raise exceptions.ACLQueueError('You must specify an ACL to delete from the queue') escalation, acl = self._normalize(acl) m = self.get_model('integrated') if routers is not None: devs = routers else: self.vprint('Fetching routers from database') result = m.select(m.router).distinct().where( m.acl == acl, m.loaded >> None).order_by(m.router) rows = result.tuples() devs = [row[0] for row in rows] if devs: for dev in devs: m.delete().where(m.acl == acl, m.router == dev, m.loaded >> None).execute() self.vprint('ACL %s cleared from integrated load queue for %s' % (acl, ', '.join(dev[:dev.find('.')] for dev in devs))) return True else: m = self.get_model('manual') if m.delete().where(m.q_name == acl, m.done == False).execute(): self.vprint('%r cleared from manual load queue' % acl) return True self.vprint('%r not found in any queues' % acl) return False def complete(self, device, acls): """ Mark a device and its ACLs as complete using current timestamp. (Integrated queue only.) :param device: Device names :param acls: List of ACL names """ m = self.get_model('integrated') for acl in acls: now = loaded=datetime.datetime.now() m.update(loaded=now).where(m.acl == acl, m.router == device, m.loaded >> None).execute() self.vprint('Marked the following ACLs as complete for %s:' % device) self.vprint(', '.join(acls)) def remove(self, acl, routers, escalation=False): """ Integrated queue only. Mark an ACL and associated devices as "removed" (loaded=0). Intended for use when performing manual actions on the load queue when troubleshooting or addressing errors with automated loads. This leaves the items in the database but removes them from the active queue. :param acl: ACL name :param routers: List of device names :param escalation: Whether this is an escalated task """ if not acl: raise exceptions.ACLQueueError('You must specify an ACL to remove from the queue') m = self.get_model('integrated') loaded = 0 if settings.DATABASE_ENGINE == 'postgresql': loaded = '-infinity' # See: http://bit.ly/15f0J3z for router in routers: m.update(loaded=loaded).where(m.acl == acl, m.router == router, m.loaded >> None).execute() self.vprint('Marked the following devices as removed for ACL %s: ' % acl) self.vprint(', '.join(routers)) def list(self, queue='integrated', escalation=False, q_names=QUEUE_NAMES): """ List items in the specified queue, defauls to integrated queue. :param queue: Name of the queue to list :param escalation: Whether this is an escalated task :param q_names: (Optional) List of valid queue names """ if queue not in q_names: self.vprint('Queue must be one of %s, not: %s' % (q_names, queue)) return False m = self.get_model(queue) if queue == 'integrated': result = m.select(m.router, m.acl).distinct().where( m.loaded >> None, m.escalation == escalation) elif queue == 'manual': result = m.select(m.q_name, m.login, m.q_ts, m.done).where( m.done == False) else: raise RuntimeError('This should never happen!!') all_data = list(result.tuples()) return all_data
#!/usr/bin/python """ Data Manager Frame Copyright (c) 2014, 2015 Andrew Hawkins 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 Declarations """ import sqlite3 import wx from forsteri.interface import sql as isql """ Constant Declarations """ ID_HIERARCHY = 45 ID_VARIABLE = 46 """ Panel Class """ class ManagerPanel(wx.Panel): """ A panel that contains a combo box selection and a list control. This is allows for adding, editing, and deleting some variable held in the HDF5 file. Extends: wx.Panel """ def __init__(self, id, connection, *args, **kwargs): """ Initialize the panel. Args: parent (wx.Frame): The associated parent for this panel. id (int): The ID for the panel which defines what will be edited. This can currently be ID_HIERARCHY or ID_VARIABLE. As the software expands, so will the possibilities. connection (sqlite3.Connection): A connection to the database. Returns: ManagerPanel To Do: Find a better way to handle the IDs. """ ## Panel # Initialize by the parent's constructor. super(ManagerPanel, self).__init__(*args, **kwargs) # Set the ID for the panel. self.id = id # Create the master sizer. masterSizer = wx.BoxSizer(wx.VERTICAL) # Create a static connection. self.connection = connection ## Combo Box # Get the combo box choices. choices = self.getChoices() # Create the label and input box. self.combo = wx.ComboBox(self, choices=choices, style=wx.CB_READONLY|wx.CB_SORT) # Set the initial selection to be the first item. self.combo.SetSelection(0) # Bind the combo box selection to a function. self.combo.Bind(wx.EVT_COMBOBOX, self.updateList) ## List Control # Create the list control. self.itemList = wx.ListCtrl(self, size=(-1, 200), style=wx.BORDER_SUNKEN|wx.LC_REPORT|wx.LC_HRULES|wx.LC_VRULES) # Add the title column. self.itemList.InsertColumn(0, "Title", width=500) # Bind the selection of an item to a function. self.itemList.Bind(wx.EVT_LIST_ITEM_SELECTED, self.onSelected) self.itemList.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.onSelected) self.itemList.Bind(wx.EVT_LEFT_DCLICK, self.onEdit) ## Manipulate Buttons # Create the manipulate sizer. manipSizer = wx.BoxSizer(wx.HORIZONTAL) # Create the buttons. addButton = wx.Button(self, id=wx.ID_ADD) self.editButton = wx.Button(self, id=wx.ID_EDIT) self.deleteButton = wx.Button(self, id=wx.ID_DELETE) # Add the buttons to the manipulate sizer. manipSizer.AddMany([addButton, (5, 0), self.editButton, (5, 0), self.deleteButton]) # Bind button presses to functions. addButton.Bind(wx.EVT_BUTTON, self.onAdd) self.editButton.Bind(wx.EVT_BUTTON, self.onEdit) self.deleteButton.Bind(wx.EVT_BUTTON, self.onDelete) ## Key Bindings # Create a new id for selecting all. selectAllId = wx.NewId() # Bind the id to a function. self.Bind(wx.EVT_MENU, self.selectAll, id=selectAllId) # Create a new accelerator table and set it to the frame. accelT = wx.AcceleratorTable([(wx.ACCEL_CTRL, ord("A"), selectAllId)]) self.SetAcceleratorTable(accelT) ## Frame Operations # Add everything to the master sizer. masterSizer.AddSpacer(5) masterSizer.Add(self.combo, flag=wx.ALIGN_CENTER) masterSizer.AddSpacer(10) masterSizer.Add(self.itemList, flag=wx.LEFT|wx.RIGHT|wx.EXPAND, border=5) masterSizer.AddSpacer(10) masterSizer.Add(manipSizer, flag=wx.ALIGN_CENTER) masterSizer.AddSpacer(5) # Update the list display. self.updateList(None) # Set the sizer for the master panel. self.SetSizer(masterSizer) """ Helper Functions """ def getChoices(self): """ Get the combo box choices depending on the ID. Args: None Returns: list of str: The possible choices for the combo box with regard to the defined ID. """ # Pull the possible tiers from the database. if self.id == ID_HIERARCHY: return isql.getTiers(self.connection) else: return isql.getVariables(self.connection) """ Event Handler Functions """ def updateList(self, event): """ Update the items displayed in the list control. Args: event (wx._core.CommandEvent): The triggered event after completing some action that would alter the items in the list control. Returns: None """ # Reset the edit and delete buttons. self.editButton.Enable() self.deleteButton.SetBackgroundColour(wx.NullColour) # Get the list for the selected tier. if self.id == ID_HIERARCHY: items = isql.getForTier(self.combo.GetStringSelection(), self.connection) else: items = isql.getForVariable(self.combo.GetStringSelection(), self.connection) # Sort the items in ascending order. items.sort() # Remove all items from the list control. self.itemList.DeleteAllItems() # Add the items to the list control. index = 0 for item in items: self.itemList.InsertStringItem(index, item) index += 1 def selectAll(self, event): """ What to do when the "Ctrl+A" button combination is entered. Select all items in the list control. Args: event (wx._core.CommandEvent): The triggered event after the button combo "Ctrl+A" is entered. Returns: None """ # Iterate through the items in the list selecting each. for i in range(0, self.itemList.GetItemCount()): self.itemList.Select(i) def onSelected(self, event): """ What to do when items in the list control are selected. Reset the color of the buttons if only one item is selected. If multiple items are selected, disable the edit button and set the delete button to be yellow. Args: event (wx._core.CommandEvent): The triggered event after an item in the list control is selected. Returns: None """ # If multiple products are selected, set the edit and delete buttons # to be yellow. if self.itemList.GetSelectedItemCount() > 1: self.editButton.Disable() self.deleteButton.SetBackgroundColour("Yellow") # If only one product is selected, set the edit and delete buttons # to be the default color. else: self.editButton.Enable() self.deleteButton.SetBackgroundColour(wx.NullColour) def onAdd(self, event): """ What to do when the add button is pressed. Open the text entry dialog and obtain the title of the new item. Write the new item into the HDF5 file. Args: event (wx._core.CommandEvent): The triggered event when the add button is pressed. Returns: None """ # Create the text entry dialog box. dialog = wx.TextEntryDialog(self, "What is the name of the item?", "New Item") # If OK is not pressed, return false. if dialog.ShowModal() != wx.ID_OK: return False # Get the new item value. newItem = dialog.GetValue() # If an empty string is input, return false. if newItem == "": return False # Destroy the dialog box. dialog.Destroy() # Add the inputted text to the database. if self.id == ID_HIERARCHY: isql.addTitle(self.combo.GetStringSelection(), newItem, self.connection) else: isql.addAlias(self.combo.GetStringSelection(), newItem, self.connection) # Update the list. self.updateList(None) def onEdit(self, event): """ What to do when the edit button is pressed. Open the text entry dialog and fill it with what the current title is. Obtain the altered title for the item. Write the altered item into the HDF5 file. Args: event (wx._core.CommandEvent): The triggered event when the edit button is pressed. Returns: None """ # Get the selected item index from the list. itemIndex = self.itemList.GetFirstSelected() # Send an error if nothing is selected. if itemIndex == -1: errorDialog = wx.MessageDialog(self, "No item was selected.", "Error", wx.OK|wx.ICON_ERROR) errorDialog.ShowModal() return False # Get the string value of the old item. oldItem = self.itemList.GetItemText(itemIndex) # Create the text entry dialog box. dialog = wx.TextEntryDialog(self, "What is the name of the item?", "Edit Item", oldItem) # If OK is not pressed, return false. if dialog.ShowModal() != wx.ID_OK: return False # Get the new item value. newItem = dialog.GetValue() # If an empty string is input or there is no change, return false. if newItem == "" or newItem == oldItem: return False # Destroy the dialog box. dialog.Destroy() # Get the selected combo box item. selection = self.combo.GetStringSelection() if self.id == ID_HIERARCHY: # Set the new item in the database. isql.setTitle(selection, oldItem, newItem, self.connection) else: # Set the new item in the database. isql.setAlias(selection, oldItem, newItem, self.connection) # Update the list. self.updateList(None) def onDelete(self, event): """ What to do when the delete button is pressed. Remove the selected item in the list control from the HDF5 file. Args: event (wx._core.CommandEvent): The triggered event when the delete button is pressed. Returns: None """ # Get the first selected item index from the list. itemIndex = self.itemList.GetFirstSelected() # Send an error if nothing is selected. if itemIndex == -1: errorDialog = wx.MessageDialog(self, "No item was selected.", "Error", wx.OK|wx.ICON_ERROR) errorDialog.ShowModal() return False # Get the number of selected products. count = self.itemList.GetSelectedItemCount() # Create the delete confimation dialog box. confirmDialog = wx.MessageDialog(self, "You are about to delete " + str(count) + " item(s). Continue?", "Delete Confirmation", wx.YES_NO) # If no is selected, return false. if confirmDialog.ShowModal() != wx.ID_YES: return False # Remove all selected items. selection = self.combo.GetStringSelection() for i in range(0, self.itemList.GetSelectedItemCount()): # Get the item text. item = self.itemList.GetItemText(itemIndex) if self.id == ID_HIERARCHY: # Remove the selected item. isql.removeTitle(selection, item, self.connection) else: # Remove the selected item. isql.removeAlias(selection, item, self.connection) # Get the next selected item index. itemIndex = self.itemList.GetNextSelected(itemIndex) # Update the list. self.updateList(None) """ Notebook Class """ class ManagerNotebook(wx.Notebook): """ A notebook that holds the possible panels. Extends: wx.Notebook """ def __init__(self, connection, *args, **kwargs): """ Initialize the notebook. Args: *args (): Any arguments to be passed directly to the super's constructor. **kwargs (): Any keyword arguments to be passed to the super's constructor. Returns: ManagerNotebook """ # Initialize by the parent's constructor. super(ManagerNotebook, self).__init__(*args, **kwargs) # Create the hierarchy tab. hierarchy = ManagerPanel(ID_HIERARCHY, connection, self) # Add the hierarchy page to the notebook. self.AddPage(hierarchy, "Hierarchy") # Create the variable tab. variable = ManagerPanel(ID_VARIABLE, connection, self) # Add the manager page to the notebook. self.AddPage(variable, "Input Variable") # Bind tab seletion to functions. self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.onPageChange) """ Event Handler Functions """ def onPageChange(self, event): """ What to do when a new page has been selected. Args: event (wx._core.CommandEvent): The triggered event when a new page is selected. Returns: None """ # Skip the event. event.Skip() """ Frame Class """ class ManagerFrame(wx.Frame): """ The frame that contains the notebook and all panels. The "OK", "Apply", and "Cancel" buttons are housed here. Extends: wx.Frame """ def __init__(self, *args, **kwargs): """ Initialize the frame. Args: *args (): Any arguments to be passed directly to the super's constructor. **kwargs (): Any keyword arguments to be passed to the super's constructor. Returns: ManagerFrame """ """Initialize the frame.""" # Initialize by the parent's constructor. super(ManagerFrame, self).__init__(*args, **kwargs) # Create the master panel. masterPanel = wx.Panel(self) # Create the master sizer. masterSizer = wx.BoxSizer(wx.VERTICAL) # Open a connection to the database. self.connection = sqlite3.connect(isql.MASTER) """Initialize the notebook panel.""" # Create the notebook. notebook = ManagerNotebook(self.connection, masterPanel) """Initialize the finish buttons.""" # Create the finish sizer. finishSizer = wx.BoxSizer(wx.HORIZONTAL) # Create the buttons. okButton = wx.Button(masterPanel, id=wx.ID_OK) applyButton = wx.Button(masterPanel, id=wx.ID_APPLY) cancelButton = wx.Button(masterPanel, id=wx.ID_CANCEL) # Set the OK button to be the dafault button. okButton.SetDefault() # Add the buttons to the finish sizer. finishSizer.AddMany([okButton, (5, 0), applyButton, (5, 0), cancelButton, (5, 0)]) # Bind button presses to functions. okButton.Bind(wx.EVT_BUTTON, self.onOK) applyButton.Bind(wx.EVT_BUTTON, self.onApply) cancelButton.Bind(wx.EVT_BUTTON, self.onCancel) """Final frame operations.""" # Add everything to the master sizer. masterSizer.Add(notebook, 1, wx.ALL|wx.EXPAND, 5) masterSizer.Add(finishSizer, flag=wx.ALIGN_RIGHT) masterSizer.AddSpacer(5) # Set the sizer for the master panel. masterPanel.SetSizer(masterSizer) # Bind closing the frame to a function. self.Bind(wx.EVT_CLOSE, self.onClose) # Set window properties. self.SetSize((600, 400)) self.SetTitle("Data Manager") self.Centre() self.Show(True) """ Event Handler Functions """ def onOK(self, event): """ What to do when the OK button has been pressed. Remove the HDF5 copy file from the filesystem. Args: event (wx._core.CommandEvent): The triggered event when a new page is selected. Returns: None """ # Commit and close the database. self.connection.commit() self.connection.close() # Close the window. self.Close() def onApply(self, event): """ What to do when the Apply button has been pressed. Make a new copy of the HDF5 file in the filesystem. Args: event (wx._core.CommandEvent): The triggered event when a new page is selected. Returns: None """ # Commit the database. self.connection.commit() def onCancel(self, event): """ What to do when the Cancel button has been pressed. Replace the HDF5 file with the copy made in the filesystem. Args: event (wx._core.CommandEvent): The triggered event when a new page is selected. Returns: None """ # Close the database. self.connection.close() # Close the window. self.Close() def onClose(self, event): """ What to do when the frame is closed. If a copy still exists, replace the HDF5 file with the copy in the filesystem. Args: event (wx._core.CommandEvent): The triggered event when a new page is selected. Returns: None """ # Close the database. self.connection.close() # Destroy the window. self.Destroy() def main(): """ When the file is called independently create and display the manager frame. """ app = wx.App() ManagerFrame(None, title="Data Manager", size=(600, 400), style=wx.DEFAULT_FRAME_STYLE^wx.RESIZE_BORDER) app.MainLoop() if __name__ == '__main__': main()
# Copyright 2016 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. # ============================================================================== """Tests for slim.learning.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tempfile import numpy as np from numpy import testing as np_testing from tensorflow.contrib.framework.python.ops import variables as variables_lib2 from tensorflow.contrib.layers.python.layers import layers from tensorflow.contrib.losses.python.losses import loss_ops from tensorflow.contrib.slim.python.slim import learning from tensorflow.core.protobuf import config_pb2 from tensorflow.python.client import session from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import random_seed from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import variables as variables_lib from tensorflow.python.platform import test from tensorflow.python.summary import summary from tensorflow.python.training import gradient_descent from tensorflow.python.training import input as input_lib from tensorflow.python.training import saver as saver_lib class ClipGradientNormsTest(test.TestCase): def clip_values(self, arr): norm = np.sqrt(np.sum(arr**2)) if norm > self._max_norm: return self._max_norm * arr / np.sqrt(np.sum(arr**2)) return arr def setUp(self): np.random.seed(0) self._max_norm = 1.0 self._grad_vec = np.array([1., 2., 3.]) self._clipped_grad_vec = self.clip_values(self._grad_vec) self._zero_vec = np.zeros(self._grad_vec.size) def testOrdinaryGradIsClippedCorrectly(self): gradient = constant_op.constant(self._grad_vec, dtype=dtypes.float32) variable = variables_lib.Variable(self._zero_vec, dtype=dtypes.float32) gradients_to_variables = (gradient, variable) [gradients_to_variables] = learning.clip_gradient_norms( [gradients_to_variables], self._max_norm) # Ensure the variable passed through. self.assertEqual(gradients_to_variables[1], variable) with self.test_session() as sess: actual_gradient = sess.run(gradients_to_variables[0]) np_testing.assert_almost_equal(actual_gradient, self._clipped_grad_vec) def testNoneGradPassesThroughCorrectly(self): gradient = None variable = variables_lib.Variable(self._zero_vec, dtype=dtypes.float32) gradients_to_variables = (gradient, variable) [gradients_to_variables] = learning.clip_gradient_norms( [gradients_to_variables], self._max_norm) self.assertEqual(gradients_to_variables[0], None) self.assertEqual(gradients_to_variables[1], variable) def testIndexedSlicesGradIsClippedCorrectly(self): sparse_grad_indices = np.array([0, 1, 4]) sparse_grad_dense_shape = [self._grad_vec.size] values = constant_op.constant(self._grad_vec, dtype=dtypes.float32) indices = constant_op.constant(sparse_grad_indices, dtype=dtypes.int32) dense_shape = constant_op.constant( sparse_grad_dense_shape, dtype=dtypes.int32) gradient = ops.IndexedSlices(values, indices, dense_shape) variable = variables_lib.Variable(self._zero_vec, dtype=dtypes.float32) gradients_to_variables = (gradient, variable) gradients_to_variables = learning.clip_gradient_norms( [gradients_to_variables], self._max_norm)[0] # Ensure the built IndexedSlice has the right form. self.assertEqual(gradients_to_variables[1], variable) self.assertEqual(gradients_to_variables[0].indices, indices) self.assertEqual(gradients_to_variables[0].dense_shape, dense_shape) with session.Session() as sess: actual_gradient = sess.run(gradients_to_variables[0].values) np_testing.assert_almost_equal(actual_gradient, self._clipped_grad_vec) class MultiplyGradientsTest(test.TestCase): def setUp(self): np.random.seed(0) self._multiplier = 3.7 self._grad_vec = np.array([1., 2., 3.]) self._multiplied_grad_vec = np.multiply(self._grad_vec, self._multiplier) def testNonListGradsRaisesError(self): gradient = constant_op.constant(self._grad_vec, dtype=dtypes.float32) variable = variables_lib.Variable(array_ops.zeros_like(gradient)) grad_to_var = (gradient, variable) gradient_multipliers = {variable: self._multiplier} with self.assertRaises(ValueError): learning.multiply_gradients(grad_to_var, gradient_multipliers) def testEmptyMultiplesRaisesError(self): gradient = constant_op.constant(self._grad_vec, dtype=dtypes.float32) variable = variables_lib.Variable(array_ops.zeros_like(gradient)) grad_to_var = (gradient, variable) with self.assertRaises(ValueError): learning.multiply_gradients([grad_to_var], {}) def testNonDictMultiplierRaisesError(self): gradient = constant_op.constant(self._grad_vec, dtype=dtypes.float32) variable = variables_lib.Variable(array_ops.zeros_like(gradient)) grad_to_var = (gradient, variable) with self.assertRaises(ValueError): learning.multiply_gradients([grad_to_var], 3) def testMultipleOfNoneGradRaisesError(self): gradient = constant_op.constant(self._grad_vec, dtype=dtypes.float32) variable = variables_lib.Variable(array_ops.zeros_like(gradient)) grad_to_var = (None, variable) gradient_multipliers = {variable: self._multiplier} with self.assertRaises(ValueError): learning.multiply_gradients(grad_to_var, gradient_multipliers) def testMultipleGradientsWithVariables(self): gradient = constant_op.constant(self._grad_vec, dtype=dtypes.float32) variable = variables_lib.Variable(array_ops.zeros_like(gradient)) grad_to_var = (gradient, variable) gradient_multipliers = {variable: self._multiplier} [grad_to_var] = learning.multiply_gradients([grad_to_var], gradient_multipliers) # Ensure the variable passed through. self.assertEqual(grad_to_var[1], variable) with self.test_session() as sess: actual_gradient = sess.run(grad_to_var[0]) np_testing.assert_almost_equal(actual_gradient, self._multiplied_grad_vec, 5) def testIndexedSlicesGradIsMultiplied(self): values = constant_op.constant(self._grad_vec, dtype=dtypes.float32) indices = constant_op.constant([0, 1, 2], dtype=dtypes.int32) dense_shape = constant_op.constant( [self._grad_vec.size], dtype=dtypes.int32) gradient = ops.IndexedSlices(values, indices, dense_shape) variable = variables_lib.Variable(array_ops.zeros((1, 3))) grad_to_var = (gradient, variable) gradient_multipliers = {variable: self._multiplier} [grad_to_var] = learning.multiply_gradients([grad_to_var], gradient_multipliers) # Ensure the built IndexedSlice has the right form. self.assertEqual(grad_to_var[1], variable) self.assertEqual(grad_to_var[0].indices, indices) self.assertEqual(grad_to_var[0].dense_shape, dense_shape) with self.test_session() as sess: actual_gradient = sess.run(grad_to_var[0].values) np_testing.assert_almost_equal(actual_gradient, self._multiplied_grad_vec, 5) def testTensorMultiplierOfGradient(self): gradient = constant_op.constant(self._grad_vec, dtype=dtypes.float32) variable = variables_lib.Variable(array_ops.zeros_like(gradient)) multiplier_flag = variables_lib.Variable(True) tensor_multiplier = array_ops.where(multiplier_flag, self._multiplier, 1.0) grad_to_var = (gradient, variable) gradient_multipliers = {variable: tensor_multiplier} [grad_to_var] = learning.multiply_gradients([grad_to_var], gradient_multipliers) with self.test_session() as sess: sess.run(variables_lib.global_variables_initializer()) gradient_true_flag = sess.run(grad_to_var[0]) sess.run(multiplier_flag.assign(False)) gradient_false_flag = sess.run(grad_to_var[0]) np_testing.assert_almost_equal(gradient_true_flag, self._multiplied_grad_vec, 5) np_testing.assert_almost_equal(gradient_false_flag, self._grad_vec, 5) def LogisticClassifier(inputs): return layers.fully_connected(inputs, 1, activation_fn=math_ops.sigmoid) def BatchNormClassifier(inputs): inputs = layers.batch_norm(inputs, decay=0.1, fused=True) return layers.fully_connected(inputs, 1, activation_fn=math_ops.sigmoid) class TrainBNClassifierTest(test.TestCase): def setUp(self): # Create an easy training set: np.random.seed(0) self._inputs = np.zeros((16, 4)) self._labels = np.random.randint(0, 2, size=(16, 1)).astype(np.float32) for i in range(16): j = int(2 * self._labels[i] + np.random.randint(0, 2)) self._inputs[i, j] = 1 def testTrainWithNoInitAssignCanAchieveZeroLoss(self): logdir = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs') g = ops.Graph() with g.as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = BatchNormClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) loss = learning.train( train_op, logdir, number_of_steps=300, log_every_n_steps=10) self.assertLess(loss, .1) class CreateTrainOpTest(test.TestCase): def setUp(self): # Create an easy training set: np.random.seed(0) self._inputs = np.random.rand(16, 4).astype(np.float32) self._labels = np.random.randint(0, 2, size=(16, 1)).astype(np.float32) def _addBesselsCorrection(self, sample_size, expected_var): correction_factor = sample_size / (sample_size - 1) expected_var *= correction_factor return expected_var def testUseUpdateOps(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) expected_mean = np.mean(self._inputs, axis=(0)) expected_var = np.var(self._inputs, axis=(0)) expected_var = self._addBesselsCorrection(16, expected_var) tf_predictions = BatchNormClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) moving_mean = variables_lib2.get_variables_by_name('moving_mean')[0] moving_variance = variables_lib2.get_variables_by_name('moving_variance')[ 0] with session.Session() as sess: # Initialize all variables sess.run(variables_lib.global_variables_initializer()) mean, variance = sess.run([moving_mean, moving_variance]) # After initialization moving_mean == 0 and moving_variance == 1. self.assertAllClose(mean, [0] * 4) self.assertAllClose(variance, [1] * 4) for _ in range(10): sess.run([train_op]) mean = moving_mean.eval() variance = moving_variance.eval() # After 10 updates with decay 0.1 moving_mean == expected_mean and # moving_variance == expected_var. self.assertAllClose(mean, expected_mean) self.assertAllClose(variance, expected_var) def testEmptyUpdateOps(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = BatchNormClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer, update_ops=[]) moving_mean = variables_lib2.get_variables_by_name('moving_mean')[0] moving_variance = variables_lib2.get_variables_by_name('moving_variance')[ 0] with session.Session() as sess: # Initialize all variables sess.run(variables_lib.global_variables_initializer()) mean, variance = sess.run([moving_mean, moving_variance]) # After initialization moving_mean == 0 and moving_variance == 1. self.assertAllClose(mean, [0] * 4) self.assertAllClose(variance, [1] * 4) for _ in range(10): sess.run([train_op]) mean = moving_mean.eval() variance = moving_variance.eval() # Since we skip update_ops the moving_vars are not updated. self.assertAllClose(mean, [0] * 4) self.assertAllClose(variance, [1] * 4) def testUseGlobalStep(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = BatchNormClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) global_step = variables_lib2.get_or_create_global_step() with session.Session() as sess: # Initialize all variables sess.run(variables_lib.global_variables_initializer()) for _ in range(10): sess.run([train_op]) global_step = global_step.eval() # After 10 updates global_step should be 10. self.assertAllClose(global_step, 10) def testNoneGlobalStep(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = BatchNormClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op( total_loss, optimizer, global_step=None) global_step = variables_lib2.get_or_create_global_step() with session.Session() as sess: # Initialize all variables sess.run(variables_lib.global_variables_initializer()) for _ in range(10): sess.run([train_op]) global_step = global_step.eval() # Since train_op don't use global_step it shouldn't change. self.assertAllClose(global_step, 0) def testRecordTrainOpInCollection(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) # Make sure the training op was recorded in the proper collection self.assertTrue(train_op in ops.get_collection(ops.GraphKeys.TRAIN_OP)) class TrainTest(test.TestCase): def setUp(self): # Create an easy training set: np.random.seed(0) self._inputs = np.zeros((16, 4)) self._labels = np.random.randint(0, 2, size=(16, 1)).astype(np.float32) for i in range(16): j = int(2 * self._labels[i] + np.random.randint(0, 2)) self._inputs[i, j] = 1 def testTrainWithNonDefaultGraph(self): logdir = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs') g = ops.Graph() with g.as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) loss = learning.train( train_op, logdir, number_of_steps=300, log_every_n_steps=10, graph=g) self.assertIsNotNone(loss) self.assertLess(loss, .015) def testTrainWithNoneAsLogdir(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) loss = learning.train( train_op, None, number_of_steps=300, log_every_n_steps=10) self.assertIsNotNone(loss) self.assertLess(loss, .015) def testTrainWithSessionConfig(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) session_config = config_pb2.ConfigProto(allow_soft_placement=True) loss = learning.train( train_op, None, number_of_steps=300, log_every_n_steps=10, session_config=session_config) self.assertIsNotNone(loss) self.assertLess(loss, .015) def testTrainWithTrace(self): logdir = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs') with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() summary.scalar('total_loss', total_loss) optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) loss = learning.train( train_op, logdir, number_of_steps=300, log_every_n_steps=10, trace_every_n_steps=100) self.assertIsNotNone(loss) for trace_step in [1, 101, 201]: trace_filename = 'tf_trace-%d.json' % trace_step self.assertTrue(os.path.isfile(os.path.join(logdir, trace_filename))) def testTrainWithNoneAsLogdirWhenUsingSummariesRaisesError(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() summary.scalar('total_loss', total_loss) optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) summary_op = summary.merge_all() with self.assertRaises(ValueError): learning.train( train_op, None, number_of_steps=300, summary_op=summary_op) def testTrainWithNoneAsLogdirWhenUsingTraceRaisesError(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) with self.assertRaises(ValueError): learning.train( train_op, None, number_of_steps=300, trace_every_n_steps=10) def testTrainWithNoneAsLogdirWhenUsingSaverRaisesError(self): with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) saver = saver_lib.Saver() with self.assertRaises(ValueError): learning.train( train_op, None, init_op=None, number_of_steps=300, saver=saver) def testTrainWithNoneAsInitWhenUsingVarsRaisesError(self): logdir = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs') with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) with self.assertRaises(RuntimeError): learning.train(train_op, logdir, init_op=None, number_of_steps=300) def testTrainWithNoInitAssignCanAchieveZeroLoss(self): logdir = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs') with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) loss = learning.train( train_op, logdir, number_of_steps=300, log_every_n_steps=10) self.assertIsNotNone(loss) self.assertLess(loss, .015) def testTrainWithLocalVariable(self): logdir = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs') with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) local_multiplier = variables_lib2.local_variable(1.0) tf_predictions = LogisticClassifier(tf_inputs) * local_multiplier loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) loss = learning.train( train_op, logdir, number_of_steps=300, log_every_n_steps=10) self.assertIsNotNone(loss) self.assertLess(loss, .015) def testResumeTrainAchievesRoughlyTheSameLoss(self): logdir = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs') number_of_steps = [300, 301, 305] for i in range(len(number_of_steps)): with ops.Graph().as_default(): random_seed.set_random_seed(i) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) loss = learning.train( train_op, logdir, number_of_steps=number_of_steps[i], log_every_n_steps=10) self.assertIsNotNone(loss) self.assertLess(loss, .015) def create_train_op(self, learning_rate=1.0, gradient_multiplier=1.0): tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer( learning_rate=learning_rate) if gradient_multiplier != 1.0: variables = variables_lib.trainable_variables() gradient_multipliers = {var: gradient_multiplier for var in variables} else: gradient_multipliers = None return learning.create_train_op( total_loss, optimizer, gradient_multipliers=gradient_multipliers) def testTrainWithInitFromCheckpoint(self): logdir1 = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs1') logdir2 = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs2') # First, train the model one step (make sure the error is high). with ops.Graph().as_default(): random_seed.set_random_seed(0) train_op = self.create_train_op() loss = learning.train(train_op, logdir1, number_of_steps=1) self.assertGreater(loss, .5) # Next, train the model to convergence. with ops.Graph().as_default(): random_seed.set_random_seed(1) train_op = self.create_train_op() loss = learning.train( train_op, logdir1, number_of_steps=300, log_every_n_steps=10) self.assertIsNotNone(loss) self.assertLess(loss, .02) # Finally, advance the model a single step and validate that the loss is # still low. with ops.Graph().as_default(): random_seed.set_random_seed(2) train_op = self.create_train_op() model_variables = variables_lib.global_variables() model_path = os.path.join(logdir1, 'model.ckpt-300') init_op = variables_lib.global_variables_initializer() op, init_feed_dict = variables_lib2.assign_from_checkpoint( model_path, model_variables) def InitAssignFn(sess): sess.run(op, init_feed_dict) loss = learning.train( train_op, logdir2, number_of_steps=1, init_op=init_op, init_fn=InitAssignFn) self.assertIsNotNone(loss) self.assertLess(loss, .02) def testTrainWithInitFromFn(self): logdir1 = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs1') logdir2 = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs2') # First, train the model one step (make sure the error is high). with ops.Graph().as_default(): random_seed.set_random_seed(0) train_op = self.create_train_op() loss = learning.train(train_op, logdir1, number_of_steps=1) self.assertGreater(loss, .5) # Next, train the model to convergence. with ops.Graph().as_default(): random_seed.set_random_seed(1) train_op = self.create_train_op() loss = learning.train( train_op, logdir1, number_of_steps=300, log_every_n_steps=10) self.assertIsNotNone(loss) self.assertLess(loss, .015) # Finally, advance the model a single step and validate that the loss is # still low. with ops.Graph().as_default(): random_seed.set_random_seed(2) train_op = self.create_train_op() model_variables = variables_lib.global_variables() model_path = os.path.join(logdir1, 'model.ckpt-300') saver = saver_lib.Saver(model_variables) def RestoreFn(sess): saver.restore(sess, model_path) loss = learning.train( train_op, logdir2, number_of_steps=1, init_fn=RestoreFn) self.assertIsNotNone(loss) self.assertLess(loss, .015) def ModelLoss(self): tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_predictions = LogisticClassifier(tf_inputs) loss_ops.log_loss(tf_predictions, tf_labels) return loss_ops.get_total_loss() def testTrainAllVarsHasLowerLossThanTrainSubsetOfVars(self): logdir1 = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs1') # First, train only the weights of the model. with ops.Graph().as_default(): random_seed.set_random_seed(0) total_loss = self.ModelLoss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) weights = variables_lib2.get_variables_by_name('weights') train_op = learning.create_train_op( total_loss, optimizer, variables_to_train=weights) loss = learning.train( train_op, logdir1, number_of_steps=200, log_every_n_steps=10) self.assertGreater(loss, .015) self.assertLess(loss, .05) # Next, train the biases of the model. with ops.Graph().as_default(): random_seed.set_random_seed(1) total_loss = self.ModelLoss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) biases = variables_lib2.get_variables_by_name('biases') train_op = learning.create_train_op( total_loss, optimizer, variables_to_train=biases) loss = learning.train( train_op, logdir1, number_of_steps=300, log_every_n_steps=10) self.assertGreater(loss, .015) self.assertLess(loss, .05) # Finally, train both weights and bias to get lower loss. with ops.Graph().as_default(): random_seed.set_random_seed(2) total_loss = self.ModelLoss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) loss = learning.train( train_op, logdir1, number_of_steps=400, log_every_n_steps=10) self.assertIsNotNone(loss) self.assertLess(loss, .015) def testTrainingSubsetsOfVariablesOnlyUpdatesThoseVariables(self): # First, train only the weights of the model. with ops.Graph().as_default(): random_seed.set_random_seed(0) total_loss = self.ModelLoss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) weights, biases = variables_lib2.get_variables() train_op = learning.create_train_op(total_loss, optimizer) train_weights = learning.create_train_op( total_loss, optimizer, variables_to_train=[weights]) train_biases = learning.create_train_op( total_loss, optimizer, variables_to_train=[biases]) with session.Session() as sess: # Initialize the variables. sess.run(variables_lib.global_variables_initializer()) # Get the initial weights and biases values. weights_values, biases_values = sess.run([weights, biases]) self.assertGreater(np.linalg.norm(weights_values), 0) self.assertAlmostEqual(np.linalg.norm(biases_values), 0) # Update weights and biases. loss = sess.run(train_op) self.assertGreater(loss, .5) new_weights, new_biases = sess.run([weights, biases]) # Check that the weights and biases have been updated. self.assertGreater(np.linalg.norm(weights_values - new_weights), 0) self.assertGreater(np.linalg.norm(biases_values - new_biases), 0) weights_values, biases_values = new_weights, new_biases # Update only weights. loss = sess.run(train_weights) self.assertGreater(loss, .5) new_weights, new_biases = sess.run([weights, biases]) # Check that the weights have been updated, but biases have not. self.assertGreater(np.linalg.norm(weights_values - new_weights), 0) self.assertAlmostEqual(np.linalg.norm(biases_values - new_biases), 0) weights_values = new_weights # Update only biases. loss = sess.run(train_biases) self.assertGreater(loss, .5) new_weights, new_biases = sess.run([weights, biases]) # Check that the biases have been updated, but weights have not. self.assertAlmostEqual(np.linalg.norm(weights_values - new_weights), 0) self.assertGreater(np.linalg.norm(biases_values - new_biases), 0) def testTrainWithAlteredGradients(self): # Use the same learning rate but different gradient multipliers # to train two models. Model with equivalently larger learning # rate (i.e., learning_rate * gradient_multiplier) has smaller # training loss. logdir1 = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs1') logdir2 = os.path.join( tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs2') multipliers = [1., 1000.] number_of_steps = 10 losses = [] learning_rate = 0.001 # First, train the model with equivalently smaller learning rate. with ops.Graph().as_default(): random_seed.set_random_seed(0) train_op = self.create_train_op( learning_rate=learning_rate, gradient_multiplier=multipliers[0]) loss = learning.train(train_op, logdir1, number_of_steps=number_of_steps) losses.append(loss) self.assertGreater(loss, .5) # Second, train the model with equivalently larger learning rate. with ops.Graph().as_default(): random_seed.set_random_seed(0) train_op = self.create_train_op( learning_rate=learning_rate, gradient_multiplier=multipliers[1]) loss = learning.train(train_op, logdir2, number_of_steps=number_of_steps) losses.append(loss) self.assertIsNotNone(loss) self.assertLess(loss, .5) # The loss of the model trained with larger learning rate should # be smaller. self.assertGreater(losses[0], losses[1]) def testTrainWithEpochLimit(self): logdir = os.path.join(tempfile.mkdtemp(prefix=self.get_temp_dir()), 'tmp_logs') with ops.Graph().as_default(): random_seed.set_random_seed(0) tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) tf_inputs_limited = input_lib.limit_epochs(tf_inputs, num_epochs=300) tf_labels_limited = input_lib.limit_epochs(tf_labels, num_epochs=300) tf_predictions = LogisticClassifier(tf_inputs_limited) loss_ops.log_loss(tf_predictions, tf_labels_limited) total_loss = loss_ops.get_total_loss() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) train_op = learning.create_train_op(total_loss, optimizer) loss = learning.train(train_op, logdir, log_every_n_steps=10) self.assertIsNotNone(loss) self.assertLess(loss, .015) self.assertTrue(os.path.isfile('{}/model.ckpt-300.index'.format(logdir))) self.assertTrue(os.path.isfile('{}/model.ckpt-300.data-00000-of-00001'.format(logdir))) if __name__ == '__main__': test.main()
# Copyright 2018-present Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import glob import hashlib import logging import os import re import shutil import tempfile import requests from platforms.common import ReleaseException, run, temp_move_file from releases import get_version_and_timestamp_from_release def brew(homebrew_dir, command, *run_args, **run_kwargs): """ Run brew that is installed in the specified prefix. Args: homebrew_dir: The path containing bin/brew. e.g. /usr/local command: The list of args to pass to the brew command run_args: Extra args to send to platforms.common.run run_kwargs: Extra kwargs to send to platforms.common.run Returns: Result from subprocess.run """ brew_path = os.path.join(homebrew_dir, "bin", "brew") return run([brew_path] + command, *run_args, **run_kwargs) def install_homebrew(homebrew_dir): logging.info("Installing homebrew to {}".format(homebrew_dir)) if not os.path.exists(homebrew_dir): os.makedirs(homebrew_dir) logging.info("Downloading homebrew...") response = requests.get( "https://github.com/Homebrew/brew/tarball/master", stream=True ) response.raise_for_status() with tempfile.NamedTemporaryFile() as fout: for chunk in response.iter_content(1024 * 1024): fout.write(chunk) fout.flush() logging.info("Extracting homebrew...") run(["tar", "xzf", fout.name, "--strip", "1", "-C", homebrew_dir]) logging.info("Extracted homebrew") def fetch_tarball_sha256(url): """ Get the sha256 of a tarball """ logging.info("Fetching tarball from {}...".format(url)) response = requests.get(url, stream=True) sha256 = hashlib.sha256() for chunk in response.iter_content(chunk_size=1024 * 1024): sha256.update(chunk) hex_hash = sha256.hexdigest() logging.info("Downloaded {} with hash {}".format(url, hex_hash)) return hex_hash def get_formula_path(homebrew_dir, tap_repository): """ Get the path for the buck forumula in the given repository """ result = brew(homebrew_dir, ["formula", tap_repository + "/buck"], None, True) return result.stdout.decode("utf-8").strip() def setup_tap(homebrew_dir, tap_repository): """ Make sure that `tap_repository` is tapped """ logging.info("Tapping {}".format(tap_repository)) brew(homebrew_dir, ["tap", tap_repository]) logging.info("Tapped {}".format(tap_repository)) def update_formula_before_bottle( release, release_version, release_timestamp, formula_path, tarball_sha256 ): """ Updates `formula_path` with correct urls, version and sha for building a bottle Args: release: The github release object release_version: The version of the release (no "v" prefix) release_timestamp: The timestamp to use while building formula_path: The local path to the buck formula tarball_sha256: The sha256 of the source tarball for the specified release """ logging.info("Updating formula at {}".format(formula_path)) with open(formula_path, "r") as fin: all_data = fin.read() all_data = re.sub( r"@@buck_version = .*$", '@@buck_version = "{}"'.format(release_version), all_data, flags=re.MULTILINE, ) all_data = re.sub( r"@@buck_release_timestamp = .*$", '@@buck_release_timestamp = "{}"'.format(release_timestamp), all_data, flags=re.MULTILINE, ) all_data = re.sub( r'sha256 "[a-z0-9]{64}"$', 'sha256 "{}"'.format(tarball_sha256), all_data, flags=re.MULTILINE, ) all_data = re.sub( r' url "https://.+"$', r' url "{}"'.format(release["tarball_url"]), all_data, flags=re.MULTILINE, ) with open(formula_path, "w") as fout: fout.write(all_data) def build_bottle_file( homebrew_dir, tap_repository, tap_path, release_version, target_macos_version, output_dir, ): """ Builds the actual bottle file via brew Args: tap_repository: The name of the tap repository tap_path: The local path to the given tap repository release_version: The version that should be built (no "v" prefix) target_macos_version: The target macos short nameto use in the resulting path output_dir: The directory to move the build artifact to after building Returns: The path to the bottle.tar.gz """ brew_target = tap_repository + "/buck" # So, if buck wasn't linked to begin with, we can't unlink it. Ideally the install # fails down the road. There is, so far as I could tell, no way to verify if # a formula is linked :/ logging.info("Unlinking buck") brew(homebrew_dir, ["unlink", brew_target], tap_path, check=False) logging.info("Building bottle") # If there is still a buck file that exists, move it out of the way for now # This should generally not be an issue outside of FB with temp_move_file("/usr/local/bin/buck") as moved: # Cool, so install --force will still not rebuild. Uninstall, and just don't # care if the uninstall fails brew( homebrew_dir, ["uninstall", "--force", "--build-bottle", brew_target], tap_path, check=False, ) brew( homebrew_dir, ["install", "--force", "--build-bottle", brew_target], tap_path, ) logging.info("Creating bottle file") brew( homebrew_dir, ["bottle", "--no-rebuild", "--skip-relocation", brew_target], tap_path, ) logging.info("Created bottle file") if moved: # Make sure to unlink again so that we can move the original file back logging.info("Unlinking buck again") brew(homebrew_dir, ["unlink", brew_target], tap_path) bottle_filename = "buck-{ver}.{macos_ver}.bottle.tar.gz".format( ver=release_version, macos_ver=target_macos_version ) bottle_path = os.path.join(output_dir, bottle_filename) bottles = glob.glob( os.path.join(tap_path, "buck--{}*.bottle.tar.gz".format(release_version)) ) if len(bottles) != 1: raise ReleaseException( "Got an invalid number of bottle files ({} files: {})".format( len(bottles), " ".join(bottles) ) ) shutil.move(bottles[0], bottle_path) return bottle_path def get_sha256(path, chunk_size=1024 * 1024): """ Get the sha256 of a file """ sha = hashlib.sha256() with open(path, "rb") as fin: data = fin.read(chunk_size) while data: sha.update(data) data = fin.read(chunk_size) return sha.hexdigest() def update_formula_after_bottle(formula_path, sha, target_macos_version_spec): """ Update the buck formula with the sha for the newly created bottle Args: formula_path: The path to the buck formula sha: The new sha to use target_macos_version_spec: The version spec to use for this sha """ logging.info("Updating formula with new bottle sha") with open(formula_path, "r") as fin: all_data = fin.read() all_data = re.sub( r'sha256 "[a-z0-9]+" => :.*$', 'sha256 "{}" => :{}'.format(sha, target_macos_version_spec), all_data, flags=re.MULTILINE, ) with open(formula_path, "w") as fout: fout.write(all_data) logging.info("Updated formula with new bottle sha") def push_tap(git_repository, tap_path, version): """ Grab any working directory changes for the tap, clone a new tap repository, and push those changes upstream. The original tap path is in a clean state after this push. The clone is done with ssh, so ssh keys must be available Args: git_repository: The repo on github that needs to be cloned/pushed to tap_path: The directory that the tap (with changes) exists in version: The version to use in commit messages """ logging.info("Gathering git diff from {}".format(tap_path)) git_diff = run(["git", "diff"], tap_path, True).stdout git_url = "[email protected]:{}.git".format(git_repository) with tempfile.TemporaryDirectory() as temp_dir: logging.info("Cloning {} into {}".format(git_url, temp_dir)) run(["git", "clone", git_url, temp_dir]) logging.info("Cloned into {}. Applying patch".format(temp_dir)) run(["git", "apply", "-"], temp_dir, input=git_diff) logging.info("Committing...") with tempfile.NamedTemporaryFile() as fout: commit_message = ( "Bump buck to version {}\n\nThis commit was generated by " "release automation\n" ).format(version) fout.write(commit_message.encode("utf-8")) fout.flush() run(["git", "commit", "-F", fout.name, "buck.rb"], temp_dir) logging.info("Pushing commit upstream") run(["git", "push", "origin"], temp_dir) logging.info("Pushed commit upstream!") logging.info("Resetting state of {}, and updating it after push".format(tap_path)) run(["git", "checkout", "buck.rb"], tap_path) run(["git", "checkout", "master"], tap_path) run(["git", "pull"], tap_path) logging.info("Reset state of {}, and updating it after push".format(tap_path)) def validate_tap(homebrew_dir, tap_repository, version): logging.info("Validating that brew installs with new tap information") brew_target = tap_repository + "/buck" brew(homebrew_dir, ["uninstall", "--force", brew_target]) with temp_move_file("/usr/local/bin/buck") as moved: brew(homebrew_dir, ["install", brew_target]) output = ( brew(homebrew_dir, ["info", brew_target], capture_output=True) .stdout.decode("utf-8") .splitlines()[0] ) if moved: brew(homebrew_dir, ["uninstall", brew_target]) if "{}/buck: stable {}".format(tap_repository, version) not in output: raise ReleaseException( "Expected version {} to be installed, but got this from `brew info {}`: {}".format( version, tap_repository, output ) ) def publish_tap_changes(homebrew_dir, tap_repository, version): git_user, git_repo = tap_repository.split("/") full_git_repo = "{}/homebrew-{}".format(git_user, git_repo) formula_path = get_formula_path(homebrew_dir, tap_repository) tap_path = os.path.dirname(formula_path) push_tap(full_git_repo, tap_path, version) def log_about_manual_tap_push(homebrew_dir, tap_repository): formula_path = get_formula_path(homebrew_dir, tap_repository) tap_path = os.path.dirname(formula_path) logging.info( "The homebrew tap is ready for a pull request. It can be found at {}".format( tap_path ) ) def build_bottle( homebrew_dir, release, tap_repository, target_macos_version, target_macos_version_spec, output_dir, ): release_version, release_timestamp = get_version_and_timestamp_from_release(release) if not os.path.exists(os.path.join(homebrew_dir, "bin", "brew")): install_homebrew(homebrew_dir) setup_tap(homebrew_dir, tap_repository) formula_path = get_formula_path(homebrew_dir, tap_repository) tap_path = os.path.dirname(formula_path) tarball_sha256 = fetch_tarball_sha256(release["tarball_url"]) # First, update the bottle to have the new version and tarball sha. update_formula_before_bottle( release, release_version, release_timestamp, formula_path, tarball_sha256 ) # Build the actual bottle file bottle_path = build_bottle_file( homebrew_dir, tap_repository, tap_path, release_version, target_macos_version, output_dir, ) # Get the bottle file sha, and update the bottle formula bottle_sha = get_sha256(bottle_path) update_formula_after_bottle(formula_path, bottle_sha, target_macos_version_spec) return bottle_path
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os from pants.backend.jvm.targets.jar_library import JarLibrary from pants.backend.jvm.tasks.jar_import_products import JarImportProducts from pants.fs.archive import ZIP from pants.java.jar.jar_dependency import JarDependency from pants.java.jar.jar_dependency_utils import M2Coordinate from pants.util.contextutil import open_zip, temporary_dir, temporary_file from pants.util.dirutil import safe_mkdir, safe_open, safe_walk, touch from pants_test.contrib.android.test_android_base import TestAndroidBase from pants.contrib.android.targets.android_dependency import AndroidDependency from pants.contrib.android.targets.android_library import AndroidLibrary from pants.contrib.android.targets.android_resources import AndroidResources from pants.contrib.android.tasks.unpack_libraries import UnpackLibraries class UnpackLibrariesTest(TestAndroidBase): @classmethod def task_type(cls): return UnpackLibraries def unpacked_aar_library(self, location, manifest=True, classes_jar=True, resources=True, filenames=None): """Mock the contents of an aar file, with optional components and additional files.""" if manifest: manifest_file = os.path.join(location, 'AndroidManifest.xml') touch(manifest_file) with safe_open(manifest_file, 'w') as fp: fp.write(self.android_manifest()) fp.close() if classes_jar: self.create_jarfile(location, filenames=filenames) if resources: safe_mkdir(os.path.join(location, 'res')) return location def create_aarfile(self, location, name, filenames=None): """Create an aar file, using the contents created by self.unpacked_aar_library.""" with temporary_dir() as temp: aar_contents = self.unpacked_aar_library(temp, filenames=filenames) archive = ZIP.create(aar_contents, location, name) aar = os.path.join(location, '{}.aar'.format(name)) os.rename(archive, aar) return aar def create_jarfile(self, location, name=None, filenames=None): """Create a sample jar file.""" name = '{}.jar'.format(name or 'classes') jar_name = os.path.join(location, name) with open_zip(jar_name, 'w') as library: library.writestr('a/b/c/Foo.class', '0xCAFEBABE') library.writestr('a/b/c/Bar.class', '0xCAFEBABE') if filenames: for class_file in filenames: library.writestr(class_file, '0xCAFEBABE') return jar_name def test_unpack_smoke(self): task = self.create_task(self.context()) task.execute() def test_is_library(self): with self.android_library() as android_library: task = self.create_task(self.context()) self.assertTrue(task.is_library(android_library)) def test_detect_nonlibrary(self): with self.android_target() as android_target: task = self.create_task(self.context()) self.assertFalse(task.is_library(android_target)) def test_aar_out(self): task = self.create_task(self.context()) coordinate = M2Coordinate(org='org.pantsbuild', name='example', rev='1.0', ext='aar') outdir = task.unpacked_aar_location(coordinate) self.assertEqual(os.path.join(task.workdir, 'org.pantsbuild-example-1.0.aar'), outdir) def test_jar_out(self): task = self.create_task(self.context()) coordinate = M2Coordinate(org='org.pantsbuild', name='example', rev='1.0', ext='jar') outdir = task.unpacked_jar_location(coordinate) self.assertEqual(os.path.join(task.workdir, 'explode-jars', 'org.pantsbuild-example-1.0.jar'), outdir) def test_create_classes_jar_target(self): with self.android_library() as android_library: with temporary_file() as jar: task = self.create_task(self.context()) coordinate = M2Coordinate(org='org.pantsbuild', name='example', rev='1.0') created_target = task.create_classes_jar_target(android_library, coordinate, jar) self.assertEqual(created_target.derived_from, android_library) self.assertTrue(created_target.is_synthetic) self.assertTrue(isinstance(created_target, JarLibrary)) def test_create_resource_target(self): with self.android_library() as library: with temporary_file() as manifest: with temporary_dir() as res: manifest.write(self.android_manifest()) manifest.close() task = self.create_task(self.context()) coordinate = M2Coordinate(org='org.pantsbuild', name='example', rev='1.0') created_target = task.create_resource_target(library, coordinate, manifest.name, res) self.assertEqual(created_target.derived_from, library) self.assertTrue(created_target.is_synthetic) self.assertTrue(isinstance(created_target, AndroidResources)) self.assertEqual(created_target.resource_dir, res) self.assertEqual(created_target.manifest.path, manifest.name) def test_create_android_library_target(self): with self.android_library(include_patterns=['**/*.class']) as android_library: with self.android_binary(dependencies=[android_library]) as android_binary: with temporary_dir() as temp: contents = self.unpacked_aar_library(temp) task = self.create_task(self.context()) coordinate = M2Coordinate(org='org.pantsbuild', name='example', rev='1.0') created_library = task.create_android_library_target(android_binary, android_library, coordinate, contents) self.assertEqual(created_library.derived_from, android_library) self.assertTrue(created_library.is_synthetic) self.assertTrue(isinstance(created_library, AndroidLibrary)) self.assertEqual(android_library.payload.include_patterns, created_library.payload.include_patterns) self.assertEqual(android_library.payload.exclude_patterns, created_library.payload.exclude_patterns) self.assertEqual(len(created_library.dependencies), 1) self.assertTrue(isinstance(created_library.dependencies[0], AndroidResources)) def test_create_android_library_dependency_injection(self): with self.android_library() as android_library: with self.android_binary(dependencies=[android_library]) as android_binary: with temporary_dir() as temp: self.assertEqual([android_library], android_binary.dependencies) contents = self.unpacked_aar_library(temp) task = self.create_task(self.context()) coordinate = M2Coordinate(org='org.pantsbuild', name='example', rev='1.0') task.create_android_library_target(android_binary, android_library, coordinate, contents) # Make sure that a JarLibrary has been injected into the android_binary deps. self.assertTrue(any(isinstance(x, JarLibrary) for x in android_binary.dependencies)) for dep in android_binary.dependencies: self.assertTrue(isinstance(dep, AndroidLibrary) or isinstance(dep, JarLibrary)) def test_no_classes_jar(self): with self.android_library(include_patterns=['**/*.class']) as android_library: with self.android_binary(dependencies=[android_library]) as android_binary: with temporary_dir() as temp: contents = self.unpacked_aar_library(temp, classes_jar=False) task = self.create_task(self.context()) coordinate = M2Coordinate(org='org.pantsbuild', name='example', rev='1.0') created_library = task.create_android_library_target(android_binary, android_library, coordinate, contents) self.assertEqual(len(created_library.dependencies), 1) for dep in created_library.dependencies: isinstance(dep, AndroidResources) def test_no_resources(self): with self.android_library() as android_library: with self.android_binary(dependencies=[android_library]) as android_binary: with temporary_dir() as temp: contents = self.unpacked_aar_library(temp, classes_jar=False) task = self.create_task(self.context()) coordinate = M2Coordinate(org='org.pantsbuild', name='example', rev='1.0') created_library = task.create_android_library_target(android_binary, android_library, coordinate, contents) self.assertEqual(len(created_library.dependencies), 1) for dep in created_library.dependencies: isinstance(dep, JarLibrary) def test_no_manifest(self): with self.android_library(include_patterns=['**/*.class']) as android_library: with self.android_binary(dependencies=[android_library]) as android_binary: with temporary_dir() as temp: contents = self.unpacked_aar_library(temp, manifest=False) task = self.create_task(self.context()) archive = 'org.pantsbuild.example-1.0' with self.assertRaises(UnpackLibraries.MissingElementException): task.create_android_library_target(android_binary, android_library, archive, contents) # Test unpacking process. def create_android_library(self, rev, library_file): _, ext = os.path.splitext(library_file) coord = M2Coordinate(org='com.example', name='bar', rev=rev, ext=ext[1:]) dep_spec = 'unpack/libs:{}-{}-{}'.format(coord.org, coord.name, coord.rev) adroid_dep = self.make_target(spec=dep_spec, target_type=AndroidDependency, jars=[JarDependency(org=coord.org, name=coord.name, rev=coord.rev, url='file:{}'.format(library_file))]) target = self.make_target(spec='unpack:test', target_type=AndroidLibrary, libraries=[adroid_dep.address.spec], include_patterns=['a/b/c/*.class']) return target, coord def test_unpack_jar_library(self): # Test for when the imported library is a jarfile. with temporary_dir() as temp: jar_file = self.create_jarfile(temp, 'org.pantsbuild.android.test', filenames=['a/b/c/Any.class', 'a/b/d/Thing.class']) test_target, coordinate = self.create_android_library(rev='1.0', library_file=jar_file) original_dependencies = list(test_target.dependencies) files = self.unpack_libraries(target=test_target, aar_file=jar_file, coordinate=coordinate) # If the android_library imports a jar, files are unpacked but no new targets are created. self.assertEqual(sorted(['Any.class', 'Thing.class', 'Foo.class', 'Bar.class']), sorted(files)) self.assertEqual(original_dependencies, test_target.dependencies) def test_unexpected_archive_type(self): with temporary_dir() as temp: aar = self.create_aarfile(temp, 'org.pantsbuild.android.test') unexpected_archive = os.path.join(temp, 'org.pantsbuild.android.test{}'.format('.other')) os.rename(aar, unexpected_archive) lib, coordinate = self.create_android_library(rev='1.0', library_file=unexpected_archive) with self.assertRaises(UnpackLibraries.UnexpectedArchiveType): self.unpack_libraries(target=lib, aar_file=unexpected_archive, coordinate=coordinate) def unpack_libraries(self, target, aar_file, coordinate): context = self.context(target_roots=[target]) task = self.create_task(context) jar_import_products = context.products.get_data(JarImportProducts, init_func=JarImportProducts) jar_import_products.imported(target, coordinate, aar_file) task.execute() # Gather classes found when unpacking the aar_file. files = [] jar_location = task.unpacked_jar_location(coordinate) for _, _, filenames in safe_walk(jar_location): files.extend(filenames) return files def test_unpack_aar_files_and_invalidation(self): with temporary_dir() as temp: aar = self.create_aarfile(temp, 'org.pantsbuild.android.test') lib, coordinate = self.create_android_library(rev='1.0', library_file=aar) files = self.unpack_libraries(target=lib, aar_file=aar, coordinate=coordinate) self.assertIn('Foo.class', files) # Reset build graph to dismiss all the created targets. self.reset_build_graph() # Create a new copy of the archive- adding a sentinel file but without bumping the version. new_aar = self.create_aarfile(temp, 'org.pantsbuild.android.test', filenames=['a/b/c/Baz.class']) lib, coordinate = self.create_android_library(rev='1.0', library_file=new_aar) # Call task a 2nd time but the sentinel file is not found because we didn't bump version. files = self.unpack_libraries(target=lib, aar_file=new_aar, coordinate=coordinate) self.assertNotIn('Baz.class', files) # Now bump version and this time the aar is unpacked and the sentinel file is found. self.reset_build_graph() lib, coordinate = self.create_android_library(rev='2.0', library_file=aar) files = self.unpack_libraries(target=lib, aar_file=new_aar, coordinate=coordinate) self.assertIn('Baz.class', files)
# Copyright (C) 2021 Nippon Telegraph and Telephone Corporation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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 yaml from tacker.sol_refactored.common import vnf_instance_utils as inst_utils from tacker.sol_refactored.infra_drivers.openstack import userdata_utils class DefaultUserData(userdata_utils.AbstractUserData): @staticmethod def instantiate(req, inst, grant_req, grant, tmp_csar_dir): vnfd = userdata_utils.get_vnfd(inst['vnfdId'], tmp_csar_dir) flavour_id = req['flavourId'] hot_dict = vnfd.get_base_hot(flavour_id) top_hot = hot_dict['template'] nfv_dict = userdata_utils.init_nfv_dict(top_hot) vdus = nfv_dict.get('VDU', {}) for vdu_name, vdu_value in vdus.items(): if 'computeFlavourId' in vdu_value: vdu_value['computeFlavourId'] = ( userdata_utils.get_param_flavor( vdu_name, flavour_id, vnfd, grant)) if 'vcImageId' in vdu_value: vdu_value['vcImageId'] = userdata_utils.get_param_image( vdu_name, flavour_id, vnfd, grant) if 'locationConstraints' in vdu_value: vdu_value['locationConstraints'] = ( userdata_utils.get_param_zone( vdu_name, grant_req, grant)) if 'desired_capacity' in vdu_value: vdu_value['desired_capacity'] = ( userdata_utils.get_param_capacity( vdu_name, inst, grant_req)) cps = nfv_dict.get('CP', {}) for cp_name, cp_value in cps.items(): if 'network' in cp_value: cp_value['network'] = userdata_utils.get_param_network( cp_name, grant, req) if 'fixed_ips' in cp_value: ext_fixed_ips = userdata_utils.get_param_fixed_ips( cp_name, grant, req) fixed_ips = [] for i in range(len(ext_fixed_ips)): if i not in cp_value['fixed_ips']: break ips_i = cp_value['fixed_ips'][i] if 'subnet' in ips_i: ips_i['subnet'] = ext_fixed_ips[i].get('subnet') if 'ip_address' in ips_i: ips_i['ip_address'] = ext_fixed_ips[i].get( 'ip_address') fixed_ips.append(ips_i) cp_value['fixed_ips'] = fixed_ips userdata_utils.apply_ext_managed_vls(top_hot, req, grant) if 'nfv' in req.get('additionalParams', {}): nfv_dict = inst_utils.json_merge_patch(nfv_dict, req['additionalParams']['nfv']) if 'nfv' in grant.get('additionalParams', {}): nfv_dict = inst_utils.json_merge_patch(nfv_dict, grant['additionalParams']['nfv']) fields = { 'template': yaml.safe_dump(top_hot), 'parameters': {'nfv': nfv_dict}, 'files': {} } for key, value in hot_dict.get('files', {}).items(): fields['files'][key] = yaml.safe_dump(value) return fields @staticmethod def scale(req, inst, grant_req, grant, tmp_csar_dir): # scale is interested in 'desired_capacity' only. # This method returns only 'desired_capacity' part in the # 'nfv' dict. It is applied to json merge patch against # the existing 'nfv' dict by the caller. # NOTE: complete 'nfv' dict can not be made at the moment # since InstantiateVnfRequest is necessary to make it. vnfd = userdata_utils.get_vnfd(inst['vnfdId'], tmp_csar_dir) flavour_id = inst['instantiatedVnfInfo']['flavourId'] hot_dict = vnfd.get_base_hot(flavour_id) top_hot = hot_dict['template'] nfv_dict = userdata_utils.init_nfv_dict(top_hot) vdus = nfv_dict.get('VDU', {}) new_vdus = {} for vdu_name, vdu_value in vdus.items(): if 'desired_capacity' in vdu_value: capacity = userdata_utils.get_param_capacity( vdu_name, inst, grant_req) new_vdus[vdu_name] = {'desired_capacity': capacity} fields = {'parameters': {'nfv': {'VDU': new_vdus}}} return fields @staticmethod def scale_rollback(req, inst, grant_req, grant, tmp_csar_dir): # NOTE: This method is not called by a userdata script but # is called by the openstack infra_driver directly now. # It is thought that it is suitable that this method defines # here since it is very likely to scale method above. vnfd = userdata_utils.get_vnfd(inst['vnfdId'], tmp_csar_dir) flavour_id = inst['instantiatedVnfInfo']['flavourId'] hot_dict = vnfd.get_base_hot(flavour_id) top_hot = hot_dict['template'] nfv_dict = userdata_utils.init_nfv_dict(top_hot) vdus = nfv_dict.get('VDU', {}) new_vdus = {} for vdu_name, vdu_value in vdus.items(): if 'desired_capacity' in vdu_value: capacity = userdata_utils.get_current_capacity( vdu_name, inst) new_vdus[vdu_name] = {'desired_capacity': capacity} fields = {'parameters': {'nfv': {'VDU': new_vdus}}} return fields @staticmethod def change_ext_conn(req, inst, grant_req, grant, tmp_csar_dir): # change_ext_conn is interested in 'CP' only. # This method returns only 'CP' part in the 'nfv' dict from # ChangeExtVnfConnectivityRequest. # It is applied to json merge patch against the existing 'nfv' # dict by the caller. # NOTE: complete 'nfv' dict can not be made at the moment # since InstantiateVnfRequest is necessary to make it. vnfd = userdata_utils.get_vnfd(inst['vnfdId'], tmp_csar_dir) flavour_id = inst['instantiatedVnfInfo']['flavourId'] hot_dict = vnfd.get_base_hot(flavour_id) top_hot = hot_dict['template'] nfv_dict = userdata_utils.init_nfv_dict(top_hot) cps = nfv_dict.get('CP', {}) new_cps = {} for cp_name, cp_value in cps.items(): if 'network' in cp_value: network = userdata_utils.get_param_network(cp_name, grant, req) if network is None: continue new_cps.setdefault(cp_name, {}) new_cps[cp_name]['network'] = network if 'fixed_ips' in cp_value: ext_fixed_ips = userdata_utils.get_param_fixed_ips( cp_name, grant, req) fixed_ips = [] for i in range(len(ext_fixed_ips)): if i not in cp_value['fixed_ips']: break ips_i = cp_value['fixed_ips'][i] if 'subnet' in ips_i: ips_i['subnet'] = ext_fixed_ips[i].get('subnet') if 'ip_address' in ips_i: ips_i['ip_address'] = ext_fixed_ips[i].get( 'ip_address') fixed_ips.append(ips_i) new_cps.setdefault(cp_name, {}) new_cps[cp_name]['fixed_ips'] = fixed_ips fields = {'parameters': {'nfv': {'CP': new_cps}}} return fields @staticmethod def change_ext_conn_rollback(req, inst, grant_req, grant, tmp_csar_dir): # NOTE: This method is not called by a userdata script but # is called by the openstack infra_driver directly now. # It is thought that it is suitable that this method defines # here since it is very likely to scale method above. vnfd = userdata_utils.get_vnfd(inst['vnfdId'], tmp_csar_dir) flavour_id = inst['instantiatedVnfInfo']['flavourId'] hot_dict = vnfd.get_base_hot(flavour_id) top_hot = hot_dict['template'] nfv_dict = userdata_utils.init_nfv_dict(top_hot) cps = nfv_dict.get('CP', {}) new_cps = {} for cp_name, cp_value in cps.items(): if 'network' in cp_value: network = userdata_utils.get_param_network_from_inst( cp_name, inst) if network is None: continue new_cps.setdefault(cp_name, {}) new_cps[cp_name]['network'] = network if 'fixed_ips' in cp_value: ext_fixed_ips = userdata_utils.get_param_fixed_ips_from_inst( cp_name, inst) fixed_ips = [] for i in range(len(ext_fixed_ips)): if i not in cp_value['fixed_ips']: break ips_i = cp_value['fixed_ips'][i] if 'subnet' in ips_i: ips_i['subnet'] = ext_fixed_ips[i].get('subnet') if 'ip_address' in ips_i: ips_i['ip_address'] = ext_fixed_ips[i].get( 'ip_address') fixed_ips.append(ips_i) new_cps.setdefault(cp_name, {}) new_cps[cp_name]['fixed_ips'] = fixed_ips fields = {'parameters': {'nfv': {'CP': new_cps}}} return fields @staticmethod def heal(req, inst, grant_req, grant, tmp_csar_dir): # It is not necessary to change parameters at heal basically. fields = {'parameters': {'nfv': {}}} return fields
#!/usr/bin/env python import numpy as np import math def compute_kl(mean_1, log_prec_1, mean_2, log_prec_2): """ compute KL between two Gaussian distributions """ mean_1 = np.asarray(mean_1) log_prec_1 = np.asarray(log_prec_1) mean_2 = np.asarray(mean_2) log_prec_2 = np.asarray(log_prec_2) len_1 = len(mean_1) len_2 = len(mean_2) len_max = max(len_1, len_2) var_1, var_2 = np.exp(-log_prec_1), np.exp(-log_prec_2) # computationally more stable? kl = 0.5 * ( log_prec_1 - log_prec_2 - 1 + np.exp(log_prec_2 - log_prec_1) + np.power(mean_1-mean_2,2)/var_2 ) # when log_prec_2 > -np.inf, log_prec_1=-np.inf leads to infinite kl if len_1 == 1: cond = np.logical_and(np.isinf(log_prec_1), log_prec_1 < 0) idx_log_prec_1_neginf = np.ones(len_max) * cond if cond: kl = np.inf * np.ones(len_max) else: idx_log_prec_1_neginf = np.logical_and(np.isinf(log_prec_1), log_prec_1 < 0) kl[idx_log_prec_1_neginf] = np.inf if len_2 == 1: cond = np.logical_and(np.isinf(log_prec_2), log_prec_2 < 0) idx_log_prec_2_neginf = np.ones(len_max) * cond else: idx_log_prec_2_neginf = np.logical_and(np.isinf(log_prec_2), log_prec_2 < 0) # when log_prec_2 = -np.inf, log_prec_1=-np.inf leads to zero kl idx_both_log_prec_neginf = np.logical_and(idx_log_prec_1_neginf, idx_log_prec_2_neginf) kl[idx_both_log_prec_neginf] = 0. # when log_prec_2 = np.inf, any value of log_prec_1 leads to infinite kl idx_log_prec_2_posinf = np.logical_and(np.isinf(log_prec_2), log_prec_2 > 0) if (len_2 == 1) and idx_log_prec_2_posinf: kl = np.inf * np.ones(len_max) else: kl[idx_log_prec_2_posinf] = np.inf if False: print 'log_prec_1 = %s, log_prec_2 = %s, kl = %s' % (log_prec_1, log_prec_2, kl) if np.any(np.isnan(kl)): print '\nsomething went wrong with kl computation' print 'var_1 = %s, var_2 = %s' % (var_1, var_2) print 'log_prec_1 = %s, log_prec_2 = %s' % (log_prec_1, log_prec_2) print 'idx_log_prec_1_neginf = %s' % idx_log_prec_1_neginf print 'idx_log_prec_2_neginf = %s' % idx_log_prec_2_neginf print 'idx_log_prec_2_posinf = %s' % idx_log_prec_2_posinf print 'kl = %s' % kl raise Exception return kl def test_compute_kl(): compute_kl(0*np.ones(2), np.inf*np.ones(2), 0*np.ones(1), np.inf*np.ones(1)) compute_kl(0*np.ones(2), -np.inf*np.ones(2), 0*np.ones(1), np.inf*np.ones(1)) compute_kl(0*np.ones(2), np.inf*np.ones(2), 0*np.ones(1), -np.inf*np.ones(1)) compute_kl(0*np.ones(2), -np.inf*np.ones(2), 0*np.ones(1), -np.inf*np.ones(1)) compute_kl(0*np.ones(1), np.inf*np.ones(1), 0*np.ones(2), np.inf*np.ones(2)) compute_kl(0*np.ones(1), -np.inf*np.ones(1), 0*np.ones(2), np.inf*np.ones(2)) compute_kl(0*np.ones(1), np.inf*np.ones(1), 0*np.ones(2), -np.inf*np.ones(2)) compute_kl(0*np.ones(1), -np.inf*np.ones(1), 0*np.ones(2), -np.inf*np.ones(2)) def multiply_gaussians(*params): """ input is a list containing (variable number of) gaussian parameters each element is a numpy array containing mean and precision of that gaussian """ precision_op, mean_op = 0., 0. for param in params: precision_op += param[1] mean_op += param[0] * param[1] mean_op /= precision_op return np.array([mean_op, precision_op]) def divide_gaussians(mean_precision_num, mean_precision_den): """ mean_precision_num are parameters of gaussian in the numerator mean_precision_den are parameters of gaussian in the denominator output is a valid gaussian only if the variance of ouput is non-negative """ precision_op = mean_precision_num[1] - mean_precision_den[1] try: assert precision_op >= 0. # making it > so that mean_op is not inf except AssertionError: print 'inputs = %s, %s' % (mean_precision_num, mean_precision_den) print 'precision_op = %s' % (precision_op) raise AssertionError if precision_op == 0.: mean_op = 0. else: mean_op = (mean_precision_num[0] * mean_precision_num[1] \ - mean_precision_den[0] * mean_precision_den[1] ) / precision_op return np.array([mean_op, precision_op]) def hist_count(x, basis): """ counts number of times each element in basis appears in x op is a vector of same size as basis assume no duplicates in basis """ op = np.zeros((len(basis)), dtype=int) map_basis = {} for n, k in enumerate(basis): map_basis[k] = n for t in x: op[map_basis[t]] += 1 return op def logsumexp(x): tmp = x.copy() tmp_max = np.max(tmp) tmp -= tmp_max op = np.log(np.sum(np.exp(tmp))) + tmp_max return op def logsumexp_array(v1, v2): """ computes logsumexp of each element in v1 and v2 """ v_min = np.minimum(v1, v2) v_max = np.maximum(v1, v2) op = v_max + np.log(1 + np.exp(v_min - v_max)) return op def logsumexp_2(x, y): # fast logsumexp for 2 variables # output = log (e^x + e^y) = log(e^max(1+e^(min-max))) = max + log(1 + e^(min-max)) if x > y: min_val = y max_val = x else: min_val = x max_val = y op = max_val + math.log(1 + math.exp(min_val - max_val)) return op def softmax(x): tmp = x.copy() tmp_max = np.max(tmp) tmp -= float(tmp_max) tmp = np.exp(tmp) op = tmp / np.sum(tmp) return op def assert_no_nan(mat, name='matrix'): try: assert(not any(np.isnan(mat))) except AssertionError: print '%s contains NaN' % name print mat raise AssertionError def check_if_one(val): try: assert(np.abs(val - 1) < 1e-9) except AssertionError: print 'val = %s (needs to be equal to 1)' % val raise AssertionError def check_if_zero(val): try: assert(np.abs(val) < 1e-9) except AssertionError: print 'val = %s (needs to be equal to 0)' % val raise AssertionError def linear_regression(x, y): ls = np.linalg.lstsq(x, y) #print ls coef = ls[0] if ls[1]: sum_squared_residuals = float(ls[1]) # sum of squared residuals else: sum_squared_residuals = np.sum(np.dot(x, coef) - y) # sum of squared residuals return (coef, sum_squared_residuals) def sample_multinomial(prob): try: k = int(np.where(np.random.multinomial(1, prob, size=1)[0]==1)[0]) except TypeError: print 'problem in sample_multinomial: prob = ' print prob raise TypeError except: raise Exception return k def sample_multinomial_scores(scores): scores_cumsum = np.cumsum(scores) s = scores_cumsum[-1] * np.random.rand(1) k = int(np.sum(s > scores_cumsum)) return k def sample_multinomial_scores_old(scores): scores_cumsum = np.cumsum(scores) s = scores_cumsum[-1] * np.random.rand(1) k = 0 while s > scores_cumsum[k]: k += 1 return k def sample_polya(alpha_vec, n): """ alpha_vec is the parameter of the Dirichlet distribution, n is the #samples """ prob = np.random.dirichlet(alpha_vec) n_vec = np.random.multinomial(n, prob) return n_vec def get_kth_minimum(x, k=1): """ gets the k^th minimum element of the list x (note: k=1 is the minimum, k=2 is 2nd minimum) ... based on the incomplete selection sort pseudocode """ n = len(x) for i in range(n): minIndex = i minValue = x[i] for j in range(i+1, n): if x[j] < minValue: minIndex = j minValue = x[j] x[i], x[minIndex] = x[minIndex], x[i] return x[k-1] class empty(object): def __init__(self): pass def sigmoid(x): op = 1.0 / (1 + np.exp(-x)) return op def compute_m_sd(x): m = np.mean(x) s = np.sqrt(np.var(x)) return (m, s) if __name__ == "__main__": test_compute_kl()
#!/usr/bin/env python # -*- coding: utf-8 -*- # ============================================================================== # Copyright 2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Amazon Software License (the "License"). You may not use # this file except in compliance with the License. A copy of the License is # located at # # http://aws.amazon.com/asl/ # # or in the "license" file accompanying this file. This file is distributed on # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or # implied. See the License for the specific language governing permissions # and limitations under the License. #============================================================================== from lib.utility.basetype import ValuedEnum from lib.utility.basetype import OrderedEnum EbCliVersion = 'v2.6.4' class Key(object): Default = 'default' Options = 'options' #---------------------------------------------- # Parameters #---------------------------------------------- # Standard name of parameters used in Elastic Beanstalk Command Line Interface ParameterName = ValuedEnum({ 'Command': 0, 'SubCommand': 1, 'AwsAccessKeyId': 11, 'AwsSecretAccessKey': 12, 'AwsCredentialFile': 13, 'Region': 21, 'OriginalRegion': 22, 'ServiceEndpoint': 31, 'DevToolsEndpoint': 41, 'ApplicationName': 101, 'OriginalApplicationName': 102, 'ApplicationVersionName': 111, 'EnvironmentName': 121, 'EnvironmentId': 122, 'EnvironmentTier': 150, 'SolutionStack': 201, 'OriginalSolutionStack': 202, 'EnvironmentType': 211, 'Branches': 301, 'CurrentBranch': 302, 'BranchMapping': 303, 'DefaultEnvironmentName': 351, 'OptionSettingFile': 501, 'ConfigFileExtra': 511, 'RdsEnabled': 601, 'RdsEndpoint': 602, 'RdsSnippetUrl': 603, 'RdsSourceSnapshotName': 606, 'RdsEngine': 611, 'RdsEngineVersion': 612, 'RdsInstanceClass': 613, 'RdsMultiAZ': 614, 'RdsLicenseModel': 615, 'RdsAllocatedStorage': 616, 'RdsInstanceName': 621, 'RdsMasterUsername': 622, 'RdsMasterPassword': 623, 'RdsDbName': 631, 'RdsDeletionPolicy': 651, 'InstanceProfileName': 701, 'ServiceConnectionTimeout': 1001, 'ServiceRetryThreshold': 1011, 'Force': 1021, 'Verbose': 1051, 'WaitForFinishTimeout': 1101, 'WaitForUpdateTimeout': 1102, 'PollDelay': 1201, 'CreateEnvironmentRequestID': 2001, 'TerminateEnvironmentRequestID': 2002, 'UpdateEnvironmentRequestID': 2003, 'RequestEnvInfoRequestID': 2004, 'AvailableSolutionStacks': 2101, }) # Source of parameter value ParameterSource = ValuedEnum({ 'CliArgument': 0, 'Terminal': 1, 'ConfigFile': 2, 'OsEnvironment': 3, 'OperationOutput': 4, 'Default': 10, }) #---------------------------------------------- # Command #---------------------------------------------- CommandType = OrderedEnum([ 'INIT', 'BRANCH', 'START', 'STATUS', 'UPDATE', 'STOP', 'DELETE', 'LOGS', 'EVENTS', 'PUSH', ]) SubCommandType = OrderedEnum([ # LOGS command 'TAIL', 'OPEN' ]) CommandCombination = { CommandType.LOGS: { Key.Default: SubCommandType.TAIL, Key.Options: [ SubCommandType.TAIL, ] }, } #---------------------------------------------- # Terminal #---------------------------------------------- class TerminalConstant(object): Y = 'Y' Yes = 'Yes' N = 'N' No = 'No' TRUE = 'True' FALSE = 'False' RdsSnapshotListNumber = 5 IamProfileListNumber = 6 #---------------------------------------------- # Services #---------------------------------------------- ServiceRegion = OrderedEnum([ 'UsEast1', 'UsWest1', 'UsWest2', 'EuWest1', 'EuCentral1', 'ApNortheast1', 'ApSoutheast1', 'ApSoutheast2', 'SaEast1', ]) AvailableServiceRegion = [ ServiceRegion.UsEast1, ServiceRegion.UsWest2, ServiceRegion.UsWest1, ServiceRegion.EuWest1, ServiceRegion.EuCentral1, ServiceRegion.ApSoutheast1, ServiceRegion.ApNortheast1, ServiceRegion.ApSoutheast2, ServiceRegion.SaEast1, ] ServiceRegionName = { ServiceRegion.ApNortheast1: 'Asia Pacific (Tokyo)', ServiceRegion.ApSoutheast1: 'Asia Pacific (Singapore)', ServiceRegion.ApSoutheast2: 'Asia Pacific (Sydney)', ServiceRegion.EuWest1: 'EU West (Ireland)', ServiceRegion.EuCentral1: 'EU Central (Frankfurt)', ServiceRegion.SaEast1: 'South America (Sao Paulo)', ServiceRegion.UsEast1: 'US East (Virginia)', ServiceRegion.UsWest1: 'US West (North California)', ServiceRegion.UsWest2: 'US West (Oregon)', } ServiceRegionId = { ServiceRegion.ApNortheast1: 'ap-northeast-1', ServiceRegion.ApSoutheast1: 'ap-southeast-1', ServiceRegion.ApSoutheast2: 'ap-southeast-2', ServiceRegion.EuWest1: 'eu-west-1', ServiceRegion.EuCentral1: 'eu-central-1', ServiceRegion.SaEast1: 'sa-east-1', ServiceRegion.UsEast1: 'us-east-1', ServiceRegion.UsWest1: 'us-west-1', ServiceRegion.UsWest2: 'us-west-2', } ServiceEndpoint = { ServiceRegion.ApNortheast1: 'https://elasticbeanstalk.ap-northeast-1.amazonaws.com', ServiceRegion.ApSoutheast1: 'https://elasticbeanstalk.ap-southeast-1.amazonaws.com', ServiceRegion.ApSoutheast2: 'https://elasticbeanstalk.ap-southeast-2.amazonaws.com', ServiceRegion.EuWest1: 'https://elasticbeanstalk.eu-west-1.amazonaws.com', ServiceRegion.EuCentral1: 'https://elasticbeanstalk.eu-central-1.amazonaws.com', ServiceRegion.SaEast1: 'https://elasticbeanstalk.sa-east-1.amazonaws.com', ServiceRegion.UsEast1: 'https://elasticbeanstalk.us-east-1.amazonaws.com', ServiceRegion.UsWest1: 'https://elasticbeanstalk.us-west-1.amazonaws.com', ServiceRegion.UsWest2: 'https://elasticbeanstalk.us-west-2.amazonaws.com', } SnippetBucket = { ServiceRegion.ApNortheast1: 'https://s3-ap-northeast-1.amazonaws.com/elasticbeanstalk-env-resources-ap-northeast-1/eb_snippets', ServiceRegion.ApSoutheast1: 'https://s3-ap-southeast-1.amazonaws.com/elasticbeanstalk-env-resources-ap-southeast-1/eb_snippets', ServiceRegion.ApSoutheast2: 'https://s3-ap-southeast-2.amazonaws.com/elasticbeanstalk-env-resources-ap-southeast-2/eb_snippets', ServiceRegion.EuWest1: 'https://s3-eu-west-1.amazonaws.com/elasticbeanstalk-env-resources-eu-west-1/eb_snippets', ServiceRegion.EuCentral1: 'https://s3.eu-central-1.amazonaws.com/elasticbeanstalk-env-resources-eu-central-1/eb_snippets', ServiceRegion.SaEast1: 'https://s3-sa-east-1.amazonaws.com/elasticbeanstalk-env-resources-sa-east-1/eb_snippets', ServiceRegion.UsEast1: 'https://s3.amazonaws.com/elasticbeanstalk-env-resources-us-east-1/eb_snippets', ServiceRegion.UsWest1: 'https://s3-us-west-1.amazonaws.com/elasticbeanstalk-env-resources-us-west-1/eb_snippets', ServiceRegion.UsWest2: 'https://s3-us-west-2.amazonaws.com/elasticbeanstalk-env-resources-us-west-2/eb_snippets', } PolicyBucket = { ServiceRegion.ApNortheast1: 'https://s3-ap-northeast-1.amazonaws.com/elasticbeanstalk-env-resources-ap-northeast-1/eb_policies', ServiceRegion.ApSoutheast1: 'https://s3-ap-southeast-1.amazonaws.com/elasticbeanstalk-env-resources-ap-southeast-1/eb_policies', ServiceRegion.ApSoutheast2: 'https://s3-ap-southeast-2.amazonaws.com/elasticbeanstalk-env-resources-ap-southeast-2/eb_policies', ServiceRegion.EuWest1: 'https://s3-eu-west-1.amazonaws.com/elasticbeanstalk-env-resources-eu-west-1/eb_policies', ServiceRegion.EuCentral1: 'https://s3.eu-central-1.amazonaws.com/elasticbeanstalk-env-resources-eu-central-1/eb_policies', ServiceRegion.SaEast1: 'https://s3-sa-east-1.amazonaws.com/elasticbeanstalk-env-resources-sa-east-1/eb_policies', ServiceRegion.UsEast1: 'https://s3.amazonaws.com/elasticbeanstalk-env-resources-us-east-1/eb_policies', ServiceRegion.UsWest1: 'https://s3-us-west-1.amazonaws.com/elasticbeanstalk-env-resources-us-west-1/eb_policies', ServiceRegion.UsWest2: 'https://s3-us-west-2.amazonaws.com/elasticbeanstalk-env-resources-us-west-2/eb_policies', } DevToolsEndpoint = { ServiceRegion.ApNortheast1: 'git.elasticbeanstalk.ap-northeast-1.amazonaws.com', ServiceRegion.ApSoutheast1: 'git.elasticbeanstalk.ap-southeast-1.amazonaws.com', ServiceRegion.ApSoutheast2: 'git.elasticbeanstalk.ap-southeast-2.amazonaws.com', ServiceRegion.EuWest1: 'git.elasticbeanstalk.eu-west-1.amazonaws.com', ServiceRegion.EuCentral1: '', ServiceRegion.SaEast1: 'git.elasticbeanstalk.sa-east-1.amazonaws.com', ServiceRegion.UsEast1: 'git.elasticbeanstalk.us-east-1.amazonaws.com', ServiceRegion.UsWest1: 'git.elasticbeanstalk.us-west-1.amazonaws.com', ServiceRegion.UsWest2: 'git.elasticbeanstalk.us-west-2.amazonaws.com', } class EbDefault(object): TailLog = 'tail' RoleAssumePolicyUrlMask = '{0}/role-assume-policy' DefaultRoleName = 'aws-elasticbeanstalk-ec2-role' DefaultInstanceProfileName = 'aws-elasticbeanstalk-ec2-role' class DevToolsDefault(object): NameDelimiter = '-' VersionNameRe = '^git-{0}-\d+$' VersionNameMask = 'git-{0}-{1}' AwsPush = ['git', 'aws.push'] AwsCreateAppVersion = ['git', 'aws.createapplicationversion'] #---------------------------------------------- # Solution stacks and sample app #---------------------------------------------- class DefaultAppSource(object): Namespace = 'aws:cloudformation:template:parameter' OptionName = 'AppSource' class LegacyContainer(object): Regex = '\(legacy\) *$' class TomcatAppContainer(object): Name = 'Tomcat' Regex = '^(32|64)bit Amazon Linux running Tomcat (6|7)(( (L|l)egacy)|( \((L|l)egacy\)))?$' class PhpAppContainer(object): Name = 'PHP' Regex = '^(32|64)bit Amazon Linux running PHP 5.3(( (L|l)egacy)|( \((L|l)egacy\)))?$' class IisAppContainer(object): Name = 'IIS' Regex = '^64bit Windows Server 2008 R2 running IIS 7.5(( (L|l)egacy)|( \((L|l)egacy\)))?$' class PythonAppContainer(object): Name = 'Python' Regex = '^(32|64)bit Amazon Linux running Python.*' class RubyAppContainer(object): Name = 'Ruby' Regex = '^(32|64)bit Amazon Linux running Ruby .*' #---------------------------------------------- # RDS #---------------------------------------------- RdsEndpoint = { ServiceRegion.ApNortheast1: 'https://rds.ap-northeast-1.amazonaws.com', ServiceRegion.ApSoutheast1: 'https://rds.ap-southeast-1.amazonaws.com', ServiceRegion.ApSoutheast2: 'https://rds.ap-southeast-2.amazonaws.com', ServiceRegion.EuWest1: 'https://rds.eu-west-1.amazonaws.com', ServiceRegion.EuCentral1: 'https://rds.eu-central-1.amazonaws.com', ServiceRegion.SaEast1: 'https://rds.sa-east-1.amazonaws.com', ServiceRegion.UsEast1: 'https://rds.amazonaws.com', ServiceRegion.UsWest1: 'https://rds.us-west-1.amazonaws.com', ServiceRegion.UsWest2: 'https://rds.us-west-2.amazonaws.com', } class RdsDefault(object): PasswordMismatchThreshold = 3 SnippetUrlMask = '{0}/rds/rds.json' SnippetName = 'RdsExtensionEB' SnippetAddOrder = 10000 SnippetRemoveOrder = -1 DbIdLengthLimit = { 'mysql': 63, 'sqlserver-ex': 15, 'sqlserver-se': 15, 'sqlserver-web': 15, } DeletionPolicySnapshot = 'Snapshot' DeletionPolicyDelete = 'Delete' ResourceType = 'AWS::RDS::DBInstance' HostnameType = 'Endpoint' PortType = 'Port' @classmethod def get_snippet_url(cls, region): return cls.SnippetUrlMask.format(SnippetBucket[region]) @classmethod def bool_to_del_policy(cls, switch): if switch: return cls.DeletionPolicySnapshot else: return cls.DeletionPolicyDelete @classmethod def del_policy_to_bool(cls, policy): if policy == cls.DeletionPolicySnapshot: return True else: return False Namespace = 'aws:rds:dbinstance' OptionNames = { ParameterName.RdsEngine: 'DBEngine', ParameterName.RdsEngineVersion: 'DBEngineVersion', ParameterName.RdsInstanceClass: 'DBInstanceClass', ParameterName.RdsAllocatedStorage: 'DBAllocatedStorage', ParameterName.RdsMultiAZ: 'MultiAZDatabase', ParameterName.RdsLicenseModel: 'DBLicenseModel', ParameterName.RdsSourceSnapshotName: 'DBSnapshotIdentifier', ParameterName.RdsDbName: 'DBName', ParameterName.RdsMasterUsername: 'DBUser', ParameterName.RdsMasterPassword: 'DBPassword', ParameterName.RdsDeletionPolicy: 'DBDeletionPolicy', } OptionMinSet = { ParameterName.RdsEngine, ParameterName.RdsSourceSnapshotName, ParameterName.RdsMasterPassword, ParameterName.RdsDeletionPolicy, } PasswordMinSize = 8 PasswordMaxSize = 41 #---------------------------------------------- # IAM #---------------------------------------------- IamEndpoint = 'https://iam.amazonaws.com' IamRegion = 'us-east-1' #---------------------------------------------- # Application and environment default #---------------------------------------------- class EnvironmentStatus(object): Launching = 'Launching' Ready = 'Ready' Updating = 'Updating' Terminating = 'Terminating' Terminated = 'Terminated' class EnvironmentHealth(object): Green = 'Green' Yellow = 'Yellow' Red = 'Red' Grey = 'Grey' class EventSeverity(object): Trace = 'TRACE' Debug = 'Debug' Info = 'INFO' Warn = 'WARN' Error = 'ERROR' Fatal = 'FATAL' class ValidationSeverity(object): SeverityError = 'error' SeverityWarning = 'warning' class ServiceDefault(object): """ Defines CLI related constant values. """ DEFAULT_VERSION_NAME = 'Sample Application' SERVICE_CALL_MAX_RETRY = 5 CONNECTION_TIMEOUT_IN_SEC = 30 WAIT_TIMEOUT_IN_SEC = 600 UPDATE_TIMEOUT_IN_SEC = 300 RDS_ADDITION_TIMEOUT_IN_SEC = 300 POLL_DELAY_IN_SEC = 5 CREATE_ENV_POLL_DELAY = 3 TERMINATE_ENV_POLL_DELAY = 0 UPDATE_ENV_POLL_DELAY = 0 CHAR_CODEC = 'utf-8' ENABLED = 'Enabled' USER_AGENT = 'eb ' + EbCliVersion STATUS_EVENT_LEVEL = EventSeverity.Warn STATUS_EVENT_MAX_NUM = 3 EVENT_DEFAULT_NUM = 10 class Environment(object): REGEX_NAME_FILTER = '[^A-Za-z0-9\-]+' NAME_POSTFIX = '-env' MAX_NAME_LEN = 23 BRANCH_NAME_SEPERATOR = '-' OutputLevel = OrderedEnum([ 'Info', 'ResultOnly', 'Quiet', 'Silence', ]) #---------------------------------------------- # Configuration file and log file #---------------------------------------------- class FileDefaultParameter(object): RotationMaxRetry = 1000 class OSSpecific(object): '''Windows specific constants''' WindowsName = 'Windows' WindowsClimbUpDepth = 2 WindowsModuleScriptPath = 'AWSDevTools\\Windows' WindowsModuleScriptName = 'AWSDevTools-OneTimeSetup.bat' WindowsRepoScript = 'AWSDevTools\\Windows\\AWSDevTools-RepositorySetup.bat' '''Nix specific constants''' LinuxName = 'Linux' LinuxClimbUpDepth = 3 LinuxRepoScript = 'AWSDevTools/Linux/AWSDevTools-RepositorySetup.sh' class AwsCredentialFileDefault(object): FilePath = '.elasticbeanstalk' FileName = 'aws_credential_file' OSVariableName = 'AWS_CREDENTIAL_FILE' KeyName = { ParameterName.AwsAccessKeyId: 'AWSAccessKeyId', ParameterName.AwsSecretAccessKey: 'AWSSecretKey', ParameterName.RdsMasterPassword: 'RDSMasterPassword', } class EbLocalDir(object): Path = '.elasticbeanstalk' Name = Path + '/' NameRe = Path + '/' LogDir = 'log' class EbLogFile(object): Name = 'eb-cli.log' NameRe = '.*eb-cli\.log.*' class EbConfigFile(object): Name = 'config' NameRe = '.*\config.*' SectionNameDelimiter = ':' RootSectionName = 'global' RootSectionKeys = { ParameterName.AwsCredentialFile, ParameterName.ApplicationName, ParameterName.ApplicationVersionName, ParameterName.DevToolsEndpoint, ParameterName.EnvironmentName, ParameterName.OptionSettingFile, ParameterName.EnvironmentTier, ParameterName.SolutionStack, ParameterName.Region, ParameterName.ServiceEndpoint, ParameterName.RdsEnabled, ParameterName.RdsSourceSnapshotName, ParameterName.RdsDeletionPolicy, ParameterName.InstanceProfileName, ParameterName.EnvironmentType, } BranchResetParameters = { ParameterName.ApplicationName: ParameterName.OriginalApplicationName, ParameterName.Region: ParameterName.OriginalRegion, ParameterName.SolutionStack: ParameterName.OriginalSolutionStack, } BranchSectionName = 'branches' BranchSectionPrefix = 'branch' + SectionNameDelimiter BranchSectionKeys = { ParameterName.ApplicationVersionName, ParameterName.EnvironmentName, ParameterName.EnvironmentTier, ParameterName.OptionSettingFile, ParameterName.RdsEnabled, ParameterName.RdsSourceSnapshotName, ParameterName.RdsDeletionPolicy, ParameterName.InstanceProfileName, ParameterName.EnvironmentType, } BranchSectionHiddenKeys = { ParameterName.RdsMasterPassword, } # Map from section name to (section existence condition, list of member keys) KnownSections = { RootSectionName: (ParameterName.ApplicationName, RootSectionKeys), } class OptionSettingFile(object): Name = 'optionsettings' class CABundle(object): Path = '.' Name = 'ca-bundle.crt' class FileErrorConstant(object): FileNotFoundErrorCode = 2 FileNotFoundErrorMsg = 'No such file or directory' #---------------------------------------------- # Git and DevTools file #---------------------------------------------- class GitDefault(object): HeadRe = '\* .+' GetBranch = ['git', 'branch'] GetHeadHash = ['git', 'rev-parse', 'HEAD'] class GitIgnoreFile(object): Name = '.gitignore' Path = '.' Files = { EbLocalDir, } class DevToolsConfigFile(object): Name = 'config' Path = '.git' InitHelpUrl = 'http://docs.amazonwebservices.com/elasticbeanstalk' \ '/latest/dg/command-reference-get-started.html' #---------------------------------------------- # OptionSettingList #---------------------------------------------- LocalOptionSettings = { 'aws:autoscaling:launchconfiguration': { 'EC2KeyName', 'InstanceType', }, 'aws:elasticbeanstalk:sns:topics': { 'Notification Endpoint', 'Notification Protocol', }, 'aws:elasticbeanstalk:monitoring': { 'Automatically Terminate Unhealthy Instances', }, 'aws:elasticbeanstalk:hostmanager': { 'LogPublicationControl', }, 'aws:elasticbeanstalk:application': { 'Application Healthcheck URL', }, 'aws:autoscaling:asg': { 'MaxSize', 'MinSize', 'Custom Availability Zones', }, 'aws:autoscaling:updatepolicy:rollingupdate': { 'RollingUpdateEnabled', }, 'aws:rds:dbinstance': { 'DBDeletionPolicy', 'DBEngine', 'DBInstanceClass', 'DBSnapshotIdentifier', 'DBUser', }, 'aws:ec2:vpc': { 'VPCId', 'Subnets', 'ELBSubnets', 'DBSubnets', 'ELBScheme', 'AutoScalingGroupScheme', }, 'aws:elasticbeanstalk:sqsd': { 'WorkerQueueURL', 'HttpPath', 'MimeType', 'MaxRetries', 'HttpConnections', 'ConnectTimeout', 'InactivityTimeout', 'VisibilityTimeout', 'RetentionPeriod', }, } OptionSettingContainerPrefix = 'aws:elasticbeanstalk:container' OptionSettingTemplatePrefix = 'aws:cloudformation:template' class OptionSettingApplicationEnvironment(object): Namespace = 'aws:elasticbeanstalk:application:environment' IgnoreOptionNames = { 'AWS_ACCESS_KEY_ID', 'AWS_SECRET_KEY', } class OptionSettingVPC(object): Namespace = 'aws:ec2:vpc' MagicOptionName = 'Subnets' DBSubnets = 'DBSubnets' TrimOption = { 'aws:autoscaling:asg': { 'Custom Availability Zones', }, } class OptionSettingIAMProfile(object): Namespace = 'aws:autoscaling:launchconfiguration' OptionName = 'IamInstanceProfile' class OptionSettingEnvironmentType(object): Namespace = 'aws:elasticbeanstalk:environment' OptionName = 'EnvironmentType'