code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import math
import logging
import warnings
import scipy.constants
import scipy.interpolate
from tkp.telescope.lofar import antennaarrays
logger = logging.getLogger(__name__)
ANTENNAE_PER_TILE = 16
TILES_PER_CORE_STATION = 24
TILES_PER_REMOTE_STATION = 48
TILES_PER_INTL_STATION = 96
def noise_level(freq_eff, bandwidth, tau_time, antenna_set, Ncore, Nremote,
Nintl):
"""
Returns the theoretical noise level (in Jy) given the supplied array
antenna_set.
:param bandwidth: in Hz
:param tau_time: in seconds
:param inner: in case of LBA, inner or outer
:param antenna_set: LBA_INNER, LBA_OUTER, LBA_SPARSE, LBA or HBA
"""
if antenna_set.startswith("LBA"):
ds_core = antennaarrays.core_dipole_distances[antenna_set]
Aeff_core = sum([Aeff_dipole(freq_eff, x) for x in ds_core])
ds_remote = antennaarrays.remote_dipole_distances[antenna_set]
Aeff_remote = sum([Aeff_dipole(freq_eff, x) for x in ds_remote])
ds_intl = antennaarrays.intl_dipole_distances[antenna_set]
Aeff_intl = sum([Aeff_dipole(freq_eff, x) for x in ds_intl])
else:
Aeff_core = ANTENNAE_PER_TILE * TILES_PER_CORE_STATION * \
Aeff_dipole(freq_eff)
Aeff_remote = ANTENNAE_PER_TILE * TILES_PER_REMOTE_STATION * \
Aeff_dipole(freq_eff)
Aeff_intl = ANTENNAE_PER_TILE * TILES_PER_INTL_STATION * \
Aeff_dipole(freq_eff)
# c = core, r = remote, i = international
# so for example cc is core-core baseline
Ssys_c = system_sensitivity(freq_eff, Aeff_core)
Ssys_r = system_sensitivity(freq_eff, Aeff_remote)
Ssys_i = system_sensitivity(freq_eff, Aeff_intl)
baselines_cc = (Ncore * (Ncore - 1)) / 2
baselines_rr = (Nremote * (Nremote - 1)) / 2
baselines_ii = (Nintl * (Nintl - 1)) / 2
baselines_cr = (Ncore * Nremote)
baselines_ci = (Ncore * Nintl)
baselines_ri = (Nremote * Nintl)
#baselines_total = baselines_cc + baselines_rr + baselines_ii +\
# baselines_cr + baselines_ci + baselines_ri
# baseline noise, for example cc is core-core
temp_cc = Ssys_c
temp_rr = Ssys_r
temp_ii = Ssys_i
#temp_cr = math.sqrt(SEFD_cc) * math.sqrt(SEFD_rr)
#temp_ci = math.sqrt(SEFD_cc) * math.sqrt(SEFD_ii)
#temp_ri = math.sqrt(SEFD_rr) * math.sqrt(SEFD_ii)
# The noise level in a LOFAR image
t_cc = baselines_cc / (temp_cc * temp_cc)
t_rr = baselines_rr / (temp_rr * temp_cc)
t_ii = baselines_ii / (temp_ii * temp_ii)
t_cr = baselines_cr / (temp_cc * temp_rr)
t_ci = baselines_ci / (temp_cc * temp_ii)
t_ri = baselines_ri / (temp_rr * temp_ii)
# factor for increase of noise due to the weighting scheme
W = 1 # taken from PHP script
image_sens = W / math.sqrt(4 * bandwidth * tau_time *
(t_cc + t_rr + t_ii + t_cr + t_ci + t_ri))
return image_sens
def Aeff_dipole(freq_eff, distance=None):
"""
The effective area of each dipole in the array is determined by its
distance to the nearest dipole (d) within the full array.
:param freq_eff: Frequency
:param distance: Distance to nearest dipole, only required for LBA.
"""
wavelength = scipy.constants.c/freq_eff
if wavelength > 3: # LBA dipole
if not distance:
msg = "Distance to nearest dipole required for LBA noise calculation"
logger.error(msg)
warnings.warn(msg)
distance = 1
return min(pow(wavelength, 2) / 3, (math.pi * pow(distance, 2)) / 4)
else: # HBA dipole
return min(pow(wavelength, 2) / 3, 1.5625)
def system_sensitivity(freq_eff, Aeff):
"""
Returns the SEFD of a system, given the freq_eff and effective
collecting area. Returns SEFD in Jansky's.
"""
wavelength = scipy.constants.c / freq_eff
# Ts0 = 60 +/- 20 K for Galactic latitudes between 10 and 90 degrees.
Ts0 = 60
# system efficiency factor (~ 1.0)
n = 1
# For all LOFAR frequencies the sky brightness temperature is dominated by
# the Galactic radiation, which depends strongly on the wavelength
Tsky = Ts0 * wavelength ** 2.55
#The instrumental noise temperature follows from measurements or simulations
# This is a quick & dirty approach based roughly on Fig 5 here
# <http://www.skatelescope.org/uploaded/59513_113_Memo_Nijboer.pdf>
sensitivities = [
(0, 0),
(10e6, 0.1 * Tsky),
(40e6, 0.7 * Tsky),
(50e6, 0.85 * Tsky),
(55e6, 0.9 * Tsky),
(60e6, 0.85 * Tsky),
(70e6, 0.6 * Tsky),
(80e6, 0.3 * Tsky),
(90e6, 0 * Tsky),
(110e6, 0 * Tsky),
(120e6, 200),
(300e6, 200)
]
x, y = zip(*sensitivities)
sensitivity = scipy.interpolate.interp1d(x, y, kind='linear')
Tinst = sensitivity(freq_eff)
Tsys = Tsky + Tinst
# SEFD or system sensitivity
S = (2 * n * scipy.constants.k / Aeff) * Tsys
# S is in Watts per square metre per Hertz. One Jansky = 10**-26 Watts/sq
# metre/Hz
return S * 10**26 | tkp/telescope/lofar/noise.py | import math
import logging
import warnings
import scipy.constants
import scipy.interpolate
from tkp.telescope.lofar import antennaarrays
logger = logging.getLogger(__name__)
ANTENNAE_PER_TILE = 16
TILES_PER_CORE_STATION = 24
TILES_PER_REMOTE_STATION = 48
TILES_PER_INTL_STATION = 96
def noise_level(freq_eff, bandwidth, tau_time, antenna_set, Ncore, Nremote,
Nintl):
"""
Returns the theoretical noise level (in Jy) given the supplied array
antenna_set.
:param bandwidth: in Hz
:param tau_time: in seconds
:param inner: in case of LBA, inner or outer
:param antenna_set: LBA_INNER, LBA_OUTER, LBA_SPARSE, LBA or HBA
"""
if antenna_set.startswith("LBA"):
ds_core = antennaarrays.core_dipole_distances[antenna_set]
Aeff_core = sum([Aeff_dipole(freq_eff, x) for x in ds_core])
ds_remote = antennaarrays.remote_dipole_distances[antenna_set]
Aeff_remote = sum([Aeff_dipole(freq_eff, x) for x in ds_remote])
ds_intl = antennaarrays.intl_dipole_distances[antenna_set]
Aeff_intl = sum([Aeff_dipole(freq_eff, x) for x in ds_intl])
else:
Aeff_core = ANTENNAE_PER_TILE * TILES_PER_CORE_STATION * \
Aeff_dipole(freq_eff)
Aeff_remote = ANTENNAE_PER_TILE * TILES_PER_REMOTE_STATION * \
Aeff_dipole(freq_eff)
Aeff_intl = ANTENNAE_PER_TILE * TILES_PER_INTL_STATION * \
Aeff_dipole(freq_eff)
# c = core, r = remote, i = international
# so for example cc is core-core baseline
Ssys_c = system_sensitivity(freq_eff, Aeff_core)
Ssys_r = system_sensitivity(freq_eff, Aeff_remote)
Ssys_i = system_sensitivity(freq_eff, Aeff_intl)
baselines_cc = (Ncore * (Ncore - 1)) / 2
baselines_rr = (Nremote * (Nremote - 1)) / 2
baselines_ii = (Nintl * (Nintl - 1)) / 2
baselines_cr = (Ncore * Nremote)
baselines_ci = (Ncore * Nintl)
baselines_ri = (Nremote * Nintl)
#baselines_total = baselines_cc + baselines_rr + baselines_ii +\
# baselines_cr + baselines_ci + baselines_ri
# baseline noise, for example cc is core-core
temp_cc = Ssys_c
temp_rr = Ssys_r
temp_ii = Ssys_i
#temp_cr = math.sqrt(SEFD_cc) * math.sqrt(SEFD_rr)
#temp_ci = math.sqrt(SEFD_cc) * math.sqrt(SEFD_ii)
#temp_ri = math.sqrt(SEFD_rr) * math.sqrt(SEFD_ii)
# The noise level in a LOFAR image
t_cc = baselines_cc / (temp_cc * temp_cc)
t_rr = baselines_rr / (temp_rr * temp_cc)
t_ii = baselines_ii / (temp_ii * temp_ii)
t_cr = baselines_cr / (temp_cc * temp_rr)
t_ci = baselines_ci / (temp_cc * temp_ii)
t_ri = baselines_ri / (temp_rr * temp_ii)
# factor for increase of noise due to the weighting scheme
W = 1 # taken from PHP script
image_sens = W / math.sqrt(4 * bandwidth * tau_time *
(t_cc + t_rr + t_ii + t_cr + t_ci + t_ri))
return image_sens
def Aeff_dipole(freq_eff, distance=None):
"""
The effective area of each dipole in the array is determined by its
distance to the nearest dipole (d) within the full array.
:param freq_eff: Frequency
:param distance: Distance to nearest dipole, only required for LBA.
"""
wavelength = scipy.constants.c/freq_eff
if wavelength > 3: # LBA dipole
if not distance:
msg = "Distance to nearest dipole required for LBA noise calculation"
logger.error(msg)
warnings.warn(msg)
distance = 1
return min(pow(wavelength, 2) / 3, (math.pi * pow(distance, 2)) / 4)
else: # HBA dipole
return min(pow(wavelength, 2) / 3, 1.5625)
def system_sensitivity(freq_eff, Aeff):
"""
Returns the SEFD of a system, given the freq_eff and effective
collecting area. Returns SEFD in Jansky's.
"""
wavelength = scipy.constants.c / freq_eff
# Ts0 = 60 +/- 20 K for Galactic latitudes between 10 and 90 degrees.
Ts0 = 60
# system efficiency factor (~ 1.0)
n = 1
# For all LOFAR frequencies the sky brightness temperature is dominated by
# the Galactic radiation, which depends strongly on the wavelength
Tsky = Ts0 * wavelength ** 2.55
#The instrumental noise temperature follows from measurements or simulations
# This is a quick & dirty approach based roughly on Fig 5 here
# <http://www.skatelescope.org/uploaded/59513_113_Memo_Nijboer.pdf>
sensitivities = [
(0, 0),
(10e6, 0.1 * Tsky),
(40e6, 0.7 * Tsky),
(50e6, 0.85 * Tsky),
(55e6, 0.9 * Tsky),
(60e6, 0.85 * Tsky),
(70e6, 0.6 * Tsky),
(80e6, 0.3 * Tsky),
(90e6, 0 * Tsky),
(110e6, 0 * Tsky),
(120e6, 200),
(300e6, 200)
]
x, y = zip(*sensitivities)
sensitivity = scipy.interpolate.interp1d(x, y, kind='linear')
Tinst = sensitivity(freq_eff)
Tsys = Tsky + Tinst
# SEFD or system sensitivity
S = (2 * n * scipy.constants.k / Aeff) * Tsys
# S is in Watts per square metre per Hertz. One Jansky = 10**-26 Watts/sq
# metre/Hz
return S * 10**26 | 0.635788 | 0.428293 |
from Pipeline.main.PositionSize.Position import Position
from Pipeline.main.Utils.ExchangeUtil import ExchangeUtil
from Pipeline.main.Utils.AccountUtil import AccountUtil
from Pipeline.main.Utils.EmailUtil import EmailUtil
from Pipeline.main.PullData.Price.Pull import Pull
from pymongo import MongoClient
import numpy as np
import logging
import Settings
import yaml
import time
class OpenTrade:
def __init__(self, stratName, isLive=False):
self.stratName = stratName
logging.debug("Initialising OpenTrade()")
self.isLive = isLive
self.resourcePath = "%s/Pipeline/resources/%s" % (Settings.BASE_PATH, stratName)
self.db = MongoClient("localhost", 27017)[stratName]
self.EU = ExchangeUtil()
self.P = Position(stratName)
self.pull = Pull()
self.capDict = None
def initRun(self):
with open("%s/capital.yml" % self.resourcePath) as capFile:
self.capDict = yaml.load(capFile)
def _getPrice(self, fills):
return round(
sum([float(val["price"]) * float(val["qty"]) for val in fills])
/ sum([float(val["qty"]) for val in fills]),
8,
)
def open(self, assetVals):
logging.debug("Starting OpenTrade.open")
# assetVals = (name, exchange, price)
capAllocated = self.P.getSize(asset=assetVals[0])
posSize = capAllocated * (1 - self.EU.fees(exchange=assetVals[1]))
if not self.isLive:
openDict = {
"assetName": assetVals[0],
"openPrice": assetVals[2],
"currentPrice": assetVals[2],
"periods": 0,
"positionSize": posSize,
"paperSize": posSize,
"TSOpen": round(time.time()),
"exchange": assetVals[1],
}
else:
try:
quantity = round(capAllocated / assetVals[2], 2)
orderDict = self.pull.makeTrade(
exchange=assetVals[1],
asset=assetVals[0],
quantity=np.floor(quantity),
dir="BUY",
)
buyPrice = self._getPrice(orderDict["fills"])
openDict = {
"assetName": assetVals[0],
"openPrice": buyPrice,
"currentPrice": buyPrice,
"periods": 0,
"positionSize": float(orderDict["cummulativeQuoteQty"]),
"posSizeBase": float(orderDict["executedQty"]),
"TSOpen": round(time.time()),
"exchange": assetVals[1],
"clientOrderId": orderDict["clientOrderId"],
}
except KeyError as e:
EmailUtil(strat=self.stratName).errorExit(
file=self.stratName, funct="Enter.runNorm()", message=e
)
logging.error("orderDict: %s" % orderDict)
raise Exception(
"Failed with error message: %s and assetVals: %s" % (e, assetVals)
)
self.db["currentPositions"].insert_one(openDict)
self.capDict["paperCurrent"] -= round(
capAllocated - openDict["positionSize"], 6
)
self.capDict["liquidCurrent"] -= capAllocated
def updateBooks(self):
logging.debug("Starting OpenTrade.updateBooks()")
if not self.isLive:
self.capDict["percentAllocated"] = round(
1 - self.capDict["liquidCurrent"] / self.capDict["paperCurrent"], 3
)
self.capDict["paperPnL"] = round(
self.capDict["paperCurrent"] / self.capDict["initialCapital"], 3
)
else:
# **TODO hard coding 'Binance' as whole capDict system will need to change to capListDict when adding multiple
self.capDict = AccountUtil(exchange="Binance").getValue(
initCapital=self.capDict["initialCapital"]
)
with open("%s/capital.yml" % self.resourcePath, "w") as capFile:
yaml.dump(self.capDict, capFile) | Pipeline/main/Strategy/Open/OpenTrade.py | from Pipeline.main.PositionSize.Position import Position
from Pipeline.main.Utils.ExchangeUtil import ExchangeUtil
from Pipeline.main.Utils.AccountUtil import AccountUtil
from Pipeline.main.Utils.EmailUtil import EmailUtil
from Pipeline.main.PullData.Price.Pull import Pull
from pymongo import MongoClient
import numpy as np
import logging
import Settings
import yaml
import time
class OpenTrade:
def __init__(self, stratName, isLive=False):
self.stratName = stratName
logging.debug("Initialising OpenTrade()")
self.isLive = isLive
self.resourcePath = "%s/Pipeline/resources/%s" % (Settings.BASE_PATH, stratName)
self.db = MongoClient("localhost", 27017)[stratName]
self.EU = ExchangeUtil()
self.P = Position(stratName)
self.pull = Pull()
self.capDict = None
def initRun(self):
with open("%s/capital.yml" % self.resourcePath) as capFile:
self.capDict = yaml.load(capFile)
def _getPrice(self, fills):
return round(
sum([float(val["price"]) * float(val["qty"]) for val in fills])
/ sum([float(val["qty"]) for val in fills]),
8,
)
def open(self, assetVals):
logging.debug("Starting OpenTrade.open")
# assetVals = (name, exchange, price)
capAllocated = self.P.getSize(asset=assetVals[0])
posSize = capAllocated * (1 - self.EU.fees(exchange=assetVals[1]))
if not self.isLive:
openDict = {
"assetName": assetVals[0],
"openPrice": assetVals[2],
"currentPrice": assetVals[2],
"periods": 0,
"positionSize": posSize,
"paperSize": posSize,
"TSOpen": round(time.time()),
"exchange": assetVals[1],
}
else:
try:
quantity = round(capAllocated / assetVals[2], 2)
orderDict = self.pull.makeTrade(
exchange=assetVals[1],
asset=assetVals[0],
quantity=np.floor(quantity),
dir="BUY",
)
buyPrice = self._getPrice(orderDict["fills"])
openDict = {
"assetName": assetVals[0],
"openPrice": buyPrice,
"currentPrice": buyPrice,
"periods": 0,
"positionSize": float(orderDict["cummulativeQuoteQty"]),
"posSizeBase": float(orderDict["executedQty"]),
"TSOpen": round(time.time()),
"exchange": assetVals[1],
"clientOrderId": orderDict["clientOrderId"],
}
except KeyError as e:
EmailUtil(strat=self.stratName).errorExit(
file=self.stratName, funct="Enter.runNorm()", message=e
)
logging.error("orderDict: %s" % orderDict)
raise Exception(
"Failed with error message: %s and assetVals: %s" % (e, assetVals)
)
self.db["currentPositions"].insert_one(openDict)
self.capDict["paperCurrent"] -= round(
capAllocated - openDict["positionSize"], 6
)
self.capDict["liquidCurrent"] -= capAllocated
def updateBooks(self):
logging.debug("Starting OpenTrade.updateBooks()")
if not self.isLive:
self.capDict["percentAllocated"] = round(
1 - self.capDict["liquidCurrent"] / self.capDict["paperCurrent"], 3
)
self.capDict["paperPnL"] = round(
self.capDict["paperCurrent"] / self.capDict["initialCapital"], 3
)
else:
# **TODO hard coding 'Binance' as whole capDict system will need to change to capListDict when adding multiple
self.capDict = AccountUtil(exchange="Binance").getValue(
initCapital=self.capDict["initialCapital"]
)
with open("%s/capital.yml" % self.resourcePath, "w") as capFile:
yaml.dump(self.capDict, capFile) | 0.361954 | 0.161287 |
from contextlib import contextmanager
from unittest.mock import AsyncMock, MagicMock, patch
from aiosenseme import SensemeDevice, SensemeDiscovery
from homeassistant.components.senseme import config_flow
MOCK_NAME = "<NAME>"
MOCK_UUID = "77a6b7b3-925d-4695-a415-76d76dca4444"
MOCK_ADDRESS = "127.0.0.1"
device = MagicMock(auto_spec=SensemeDevice)
device.async_update = AsyncMock()
device.model = "Haiku Fan"
device.fan_speed_max = 7
device.mac = "aa:bb:cc:dd:ee:ff"
device.fan_dir = "REV"
device.room_name = "Main"
device.room_type = "Main"
device.fw_version = "1"
device.fan_autocomfort = "on"
device.fan_smartmode = "on"
device.fan_whoosh_mode = "on"
device.name = MOCK_NAME
device.uuid = MOCK_UUID
device.address = MOCK_ADDRESS
device.get_device_info = {
"name": MOCK_NAME,
"uuid": MOCK_UUID,
"mac": "20:F8:5E:92:5A:75",
"address": MOCK_ADDRESS,
"base_model": "FAN,HAIKU,HSERIES",
"has_light": False,
"has_sensor": True,
"is_fan": True,
"is_light": False,
}
device_alternate_ip = MagicMock(auto_spec=SensemeDevice)
device_alternate_ip.async_update = AsyncMock()
device_alternate_ip.model = "Haiku Fan"
device_alternate_ip.fan_speed_max = 7
device_alternate_ip.mac = "aa:bb:cc:dd:ee:ff"
device_alternate_ip.fan_dir = "REV"
device_alternate_ip.room_name = "Main"
device_alternate_ip.room_type = "Main"
device_alternate_ip.fw_version = "1"
device_alternate_ip.fan_autocomfort = "on"
device_alternate_ip.fan_smartmode = "on"
device_alternate_ip.fan_whoosh_mode = "on"
device_alternate_ip.name = MOCK_NAME
device_alternate_ip.uuid = MOCK_UUID
device_alternate_ip.address = "127.0.0.8"
device_alternate_ip.get_device_info = {
"name": MOCK_NAME,
"uuid": MOCK_UUID,
"mac": "20:F8:5E:92:5A:75",
"address": "127.0.0.8",
"base_model": "FAN,HAIKU,HSERIES",
"has_light": False,
"has_sensor": True,
"is_fan": True,
"is_light": False,
}
device2 = MagicMock(auto_spec=SensemeDevice)
device2.async_update = AsyncMock()
device2.model = "Haiku Fan"
device2.fan_speed_max = 7
device2.mac = "aa:bb:cc:dd:ee:ff"
device2.fan_dir = "FWD"
device2.room_name = "Main"
device2.room_type = "Main"
device2.fw_version = "1"
device2.fan_autocomfort = "on"
device2.fan_smartmode = "on"
device2.fan_whoosh_mode = "on"
device2.name = "Device 2"
device2.uuid = "uuid2"
device2.address = "127.0.0.2"
device2.get_device_info = {
"name": "Device 2",
"uuid": "uuid2",
"mac": "20:F8:5E:92:5A:76",
"address": "127.0.0.2",
"base_model": "FAN,HAIKU,HSERIES",
"has_light": True,
"has_sensor": True,
"is_fan": True,
"is_light": False,
}
MOCK_DEVICE = device
MOCK_DEVICE_ALTERNATE_IP = device_alternate_ip
MOCK_DEVICE2 = device2
def _patch_discovery(device=None, no_device=None):
"""Patch discovery."""
mock_senseme_discovery = MagicMock(auto_spec=SensemeDiscovery)
if not no_device:
mock_senseme_discovery.devices = [device or MOCK_DEVICE]
@contextmanager
def _patcher():
with patch.object(config_flow, "DISCOVER_TIMEOUT", 0), patch(
"homeassistant.components.senseme.discovery.SensemeDiscovery",
return_value=mock_senseme_discovery,
):
yield
return _patcher() | tests/components/senseme/__init__.py |
from contextlib import contextmanager
from unittest.mock import AsyncMock, MagicMock, patch
from aiosenseme import SensemeDevice, SensemeDiscovery
from homeassistant.components.senseme import config_flow
MOCK_NAME = "<NAME>"
MOCK_UUID = "77a6b7b3-925d-4695-a415-76d76dca4444"
MOCK_ADDRESS = "127.0.0.1"
device = MagicMock(auto_spec=SensemeDevice)
device.async_update = AsyncMock()
device.model = "Haiku Fan"
device.fan_speed_max = 7
device.mac = "aa:bb:cc:dd:ee:ff"
device.fan_dir = "REV"
device.room_name = "Main"
device.room_type = "Main"
device.fw_version = "1"
device.fan_autocomfort = "on"
device.fan_smartmode = "on"
device.fan_whoosh_mode = "on"
device.name = MOCK_NAME
device.uuid = MOCK_UUID
device.address = MOCK_ADDRESS
device.get_device_info = {
"name": MOCK_NAME,
"uuid": MOCK_UUID,
"mac": "20:F8:5E:92:5A:75",
"address": MOCK_ADDRESS,
"base_model": "FAN,HAIKU,HSERIES",
"has_light": False,
"has_sensor": True,
"is_fan": True,
"is_light": False,
}
device_alternate_ip = MagicMock(auto_spec=SensemeDevice)
device_alternate_ip.async_update = AsyncMock()
device_alternate_ip.model = "Haiku Fan"
device_alternate_ip.fan_speed_max = 7
device_alternate_ip.mac = "aa:bb:cc:dd:ee:ff"
device_alternate_ip.fan_dir = "REV"
device_alternate_ip.room_name = "Main"
device_alternate_ip.room_type = "Main"
device_alternate_ip.fw_version = "1"
device_alternate_ip.fan_autocomfort = "on"
device_alternate_ip.fan_smartmode = "on"
device_alternate_ip.fan_whoosh_mode = "on"
device_alternate_ip.name = MOCK_NAME
device_alternate_ip.uuid = MOCK_UUID
device_alternate_ip.address = "127.0.0.8"
device_alternate_ip.get_device_info = {
"name": MOCK_NAME,
"uuid": MOCK_UUID,
"mac": "20:F8:5E:92:5A:75",
"address": "127.0.0.8",
"base_model": "FAN,HAIKU,HSERIES",
"has_light": False,
"has_sensor": True,
"is_fan": True,
"is_light": False,
}
device2 = MagicMock(auto_spec=SensemeDevice)
device2.async_update = AsyncMock()
device2.model = "Haiku Fan"
device2.fan_speed_max = 7
device2.mac = "aa:bb:cc:dd:ee:ff"
device2.fan_dir = "FWD"
device2.room_name = "Main"
device2.room_type = "Main"
device2.fw_version = "1"
device2.fan_autocomfort = "on"
device2.fan_smartmode = "on"
device2.fan_whoosh_mode = "on"
device2.name = "Device 2"
device2.uuid = "uuid2"
device2.address = "127.0.0.2"
device2.get_device_info = {
"name": "Device 2",
"uuid": "uuid2",
"mac": "20:F8:5E:92:5A:76",
"address": "127.0.0.2",
"base_model": "FAN,HAIKU,HSERIES",
"has_light": True,
"has_sensor": True,
"is_fan": True,
"is_light": False,
}
MOCK_DEVICE = device
MOCK_DEVICE_ALTERNATE_IP = device_alternate_ip
MOCK_DEVICE2 = device2
def _patch_discovery(device=None, no_device=None):
"""Patch discovery."""
mock_senseme_discovery = MagicMock(auto_spec=SensemeDiscovery)
if not no_device:
mock_senseme_discovery.devices = [device or MOCK_DEVICE]
@contextmanager
def _patcher():
with patch.object(config_flow, "DISCOVER_TIMEOUT", 0), patch(
"homeassistant.components.senseme.discovery.SensemeDiscovery",
return_value=mock_senseme_discovery,
):
yield
return _patcher() | 0.73782 | 0.154663 |
import matplotlib.pyplot as plt
from numpy import gradient, inf, linspace, pi, power, sqrt, std
from pandas import read_csv
from scipy.integrate import romb, simps
from scipy.optimize import least_squares as ls
from scipy.stats import gaussian_kde as kde
from fast_deriv import FastUnivariateDensityDerivative as FUDD
def _fast_h_fun(h, N, X, c1, c2, eps):
lam = c2 * h ** (5 / 7)
D4 = FUDD(N, N, X, X, float(lam), 4, eps)
D4.evaluate()
phi4 = sum(D4.pD) / (N - 1)
return h - c1 * phi4 ** (-1 / 5)
def _get_scale_list(x_list):
shift = min(x_list)
scale = 1 / (max(x_list) - shift)
X_shifted_scale = [(x - shift) * scale for x in x_list]
return X_shifted_scale, scale
def _get_opt_h(x_list, eps):
N = len(x_list)
X_shifted_scale, scale = _get_scale_list(x_list)
sigma = std(X_shifted_scale)
phi6 = (-15 / (16 * sqrt(pi))) * power(sigma, -7)
phi8 = (105 / (32 * sqrt(pi))) * power(sigma, -9)
g1 = (-6 / (sqrt(2 * pi) * phi6 * N)) ** (1 / 7)
g2 = (30 / (sqrt(2 * pi) * phi8 * N)) ** (1 / 9)
D4 = FUDD(N, N, X_shifted_scale, X_shifted_scale, g1, 4, eps)
D6 = FUDD(N, N, X_shifted_scale, X_shifted_scale, g2, 6, eps)
D4.evaluate()
D6.evaluate()
phi4 = sum(D4.pD) / (N - 1)
phi6 = sum(D6.pD) / (N - 1)
constant1 = (1 / (2 * sqrt(pi) * N)) ** (1 / 5)
constant2 = (-6 * sqrt(2) * phi4 / phi6) ** (1 / 7)
h_initial = constant1 * phi4 ** (-1 / 5)
h = ls(
_fast_h_fun,
h_initial,
bounds=(0, inf),
ftol=1e-14,
xtol=1e-14,
verbose=0,
args=(N, X_shifted_scale, constant1, constant2, eps),
)
h = float(h.x) / scale
return h
def _get_uni_kde(data, bw_method="silverman"):
return kde(data, bw_method=bw_method)
def _get_array_bounds(kernel, low_bound, high_bound):
low = ls(_ls_get_value, 0, args=(kernel, low_bound))
high = ls(_ls_get_value, 0, args=(kernel, high_bound))
return float(low.x), float(high.x)
def _ls_get_value(x, k, p):
return p - k.integrate_box_1d(-inf, x)
def kernel_fi(x_list, opt_h):
kernel = _get_uni_kde(x_list, opt_h)
low, high = _get_array_bounds(kernel, 0.0001, 0.9999)
x = linspace(low, high, 2 ** 11 + 1)
probs = kernel.pdf(x)
p_prime2 = gradient(probs, x) ** 2
return romb(p_prime2 / probs)
def temporal_kern(x, dN, over, eps):
opt_h = _get_opt_h(x, eps)
N = len(x)
fi = []
for i in range(0, 1 + N - dN, over):
window = x[i : i + dN]
fi.append(kernel_fi(window, opt_h))
return fi
if __name__ == "__main__":
df = read_csv("cantar2019.csv")
x = list(df["storage"])
k = 2
dN = 48
over = 1
eps = 10 ** -9
fi = temporal_kern(x, dN, over, eps)
fig, ax1 = plt.subplots(figsize=(5, 4))
ax1.plot(x, "k")
ax2 = ax1.twinx()
ax2.plot(range(dN, 1 + len(x), over), fi, "b")
plt.savefig("kernel_functions.png") | kernel_functions.py | import matplotlib.pyplot as plt
from numpy import gradient, inf, linspace, pi, power, sqrt, std
from pandas import read_csv
from scipy.integrate import romb, simps
from scipy.optimize import least_squares as ls
from scipy.stats import gaussian_kde as kde
from fast_deriv import FastUnivariateDensityDerivative as FUDD
def _fast_h_fun(h, N, X, c1, c2, eps):
lam = c2 * h ** (5 / 7)
D4 = FUDD(N, N, X, X, float(lam), 4, eps)
D4.evaluate()
phi4 = sum(D4.pD) / (N - 1)
return h - c1 * phi4 ** (-1 / 5)
def _get_scale_list(x_list):
shift = min(x_list)
scale = 1 / (max(x_list) - shift)
X_shifted_scale = [(x - shift) * scale for x in x_list]
return X_shifted_scale, scale
def _get_opt_h(x_list, eps):
N = len(x_list)
X_shifted_scale, scale = _get_scale_list(x_list)
sigma = std(X_shifted_scale)
phi6 = (-15 / (16 * sqrt(pi))) * power(sigma, -7)
phi8 = (105 / (32 * sqrt(pi))) * power(sigma, -9)
g1 = (-6 / (sqrt(2 * pi) * phi6 * N)) ** (1 / 7)
g2 = (30 / (sqrt(2 * pi) * phi8 * N)) ** (1 / 9)
D4 = FUDD(N, N, X_shifted_scale, X_shifted_scale, g1, 4, eps)
D6 = FUDD(N, N, X_shifted_scale, X_shifted_scale, g2, 6, eps)
D4.evaluate()
D6.evaluate()
phi4 = sum(D4.pD) / (N - 1)
phi6 = sum(D6.pD) / (N - 1)
constant1 = (1 / (2 * sqrt(pi) * N)) ** (1 / 5)
constant2 = (-6 * sqrt(2) * phi4 / phi6) ** (1 / 7)
h_initial = constant1 * phi4 ** (-1 / 5)
h = ls(
_fast_h_fun,
h_initial,
bounds=(0, inf),
ftol=1e-14,
xtol=1e-14,
verbose=0,
args=(N, X_shifted_scale, constant1, constant2, eps),
)
h = float(h.x) / scale
return h
def _get_uni_kde(data, bw_method="silverman"):
return kde(data, bw_method=bw_method)
def _get_array_bounds(kernel, low_bound, high_bound):
low = ls(_ls_get_value, 0, args=(kernel, low_bound))
high = ls(_ls_get_value, 0, args=(kernel, high_bound))
return float(low.x), float(high.x)
def _ls_get_value(x, k, p):
return p - k.integrate_box_1d(-inf, x)
def kernel_fi(x_list, opt_h):
kernel = _get_uni_kde(x_list, opt_h)
low, high = _get_array_bounds(kernel, 0.0001, 0.9999)
x = linspace(low, high, 2 ** 11 + 1)
probs = kernel.pdf(x)
p_prime2 = gradient(probs, x) ** 2
return romb(p_prime2 / probs)
def temporal_kern(x, dN, over, eps):
opt_h = _get_opt_h(x, eps)
N = len(x)
fi = []
for i in range(0, 1 + N - dN, over):
window = x[i : i + dN]
fi.append(kernel_fi(window, opt_h))
return fi
if __name__ == "__main__":
df = read_csv("cantar2019.csv")
x = list(df["storage"])
k = 2
dN = 48
over = 1
eps = 10 ** -9
fi = temporal_kern(x, dN, over, eps)
fig, ax1 = plt.subplots(figsize=(5, 4))
ax1.plot(x, "k")
ax2 = ax1.twinx()
ax2.plot(range(dN, 1 + len(x), over), fi, "b")
plt.savefig("kernel_functions.png") | 0.681939 | 0.564459 |
from abc import ABC
from abc import abstractmethod
class Strategy(ABC):
'''Abstract strategy class (used as an implementation base).'''
def __init__(self, network):
'''Create a strategy.
*** This method could be updated, but not mandatory. ***
Initialize the strategy by collecting all neurons in the network.
Args:
network: A wrapped Keras model with `adapt.Network`.
'''
def __call__(self, k):
'''Python magic call method.
This will make object callable. Just passing the argument to select method.
'''
return self.select(k)
@abstractmethod
def select(self, k):
'''Select k neurons.
*** This method should be implemented. ***
Select k neurons, and returns their location.
Args:
k: A positive integer. The number of neurons to select.
Returns:
A list of locations of selected neurons.
Global id
'''
def init(self, **kwargs):
'''Initialize the variables of the strategy.
*** This method could be update, but not mandatory. ***
Initialize the variables that managed by the strategy. This should be called
before other methods of the strategy called.
Args:
kwargs: A dictionary of keyword arguments. The followings are privileged
arguments.
covered: A list of coverage vectors that the initial input covers.
label: A label that initial input classified into.
Returns:
Self for possible call chains.
'''
return self
def update(self, covered, **kwargs):
'''Update the variables of the strategy.
*** This method could be updated, but not mandatory. ***
Update the variables that managed by the strategy. This method is called
everytime after a new input is created. By default, not update anything.
Args:
kwargs: A dictionary of keyword arguments. The followings are privileged
arguments.
covered: A list of coverage vectors that a current input covers.
label: A label that a current input classified into.
Returns:
Self for possible call chains.
'''
return self
def next(self):
'''Move to the next strategy.
*** This method could be updated, but not mandatory. ***
Update the strategy itself to next strategy. This may be important for
strategies using multiple strategies (i.e. round-robin). Be default,
not update strategy.
'''
return self | CV_adv/DNNtest/strategy/strategy.py | from abc import ABC
from abc import abstractmethod
class Strategy(ABC):
'''Abstract strategy class (used as an implementation base).'''
def __init__(self, network):
'''Create a strategy.
*** This method could be updated, but not mandatory. ***
Initialize the strategy by collecting all neurons in the network.
Args:
network: A wrapped Keras model with `adapt.Network`.
'''
def __call__(self, k):
'''Python magic call method.
This will make object callable. Just passing the argument to select method.
'''
return self.select(k)
@abstractmethod
def select(self, k):
'''Select k neurons.
*** This method should be implemented. ***
Select k neurons, and returns their location.
Args:
k: A positive integer. The number of neurons to select.
Returns:
A list of locations of selected neurons.
Global id
'''
def init(self, **kwargs):
'''Initialize the variables of the strategy.
*** This method could be update, but not mandatory. ***
Initialize the variables that managed by the strategy. This should be called
before other methods of the strategy called.
Args:
kwargs: A dictionary of keyword arguments. The followings are privileged
arguments.
covered: A list of coverage vectors that the initial input covers.
label: A label that initial input classified into.
Returns:
Self for possible call chains.
'''
return self
def update(self, covered, **kwargs):
'''Update the variables of the strategy.
*** This method could be updated, but not mandatory. ***
Update the variables that managed by the strategy. This method is called
everytime after a new input is created. By default, not update anything.
Args:
kwargs: A dictionary of keyword arguments. The followings are privileged
arguments.
covered: A list of coverage vectors that a current input covers.
label: A label that a current input classified into.
Returns:
Self for possible call chains.
'''
return self
def next(self):
'''Move to the next strategy.
*** This method could be updated, but not mandatory. ***
Update the strategy itself to next strategy. This may be important for
strategies using multiple strategies (i.e. round-robin). Be default,
not update strategy.
'''
return self | 0.888166 | 0.345933 |
import argparse
import logging
import yaml
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
import os
from datetime import datetime, timedelta
import matplotlib
import numpy as np
import torch
import torch.optim as optim
import wandb
from torch.optim.lr_scheduler import MultiStepLR, CyclicLR
from torch.utils.data import DataLoader
from src.utils.libconfig import config
from src.DSMEvaluation import DSMEvaluator, print_statistics
from src.io.checkpoints import CheckpointIO, DEFAULT_MODEL_FILE
from src.dataset import ImpliCityDataset
from src.utils.libconfig import lock_seed
from src.model import get_model
from src.generation import DSMGenerator
from src.Trainer import Trainer
from src.utils.libconfig import config_logging
from src.loss import wrapped_bce, wrapped_cross_entropy
# -------------------- Initialization --------------------
matplotlib.use('Agg')
# clear environment variable for rasterio
if os.environ.get('PROJ_LIB') is not None:
del os.environ['PROJ_LIB']
# Set t0
# t0 = time.time()
t_start = datetime.now()
# -------------------- Arguments --------------------
parser = argparse.ArgumentParser(
description='Train a 3D reconstruction model.'
)
parser.add_argument('config', type=str, help='Path to config file.')
parser.add_argument('--no-cuda', action='store_true', help='Do not use cuda.')
parser.add_argument('--no-wandb', action='store_true', help='run without wandb')
parser.add_argument('--exit-after', type=int, default=-1,
help='Checkpoint and exit after specified number of seconds'
'with exit code 3.')
args = parser.parse_args()
exit_after = args.exit_after
if not (os.path.exists(args.config) and os.path.isfile(args.config)):
raise IOError(f"config file not exist: '{args.config}'")
cfg = config.load_config(args.config, None)
# -------------------- shorthands --------------------
cfg_dataset = cfg['dataset']
cfg_loader = cfg['dataloader']
cfg_model = cfg['model']
cfg_training = cfg['training']
cfg_test = cfg['test']
cfg_dsm = cfg['dsm_generation']
cfg_multi_class = cfg_model.get('multi_label', False)
batch_size = cfg_training['batch_size']
val_batch_size = cfg_training['val_batch_size']
learning_rate = cfg_training['learning_rate']
model_selection_metric = cfg_training['model_selection_metric']
print_every = cfg_training['print_every']
visualize_every = cfg_training['visualize_every']
validate_every = cfg_training['validate_every']
checkpoint_every = cfg_training['checkpoint_every']
backup_every = cfg_training['backup_every']
# -------------------- Output directory --------------------
out_dir = cfg_training['out_dir']
pure_run_name = cfg_training['run_name']
run_name = f"{t_start.strftime('%y_%m_%d-%H_%M_%S')}-{pure_run_name}"
out_dir_run = os.path.join(out_dir, run_name)
out_dir_ckpt = os.path.join(out_dir_run, "check_points")
out_dir_tiff = os.path.join(out_dir_run, "tiff")
if not os.path.exists(out_dir_run):
os.makedirs(out_dir_run)
if not os.path.exists(out_dir_ckpt):
os.makedirs(out_dir_ckpt)
if not os.path.exists(out_dir_tiff):
os.makedirs(out_dir_tiff)
if cfg_training['lock_seed']:
lock_seed(0)
# %% -------------------- config logging --------------------
config_logging(cfg['logging'], out_dir_run)
print(f"{'*' * 30} Start {'*' * 30}")
# %% -------------------- save config file --------------------
_output_path = os.path.join(out_dir_run, "config.yaml")
with open(_output_path, 'w+') as f:
yaml.dump(cfg, f, default_flow_style=None, allow_unicode=True, Dumper=Dumper)
logging.info(f"Config saved to {_output_path}")
# %% -------------------- Config wandb --------------------
_wandb_out_dir = os.path.join(out_dir_run, "wandb")
if not os.path.exists(_wandb_out_dir):
os.makedirs(_wandb_out_dir)
if args.no_wandb:
wandb.init(mode='disabled')
else:
wandb.init(project='PROJECT_NAME',
config=cfg,
name=os.path.basename(out_dir_run),
dir=_wandb_out_dir,
mode='online',
settings=wandb.Settings(start_method="fork"))
# %% -------------------- Device --------------------
cuda_avail = (torch.cuda.is_available() and not args.no_cuda)
device = torch.device("cuda" if cuda_avail else "cpu")
logging.info(f"Device: {device}")
# torch.cuda.synchronize(device)
# %% -------------------- Data --------------------
train_dataset = ImpliCityDataset('train', cfg_dataset=cfg_dataset, merge_query_occ=not cfg_multi_class,
random_sample=True, random_length=cfg_training['random_dataset_length'],
flip_augm=cfg_training['augmentation']['flip'],
rotate_augm=cfg_training['augmentation']['rotate'])
val_dataset = ImpliCityDataset('val', cfg_dataset=cfg_dataset, merge_query_occ=not cfg_multi_class,
random_sample=False,
flip_augm=False, rotate_augm=False)
vis_dataset = ImpliCityDataset('vis', cfg_dataset=cfg_dataset, merge_query_occ=not cfg_multi_class,
random_sample=False,
flip_augm=False, rotate_augm=False)
n_workers = cfg_loader['n_workers']
# train dataloader
train_loader = DataLoader(train_dataset, batch_size=batch_size, num_workers=n_workers, shuffle=True,
# pin_memory=True
)
# val dataloader
val_loader = DataLoader(val_dataset, batch_size=val_batch_size, num_workers=n_workers, shuffle=False)
# visualization dataloader
vis_loader = DataLoader(vis_dataset, batch_size=1, num_workers=n_workers, shuffle=False)
logging.info(f"dataset path: '{cfg_dataset['path']}'")
logging.info(f"training data: n_data={len(train_dataset)}, batch_size={batch_size}")
logging.info(f"validation data: n_data={len(val_dataset)}, val_batch_size={val_batch_size}")
# %% -------------------- Model --------------------
model = get_model(cfg, device)
wandb.watch(model)
# %% -------------------- Optimizer --------------------
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# Scheduler
cfg_scheduler = cfg_training['scheduler']
_scheduler_type = cfg_scheduler['type']
_scheduler_kwargs = cfg_scheduler['kwargs']
if 'MultiStepLR' == _scheduler_type:
scheduler = MultiStepLR(optimizer=optimizer, gamma=_scheduler_kwargs['gamma'], milestones=_scheduler_kwargs['milestones'])
elif 'CyclicLR' == _scheduler_type:
scheduler = CyclicLR(optimizer=optimizer,
base_lr=_scheduler_kwargs['base_lr'],
max_lr=_scheduler_kwargs['max_lr'],
mode=_scheduler_kwargs['mode'],
scale_mode=_scheduler_kwargs.get('scale_mode', 'cycle'),
gamma=_scheduler_kwargs['gamma'],
step_size_up=_scheduler_kwargs['step_size_up'],
step_size_down=_scheduler_kwargs['step_size_down'],
cycle_momentum=False)
else:
raise ValueError("Unknown scheduler type")
# %% -------------------- Trainer --------------------
# Loss
if cfg_multi_class:
criteria = wrapped_cross_entropy
else:
criteria = wrapped_bce
trainer = Trainer(model=model, optimizer=optimizer, criteria=criteria, device=device,
optimize_every=cfg_training['optimize_every'], cfg_loss_weights=cfg_training['loss_weights'],
multi_class=cfg_multi_class, multi_tower_weights=cfg_training.get('multi_tower_weights', None),
balance_weight=cfg_training['loss_weights'].get('balance_building_weight', False))
# %% -------------------- Generator: generate DSM --------------------
generator_dsm = DSMGenerator(model=model, device=device, data_loader=vis_loader,
fill_empty=cfg_dsm['fill_empty'],
dsm_pixel_size=cfg_dsm['pixel_size'],
h_range=cfg_dsm['h_range'],
h_res_0=cfg_dsm['h_resolution_0'],
upsample_steps=cfg_dsm['h_upsampling_steps'],
half_blend_percent=cfg_dsm.get('half_blend_percent', None),
crs_epsg=cfg_dsm.get('crs_epsg', 32632))
gt_dsm_path = cfg_dataset['dsm_gt_path']
gt_mask_path = cfg_dataset['mask_files']['gt']
land_mask_path_dict = {
'building': cfg_dataset['mask_files']['building'],
'forest': cfg_dataset['mask_files']['forest'],
'water': cfg_dataset['mask_files']['water']
}
evaluator = DSMEvaluator(gt_dsm_path, gt_mask_path, land_mask_path_dict)
# %% -------------------- Initialize training --------------------
# Load checkpoint
checkpoint_io = CheckpointIO(out_dir_run, model=model, optimizer=optimizer, scheduler=scheduler)
resume_from = cfg_training.get('resume_from', None)
resume_scheduler = cfg_training.get('resume_scheduler', True)
try:
_resume_from_file = resume_from if resume_from is not None else ""
logging.info(f"resume: {_resume_from_file}")
# print(os.path.exists(_resume_from_file))
load_dict = checkpoint_io.load(_resume_from_file, resume_scheduler=resume_scheduler)
logging.info(f"Checkpoint loaded: '{_resume_from_file}'")
except FileExistsError:
load_dict = dict()
logging.info(f"No checkpoint, train from beginning")
# n_epoch = load_dict.get('n_epoch', 0) # epoch numbers
n_iter = load_dict.get('n_iter', 0) # total iterations
_last_train_seconds = load_dict.get('training_time', 0)
last_training_time = timedelta(seconds=_last_train_seconds)
if cfg['training']['model_selection_mode'] == 'maximize':
model_selection_sign = 1 # metric * sign => larger is better
elif cfg['training']['model_selection_mode'] == 'minimize':
model_selection_sign = -1 # metric * sign => larger is better
else:
_msg = 'model_selection_mode must be either maximize or minimize.'
logging.error(_msg)
raise ValueError(_msg)
metric_val_best = load_dict.get('loss_val_best', -model_selection_sign * np.inf)
logging.info(f"Current best validation metric = {metric_val_best:.8f}")
# %% -------------------- Training iterations --------------------
n_parameters = sum(p.numel() for p in model.parameters())
logging.info(f"Total number of parameters = {n_parameters}")
logging.info(f"output path: '{out_dir_run}'")
def visualize():
_output_path = os.path.join(out_dir_tiff, f"{pure_run_name}_dsm_{n_iter:06d}.tiff")
dsm_writer = generator_dsm.generate_dsm(_output_path)
logging.info(f"DSM saved to '{_output_path}'")
_target_dsm = dsm_writer.get_data()
# evaluate dsm
output_dic, diff_arr = evaluator.eval(_target_dsm, dsm_writer.T)
wandb_dic = {f"test/{k}": v for k, v in output_dic['overall'].items()}
_output_path = os.path.join(out_dir_tiff, f"{pure_run_name}_dsm_{n_iter:06d}_eval.txt")
str_stat = print_statistics(output_dic, f"{pure_run_name}-iter{n_iter}", save_to=_output_path)
logging.info(f"DSM evaluation saved to '{_output_path}")
# residual
dsm_writer.set_data(diff_arr)
_output_path = os.path.join(out_dir_tiff, f"{pure_run_name}_residual_{n_iter:06d}.tiff")
dsm_writer.write_to_file(_output_path)
logging.info(f"DSM residual saved to '{_output_path}")
_dsm_log_dic = {f'DSM/{k}/{k2}': v2 for k, v in output_dic.items() for k2, v2 in v.items()}
wandb.log(_dsm_log_dic, step=n_iter)
try:
while True:
for batch in train_loader:
# Train step
_ = trainer.train_step(batch)
if 0 == trainer.accumulated_steps:
# Use gradient accumulation. Each optimize step is 1 iteration
n_iter += 1
training_time = datetime.now() - t_start + last_training_time
loss = trainer.last_avg_loss_total
loss_category = trainer.last_avg_loss_category
wdb_dic = {
'iteration': n_iter,
'train/loss': loss,
'lr': scheduler.get_last_lr()[0],
'misc/training_time': training_time.total_seconds(),
'misc/n_query_points': trainer.last_avg_n_pts
# 'epoch': n_epoch
}
for _key, _value in trainer.last_avg_loss_category.items():
wdb_dic[f'train/{_key}'] = _value
for _key, _value in trainer.last_avg_metrics_total.items():
wdb_dic[f'train/{_key}'] = _value
for _key, _value in trainer.last_avg_metrics_category.items():
wdb_dic[f'train/{_key}'] = _value
wandb.log(wdb_dic, step=n_iter)
if print_every > 0 and (n_iter % print_every) == 0:
logging.info(f"iteration: {n_iter:6d}, loss ={loss:7.5f}, training_time = {training_time}")
# Save checkpoint
if checkpoint_every > 0 and (n_iter % checkpoint_every) == 0:
logging.info('Saving checkpoint')
_checkpoint_file = os.path.join(out_dir_ckpt, DEFAULT_MODEL_FILE)
checkpoint_io.save(_checkpoint_file, n_iter=n_iter, loss_val_best=metric_val_best,
training_time=training_time.total_seconds())
logging.info(f"Checkpoint saved to: '{_checkpoint_file}'")
# Backup if necessary
if backup_every > 0 and (n_iter % backup_every) == 0:
logging.info('Backing up checkpoint')
_checkpoint_file = os.path.join(out_dir_ckpt, f'model_{n_iter}.pt')
checkpoint_io.save(_checkpoint_file, n_iter=n_iter, loss_val_best=metric_val_best,
training_time=training_time.total_seconds())
logging.info(f"Backup to: {_checkpoint_file}")
# Validation
if validate_every > 0 and (n_iter % validate_every) == 0:
with torch.no_grad():
eval_dict = trainer.evaluate(val_loader)
metric_val = eval_dict[model_selection_metric]
logging.info(f"Model selection metric: {model_selection_metric} = {metric_val:.4f}")
wandb_dic = {f"val/{k}": v for k, v in eval_dict.items()}
# print('validation wandb_dic: ', wandb_dic)
wandb.log(wandb_dic, step=n_iter)
logging.info(
f"Validation: iteration {n_iter}, {', '.join([f'{k} = {eval_dict[k]}' for k in ['loss', 'iou']])}")
# save best model
if model_selection_sign * (metric_val - metric_val_best) > 0:
metric_val_best = metric_val
logging.info(f'New best model ({model_selection_metric}: {metric_val_best})')
_checkpoint_file = os.path.join(out_dir_ckpt, 'model_best.pt')
checkpoint_io.save(_checkpoint_file, n_iter=n_iter,
loss_val_best=metric_val_best,
training_time=training_time.total_seconds())
logging.info(f"Best model saved to: {_checkpoint_file}")
# Visualization
if visualize_every > 0 and (n_iter % visualize_every) == 0:
visualize()
# Exit if necessary
if 0 < exit_after <= (datetime.now() - t_start).total_seconds():
logging.info('Time limit reached. Exiting.')
_checkpoint_file = os.path.join(out_dir_ckpt, DEFAULT_MODEL_FILE)
checkpoint_io.save(_checkpoint_file, n_iter=n_iter, loss_val_best=metric_val_best,
training_time=training_time.total_seconds())
exit(3)
scheduler.step()
# optimize step[end]
# batch[end]
except IOError as e:
logging.error("Error: " + e.__str__()) | train.py | import argparse
import logging
import yaml
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
import os
from datetime import datetime, timedelta
import matplotlib
import numpy as np
import torch
import torch.optim as optim
import wandb
from torch.optim.lr_scheduler import MultiStepLR, CyclicLR
from torch.utils.data import DataLoader
from src.utils.libconfig import config
from src.DSMEvaluation import DSMEvaluator, print_statistics
from src.io.checkpoints import CheckpointIO, DEFAULT_MODEL_FILE
from src.dataset import ImpliCityDataset
from src.utils.libconfig import lock_seed
from src.model import get_model
from src.generation import DSMGenerator
from src.Trainer import Trainer
from src.utils.libconfig import config_logging
from src.loss import wrapped_bce, wrapped_cross_entropy
# -------------------- Initialization --------------------
matplotlib.use('Agg')
# clear environment variable for rasterio
if os.environ.get('PROJ_LIB') is not None:
del os.environ['PROJ_LIB']
# Set t0
# t0 = time.time()
t_start = datetime.now()
# -------------------- Arguments --------------------
parser = argparse.ArgumentParser(
description='Train a 3D reconstruction model.'
)
parser.add_argument('config', type=str, help='Path to config file.')
parser.add_argument('--no-cuda', action='store_true', help='Do not use cuda.')
parser.add_argument('--no-wandb', action='store_true', help='run without wandb')
parser.add_argument('--exit-after', type=int, default=-1,
help='Checkpoint and exit after specified number of seconds'
'with exit code 3.')
args = parser.parse_args()
exit_after = args.exit_after
if not (os.path.exists(args.config) and os.path.isfile(args.config)):
raise IOError(f"config file not exist: '{args.config}'")
cfg = config.load_config(args.config, None)
# -------------------- shorthands --------------------
cfg_dataset = cfg['dataset']
cfg_loader = cfg['dataloader']
cfg_model = cfg['model']
cfg_training = cfg['training']
cfg_test = cfg['test']
cfg_dsm = cfg['dsm_generation']
cfg_multi_class = cfg_model.get('multi_label', False)
batch_size = cfg_training['batch_size']
val_batch_size = cfg_training['val_batch_size']
learning_rate = cfg_training['learning_rate']
model_selection_metric = cfg_training['model_selection_metric']
print_every = cfg_training['print_every']
visualize_every = cfg_training['visualize_every']
validate_every = cfg_training['validate_every']
checkpoint_every = cfg_training['checkpoint_every']
backup_every = cfg_training['backup_every']
# -------------------- Output directory --------------------
out_dir = cfg_training['out_dir']
pure_run_name = cfg_training['run_name']
run_name = f"{t_start.strftime('%y_%m_%d-%H_%M_%S')}-{pure_run_name}"
out_dir_run = os.path.join(out_dir, run_name)
out_dir_ckpt = os.path.join(out_dir_run, "check_points")
out_dir_tiff = os.path.join(out_dir_run, "tiff")
if not os.path.exists(out_dir_run):
os.makedirs(out_dir_run)
if not os.path.exists(out_dir_ckpt):
os.makedirs(out_dir_ckpt)
if not os.path.exists(out_dir_tiff):
os.makedirs(out_dir_tiff)
if cfg_training['lock_seed']:
lock_seed(0)
# %% -------------------- config logging --------------------
config_logging(cfg['logging'], out_dir_run)
print(f"{'*' * 30} Start {'*' * 30}")
# %% -------------------- save config file --------------------
_output_path = os.path.join(out_dir_run, "config.yaml")
with open(_output_path, 'w+') as f:
yaml.dump(cfg, f, default_flow_style=None, allow_unicode=True, Dumper=Dumper)
logging.info(f"Config saved to {_output_path}")
# %% -------------------- Config wandb --------------------
_wandb_out_dir = os.path.join(out_dir_run, "wandb")
if not os.path.exists(_wandb_out_dir):
os.makedirs(_wandb_out_dir)
if args.no_wandb:
wandb.init(mode='disabled')
else:
wandb.init(project='PROJECT_NAME',
config=cfg,
name=os.path.basename(out_dir_run),
dir=_wandb_out_dir,
mode='online',
settings=wandb.Settings(start_method="fork"))
# %% -------------------- Device --------------------
cuda_avail = (torch.cuda.is_available() and not args.no_cuda)
device = torch.device("cuda" if cuda_avail else "cpu")
logging.info(f"Device: {device}")
# torch.cuda.synchronize(device)
# %% -------------------- Data --------------------
train_dataset = ImpliCityDataset('train', cfg_dataset=cfg_dataset, merge_query_occ=not cfg_multi_class,
random_sample=True, random_length=cfg_training['random_dataset_length'],
flip_augm=cfg_training['augmentation']['flip'],
rotate_augm=cfg_training['augmentation']['rotate'])
val_dataset = ImpliCityDataset('val', cfg_dataset=cfg_dataset, merge_query_occ=not cfg_multi_class,
random_sample=False,
flip_augm=False, rotate_augm=False)
vis_dataset = ImpliCityDataset('vis', cfg_dataset=cfg_dataset, merge_query_occ=not cfg_multi_class,
random_sample=False,
flip_augm=False, rotate_augm=False)
n_workers = cfg_loader['n_workers']
# train dataloader
train_loader = DataLoader(train_dataset, batch_size=batch_size, num_workers=n_workers, shuffle=True,
# pin_memory=True
)
# val dataloader
val_loader = DataLoader(val_dataset, batch_size=val_batch_size, num_workers=n_workers, shuffle=False)
# visualization dataloader
vis_loader = DataLoader(vis_dataset, batch_size=1, num_workers=n_workers, shuffle=False)
logging.info(f"dataset path: '{cfg_dataset['path']}'")
logging.info(f"training data: n_data={len(train_dataset)}, batch_size={batch_size}")
logging.info(f"validation data: n_data={len(val_dataset)}, val_batch_size={val_batch_size}")
# %% -------------------- Model --------------------
model = get_model(cfg, device)
wandb.watch(model)
# %% -------------------- Optimizer --------------------
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# Scheduler
cfg_scheduler = cfg_training['scheduler']
_scheduler_type = cfg_scheduler['type']
_scheduler_kwargs = cfg_scheduler['kwargs']
if 'MultiStepLR' == _scheduler_type:
scheduler = MultiStepLR(optimizer=optimizer, gamma=_scheduler_kwargs['gamma'], milestones=_scheduler_kwargs['milestones'])
elif 'CyclicLR' == _scheduler_type:
scheduler = CyclicLR(optimizer=optimizer,
base_lr=_scheduler_kwargs['base_lr'],
max_lr=_scheduler_kwargs['max_lr'],
mode=_scheduler_kwargs['mode'],
scale_mode=_scheduler_kwargs.get('scale_mode', 'cycle'),
gamma=_scheduler_kwargs['gamma'],
step_size_up=_scheduler_kwargs['step_size_up'],
step_size_down=_scheduler_kwargs['step_size_down'],
cycle_momentum=False)
else:
raise ValueError("Unknown scheduler type")
# %% -------------------- Trainer --------------------
# Loss
if cfg_multi_class:
criteria = wrapped_cross_entropy
else:
criteria = wrapped_bce
trainer = Trainer(model=model, optimizer=optimizer, criteria=criteria, device=device,
optimize_every=cfg_training['optimize_every'], cfg_loss_weights=cfg_training['loss_weights'],
multi_class=cfg_multi_class, multi_tower_weights=cfg_training.get('multi_tower_weights', None),
balance_weight=cfg_training['loss_weights'].get('balance_building_weight', False))
# %% -------------------- Generator: generate DSM --------------------
generator_dsm = DSMGenerator(model=model, device=device, data_loader=vis_loader,
fill_empty=cfg_dsm['fill_empty'],
dsm_pixel_size=cfg_dsm['pixel_size'],
h_range=cfg_dsm['h_range'],
h_res_0=cfg_dsm['h_resolution_0'],
upsample_steps=cfg_dsm['h_upsampling_steps'],
half_blend_percent=cfg_dsm.get('half_blend_percent', None),
crs_epsg=cfg_dsm.get('crs_epsg', 32632))
gt_dsm_path = cfg_dataset['dsm_gt_path']
gt_mask_path = cfg_dataset['mask_files']['gt']
land_mask_path_dict = {
'building': cfg_dataset['mask_files']['building'],
'forest': cfg_dataset['mask_files']['forest'],
'water': cfg_dataset['mask_files']['water']
}
evaluator = DSMEvaluator(gt_dsm_path, gt_mask_path, land_mask_path_dict)
# %% -------------------- Initialize training --------------------
# Load checkpoint
checkpoint_io = CheckpointIO(out_dir_run, model=model, optimizer=optimizer, scheduler=scheduler)
resume_from = cfg_training.get('resume_from', None)
resume_scheduler = cfg_training.get('resume_scheduler', True)
try:
_resume_from_file = resume_from if resume_from is not None else ""
logging.info(f"resume: {_resume_from_file}")
# print(os.path.exists(_resume_from_file))
load_dict = checkpoint_io.load(_resume_from_file, resume_scheduler=resume_scheduler)
logging.info(f"Checkpoint loaded: '{_resume_from_file}'")
except FileExistsError:
load_dict = dict()
logging.info(f"No checkpoint, train from beginning")
# n_epoch = load_dict.get('n_epoch', 0) # epoch numbers
n_iter = load_dict.get('n_iter', 0) # total iterations
_last_train_seconds = load_dict.get('training_time', 0)
last_training_time = timedelta(seconds=_last_train_seconds)
if cfg['training']['model_selection_mode'] == 'maximize':
model_selection_sign = 1 # metric * sign => larger is better
elif cfg['training']['model_selection_mode'] == 'minimize':
model_selection_sign = -1 # metric * sign => larger is better
else:
_msg = 'model_selection_mode must be either maximize or minimize.'
logging.error(_msg)
raise ValueError(_msg)
metric_val_best = load_dict.get('loss_val_best', -model_selection_sign * np.inf)
logging.info(f"Current best validation metric = {metric_val_best:.8f}")
# %% -------------------- Training iterations --------------------
n_parameters = sum(p.numel() for p in model.parameters())
logging.info(f"Total number of parameters = {n_parameters}")
logging.info(f"output path: '{out_dir_run}'")
def visualize():
_output_path = os.path.join(out_dir_tiff, f"{pure_run_name}_dsm_{n_iter:06d}.tiff")
dsm_writer = generator_dsm.generate_dsm(_output_path)
logging.info(f"DSM saved to '{_output_path}'")
_target_dsm = dsm_writer.get_data()
# evaluate dsm
output_dic, diff_arr = evaluator.eval(_target_dsm, dsm_writer.T)
wandb_dic = {f"test/{k}": v for k, v in output_dic['overall'].items()}
_output_path = os.path.join(out_dir_tiff, f"{pure_run_name}_dsm_{n_iter:06d}_eval.txt")
str_stat = print_statistics(output_dic, f"{pure_run_name}-iter{n_iter}", save_to=_output_path)
logging.info(f"DSM evaluation saved to '{_output_path}")
# residual
dsm_writer.set_data(diff_arr)
_output_path = os.path.join(out_dir_tiff, f"{pure_run_name}_residual_{n_iter:06d}.tiff")
dsm_writer.write_to_file(_output_path)
logging.info(f"DSM residual saved to '{_output_path}")
_dsm_log_dic = {f'DSM/{k}/{k2}': v2 for k, v in output_dic.items() for k2, v2 in v.items()}
wandb.log(_dsm_log_dic, step=n_iter)
try:
while True:
for batch in train_loader:
# Train step
_ = trainer.train_step(batch)
if 0 == trainer.accumulated_steps:
# Use gradient accumulation. Each optimize step is 1 iteration
n_iter += 1
training_time = datetime.now() - t_start + last_training_time
loss = trainer.last_avg_loss_total
loss_category = trainer.last_avg_loss_category
wdb_dic = {
'iteration': n_iter,
'train/loss': loss,
'lr': scheduler.get_last_lr()[0],
'misc/training_time': training_time.total_seconds(),
'misc/n_query_points': trainer.last_avg_n_pts
# 'epoch': n_epoch
}
for _key, _value in trainer.last_avg_loss_category.items():
wdb_dic[f'train/{_key}'] = _value
for _key, _value in trainer.last_avg_metrics_total.items():
wdb_dic[f'train/{_key}'] = _value
for _key, _value in trainer.last_avg_metrics_category.items():
wdb_dic[f'train/{_key}'] = _value
wandb.log(wdb_dic, step=n_iter)
if print_every > 0 and (n_iter % print_every) == 0:
logging.info(f"iteration: {n_iter:6d}, loss ={loss:7.5f}, training_time = {training_time}")
# Save checkpoint
if checkpoint_every > 0 and (n_iter % checkpoint_every) == 0:
logging.info('Saving checkpoint')
_checkpoint_file = os.path.join(out_dir_ckpt, DEFAULT_MODEL_FILE)
checkpoint_io.save(_checkpoint_file, n_iter=n_iter, loss_val_best=metric_val_best,
training_time=training_time.total_seconds())
logging.info(f"Checkpoint saved to: '{_checkpoint_file}'")
# Backup if necessary
if backup_every > 0 and (n_iter % backup_every) == 0:
logging.info('Backing up checkpoint')
_checkpoint_file = os.path.join(out_dir_ckpt, f'model_{n_iter}.pt')
checkpoint_io.save(_checkpoint_file, n_iter=n_iter, loss_val_best=metric_val_best,
training_time=training_time.total_seconds())
logging.info(f"Backup to: {_checkpoint_file}")
# Validation
if validate_every > 0 and (n_iter % validate_every) == 0:
with torch.no_grad():
eval_dict = trainer.evaluate(val_loader)
metric_val = eval_dict[model_selection_metric]
logging.info(f"Model selection metric: {model_selection_metric} = {metric_val:.4f}")
wandb_dic = {f"val/{k}": v for k, v in eval_dict.items()}
# print('validation wandb_dic: ', wandb_dic)
wandb.log(wandb_dic, step=n_iter)
logging.info(
f"Validation: iteration {n_iter}, {', '.join([f'{k} = {eval_dict[k]}' for k in ['loss', 'iou']])}")
# save best model
if model_selection_sign * (metric_val - metric_val_best) > 0:
metric_val_best = metric_val
logging.info(f'New best model ({model_selection_metric}: {metric_val_best})')
_checkpoint_file = os.path.join(out_dir_ckpt, 'model_best.pt')
checkpoint_io.save(_checkpoint_file, n_iter=n_iter,
loss_val_best=metric_val_best,
training_time=training_time.total_seconds())
logging.info(f"Best model saved to: {_checkpoint_file}")
# Visualization
if visualize_every > 0 and (n_iter % visualize_every) == 0:
visualize()
# Exit if necessary
if 0 < exit_after <= (datetime.now() - t_start).total_seconds():
logging.info('Time limit reached. Exiting.')
_checkpoint_file = os.path.join(out_dir_ckpt, DEFAULT_MODEL_FILE)
checkpoint_io.save(_checkpoint_file, n_iter=n_iter, loss_val_best=metric_val_best,
training_time=training_time.total_seconds())
exit(3)
scheduler.step()
# optimize step[end]
# batch[end]
except IOError as e:
logging.error("Error: " + e.__str__()) | 0.440951 | 0.088269 |
import utils
import logging
import os
import csv
from abc import ABCMeta
from dataservice import AbstractDataService
class AbstractPersistenceService(metaclass=ABCMeta):
"""
Persistence service pulls data from data service, processes it, and then stores it.
"""
def __init__(self, data_service: AbstractDataService):
self._logger = logging.getLogger(__name__)
self._data_service = data_service
self._results = []
def start(self):
pass
def stop(self):
pass
class CSVEnrollmentPersistenceService(AbstractPersistenceService):
def __init__(self, data_service: AbstractDataService, filename, encoding=None):
super().__init__(data_service)
self._filename = filename
self._encoding = encoding
def output(self):
rows = utils.OutputHelper.output_rows(self._results, utils.EnrollmentFieldsHelper.get_output_fields(),
utils.EnrollmentFieldsHelper.get_output_field_names())
try:
os.makedirs(os.path.dirname(self._filename), exist_ok=True)
except FileNotFoundError:
pass
with open(self._filename, mode='w', encoding=self._encoding) as fle:
writer = csv.writer(fle)
writer.writerows(rows)
def start(self):
# This type of persistence service has no need to continuously get data
self._logger.debug('CSVPersistenceService started; waiting for data service to finish')
self._data_service.wait()
self._logger.debug('wait() returned; data service finished')
self._results = self._data_service.get_result_list()
try:
self.output()
except Exception:
self._logger.exception('Error occurred outputting data; returning')
return
self._logger.info('Data output done! Output file: %s' % self._filename)
class CSVPersistenceService(AbstractPersistenceService):
def __init__(self, data_service: AbstractDataService, filename, encoding=None, rank=True, avg=True):
super().__init__(data_service)
self._filename = filename
self._encoding = encoding
self._rank = rank
self._avg = avg
def output(self):
rows = utils.OutputHelper.output_rows(self._results, utils.FieldsHelper.get_output_fields(), utils.FieldsHelper.get_output_field_names())
try:
os.makedirs(os.path.dirname(self._filename), exist_ok=True)
except FileNotFoundError:
pass
with open(self._filename, mode='w', encoding=self._encoding) as fle:
writer = csv.writer(fle)
writer.writerows(rows)
def process(self):
if self._rank:
for key in utils.FieldsHelper.rankable_fields:
for major in utils.FieldsHelper.major_list:
utils.RankingHelper.rank_column(self._results, key, utils.FieldsHelper.wrap_rank(key),
range_controller=lambda x: x['major'] == major)
for key in utils.FieldsHelper.cross_rankable_fields:
utils.RankingHelper.rank_column(self._results, key, utils.FieldsHelper.wrap_cross_rank(key))
if self._avg:
for key in utils.FieldsHelper.rankable_fields:
for major in utils.FieldsHelper.major_list:
utils.RankingHelper.average(self._results, key, utils.FieldsHelper.wrap_avg(key),
range_controller=lambda x: x['major'] == major and x[key] != -1)
for key in utils.FieldsHelper.cross_rankable_fields:
utils.RankingHelper.average(self._results, key, utils.FieldsHelper.wrap_cross_avg(key), range_controller=lambda x: x[key] != -1)
def start(self):
# This type of persistence service has no need to continuously get data
self._logger.debug('CSVPersistenceService started; waiting for data service to finish')
self._data_service.wait()
self._logger.debug('wait() returned; data service finished')
self._results = self._data_service.get_result_list()
try:
self.process()
except Exception:
self._logger.exception('Error occurred processing data; returning')
return
try:
self.output()
except Exception:
self._logger.exception('Error occurred outputting data; returning')
return
self._logger.info('Data output done! Output file: %s' % self._filename) | persistenceservice.py | import utils
import logging
import os
import csv
from abc import ABCMeta
from dataservice import AbstractDataService
class AbstractPersistenceService(metaclass=ABCMeta):
"""
Persistence service pulls data from data service, processes it, and then stores it.
"""
def __init__(self, data_service: AbstractDataService):
self._logger = logging.getLogger(__name__)
self._data_service = data_service
self._results = []
def start(self):
pass
def stop(self):
pass
class CSVEnrollmentPersistenceService(AbstractPersistenceService):
def __init__(self, data_service: AbstractDataService, filename, encoding=None):
super().__init__(data_service)
self._filename = filename
self._encoding = encoding
def output(self):
rows = utils.OutputHelper.output_rows(self._results, utils.EnrollmentFieldsHelper.get_output_fields(),
utils.EnrollmentFieldsHelper.get_output_field_names())
try:
os.makedirs(os.path.dirname(self._filename), exist_ok=True)
except FileNotFoundError:
pass
with open(self._filename, mode='w', encoding=self._encoding) as fle:
writer = csv.writer(fle)
writer.writerows(rows)
def start(self):
# This type of persistence service has no need to continuously get data
self._logger.debug('CSVPersistenceService started; waiting for data service to finish')
self._data_service.wait()
self._logger.debug('wait() returned; data service finished')
self._results = self._data_service.get_result_list()
try:
self.output()
except Exception:
self._logger.exception('Error occurred outputting data; returning')
return
self._logger.info('Data output done! Output file: %s' % self._filename)
class CSVPersistenceService(AbstractPersistenceService):
def __init__(self, data_service: AbstractDataService, filename, encoding=None, rank=True, avg=True):
super().__init__(data_service)
self._filename = filename
self._encoding = encoding
self._rank = rank
self._avg = avg
def output(self):
rows = utils.OutputHelper.output_rows(self._results, utils.FieldsHelper.get_output_fields(), utils.FieldsHelper.get_output_field_names())
try:
os.makedirs(os.path.dirname(self._filename), exist_ok=True)
except FileNotFoundError:
pass
with open(self._filename, mode='w', encoding=self._encoding) as fle:
writer = csv.writer(fle)
writer.writerows(rows)
def process(self):
if self._rank:
for key in utils.FieldsHelper.rankable_fields:
for major in utils.FieldsHelper.major_list:
utils.RankingHelper.rank_column(self._results, key, utils.FieldsHelper.wrap_rank(key),
range_controller=lambda x: x['major'] == major)
for key in utils.FieldsHelper.cross_rankable_fields:
utils.RankingHelper.rank_column(self._results, key, utils.FieldsHelper.wrap_cross_rank(key))
if self._avg:
for key in utils.FieldsHelper.rankable_fields:
for major in utils.FieldsHelper.major_list:
utils.RankingHelper.average(self._results, key, utils.FieldsHelper.wrap_avg(key),
range_controller=lambda x: x['major'] == major and x[key] != -1)
for key in utils.FieldsHelper.cross_rankable_fields:
utils.RankingHelper.average(self._results, key, utils.FieldsHelper.wrap_cross_avg(key), range_controller=lambda x: x[key] != -1)
def start(self):
# This type of persistence service has no need to continuously get data
self._logger.debug('CSVPersistenceService started; waiting for data service to finish')
self._data_service.wait()
self._logger.debug('wait() returned; data service finished')
self._results = self._data_service.get_result_list()
try:
self.process()
except Exception:
self._logger.exception('Error occurred processing data; returning')
return
try:
self.output()
except Exception:
self._logger.exception('Error occurred outputting data; returning')
return
self._logger.info('Data output done! Output file: %s' % self._filename) | 0.391406 | 0.10961 |
from py_build.build import BuildCompleteState, BuildConfigureState, BuildError, BuildErrorState, BuildRunningState, Builder, BuilderError
import pytest
@pytest.fixture
def builder_configure():
return Builder(BuildConfigureState)
@pytest.fixture
def builder_complete():
return Builder(BuildCompleteState)
@pytest.fixture
def builder_running():
return Builder(BuildRunningState)
@pytest.fixture
def builder_error():
return Builder(BuildErrorState)
@pytest.fixture
def builder_states(builder_configure, builder_running, builder_complete, builder_error):
return (builder_configure, builder_running, builder_complete, builder_error)
@pytest.fixture(params=(0, 1, 2))
def builder_running_complete_error(builder_states, request):
builders = builder_states[1:]
messages = (
'Cannot {verb}, build already running',
'Cannot {verb}, build already completed',
'Cannot {verb}, build already completed with errors',
)
return (builders[request.param], messages[request.param])
def test_build_step_raises_exception_if_builder_running_or_completed(builder_running_complete_error):
builder, message = builder_running_complete_error
with pytest.raises(BuilderError, match=message.format(verb='add build step')):
builder.build_step()
def test_build_raises_exception_if_builder_running_or_completed(builder_running_complete_error):
builder, message = builder_running_complete_error
with pytest.raises(BuilderError, match=message.format(verb='run build')):
builder.build()
@pytest.fixture(params=[
0, 1
])
def builder_complete_error(builder_states, request):
return tuple(builder_states[2:])[request.param]
def test_is_complete_returns_true_if_state_is_complete_or_error(builder_complete_error):
assert builder_complete_error.is_complete == True
@pytest.fixture
def builder():
return Builder()
def test_build_state_is_running_during_build_step_execution(builder):
running = []
@builder.build_step()
@builder.capture_results(lambda res: running.append(res))
def assert_state():
return isinstance(builder.state, BuildRunningState)
builder.build()
assert any(running)
def test_build_state_is_complete_when_build_is_complete(builder):
@builder.build_step()
def step1():
pass
@builder.build_step()
def step2():
pass
builder.build()
assert isinstance(builder.state, BuildCompleteState)
assert builder.is_complete
def test_build_state_is_error_when_build_has_exception(builder):
step3_notran = []
@builder.build_step()
def step1():
pass
@builder.build_step()
def errors_step():
1 / 0
@builder.build_step()
@builder.capture_results(lambda res: step3_notran.append(True))
def step3():
return True
exc = None
with pytest.raises(BuildError):
try:
builder.build()
except BuildError as ex:
exc = ex
raise ex
assert exc.build_step == errors_step
assert exc.message == 'division by zero'
assert isinstance(builder.state, BuildErrorState)
assert builder.is_complete
assert not any(step3_notran) | tests/test_builder_states.py | from py_build.build import BuildCompleteState, BuildConfigureState, BuildError, BuildErrorState, BuildRunningState, Builder, BuilderError
import pytest
@pytest.fixture
def builder_configure():
return Builder(BuildConfigureState)
@pytest.fixture
def builder_complete():
return Builder(BuildCompleteState)
@pytest.fixture
def builder_running():
return Builder(BuildRunningState)
@pytest.fixture
def builder_error():
return Builder(BuildErrorState)
@pytest.fixture
def builder_states(builder_configure, builder_running, builder_complete, builder_error):
return (builder_configure, builder_running, builder_complete, builder_error)
@pytest.fixture(params=(0, 1, 2))
def builder_running_complete_error(builder_states, request):
builders = builder_states[1:]
messages = (
'Cannot {verb}, build already running',
'Cannot {verb}, build already completed',
'Cannot {verb}, build already completed with errors',
)
return (builders[request.param], messages[request.param])
def test_build_step_raises_exception_if_builder_running_or_completed(builder_running_complete_error):
builder, message = builder_running_complete_error
with pytest.raises(BuilderError, match=message.format(verb='add build step')):
builder.build_step()
def test_build_raises_exception_if_builder_running_or_completed(builder_running_complete_error):
builder, message = builder_running_complete_error
with pytest.raises(BuilderError, match=message.format(verb='run build')):
builder.build()
@pytest.fixture(params=[
0, 1
])
def builder_complete_error(builder_states, request):
return tuple(builder_states[2:])[request.param]
def test_is_complete_returns_true_if_state_is_complete_or_error(builder_complete_error):
assert builder_complete_error.is_complete == True
@pytest.fixture
def builder():
return Builder()
def test_build_state_is_running_during_build_step_execution(builder):
running = []
@builder.build_step()
@builder.capture_results(lambda res: running.append(res))
def assert_state():
return isinstance(builder.state, BuildRunningState)
builder.build()
assert any(running)
def test_build_state_is_complete_when_build_is_complete(builder):
@builder.build_step()
def step1():
pass
@builder.build_step()
def step2():
pass
builder.build()
assert isinstance(builder.state, BuildCompleteState)
assert builder.is_complete
def test_build_state_is_error_when_build_has_exception(builder):
step3_notran = []
@builder.build_step()
def step1():
pass
@builder.build_step()
def errors_step():
1 / 0
@builder.build_step()
@builder.capture_results(lambda res: step3_notran.append(True))
def step3():
return True
exc = None
with pytest.raises(BuildError):
try:
builder.build()
except BuildError as ex:
exc = ex
raise ex
assert exc.build_step == errors_step
assert exc.message == 'division by zero'
assert isinstance(builder.state, BuildErrorState)
assert builder.is_complete
assert not any(step3_notran) | 0.520984 | 0.376279 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import os
import urllib
import numpy as np
import tensorflow as tf
def main():
# Load datasets.
training_set = tf.contrib.learn.datasets.base.load_csv_without_header(
filename="data/train.csv",
target_dtype=np.int,
features_dtype=np.int,
target_column=0)
test_set = tf.contrib.learn.datasets.base.load_csv_without_header(
filename="data/test.csv",
target_dtype=np.int,
features_dtype=np.int,
target_column=0)
# Specify that all features have real-value data
feature_columns = [tf.contrib.layers.real_valued_column("", dimension=10000)]
# Build 3 layer DNN with 10, 20, 10 units respectively.
classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,
hidden_units=[10, 20, 10],
n_classes=3, #green, yellow, red
model_dir="data/pd_model")
# Define the training inputs
def get_train_inputs():
x = tf.constant(training_set.data)
y = tf.constant(training_set.target)
return x, y
# Fit model.
classifier.fit(input_fn=get_train_inputs, steps=2000)
# Define the test inputs
def get_test_inputs():
x = tf.constant(test_set.data)
y = tf.constant(test_set.target)
return x, y
# Evaluate accuracy.
accuracy_score = classifier.evaluate(input_fn=get_test_inputs,
steps=1)["accuracy"]
print("\nTest Accuracy: {0:f}\n".format(accuracy_score))
# Classify two new flower samples.
'''
def new_samples():
return np.array(
[[6.4, 3.2, 4.5, 1.5],
[5.8, 3.1, 5.0, 1.7]], dtype=np.float32)
predictions = list(classifier.predict(input_fn=new_samples))
print(
"New Samples, Class Predictions: {}\n"
.format(predictions))
'''
if __name__ == "__main__":
main() | learn.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import os
import urllib
import numpy as np
import tensorflow as tf
def main():
# Load datasets.
training_set = tf.contrib.learn.datasets.base.load_csv_without_header(
filename="data/train.csv",
target_dtype=np.int,
features_dtype=np.int,
target_column=0)
test_set = tf.contrib.learn.datasets.base.load_csv_without_header(
filename="data/test.csv",
target_dtype=np.int,
features_dtype=np.int,
target_column=0)
# Specify that all features have real-value data
feature_columns = [tf.contrib.layers.real_valued_column("", dimension=10000)]
# Build 3 layer DNN with 10, 20, 10 units respectively.
classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,
hidden_units=[10, 20, 10],
n_classes=3, #green, yellow, red
model_dir="data/pd_model")
# Define the training inputs
def get_train_inputs():
x = tf.constant(training_set.data)
y = tf.constant(training_set.target)
return x, y
# Fit model.
classifier.fit(input_fn=get_train_inputs, steps=2000)
# Define the test inputs
def get_test_inputs():
x = tf.constant(test_set.data)
y = tf.constant(test_set.target)
return x, y
# Evaluate accuracy.
accuracy_score = classifier.evaluate(input_fn=get_test_inputs,
steps=1)["accuracy"]
print("\nTest Accuracy: {0:f}\n".format(accuracy_score))
# Classify two new flower samples.
'''
def new_samples():
return np.array(
[[6.4, 3.2, 4.5, 1.5],
[5.8, 3.1, 5.0, 1.7]], dtype=np.float32)
predictions = list(classifier.predict(input_fn=new_samples))
print(
"New Samples, Class Predictions: {}\n"
.format(predictions))
'''
if __name__ == "__main__":
main() | 0.826046 | 0.232005 |
from .._compat import basestring
from ..adapters.ingres import Ingres, IngresUnicode
from .base import SQLDialect
from . import dialects, sqltype_for
@dialects.register_for(Ingres)
class IngresDialect(SQLDialect):
SEQNAME = 'ii***lineitemsequence'
@sqltype_for('text')
def type_text(self):
return 'CLOB'
@sqltype_for('integer')
def type_integer(self):
return 'INTEGER4'
@sqltype_for('bigint')
def type_bigint(self):
return 'BIGINT'
@sqltype_for('double')
def type_float(self):
return 'FLOAT8'
@sqltype_for('date')
def type_date(self):
return 'ANSIDATE'
@sqltype_for('time')
def type_time(self):
return 'TIME WITHOUT TIME ZONE'
@sqltype_for('datetime')
def type_datetime(self):
return 'TIMESTAMP WITHOUT TIME ZONE'
@sqltype_for('id')
def type_id(self):
return 'int not null unique with default next value for %s' % \
self.INGRES_SEQNAME
@sqltype_for('big-id')
def type_big_id(self):
return 'bigint not null unique with default next value for %s' % \
self.INGRES_SEQNAME
@sqltype_for('reference')
def type_reference(self):
return 'INT, FOREIGN KEY (%(field_name)s) REFERENCES ' + \
'%(foreign_key)s ON DELETE %(on_delete_action)s'
@sqltype_for('big-reference')
def type_big_reference(self):
return 'BIGINT, FOREIGN KEY (%(field_name)s) REFERENCES ' + \
'%(foreign_key)s ON DELETE %(on_delete_action)s'
@sqltype_for('reference FK')
def type_reference_fk(self):
return ', CONSTRAINT FK_%(constraint_name)s FOREIGN KEY ' + \
'(%(field_name)s) REFERENCES %(foreign_key)s ' + \
'ON DELETE %(on_delete_action)s'
@sqltype_for('reference TFK')
def type_reference_tfk(self):
return ' CONSTRAINT FK_%(constraint_name)s_PK FOREIGN KEY ' + \
'(%(field_name)s) REFERENCES %(foreign_table)s' + \
'(%(foreign_key)s) ON DELETE %(on_delete_action)s'
def left_join(self, val, query_env={}):
# Left join must always have an ON clause
if not isinstance(val, basestring):
val = self.expand(val, query_env=query_env)
return 'LEFT OUTER JOIN %s' % val
@property
def random(self):
return 'RANDOM()'
def select(self, fields, tables, where=None, groupby=None, having=None,
orderby=None, limitby=None, distinct=False, for_update=False):
dst, whr, grp, order, limit, offset, upd = '', '', '', '', '', '', ''
if distinct is True:
dst = ' DISTINCT'
elif distinct:
dst = ' DISTINCT ON (%s)' % distinct
if where:
whr = ' %s' % self.where(where)
if groupby:
grp = ' GROUP BY %s' % groupby
if having:
grp += ' HAVING %s' % having
if orderby:
order = ' ORDER BY %s' % orderby
if limitby:
(lmin, lmax) = limitby
fetch_amt = lmax - lmin
if fetch_amt:
limit = ' FIRST %i' % fetch_amt
if lmin:
offset = ' OFFSET %i' % lmin
if for_update:
upd = ' FOR UPDATE'
return 'SELECT%s%S %s FROM %s%s%s%s%s%s;' % (
dst, limit, fields, tables, whr, grp, order, offset, upd)
@dialects.register_for(IngresUnicode)
class IngresUnicodeDialect(IngresDialect):
@sqltype_for('string')
def type_string(self):
return 'NVARCHAR(%(length)s)'
@sqltype_for('text')
def type_text(self):
return 'NCLOB' | gluon/packages/dal/pydal/dialects/ingres.py | from .._compat import basestring
from ..adapters.ingres import Ingres, IngresUnicode
from .base import SQLDialect
from . import dialects, sqltype_for
@dialects.register_for(Ingres)
class IngresDialect(SQLDialect):
SEQNAME = 'ii***lineitemsequence'
@sqltype_for('text')
def type_text(self):
return 'CLOB'
@sqltype_for('integer')
def type_integer(self):
return 'INTEGER4'
@sqltype_for('bigint')
def type_bigint(self):
return 'BIGINT'
@sqltype_for('double')
def type_float(self):
return 'FLOAT8'
@sqltype_for('date')
def type_date(self):
return 'ANSIDATE'
@sqltype_for('time')
def type_time(self):
return 'TIME WITHOUT TIME ZONE'
@sqltype_for('datetime')
def type_datetime(self):
return 'TIMESTAMP WITHOUT TIME ZONE'
@sqltype_for('id')
def type_id(self):
return 'int not null unique with default next value for %s' % \
self.INGRES_SEQNAME
@sqltype_for('big-id')
def type_big_id(self):
return 'bigint not null unique with default next value for %s' % \
self.INGRES_SEQNAME
@sqltype_for('reference')
def type_reference(self):
return 'INT, FOREIGN KEY (%(field_name)s) REFERENCES ' + \
'%(foreign_key)s ON DELETE %(on_delete_action)s'
@sqltype_for('big-reference')
def type_big_reference(self):
return 'BIGINT, FOREIGN KEY (%(field_name)s) REFERENCES ' + \
'%(foreign_key)s ON DELETE %(on_delete_action)s'
@sqltype_for('reference FK')
def type_reference_fk(self):
return ', CONSTRAINT FK_%(constraint_name)s FOREIGN KEY ' + \
'(%(field_name)s) REFERENCES %(foreign_key)s ' + \
'ON DELETE %(on_delete_action)s'
@sqltype_for('reference TFK')
def type_reference_tfk(self):
return ' CONSTRAINT FK_%(constraint_name)s_PK FOREIGN KEY ' + \
'(%(field_name)s) REFERENCES %(foreign_table)s' + \
'(%(foreign_key)s) ON DELETE %(on_delete_action)s'
def left_join(self, val, query_env={}):
# Left join must always have an ON clause
if not isinstance(val, basestring):
val = self.expand(val, query_env=query_env)
return 'LEFT OUTER JOIN %s' % val
@property
def random(self):
return 'RANDOM()'
def select(self, fields, tables, where=None, groupby=None, having=None,
orderby=None, limitby=None, distinct=False, for_update=False):
dst, whr, grp, order, limit, offset, upd = '', '', '', '', '', '', ''
if distinct is True:
dst = ' DISTINCT'
elif distinct:
dst = ' DISTINCT ON (%s)' % distinct
if where:
whr = ' %s' % self.where(where)
if groupby:
grp = ' GROUP BY %s' % groupby
if having:
grp += ' HAVING %s' % having
if orderby:
order = ' ORDER BY %s' % orderby
if limitby:
(lmin, lmax) = limitby
fetch_amt = lmax - lmin
if fetch_amt:
limit = ' FIRST %i' % fetch_amt
if lmin:
offset = ' OFFSET %i' % lmin
if for_update:
upd = ' FOR UPDATE'
return 'SELECT%s%S %s FROM %s%s%s%s%s%s;' % (
dst, limit, fields, tables, whr, grp, order, offset, upd)
@dialects.register_for(IngresUnicode)
class IngresUnicodeDialect(IngresDialect):
@sqltype_for('string')
def type_string(self):
return 'NVARCHAR(%(length)s)'
@sqltype_for('text')
def type_text(self):
return 'NCLOB' | 0.458106 | 0.087876 |
from logging import getLogger
from sys import platform as _platform
from subprocess import Popen, PIPE,DEVNULL, STDOUT
from pathlib import Path
import requests
from kivymd.uix.list import OneLineListItem
from kivymd.uix.dialog import MDDialog
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.textfield import MDTextField
from kivymd.uix.button import MDFlatButton
from kivymd.toast import toast
from functools import partial
from tesseractXplore.app import get_app
logger = getLogger().getChild(__name__)
def install_tesseract_dialog():
def close_dialog(instance, *args):
instance.parent.parent.parent.parent.dismiss()
layout = MDBoxLayout(orientation="horizontal", adaptive_height=True)
layout.add_widget(OneLineListItem(text="Tesseract wasn't found on the system. You can install it now or set"
"the right path in the settings-menu. (Restart required)"))
dialog = MDDialog(title="Installing tesseract?",
type='custom',
auto_dismiss=False,
content_cls=layout,
buttons=[
MDFlatButton(
text="INSTALL", on_release=partial(install_tesseract)
),
MDFlatButton(
text="DISCARD", on_release=close_dialog
),
],
)
dialog.content_cls.focused = True
dialog.open()
def install_tesseract(instance):
instance.parent.parent.parent.parent.dismiss()
if _platform in ["win32", "win64"]:
install_win()
else:
install_unix_dialog()
def install_win():
try:
if _platform == "win32":
url = get_app().settings_controller.tesseract['win32url']
else:
url = get_app().settings_controller.tesseract['win64url']
r = requests.get(url)
import tempfile
from os import startfile
fout = Path(tempfile.gettempdir()).joinpath("tesseract.exe")
logger.info(f"Creating: {fout}")
with open(fout, 'wb') as f:
f.write(r.content)
toast('Download: Succesful')
logger.info(f'Download: Succesful')
startfile(fout)
get_app().stop()
except Exception as e:
print(e)
toast('Download: Error')
logger.info(f'Download: Error while downloading')
def install_unix_dialog():
def close_dialog(instance, *args):
instance.parent.parent.parent.parent.dismiss()
layout = MDBoxLayout(orientation="horizontal", adaptive_height=True)
layout.add_widget(MDTextField(hint_text="Password",password=True))
dialog = MDDialog(title="Enter sudo password to change the rights of the destination folder",
type='custom',
auto_dismiss=False,
content_cls=layout,
buttons=[
MDFlatButton(
text="ENTER", on_release=partial(install_unix)
),
MDFlatButton(
text="DISCARD", on_release=close_dialog
),
],
)
dialog.content_cls.focused = True
dialog.open()
def install_unix(instance, *args):
pwd = instance.parent.parent.parent.parent.content_cls.children[0].text
instance.parent.parent.parent.parent.dismiss()
install_tesseract = Popen(['sudo', '-S', 'ap-get', 'install', '-y', 'tesseract-ocr'],
stdin=PIPE, stdout=DEVNULL, stderr=STDOUT)
install_tesseract.stdin.write(bytes(pwd, 'utf-8'))
install_tesseract.communicate()
get_app().stop()
return | tesseractXplore/tesseract.py | from logging import getLogger
from sys import platform as _platform
from subprocess import Popen, PIPE,DEVNULL, STDOUT
from pathlib import Path
import requests
from kivymd.uix.list import OneLineListItem
from kivymd.uix.dialog import MDDialog
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.textfield import MDTextField
from kivymd.uix.button import MDFlatButton
from kivymd.toast import toast
from functools import partial
from tesseractXplore.app import get_app
logger = getLogger().getChild(__name__)
def install_tesseract_dialog():
def close_dialog(instance, *args):
instance.parent.parent.parent.parent.dismiss()
layout = MDBoxLayout(orientation="horizontal", adaptive_height=True)
layout.add_widget(OneLineListItem(text="Tesseract wasn't found on the system. You can install it now or set"
"the right path in the settings-menu. (Restart required)"))
dialog = MDDialog(title="Installing tesseract?",
type='custom',
auto_dismiss=False,
content_cls=layout,
buttons=[
MDFlatButton(
text="INSTALL", on_release=partial(install_tesseract)
),
MDFlatButton(
text="DISCARD", on_release=close_dialog
),
],
)
dialog.content_cls.focused = True
dialog.open()
def install_tesseract(instance):
instance.parent.parent.parent.parent.dismiss()
if _platform in ["win32", "win64"]:
install_win()
else:
install_unix_dialog()
def install_win():
try:
if _platform == "win32":
url = get_app().settings_controller.tesseract['win32url']
else:
url = get_app().settings_controller.tesseract['win64url']
r = requests.get(url)
import tempfile
from os import startfile
fout = Path(tempfile.gettempdir()).joinpath("tesseract.exe")
logger.info(f"Creating: {fout}")
with open(fout, 'wb') as f:
f.write(r.content)
toast('Download: Succesful')
logger.info(f'Download: Succesful')
startfile(fout)
get_app().stop()
except Exception as e:
print(e)
toast('Download: Error')
logger.info(f'Download: Error while downloading')
def install_unix_dialog():
def close_dialog(instance, *args):
instance.parent.parent.parent.parent.dismiss()
layout = MDBoxLayout(orientation="horizontal", adaptive_height=True)
layout.add_widget(MDTextField(hint_text="Password",password=True))
dialog = MDDialog(title="Enter sudo password to change the rights of the destination folder",
type='custom',
auto_dismiss=False,
content_cls=layout,
buttons=[
MDFlatButton(
text="ENTER", on_release=partial(install_unix)
),
MDFlatButton(
text="DISCARD", on_release=close_dialog
),
],
)
dialog.content_cls.focused = True
dialog.open()
def install_unix(instance, *args):
pwd = instance.parent.parent.parent.parent.content_cls.children[0].text
instance.parent.parent.parent.parent.dismiss()
install_tesseract = Popen(['sudo', '-S', 'ap-get', 'install', '-y', 'tesseract-ocr'],
stdin=PIPE, stdout=DEVNULL, stderr=STDOUT)
install_tesseract.stdin.write(bytes(pwd, 'utf-8'))
install_tesseract.communicate()
get_app().stop()
return | 0.189521 | 0.07373 |
""" Test queries with ModelSEEDDatabase compounds/reactions data """
import unittest
from nosqlbiosets.dbutils import DBconnection
from nosqlbiosets.graphutils import neighbors_graph, shortest_paths,\
set_degree_as_weight
from nosqlbiosets.modelseed.query import QueryModelSEED
qry = QueryModelSEED(db="MongoDB", index="biosets")
class TestQueryModelSEEDDatabase(unittest.TestCase):
# Finds ModelSEEDdb 'status' values for KEGG reactions
# https://github.com/ModelSEED/ModelSEEDDatabase/tree/master/Biochemistry#reaction-status-values
def test_kegg_reactions_in_modelseeddb(self):
rstatus = {"OK": 6869, "CI:1": 27, "CI:2": 175, "CI:4": 19,
"CI:-2": 137, "CI:-4": 16,
"MI:O:1": 118, "MI:O:-1": 16, "MI:H:2/N:1/R:1": 54,
"MI:C:1/H:2": 32,
"MI:H:-1/O:1|CI:-1": 22,
"MI:C:6/H:10/O:5": 19,
"MI:H:-2/O:1": 22,
"MI:C:-1/H:-2": 22,
"MI:H:-2/N:-1/R:-1": 88,
"CPDFORMERROR": 224}
aggpl = [
{"$project": {"abbreviation": 1, "status": 1}},
{"$match": {"abbreviation": {"$regex": "^R[0-9]*$"}}},
{"$group": {
"_id": "$status",
"kegg_ids": {"$addToSet": "$abbreviation"}
}}
]
r = qry.dbc.mdbi["modelseed_reaction"].aggregate(aggpl)
for i in r:
# 769 different status values, check only frequent values
if len(i['kegg_ids']) > 15:
self.assertAlmostEqual(len(i['kegg_ids']), rstatus[i['_id']],
delta=10), i['_id']
def test_compounds_in_transport_reactions(self):
# Test with the compounds of transport reactions
aggpl = [
{"$match": {
'is_transport': True,
"is_obsolete": False
}},
{"$project": {"compound_ids": 1, "status": 1}}
]
r = qry.dbc.mdbi["modelseed_reaction"].aggregate(aggpl)
r = list(r)
assert len(r) == 3728
cids = set()
for i in r:
for j in i['compound_ids'].split(';'):
cids.add(j)
print(len(cids))
assert len(cids) == 2384
qc = [
{"$match": {
'_id': {"$in": list(cids)}
}},
{"$project": {"aliases": 1, "_id":0}}
]
r = qry.dbc.mdbi["modelseed_compound"].aggregate(qc)
r = list(r)
assert len(r) == 2384
def aliases2keggids(a):
if "KEGG" not in a:
return []
keggids = [i for i in a.split('|') if i.startswith("KEGG")][0]
return [i for i in keggids[6:].split('; ') if i[0] == 'C']
cids.clear()
for c in r:
if 'aliases' in c:
ids = aliases2keggids(c['aliases'])
cids = cids.union(ids)
assert len(cids) == 1390
def test_comparewithMetaNetX_reactions(self):
aggpl = [
{"$match": {"status": "OK"}},
{"$project": {"abbreviation": 1}},
{"$match": {"abbreviation": {"$regex": "^R[0-9]*$"}}}
]
r = qry.dbc.mdbi["modelseed_reaction"].aggregate(aggpl)
inmodelseeddb = {i['abbreviation'] for i in r}
self.assertAlmostEqual(6859, len(inmodelseeddb), delta=300)
aggpl = [
{"$match": {"balance": "true"}},
{"$project": {"xrefs": 1}},
{"$unwind": "$xrefs"},
{"$match": {"xrefs.lib": "kegg"}}
]
r = qry.dbc.mdbi["metanetx_reaction"].aggregate(aggpl)
inmetanetx = {i['xrefs']['id'] for i in r}
assert 7927 == len(inmetanetx)
self.assertAlmostEqual(len(inmodelseeddb - inmetanetx), 542, delta=80)
self.assertAlmostEqual(len(inmodelseeddb.union(inmetanetx)), 8453,
delta=100)
self.assertAlmostEqual(6317,
len(inmodelseeddb.intersection(inmetanetx)),
delta=100)
def test_comparewithMetaNetX_inchikeys(self):
r = qry.dbc.mdbi["modelseed_compound"].distinct("inchikey")
inmodelseeddb = {i for i in r}
self.assertAlmostEqual(24082, len(inmodelseeddb), delta=300)
aggpl = [
{"$match": {"source.lib": "seed"}},
{"$group": {"_id": "$inchikey"}}
]
r = qry.dbc.mdbi["metanetx_compound"].aggregate(aggpl)
inmetanetx = {i['_id'] for i in r}
self.assertAlmostEqual(3097, len(inmetanetx), delta=100)
assert len(inmodelseeddb - inmetanetx) == 21971
assert len(inmodelseeddb.union(inmetanetx)) == 25068
self.assertAlmostEqual(len(inmodelseeddb.intersection(inmetanetx)),
2100, delta=30)
def test_modelseeddb_parse_equation(self):
from nosqlbiosets.modelseed.query import modelseeddb_parse_equation
eq = "(1) cpd00003[0] + (1) cpd19024[0] <=>" \
" (1) cpd00004[0] + (3) cpd00067[0] + (1) cpd00428[0]"
reactants, products, direction = modelseeddb_parse_equation(eq)
assert len(reactants) == 2
assert len(products) == 3
assert direction == '='
def test_compoundnames(self):
mids = ['cpd00191', 'cpd00047', 'cpd00100']
descs = ['3-Oxopropanoate', 'Formate', 'Glycerol']
esdbc = DBconnection("Elasticsearch", "modelseed_compound")
for mid in mids:
desc = descs.pop(0)
assert desc == qry.getcompoundname(esdbc, mid)
assert desc == qry.getcompoundname(qry.dbc, mid)
def test_textsearch_metabolites(self):
mids = ['cpd00306', 'cpd00191', 'cpd00047', 'cpd00776',
'cpd00100', 'cpd26831']
names = ['Xylitol', '3-Oxopropanoate', 'Formate', 'Squalene',
'Glycerol', 'D-xylose']
for mid in mids:
name = names.pop(0)
for qterm in [name.lower(), name.upper(), name]:
r = qry.textsearch_metabolites(qterm)
assert 1 <= len(r)
assert mid in [i['_id'] for i in r]
def test_autocomplete_metabolitenames(self):
names = ['Xylitol', '3-Oxopropanoate', 'Formate', 'Squalene',
'Glycerol', 'D-Xylose']
for name in names:
for qterm in [name.lower(), name.upper(), name[:4]]:
r = qry.autocomplete_metabolitenames(qterm)
assert any(name in i['name'] for i in r), name
def test_metabolite_networks_neighbors(self):
qc = {
'$text': {'$search': 'glycerol'}
}
mn = qry.get_metabolite_network(qc, limit=1440)
assert "Glycerol" in mn.nodes
assert len(mn.edges) == 3219
assert len(mn.nodes) == 906
qc = {
'$text': {'$search': 'glycerol'},
'is_transport': True
}
mn = qry.get_metabolite_network(qc)
assert "Glycerol" in mn.nodes
assert len(mn.edges) == 228
assert len(mn.nodes) == 64
qc = {"_id": "rxn36327"}
mn = qry.get_metabolite_network(qc)
assert "(S)-Propane-1,2-diol" in mn.nodes
qc = {"status": "OK", "reversibility": "<"}
mn = qry.get_metabolite_network(qc)
self.assertAlmostEqual(len(mn.edges), 2027, delta=100)
self.assertAlmostEqual(len(mn.nodes), 961, delta=100)
assert 'Phosphate' in mn.nodes
r = neighbors_graph(mn, "Phosphate", beamwidth=8, maxnodes=100)
assert r.number_of_nodes() == 95
r = neighbors_graph(mn, "Phosphate", beamwidth=6, maxnodes=20)
assert r.number_of_nodes() == 20
r = neighbors_graph(mn, "Phosphate", beamwidth=4, maxnodes=20)
assert r.number_of_nodes() == 20
def test_metabolite_networks_shortespaths(self):
qc = {}
mn = qry.get_metabolite_network(qc)
assert "(S)-Propane-1,2-diol" in mn.nodes
assert "3-Hydroxypropanal" in mn.nodes
assert mn.has_node('D-Xylose')
assert mn.has_node('Xylitol')
assert mn.has_edge('Parapyruvate', 'Pyruvate')
assert '4-hydroxy-4-methyl-2-oxoglutarate pyruvate-lyase' \
' (pyruvate-forming)' in\
mn.get_edge_data('Parapyruvate', 'Pyruvate')['reactions']
self.assertAlmostEqual(len(mn.edges), 97416, delta=1000)
self.assertAlmostEqual(len(mn.nodes), 20510, delta=1000)
assert 'Glycerol' in mn.nodes
paths = shortest_paths(mn, 'D-Xylose', 'Xylitol', 40)
assert len(paths) == 40
assert len(paths[0]) == 3
paths = shortest_paths(mn, 'Parapyruvate', 'Pyruvate', 40)
assert len(paths) == 40
assert len(paths[0]) == 2
set_degree_as_weight(mn)
paths = shortest_paths(mn, 'D-Xylose', 'Xylitol', 10,
cutoff=8, weight='weight')
assert len(paths) == 6
assert 8 == len(paths[0])
paths = shortest_paths(mn, 'Parapyruvate', 'Pyruvate', 20,
weight='weight')
assert 9 == len(paths)
assert 2 == len(paths[0])
if __name__ == '__main__':
unittest.main() | tests/test_modelseeddb_queries.py | """ Test queries with ModelSEEDDatabase compounds/reactions data """
import unittest
from nosqlbiosets.dbutils import DBconnection
from nosqlbiosets.graphutils import neighbors_graph, shortest_paths,\
set_degree_as_weight
from nosqlbiosets.modelseed.query import QueryModelSEED
qry = QueryModelSEED(db="MongoDB", index="biosets")
class TestQueryModelSEEDDatabase(unittest.TestCase):
# Finds ModelSEEDdb 'status' values for KEGG reactions
# https://github.com/ModelSEED/ModelSEEDDatabase/tree/master/Biochemistry#reaction-status-values
def test_kegg_reactions_in_modelseeddb(self):
rstatus = {"OK": 6869, "CI:1": 27, "CI:2": 175, "CI:4": 19,
"CI:-2": 137, "CI:-4": 16,
"MI:O:1": 118, "MI:O:-1": 16, "MI:H:2/N:1/R:1": 54,
"MI:C:1/H:2": 32,
"MI:H:-1/O:1|CI:-1": 22,
"MI:C:6/H:10/O:5": 19,
"MI:H:-2/O:1": 22,
"MI:C:-1/H:-2": 22,
"MI:H:-2/N:-1/R:-1": 88,
"CPDFORMERROR": 224}
aggpl = [
{"$project": {"abbreviation": 1, "status": 1}},
{"$match": {"abbreviation": {"$regex": "^R[0-9]*$"}}},
{"$group": {
"_id": "$status",
"kegg_ids": {"$addToSet": "$abbreviation"}
}}
]
r = qry.dbc.mdbi["modelseed_reaction"].aggregate(aggpl)
for i in r:
# 769 different status values, check only frequent values
if len(i['kegg_ids']) > 15:
self.assertAlmostEqual(len(i['kegg_ids']), rstatus[i['_id']],
delta=10), i['_id']
def test_compounds_in_transport_reactions(self):
# Test with the compounds of transport reactions
aggpl = [
{"$match": {
'is_transport': True,
"is_obsolete": False
}},
{"$project": {"compound_ids": 1, "status": 1}}
]
r = qry.dbc.mdbi["modelseed_reaction"].aggregate(aggpl)
r = list(r)
assert len(r) == 3728
cids = set()
for i in r:
for j in i['compound_ids'].split(';'):
cids.add(j)
print(len(cids))
assert len(cids) == 2384
qc = [
{"$match": {
'_id': {"$in": list(cids)}
}},
{"$project": {"aliases": 1, "_id":0}}
]
r = qry.dbc.mdbi["modelseed_compound"].aggregate(qc)
r = list(r)
assert len(r) == 2384
def aliases2keggids(a):
if "KEGG" not in a:
return []
keggids = [i for i in a.split('|') if i.startswith("KEGG")][0]
return [i for i in keggids[6:].split('; ') if i[0] == 'C']
cids.clear()
for c in r:
if 'aliases' in c:
ids = aliases2keggids(c['aliases'])
cids = cids.union(ids)
assert len(cids) == 1390
def test_comparewithMetaNetX_reactions(self):
aggpl = [
{"$match": {"status": "OK"}},
{"$project": {"abbreviation": 1}},
{"$match": {"abbreviation": {"$regex": "^R[0-9]*$"}}}
]
r = qry.dbc.mdbi["modelseed_reaction"].aggregate(aggpl)
inmodelseeddb = {i['abbreviation'] for i in r}
self.assertAlmostEqual(6859, len(inmodelseeddb), delta=300)
aggpl = [
{"$match": {"balance": "true"}},
{"$project": {"xrefs": 1}},
{"$unwind": "$xrefs"},
{"$match": {"xrefs.lib": "kegg"}}
]
r = qry.dbc.mdbi["metanetx_reaction"].aggregate(aggpl)
inmetanetx = {i['xrefs']['id'] for i in r}
assert 7927 == len(inmetanetx)
self.assertAlmostEqual(len(inmodelseeddb - inmetanetx), 542, delta=80)
self.assertAlmostEqual(len(inmodelseeddb.union(inmetanetx)), 8453,
delta=100)
self.assertAlmostEqual(6317,
len(inmodelseeddb.intersection(inmetanetx)),
delta=100)
def test_comparewithMetaNetX_inchikeys(self):
r = qry.dbc.mdbi["modelseed_compound"].distinct("inchikey")
inmodelseeddb = {i for i in r}
self.assertAlmostEqual(24082, len(inmodelseeddb), delta=300)
aggpl = [
{"$match": {"source.lib": "seed"}},
{"$group": {"_id": "$inchikey"}}
]
r = qry.dbc.mdbi["metanetx_compound"].aggregate(aggpl)
inmetanetx = {i['_id'] for i in r}
self.assertAlmostEqual(3097, len(inmetanetx), delta=100)
assert len(inmodelseeddb - inmetanetx) == 21971
assert len(inmodelseeddb.union(inmetanetx)) == 25068
self.assertAlmostEqual(len(inmodelseeddb.intersection(inmetanetx)),
2100, delta=30)
def test_modelseeddb_parse_equation(self):
from nosqlbiosets.modelseed.query import modelseeddb_parse_equation
eq = "(1) cpd00003[0] + (1) cpd19024[0] <=>" \
" (1) cpd00004[0] + (3) cpd00067[0] + (1) cpd00428[0]"
reactants, products, direction = modelseeddb_parse_equation(eq)
assert len(reactants) == 2
assert len(products) == 3
assert direction == '='
def test_compoundnames(self):
mids = ['cpd00191', 'cpd00047', 'cpd00100']
descs = ['3-Oxopropanoate', 'Formate', 'Glycerol']
esdbc = DBconnection("Elasticsearch", "modelseed_compound")
for mid in mids:
desc = descs.pop(0)
assert desc == qry.getcompoundname(esdbc, mid)
assert desc == qry.getcompoundname(qry.dbc, mid)
def test_textsearch_metabolites(self):
mids = ['cpd00306', 'cpd00191', 'cpd00047', 'cpd00776',
'cpd00100', 'cpd26831']
names = ['Xylitol', '3-Oxopropanoate', 'Formate', 'Squalene',
'Glycerol', 'D-xylose']
for mid in mids:
name = names.pop(0)
for qterm in [name.lower(), name.upper(), name]:
r = qry.textsearch_metabolites(qterm)
assert 1 <= len(r)
assert mid in [i['_id'] for i in r]
def test_autocomplete_metabolitenames(self):
names = ['Xylitol', '3-Oxopropanoate', 'Formate', 'Squalene',
'Glycerol', 'D-Xylose']
for name in names:
for qterm in [name.lower(), name.upper(), name[:4]]:
r = qry.autocomplete_metabolitenames(qterm)
assert any(name in i['name'] for i in r), name
def test_metabolite_networks_neighbors(self):
qc = {
'$text': {'$search': 'glycerol'}
}
mn = qry.get_metabolite_network(qc, limit=1440)
assert "Glycerol" in mn.nodes
assert len(mn.edges) == 3219
assert len(mn.nodes) == 906
qc = {
'$text': {'$search': 'glycerol'},
'is_transport': True
}
mn = qry.get_metabolite_network(qc)
assert "Glycerol" in mn.nodes
assert len(mn.edges) == 228
assert len(mn.nodes) == 64
qc = {"_id": "rxn36327"}
mn = qry.get_metabolite_network(qc)
assert "(S)-Propane-1,2-diol" in mn.nodes
qc = {"status": "OK", "reversibility": "<"}
mn = qry.get_metabolite_network(qc)
self.assertAlmostEqual(len(mn.edges), 2027, delta=100)
self.assertAlmostEqual(len(mn.nodes), 961, delta=100)
assert 'Phosphate' in mn.nodes
r = neighbors_graph(mn, "Phosphate", beamwidth=8, maxnodes=100)
assert r.number_of_nodes() == 95
r = neighbors_graph(mn, "Phosphate", beamwidth=6, maxnodes=20)
assert r.number_of_nodes() == 20
r = neighbors_graph(mn, "Phosphate", beamwidth=4, maxnodes=20)
assert r.number_of_nodes() == 20
def test_metabolite_networks_shortespaths(self):
qc = {}
mn = qry.get_metabolite_network(qc)
assert "(S)-Propane-1,2-diol" in mn.nodes
assert "3-Hydroxypropanal" in mn.nodes
assert mn.has_node('D-Xylose')
assert mn.has_node('Xylitol')
assert mn.has_edge('Parapyruvate', 'Pyruvate')
assert '4-hydroxy-4-methyl-2-oxoglutarate pyruvate-lyase' \
' (pyruvate-forming)' in\
mn.get_edge_data('Parapyruvate', 'Pyruvate')['reactions']
self.assertAlmostEqual(len(mn.edges), 97416, delta=1000)
self.assertAlmostEqual(len(mn.nodes), 20510, delta=1000)
assert 'Glycerol' in mn.nodes
paths = shortest_paths(mn, 'D-Xylose', 'Xylitol', 40)
assert len(paths) == 40
assert len(paths[0]) == 3
paths = shortest_paths(mn, 'Parapyruvate', 'Pyruvate', 40)
assert len(paths) == 40
assert len(paths[0]) == 2
set_degree_as_weight(mn)
paths = shortest_paths(mn, 'D-Xylose', 'Xylitol', 10,
cutoff=8, weight='weight')
assert len(paths) == 6
assert 8 == len(paths[0])
paths = shortest_paths(mn, 'Parapyruvate', 'Pyruvate', 20,
weight='weight')
assert 9 == len(paths)
assert 2 == len(paths[0])
if __name__ == '__main__':
unittest.main() | 0.571408 | 0.610453 |
import pprint
import re # noqa: F401
import six
class Constants(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'bool_values': 'BoolConstants',
'int_64_values': 'Int64Constants',
'string_values': 'StringConstants'
}
attribute_map = {
'bool_values': 'bool_values',
'int_64_values': 'int_64_values',
'string_values': 'string_values'
}
def __init__(self, bool_values=None, int_64_values=None, string_values=None): # noqa: E501
"""Constants - a model defined in Swagger""" # noqa: E501
self._bool_values = None
self._int_64_values = None
self._string_values = None
self.discriminator = None
self.bool_values = bool_values
self.int_64_values = int_64_values
self.string_values = string_values
@property
def bool_values(self):
"""Gets the bool_values of this Constants. # noqa: E501
:return: The bool_values of this Constants. # noqa: E501
:rtype: BoolConstants
"""
return self._bool_values
@bool_values.setter
def bool_values(self, bool_values):
"""Sets the bool_values of this Constants.
:param bool_values: The bool_values of this Constants. # noqa: E501
:type: BoolConstants
"""
if bool_values is None:
raise ValueError("Invalid value for `bool_values`, must not be `None`") # noqa: E501
self._bool_values = bool_values
@property
def int_64_values(self):
"""Gets the int_64_values of this Constants. # noqa: E501
:return: The int_64_values of this Constants. # noqa: E501
:rtype: Int64Constants
"""
return self._int_64_values
@int_64_values.setter
def int_64_values(self, int_64_values):
"""Sets the int_64_values of this Constants.
:param int_64_values: The int_64_values of this Constants. # noqa: E501
:type: Int64Constants
"""
if int_64_values is None:
raise ValueError("Invalid value for `int_64_values`, must not be `None`") # noqa: E501
self._int_64_values = int_64_values
@property
def string_values(self):
"""Gets the string_values of this Constants. # noqa: E501
:return: The string_values of this Constants. # noqa: E501
:rtype: StringConstants
"""
return self._string_values
@string_values.setter
def string_values(self, string_values):
"""Sets the string_values of this Constants.
:param string_values: The string_values of this Constants. # noqa: E501
:type: StringConstants
"""
if string_values is None:
raise ValueError("Invalid value for `string_values`, must not be `None`") # noqa: E501
self._string_values = string_values
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(Constants, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, Constants):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other | midgard_client/midgard_client/models/constants.py | import pprint
import re # noqa: F401
import six
class Constants(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'bool_values': 'BoolConstants',
'int_64_values': 'Int64Constants',
'string_values': 'StringConstants'
}
attribute_map = {
'bool_values': 'bool_values',
'int_64_values': 'int_64_values',
'string_values': 'string_values'
}
def __init__(self, bool_values=None, int_64_values=None, string_values=None): # noqa: E501
"""Constants - a model defined in Swagger""" # noqa: E501
self._bool_values = None
self._int_64_values = None
self._string_values = None
self.discriminator = None
self.bool_values = bool_values
self.int_64_values = int_64_values
self.string_values = string_values
@property
def bool_values(self):
"""Gets the bool_values of this Constants. # noqa: E501
:return: The bool_values of this Constants. # noqa: E501
:rtype: BoolConstants
"""
return self._bool_values
@bool_values.setter
def bool_values(self, bool_values):
"""Sets the bool_values of this Constants.
:param bool_values: The bool_values of this Constants. # noqa: E501
:type: BoolConstants
"""
if bool_values is None:
raise ValueError("Invalid value for `bool_values`, must not be `None`") # noqa: E501
self._bool_values = bool_values
@property
def int_64_values(self):
"""Gets the int_64_values of this Constants. # noqa: E501
:return: The int_64_values of this Constants. # noqa: E501
:rtype: Int64Constants
"""
return self._int_64_values
@int_64_values.setter
def int_64_values(self, int_64_values):
"""Sets the int_64_values of this Constants.
:param int_64_values: The int_64_values of this Constants. # noqa: E501
:type: Int64Constants
"""
if int_64_values is None:
raise ValueError("Invalid value for `int_64_values`, must not be `None`") # noqa: E501
self._int_64_values = int_64_values
@property
def string_values(self):
"""Gets the string_values of this Constants. # noqa: E501
:return: The string_values of this Constants. # noqa: E501
:rtype: StringConstants
"""
return self._string_values
@string_values.setter
def string_values(self, string_values):
"""Sets the string_values of this Constants.
:param string_values: The string_values of this Constants. # noqa: E501
:type: StringConstants
"""
if string_values is None:
raise ValueError("Invalid value for `string_values`, must not be `None`") # noqa: E501
self._string_values = string_values
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(Constants, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, Constants):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other | 0.622918 | 0.446917 |
import argparse
import sys
from collections import defaultdict
# Check correct usage
parser = argparse.ArgumentParser(description="Parse some data.")
parser.add_argument('input', metavar='input', type=str,
help='Input data file.')
args = parser.parse_args()
data = []
grid = defaultdict(int)
# Parse the input file
def parseInput(inp):
try:
input_fh = open(inp, 'r')
except IOError:
sys.exit("Unable to open input file: " + inp)
for line in input_fh:
data.append(line.strip("\n"))
# Only consider horizontal lines
def processHorizontals():
for line in data:
temp = []
points = line.split(" -> ")
for point in points:
(re, im) = point.split(",")
temp.append(int(re) + int(im) * 1j)
if (temp[0].real == temp[1].real):
start = int(min(temp[0].imag, temp[1].imag))
stop = int(max(temp[0].imag, temp[1].imag))
for v in range(start, stop + 1):
grid[temp[0].real + v * 1j] += 1
elif (temp[0].imag == temp[1].imag):
start = int(min(temp[0].real, temp[1].real))
stop = int(max(temp[0].real, temp[1].real))
for v in range(start, stop + 1):
grid[v + temp[0].imag * 1j] += 1
# Process Diagonals
else:
# TLBR
if (temp[0].real < temp[1].real) and (temp[0].imag < temp[1].imag):
for step in range(int(temp[1].real - temp[0].real) + 1):
grid[temp[0].real + step + (temp[0].imag + step) * 1j] += 1
elif (temp[0].real > temp[1].real) and (temp[0].imag > temp[1].imag):
for step in range(int(temp[0].real - temp[1].real) + 1):
grid[temp[1].real + step + (temp[1].imag + step) * 1j] += 1
# TRBL
elif (temp[0].real < temp[1].real) and (temp[0].imag > temp[1].imag):
for step in range(int(temp[1].real - temp[0].real) + 1):
grid[temp[0].real + step + (temp[0].imag - step) * 1j] += 1
elif (temp[0].real > temp[1].real) and (temp[0].imag < temp[1].imag):
for step in range(int(temp[0].real - temp[1].real) + 1):
grid[temp[1].real + step + (temp[1].imag - step) * 1j] += 1
# Debug visualisation for test input
"""for y in range(10):
for x in range(10):
if (grid[x + y * 1j] == 0):
print(".", end="")
else:
print(grid[x + y * 1j], end="")
print("\n", end="")"""
count = 0
for loc in grid:
if (grid[loc] > 1):
count += 1
print(f"Solution: {count}")
# Process diagonals
def processDiagonals():
return False
def main():
parseInput(args.input)
# Part 1
processHorizontals()
# Part 2
processDiagonals()
if __name__ == "__main__":
main() | 2021/src/day-05.py |
import argparse
import sys
from collections import defaultdict
# Check correct usage
parser = argparse.ArgumentParser(description="Parse some data.")
parser.add_argument('input', metavar='input', type=str,
help='Input data file.')
args = parser.parse_args()
data = []
grid = defaultdict(int)
# Parse the input file
def parseInput(inp):
try:
input_fh = open(inp, 'r')
except IOError:
sys.exit("Unable to open input file: " + inp)
for line in input_fh:
data.append(line.strip("\n"))
# Only consider horizontal lines
def processHorizontals():
for line in data:
temp = []
points = line.split(" -> ")
for point in points:
(re, im) = point.split(",")
temp.append(int(re) + int(im) * 1j)
if (temp[0].real == temp[1].real):
start = int(min(temp[0].imag, temp[1].imag))
stop = int(max(temp[0].imag, temp[1].imag))
for v in range(start, stop + 1):
grid[temp[0].real + v * 1j] += 1
elif (temp[0].imag == temp[1].imag):
start = int(min(temp[0].real, temp[1].real))
stop = int(max(temp[0].real, temp[1].real))
for v in range(start, stop + 1):
grid[v + temp[0].imag * 1j] += 1
# Process Diagonals
else:
# TLBR
if (temp[0].real < temp[1].real) and (temp[0].imag < temp[1].imag):
for step in range(int(temp[1].real - temp[0].real) + 1):
grid[temp[0].real + step + (temp[0].imag + step) * 1j] += 1
elif (temp[0].real > temp[1].real) and (temp[0].imag > temp[1].imag):
for step in range(int(temp[0].real - temp[1].real) + 1):
grid[temp[1].real + step + (temp[1].imag + step) * 1j] += 1
# TRBL
elif (temp[0].real < temp[1].real) and (temp[0].imag > temp[1].imag):
for step in range(int(temp[1].real - temp[0].real) + 1):
grid[temp[0].real + step + (temp[0].imag - step) * 1j] += 1
elif (temp[0].real > temp[1].real) and (temp[0].imag < temp[1].imag):
for step in range(int(temp[0].real - temp[1].real) + 1):
grid[temp[1].real + step + (temp[1].imag - step) * 1j] += 1
# Debug visualisation for test input
"""for y in range(10):
for x in range(10):
if (grid[x + y * 1j] == 0):
print(".", end="")
else:
print(grid[x + y * 1j], end="")
print("\n", end="")"""
count = 0
for loc in grid:
if (grid[loc] > 1):
count += 1
print(f"Solution: {count}")
# Process diagonals
def processDiagonals():
return False
def main():
parseInput(args.input)
# Part 1
processHorizontals()
# Part 2
processDiagonals()
if __name__ == "__main__":
main() | 0.279828 | 0.230389 |
class Color:
""" Color formats."""
alpha_num = "100"
def __init__(self, hex_code):
if not self.is_valid_hex_code(hex_code):
raise ValueError("{} is not a valid hex code".format(hex_code))
self._hex = hex_code
@staticmethod
def is_valid_hex_code(value):
if value.startswith('#'):
nums = value[1:]
else:
nums = value
if len(nums) != 6:
return False
try:
int(nums, base=16)
except ValueError:
return False
return True
@property
def hex(self):
return self._hex
@property
def rgb(self):
if self.hex.startswith('#'):
hex_code = self.hex[1:]
else:
hex_code = self.hex
colors = []
hex_code = iter(hex_code)
for a in hex_code:
b = next(hex_code)
ci = int(a+b, base=16)
colors.append(ci)
return tuple(colors)
@property
def rgb_percentage(self):
return self.rgb_percented(accuracy=100)
@property
def rgb_large_percentage(self):
# there is a proper word for this...
return self.rgb_percented(accuracy=1000)
def rgb_percented(self, accuracy=100):
perc = []
for part in self.rgb:
p = (part / 256) * accuracy
perc.append(int(p))
return perc
def __hash__(self):
return hash(self._hex)
def __eq__(self, other):
return isinstance(other, self.__class__) and self._hex == other._hex
def __repr__(self):
return f"{self.__class__.__name__}({self._hex})"
class ColorIdentifier:
""" Color identifier formats."""
all_four_bit_color_names = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']
all_four_bit_color_names = all_four_bit_color_names + ['li_' + c for c in all_four_bit_color_names]
def __init__(self, id):
if not self.__class__.is_valid(color_id=id):
raise ValueError(f'color_id {id!r} is not valid')
self._id = id
@classmethod
def is_valid(cls, color_id):
return color_id in range(0, 16)
@classmethod
def all_four_bit_colors(cls):
yield from map(cls, range(0, 16))
@classmethod
def all_resources(cls):
for k in range(0, 16):
yield cls(k)
@property
def resource_id(self):
return 'color' + str(self.id)
@property
def id(self):
return self._id
@property
def escape_sequence_index(self):
if self.id in range(8):
return str(30 + self.id)
elif self.id in range(8, 16):
return f'1;{40 + self.id - 8}'
else:
return None
@property
def four_bit_color_name(self):
return self.all_four_bit_color_names[self.id]
def __eq__(self, other):
return isinstance(other, self.__class__) and self.id == other.id
def __hash__(self):
return hash(self.id)
def __repr__(self):
return f"{self.__class__.__name__}({self.id!r})" | src/xthematic/colors.py | class Color:
""" Color formats."""
alpha_num = "100"
def __init__(self, hex_code):
if not self.is_valid_hex_code(hex_code):
raise ValueError("{} is not a valid hex code".format(hex_code))
self._hex = hex_code
@staticmethod
def is_valid_hex_code(value):
if value.startswith('#'):
nums = value[1:]
else:
nums = value
if len(nums) != 6:
return False
try:
int(nums, base=16)
except ValueError:
return False
return True
@property
def hex(self):
return self._hex
@property
def rgb(self):
if self.hex.startswith('#'):
hex_code = self.hex[1:]
else:
hex_code = self.hex
colors = []
hex_code = iter(hex_code)
for a in hex_code:
b = next(hex_code)
ci = int(a+b, base=16)
colors.append(ci)
return tuple(colors)
@property
def rgb_percentage(self):
return self.rgb_percented(accuracy=100)
@property
def rgb_large_percentage(self):
# there is a proper word for this...
return self.rgb_percented(accuracy=1000)
def rgb_percented(self, accuracy=100):
perc = []
for part in self.rgb:
p = (part / 256) * accuracy
perc.append(int(p))
return perc
def __hash__(self):
return hash(self._hex)
def __eq__(self, other):
return isinstance(other, self.__class__) and self._hex == other._hex
def __repr__(self):
return f"{self.__class__.__name__}({self._hex})"
class ColorIdentifier:
""" Color identifier formats."""
all_four_bit_color_names = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']
all_four_bit_color_names = all_four_bit_color_names + ['li_' + c for c in all_four_bit_color_names]
def __init__(self, id):
if not self.__class__.is_valid(color_id=id):
raise ValueError(f'color_id {id!r} is not valid')
self._id = id
@classmethod
def is_valid(cls, color_id):
return color_id in range(0, 16)
@classmethod
def all_four_bit_colors(cls):
yield from map(cls, range(0, 16))
@classmethod
def all_resources(cls):
for k in range(0, 16):
yield cls(k)
@property
def resource_id(self):
return 'color' + str(self.id)
@property
def id(self):
return self._id
@property
def escape_sequence_index(self):
if self.id in range(8):
return str(30 + self.id)
elif self.id in range(8, 16):
return f'1;{40 + self.id - 8}'
else:
return None
@property
def four_bit_color_name(self):
return self.all_four_bit_color_names[self.id]
def __eq__(self, other):
return isinstance(other, self.__class__) and self.id == other.id
def __hash__(self):
return hash(self.id)
def __repr__(self):
return f"{self.__class__.__name__}({self.id!r})" | 0.902796 | 0.24068 |
from enum import Enum, auto
class Direction(Enum):
EAST = auto()
NORTH = auto()
WEST = auto()
SOUTH = auto()
def translate(pos, direction, distance):
if direction == "N":
pos = (pos[0]+distance, pos[1])
elif direction == "S":
pos = (pos[0]-distance, pos[1])
elif direction == "E":
pos = (pos[0], pos[1]+distance)
elif direction == "W":
pos = (pos[0], pos[1]-distance)
return pos
def turn(heading, direction, degrees):
turns = {
"L": {
Direction.EAST: Direction.NORTH,
Direction.NORTH: Direction.WEST,
Direction.WEST: Direction.SOUTH,
Direction.SOUTH: Direction.EAST
},
"R": {
Direction.EAST: Direction.SOUTH,
Direction.SOUTH: Direction.WEST,
Direction.WEST: Direction.NORTH,
Direction.NORTH: Direction.EAST
}
}
n_turns = degrees // 90
for turn in range(n_turns):
heading = turns[direction][heading]
return heading
def forward(pos, heading, distance):
if heading == Direction.EAST:
pos = (pos[0], pos[1]+distance)
elif heading == Direction.NORTH:
pos = (pos[0]+distance, pos[1])
elif heading == Direction.WEST:
pos = (pos[0], pos[1]-distance)
elif heading == Direction.SOUTH:
pos = (pos[0]-distance, pos[1])
return pos
def update_position(instruction, pos, heading):
action, arg = instruction[0], int(instruction[1:])
if action in ["N", "S", "E", "W"]:
pos = translate(pos, action, arg)
elif action in ["L", "R"]:
heading = turn(heading, action, arg)
elif action == "F":
pos = forward(pos, heading, arg)
return pos, heading
def follow_route(route):
pos = (0, 0)
heading = Direction.EAST
for instruction in route.splitlines():
pos, heading = update_position(instruction, pos, heading)
return pos, heading
def manhattan_distance(pos):
return abs(pos[0]) + abs(pos[1])
def rotate(waypoint, direction, degrees):
n_turns = degrees // 90
for i in range(n_turns):
if direction == "L":
waypoint = (waypoint[1], -waypoint[0])
if direction == "R":
waypoint = (-waypoint[1], waypoint[0])
return waypoint
def forward2(pos, waypoint, distance):
return (pos[0]+waypoint[0]*distance, pos[1]+waypoint[1]*distance)
def update_position2(instruction, pos, waypoint):
action, arg = instruction[0], int(instruction[1:])
if action in ["N", "S", "E", "W"]:
waypoint = translate(waypoint, action, arg)
elif action in ["L", "R"]:
waypoint = rotate(waypoint, action, arg)
elif action == "F":
pos = forward2(pos, waypoint, arg)
return pos, waypoint
def follow_route2(route):
pos = (0, 0)
waypoint = (1, 10)
for instruction in route.splitlines():
pos, waypoint = update_position2(instruction, pos, waypoint)
return pos | adventofcode/day12.py | from enum import Enum, auto
class Direction(Enum):
EAST = auto()
NORTH = auto()
WEST = auto()
SOUTH = auto()
def translate(pos, direction, distance):
if direction == "N":
pos = (pos[0]+distance, pos[1])
elif direction == "S":
pos = (pos[0]-distance, pos[1])
elif direction == "E":
pos = (pos[0], pos[1]+distance)
elif direction == "W":
pos = (pos[0], pos[1]-distance)
return pos
def turn(heading, direction, degrees):
turns = {
"L": {
Direction.EAST: Direction.NORTH,
Direction.NORTH: Direction.WEST,
Direction.WEST: Direction.SOUTH,
Direction.SOUTH: Direction.EAST
},
"R": {
Direction.EAST: Direction.SOUTH,
Direction.SOUTH: Direction.WEST,
Direction.WEST: Direction.NORTH,
Direction.NORTH: Direction.EAST
}
}
n_turns = degrees // 90
for turn in range(n_turns):
heading = turns[direction][heading]
return heading
def forward(pos, heading, distance):
if heading == Direction.EAST:
pos = (pos[0], pos[1]+distance)
elif heading == Direction.NORTH:
pos = (pos[0]+distance, pos[1])
elif heading == Direction.WEST:
pos = (pos[0], pos[1]-distance)
elif heading == Direction.SOUTH:
pos = (pos[0]-distance, pos[1])
return pos
def update_position(instruction, pos, heading):
action, arg = instruction[0], int(instruction[1:])
if action in ["N", "S", "E", "W"]:
pos = translate(pos, action, arg)
elif action in ["L", "R"]:
heading = turn(heading, action, arg)
elif action == "F":
pos = forward(pos, heading, arg)
return pos, heading
def follow_route(route):
pos = (0, 0)
heading = Direction.EAST
for instruction in route.splitlines():
pos, heading = update_position(instruction, pos, heading)
return pos, heading
def manhattan_distance(pos):
return abs(pos[0]) + abs(pos[1])
def rotate(waypoint, direction, degrees):
n_turns = degrees // 90
for i in range(n_turns):
if direction == "L":
waypoint = (waypoint[1], -waypoint[0])
if direction == "R":
waypoint = (-waypoint[1], waypoint[0])
return waypoint
def forward2(pos, waypoint, distance):
return (pos[0]+waypoint[0]*distance, pos[1]+waypoint[1]*distance)
def update_position2(instruction, pos, waypoint):
action, arg = instruction[0], int(instruction[1:])
if action in ["N", "S", "E", "W"]:
waypoint = translate(waypoint, action, arg)
elif action in ["L", "R"]:
waypoint = rotate(waypoint, action, arg)
elif action == "F":
pos = forward2(pos, waypoint, arg)
return pos, waypoint
def follow_route2(route):
pos = (0, 0)
waypoint = (1, 10)
for instruction in route.splitlines():
pos, waypoint = update_position2(instruction, pos, waypoint)
return pos | 0.698741 | 0.658541 |
import typing
from cloudevents.sdk import exceptions
from cloudevents.sdk.converters import base
from cloudevents.sdk.converters import binary
from cloudevents.sdk.converters import structured
from cloudevents.sdk.event import base as event_base
class HTTPMarshaller(object):
"""
HTTP Marshaller class.
API of this class designed to work with CloudEvent (upstream and v0.1)
"""
def __init__(self, converters: typing.List[base.Converter]):
"""
CloudEvent HTTP marshaller constructor
:param converters: a list of HTTP-to-CloudEvent-to-HTTP constructors
:type converters: typing.List[base.Converter]
"""
self.__converters = [c for c in converters]
self.__converters_by_type = {c.TYPE: c for c in converters}
def FromRequest(
self,
event: event_base.BaseEvent,
headers: dict,
body: typing.IO,
data_unmarshaller: typing.Callable,
) -> event_base.BaseEvent:
"""
Reads a CloudEvent from an HTTP headers and request body
:param event: CloudEvent placeholder
:type event: cloudevents.sdk.event.base.BaseEvent
:param headers: a dict-like HTTP headers
:type headers: dict
:param body: a stream-like HTTP request body
:type body: typing.IO
:param data_unmarshaller: a callable-like
unmarshaller the CloudEvent data
:return: a CloudEvent
:rtype: event_base.BaseEvent
"""
if not isinstance(data_unmarshaller, typing.Callable):
raise exceptions.InvalidDataUnmarshaller()
content_type = headers.get("content-type", headers.get("Content-Type"))
for cnvrtr in self.__converters:
if cnvrtr.can_read(content_type) and cnvrtr.event_supported(event):
return cnvrtr.read(event, headers, body, data_unmarshaller)
raise exceptions.UnsupportedEventConverter(
"No registered marshaller for {0} in {1}".format(
content_type, self.__converters
)
)
def ToRequest(
self,
event: event_base.BaseEvent,
converter_type: str,
data_marshaller: typing.Callable,
) -> (dict, typing.IO):
"""
Writes a CloudEvent into a HTTP-ready form of headers and request body
:param event: CloudEvent
:type event: event_base.BaseEvent
:param converter_type: a type of CloudEvent-to-HTTP converter
:type converter_type: str
:param data_marshaller: a callable-like marshaller CloudEvent data
:type data_marshaller: typing.Callable
:return: dict of HTTP headers and stream of HTTP request body
:rtype: tuple
"""
if not isinstance(data_marshaller, typing.Callable):
raise exceptions.InvalidDataMarshaller()
if converter_type in self.__converters_by_type:
cnvrtr = self.__converters_by_type[converter_type]
return cnvrtr.write(event, data_marshaller)
raise exceptions.NoSuchConverter(converter_type)
def NewDefaultHTTPMarshaller() -> HTTPMarshaller:
"""
Creates the default HTTP marshaller with both structured
and binary converters
:return: an instance of HTTP marshaller
:rtype: cloudevents.sdk.marshaller.HTTPMarshaller
"""
return HTTPMarshaller(
[
structured.NewJSONHTTPCloudEventConverter(),
binary.NewBinaryHTTPCloudEventConverter(),
]
)
def NewHTTPMarshaller(
converters: typing.List[base.Converter]
) -> HTTPMarshaller:
"""
Creates the default HTTP marshaller with both
structured and binary converters
:param converters: a list of CloudEvent-to-HTTP-to-CloudEvent converters
:type converters: typing.List[base.Converter]
:return: an instance of HTTP marshaller
:rtype: cloudevents.sdk.marshaller.HTTPMarshaller
"""
return HTTPMarshaller(converters) | cloudevents/sdk/marshaller.py |
import typing
from cloudevents.sdk import exceptions
from cloudevents.sdk.converters import base
from cloudevents.sdk.converters import binary
from cloudevents.sdk.converters import structured
from cloudevents.sdk.event import base as event_base
class HTTPMarshaller(object):
"""
HTTP Marshaller class.
API of this class designed to work with CloudEvent (upstream and v0.1)
"""
def __init__(self, converters: typing.List[base.Converter]):
"""
CloudEvent HTTP marshaller constructor
:param converters: a list of HTTP-to-CloudEvent-to-HTTP constructors
:type converters: typing.List[base.Converter]
"""
self.__converters = [c for c in converters]
self.__converters_by_type = {c.TYPE: c for c in converters}
def FromRequest(
self,
event: event_base.BaseEvent,
headers: dict,
body: typing.IO,
data_unmarshaller: typing.Callable,
) -> event_base.BaseEvent:
"""
Reads a CloudEvent from an HTTP headers and request body
:param event: CloudEvent placeholder
:type event: cloudevents.sdk.event.base.BaseEvent
:param headers: a dict-like HTTP headers
:type headers: dict
:param body: a stream-like HTTP request body
:type body: typing.IO
:param data_unmarshaller: a callable-like
unmarshaller the CloudEvent data
:return: a CloudEvent
:rtype: event_base.BaseEvent
"""
if not isinstance(data_unmarshaller, typing.Callable):
raise exceptions.InvalidDataUnmarshaller()
content_type = headers.get("content-type", headers.get("Content-Type"))
for cnvrtr in self.__converters:
if cnvrtr.can_read(content_type) and cnvrtr.event_supported(event):
return cnvrtr.read(event, headers, body, data_unmarshaller)
raise exceptions.UnsupportedEventConverter(
"No registered marshaller for {0} in {1}".format(
content_type, self.__converters
)
)
def ToRequest(
self,
event: event_base.BaseEvent,
converter_type: str,
data_marshaller: typing.Callable,
) -> (dict, typing.IO):
"""
Writes a CloudEvent into a HTTP-ready form of headers and request body
:param event: CloudEvent
:type event: event_base.BaseEvent
:param converter_type: a type of CloudEvent-to-HTTP converter
:type converter_type: str
:param data_marshaller: a callable-like marshaller CloudEvent data
:type data_marshaller: typing.Callable
:return: dict of HTTP headers and stream of HTTP request body
:rtype: tuple
"""
if not isinstance(data_marshaller, typing.Callable):
raise exceptions.InvalidDataMarshaller()
if converter_type in self.__converters_by_type:
cnvrtr = self.__converters_by_type[converter_type]
return cnvrtr.write(event, data_marshaller)
raise exceptions.NoSuchConverter(converter_type)
def NewDefaultHTTPMarshaller() -> HTTPMarshaller:
"""
Creates the default HTTP marshaller with both structured
and binary converters
:return: an instance of HTTP marshaller
:rtype: cloudevents.sdk.marshaller.HTTPMarshaller
"""
return HTTPMarshaller(
[
structured.NewJSONHTTPCloudEventConverter(),
binary.NewBinaryHTTPCloudEventConverter(),
]
)
def NewHTTPMarshaller(
converters: typing.List[base.Converter]
) -> HTTPMarshaller:
"""
Creates the default HTTP marshaller with both
structured and binary converters
:param converters: a list of CloudEvent-to-HTTP-to-CloudEvent converters
:type converters: typing.List[base.Converter]
:return: an instance of HTTP marshaller
:rtype: cloudevents.sdk.marshaller.HTTPMarshaller
"""
return HTTPMarshaller(converters) | 0.828349 | 0.166337 |
import arcpy
import math
## Variables
# 3D Lateral Line feature class
laterals = r"N:\foo\bar.gdb\laterals_fc"
perf_fc = r"N:\foo\bar.gdb\perf_point_fc"
# Unique ID for lateral
unique_well_id_name = "BHLID"
unique_well_id = 433
# Measured distance in feet
perf = 12090
# Create empty lists for storing values
loc1 = []
locList = []
# Set location variables surrounding perf
loc1x = 0
loc1y = 0
loc1z = 0
loc1m = 0
loc2x = 0
loc2y = 0
loc2z = 0
loc2m = 10000000000
## Find xyzm locations of the nodes surrounding measure distance value
# Find first node
with arcpy.da.SearchCursor(laterals, ["SHAPE@", "SHAPE@X", "SHAPE@Y", "SHAPE@Z", "SHAPE@M", unique_well_id_name],
"", "", True) as cursor:
for row in cursor: # 0 1 2 3 4 5
if row[6] == unique_well_id:
# Find smallest value surrounding perf location
print row[5]
while row[5] > loc1m and row[5] < perf:
loc1x = row[2]
loc1y = row[3]
loc1z = row[4]
loc1m = row[5]
# print "loc1m is " + str(loc1m)
# print "X=" + str(row[2]) + " Y=" + str(row[3]) + " M=" + str(row[4])
del cursor
# Find second node
with arcpy.da.SearchCursor(laterals, ["SHAPE@", "SHAPE@X", "SHAPE@Y", "SHAPE@Z", "SHAPE@M", unique_well_id_name],
"", "", True) as cursor:
for row in cursor: # 0 1 2 3 4 5
if row[6] == unique_well_id:
# Find largest value surrounding perf location
while row[5] < loc2m and row[5] >= perf:
loc2x = row[2]
loc2y = row[3]
loc2z = row[4]
loc2m = row[5]
# print "X=" + str(row[2]) + " Y=" + str(row[3]) + " M=" + str(row[4])
del cursor
# Find xyz of perf located between the two nodes
xv = loc2x - loc1x
yv = loc2y - loc1y
zv = loc2z - loc1z
xyz2 = math.sqrt(xv**2 + yv**2 + zv**2)
xUnitVector = xv/xyz2
yUnitVector = yv/xyz2
zUnitVector = zv/xyz2
DistFromLoc1 = perf - loc1m
# XYZ location of perf
x3 = loc1x + (DistFromLoc1 * xUnitVector)
y3 = loc1y + (DistFromLoc1 * yUnitVector)
z3 = loc1z + (DistFromLoc1 * zUnitVector)
print "x3= " + str(x3)
print "y3= " + str(y3)
print "z3= " + str(z3)
# Create and add to designated feature class
with arcpy.da.InsertCursor(perf_fc, ["Shape@X", "Shape@Y", "Shape@Z", unique_well_id_name]) as cursor:
cursor.insertRow([x3, y3, z3, unique_well_id])
del cursor | create_perfs.py | import arcpy
import math
## Variables
# 3D Lateral Line feature class
laterals = r"N:\foo\bar.gdb\laterals_fc"
perf_fc = r"N:\foo\bar.gdb\perf_point_fc"
# Unique ID for lateral
unique_well_id_name = "BHLID"
unique_well_id = 433
# Measured distance in feet
perf = 12090
# Create empty lists for storing values
loc1 = []
locList = []
# Set location variables surrounding perf
loc1x = 0
loc1y = 0
loc1z = 0
loc1m = 0
loc2x = 0
loc2y = 0
loc2z = 0
loc2m = 10000000000
## Find xyzm locations of the nodes surrounding measure distance value
# Find first node
with arcpy.da.SearchCursor(laterals, ["SHAPE@", "SHAPE@X", "SHAPE@Y", "SHAPE@Z", "SHAPE@M", unique_well_id_name],
"", "", True) as cursor:
for row in cursor: # 0 1 2 3 4 5
if row[6] == unique_well_id:
# Find smallest value surrounding perf location
print row[5]
while row[5] > loc1m and row[5] < perf:
loc1x = row[2]
loc1y = row[3]
loc1z = row[4]
loc1m = row[5]
# print "loc1m is " + str(loc1m)
# print "X=" + str(row[2]) + " Y=" + str(row[3]) + " M=" + str(row[4])
del cursor
# Find second node
with arcpy.da.SearchCursor(laterals, ["SHAPE@", "SHAPE@X", "SHAPE@Y", "SHAPE@Z", "SHAPE@M", unique_well_id_name],
"", "", True) as cursor:
for row in cursor: # 0 1 2 3 4 5
if row[6] == unique_well_id:
# Find largest value surrounding perf location
while row[5] < loc2m and row[5] >= perf:
loc2x = row[2]
loc2y = row[3]
loc2z = row[4]
loc2m = row[5]
# print "X=" + str(row[2]) + " Y=" + str(row[3]) + " M=" + str(row[4])
del cursor
# Find xyz of perf located between the two nodes
xv = loc2x - loc1x
yv = loc2y - loc1y
zv = loc2z - loc1z
xyz2 = math.sqrt(xv**2 + yv**2 + zv**2)
xUnitVector = xv/xyz2
yUnitVector = yv/xyz2
zUnitVector = zv/xyz2
DistFromLoc1 = perf - loc1m
# XYZ location of perf
x3 = loc1x + (DistFromLoc1 * xUnitVector)
y3 = loc1y + (DistFromLoc1 * yUnitVector)
z3 = loc1z + (DistFromLoc1 * zUnitVector)
print "x3= " + str(x3)
print "y3= " + str(y3)
print "z3= " + str(z3)
# Create and add to designated feature class
with arcpy.da.InsertCursor(perf_fc, ["Shape@X", "Shape@Y", "Shape@Z", unique_well_id_name]) as cursor:
cursor.insertRow([x3, y3, z3, unique_well_id])
del cursor | 0.202996 | 0.296591 |
from __future__ import annotations
import logging
from typing import IO
import boto3
import click
import click_log
import colorlog
import json
from access_undenied_aws import analysis
from access_undenied_aws import common
from access_undenied_aws import logger
from access_undenied_aws import organizations
def _initialize_logger() -> None:
click_log.basic_config(logger)
root_handler = logger.handlers[0]
formatter = colorlog.ColoredFormatter(
"%(log_color)s[%(asctime)s,%(msecs)d %(levelname)-8s"
" %(filename)s:%(lineno)d - %(funcName)20s()]%(reset)s"
" %(white)s%(message)s",
datefmt="%H:%M:%S",
reset=True,
log_colors={
"DEBUG": "blue",
"INFO": "green",
"WARNING": "yellow",
"ERROR": "red",
"CRITICAL": "red",
},
)
root_handler.setFormatter(formatter)
def initialize_config_from_user_input(
config: common.Config,
output_file: IO[str],
management_account_role_arn: str,
suppress_output: bool,
cross_account_role_name: str,
) -> None:
config.cross_account_role_name = cross_account_role_name
config.management_account_role_arn = management_account_role_arn
if logger.level == logging.NOTSET:
logger.setLevel(logging.INFO)
config.output_file = output_file
config.suppress_output = suppress_output
_initialize_logger()
pass_config = click.make_pass_decorator(common.Config, ensure=True)
@click.group()
@click_log.simple_verbosity_option(logger)
@click.option(
"--profile",
help="the AWS profile to use (default is default profile)",
default=None,
)
@pass_config
def access_undenied_aws(config: common.Config, profile: str) -> None:
"""
Parses AWS AccessDenied CloudTrail events, explains the reasons for them, and offers actionable fixes.
"""
config.session = boto3.Session(profile_name=profile)
config.account_id = config.session.client("sts").get_caller_identity()["Account"]
config.iam_client = config.session.client("iam")
@access_undenied_aws.command()
@click.option(
"--events-file",
help="input file of CloudTrail events",
required=True,
type=click.File("r"),
)
@click.option(
"--scp-file",
help="Service control policy data file generated by the get_scps command.",
default=None,
type=click.File("r"),
)
@click.option(
"--management-account-role-arn",
help=(
"a cross-account role in the management account of the organization "
"that must be assumable by your credentials."
),
default=None,
)
@click.option(
"--cross-account-role-name",
help=(
"The name of the cross-account role for AccessUndenied to assume."
" default: AccessUndeniedRole"
),
default="AccessUndeniedRole",
)
@click.option(
"--output-file",
help="output file for results (default: no output to file)",
default=None,
type=click.File("w"),
)
@click.option(
"--suppress-output/--no-suppress-output",
help="should output to stdout be suppressed (default: not suppressed)",
default=False,
)
@pass_config
def analyze(
config: common.Config,
events_file: click.File,
scp_file: IO[str],
management_account_role_arn: str,
cross_account_role_name: str,
output_file: IO[str],
suppress_output: bool,
) -> None:
"""
Analyzes AWS CloudTrail events and explains the reasons for AccessDenied
"""
initialize_config_from_user_input(
config,
output_file,
management_account_role_arn,
suppress_output,
cross_account_role_name,
)
organizations.initialize_organization_data(config, scp_file.read() if scp_file else None)
analysis.analyze_cloudtrail_events(config, events_file)
@access_undenied_aws.command()
@click.option(
"--output-file",
help="output file for scp data (default: scp_data.json)",
default="scp_data.json",
type=click.File("w"),
)
@pass_config
def get_scps(
config: common.Config,
output_file: IO[str],
) -> None:
"""
Writes the organization's SCPs and organizational tree to a file
"""
logger.info("Gathering Service Control Policy data...")
organizations.initialize_organization_data(config, None)
json.dump(config.organization_nodes, output_file, default=vars, indent=2)
logger.info(f"Finished writing Service Control Policy data to {output_file.name}.") | access_undenied_aws/cli.py | from __future__ import annotations
import logging
from typing import IO
import boto3
import click
import click_log
import colorlog
import json
from access_undenied_aws import analysis
from access_undenied_aws import common
from access_undenied_aws import logger
from access_undenied_aws import organizations
def _initialize_logger() -> None:
click_log.basic_config(logger)
root_handler = logger.handlers[0]
formatter = colorlog.ColoredFormatter(
"%(log_color)s[%(asctime)s,%(msecs)d %(levelname)-8s"
" %(filename)s:%(lineno)d - %(funcName)20s()]%(reset)s"
" %(white)s%(message)s",
datefmt="%H:%M:%S",
reset=True,
log_colors={
"DEBUG": "blue",
"INFO": "green",
"WARNING": "yellow",
"ERROR": "red",
"CRITICAL": "red",
},
)
root_handler.setFormatter(formatter)
def initialize_config_from_user_input(
config: common.Config,
output_file: IO[str],
management_account_role_arn: str,
suppress_output: bool,
cross_account_role_name: str,
) -> None:
config.cross_account_role_name = cross_account_role_name
config.management_account_role_arn = management_account_role_arn
if logger.level == logging.NOTSET:
logger.setLevel(logging.INFO)
config.output_file = output_file
config.suppress_output = suppress_output
_initialize_logger()
pass_config = click.make_pass_decorator(common.Config, ensure=True)
@click.group()
@click_log.simple_verbosity_option(logger)
@click.option(
"--profile",
help="the AWS profile to use (default is default profile)",
default=None,
)
@pass_config
def access_undenied_aws(config: common.Config, profile: str) -> None:
"""
Parses AWS AccessDenied CloudTrail events, explains the reasons for them, and offers actionable fixes.
"""
config.session = boto3.Session(profile_name=profile)
config.account_id = config.session.client("sts").get_caller_identity()["Account"]
config.iam_client = config.session.client("iam")
@access_undenied_aws.command()
@click.option(
"--events-file",
help="input file of CloudTrail events",
required=True,
type=click.File("r"),
)
@click.option(
"--scp-file",
help="Service control policy data file generated by the get_scps command.",
default=None,
type=click.File("r"),
)
@click.option(
"--management-account-role-arn",
help=(
"a cross-account role in the management account of the organization "
"that must be assumable by your credentials."
),
default=None,
)
@click.option(
"--cross-account-role-name",
help=(
"The name of the cross-account role for AccessUndenied to assume."
" default: AccessUndeniedRole"
),
default="AccessUndeniedRole",
)
@click.option(
"--output-file",
help="output file for results (default: no output to file)",
default=None,
type=click.File("w"),
)
@click.option(
"--suppress-output/--no-suppress-output",
help="should output to stdout be suppressed (default: not suppressed)",
default=False,
)
@pass_config
def analyze(
config: common.Config,
events_file: click.File,
scp_file: IO[str],
management_account_role_arn: str,
cross_account_role_name: str,
output_file: IO[str],
suppress_output: bool,
) -> None:
"""
Analyzes AWS CloudTrail events and explains the reasons for AccessDenied
"""
initialize_config_from_user_input(
config,
output_file,
management_account_role_arn,
suppress_output,
cross_account_role_name,
)
organizations.initialize_organization_data(config, scp_file.read() if scp_file else None)
analysis.analyze_cloudtrail_events(config, events_file)
@access_undenied_aws.command()
@click.option(
"--output-file",
help="output file for scp data (default: scp_data.json)",
default="scp_data.json",
type=click.File("w"),
)
@pass_config
def get_scps(
config: common.Config,
output_file: IO[str],
) -> None:
"""
Writes the organization's SCPs and organizational tree to a file
"""
logger.info("Gathering Service Control Policy data...")
organizations.initialize_organization_data(config, None)
json.dump(config.organization_nodes, output_file, default=vars, indent=2)
logger.info(f"Finished writing Service Control Policy data to {output_file.name}.") | 0.602412 | 0.074534 |
import argparse
import ray
from ray import tune
from ray.rllib.models import ModelCatalog
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.misc import normc_initializer
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.utils import try_import_tf
from ray.rllib.utils.annotations import override
tf = try_import_tf()
parser = argparse.ArgumentParser()
parser.add_argument("--num-iters", type=int, default=200)
parser.add_argument("--run", type=str, default="PPO")
class BatchNormModel(TFModelV2):
"""Example of a TFModelV2 that is built w/o using tf.keras.
NOTE: This example does not work when using a keras-based TFModelV2 due
to a bug in keras related to missing values for input placeholders, even
though these input values have been provided in a forward pass through the
actual keras Model.
All Model logic (layers) is defined in the `forward` method (incl.
the batch_normalization layers). Also, all variables are registered
(only once) at the end of `forward`, so an optimizer knows which tensors
to train on. A standard `value_function` override is used.
"""
capture_index = 0
def __init__(self, obs_space, action_space, num_outputs, model_config,
name):
super().__init__(obs_space, action_space, num_outputs, model_config,
name)
# Have we registered our vars yet (see `forward`)?
self._registered = False
@override(ModelV2)
def forward(self, input_dict, state, seq_lens):
last_layer = input_dict["obs"]
hiddens = [256, 256]
with tf.variable_scope("model", reuse=tf.AUTO_REUSE):
for i, size in enumerate(hiddens):
last_layer = tf.layers.dense(
last_layer,
size,
kernel_initializer=normc_initializer(1.0),
activation=tf.nn.tanh,
name="fc{}".format(i))
# Add a batch norm layer
last_layer = tf.layers.batch_normalization(
last_layer,
training=input_dict["is_training"],
name="bn_{}".format(i))
output = tf.layers.dense(
last_layer,
self.num_outputs,
kernel_initializer=normc_initializer(0.01),
activation=None,
name="out")
self._value_out = tf.layers.dense(
last_layer,
1,
kernel_initializer=normc_initializer(1.0),
activation=None,
name="vf")
if not self._registered:
self.register_variables(
tf.get_collection(
tf.GraphKeys.TRAINABLE_VARIABLES, scope=".+/model/.+"))
self._registered = True
return output, []
@override(ModelV2)
def value_function(self):
return tf.reshape(self._value_out, [-1])
class KerasBatchNormModel(TFModelV2):
"""Keras version of above BatchNormModel with exactly the same structure.
IMORTANT NOTE: This model will not work with PPO due to a bug in keras
that surfaces when having more than one input placeholder (here: `inputs`
and `is_training`) AND using the `make_tf_callable` helper (e.g. used by
PPO), in which auto-placeholders are generated, then passed through the
tf.keras. models.Model. In this last step, the connection between 1) the
provided value in the auto-placeholder and 2) the keras `is_training`
Input is broken and keras complains.
Use the above `BatchNormModel` (a non-keras based TFModelV2), instead.
"""
def __init__(self, obs_space, action_space, num_outputs, model_config,
name):
super().__init__(obs_space, action_space, num_outputs, model_config,
name)
inputs = tf.keras.layers.Input(shape=obs_space.shape, name="inputs")
is_training = tf.keras.layers.Input(
shape=(), dtype=tf.bool, batch_size=1, name="is_training")
last_layer = inputs
hiddens = [256, 256]
for i, size in enumerate(hiddens):
label = "fc{}".format(i)
last_layer = tf.keras.layers.Dense(
units=size,
kernel_initializer=normc_initializer(1.0),
activation=tf.nn.tanh,
name=label)(last_layer)
# Add a batch norm layer
last_layer = tf.keras.layers.BatchNormalization()(
last_layer, training=is_training[0])
output = tf.keras.layers.Dense(
units=self.num_outputs,
kernel_initializer=normc_initializer(0.01),
activation=None,
name="fc_out")(last_layer)
value_out = tf.keras.layers.Dense(
units=1,
kernel_initializer=normc_initializer(0.01),
activation=None,
name="value_out")(last_layer)
self.base_model = tf.keras.models.Model(
inputs=[inputs, is_training], outputs=[output, value_out])
self.register_variables(self.base_model.variables)
@override(ModelV2)
def forward(self, input_dict, state, seq_lens):
out, self._value_out = self.base_model(
[input_dict["obs"], input_dict["is_training"]])
return out, []
@override(ModelV2)
def value_function(self):
return tf.reshape(self._value_out, [-1])
if __name__ == "__main__":
args = parser.parse_args()
ray.init()
ModelCatalog.register_custom_model("bn_model", BatchNormModel)
config = {
"env": "Pendulum-v0" if args.run == "DDPG" else "CartPole-v0",
"model": {
"custom_model": "bn_model",
},
"num_workers": 0,
}
tune.run(
args.run,
stop={"training_iteration": args.num_iters},
config=config,
) | rllib/examples/batch_norm_model.py |
import argparse
import ray
from ray import tune
from ray.rllib.models import ModelCatalog
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.misc import normc_initializer
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.utils import try_import_tf
from ray.rllib.utils.annotations import override
tf = try_import_tf()
parser = argparse.ArgumentParser()
parser.add_argument("--num-iters", type=int, default=200)
parser.add_argument("--run", type=str, default="PPO")
class BatchNormModel(TFModelV2):
"""Example of a TFModelV2 that is built w/o using tf.keras.
NOTE: This example does not work when using a keras-based TFModelV2 due
to a bug in keras related to missing values for input placeholders, even
though these input values have been provided in a forward pass through the
actual keras Model.
All Model logic (layers) is defined in the `forward` method (incl.
the batch_normalization layers). Also, all variables are registered
(only once) at the end of `forward`, so an optimizer knows which tensors
to train on. A standard `value_function` override is used.
"""
capture_index = 0
def __init__(self, obs_space, action_space, num_outputs, model_config,
name):
super().__init__(obs_space, action_space, num_outputs, model_config,
name)
# Have we registered our vars yet (see `forward`)?
self._registered = False
@override(ModelV2)
def forward(self, input_dict, state, seq_lens):
last_layer = input_dict["obs"]
hiddens = [256, 256]
with tf.variable_scope("model", reuse=tf.AUTO_REUSE):
for i, size in enumerate(hiddens):
last_layer = tf.layers.dense(
last_layer,
size,
kernel_initializer=normc_initializer(1.0),
activation=tf.nn.tanh,
name="fc{}".format(i))
# Add a batch norm layer
last_layer = tf.layers.batch_normalization(
last_layer,
training=input_dict["is_training"],
name="bn_{}".format(i))
output = tf.layers.dense(
last_layer,
self.num_outputs,
kernel_initializer=normc_initializer(0.01),
activation=None,
name="out")
self._value_out = tf.layers.dense(
last_layer,
1,
kernel_initializer=normc_initializer(1.0),
activation=None,
name="vf")
if not self._registered:
self.register_variables(
tf.get_collection(
tf.GraphKeys.TRAINABLE_VARIABLES, scope=".+/model/.+"))
self._registered = True
return output, []
@override(ModelV2)
def value_function(self):
return tf.reshape(self._value_out, [-1])
class KerasBatchNormModel(TFModelV2):
"""Keras version of above BatchNormModel with exactly the same structure.
IMORTANT NOTE: This model will not work with PPO due to a bug in keras
that surfaces when having more than one input placeholder (here: `inputs`
and `is_training`) AND using the `make_tf_callable` helper (e.g. used by
PPO), in which auto-placeholders are generated, then passed through the
tf.keras. models.Model. In this last step, the connection between 1) the
provided value in the auto-placeholder and 2) the keras `is_training`
Input is broken and keras complains.
Use the above `BatchNormModel` (a non-keras based TFModelV2), instead.
"""
def __init__(self, obs_space, action_space, num_outputs, model_config,
name):
super().__init__(obs_space, action_space, num_outputs, model_config,
name)
inputs = tf.keras.layers.Input(shape=obs_space.shape, name="inputs")
is_training = tf.keras.layers.Input(
shape=(), dtype=tf.bool, batch_size=1, name="is_training")
last_layer = inputs
hiddens = [256, 256]
for i, size in enumerate(hiddens):
label = "fc{}".format(i)
last_layer = tf.keras.layers.Dense(
units=size,
kernel_initializer=normc_initializer(1.0),
activation=tf.nn.tanh,
name=label)(last_layer)
# Add a batch norm layer
last_layer = tf.keras.layers.BatchNormalization()(
last_layer, training=is_training[0])
output = tf.keras.layers.Dense(
units=self.num_outputs,
kernel_initializer=normc_initializer(0.01),
activation=None,
name="fc_out")(last_layer)
value_out = tf.keras.layers.Dense(
units=1,
kernel_initializer=normc_initializer(0.01),
activation=None,
name="value_out")(last_layer)
self.base_model = tf.keras.models.Model(
inputs=[inputs, is_training], outputs=[output, value_out])
self.register_variables(self.base_model.variables)
@override(ModelV2)
def forward(self, input_dict, state, seq_lens):
out, self._value_out = self.base_model(
[input_dict["obs"], input_dict["is_training"]])
return out, []
@override(ModelV2)
def value_function(self):
return tf.reshape(self._value_out, [-1])
if __name__ == "__main__":
args = parser.parse_args()
ray.init()
ModelCatalog.register_custom_model("bn_model", BatchNormModel)
config = {
"env": "Pendulum-v0" if args.run == "DDPG" else "CartPole-v0",
"model": {
"custom_model": "bn_model",
},
"num_workers": 0,
}
tune.run(
args.run,
stop={"training_iteration": args.num_iters},
config=config,
) | 0.90942 | 0.356167 |
import os
import sys
from fastapi_websocket_rpc import logger
from fastapi_websocket_rpc.rpc_channel import RpcChannel
# Add parent path to use local src as package for tests
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
import asyncio
from multiprocessing import Process
import requests
import pytest
import uvicorn
from fastapi import APIRouter, FastAPI
from fastapi_websocket_rpc.logger import get_logger
from fastapi_websocket_rpc.utils import gen_uid
from fastapi_websocket_pubsub import PubSubEndpoint, PubSubClient, Subscription
from fastapi_websocket_pubsub.event_notifier import ALL_TOPICS
logger = get_logger("Test")
# Configurable
PORT = int(os.environ.get("PORT") or "7990")
uri = f"ws://localhost:{PORT}/pubsub"
trigger_url = f"http://localhost:{PORT}/trigger"
ask_remote_id_url = f"http://localhost:{PORT}/ask-remote-id"
DATA = "MAGIC"
EVENT_TOPIC = "event/has-happened"
REMOTE_ID_ANSWER_TOPIC = "client/my-remote-id"
def setup_server_rest_routes(app, endpoint: PubSubEndpoint, remote_id_event: asyncio.Event):
@app.get("/trigger")
async def trigger_events():
logger.info("Triggered via HTTP route - publishing event")
# Publish an event named 'steel'
# Since we are calling back (RPC) to the client- this would deadlock if we wait on it
asyncio.create_task(endpoint.publish([EVENT_TOPIC], data=DATA))
return "triggered"
@app.get("/ask-remote-id")
async def trigger_events():
logger.info("Got asked if i have the remote id")
answer = "yes" if remote_id_event.is_set() else "no"
asyncio.create_task(endpoint.publish([REMOTE_ID_ANSWER_TOPIC], {"answer": answer}))
return {"answer": answer}
def setup_server():
app = FastAPI()
remote_id_ok = asyncio.Event()
async def try_to_get_remote_id(channel: RpcChannel):
logger.info(f"trying to get remote channel id")
channel_other_channel_id = await channel.get_other_channel_id()
logger.info(f"finished getting remote channel id")
if channel_other_channel_id is not None:
remote_id_ok.set()
logger.info(f"remote channel id: {channel_other_channel_id}")
logger.info(f"local channel id: {channel_other_channel_id}")
async def on_connect(channel: RpcChannel):
logger.info(f"Connected to remote channel")
asyncio.create_task(try_to_get_remote_id(channel))
# PubSub websocket endpoint - setting up the server with remote id
endpoint = PubSubEndpoint(rpc_channel_get_remote_id=True, on_connect=[on_connect])
endpoint.register_route(app, "/pubsub")
# Regular REST endpoint - that publishes to PubSub
setup_server_rest_routes(app, endpoint, remote_id_ok)
uvicorn.run(app, port=PORT)
@pytest.fixture()
def server():
# Run the server as a separate process
proc = Process(target=setup_server, args=(), daemon=True)
proc.start()
yield proc
proc.kill() # Cleanup after test
@pytest.mark.asyncio
async def test_subscribe_http_trigger_with_remote_id_on(server):
"""
same as the basic_test::test_subscribe_http_trigger, but this time makes sure that
the rpc_channel_get_remote_id doesn't break anything.
"""
# finish trigger
finish = asyncio.Event()
# Create a client and subscribe to topics
async with PubSubClient() as client:
async def on_event(data, topic):
assert data == DATA
finish.set()
# subscribe for the event
client.subscribe(EVENT_TOPIC, on_event)
# start listentining
client.start_client(uri)
# wait for the client to be ready to receive events
await client.wait_until_ready()
# trigger the server via an HTTP route
requests.get(trigger_url)
# wait for finish trigger
await asyncio.wait_for(finish.wait(),5)
@pytest.mark.asyncio
async def test_pub_sub_with_remote_id_on(server):
"""
same as the basic_test::test_pubsub, but this time makes sure that
the rpc_channel_get_remote_id doesn't break anything.
"""
# finish trigger
finish = asyncio.Event()
# Create a client and subscribe to topics
async with PubSubClient() as client:
async def on_event(data, topic):
assert data == DATA
finish.set()
# subscribe for the event
client.subscribe(EVENT_TOPIC, on_event)
# start listentining
client.start_client(uri)
# wait for the client to be ready to receive events
await client.wait_until_ready()
# publish events (with sync=False toa void deadlocks waiting on the publish to ourselves)
published = await client.publish([EVENT_TOPIC], data=DATA, sync=False, notifier_id=gen_uid())
assert published.result == True
# wait for finish trigger
await asyncio.wait_for(finish.wait(),5)
@pytest.mark.asyncio
async def test_pub_sub_with_all_topics_with_remote_id_on(server):
"""
same as the basic_test::test_pub_sub_with_all_topics, but this time makes sure that
the rpc_channel_get_remote_id doesn't break anything.
"""
# finish trigger
finish = asyncio.Event()
# Create a client and subscribe to topics
async with PubSubClient() as client:
async def on_event(data, topic):
assert data == DATA
finish.set()
# subscribe for the event
client.subscribe(ALL_TOPICS, on_event)
# start listentining
client.start_client(uri)
# wait for the client to be ready to receive events
await client.wait_until_ready()
# publish events (with sync=False toa void deadlocks waiting on the publish to ourselves)
published = await client.publish([EVENT_TOPIC], data=DATA, sync=False, notifier_id=gen_uid())
assert published.result == True
# wait for finish trigger
await asyncio.wait_for(finish.wait(),5)
@pytest.mark.asyncio
async def test_getting_remote_id(server):
"""
tests that the server managed to get the client's channel id successfully.
"""
# finish trigger
finish = asyncio.Event()
remote_id_yes = asyncio.Event()
# Create a client and subscribe to topics
async with PubSubClient() as client:
async def on_event(data, topic):
assert data == DATA
finish.set()
async def on_answer(data, topic):
assert data.get("answer", None) == "yes"
remote_id_yes.set()
# subscribe for the event
client.subscribe(EVENT_TOPIC, on_event)
client.subscribe(REMOTE_ID_ANSWER_TOPIC, on_answer)
# start listentining
client.start_client(uri)
# wait for the client to be ready to receive events
await client.wait_until_ready()
# trigger the server via an HTTP route
requests.get(trigger_url)
# wait for finish trigger
await asyncio.wait_for(finish.wait(),5)
# sleep so that the server can finish getting the remote id
await asyncio.sleep(1)
# ask the server if he got the remote id
# will trigger the REMOTE_ID_ANSWER_TOPIC topic and the on_answer() callback
requests.get(ask_remote_id_url)
await asyncio.wait_for(remote_id_yes.wait(),5)
# the client can also try to get it's remote id
# super ugly but it's working:
my_remote_id = await client._rpc_channel._get_other_channel_id()
assert my_remote_id is not None | tests/server_with_remote_id_test.py | import os
import sys
from fastapi_websocket_rpc import logger
from fastapi_websocket_rpc.rpc_channel import RpcChannel
# Add parent path to use local src as package for tests
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
import asyncio
from multiprocessing import Process
import requests
import pytest
import uvicorn
from fastapi import APIRouter, FastAPI
from fastapi_websocket_rpc.logger import get_logger
from fastapi_websocket_rpc.utils import gen_uid
from fastapi_websocket_pubsub import PubSubEndpoint, PubSubClient, Subscription
from fastapi_websocket_pubsub.event_notifier import ALL_TOPICS
logger = get_logger("Test")
# Configurable
PORT = int(os.environ.get("PORT") or "7990")
uri = f"ws://localhost:{PORT}/pubsub"
trigger_url = f"http://localhost:{PORT}/trigger"
ask_remote_id_url = f"http://localhost:{PORT}/ask-remote-id"
DATA = "MAGIC"
EVENT_TOPIC = "event/has-happened"
REMOTE_ID_ANSWER_TOPIC = "client/my-remote-id"
def setup_server_rest_routes(app, endpoint: PubSubEndpoint, remote_id_event: asyncio.Event):
@app.get("/trigger")
async def trigger_events():
logger.info("Triggered via HTTP route - publishing event")
# Publish an event named 'steel'
# Since we are calling back (RPC) to the client- this would deadlock if we wait on it
asyncio.create_task(endpoint.publish([EVENT_TOPIC], data=DATA))
return "triggered"
@app.get("/ask-remote-id")
async def trigger_events():
logger.info("Got asked if i have the remote id")
answer = "yes" if remote_id_event.is_set() else "no"
asyncio.create_task(endpoint.publish([REMOTE_ID_ANSWER_TOPIC], {"answer": answer}))
return {"answer": answer}
def setup_server():
app = FastAPI()
remote_id_ok = asyncio.Event()
async def try_to_get_remote_id(channel: RpcChannel):
logger.info(f"trying to get remote channel id")
channel_other_channel_id = await channel.get_other_channel_id()
logger.info(f"finished getting remote channel id")
if channel_other_channel_id is not None:
remote_id_ok.set()
logger.info(f"remote channel id: {channel_other_channel_id}")
logger.info(f"local channel id: {channel_other_channel_id}")
async def on_connect(channel: RpcChannel):
logger.info(f"Connected to remote channel")
asyncio.create_task(try_to_get_remote_id(channel))
# PubSub websocket endpoint - setting up the server with remote id
endpoint = PubSubEndpoint(rpc_channel_get_remote_id=True, on_connect=[on_connect])
endpoint.register_route(app, "/pubsub")
# Regular REST endpoint - that publishes to PubSub
setup_server_rest_routes(app, endpoint, remote_id_ok)
uvicorn.run(app, port=PORT)
@pytest.fixture()
def server():
# Run the server as a separate process
proc = Process(target=setup_server, args=(), daemon=True)
proc.start()
yield proc
proc.kill() # Cleanup after test
@pytest.mark.asyncio
async def test_subscribe_http_trigger_with_remote_id_on(server):
"""
same as the basic_test::test_subscribe_http_trigger, but this time makes sure that
the rpc_channel_get_remote_id doesn't break anything.
"""
# finish trigger
finish = asyncio.Event()
# Create a client and subscribe to topics
async with PubSubClient() as client:
async def on_event(data, topic):
assert data == DATA
finish.set()
# subscribe for the event
client.subscribe(EVENT_TOPIC, on_event)
# start listentining
client.start_client(uri)
# wait for the client to be ready to receive events
await client.wait_until_ready()
# trigger the server via an HTTP route
requests.get(trigger_url)
# wait for finish trigger
await asyncio.wait_for(finish.wait(),5)
@pytest.mark.asyncio
async def test_pub_sub_with_remote_id_on(server):
"""
same as the basic_test::test_pubsub, but this time makes sure that
the rpc_channel_get_remote_id doesn't break anything.
"""
# finish trigger
finish = asyncio.Event()
# Create a client and subscribe to topics
async with PubSubClient() as client:
async def on_event(data, topic):
assert data == DATA
finish.set()
# subscribe for the event
client.subscribe(EVENT_TOPIC, on_event)
# start listentining
client.start_client(uri)
# wait for the client to be ready to receive events
await client.wait_until_ready()
# publish events (with sync=False toa void deadlocks waiting on the publish to ourselves)
published = await client.publish([EVENT_TOPIC], data=DATA, sync=False, notifier_id=gen_uid())
assert published.result == True
# wait for finish trigger
await asyncio.wait_for(finish.wait(),5)
@pytest.mark.asyncio
async def test_pub_sub_with_all_topics_with_remote_id_on(server):
"""
same as the basic_test::test_pub_sub_with_all_topics, but this time makes sure that
the rpc_channel_get_remote_id doesn't break anything.
"""
# finish trigger
finish = asyncio.Event()
# Create a client and subscribe to topics
async with PubSubClient() as client:
async def on_event(data, topic):
assert data == DATA
finish.set()
# subscribe for the event
client.subscribe(ALL_TOPICS, on_event)
# start listentining
client.start_client(uri)
# wait for the client to be ready to receive events
await client.wait_until_ready()
# publish events (with sync=False toa void deadlocks waiting on the publish to ourselves)
published = await client.publish([EVENT_TOPIC], data=DATA, sync=False, notifier_id=gen_uid())
assert published.result == True
# wait for finish trigger
await asyncio.wait_for(finish.wait(),5)
@pytest.mark.asyncio
async def test_getting_remote_id(server):
"""
tests that the server managed to get the client's channel id successfully.
"""
# finish trigger
finish = asyncio.Event()
remote_id_yes = asyncio.Event()
# Create a client and subscribe to topics
async with PubSubClient() as client:
async def on_event(data, topic):
assert data == DATA
finish.set()
async def on_answer(data, topic):
assert data.get("answer", None) == "yes"
remote_id_yes.set()
# subscribe for the event
client.subscribe(EVENT_TOPIC, on_event)
client.subscribe(REMOTE_ID_ANSWER_TOPIC, on_answer)
# start listentining
client.start_client(uri)
# wait for the client to be ready to receive events
await client.wait_until_ready()
# trigger the server via an HTTP route
requests.get(trigger_url)
# wait for finish trigger
await asyncio.wait_for(finish.wait(),5)
# sleep so that the server can finish getting the remote id
await asyncio.sleep(1)
# ask the server if he got the remote id
# will trigger the REMOTE_ID_ANSWER_TOPIC topic and the on_answer() callback
requests.get(ask_remote_id_url)
await asyncio.wait_for(remote_id_yes.wait(),5)
# the client can also try to get it's remote id
# super ugly but it's working:
my_remote_id = await client._rpc_channel._get_other_channel_id()
assert my_remote_id is not None | 0.353428 | 0.094929 |
import colors
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA
from ssh_transport import SSHTransportConnection
from utils import parse_byte, generate_byte, \
parse_uint32, generate_uint32, \
parse_string, generate_string, \
generate_mpint, parse_name_list
SSH_MSG_NUMS = {
'SSH_MSG_SERVICE_REQUEST': 5,
'SSH_MSG_SERVICE_ACCEPT': 6,
'SSH_MSG_USERAUTH_REQUEST': 50,
'SSH_MSG_USERAUTH_FAILURE': 51,
'SSH_MSG_USERAUTH_SUCCESS': 52,
'SSH_MSG_GLOBAL_REQUEST': 80,
'SSH_MSG_REQUEST_FAILURE': 82,
'SSH_MSG_CHANNEL_OPEN': 90,
'SSH_MSG_CHANNEL_OPEN_CONFIRMATION': 91,
'SSH_MSG_CHANNEL_WINDOW_ADJUST': 93,
'SSH_MSG_CHANNEL_DATA': 94,
'SSH_MSG_CHANNEL_CLOSE': 97,
'SSH_MSG_CHANNEL_REQUEST': 98,
'SSH_MSG_CHANNEL_SUCCESS': 99,
}
SSH_USERAUTH_STRING = 'ssh-userauth'
class SSHConnection(object):
'''An SSH connection - allows communication with a remote server over SSH.
Args:
hostname (string): The hostname of the server to communicate with.
username (string): The username to be used for authentication.
keyfile (string): The filename of the private key that will be used for authentication.
Attributes:
hostname (string): The hostname of the server to communicate with.
username (string): The username of the server to communicate with.
keyfile (string): The filename of the private key that will be used for authentication.
'''
def __init__(self, hostname, username, keyfile):
self.username = username
self.keyfile = keyfile
self._ssh_transport_connection = SSHTransportConnection(hostname)
# ssh-connection variables
self._local_channel_number = 0
self._remote_channel_number = None
def connect(self):
'''Open an authenticated connection to the remote server.'''
self._ssh_transport_connection.connect()
self._do_user_auth()
self._create_ssh_connection()
def disconnect(self):
'''Cleanly close the connection to the remote server.'''
# Send our exit status
msg = []
msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_CHANNEL_REQUEST']))
msg.append(generate_uint32(self._remote_channel_number))
msg.append(generate_string('exit-status'))
msg.append(generate_byte(0)) # False
msg.append(generate_uint32(0)) # Exit status = 0
self._ssh_transport_connection.send(''.join(msg))
# Then close the channel
msg = []
msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_CHANNEL_CLOSE']))
msg.append(generate_uint32(self._remote_channel_number))
self._ssh_transport_connection.send(''.join(msg))
# Read back the remote side's exit status
data = self._ssh_transport_connection.read()
index, msg_type = parse_byte(data, 0)
index, recipient_channel = parse_uint32(data, index)
index, request_type = parse_string(data, index)
index, want_reply_byte = parse_byte(data, index)
want_reply = want_reply_byte != 0
index, exit_status = parse_uint32(data, index)
assert msg_type == SSH_MSG_NUMS['SSH_MSG_CHANNEL_REQUEST']
assert recipient_channel == self._local_channel_number
assert request_type == 'exit-status'
assert not want_reply
# Disconnect at the transport layer
self._ssh_transport_connection.disconnect()
return exit_status
def read(self):
'''Read data from the remote server.
This data will be encrypted, and its authenticity guaranteed (both client-to-server and
server-to-client).
Returns (string): the data sent by the remote server.
'''
data = self._ssh_transport_connection.read()
index, msg_type = parse_byte(data, 0)
index, recipient_channel = parse_uint32(data, index)
index, channel_data = parse_string(data, index)
assert msg_type == SSH_MSG_NUMS['SSH_MSG_CHANNEL_DATA']
assert recipient_channel == self._local_channel_number
return channel_data
def send(self, payload):
'''Send data to the remote server.
This data will be encrypted, and its authenticity guaranteed (both client-to-server and
server-to-client).
Args:
payload (string): the data to be sent to the remote server.
'''
msg = []
msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_CHANNEL_DATA']))
msg.append(generate_uint32(self._remote_channel_number))
msg.append(generate_string(payload))
self._ssh_transport_connection.send(''.join(msg))
def _do_user_auth(self):
# Ask the server whether it supports doing SSH user auth
msg = []
msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_SERVICE_REQUEST']))
msg.append(generate_string(SSH_USERAUTH_STRING))
self._ssh_transport_connection.send(''.join(msg))
# Check that it says yes
data = self._ssh_transport_connection.read()
index, msg_type = parse_byte(data, 0)
assert msg_type == SSH_MSG_NUMS['SSH_MSG_SERVICE_ACCEPT'], \
'Unknown message type received: %d' % msg_type
index, service_name = parse_string(data, index)
assert service_name == SSH_USERAUTH_STRING
print colors.cyan("Let's do ssh-userauth!")
# Ask the server which authentication methods it supports
msg = []
msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_USERAUTH_REQUEST']))
msg.append(generate_string(self.username.encode('utf-8')))
msg.append(generate_string('ssh-connection'))
msg.append(generate_string('none'))
self._ssh_transport_connection.send(''.join(msg))
# Check that publickey is one of them
data = self._ssh_transport_connection.read()
index, msg_type = parse_byte(data, 0)
index, supported_auth_methods = parse_name_list(data, index)
index, partial_success_byte = parse_byte(data, index)
partial_success = partial_success_byte != 0
assert msg_type == SSH_MSG_NUMS['SSH_MSG_USERAUTH_FAILURE'], \
'Unknown message type: %d' % msg_type
assert 'publickey' in supported_auth_methods, \
'Server does not support public key authentication'
assert not partial_success
# Try to public key auth
rsa_key = RSA.importKey(open(self.keyfile))
pkcs_key = PKCS1_v1_5.new(rsa_key)
msg = []
msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_USERAUTH_REQUEST']))
msg.append(generate_string(self.username.encode('utf-8')))
msg.append(generate_string('ssh-connection'))
msg.append(generate_string('publickey'))
msg.append(generate_byte(1)) # True: we really do want to authenticate
msg.append(generate_string('ssh-rsa'))
msg.append(generate_string(
generate_string('ssh-rsa') + generate_mpint(rsa_key.e) + generate_mpint(rsa_key.n)
))
# Desperately try to figure out how signing works in this silly encapsulating protocol
signed_data = generate_string(self._ssh_transport_connection.session_id) + ''.join(msg)
# OMG Pycrypto, did it have to be *your* SHA1 implementation?
signature = pkcs_key.sign(SHA.new(signed_data))
msg.append(generate_string(generate_string('ssh-rsa') + generate_string(signature)))
# Send the public key auth message to the server
self._ssh_transport_connection.send(''.join(msg))
data = self._ssh_transport_connection.read()
index, msg_type = parse_byte(data, 0)
assert msg_type == SSH_MSG_NUMS['SSH_MSG_USERAUTH_SUCCESS'], \
'Unknown message type: %d' % msg_type
print colors.cyan('Successfully user authed!')
def _create_ssh_connection(self):
# Read the global request that SSH sends us - this is trying to let us know all host keys, but
# it's OpenSSH-specific, and we don't need it
data = self._ssh_transport_connection.read()
index, msg_type = parse_byte(data, 0)
index, request_name = parse_string(data, index)
index, want_reply_byte = parse_byte(data, index)
want_reply = want_reply_byte != 0
assert msg_type == SSH_MSG_NUMS['SSH_MSG_GLOBAL_REQUEST']
assert request_name == '<EMAIL>'
assert not want_reply
# Reply to let OpenSSH know that we don't know what they're talking about
msg = []
msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_REQUEST_FAILURE']))
self._ssh_transport_connection.send(''.join(msg))
# Actually get started with opening a channel for SSH communication
window_size = 1048576
maximum_packet_size = 16384
# Request to open a session channel
msg = []
msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_CHANNEL_OPEN']))
msg.append(generate_string('session'))
msg.append(generate_uint32(self._local_channel_number))
msg.append(generate_uint32(window_size))
msg.append(generate_uint32(maximum_packet_size))
self._ssh_transport_connection.send(''.join(msg))
# Check that a channel was opened successfully
data = self._ssh_transport_connection.read()
index, msg_type = parse_byte(data, 0)
index, recipient_channel = parse_uint32(data, index)
index, self._remote_channel_number = parse_uint32(data, index)
index, initial_window_size = parse_uint32(data, index)
index, maximum_packet_size = parse_uint32(data, index)
print colors.cyan('Message type: %d' % msg_type)
assert msg_type == SSH_MSG_NUMS['SSH_MSG_CHANNEL_OPEN_CONFIRMATION']
assert recipient_channel == self._local_channel_number
print colors.cyan('Remote channel number: %d' % self._remote_channel_number)
print colors.cyan('Initial window size: %d' % initial_window_size)
print colors.cyan('Maximum window size: %d' % maximum_packet_size)
# Ask to turn that session channel into a shell
msg = []
msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_CHANNEL_REQUEST']))
msg.append(generate_uint32(self._remote_channel_number))
msg.append(generate_string('shell'))
msg.append(generate_byte(1)) # True, we do want a reply here
self._ssh_transport_connection.send(''.join(msg))
# OpenSSH then asks to increase their window size, that's fine, do it
data = self._ssh_transport_connection.read()
index, msg_type = parse_byte(data, 0)
index, recipient_channel = parse_uint32(data, index)
index, bytes_to_add = parse_uint32(data, index)
assert msg_type == SSH_MSG_NUMS['SSH_MSG_CHANNEL_WINDOW_ADJUST']
initial_window_size += bytes_to_add
# Check that they tell us they've opened a channel successfully
data = self._ssh_transport_connection.read()
index, msg_type = parse_byte(data, 0)
assert msg_type == SSH_MSG_NUMS['SSH_MSG_CHANNEL_SUCCESS']
assert recipient_channel == self._local_channel_number
print colors.cyan('Successfully opened shell!') | ssh_connection.py | import colors
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA
from ssh_transport import SSHTransportConnection
from utils import parse_byte, generate_byte, \
parse_uint32, generate_uint32, \
parse_string, generate_string, \
generate_mpint, parse_name_list
SSH_MSG_NUMS = {
'SSH_MSG_SERVICE_REQUEST': 5,
'SSH_MSG_SERVICE_ACCEPT': 6,
'SSH_MSG_USERAUTH_REQUEST': 50,
'SSH_MSG_USERAUTH_FAILURE': 51,
'SSH_MSG_USERAUTH_SUCCESS': 52,
'SSH_MSG_GLOBAL_REQUEST': 80,
'SSH_MSG_REQUEST_FAILURE': 82,
'SSH_MSG_CHANNEL_OPEN': 90,
'SSH_MSG_CHANNEL_OPEN_CONFIRMATION': 91,
'SSH_MSG_CHANNEL_WINDOW_ADJUST': 93,
'SSH_MSG_CHANNEL_DATA': 94,
'SSH_MSG_CHANNEL_CLOSE': 97,
'SSH_MSG_CHANNEL_REQUEST': 98,
'SSH_MSG_CHANNEL_SUCCESS': 99,
}
SSH_USERAUTH_STRING = 'ssh-userauth'
class SSHConnection(object):
'''An SSH connection - allows communication with a remote server over SSH.
Args:
hostname (string): The hostname of the server to communicate with.
username (string): The username to be used for authentication.
keyfile (string): The filename of the private key that will be used for authentication.
Attributes:
hostname (string): The hostname of the server to communicate with.
username (string): The username of the server to communicate with.
keyfile (string): The filename of the private key that will be used for authentication.
'''
def __init__(self, hostname, username, keyfile):
self.username = username
self.keyfile = keyfile
self._ssh_transport_connection = SSHTransportConnection(hostname)
# ssh-connection variables
self._local_channel_number = 0
self._remote_channel_number = None
def connect(self):
'''Open an authenticated connection to the remote server.'''
self._ssh_transport_connection.connect()
self._do_user_auth()
self._create_ssh_connection()
def disconnect(self):
'''Cleanly close the connection to the remote server.'''
# Send our exit status
msg = []
msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_CHANNEL_REQUEST']))
msg.append(generate_uint32(self._remote_channel_number))
msg.append(generate_string('exit-status'))
msg.append(generate_byte(0)) # False
msg.append(generate_uint32(0)) # Exit status = 0
self._ssh_transport_connection.send(''.join(msg))
# Then close the channel
msg = []
msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_CHANNEL_CLOSE']))
msg.append(generate_uint32(self._remote_channel_number))
self._ssh_transport_connection.send(''.join(msg))
# Read back the remote side's exit status
data = self._ssh_transport_connection.read()
index, msg_type = parse_byte(data, 0)
index, recipient_channel = parse_uint32(data, index)
index, request_type = parse_string(data, index)
index, want_reply_byte = parse_byte(data, index)
want_reply = want_reply_byte != 0
index, exit_status = parse_uint32(data, index)
assert msg_type == SSH_MSG_NUMS['SSH_MSG_CHANNEL_REQUEST']
assert recipient_channel == self._local_channel_number
assert request_type == 'exit-status'
assert not want_reply
# Disconnect at the transport layer
self._ssh_transport_connection.disconnect()
return exit_status
def read(self):
'''Read data from the remote server.
This data will be encrypted, and its authenticity guaranteed (both client-to-server and
server-to-client).
Returns (string): the data sent by the remote server.
'''
data = self._ssh_transport_connection.read()
index, msg_type = parse_byte(data, 0)
index, recipient_channel = parse_uint32(data, index)
index, channel_data = parse_string(data, index)
assert msg_type == SSH_MSG_NUMS['SSH_MSG_CHANNEL_DATA']
assert recipient_channel == self._local_channel_number
return channel_data
def send(self, payload):
'''Send data to the remote server.
This data will be encrypted, and its authenticity guaranteed (both client-to-server and
server-to-client).
Args:
payload (string): the data to be sent to the remote server.
'''
msg = []
msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_CHANNEL_DATA']))
msg.append(generate_uint32(self._remote_channel_number))
msg.append(generate_string(payload))
self._ssh_transport_connection.send(''.join(msg))
def _do_user_auth(self):
# Ask the server whether it supports doing SSH user auth
msg = []
msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_SERVICE_REQUEST']))
msg.append(generate_string(SSH_USERAUTH_STRING))
self._ssh_transport_connection.send(''.join(msg))
# Check that it says yes
data = self._ssh_transport_connection.read()
index, msg_type = parse_byte(data, 0)
assert msg_type == SSH_MSG_NUMS['SSH_MSG_SERVICE_ACCEPT'], \
'Unknown message type received: %d' % msg_type
index, service_name = parse_string(data, index)
assert service_name == SSH_USERAUTH_STRING
print colors.cyan("Let's do ssh-userauth!")
# Ask the server which authentication methods it supports
msg = []
msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_USERAUTH_REQUEST']))
msg.append(generate_string(self.username.encode('utf-8')))
msg.append(generate_string('ssh-connection'))
msg.append(generate_string('none'))
self._ssh_transport_connection.send(''.join(msg))
# Check that publickey is one of them
data = self._ssh_transport_connection.read()
index, msg_type = parse_byte(data, 0)
index, supported_auth_methods = parse_name_list(data, index)
index, partial_success_byte = parse_byte(data, index)
partial_success = partial_success_byte != 0
assert msg_type == SSH_MSG_NUMS['SSH_MSG_USERAUTH_FAILURE'], \
'Unknown message type: %d' % msg_type
assert 'publickey' in supported_auth_methods, \
'Server does not support public key authentication'
assert not partial_success
# Try to public key auth
rsa_key = RSA.importKey(open(self.keyfile))
pkcs_key = PKCS1_v1_5.new(rsa_key)
msg = []
msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_USERAUTH_REQUEST']))
msg.append(generate_string(self.username.encode('utf-8')))
msg.append(generate_string('ssh-connection'))
msg.append(generate_string('publickey'))
msg.append(generate_byte(1)) # True: we really do want to authenticate
msg.append(generate_string('ssh-rsa'))
msg.append(generate_string(
generate_string('ssh-rsa') + generate_mpint(rsa_key.e) + generate_mpint(rsa_key.n)
))
# Desperately try to figure out how signing works in this silly encapsulating protocol
signed_data = generate_string(self._ssh_transport_connection.session_id) + ''.join(msg)
# OMG Pycrypto, did it have to be *your* SHA1 implementation?
signature = pkcs_key.sign(SHA.new(signed_data))
msg.append(generate_string(generate_string('ssh-rsa') + generate_string(signature)))
# Send the public key auth message to the server
self._ssh_transport_connection.send(''.join(msg))
data = self._ssh_transport_connection.read()
index, msg_type = parse_byte(data, 0)
assert msg_type == SSH_MSG_NUMS['SSH_MSG_USERAUTH_SUCCESS'], \
'Unknown message type: %d' % msg_type
print colors.cyan('Successfully user authed!')
def _create_ssh_connection(self):
# Read the global request that SSH sends us - this is trying to let us know all host keys, but
# it's OpenSSH-specific, and we don't need it
data = self._ssh_transport_connection.read()
index, msg_type = parse_byte(data, 0)
index, request_name = parse_string(data, index)
index, want_reply_byte = parse_byte(data, index)
want_reply = want_reply_byte != 0
assert msg_type == SSH_MSG_NUMS['SSH_MSG_GLOBAL_REQUEST']
assert request_name == '<EMAIL>'
assert not want_reply
# Reply to let OpenSSH know that we don't know what they're talking about
msg = []
msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_REQUEST_FAILURE']))
self._ssh_transport_connection.send(''.join(msg))
# Actually get started with opening a channel for SSH communication
window_size = 1048576
maximum_packet_size = 16384
# Request to open a session channel
msg = []
msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_CHANNEL_OPEN']))
msg.append(generate_string('session'))
msg.append(generate_uint32(self._local_channel_number))
msg.append(generate_uint32(window_size))
msg.append(generate_uint32(maximum_packet_size))
self._ssh_transport_connection.send(''.join(msg))
# Check that a channel was opened successfully
data = self._ssh_transport_connection.read()
index, msg_type = parse_byte(data, 0)
index, recipient_channel = parse_uint32(data, index)
index, self._remote_channel_number = parse_uint32(data, index)
index, initial_window_size = parse_uint32(data, index)
index, maximum_packet_size = parse_uint32(data, index)
print colors.cyan('Message type: %d' % msg_type)
assert msg_type == SSH_MSG_NUMS['SSH_MSG_CHANNEL_OPEN_CONFIRMATION']
assert recipient_channel == self._local_channel_number
print colors.cyan('Remote channel number: %d' % self._remote_channel_number)
print colors.cyan('Initial window size: %d' % initial_window_size)
print colors.cyan('Maximum window size: %d' % maximum_packet_size)
# Ask to turn that session channel into a shell
msg = []
msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_CHANNEL_REQUEST']))
msg.append(generate_uint32(self._remote_channel_number))
msg.append(generate_string('shell'))
msg.append(generate_byte(1)) # True, we do want a reply here
self._ssh_transport_connection.send(''.join(msg))
# OpenSSH then asks to increase their window size, that's fine, do it
data = self._ssh_transport_connection.read()
index, msg_type = parse_byte(data, 0)
index, recipient_channel = parse_uint32(data, index)
index, bytes_to_add = parse_uint32(data, index)
assert msg_type == SSH_MSG_NUMS['SSH_MSG_CHANNEL_WINDOW_ADJUST']
initial_window_size += bytes_to_add
# Check that they tell us they've opened a channel successfully
data = self._ssh_transport_connection.read()
index, msg_type = parse_byte(data, 0)
assert msg_type == SSH_MSG_NUMS['SSH_MSG_CHANNEL_SUCCESS']
assert recipient_channel == self._local_channel_number
print colors.cyan('Successfully opened shell!') | 0.526586 | 0.164081 |
try:
import Tkinter as tk
import ttk
except ImportError:
import tkinter as tk
import tkinter.ttk as ttk
class Base_Form(object):
"""Base class of all forms"""
def __init__(self, widget_class, master, action, hidden_input, kw):
self.action = action
if hidden_input is None:
self.hidden_input = dict()
else:
if not isinstance(hidden_input, dict):
raise ValueError("'hidden_input' should be a dict")
self.hidden_input = hidden_input
kw["class"] = "Form"
widget_class.__init__(self, master, **kw)
class Base_SubmitButton(object):
"""Base class of submit buttons"""
def submit(self):
form_widget = self
while True:
form_widget = form_widget.master
if form_widget is None:
raise Exception("No form found")
else:
if form_widget.winfo_class() == "Form":
break
if form_widget.action is None: return
form_action = form_widget.action
form_data = {}
form_data.update(form_widget.hidden_input)
# Applying list for python 2/3 compatibility. dict_values is a view in Python 3.
list_of_widgets = list(form_widget.children.values())
while True:
try:
widget = list_of_widgets.pop()
except IndexError:
break
list_of_widgets.extend(list(widget.children.values()))
if not hasattr(widget,"fieldname"): continue
field_name = widget.fieldname
Tk_class = widget.winfo_class()
if Tk_class == "Entry" or Tk_class == "TEntry":
field_value = widget.get()
elif Tk_class == "Text":
field_value = widget.get("1.0",'end-1c')
elif Tk_class == "TCombobox":
field_value = widget.get()
elif Tk_class == "Listbox":
field_value = [widget.get(idx) for idx in widget.curselection()]
elif Tk_class == "Checkbutton" or Tk_class == "TCheckbutton":
variable_name = widget.cget("variable").string
field_value = widget.tk.globalgetvar(variable_name)
elif Tk_class == "Radiobutton" or Tk_class == "TRadiobutton":
field_value = widget.tk.globalgetvar(widget.cget("variable").string)
else:
continue
form_data[field_name] = field_value
form_action(form_data)
class Form_Frame(tk.Frame, Base_Form):
def __init__(self, master, action=None, hidden_input=None, **kw):
Base_Form.__init__(self, tk.Frame, master, action, hidden_input, kw)
class Form_TFrame(tk.Frame, Base_Form):
def __init__(self, master, action=None, hidden_input=None, **kw):
Base_Form.__init__(self, ttk.Frame, master, action, hidden_input, kw)
class Form_LabelFrame(tk.LabelFrame, Base_Form):
def __init__(self, master, action=None, hidden_input=None, **kw):
Base_Form.__init__(self, tk.LabelFrame, master, action, hidden_input, kw)
class Form_TLabelFrame(ttk.LabelFrame, Base_Form):
def __init__(self, master, action=None, hidden_input=None, **kw):
Base_Form.__init__(self, ttk.LabelFrame, master, action, hidden_input, kw)
Form = Form_Frame
class Submit_Button(tk.Button, Base_SubmitButton):
def __init__(self, parent, *args, **kw):
kw["command"] = self.submit
tk.Button.__init__(self, parent, *args, **kw)
class Submit_TButton(ttk.Button, Base_SubmitButton):
def __init__(self, parent, *args, **kw):
kw["command"] = self.submit
ttk.Button.__init__(self, parent, *args, **kw)
if __name__== "__main__":
try:
from Tkinter import Frame, Entry, Radiobutton, Checkbutton, Text, Listbox, Tk, Label, StringVar
import tkMessageBox as messagebox
from ttk import Combobox
from Tkconstants import *
except ImportError:
from tkinter import Frame, Entry, Radiobutton, Checkbutton, Text, Listbox, Tk, Label, messagebox, StringVar
from tkinter.ttk import Combobox
from tkinter.constants import *
import pprint
pp = pprint.PrettyPrinter(indent=4)
root= Tk()
Label(root, text="Fill form and click submit button to execute action (open a popup) with all the form data.").pack(anchor=W, padx=(2,0))
form = Form(root, action =lambda data: messagebox.showinfo("form data",pp.pformat(data)))
form.pack(expand=True, fill="both", ipadx=10, ipady=10)
# It's possible to provide hidden data
form.hidden_input["hidden_var1"] = "value1"
form.hidden_input["hidden_var2"] = "value2"
Label(form, text="Entry:").grid(row=0,column=0, sticky=E, pady=(8,0))
# The fieldname attribute is necessary to provide data to action
entry = Entry(form)
entry.fieldname = "entry"
entry.grid(row=1,column=1, sticky =E+W)
Label(form, text="Checkbuttons:").grid(row=2,column=0, sticky=E, pady=(8,0))
column = Frame(form)
column.grid(row=3,column=1, sticky =E+W)
checkbutton0 = Checkbutton(column, text="Option 0")
checkbutton0.fieldname = "checkbutton0"
checkbutton0.pack(side=LEFT)
checkbutton1 = Checkbutton(column, text="Option 1")
checkbutton1.fieldname = "checkbutton1"
checkbutton1.pack(side=LEFT)
checkbutton2 = Checkbutton(column, text="Option 2")
checkbutton2.fieldname = "checkbutton2"
checkbutton2.pack(side=LEFT)
Label(form, text="Radiobuttons:").grid(row=4,column=0, sticky=E, pady=(8,0))
column = Frame(form)
column.grid(row=5,column=1, sticky =E+W)
# All radiobuttons require a variable
variable = StringVar()
radiobutton0 = Radiobutton(column, variable = variable, value="value0", text="Selection 0")
radiobutton0.fieldname = "radiobutton"
radiobutton0.pack(side=LEFT)
radiobutton1 = Radiobutton(column, variable = variable, value="value1", text="Selection 1")
radiobutton0.fieldname = "radiobutton"
radiobutton1.pack(side=LEFT)
Label(form, text="Text area:").grid(row=6,column=0, sticky=E, pady=(8,0))
text = Text(form, height=5)
text.fieldname = "text"
text.grid(row=7,column=1, sticky =E+W)
Label(form, text="Listbox:").grid(row=8,column=0, sticky=E, pady=(8,0))
listbox = Listbox(form)
listbox.fieldname = "listbox"
listbox.grid(row=9,column=1, sticky=W)
for item in ["one", "two", "three", "four"]:
listbox.insert("end", item)
Label(form, text="Combobox:").grid(row=10,column=0, sticky=E, pady=(8,0))
combobox = Combobox(form, values = ('X', 'Y', 'Z'), width=5)
combobox.fieldname = "combobox"
combobox.grid(row=11,column=1, sticky=W)
Submit_Button(form, text="Submit").grid(row=12,column=1,sticky =E)
root.mainloop() | recipes/Python/580714_Form_actilike_html_forms/recipe-580714.py |
try:
import Tkinter as tk
import ttk
except ImportError:
import tkinter as tk
import tkinter.ttk as ttk
class Base_Form(object):
"""Base class of all forms"""
def __init__(self, widget_class, master, action, hidden_input, kw):
self.action = action
if hidden_input is None:
self.hidden_input = dict()
else:
if not isinstance(hidden_input, dict):
raise ValueError("'hidden_input' should be a dict")
self.hidden_input = hidden_input
kw["class"] = "Form"
widget_class.__init__(self, master, **kw)
class Base_SubmitButton(object):
"""Base class of submit buttons"""
def submit(self):
form_widget = self
while True:
form_widget = form_widget.master
if form_widget is None:
raise Exception("No form found")
else:
if form_widget.winfo_class() == "Form":
break
if form_widget.action is None: return
form_action = form_widget.action
form_data = {}
form_data.update(form_widget.hidden_input)
# Applying list for python 2/3 compatibility. dict_values is a view in Python 3.
list_of_widgets = list(form_widget.children.values())
while True:
try:
widget = list_of_widgets.pop()
except IndexError:
break
list_of_widgets.extend(list(widget.children.values()))
if not hasattr(widget,"fieldname"): continue
field_name = widget.fieldname
Tk_class = widget.winfo_class()
if Tk_class == "Entry" or Tk_class == "TEntry":
field_value = widget.get()
elif Tk_class == "Text":
field_value = widget.get("1.0",'end-1c')
elif Tk_class == "TCombobox":
field_value = widget.get()
elif Tk_class == "Listbox":
field_value = [widget.get(idx) for idx in widget.curselection()]
elif Tk_class == "Checkbutton" or Tk_class == "TCheckbutton":
variable_name = widget.cget("variable").string
field_value = widget.tk.globalgetvar(variable_name)
elif Tk_class == "Radiobutton" or Tk_class == "TRadiobutton":
field_value = widget.tk.globalgetvar(widget.cget("variable").string)
else:
continue
form_data[field_name] = field_value
form_action(form_data)
class Form_Frame(tk.Frame, Base_Form):
def __init__(self, master, action=None, hidden_input=None, **kw):
Base_Form.__init__(self, tk.Frame, master, action, hidden_input, kw)
class Form_TFrame(tk.Frame, Base_Form):
def __init__(self, master, action=None, hidden_input=None, **kw):
Base_Form.__init__(self, ttk.Frame, master, action, hidden_input, kw)
class Form_LabelFrame(tk.LabelFrame, Base_Form):
def __init__(self, master, action=None, hidden_input=None, **kw):
Base_Form.__init__(self, tk.LabelFrame, master, action, hidden_input, kw)
class Form_TLabelFrame(ttk.LabelFrame, Base_Form):
def __init__(self, master, action=None, hidden_input=None, **kw):
Base_Form.__init__(self, ttk.LabelFrame, master, action, hidden_input, kw)
Form = Form_Frame
class Submit_Button(tk.Button, Base_SubmitButton):
def __init__(self, parent, *args, **kw):
kw["command"] = self.submit
tk.Button.__init__(self, parent, *args, **kw)
class Submit_TButton(ttk.Button, Base_SubmitButton):
def __init__(self, parent, *args, **kw):
kw["command"] = self.submit
ttk.Button.__init__(self, parent, *args, **kw)
if __name__== "__main__":
try:
from Tkinter import Frame, Entry, Radiobutton, Checkbutton, Text, Listbox, Tk, Label, StringVar
import tkMessageBox as messagebox
from ttk import Combobox
from Tkconstants import *
except ImportError:
from tkinter import Frame, Entry, Radiobutton, Checkbutton, Text, Listbox, Tk, Label, messagebox, StringVar
from tkinter.ttk import Combobox
from tkinter.constants import *
import pprint
pp = pprint.PrettyPrinter(indent=4)
root= Tk()
Label(root, text="Fill form and click submit button to execute action (open a popup) with all the form data.").pack(anchor=W, padx=(2,0))
form = Form(root, action =lambda data: messagebox.showinfo("form data",pp.pformat(data)))
form.pack(expand=True, fill="both", ipadx=10, ipady=10)
# It's possible to provide hidden data
form.hidden_input["hidden_var1"] = "value1"
form.hidden_input["hidden_var2"] = "value2"
Label(form, text="Entry:").grid(row=0,column=0, sticky=E, pady=(8,0))
# The fieldname attribute is necessary to provide data to action
entry = Entry(form)
entry.fieldname = "entry"
entry.grid(row=1,column=1, sticky =E+W)
Label(form, text="Checkbuttons:").grid(row=2,column=0, sticky=E, pady=(8,0))
column = Frame(form)
column.grid(row=3,column=1, sticky =E+W)
checkbutton0 = Checkbutton(column, text="Option 0")
checkbutton0.fieldname = "checkbutton0"
checkbutton0.pack(side=LEFT)
checkbutton1 = Checkbutton(column, text="Option 1")
checkbutton1.fieldname = "checkbutton1"
checkbutton1.pack(side=LEFT)
checkbutton2 = Checkbutton(column, text="Option 2")
checkbutton2.fieldname = "checkbutton2"
checkbutton2.pack(side=LEFT)
Label(form, text="Radiobuttons:").grid(row=4,column=0, sticky=E, pady=(8,0))
column = Frame(form)
column.grid(row=5,column=1, sticky =E+W)
# All radiobuttons require a variable
variable = StringVar()
radiobutton0 = Radiobutton(column, variable = variable, value="value0", text="Selection 0")
radiobutton0.fieldname = "radiobutton"
radiobutton0.pack(side=LEFT)
radiobutton1 = Radiobutton(column, variable = variable, value="value1", text="Selection 1")
radiobutton0.fieldname = "radiobutton"
radiobutton1.pack(side=LEFT)
Label(form, text="Text area:").grid(row=6,column=0, sticky=E, pady=(8,0))
text = Text(form, height=5)
text.fieldname = "text"
text.grid(row=7,column=1, sticky =E+W)
Label(form, text="Listbox:").grid(row=8,column=0, sticky=E, pady=(8,0))
listbox = Listbox(form)
listbox.fieldname = "listbox"
listbox.grid(row=9,column=1, sticky=W)
for item in ["one", "two", "three", "four"]:
listbox.insert("end", item)
Label(form, text="Combobox:").grid(row=10,column=0, sticky=E, pady=(8,0))
combobox = Combobox(form, values = ('X', 'Y', 'Z'), width=5)
combobox.fieldname = "combobox"
combobox.grid(row=11,column=1, sticky=W)
Submit_Button(form, text="Submit").grid(row=12,column=1,sticky =E)
root.mainloop() | 0.430746 | 0.115511 |
import asyncio
import os
import pytest
from async_negotiate_sspi import NegotiateAuth, NegotiateAuthWS
from dotenv import load_dotenv
from piwebasync import Controller, HTTPClient, WebsocketClient, WebsocketMessage
from piwebasync.exceptions import ChannelClosedError, ChannelClosedOK, ChannelUpdateError, ChannelRollback
"""
Fucntional tests for WebsocketClient. These tests can be run from pytest
Requirements to Run
- pytest and pytest.asyncio
- Active and accessible PI Web API server
- .env file in the root of the \\tests folder that references
the appropriate variables below
- Correct authentication flow for your servers authentication
"""
load_dotenv()
HTTP_SCHEME = os.getenv("HTTP_SCHEME")
WS_SCHEME = os.getenv("WS_SCHEME")
PI_HOST = os.getenv("PI_HOST")
ROOT = os.getenv("ROOT")
DATASERVER = os.getenv("DATASERVER")
PI_POINT = os.getenv("PI_POINT")
UPDATE_PI_POINT = os.getenv("UPDATE_PI_POINT")
# Use for kerberos or NTLM
http_auth = NegotiateAuth()
ws_auth = NegotiateAuthWS()
async def get_tag_webid(point: str):
"""Get WebId for test PI tag"""
tag_path = f"\\\\{DATASERVER}\\{point}"
request = Controller(
scheme=HTTP_SCHEME,
host=PI_HOST,
root=ROOT
).points.get_by_path(tag_path)
# Make request, select webid
async with HTTPClient(auth=http_auth, safe_chars="/?:=&%;\\", verify=False) as client:
response = await client.request(request)
selection = response.select("WebId")
return selection["WebId"][0]
async def receiver(channel: WebsocketClient):
"""Receive messages from channel in asyncio.Task"""
responses = []
try:
async for response in channel:
responses.append(response)
except ChannelClosedError:
raise
except ChannelClosedOK:
return responses
@pytest.mark.asyncio
async def test_channel_operation():
"""Test core function of Channel class"""
webid = await get_tag_webid(PI_POINT)
request = Controller(
scheme=WS_SCHEME,
host=PI_HOST,
root=ROOT
).streams.get_channel(webid, include_initial_values=True)
async with WebsocketClient(request, auth=ws_auth) as channel:
response = await channel.recv()
assert isinstance(response, WebsocketMessage)
assert channel.is_closed
@pytest.mark.asyncio
async def test_channel_iteration():
"""Test channel can be used in an async iterator"""
webid = await get_tag_webid(PI_POINT)
request = Controller(
scheme=WS_SCHEME,
host=PI_HOST,
root=ROOT
).streams.get_channel(webid, include_initial_values=True, heartbeat_rate=2)
responses = []
async with WebsocketClient(request, auth=ws_auth) as channel:
async for response in channel:
responses.append(response)
if len(responses) >= 2:
break
assert channel.is_closed
assert len(responses) >= 2
for response in responses:
assert isinstance(response, WebsocketMessage)
@pytest.mark.asyncio
async def test_channel_update_success():
"""
Test channel can be updated without receiver failing
Note: Pytest raises warnings in this test originating from
the websockets.WebsocketCommonProtocol. The test works as
expected and when run manually without pytest, no warnings are
raised. This might have to do with the way pytest handles
the event loop.
"""
loop = asyncio.get_event_loop()
webid_1 = await get_tag_webid(PI_POINT)
controller = Controller(scheme=WS_SCHEME, host=PI_HOST, root=ROOT)
request_1 = controller.streams.get_channel(webid_1, include_initial_values=True, heartbeat_rate=2)
webid_2 = await get_tag_webid(UPDATE_PI_POINT)
request_2 = controller.streams.get_channel(webid_2, include_initial_values=True, heartbeat_rate=2)
async with WebsocketClient(request_1, auth=ws_auth, loop=loop) as channel:
receive_task = loop.create_task(receiver(channel))
await asyncio.sleep(4)
await channel.update(request_2)
assert not receive_task.done()
await asyncio.sleep(4)
assert channel.is_closed
# ChannelClosedOK should be raised so receiver returns responses
responses: list = await receive_task
merged = responses.pop(0)
for response in responses:
merged.items.extend(response.items)
selection = merged.select("Items.WebId")
assert webid_1 in selection["Items.WebId"]
assert webid_2 in selection["Items.WebId"]
@pytest.mark.asyncio
async def test_channel_update_failure():
"""
Test failed update raises ChannelUpdateError and receiver task raises
ChannelClosedError
"""
loop = asyncio.get_event_loop()
webid = await get_tag_webid(PI_POINT)
request_1 = Controller(
scheme=WS_SCHEME,
host=PI_HOST,
root=ROOT
).streams.get_channel(webid, include_initial_values=True, heartbeat_rate=2)
request_2 = Controller(
scheme=WS_SCHEME,
host="mybadhost.com",
root=ROOT
).streams.get_channel(webid, include_initial_values=True, heartbeat_rate=2)
async with WebsocketClient(request_1, auth=ws_auth, loop=loop) as channel:
receive_task = loop.create_task(receiver(channel))
await asyncio.sleep(1)
try:
with pytest.raises(ChannelUpdateError):
await channel.update(request_2)
except ChannelUpdateError:
pass
try:
with pytest.raises(ChannelClosedError):
await receive_task
except ChannelClosedError:
pass
assert channel.is_closed
@pytest.mark.asyncio
async def test_channel_rollback():
"""
Test failed failed update with rollback enabled raises ChannelRollback
and channel continues to process messages at old endpoint
"""
loop = asyncio.get_event_loop()
webid = await get_tag_webid(PI_POINT)
request_1 = Controller(
scheme=WS_SCHEME,
host=PI_HOST,
root=ROOT
).streams.get_channel(webid, include_initial_values=True, heartbeat_rate=2)
request_2 = Controller(
scheme=WS_SCHEME,
host="mybadhost.com",
root=ROOT
).streams.get_channel(webid, include_initial_values=True, heartbeat_rate=2)
async with WebsocketClient(request_1, auth=ws_auth, loop=loop) as channel:
receive_task = loop.create_task(receiver(channel))
await asyncio.sleep(1)
with pytest.raises(ChannelRollback):
await channel.update(request_2, rollback=True)
await asyncio.sleep(1)
assert not receive_task.done()
assert not channel.is_closed
assert channel.is_open | tests/websockets/test_client.py | import asyncio
import os
import pytest
from async_negotiate_sspi import NegotiateAuth, NegotiateAuthWS
from dotenv import load_dotenv
from piwebasync import Controller, HTTPClient, WebsocketClient, WebsocketMessage
from piwebasync.exceptions import ChannelClosedError, ChannelClosedOK, ChannelUpdateError, ChannelRollback
"""
Fucntional tests for WebsocketClient. These tests can be run from pytest
Requirements to Run
- pytest and pytest.asyncio
- Active and accessible PI Web API server
- .env file in the root of the \\tests folder that references
the appropriate variables below
- Correct authentication flow for your servers authentication
"""
load_dotenv()
HTTP_SCHEME = os.getenv("HTTP_SCHEME")
WS_SCHEME = os.getenv("WS_SCHEME")
PI_HOST = os.getenv("PI_HOST")
ROOT = os.getenv("ROOT")
DATASERVER = os.getenv("DATASERVER")
PI_POINT = os.getenv("PI_POINT")
UPDATE_PI_POINT = os.getenv("UPDATE_PI_POINT")
# Use for kerberos or NTLM
http_auth = NegotiateAuth()
ws_auth = NegotiateAuthWS()
async def get_tag_webid(point: str):
"""Get WebId for test PI tag"""
tag_path = f"\\\\{DATASERVER}\\{point}"
request = Controller(
scheme=HTTP_SCHEME,
host=PI_HOST,
root=ROOT
).points.get_by_path(tag_path)
# Make request, select webid
async with HTTPClient(auth=http_auth, safe_chars="/?:=&%;\\", verify=False) as client:
response = await client.request(request)
selection = response.select("WebId")
return selection["WebId"][0]
async def receiver(channel: WebsocketClient):
"""Receive messages from channel in asyncio.Task"""
responses = []
try:
async for response in channel:
responses.append(response)
except ChannelClosedError:
raise
except ChannelClosedOK:
return responses
@pytest.mark.asyncio
async def test_channel_operation():
"""Test core function of Channel class"""
webid = await get_tag_webid(PI_POINT)
request = Controller(
scheme=WS_SCHEME,
host=PI_HOST,
root=ROOT
).streams.get_channel(webid, include_initial_values=True)
async with WebsocketClient(request, auth=ws_auth) as channel:
response = await channel.recv()
assert isinstance(response, WebsocketMessage)
assert channel.is_closed
@pytest.mark.asyncio
async def test_channel_iteration():
"""Test channel can be used in an async iterator"""
webid = await get_tag_webid(PI_POINT)
request = Controller(
scheme=WS_SCHEME,
host=PI_HOST,
root=ROOT
).streams.get_channel(webid, include_initial_values=True, heartbeat_rate=2)
responses = []
async with WebsocketClient(request, auth=ws_auth) as channel:
async for response in channel:
responses.append(response)
if len(responses) >= 2:
break
assert channel.is_closed
assert len(responses) >= 2
for response in responses:
assert isinstance(response, WebsocketMessage)
@pytest.mark.asyncio
async def test_channel_update_success():
"""
Test channel can be updated without receiver failing
Note: Pytest raises warnings in this test originating from
the websockets.WebsocketCommonProtocol. The test works as
expected and when run manually without pytest, no warnings are
raised. This might have to do with the way pytest handles
the event loop.
"""
loop = asyncio.get_event_loop()
webid_1 = await get_tag_webid(PI_POINT)
controller = Controller(scheme=WS_SCHEME, host=PI_HOST, root=ROOT)
request_1 = controller.streams.get_channel(webid_1, include_initial_values=True, heartbeat_rate=2)
webid_2 = await get_tag_webid(UPDATE_PI_POINT)
request_2 = controller.streams.get_channel(webid_2, include_initial_values=True, heartbeat_rate=2)
async with WebsocketClient(request_1, auth=ws_auth, loop=loop) as channel:
receive_task = loop.create_task(receiver(channel))
await asyncio.sleep(4)
await channel.update(request_2)
assert not receive_task.done()
await asyncio.sleep(4)
assert channel.is_closed
# ChannelClosedOK should be raised so receiver returns responses
responses: list = await receive_task
merged = responses.pop(0)
for response in responses:
merged.items.extend(response.items)
selection = merged.select("Items.WebId")
assert webid_1 in selection["Items.WebId"]
assert webid_2 in selection["Items.WebId"]
@pytest.mark.asyncio
async def test_channel_update_failure():
"""
Test failed update raises ChannelUpdateError and receiver task raises
ChannelClosedError
"""
loop = asyncio.get_event_loop()
webid = await get_tag_webid(PI_POINT)
request_1 = Controller(
scheme=WS_SCHEME,
host=PI_HOST,
root=ROOT
).streams.get_channel(webid, include_initial_values=True, heartbeat_rate=2)
request_2 = Controller(
scheme=WS_SCHEME,
host="mybadhost.com",
root=ROOT
).streams.get_channel(webid, include_initial_values=True, heartbeat_rate=2)
async with WebsocketClient(request_1, auth=ws_auth, loop=loop) as channel:
receive_task = loop.create_task(receiver(channel))
await asyncio.sleep(1)
try:
with pytest.raises(ChannelUpdateError):
await channel.update(request_2)
except ChannelUpdateError:
pass
try:
with pytest.raises(ChannelClosedError):
await receive_task
except ChannelClosedError:
pass
assert channel.is_closed
@pytest.mark.asyncio
async def test_channel_rollback():
"""
Test failed failed update with rollback enabled raises ChannelRollback
and channel continues to process messages at old endpoint
"""
loop = asyncio.get_event_loop()
webid = await get_tag_webid(PI_POINT)
request_1 = Controller(
scheme=WS_SCHEME,
host=PI_HOST,
root=ROOT
).streams.get_channel(webid, include_initial_values=True, heartbeat_rate=2)
request_2 = Controller(
scheme=WS_SCHEME,
host="mybadhost.com",
root=ROOT
).streams.get_channel(webid, include_initial_values=True, heartbeat_rate=2)
async with WebsocketClient(request_1, auth=ws_auth, loop=loop) as channel:
receive_task = loop.create_task(receiver(channel))
await asyncio.sleep(1)
with pytest.raises(ChannelRollback):
await channel.update(request_2, rollback=True)
await asyncio.sleep(1)
assert not receive_task.done()
assert not channel.is_closed
assert channel.is_open | 0.55254 | 0.225672 |
from __future__ import print_function, division
import onnx
import numpy as np
import pytest
from onnx.helper import make_tensor_value_info, make_graph, make_model
from tests.utils import run_model
def import_and_compute(op_type, input_data_left, input_data_right, opset=7, **node_attributes):
inputs = [np.array(input_data_left), np.array(input_data_right)]
onnx_node = onnx.helper.make_node(op_type, inputs=['x', 'y'], outputs=['z'], **node_attributes)
input_tensors = [make_tensor_value_info(name, onnx.TensorProto.FLOAT, value.shape)
for name, value in zip(onnx_node.input, inputs)]
output_tensors = [make_tensor_value_info(name, onnx.TensorProto.FLOAT, ())
for name in onnx_node.output]
graph = make_graph([onnx_node], 'compute_graph', input_tensors, output_tensors)
model = make_model(graph, producer_name='NgraphBackend')
model.opset_import[0].version = opset
return run_model(model, inputs)[0]
def test_add_opset4():
assert np.array_equal(import_and_compute('Add', 1, 2, opset=4),
np.array(3, dtype=np.float32))
assert np.array_equal(import_and_compute('Add', [1], [2], opset=4),
np.array([3], dtype=np.float32))
assert np.array_equal(import_and_compute('Add', [1, 2], [3, 4], opset=4),
np.array([4, 6], dtype=np.float32))
assert np.array_equal(import_and_compute('Add', [1, 2, 3], [4, 5, 6], opset=4),
np.array([5, 7, 9], dtype=np.float32))
assert np.array_equal(import_and_compute('Add', [[1, 2, 3], [4, 5, 6]], [7, 8, 9], broadcast=1, opset=4),
np.array([[8, 10, 12], [11, 13, 15]], dtype=np.float32))
# shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar
left_operand = np.ones((2, 3, 4, 5)).astype(np.float32)
assert np.array_equal(import_and_compute('Add', left_operand, 8, broadcast=1, opset=4),
left_operand + 8)
# shape(A) = (2, 3, 4, 5), shape(B) = (5,)
left_operand = np.ones((2, 3, 4, 5), dtype=np.float32)
right_operand = np.random.rand(5).astype(np.float32)
import_and_compute('Add', left_operand, right_operand, broadcast=1, opset=4)
# shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)
left_operand = np.ones((2, 3, 4, 5), dtype=np.float32)
right_operand = np.random.rand(4, 5).astype(np.float32)
assert np.array_equal(import_and_compute('Add', left_operand, right_operand, broadcast=1, opset=4),
left_operand + right_operand)
# shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1
left_operand = np.ones((2, 3, 4, 5), dtype=np.float32)
right_operand = np.random.rand(3, 4).astype(np.float32)
assert np.array_equal(
import_and_compute('Add', left_operand, right_operand, broadcast=1, axis=1, opset=4),
left_operand + right_operand.reshape(1, 3, 4, 1))
# shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0
left_operand = np.ones((2, 3, 4, 5), dtype=np.float32)
right_operand = np.random.rand(2).astype(np.float32)
assert np.array_equal(
import_and_compute('Add', left_operand, right_operand, broadcast=1, axis=0, opset=4),
left_operand + right_operand.reshape(2, 1, 1, 1))
@pytest.mark.parametrize('left_shape,right_shape', [
((1,), (1,)),
((256, 256, 3), (3,)),
((5, 4), (1,)),
((5, 4), (4,)),
((15, 3, 5), (3, 5)),
((15, 3, 5), (15, 1, 5)),
((15, 3, 5), (3, 1)),
((8, 1, 6, 1), (7, 1, 5)),
])
def test_add_opset7(left_shape, right_shape):
"""Test Add-7 operator, which uses numpy-style broadcasting."""
left_input = np.ones(left_shape)
right_input = np.ones(right_shape)
assert np.array_equal(import_and_compute('Add', left_input, right_input),
left_input + right_input)
def test_sub():
assert np.array_equal(import_and_compute('Sub', 20, 1),
np.array(19, dtype=np.float32))
assert np.array_equal(import_and_compute('Sub', [20], [1]),
np.array([19], dtype=np.float32))
assert np.array_equal(import_and_compute('Sub', [20, 19], [1, 2]),
np.array([19, 17], dtype=np.float32))
assert np.array_equal(import_and_compute('Sub', [[1, 2, 3], [4, 5, 6]], [7, 8, 9], broadcast=1),
np.array([[-6, -6, -6], [-3, -3, -3]], dtype=np.float32))
def test_mul():
assert np.array_equal(import_and_compute('Mul', 2, 3),
np.array(6, dtype=np.float32))
assert np.array_equal(import_and_compute('Mul', [2], [3]),
np.array([6], dtype=np.float32))
assert np.array_equal(import_and_compute('Mul', [2, 3], [4, 5]),
np.array([8, 15], dtype=np.float32))
assert np.array_equal(import_and_compute('Mul', [[1, 2, 3], [4, 5, 6]], [7, 8, 9], broadcast=1),
np.array([[7, 16, 27], [28, 40, 54]], dtype=np.float32))
def test_div():
assert np.array_equal(import_and_compute('Div', 6, 3),
np.array(2, dtype=np.float32))
assert np.array_equal(import_and_compute('Div', [6], [3]),
np.array([2], dtype=np.float32))
assert np.array_equal(import_and_compute('Div', [6, 8], [3, 2]),
np.array([2, 4], dtype=np.float32))
assert np.array_equal(import_and_compute('Div', [[10, 20, 30], [40, 50, 60]], [2, 5, 6], broadcast=1),
np.array([[5, 4, 5], [20, 10, 10]], dtype=np.float32)) | tests/test_ops_binary.py |
from __future__ import print_function, division
import onnx
import numpy as np
import pytest
from onnx.helper import make_tensor_value_info, make_graph, make_model
from tests.utils import run_model
def import_and_compute(op_type, input_data_left, input_data_right, opset=7, **node_attributes):
inputs = [np.array(input_data_left), np.array(input_data_right)]
onnx_node = onnx.helper.make_node(op_type, inputs=['x', 'y'], outputs=['z'], **node_attributes)
input_tensors = [make_tensor_value_info(name, onnx.TensorProto.FLOAT, value.shape)
for name, value in zip(onnx_node.input, inputs)]
output_tensors = [make_tensor_value_info(name, onnx.TensorProto.FLOAT, ())
for name in onnx_node.output]
graph = make_graph([onnx_node], 'compute_graph', input_tensors, output_tensors)
model = make_model(graph, producer_name='NgraphBackend')
model.opset_import[0].version = opset
return run_model(model, inputs)[0]
def test_add_opset4():
assert np.array_equal(import_and_compute('Add', 1, 2, opset=4),
np.array(3, dtype=np.float32))
assert np.array_equal(import_and_compute('Add', [1], [2], opset=4),
np.array([3], dtype=np.float32))
assert np.array_equal(import_and_compute('Add', [1, 2], [3, 4], opset=4),
np.array([4, 6], dtype=np.float32))
assert np.array_equal(import_and_compute('Add', [1, 2, 3], [4, 5, 6], opset=4),
np.array([5, 7, 9], dtype=np.float32))
assert np.array_equal(import_and_compute('Add', [[1, 2, 3], [4, 5, 6]], [7, 8, 9], broadcast=1, opset=4),
np.array([[8, 10, 12], [11, 13, 15]], dtype=np.float32))
# shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar
left_operand = np.ones((2, 3, 4, 5)).astype(np.float32)
assert np.array_equal(import_and_compute('Add', left_operand, 8, broadcast=1, opset=4),
left_operand + 8)
# shape(A) = (2, 3, 4, 5), shape(B) = (5,)
left_operand = np.ones((2, 3, 4, 5), dtype=np.float32)
right_operand = np.random.rand(5).astype(np.float32)
import_and_compute('Add', left_operand, right_operand, broadcast=1, opset=4)
# shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)
left_operand = np.ones((2, 3, 4, 5), dtype=np.float32)
right_operand = np.random.rand(4, 5).astype(np.float32)
assert np.array_equal(import_and_compute('Add', left_operand, right_operand, broadcast=1, opset=4),
left_operand + right_operand)
# shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1
left_operand = np.ones((2, 3, 4, 5), dtype=np.float32)
right_operand = np.random.rand(3, 4).astype(np.float32)
assert np.array_equal(
import_and_compute('Add', left_operand, right_operand, broadcast=1, axis=1, opset=4),
left_operand + right_operand.reshape(1, 3, 4, 1))
# shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0
left_operand = np.ones((2, 3, 4, 5), dtype=np.float32)
right_operand = np.random.rand(2).astype(np.float32)
assert np.array_equal(
import_and_compute('Add', left_operand, right_operand, broadcast=1, axis=0, opset=4),
left_operand + right_operand.reshape(2, 1, 1, 1))
@pytest.mark.parametrize('left_shape,right_shape', [
((1,), (1,)),
((256, 256, 3), (3,)),
((5, 4), (1,)),
((5, 4), (4,)),
((15, 3, 5), (3, 5)),
((15, 3, 5), (15, 1, 5)),
((15, 3, 5), (3, 1)),
((8, 1, 6, 1), (7, 1, 5)),
])
def test_add_opset7(left_shape, right_shape):
"""Test Add-7 operator, which uses numpy-style broadcasting."""
left_input = np.ones(left_shape)
right_input = np.ones(right_shape)
assert np.array_equal(import_and_compute('Add', left_input, right_input),
left_input + right_input)
def test_sub():
assert np.array_equal(import_and_compute('Sub', 20, 1),
np.array(19, dtype=np.float32))
assert np.array_equal(import_and_compute('Sub', [20], [1]),
np.array([19], dtype=np.float32))
assert np.array_equal(import_and_compute('Sub', [20, 19], [1, 2]),
np.array([19, 17], dtype=np.float32))
assert np.array_equal(import_and_compute('Sub', [[1, 2, 3], [4, 5, 6]], [7, 8, 9], broadcast=1),
np.array([[-6, -6, -6], [-3, -3, -3]], dtype=np.float32))
def test_mul():
assert np.array_equal(import_and_compute('Mul', 2, 3),
np.array(6, dtype=np.float32))
assert np.array_equal(import_and_compute('Mul', [2], [3]),
np.array([6], dtype=np.float32))
assert np.array_equal(import_and_compute('Mul', [2, 3], [4, 5]),
np.array([8, 15], dtype=np.float32))
assert np.array_equal(import_and_compute('Mul', [[1, 2, 3], [4, 5, 6]], [7, 8, 9], broadcast=1),
np.array([[7, 16, 27], [28, 40, 54]], dtype=np.float32))
def test_div():
assert np.array_equal(import_and_compute('Div', 6, 3),
np.array(2, dtype=np.float32))
assert np.array_equal(import_and_compute('Div', [6], [3]),
np.array([2], dtype=np.float32))
assert np.array_equal(import_and_compute('Div', [6, 8], [3, 2]),
np.array([2, 4], dtype=np.float32))
assert np.array_equal(import_and_compute('Div', [[10, 20, 30], [40, 50, 60]], [2, 5, 6], broadcast=1),
np.array([[5, 4, 5], [20, 10, 10]], dtype=np.float32)) | 0.835852 | 0.607343 |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='DataElement',
fields=[
('id', models.CharField(max_length=255, primary_key=True, serialize=False)),
('name', models.CharField(blank=True, max_length=500, null=True)),
('openmrs', models.CharField(blank=True, max_length=100, null=True)),
('categoryOptionCombo', models.CharField(blank=True, max_length=200, null=True)),
('attributeOptionCombo', models.CharField(blank=True, max_length=200, null=True)),
],
),
migrations.CreateModel(
name='DataSet',
fields=[
('id', models.CharField(max_length=255, primary_key=True, serialize=False)),
('name', models.CharField(blank=True, max_length=500, null=True)),
],
),
migrations.CreateModel(
name='District',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
],
),
migrations.CreateModel(
name='PeriodDescription',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('ano', models.CharField(max_length=10)),
('mes', models.CharField(choices=[('Jan', 'Janeiro'), ('Feb', 'Fevereiro'), ('Mar', 'Março'), ('Apr', 'Abril'), ('May', 'Maio'), ('Jun', 'Junho'), ('Jul', 'Julho'), ('Aug', 'Agosto'), ('Sep', 'Setembro'), ('Oct', 'Outubro'), ('Nov', 'Novembro'), ('Dec', 'Dezembro')], max_length=50)),
('period_ref', models.CharField(blank=True, max_length=100, null=True)),
('period', models.CharField(blank=True, max_length=50, null=True)),
],
),
migrations.CreateModel(
name='Province',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200)),
],
),
migrations.CreateModel(
name='OpenmrsURL',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('province', models.CharField(max_length=100)),
('instance_name', models.CharField(max_length=100)),
('uuid', models.CharField(max_length=255)),
('url', models.CharField(max_length=500)),
('dataSet', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='core.dataset')),
],
),
migrations.CreateModel(
name='HealthFacility',
fields=[
('id', models.CharField(max_length=255, primary_key=True, serialize=False)),
('name', models.CharField(max_length=255)),
('district', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.district')),
],
options={
'verbose_name': 'Health Facility',
'verbose_name_plural': 'Health Facilities',
},
),
migrations.AddField(
model_name='district',
name='province',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.province'),
),
migrations.CreateModel(
name='DataElementValue',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('period', models.CharField(max_length=100)),
('value', models.IntegerField(blank=True, null=True)),
('synced', models.BooleanField(default=False)),
('dataElement', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.dataelement')),
('healthFacility', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.healthfacility')),
],
),
migrations.AddField(
model_name='dataelement',
name='dataSet',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.dataset'),
),
] | app/core/migrations/0001_initial.py |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='DataElement',
fields=[
('id', models.CharField(max_length=255, primary_key=True, serialize=False)),
('name', models.CharField(blank=True, max_length=500, null=True)),
('openmrs', models.CharField(blank=True, max_length=100, null=True)),
('categoryOptionCombo', models.CharField(blank=True, max_length=200, null=True)),
('attributeOptionCombo', models.CharField(blank=True, max_length=200, null=True)),
],
),
migrations.CreateModel(
name='DataSet',
fields=[
('id', models.CharField(max_length=255, primary_key=True, serialize=False)),
('name', models.CharField(blank=True, max_length=500, null=True)),
],
),
migrations.CreateModel(
name='District',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
],
),
migrations.CreateModel(
name='PeriodDescription',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('ano', models.CharField(max_length=10)),
('mes', models.CharField(choices=[('Jan', 'Janeiro'), ('Feb', 'Fevereiro'), ('Mar', 'Março'), ('Apr', 'Abril'), ('May', 'Maio'), ('Jun', 'Junho'), ('Jul', 'Julho'), ('Aug', 'Agosto'), ('Sep', 'Setembro'), ('Oct', 'Outubro'), ('Nov', 'Novembro'), ('Dec', 'Dezembro')], max_length=50)),
('period_ref', models.CharField(blank=True, max_length=100, null=True)),
('period', models.CharField(blank=True, max_length=50, null=True)),
],
),
migrations.CreateModel(
name='Province',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200)),
],
),
migrations.CreateModel(
name='OpenmrsURL',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('province', models.CharField(max_length=100)),
('instance_name', models.CharField(max_length=100)),
('uuid', models.CharField(max_length=255)),
('url', models.CharField(max_length=500)),
('dataSet', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='core.dataset')),
],
),
migrations.CreateModel(
name='HealthFacility',
fields=[
('id', models.CharField(max_length=255, primary_key=True, serialize=False)),
('name', models.CharField(max_length=255)),
('district', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.district')),
],
options={
'verbose_name': 'Health Facility',
'verbose_name_plural': 'Health Facilities',
},
),
migrations.AddField(
model_name='district',
name='province',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.province'),
),
migrations.CreateModel(
name='DataElementValue',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('period', models.CharField(max_length=100)),
('value', models.IntegerField(blank=True, null=True)),
('synced', models.BooleanField(default=False)),
('dataElement', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.dataelement')),
('healthFacility', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.healthfacility')),
],
),
migrations.AddField(
model_name='dataelement',
name='dataSet',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.dataset'),
),
] | 0.567577 | 0.193452 |
import os
from absl import logging
from absl.testing import parameterized
import numpy as np
import tensorflow as tf
# pylint: disable=g-direct-tensorflow-import
from tensorflow.python.distribute import combinations
from tensorflow.python.distribute import strategy_combinations
# pylint: enable=g-direct-tensorflow-import
from official.nlp.nhnet import configs
from official.nlp.nhnet import models
from official.nlp.nhnet import utils
def all_strategy_combinations():
return combinations.combine(
distribution=[
strategy_combinations.default_strategy,
strategy_combinations.cloud_tpu_strategy,
strategy_combinations.one_device_strategy_gpu,
strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
strategy_combinations.mirrored_strategy_with_two_gpus,
],)
def distribution_forward_path(strategy,
model,
inputs,
batch_size,
mode="train"):
dataset = tf.data.Dataset.from_tensor_slices((inputs))
dataset = dataset.batch(batch_size)
dataset = strategy.experimental_distribute_dataset(dataset)
@tf.function
def test_step(inputs):
"""Calculates evaluation metrics on distributed devices."""
def _test_step_fn(inputs):
"""Replicated accuracy calculation."""
return model(inputs, mode=mode, training=False)
outputs = strategy.run(_test_step_fn, args=(inputs,))
return tf.nest.map_structure(strategy.experimental_local_results, outputs)
return [test_step(inputs) for inputs in dataset]
def process_decoded_ids(predictions, end_token_id):
"""Transforms decoded tensors to lists ending with END_TOKEN_ID."""
if isinstance(predictions, tf.Tensor):
predictions = predictions.numpy()
flatten_ids = predictions.reshape((-1, predictions.shape[-1]))
results = []
for ids in flatten_ids:
ids = list(ids)
if end_token_id in ids:
ids = ids[:ids.index(end_token_id)]
results.append(ids)
return results
class Bert2BertTest(tf.test.TestCase, parameterized.TestCase):
def setUp(self):
super(Bert2BertTest, self).setUp()
self._config = utils.get_test_params()
def test_model_creation(self):
model = models.create_bert2bert_model(params=self._config)
fake_ids = np.zeros((2, 10), dtype=np.int32)
fake_inputs = {
"input_ids": fake_ids,
"input_mask": fake_ids,
"segment_ids": fake_ids,
"target_ids": fake_ids,
}
model(fake_inputs)
@combinations.generate(all_strategy_combinations())
def test_bert2bert_train_forward(self, distribution):
seq_length = 10
# Defines the model inside distribution strategy scope.
with distribution.scope():
# Forward path.
batch_size = 2
batches = 4
fake_ids = np.zeros((batch_size * batches, seq_length), dtype=np.int32)
fake_inputs = {
"input_ids": fake_ids,
"input_mask": fake_ids,
"segment_ids": fake_ids,
"target_ids": fake_ids,
}
model = models.create_bert2bert_model(params=self._config)
results = distribution_forward_path(distribution, model, fake_inputs,
batch_size)
logging.info("Forward path results: %s", str(results))
self.assertLen(results, batches)
def test_bert2bert_decoding(self):
seq_length = 10
self._config.override(
{
"beam_size": 3,
"len_title": seq_length,
"alpha": 0.6,
},
is_strict=False)
batch_size = 2
fake_ids = np.zeros((batch_size, seq_length), dtype=np.int32)
fake_inputs = {
"input_ids": fake_ids,
"input_mask": fake_ids,
"segment_ids": fake_ids,
}
self._config.override({
"padded_decode": False,
"use_cache": False,
},
is_strict=False)
model = models.create_bert2bert_model(params=self._config)
ckpt = tf.train.Checkpoint(model=model)
# Initializes variables from checkpoint to keep outputs deterministic.
init_checkpoint = ckpt.save(os.path.join(self.get_temp_dir(), "ckpt"))
ckpt.restore(init_checkpoint).assert_existing_objects_matched()
top_ids, scores = model(fake_inputs, mode="predict")
self._config.override({
"padded_decode": False,
"use_cache": True,
},
is_strict=False)
model = models.create_bert2bert_model(params=self._config)
ckpt = tf.train.Checkpoint(model=model)
ckpt.restore(init_checkpoint).assert_existing_objects_matched()
cached_top_ids, cached_scores = model(fake_inputs, mode="predict")
self.assertEqual(
process_decoded_ids(top_ids, self._config.end_token_id),
process_decoded_ids(cached_top_ids, self._config.end_token_id))
self.assertAllClose(scores, cached_scores)
self._config.override({
"padded_decode": True,
"use_cache": True,
},
is_strict=False)
model = models.create_bert2bert_model(params=self._config)
ckpt = tf.train.Checkpoint(model=model)
ckpt.restore(init_checkpoint).assert_existing_objects_matched()
padded_top_ids, padded_scores = model(fake_inputs, mode="predict")
self.assertEqual(
process_decoded_ids(top_ids, self._config.end_token_id),
process_decoded_ids(padded_top_ids, self._config.end_token_id))
self.assertAllClose(scores, padded_scores)
@combinations.generate(all_strategy_combinations())
def test_bert2bert_eval(self, distribution):
seq_length = 10
padded_decode = isinstance(
distribution,
(tf.distribute.TPUStrategy, tf.distribute.experimental.TPUStrategy))
self._config.override(
{
"beam_size": 3,
"len_title": seq_length,
"alpha": 0.6,
"padded_decode": padded_decode,
},
is_strict=False)
# Defines the model inside distribution strategy scope.
with distribution.scope():
# Forward path.
batch_size = 2
batches = 4
fake_ids = np.zeros((batch_size * batches, seq_length), dtype=np.int32)
fake_inputs = {
"input_ids": fake_ids,
"input_mask": fake_ids,
"segment_ids": fake_ids,
}
model = models.create_bert2bert_model(params=self._config)
results = distribution_forward_path(
distribution, model, fake_inputs, batch_size, mode="predict")
self.assertLen(results, batches)
results = distribution_forward_path(
distribution, model, fake_inputs, batch_size, mode="eval")
self.assertLen(results, batches)
class NHNetTest(tf.test.TestCase, parameterized.TestCase):
def setUp(self):
super(NHNetTest, self).setUp()
self._nhnet_config = configs.NHNetConfig()
self._nhnet_config.override(utils.get_test_params().as_dict())
self._bert2bert_config = configs.BERT2BERTConfig()
self._bert2bert_config.override(utils.get_test_params().as_dict())
def _count_params(self, layer, trainable_only=True):
"""Returns the count of all model parameters, or just trainable ones."""
if not trainable_only:
return layer.count_params()
else:
return int(
np.sum([
tf.keras.backend.count_params(p) for p in layer.trainable_weights
]))
def test_create_nhnet_layers(self):
single_doc_bert, single_doc_decoder = models.get_bert2bert_layers(
self._bert2bert_config)
multi_doc_bert, multi_doc_decoder = models.get_nhnet_layers(
self._nhnet_config)
# Expects multi-doc encoder/decoder have the same number of parameters as
# single-doc encoder/decoder.
self.assertEqual(
self._count_params(multi_doc_bert), self._count_params(single_doc_bert))
self.assertEqual(
self._count_params(multi_doc_decoder),
self._count_params(single_doc_decoder))
def test_checkpoint_restore(self):
bert2bert_model = models.create_bert2bert_model(self._bert2bert_config)
ckpt = tf.train.Checkpoint(model=bert2bert_model)
init_checkpoint = ckpt.save(os.path.join(self.get_temp_dir(), "ckpt"))
nhnet_model = models.create_nhnet_model(
params=self._nhnet_config, init_checkpoint=init_checkpoint)
source_weights = (
bert2bert_model.bert_layer.trainable_weights +
bert2bert_model.decoder_layer.trainable_weights)
dest_weights = (
nhnet_model.bert_layer.trainable_weights +
nhnet_model.decoder_layer.trainable_weights)
for source_weight, dest_weight in zip(source_weights, dest_weights):
self.assertAllClose(source_weight.numpy(), dest_weight.numpy())
@combinations.generate(all_strategy_combinations())
def test_nhnet_train_forward(self, distribution):
seq_length = 10
# Defines the model inside distribution strategy scope.
with distribution.scope():
# Forward path.
batch_size = 2
num_docs = 2
batches = 4
fake_ids = np.zeros((batch_size * batches, num_docs, seq_length),
dtype=np.int32)
fake_inputs = {
"input_ids":
fake_ids,
"input_mask":
fake_ids,
"segment_ids":
fake_ids,
"target_ids":
np.zeros((batch_size * batches, seq_length * 2), dtype=np.int32),
}
model = models.create_nhnet_model(params=self._nhnet_config)
results = distribution_forward_path(distribution, model, fake_inputs,
batch_size)
logging.info("Forward path results: %s", str(results))
self.assertLen(results, batches)
@combinations.generate(all_strategy_combinations())
def test_nhnet_eval(self, distribution):
seq_length = 10
padded_decode = isinstance(
distribution,
(tf.distribute.TPUStrategy, tf.distribute.experimental.TPUStrategy))
self._nhnet_config.override(
{
"beam_size": 4,
"len_title": seq_length,
"alpha": 0.6,
"multi_channel_cross_attention": True,
"padded_decode": padded_decode,
},
is_strict=False)
# Defines the model inside distribution strategy scope.
with distribution.scope():
# Forward path.
batch_size = 2
num_docs = 2
batches = 4
fake_ids = np.zeros((batch_size * batches, num_docs, seq_length),
dtype=np.int32)
fake_inputs = {
"input_ids": fake_ids,
"input_mask": fake_ids,
"segment_ids": fake_ids,
"target_ids": np.zeros((batch_size * batches, 5), dtype=np.int32),
}
model = models.create_nhnet_model(params=self._nhnet_config)
results = distribution_forward_path(
distribution, model, fake_inputs, batch_size, mode="predict")
self.assertLen(results, batches)
results = distribution_forward_path(
distribution, model, fake_inputs, batch_size, mode="eval")
self.assertLen(results, batches)
if __name__ == "__main__":
tf.test.main() | official/nlp/nhnet/models_test.py | import os
from absl import logging
from absl.testing import parameterized
import numpy as np
import tensorflow as tf
# pylint: disable=g-direct-tensorflow-import
from tensorflow.python.distribute import combinations
from tensorflow.python.distribute import strategy_combinations
# pylint: enable=g-direct-tensorflow-import
from official.nlp.nhnet import configs
from official.nlp.nhnet import models
from official.nlp.nhnet import utils
def all_strategy_combinations():
return combinations.combine(
distribution=[
strategy_combinations.default_strategy,
strategy_combinations.cloud_tpu_strategy,
strategy_combinations.one_device_strategy_gpu,
strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
strategy_combinations.mirrored_strategy_with_two_gpus,
],)
def distribution_forward_path(strategy,
model,
inputs,
batch_size,
mode="train"):
dataset = tf.data.Dataset.from_tensor_slices((inputs))
dataset = dataset.batch(batch_size)
dataset = strategy.experimental_distribute_dataset(dataset)
@tf.function
def test_step(inputs):
"""Calculates evaluation metrics on distributed devices."""
def _test_step_fn(inputs):
"""Replicated accuracy calculation."""
return model(inputs, mode=mode, training=False)
outputs = strategy.run(_test_step_fn, args=(inputs,))
return tf.nest.map_structure(strategy.experimental_local_results, outputs)
return [test_step(inputs) for inputs in dataset]
def process_decoded_ids(predictions, end_token_id):
"""Transforms decoded tensors to lists ending with END_TOKEN_ID."""
if isinstance(predictions, tf.Tensor):
predictions = predictions.numpy()
flatten_ids = predictions.reshape((-1, predictions.shape[-1]))
results = []
for ids in flatten_ids:
ids = list(ids)
if end_token_id in ids:
ids = ids[:ids.index(end_token_id)]
results.append(ids)
return results
class Bert2BertTest(tf.test.TestCase, parameterized.TestCase):
def setUp(self):
super(Bert2BertTest, self).setUp()
self._config = utils.get_test_params()
def test_model_creation(self):
model = models.create_bert2bert_model(params=self._config)
fake_ids = np.zeros((2, 10), dtype=np.int32)
fake_inputs = {
"input_ids": fake_ids,
"input_mask": fake_ids,
"segment_ids": fake_ids,
"target_ids": fake_ids,
}
model(fake_inputs)
@combinations.generate(all_strategy_combinations())
def test_bert2bert_train_forward(self, distribution):
seq_length = 10
# Defines the model inside distribution strategy scope.
with distribution.scope():
# Forward path.
batch_size = 2
batches = 4
fake_ids = np.zeros((batch_size * batches, seq_length), dtype=np.int32)
fake_inputs = {
"input_ids": fake_ids,
"input_mask": fake_ids,
"segment_ids": fake_ids,
"target_ids": fake_ids,
}
model = models.create_bert2bert_model(params=self._config)
results = distribution_forward_path(distribution, model, fake_inputs,
batch_size)
logging.info("Forward path results: %s", str(results))
self.assertLen(results, batches)
def test_bert2bert_decoding(self):
seq_length = 10
self._config.override(
{
"beam_size": 3,
"len_title": seq_length,
"alpha": 0.6,
},
is_strict=False)
batch_size = 2
fake_ids = np.zeros((batch_size, seq_length), dtype=np.int32)
fake_inputs = {
"input_ids": fake_ids,
"input_mask": fake_ids,
"segment_ids": fake_ids,
}
self._config.override({
"padded_decode": False,
"use_cache": False,
},
is_strict=False)
model = models.create_bert2bert_model(params=self._config)
ckpt = tf.train.Checkpoint(model=model)
# Initializes variables from checkpoint to keep outputs deterministic.
init_checkpoint = ckpt.save(os.path.join(self.get_temp_dir(), "ckpt"))
ckpt.restore(init_checkpoint).assert_existing_objects_matched()
top_ids, scores = model(fake_inputs, mode="predict")
self._config.override({
"padded_decode": False,
"use_cache": True,
},
is_strict=False)
model = models.create_bert2bert_model(params=self._config)
ckpt = tf.train.Checkpoint(model=model)
ckpt.restore(init_checkpoint).assert_existing_objects_matched()
cached_top_ids, cached_scores = model(fake_inputs, mode="predict")
self.assertEqual(
process_decoded_ids(top_ids, self._config.end_token_id),
process_decoded_ids(cached_top_ids, self._config.end_token_id))
self.assertAllClose(scores, cached_scores)
self._config.override({
"padded_decode": True,
"use_cache": True,
},
is_strict=False)
model = models.create_bert2bert_model(params=self._config)
ckpt = tf.train.Checkpoint(model=model)
ckpt.restore(init_checkpoint).assert_existing_objects_matched()
padded_top_ids, padded_scores = model(fake_inputs, mode="predict")
self.assertEqual(
process_decoded_ids(top_ids, self._config.end_token_id),
process_decoded_ids(padded_top_ids, self._config.end_token_id))
self.assertAllClose(scores, padded_scores)
@combinations.generate(all_strategy_combinations())
def test_bert2bert_eval(self, distribution):
seq_length = 10
padded_decode = isinstance(
distribution,
(tf.distribute.TPUStrategy, tf.distribute.experimental.TPUStrategy))
self._config.override(
{
"beam_size": 3,
"len_title": seq_length,
"alpha": 0.6,
"padded_decode": padded_decode,
},
is_strict=False)
# Defines the model inside distribution strategy scope.
with distribution.scope():
# Forward path.
batch_size = 2
batches = 4
fake_ids = np.zeros((batch_size * batches, seq_length), dtype=np.int32)
fake_inputs = {
"input_ids": fake_ids,
"input_mask": fake_ids,
"segment_ids": fake_ids,
}
model = models.create_bert2bert_model(params=self._config)
results = distribution_forward_path(
distribution, model, fake_inputs, batch_size, mode="predict")
self.assertLen(results, batches)
results = distribution_forward_path(
distribution, model, fake_inputs, batch_size, mode="eval")
self.assertLen(results, batches)
class NHNetTest(tf.test.TestCase, parameterized.TestCase):
def setUp(self):
super(NHNetTest, self).setUp()
self._nhnet_config = configs.NHNetConfig()
self._nhnet_config.override(utils.get_test_params().as_dict())
self._bert2bert_config = configs.BERT2BERTConfig()
self._bert2bert_config.override(utils.get_test_params().as_dict())
def _count_params(self, layer, trainable_only=True):
"""Returns the count of all model parameters, or just trainable ones."""
if not trainable_only:
return layer.count_params()
else:
return int(
np.sum([
tf.keras.backend.count_params(p) for p in layer.trainable_weights
]))
def test_create_nhnet_layers(self):
single_doc_bert, single_doc_decoder = models.get_bert2bert_layers(
self._bert2bert_config)
multi_doc_bert, multi_doc_decoder = models.get_nhnet_layers(
self._nhnet_config)
# Expects multi-doc encoder/decoder have the same number of parameters as
# single-doc encoder/decoder.
self.assertEqual(
self._count_params(multi_doc_bert), self._count_params(single_doc_bert))
self.assertEqual(
self._count_params(multi_doc_decoder),
self._count_params(single_doc_decoder))
def test_checkpoint_restore(self):
bert2bert_model = models.create_bert2bert_model(self._bert2bert_config)
ckpt = tf.train.Checkpoint(model=bert2bert_model)
init_checkpoint = ckpt.save(os.path.join(self.get_temp_dir(), "ckpt"))
nhnet_model = models.create_nhnet_model(
params=self._nhnet_config, init_checkpoint=init_checkpoint)
source_weights = (
bert2bert_model.bert_layer.trainable_weights +
bert2bert_model.decoder_layer.trainable_weights)
dest_weights = (
nhnet_model.bert_layer.trainable_weights +
nhnet_model.decoder_layer.trainable_weights)
for source_weight, dest_weight in zip(source_weights, dest_weights):
self.assertAllClose(source_weight.numpy(), dest_weight.numpy())
@combinations.generate(all_strategy_combinations())
def test_nhnet_train_forward(self, distribution):
seq_length = 10
# Defines the model inside distribution strategy scope.
with distribution.scope():
# Forward path.
batch_size = 2
num_docs = 2
batches = 4
fake_ids = np.zeros((batch_size * batches, num_docs, seq_length),
dtype=np.int32)
fake_inputs = {
"input_ids":
fake_ids,
"input_mask":
fake_ids,
"segment_ids":
fake_ids,
"target_ids":
np.zeros((batch_size * batches, seq_length * 2), dtype=np.int32),
}
model = models.create_nhnet_model(params=self._nhnet_config)
results = distribution_forward_path(distribution, model, fake_inputs,
batch_size)
logging.info("Forward path results: %s", str(results))
self.assertLen(results, batches)
@combinations.generate(all_strategy_combinations())
def test_nhnet_eval(self, distribution):
seq_length = 10
padded_decode = isinstance(
distribution,
(tf.distribute.TPUStrategy, tf.distribute.experimental.TPUStrategy))
self._nhnet_config.override(
{
"beam_size": 4,
"len_title": seq_length,
"alpha": 0.6,
"multi_channel_cross_attention": True,
"padded_decode": padded_decode,
},
is_strict=False)
# Defines the model inside distribution strategy scope.
with distribution.scope():
# Forward path.
batch_size = 2
num_docs = 2
batches = 4
fake_ids = np.zeros((batch_size * batches, num_docs, seq_length),
dtype=np.int32)
fake_inputs = {
"input_ids": fake_ids,
"input_mask": fake_ids,
"segment_ids": fake_ids,
"target_ids": np.zeros((batch_size * batches, 5), dtype=np.int32),
}
model = models.create_nhnet_model(params=self._nhnet_config)
results = distribution_forward_path(
distribution, model, fake_inputs, batch_size, mode="predict")
self.assertLen(results, batches)
results = distribution_forward_path(
distribution, model, fake_inputs, batch_size, mode="eval")
self.assertLen(results, batches)
if __name__ == "__main__":
tf.test.main() | 0.700485 | 0.231397 |
import pytest
from datadog_checks.nginx import Nginx
from . import common
@pytest.mark.e2e
@pytest.mark.skipif(common.USING_VTS, reason="Non-VTS test")
def test_e2e(dd_agent_check, instance):
aggregator = dd_agent_check(instance, rate=True)
aggregator.assert_metric('nginx.net.writing', count=2, tags=common.TAGS)
aggregator.assert_metric('nginx.net.waiting', count=2, tags=common.TAGS)
aggregator.assert_metric('nginx.net.reading', count=2, tags=common.TAGS)
aggregator.assert_metric('nginx.net.conn_dropped_per_s', count=1, tags=common.TAGS)
aggregator.assert_metric('nginx.net.conn_opened_per_s', count=1, tags=common.TAGS)
aggregator.assert_metric('nginx.net.request_per_s', count=1, tags=common.TAGS)
aggregator.assert_metric('nginx.net.connections', count=2, tags=common.TAGS)
aggregator.assert_all_metrics_covered()
tags = common.TAGS + [
'nginx_host:{}'.format(common.HOST),
'port:{}'.format(common.PORT),
]
aggregator.assert_service_check('nginx.can_connect', status=Nginx.OK, tags=tags)
@pytest.mark.e2e
@pytest.mark.skipif(not common.USING_VTS, reason="VTS test")
def test_e2e_vts(dd_agent_check, instance_vts):
aggregator = dd_agent_check(instance_vts, rate=True)
aggregator.assert_metric('nginx.net.writing', count=2, tags=common.TAGS)
aggregator.assert_metric('nginx.net.waiting', count=2, tags=common.TAGS)
aggregator.assert_metric('nginx.net.reading', count=2, tags=common.TAGS)
aggregator.assert_metric('nginx.net.conn_dropped_per_s', count=1, tags=common.TAGS)
aggregator.assert_metric('nginx.net.conn_opened_per_s', count=1, tags=common.TAGS)
aggregator.assert_metric('nginx.net.request_per_s', count=1, tags=common.TAGS)
tags_server_zone = common.TAGS + ['server_zone:*']
aggregator.assert_metric('nginx.connections.active', count=2, tags=common.TAGS)
aggregator.assert_metric('nginx.server_zone.sent', count=2, tags=tags_server_zone)
aggregator.assert_metric('nginx.server_zone.sent_count', count=1, tags=tags_server_zone)
aggregator.assert_metric('nginx.server_zone.received', count=2, tags=tags_server_zone)
aggregator.assert_metric('nginx.server_zone.received_count', count=1, tags=tags_server_zone)
aggregator.assert_metric('nginx.requests.total_count', count=1, tags=common.TAGS)
aggregator.assert_metric('nginx.requests.total', count=2, tags=common.TAGS)
aggregator.assert_metric('nginx.timestamp', count=2, tags=common.TAGS)
aggregator.assert_metric('nginx.server_zone.requests_count', count=1, tags=tags_server_zone)
aggregator.assert_metric('nginx.load_timestamp', count=2, tags=common.TAGS)
aggregator.assert_metric('nginx.server_zone.requests', count=2, tags=tags_server_zone)
aggregator.assert_metric('nginx.connections.accepted', count=2, tags=common.TAGS)
aggregator.assert_metric('nginx.connections.accepted_count', count=1, tags=common.TAGS)
aggregator.assert_metric('nginx.server_zone.responses.1xx_count', count=1, tags=tags_server_zone)
aggregator.assert_metric('nginx.server_zone.responses.2xx_count', count=1, tags=tags_server_zone)
aggregator.assert_metric('nginx.server_zone.responses.3xx_count', count=1, tags=tags_server_zone)
aggregator.assert_metric('nginx.server_zone.responses.4xx_count', count=1, tags=tags_server_zone)
aggregator.assert_metric('nginx.server_zone.responses.5xx_count', count=1, tags=tags_server_zone)
aggregator.assert_metric('nginx.server_zone.responses.1xx', count=2, tags=tags_server_zone)
aggregator.assert_metric('nginx.server_zone.responses.2xx', count=2, tags=tags_server_zone)
aggregator.assert_metric('nginx.server_zone.responses.3xx', count=2, tags=tags_server_zone)
aggregator.assert_metric('nginx.server_zone.responses.4xx', count=2, tags=tags_server_zone)
aggregator.assert_metric('nginx.server_zone.responses.5xx', count=2, tags=tags_server_zone)
aggregator.assert_all_metrics_covered()
tags = common.TAGS + [
'nginx_host:{}'.format(common.HOST),
'port:{}'.format(common.PORT),
]
aggregator.assert_service_check('nginx.can_connect', status=Nginx.OK, tags=tags) | nginx/tests/test_e2e.py | import pytest
from datadog_checks.nginx import Nginx
from . import common
@pytest.mark.e2e
@pytest.mark.skipif(common.USING_VTS, reason="Non-VTS test")
def test_e2e(dd_agent_check, instance):
aggregator = dd_agent_check(instance, rate=True)
aggregator.assert_metric('nginx.net.writing', count=2, tags=common.TAGS)
aggregator.assert_metric('nginx.net.waiting', count=2, tags=common.TAGS)
aggregator.assert_metric('nginx.net.reading', count=2, tags=common.TAGS)
aggregator.assert_metric('nginx.net.conn_dropped_per_s', count=1, tags=common.TAGS)
aggregator.assert_metric('nginx.net.conn_opened_per_s', count=1, tags=common.TAGS)
aggregator.assert_metric('nginx.net.request_per_s', count=1, tags=common.TAGS)
aggregator.assert_metric('nginx.net.connections', count=2, tags=common.TAGS)
aggregator.assert_all_metrics_covered()
tags = common.TAGS + [
'nginx_host:{}'.format(common.HOST),
'port:{}'.format(common.PORT),
]
aggregator.assert_service_check('nginx.can_connect', status=Nginx.OK, tags=tags)
@pytest.mark.e2e
@pytest.mark.skipif(not common.USING_VTS, reason="VTS test")
def test_e2e_vts(dd_agent_check, instance_vts):
aggregator = dd_agent_check(instance_vts, rate=True)
aggregator.assert_metric('nginx.net.writing', count=2, tags=common.TAGS)
aggregator.assert_metric('nginx.net.waiting', count=2, tags=common.TAGS)
aggregator.assert_metric('nginx.net.reading', count=2, tags=common.TAGS)
aggregator.assert_metric('nginx.net.conn_dropped_per_s', count=1, tags=common.TAGS)
aggregator.assert_metric('nginx.net.conn_opened_per_s', count=1, tags=common.TAGS)
aggregator.assert_metric('nginx.net.request_per_s', count=1, tags=common.TAGS)
tags_server_zone = common.TAGS + ['server_zone:*']
aggregator.assert_metric('nginx.connections.active', count=2, tags=common.TAGS)
aggregator.assert_metric('nginx.server_zone.sent', count=2, tags=tags_server_zone)
aggregator.assert_metric('nginx.server_zone.sent_count', count=1, tags=tags_server_zone)
aggregator.assert_metric('nginx.server_zone.received', count=2, tags=tags_server_zone)
aggregator.assert_metric('nginx.server_zone.received_count', count=1, tags=tags_server_zone)
aggregator.assert_metric('nginx.requests.total_count', count=1, tags=common.TAGS)
aggregator.assert_metric('nginx.requests.total', count=2, tags=common.TAGS)
aggregator.assert_metric('nginx.timestamp', count=2, tags=common.TAGS)
aggregator.assert_metric('nginx.server_zone.requests_count', count=1, tags=tags_server_zone)
aggregator.assert_metric('nginx.load_timestamp', count=2, tags=common.TAGS)
aggregator.assert_metric('nginx.server_zone.requests', count=2, tags=tags_server_zone)
aggregator.assert_metric('nginx.connections.accepted', count=2, tags=common.TAGS)
aggregator.assert_metric('nginx.connections.accepted_count', count=1, tags=common.TAGS)
aggregator.assert_metric('nginx.server_zone.responses.1xx_count', count=1, tags=tags_server_zone)
aggregator.assert_metric('nginx.server_zone.responses.2xx_count', count=1, tags=tags_server_zone)
aggregator.assert_metric('nginx.server_zone.responses.3xx_count', count=1, tags=tags_server_zone)
aggregator.assert_metric('nginx.server_zone.responses.4xx_count', count=1, tags=tags_server_zone)
aggregator.assert_metric('nginx.server_zone.responses.5xx_count', count=1, tags=tags_server_zone)
aggregator.assert_metric('nginx.server_zone.responses.1xx', count=2, tags=tags_server_zone)
aggregator.assert_metric('nginx.server_zone.responses.2xx', count=2, tags=tags_server_zone)
aggregator.assert_metric('nginx.server_zone.responses.3xx', count=2, tags=tags_server_zone)
aggregator.assert_metric('nginx.server_zone.responses.4xx', count=2, tags=tags_server_zone)
aggregator.assert_metric('nginx.server_zone.responses.5xx', count=2, tags=tags_server_zone)
aggregator.assert_all_metrics_covered()
tags = common.TAGS + [
'nginx_host:{}'.format(common.HOST),
'port:{}'.format(common.PORT),
]
aggregator.assert_service_check('nginx.can_connect', status=Nginx.OK, tags=tags) | 0.583203 | 0.451689 |
import copy
import torch.nn as nn
from torch.nn import Module as Module
from bert_modules.utils import BertLayerNorm, BertSelfAttention, gelu
class BertSelfOutput(Module):
def __init__(self, config):
super(BertSelfOutput, self).__init__()
self.dense = nn.Linear(config['hidden_dim'], config['hidden_dim'])
self.LayerNorm = BertLayerNorm(config['hidden_dim'], eps=1e-12)
self.dropout = nn.Dropout(0.1)
def forward(self, hidden_states, input_tensor):
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
class BertAttention(Module):
def __init__(self, config):
super(BertAttention, self).__init__()
self.self = BertSelfAttention(config)
self.output = BertSelfOutput(config)
def forward(self, input_tensor, attention_mask, output_attention_probs=False):
self_output = self.self(input_tensor, attention_mask, output_attention_probs=output_attention_probs)
if output_attention_probs:
self_output, attention_probs = self_output
attention_output = self.output(self_output, input_tensor)
if output_attention_probs:
return attention_output, attention_probs
return attention_output
class BertIntermediate(Module):
def __init__(self, config):
super(BertIntermediate, self).__init__()
self.dense = nn.Linear(config['hidden_dim'], 4 * config['hidden_dim'])
self.intermediate_act_fn = gelu
def forward(self, hidden_states):
hidden_states = self.dense(hidden_states)
hidden_states = self.intermediate_act_fn(hidden_states)
return hidden_states
class BertOutput(Module):
def __init__(self, config):
super(BertOutput, self).__init__()
self.dense = nn.Linear(4 * config['hidden_dim'], config['hidden_dim'])
self.LayerNorm = BertLayerNorm(config['hidden_dim'], eps=1e-12)
self.dropout = nn.Dropout(0.1)
def forward(self, hidden_states, input_tensor):
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
class BertLayer(Module):
def __init__(self, config):
super(BertLayer, self).__init__()
self.attention = BertAttention(config)
self.intermediate = BertIntermediate(config)
self.output = BertOutput(config)
def forward(self, hidden_states, attention_mask, output_attention_probs=False):
attention_output = self.attention(hidden_states, attention_mask, output_attention_probs=output_attention_probs)
if output_attention_probs:
attention_output, attention_probs = attention_output
intermediate_output = self.intermediate(attention_output)
layer_output = self.output(intermediate_output, attention_output)
if output_attention_probs:
return layer_output, attention_probs
else:
return layer_output
class BertEncoder(Module):
def __init__(self, config):
super(BertEncoder, self).__init__()
layer = BertLayer(config)
self.layer = nn.ModuleList([copy.deepcopy(layer) for _ in range(config['num_bert_layers'])])
def forward(self, hidden_states, attention_mask, output_all_encoded_layers=False, output_attention_probs=True):
all_encoder_layers = []
all_attention_probs = []
for layer_module in self.layer:
hidden_states = layer_module(hidden_states, attention_mask, output_attention_probs=output_attention_probs)
if output_attention_probs:
hidden_states, attention_probs = hidden_states
all_attention_probs.append(attention_probs)
if output_all_encoded_layers:
all_encoder_layers.append(hidden_states)
if not output_all_encoded_layers:
all_encoder_layers.append(hidden_states)
if output_attention_probs:
return all_encoder_layers, all_attention_probs
else:
return all_encoder_layers | bert_modules/bert_modules.py | import copy
import torch.nn as nn
from torch.nn import Module as Module
from bert_modules.utils import BertLayerNorm, BertSelfAttention, gelu
class BertSelfOutput(Module):
def __init__(self, config):
super(BertSelfOutput, self).__init__()
self.dense = nn.Linear(config['hidden_dim'], config['hidden_dim'])
self.LayerNorm = BertLayerNorm(config['hidden_dim'], eps=1e-12)
self.dropout = nn.Dropout(0.1)
def forward(self, hidden_states, input_tensor):
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
class BertAttention(Module):
def __init__(self, config):
super(BertAttention, self).__init__()
self.self = BertSelfAttention(config)
self.output = BertSelfOutput(config)
def forward(self, input_tensor, attention_mask, output_attention_probs=False):
self_output = self.self(input_tensor, attention_mask, output_attention_probs=output_attention_probs)
if output_attention_probs:
self_output, attention_probs = self_output
attention_output = self.output(self_output, input_tensor)
if output_attention_probs:
return attention_output, attention_probs
return attention_output
class BertIntermediate(Module):
def __init__(self, config):
super(BertIntermediate, self).__init__()
self.dense = nn.Linear(config['hidden_dim'], 4 * config['hidden_dim'])
self.intermediate_act_fn = gelu
def forward(self, hidden_states):
hidden_states = self.dense(hidden_states)
hidden_states = self.intermediate_act_fn(hidden_states)
return hidden_states
class BertOutput(Module):
def __init__(self, config):
super(BertOutput, self).__init__()
self.dense = nn.Linear(4 * config['hidden_dim'], config['hidden_dim'])
self.LayerNorm = BertLayerNorm(config['hidden_dim'], eps=1e-12)
self.dropout = nn.Dropout(0.1)
def forward(self, hidden_states, input_tensor):
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
class BertLayer(Module):
def __init__(self, config):
super(BertLayer, self).__init__()
self.attention = BertAttention(config)
self.intermediate = BertIntermediate(config)
self.output = BertOutput(config)
def forward(self, hidden_states, attention_mask, output_attention_probs=False):
attention_output = self.attention(hidden_states, attention_mask, output_attention_probs=output_attention_probs)
if output_attention_probs:
attention_output, attention_probs = attention_output
intermediate_output = self.intermediate(attention_output)
layer_output = self.output(intermediate_output, attention_output)
if output_attention_probs:
return layer_output, attention_probs
else:
return layer_output
class BertEncoder(Module):
def __init__(self, config):
super(BertEncoder, self).__init__()
layer = BertLayer(config)
self.layer = nn.ModuleList([copy.deepcopy(layer) for _ in range(config['num_bert_layers'])])
def forward(self, hidden_states, attention_mask, output_all_encoded_layers=False, output_attention_probs=True):
all_encoder_layers = []
all_attention_probs = []
for layer_module in self.layer:
hidden_states = layer_module(hidden_states, attention_mask, output_attention_probs=output_attention_probs)
if output_attention_probs:
hidden_states, attention_probs = hidden_states
all_attention_probs.append(attention_probs)
if output_all_encoded_layers:
all_encoder_layers.append(hidden_states)
if not output_all_encoded_layers:
all_encoder_layers.append(hidden_states)
if output_attention_probs:
return all_encoder_layers, all_attention_probs
else:
return all_encoder_layers | 0.89546 | 0.336304 |
from __future__ import absolute_import
from .printmsg import PrintMsg
from .lamb import Lambda
from .config import Config
from os.path import basename
import os
import json
import yaml
"""
Default config yaml
"""
DEFAULT_CONFIG = {
"Description": None,
"FunctionName": None,
"Handler": "lambda_handler",
"MemorySize": 128,
"Role": None,
"Runtime": "python2.7",
"Timeout": 15,
"VpcConfig": None,
"Environment": None,
"KMSKeyArn": None,
"TracingConfig": None,
"DeadLetterConfig": None
}
"""
Default python source code
"""
DEFAULT_SOURCE = """from __future__ import print_function
# noinspection PyUnusedLocal
def lambda_handler(event, context):
print(event)
"""
"""
Default Invoke config
"""
DEFAULT_INVOKE_CONFIG = {
"FunctionName": None,
"InvocationType": "Event",
"LogType": "None",
"ClientContext": None,
"Payload": None,
"Qualifier": None
}
class Project(object):
"""
Project of lambda functions
"""
path = None
functions = []
func = None
libraries = None
qualifier = None
config_file = "config.yaml"
i_config_file = "invoke.yaml"
payload = None
json_payload_file = None
invoke_type = None
virtual_env = None
debug = False
region = None
dry = False
config_postfix = '.yml'
function_postfix = '.py'
invoke_postfix = '-invoke.yml'
def __init__(self, **kwargs):
"""
Initialize project
:param kwargs:
:return:
"""
if 'path' not in kwargs:
raise KeyError('path is a Required Argument')
else:
self.path = kwargs['path']
if 'qualifier' in kwargs:
self.qualifier = kwargs['qualifier']
if 'virtual_env' in kwargs:
self.virtual_env = kwargs['virtual_env']
if 'libraries' in kwargs:
self.libraries = kwargs['libraries']
if 'config_file' in kwargs:
self.config_file = kwargs['config_file']
if 'invoke_file' in kwargs:
self.i_config_file = kwargs['invoke_file']
if 'payload' in kwargs and kwargs['payload']:
self.payload = self.load_json(kwargs['payload'])
if 'invoke_type' in kwargs and kwargs['invoke_type']:
self.invoke_type = kwargs['invoke_type']
if 'debug' in kwargs:
self.debug = kwargs['debug']
if 'region' in kwargs:
self.region = kwargs['region']
if 'dry' in kwargs:
self.dry = kwargs['dry']
if 'func' in kwargs and kwargs['func']:
self.func = kwargs['func']
if 'profile' in kwargs:
self.profile = kwargs['profile']
else:
self.profile = None
PrintMsg.debug = self.debug
PrintMsg.cmd('Path {}'.format(self.path), 'INITIALIZING', 'yellow')
if not self.func:
self.initialize_functions()
def initialize_functions(self):
"""
Initialize list of functions
"""
for root, dirs, files in os.walk(self.path):
for f in files:
if f.endswith(self.function_postfix):
file_name = os.path.splitext(basename(f))[0]
config = self.get_config(
root,
self.config_file,
file_name,
DEFAULT_CONFIG
)
icf = self.get_config(
root,
self.i_config_file,
file_name,
DEFAULT_INVOKE_CONFIG,
self.invoke_postfix
)
self.functions.append(
Lambda(
function=f,
function_name=file_name,
path=os.path.join(root),
virtual_env=self.virtual_env,
config=config,
qualifier=self.qualifier,
libraries=self.libraries,
region=self.region,
debug=self.debug,
dry=self.dry,
invoke_config=icf,
payload=self.json_payload_file,
invoke_type=self.invoke_type,
profile=self.profile
)
)
def get_config(self, path, config_file, name=None,
default=None, postfix='.yml'):
"""
Load config yaml
:param name:
:param postfix:
:param default:
:param path:
:param config_file:
:return:
"""
if os.path.exists(os.path.join(path, config_file)):
cf = Config(os.path.join(path, config_file))
data = cf.yaml_data
if default:
data = self.merge_config(data, default)
return data
elif name and os.path.exists(os.path.join(path, name) + postfix):
cf = Config(os.path.join(path, name) + postfix)
data = cf.yaml_data
if default:
data = self.merge_config(data, default)
return data
else:
return default
@staticmethod
def merge_config(data, default):
"""
Merge config data with default
:param data:
:param default:
:return data:
"""
for k, v in default.items():
if k not in data:
data[k] = v
return data
def load_json(self, payload):
"""
Load json from payload file
:param payload:
:return rj:
"""
rj = None
if os.path.exists(os.path.join(self.path, payload)):
self.json_payload_file = os.path.join(self.path, payload)
with open(os.path.join(self.path, payload), 'r') as j:
try:
rj = json.load(j)
except TypeError:
PrintMsg.error('Invalid json payload')
elif os.path.exists(payload):
self.json_payload_file = payload
with open(payload, 'r') as j:
try:
rj = json.load(j)
except TypeError:
PrintMsg.error('Invalid json payload')
if self.debug:
PrintMsg.out(rj)
return rj
def invoke(self, func):
"""
Invoke a lambda function
:param func:
:return:
"""
file_name = os.path.join(self.path, func)
config = self.get_config(
self.path,
self.config_file,
file_name,
DEFAULT_CONFIG
)
icf = self.get_config(
self.path,
self.i_config_file,
file_name,
DEFAULT_INVOKE_CONFIG,
self.invoke_postfix
)
Lambda(
function=file_name,
path=self.path,
funcion_name=func,
virtual_env=self.virtual_env,
config=config,
qualifier=self.qualifier,
libraries=self.libraries,
region=self.region,
debug=self.debug,
dry=self.dry,
invoke_config=icf,
payload=self.json_payload_file,
invoke_type=self.invoke_type,
profile=self.profile
).invoke()
def invoke_all(self):
"""
Invoke all functions in path
:return:
"""
for f in self.functions:
f.invoke()
PrintMsg.done('Invoking all')
def deploy(self, func):
"""
Deploy function
:param func:
:return:
"""
file_name = os.path.join(self.path, func)
config = self.get_config(
self.path,
self.config_file,
file_name,
DEFAULT_CONFIG
)
icf = self.get_config(
self.path,
self.i_config_file,
file_name,
DEFAULT_INVOKE_CONFIG,
self.invoke_postfix
)
f = func + self.function_postfix
Lambda(
function=f,
function_name=func,
path=self.path,
virtual_env=self.virtual_env,
config=config,
qualifier=self.qualifier,
libraries=self.libraries,
region=self.region,
debug=self.debug,
dry=self.dry,
invoke_config=icf,
payload=self.json_payload_file,
invoke_type=self.invoke_type,
profile=self.profile
).create()
PrintMsg.done('Deploying')
def deploy_all(self):
"""
Deploy all functions in path
:return:
"""
for f in self.functions:
f.create()
PrintMsg.done('Deploying all')
@staticmethod
def new(**kwargs):
"""
New function
:param kwargs:
:return:
"""
if 'Path' not in kwargs or not kwargs['Path']:
raise KeyError('path is a Required Argument')
if 'Function' not in kwargs or not kwargs['Function']:
raise KeyError('function is a Required Argument')
PrintMsg.cmd('New lambda function {}.'.format(
kwargs['Function']), 'INITIALIZING', 'yellow')
path = kwargs['Path']
func = kwargs['Function']
kwargs.pop('Path', None)
kwargs.pop('Function', None)
cf = {k: v for k, v in kwargs.items() if v}
cf = Project.merge_config(cf, DEFAULT_CONFIG)
cf = {k: v for k, v in cf.items() if v}
cf_name = os.path.join(path, func) + Project.config_postfix
f_name = os.path.join(path, func) + Project.function_postfix
PrintMsg.creating('Config file {}.'.format(cf_name))
if not os.path.exists(cf_name):
with open(cf_name, 'w') as j:
yaml.safe_dump(cf, j, default_flow_style=False)
PrintMsg.done('Creating config file {}.'.format(cf_name))
else:
PrintMsg.error('Config file already exists.')
PrintMsg.creating('Source file {}'.format(f_name))
if not os.path.exists(f_name):
f = open(f_name, 'w')
f.write(DEFAULT_SOURCE)
f.close()
PrintMsg.done('Creating source file {}.'.format(f_name))
else:
PrintMsg.error('File already exists.')
PrintMsg.done('Creating lambda function {}.'.format(func)) | albt/project.py | from __future__ import absolute_import
from .printmsg import PrintMsg
from .lamb import Lambda
from .config import Config
from os.path import basename
import os
import json
import yaml
"""
Default config yaml
"""
DEFAULT_CONFIG = {
"Description": None,
"FunctionName": None,
"Handler": "lambda_handler",
"MemorySize": 128,
"Role": None,
"Runtime": "python2.7",
"Timeout": 15,
"VpcConfig": None,
"Environment": None,
"KMSKeyArn": None,
"TracingConfig": None,
"DeadLetterConfig": None
}
"""
Default python source code
"""
DEFAULT_SOURCE = """from __future__ import print_function
# noinspection PyUnusedLocal
def lambda_handler(event, context):
print(event)
"""
"""
Default Invoke config
"""
DEFAULT_INVOKE_CONFIG = {
"FunctionName": None,
"InvocationType": "Event",
"LogType": "None",
"ClientContext": None,
"Payload": None,
"Qualifier": None
}
class Project(object):
"""
Project of lambda functions
"""
path = None
functions = []
func = None
libraries = None
qualifier = None
config_file = "config.yaml"
i_config_file = "invoke.yaml"
payload = None
json_payload_file = None
invoke_type = None
virtual_env = None
debug = False
region = None
dry = False
config_postfix = '.yml'
function_postfix = '.py'
invoke_postfix = '-invoke.yml'
def __init__(self, **kwargs):
"""
Initialize project
:param kwargs:
:return:
"""
if 'path' not in kwargs:
raise KeyError('path is a Required Argument')
else:
self.path = kwargs['path']
if 'qualifier' in kwargs:
self.qualifier = kwargs['qualifier']
if 'virtual_env' in kwargs:
self.virtual_env = kwargs['virtual_env']
if 'libraries' in kwargs:
self.libraries = kwargs['libraries']
if 'config_file' in kwargs:
self.config_file = kwargs['config_file']
if 'invoke_file' in kwargs:
self.i_config_file = kwargs['invoke_file']
if 'payload' in kwargs and kwargs['payload']:
self.payload = self.load_json(kwargs['payload'])
if 'invoke_type' in kwargs and kwargs['invoke_type']:
self.invoke_type = kwargs['invoke_type']
if 'debug' in kwargs:
self.debug = kwargs['debug']
if 'region' in kwargs:
self.region = kwargs['region']
if 'dry' in kwargs:
self.dry = kwargs['dry']
if 'func' in kwargs and kwargs['func']:
self.func = kwargs['func']
if 'profile' in kwargs:
self.profile = kwargs['profile']
else:
self.profile = None
PrintMsg.debug = self.debug
PrintMsg.cmd('Path {}'.format(self.path), 'INITIALIZING', 'yellow')
if not self.func:
self.initialize_functions()
def initialize_functions(self):
"""
Initialize list of functions
"""
for root, dirs, files in os.walk(self.path):
for f in files:
if f.endswith(self.function_postfix):
file_name = os.path.splitext(basename(f))[0]
config = self.get_config(
root,
self.config_file,
file_name,
DEFAULT_CONFIG
)
icf = self.get_config(
root,
self.i_config_file,
file_name,
DEFAULT_INVOKE_CONFIG,
self.invoke_postfix
)
self.functions.append(
Lambda(
function=f,
function_name=file_name,
path=os.path.join(root),
virtual_env=self.virtual_env,
config=config,
qualifier=self.qualifier,
libraries=self.libraries,
region=self.region,
debug=self.debug,
dry=self.dry,
invoke_config=icf,
payload=self.json_payload_file,
invoke_type=self.invoke_type,
profile=self.profile
)
)
def get_config(self, path, config_file, name=None,
default=None, postfix='.yml'):
"""
Load config yaml
:param name:
:param postfix:
:param default:
:param path:
:param config_file:
:return:
"""
if os.path.exists(os.path.join(path, config_file)):
cf = Config(os.path.join(path, config_file))
data = cf.yaml_data
if default:
data = self.merge_config(data, default)
return data
elif name and os.path.exists(os.path.join(path, name) + postfix):
cf = Config(os.path.join(path, name) + postfix)
data = cf.yaml_data
if default:
data = self.merge_config(data, default)
return data
else:
return default
@staticmethod
def merge_config(data, default):
"""
Merge config data with default
:param data:
:param default:
:return data:
"""
for k, v in default.items():
if k not in data:
data[k] = v
return data
def load_json(self, payload):
"""
Load json from payload file
:param payload:
:return rj:
"""
rj = None
if os.path.exists(os.path.join(self.path, payload)):
self.json_payload_file = os.path.join(self.path, payload)
with open(os.path.join(self.path, payload), 'r') as j:
try:
rj = json.load(j)
except TypeError:
PrintMsg.error('Invalid json payload')
elif os.path.exists(payload):
self.json_payload_file = payload
with open(payload, 'r') as j:
try:
rj = json.load(j)
except TypeError:
PrintMsg.error('Invalid json payload')
if self.debug:
PrintMsg.out(rj)
return rj
def invoke(self, func):
"""
Invoke a lambda function
:param func:
:return:
"""
file_name = os.path.join(self.path, func)
config = self.get_config(
self.path,
self.config_file,
file_name,
DEFAULT_CONFIG
)
icf = self.get_config(
self.path,
self.i_config_file,
file_name,
DEFAULT_INVOKE_CONFIG,
self.invoke_postfix
)
Lambda(
function=file_name,
path=self.path,
funcion_name=func,
virtual_env=self.virtual_env,
config=config,
qualifier=self.qualifier,
libraries=self.libraries,
region=self.region,
debug=self.debug,
dry=self.dry,
invoke_config=icf,
payload=self.json_payload_file,
invoke_type=self.invoke_type,
profile=self.profile
).invoke()
def invoke_all(self):
"""
Invoke all functions in path
:return:
"""
for f in self.functions:
f.invoke()
PrintMsg.done('Invoking all')
def deploy(self, func):
"""
Deploy function
:param func:
:return:
"""
file_name = os.path.join(self.path, func)
config = self.get_config(
self.path,
self.config_file,
file_name,
DEFAULT_CONFIG
)
icf = self.get_config(
self.path,
self.i_config_file,
file_name,
DEFAULT_INVOKE_CONFIG,
self.invoke_postfix
)
f = func + self.function_postfix
Lambda(
function=f,
function_name=func,
path=self.path,
virtual_env=self.virtual_env,
config=config,
qualifier=self.qualifier,
libraries=self.libraries,
region=self.region,
debug=self.debug,
dry=self.dry,
invoke_config=icf,
payload=self.json_payload_file,
invoke_type=self.invoke_type,
profile=self.profile
).create()
PrintMsg.done('Deploying')
def deploy_all(self):
"""
Deploy all functions in path
:return:
"""
for f in self.functions:
f.create()
PrintMsg.done('Deploying all')
@staticmethod
def new(**kwargs):
"""
New function
:param kwargs:
:return:
"""
if 'Path' not in kwargs or not kwargs['Path']:
raise KeyError('path is a Required Argument')
if 'Function' not in kwargs or not kwargs['Function']:
raise KeyError('function is a Required Argument')
PrintMsg.cmd('New lambda function {}.'.format(
kwargs['Function']), 'INITIALIZING', 'yellow')
path = kwargs['Path']
func = kwargs['Function']
kwargs.pop('Path', None)
kwargs.pop('Function', None)
cf = {k: v for k, v in kwargs.items() if v}
cf = Project.merge_config(cf, DEFAULT_CONFIG)
cf = {k: v for k, v in cf.items() if v}
cf_name = os.path.join(path, func) + Project.config_postfix
f_name = os.path.join(path, func) + Project.function_postfix
PrintMsg.creating('Config file {}.'.format(cf_name))
if not os.path.exists(cf_name):
with open(cf_name, 'w') as j:
yaml.safe_dump(cf, j, default_flow_style=False)
PrintMsg.done('Creating config file {}.'.format(cf_name))
else:
PrintMsg.error('Config file already exists.')
PrintMsg.creating('Source file {}'.format(f_name))
if not os.path.exists(f_name):
f = open(f_name, 'w')
f.write(DEFAULT_SOURCE)
f.close()
PrintMsg.done('Creating source file {}.'.format(f_name))
else:
PrintMsg.error('File already exists.')
PrintMsg.done('Creating lambda function {}.'.format(func)) | 0.409103 | 0.069132 |
from django.db import models
from django.db.models.fields import BooleanField
from accounts.models import Account
from store.models import Product, Variation
from righteous.db.models import OrderStatusChoices
# Create your models here.\
class Payment(models.Model):
user = models.ForeignKey(Account, on_delete=models.CASCADE)
payment_id = models.CharField(max_length=100)
payment_method = models.CharField(max_length=100)
amount_paid = models.CharField(max_length=100)
status = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.payment_id
class Order(models.Model):
user = models.ForeignKey(Account, on_delete=models.SET_NULL, null=True)
payment = models.ForeignKey(
Payment, on_delete=models.SET_NULL, null=True, blank=True)
order_number = models.CharField(max_length=50)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
phone = models.CharField(max_length=20)
address_line_1 = models.CharField(max_length=50)
address_line_2 = models.CharField(max_length=50, blank=True)
order_note = models.CharField(max_length=100, blank=True)
order_total = models.FloatField()
status = models.CharField(
max_length=10, choices=OrderStatusChoices.choices, default=OrderStatusChoices.NEW)
ip = models.CharField(max_length=20, blank=True)
is_ordered = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def full_name(self):
return f'{self.last_name} {self.first_name}'
def full_address(self):
return f'{self.address_line_1} {self.address_line_2}'
def get_order_products(self):
return self.orderproduct_set.filter(ordered=True)
def __str__(self):
return self.first_name
class OrderProduct(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
payment = models.ForeignKey(
Payment, on_delete=models.SET_NULL, blank=True, null=True)
user = models.ForeignKey(Account, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
variations = models.ManyToManyField(Variation, blank=True)
quantity = models.SmallIntegerField()
product_price = models.FloatField()
ordered = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.product.product_name | Django/e-commerce-website/orders/models.py | from django.db import models
from django.db.models.fields import BooleanField
from accounts.models import Account
from store.models import Product, Variation
from righteous.db.models import OrderStatusChoices
# Create your models here.\
class Payment(models.Model):
user = models.ForeignKey(Account, on_delete=models.CASCADE)
payment_id = models.CharField(max_length=100)
payment_method = models.CharField(max_length=100)
amount_paid = models.CharField(max_length=100)
status = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.payment_id
class Order(models.Model):
user = models.ForeignKey(Account, on_delete=models.SET_NULL, null=True)
payment = models.ForeignKey(
Payment, on_delete=models.SET_NULL, null=True, blank=True)
order_number = models.CharField(max_length=50)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
phone = models.CharField(max_length=20)
address_line_1 = models.CharField(max_length=50)
address_line_2 = models.CharField(max_length=50, blank=True)
order_note = models.CharField(max_length=100, blank=True)
order_total = models.FloatField()
status = models.CharField(
max_length=10, choices=OrderStatusChoices.choices, default=OrderStatusChoices.NEW)
ip = models.CharField(max_length=20, blank=True)
is_ordered = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def full_name(self):
return f'{self.last_name} {self.first_name}'
def full_address(self):
return f'{self.address_line_1} {self.address_line_2}'
def get_order_products(self):
return self.orderproduct_set.filter(ordered=True)
def __str__(self):
return self.first_name
class OrderProduct(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
payment = models.ForeignKey(
Payment, on_delete=models.SET_NULL, blank=True, null=True)
user = models.ForeignKey(Account, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
variations = models.ManyToManyField(Variation, blank=True)
quantity = models.SmallIntegerField()
product_price = models.FloatField()
ordered = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.product.product_name | 0.643105 | 0.128034 |
import unittest
from lighty.templates import Template
class VariableFieldTestCase(unittest.TestCase):
"""Test case for block template tag
"""
def setUp(self):
self.value = 'value'
self.variable_template = Template(name='base.html')
self.variable_template.parse("{{ simple_var }}")
self.object_field_template = Template(name='object-field.html')
self.object_field_template.parse('{{ object.field }}')
self.deep_template = Template(name='deep-field.html')
self.deep_template.parse('{{ object.field.field }}')
def assertResult(self, result):
assert result == self.value, 'Error emplate execution: %s' % ' '.join((
result, 'except', self.value))
def testSimpleVariable(self):
'''Test simple variable accessing from template'''
result = self.variable_template.execute({'simple_var': 'value'})
self.assertResult(result)
def testObjectField(self):
'''Test object's field accessing from template'''
class TestClass(object):
field = self.value
result = self.object_field_template.execute({'object': TestClass()})
self.assertResult(result)
def testDictValue(self):
'''Test dict item accessing from template'''
obj = {'field': self.value}
result = self.object_field_template.execute({'object': obj})
self.assertResult(result)
def testMultilevelField(self):
'''Test accesing to dict item as object field'''
class TestClass(object):
field = {'field': self.value}
result = self.deep_template.execute({'object': TestClass()})
self.assertResult(result)
def test():
suite = unittest.TestSuite()
suite.addTest(VariableFieldTestCase('testSimpleVariable'))
suite.addTest(VariableFieldTestCase('testObjectField'))
suite.addTest(VariableFieldTestCase('testDictValue'))
suite.addTest(VariableFieldTestCase('testMultilevelField'))
return suite | tests/variable_fields.py | import unittest
from lighty.templates import Template
class VariableFieldTestCase(unittest.TestCase):
"""Test case for block template tag
"""
def setUp(self):
self.value = 'value'
self.variable_template = Template(name='base.html')
self.variable_template.parse("{{ simple_var }}")
self.object_field_template = Template(name='object-field.html')
self.object_field_template.parse('{{ object.field }}')
self.deep_template = Template(name='deep-field.html')
self.deep_template.parse('{{ object.field.field }}')
def assertResult(self, result):
assert result == self.value, 'Error emplate execution: %s' % ' '.join((
result, 'except', self.value))
def testSimpleVariable(self):
'''Test simple variable accessing from template'''
result = self.variable_template.execute({'simple_var': 'value'})
self.assertResult(result)
def testObjectField(self):
'''Test object's field accessing from template'''
class TestClass(object):
field = self.value
result = self.object_field_template.execute({'object': TestClass()})
self.assertResult(result)
def testDictValue(self):
'''Test dict item accessing from template'''
obj = {'field': self.value}
result = self.object_field_template.execute({'object': obj})
self.assertResult(result)
def testMultilevelField(self):
'''Test accesing to dict item as object field'''
class TestClass(object):
field = {'field': self.value}
result = self.deep_template.execute({'object': TestClass()})
self.assertResult(result)
def test():
suite = unittest.TestSuite()
suite.addTest(VariableFieldTestCase('testSimpleVariable'))
suite.addTest(VariableFieldTestCase('testObjectField'))
suite.addTest(VariableFieldTestCase('testDictValue'))
suite.addTest(VariableFieldTestCase('testMultilevelField'))
return suite | 0.568895 | 0.386792 |
## Copyright 2009-2021 Intel Corporation
## SPDX-License-Identifier: Apache-2.0
import sys
import shutil
from glob import glob
from shutil import which
import argparse
from common import *
MODEL_VERSION='v1.4.0'
# Parse the command-line arguments
parser = argparse.ArgumentParser(description='Runs all tests, including comparing images produced by the library with generated baseline images.')
parser.usage = '\rIntel(R) Open Image Denoise - Test\n' + parser.format_usage()
parser.add_argument('command', type=str, nargs='?', choices=['baseline', 'run'], default='run')
parser.add_argument('--filter', '-f', type=str, nargs='*', choices=['RT', 'RTLightmap'], default=None, help='filters to test')
parser.add_argument('--build_dir', '-B', type=str, help='build directory')
parser.add_argument('--data_dir', '-D', type=str, help='directory of datasets (e.g. training, validation, test)')
parser.add_argument('--results_dir', '-R', type=str, help='directory of training results')
parser.add_argument('--baseline_dir', '-G', type=str, help='directory of generated baseline images')
parser.add_argument('--arch', '-a', type=str, nargs='*', choices=['native', 'pnr', 'hsw', 'skx', 'knl'], default=['native'], help='CPU architectures to test (requires Intel SDE)')
parser.add_argument('--log', '-l', type=str, default=os.path.join(root_dir, 'test.log'), help='output log file')
cfg = parser.parse_args()
training_dir = os.environ.get('OIDN_TRAINING_DIR_' + OS.upper())
if training_dir is None:
training_dir = os.path.join(root_dir, 'training')
if cfg.data_dir is None:
cfg.data_dir = os.path.join(training_dir, 'data')
if cfg.results_dir is None:
cfg.results_dir = os.path.join(training_dir, 'results')
if cfg.baseline_dir is None:
cfg.baseline_dir = os.path.join(training_dir, 'baseline_' + MODEL_VERSION)
if cfg.command == 'run':
# Detect the OIDN binary directory
if cfg.build_dir is None:
cfg.build_dir = os.path.join(root_dir, 'build')
else:
cfg.build_dir = os.path.abspath(cfg.build_dir)
bin_dir = os.path.join(cfg.build_dir, 'install', 'bin')
if not os.path.isdir(bin_dir):
bin_dir = os.path.join(root_dir, 'build')
# Detect the Intel(R) Software Development Emulator (SDE)
# See: https://software.intel.com/en-us/articles/intel-software-development-emulator
sde = 'sde.exe' if OS == 'windows' else 'sde64'
sde_dir = os.environ.get('OIDN_SDE_DIR_' + OS.upper())
if sde_dir is not None:
sde = os.path.join(sde_dir, sde)
# Prints the name of a test
def print_test(name, kind='Test'):
print(kind + ':', name, '...', end='', flush=True)
# Runs a test command
def run_test(cmd, arch='native'):
# Run test through SDE if required
if arch != 'native':
cmd = f'{sde} -{arch} -- ' + cmd
# Write command and redirect output to log
run(f'echo >> "{cfg.log}"')
run(f'echo "{cmd}" >> "{cfg.log}"')
cmd += f' >> "{cfg.log}" 2>&1'
# Run the command and check the return value
if os.system(cmd) == 0:
print(' PASSED')
else:
print(' FAILED')
print(f'Error: test failed, see "{cfg.log}" for details')
exit(1)
# Runs main tests
def test():
if cfg.command == 'run':
# Iterate over architectures
for arch in cfg.arch:
print_test(f'oidnTest.{arch}')
run_test(os.path.join(bin_dir, 'oidnTest'), arch)
# Gets the option name of a feature
def get_feature_opt(feature):
if feature == 'calb':
return 'alb'
elif feature == 'cnrm':
return 'nrm'
else:
return feature
# Gets the file extension of a feature
def get_feature_ext(feature):
if feature == 'dir':
return 'sh1x'
else:
return get_feature_opt(feature)
# Runs regression tests for the specified filter
def test_regression(filter, feature_sets, dataset):
dataset_dir = os.path.join(cfg.data_dir, dataset)
# Convert the input images to PFM
if cfg.command == 'baseline':
image_filenames = sorted(glob(os.path.join(dataset_dir, '**', '*.exr'), recursive=True))
for input_filename in image_filenames:
input_name = os.path.relpath(input_filename, dataset_dir).rsplit('.', 1)[0]
print_test(f'{filter}.{input_name}', 'Convert')
output_filename = input_filename.rsplit('.', 1)[0] + '.pfm'
convert_cmd = os.path.join(root_dir, 'training', 'convert_image.py')
convert_cmd += f' "{input_filename}" "{output_filename}"'
run_test(convert_cmd)
# Iterate over the feature sets
for features, full_test in feature_sets:
# Get the result name
result = filter.lower()
for f in features:
result += '_' + f
features_str = result.split('_', 1)[1]
if cfg.command == 'baseline':
# Generate the baseline images
print_test(f'{filter}.{features_str}', 'Infer')
infer_cmd = os.path.join(root_dir, 'training', 'infer.py')
infer_cmd += f' -D "{cfg.data_dir}" -R "{cfg.results_dir}" -O "{cfg.baseline_dir}" -i {dataset} -r {result} -F pfm -d cpu'
run_test(infer_cmd)
elif cfg.command == 'run':
main_feature = features[0]
main_feature_ext = get_feature_ext(main_feature)
# Gather the list of images
image_filenames = sorted(glob(os.path.join(dataset_dir, '**', f'*.{main_feature_ext}.pfm'), recursive=True))
if not image_filenames:
print('Error: baseline input images missing (run with "baseline" first)')
exit(1)
image_names = [os.path.relpath(filename, dataset_dir).rsplit('.', 3)[0] for filename in image_filenames]
# Iterate over architectures
for arch in cfg.arch:
# Iterate over images
for image_name in image_names:
# Iterate over in-place mode
for inplace in ([False, True] if full_test else [False]):
# Run test
test_name = f'{filter}.{features_str}.{arch}.{image_name}'
if inplace:
test_name += '.inplace'
print_test(test_name)
denoise_cmd = os.path.join(bin_dir, 'oidnDenoise')
ref_filename = os.path.join(cfg.baseline_dir, dataset, f'{image_name}.{result}.{main_feature_ext}.pfm')
if not os.path.isfile(ref_filename):
print('Error: baseline output image missing (run with "baseline" first)')
exit(1)
denoise_cmd += f' -f {filter} -v 2 --ref "{ref_filename}"'
for feature in features:
feature_opt = get_feature_opt(feature)
feature_ext = get_feature_ext(feature)
feature_filename = os.path.join(dataset_dir, image_name) + f'.{feature_ext}.pfm'
denoise_cmd += f' --{feature_opt} "{feature_filename}"'
if set(features) & {'calb', 'cnrm'}:
denoise_cmd += ' --clean_aux'
if inplace:
denoise_cmd += ' --inplace'
run_test(denoise_cmd, arch)
# Main tests
test()
# Regression tests: RT
if not cfg.filter or 'RT' in cfg.filter:
test_regression(
'RT',
[
(['hdr', 'alb', 'nrm'], True),
(['hdr', 'alb'], True),
(['hdr'], True),
(['hdr', 'calb', 'cnrm'], False),
(['ldr', 'alb', 'nrm'], False),
(['ldr', 'alb'], False),
(['ldr'], True),
(['ldr', 'calb', 'cnrm'], False),
(['alb'], True),
(['nrm'], True)
],
'rt_regress'
)
# Regression tests: RTLightmap
if not cfg.filter or 'RTLightmap' in cfg.filter:
test_regression(
'RTLightmap',
[
(['hdr'], True),
(['dir'], True)
],
'rtlightmap_regress'
)
# Done
if cfg.command == 'run':
print('Success: all tests passed') | scripts/test.py |
## Copyright 2009-2021 Intel Corporation
## SPDX-License-Identifier: Apache-2.0
import sys
import shutil
from glob import glob
from shutil import which
import argparse
from common import *
MODEL_VERSION='v1.4.0'
# Parse the command-line arguments
parser = argparse.ArgumentParser(description='Runs all tests, including comparing images produced by the library with generated baseline images.')
parser.usage = '\rIntel(R) Open Image Denoise - Test\n' + parser.format_usage()
parser.add_argument('command', type=str, nargs='?', choices=['baseline', 'run'], default='run')
parser.add_argument('--filter', '-f', type=str, nargs='*', choices=['RT', 'RTLightmap'], default=None, help='filters to test')
parser.add_argument('--build_dir', '-B', type=str, help='build directory')
parser.add_argument('--data_dir', '-D', type=str, help='directory of datasets (e.g. training, validation, test)')
parser.add_argument('--results_dir', '-R', type=str, help='directory of training results')
parser.add_argument('--baseline_dir', '-G', type=str, help='directory of generated baseline images')
parser.add_argument('--arch', '-a', type=str, nargs='*', choices=['native', 'pnr', 'hsw', 'skx', 'knl'], default=['native'], help='CPU architectures to test (requires Intel SDE)')
parser.add_argument('--log', '-l', type=str, default=os.path.join(root_dir, 'test.log'), help='output log file')
cfg = parser.parse_args()
training_dir = os.environ.get('OIDN_TRAINING_DIR_' + OS.upper())
if training_dir is None:
training_dir = os.path.join(root_dir, 'training')
if cfg.data_dir is None:
cfg.data_dir = os.path.join(training_dir, 'data')
if cfg.results_dir is None:
cfg.results_dir = os.path.join(training_dir, 'results')
if cfg.baseline_dir is None:
cfg.baseline_dir = os.path.join(training_dir, 'baseline_' + MODEL_VERSION)
if cfg.command == 'run':
# Detect the OIDN binary directory
if cfg.build_dir is None:
cfg.build_dir = os.path.join(root_dir, 'build')
else:
cfg.build_dir = os.path.abspath(cfg.build_dir)
bin_dir = os.path.join(cfg.build_dir, 'install', 'bin')
if not os.path.isdir(bin_dir):
bin_dir = os.path.join(root_dir, 'build')
# Detect the Intel(R) Software Development Emulator (SDE)
# See: https://software.intel.com/en-us/articles/intel-software-development-emulator
sde = 'sde.exe' if OS == 'windows' else 'sde64'
sde_dir = os.environ.get('OIDN_SDE_DIR_' + OS.upper())
if sde_dir is not None:
sde = os.path.join(sde_dir, sde)
# Prints the name of a test
def print_test(name, kind='Test'):
print(kind + ':', name, '...', end='', flush=True)
# Runs a test command
def run_test(cmd, arch='native'):
# Run test through SDE if required
if arch != 'native':
cmd = f'{sde} -{arch} -- ' + cmd
# Write command and redirect output to log
run(f'echo >> "{cfg.log}"')
run(f'echo "{cmd}" >> "{cfg.log}"')
cmd += f' >> "{cfg.log}" 2>&1'
# Run the command and check the return value
if os.system(cmd) == 0:
print(' PASSED')
else:
print(' FAILED')
print(f'Error: test failed, see "{cfg.log}" for details')
exit(1)
# Runs main tests
def test():
if cfg.command == 'run':
# Iterate over architectures
for arch in cfg.arch:
print_test(f'oidnTest.{arch}')
run_test(os.path.join(bin_dir, 'oidnTest'), arch)
# Gets the option name of a feature
def get_feature_opt(feature):
if feature == 'calb':
return 'alb'
elif feature == 'cnrm':
return 'nrm'
else:
return feature
# Gets the file extension of a feature
def get_feature_ext(feature):
if feature == 'dir':
return 'sh1x'
else:
return get_feature_opt(feature)
# Runs regression tests for the specified filter
def test_regression(filter, feature_sets, dataset):
dataset_dir = os.path.join(cfg.data_dir, dataset)
# Convert the input images to PFM
if cfg.command == 'baseline':
image_filenames = sorted(glob(os.path.join(dataset_dir, '**', '*.exr'), recursive=True))
for input_filename in image_filenames:
input_name = os.path.relpath(input_filename, dataset_dir).rsplit('.', 1)[0]
print_test(f'{filter}.{input_name}', 'Convert')
output_filename = input_filename.rsplit('.', 1)[0] + '.pfm'
convert_cmd = os.path.join(root_dir, 'training', 'convert_image.py')
convert_cmd += f' "{input_filename}" "{output_filename}"'
run_test(convert_cmd)
# Iterate over the feature sets
for features, full_test in feature_sets:
# Get the result name
result = filter.lower()
for f in features:
result += '_' + f
features_str = result.split('_', 1)[1]
if cfg.command == 'baseline':
# Generate the baseline images
print_test(f'{filter}.{features_str}', 'Infer')
infer_cmd = os.path.join(root_dir, 'training', 'infer.py')
infer_cmd += f' -D "{cfg.data_dir}" -R "{cfg.results_dir}" -O "{cfg.baseline_dir}" -i {dataset} -r {result} -F pfm -d cpu'
run_test(infer_cmd)
elif cfg.command == 'run':
main_feature = features[0]
main_feature_ext = get_feature_ext(main_feature)
# Gather the list of images
image_filenames = sorted(glob(os.path.join(dataset_dir, '**', f'*.{main_feature_ext}.pfm'), recursive=True))
if not image_filenames:
print('Error: baseline input images missing (run with "baseline" first)')
exit(1)
image_names = [os.path.relpath(filename, dataset_dir).rsplit('.', 3)[0] for filename in image_filenames]
# Iterate over architectures
for arch in cfg.arch:
# Iterate over images
for image_name in image_names:
# Iterate over in-place mode
for inplace in ([False, True] if full_test else [False]):
# Run test
test_name = f'{filter}.{features_str}.{arch}.{image_name}'
if inplace:
test_name += '.inplace'
print_test(test_name)
denoise_cmd = os.path.join(bin_dir, 'oidnDenoise')
ref_filename = os.path.join(cfg.baseline_dir, dataset, f'{image_name}.{result}.{main_feature_ext}.pfm')
if not os.path.isfile(ref_filename):
print('Error: baseline output image missing (run with "baseline" first)')
exit(1)
denoise_cmd += f' -f {filter} -v 2 --ref "{ref_filename}"'
for feature in features:
feature_opt = get_feature_opt(feature)
feature_ext = get_feature_ext(feature)
feature_filename = os.path.join(dataset_dir, image_name) + f'.{feature_ext}.pfm'
denoise_cmd += f' --{feature_opt} "{feature_filename}"'
if set(features) & {'calb', 'cnrm'}:
denoise_cmd += ' --clean_aux'
if inplace:
denoise_cmd += ' --inplace'
run_test(denoise_cmd, arch)
# Main tests
test()
# Regression tests: RT
if not cfg.filter or 'RT' in cfg.filter:
test_regression(
'RT',
[
(['hdr', 'alb', 'nrm'], True),
(['hdr', 'alb'], True),
(['hdr'], True),
(['hdr', 'calb', 'cnrm'], False),
(['ldr', 'alb', 'nrm'], False),
(['ldr', 'alb'], False),
(['ldr'], True),
(['ldr', 'calb', 'cnrm'], False),
(['alb'], True),
(['nrm'], True)
],
'rt_regress'
)
# Regression tests: RTLightmap
if not cfg.filter or 'RTLightmap' in cfg.filter:
test_regression(
'RTLightmap',
[
(['hdr'], True),
(['dir'], True)
],
'rtlightmap_regress'
)
# Done
if cfg.command == 'run':
print('Success: all tests passed') | 0.430028 | 0.110856 |
import base64
import datetime
import hmac
import logging
import random
import sys
import time
from hashlib import sha1
import requests
from six.moves import urllib
from lexicon.exceptions import AuthenticationError
from lexicon.providers.base import Provider as BaseProvider
LOGGER = logging.getLogger(__name__)
NAMESERVER_DOMAINS = ["hichina.com"]
ALIYUN_DNS_API_ENDPOINT = "https://alidns.aliyuncs.com"
def provider_parser(subparser):
"""Module provider for Aliyun"""
subparser.description = """
Aliyun Provider requires an access key id and access secret with full rights on dns.
Better to use RAM on Aliyun cloud to create a specified user for the dns operation.
The referrence for Aliyun DNS production:
https://help.aliyun.com/product/29697.html"""
subparser.add_argument(
"--auth-key-id", help="specify access key id for authentication"
)
subparser.add_argument(
"--auth-secret", help="specify access secret for authentication"
)
class Provider(BaseProvider):
"""Provider class for Aliyun"""
def _authenticate(self):
response = self._request_aliyun("DescribeDomainInfo")
if "DomainId" not in response:
raise AuthenticationError(
f"failed to fetch basic domain info for {self.domain}"
)
self.domain_id = response["DomainId"]
return self
def _create_record(self, rtype, name, content):
if not self._list_records(rtype, name, content):
query_params = {
"Value": content,
"Type": rtype,
"RR": self._relative_name(name),
"TTL": self._get_lexicon_option("ttl"),
}
self._request_aliyun("AddDomainRecord", query_params=query_params)
return True
# List all records. Return an empty list if no records found
# type, name and content are used to filter records.
# If possible filter during the query, otherwise filter after response is received.
def _list_records(self, rtype=None, name=None, content=None):
query_params = {}
if rtype:
query_params["TypeKeyWord"] = rtype
if name:
query_params["RRKeyWord"] = self._relative_name(name)
if content:
query_params["ValueKeyWord"] = content
response = self._request_aliyun(
"DescribeDomainRecords", query_params=query_params
)
resource_list = response["DomainRecords"]["Record"]
processed_records = []
for resource in resource_list:
processed_records.append(
{
"id": resource["RecordId"],
"type": resource["Type"],
"name": self._full_name(resource["RR"]),
"ttl": resource["TTL"],
"content": resource["Value"],
}
)
LOGGER.debug("list_records: %s", processed_records)
return processed_records
# Create or update a record.
def _update_record(self, identifier, rtype=None, name=None, content=None):
resources = self._list_records(rtype, name, None)
for record in resources:
if (
rtype == record["type"]
and (self._relative_name(name) == self._relative_name(record["name"]))
and (content == record["content"])
):
return True
if not identifier:
record = resources[0] if resources else None
identifier = record["id"] if record else None
if not identifier:
raise ValueError(f"updating {identifier} identifier not exists")
if len(resources) > 1:
LOGGER.warning(
"""There's more than one records match the given critiaria,
only the first one would be updated"""
)
LOGGER.debug("update_record: %s", identifier)
query_params = {"RecordId": identifier}
if rtype:
query_params["Type"] = rtype
if name:
query_params["RR"] = self._relative_name(name)
if content:
query_params["Value"] = content
query_params["TTL"] = self._get_lexicon_option("ttl")
self._request_aliyun("UpdateDomainRecord", query_params=query_params)
return True
# Delete an existing record.
# If record does not exist, do nothing.
def _delete_record(self, identifier=None, rtype=None, name=None, content=None):
delete_resource_id = []
if not identifier:
resources = self._list_records(rtype, name, content)
delete_resource_id = [resource["id"] for resource in resources]
else:
delete_resource_id.append(identifier)
LOGGER.debug("delete_records: %s", delete_resource_id)
for resource_id in delete_resource_id:
self._request_aliyun(
"DeleteDomainRecord", query_params={"RecordId": resource_id}
)
return True
def _request(self, action="GET", url="/", data=None, query_params=None):
response = requests.request("GET", ALIYUN_DNS_API_ENDPOINT, params=query_params)
response.raise_for_status()
try:
return response.json()
except ValueError as invalid_json_ve:
LOGGER.error(
"aliyun dns api responsed with invalid json content, %s", response.text
)
raise invalid_json_ve
def _request_aliyun(self, action, query_params=None):
if query_params is None:
query_params = {}
query_params.update(self._build_default_query_params(action))
query_params.update(self._build_signature_parameters())
query_params.update(
{"Signature": self._calculate_signature("GET", query_params)}
)
return self._request(url=ALIYUN_DNS_API_ENDPOINT, query_params=query_params)
def _calculate_signature(self, http_method, query_params):
access_secret = self._get_provider_option("auth_secret")
if not access_secret:
raise ValueError(
"auth-secret (access secret) is not specified, did you forget that?"
)
sign_secret = access_secret + "&"
query_list = list(query_params.items())
query_list.sort(key=lambda t: t[0])
canonicalized_query_string = urllib.parse.urlencode(query_list)
string_to_sign = "&".join(
[
http_method,
urllib.parse.quote_plus("/"),
urllib.parse.quote_plus(canonicalized_query_string),
]
)
if sys.version_info.major > 2:
sign_secret_bytes = bytes(sign_secret, "utf-8")
string_to_sign_bytes = bytes(string_to_sign, "utf-8")
sign = hmac.new(sign_secret_bytes, string_to_sign_bytes, sha1)
signature = base64.b64encode(sign.digest()).decode()
else:
sign = hmac.new(sign_secret, string_to_sign, sha1)
signature = sign.digest().encode("base64").rstrip("\n")
return signature
def _build_signature_parameters(self):
access_key_id = self._get_provider_option("auth_key_id")
if not access_key_id:
raise ValueError(
"auth-key-id (access key id) is not specified, did you forget that?"
)
signature_nonce = str(int(time.time())) + str(random.randint(1000, 9999))
return {
"SignatureMethod": "HMAC-SHA1",
"SignatureVersion": "1.0",
"SignatureNonce": signature_nonce,
"Timestamp": datetime.datetime.utcnow().replace(microsecond=0).isoformat()
+ "Z",
"AccessKeyId": access_key_id,
}
def _build_default_query_params(self, action):
return {
"Action": action,
"DomainName": self.domain,
"Format": "json",
"Version": "2015-01-09",
} | lexicon/providers/aliyun.py | import base64
import datetime
import hmac
import logging
import random
import sys
import time
from hashlib import sha1
import requests
from six.moves import urllib
from lexicon.exceptions import AuthenticationError
from lexicon.providers.base import Provider as BaseProvider
LOGGER = logging.getLogger(__name__)
NAMESERVER_DOMAINS = ["hichina.com"]
ALIYUN_DNS_API_ENDPOINT = "https://alidns.aliyuncs.com"
def provider_parser(subparser):
"""Module provider for Aliyun"""
subparser.description = """
Aliyun Provider requires an access key id and access secret with full rights on dns.
Better to use RAM on Aliyun cloud to create a specified user for the dns operation.
The referrence for Aliyun DNS production:
https://help.aliyun.com/product/29697.html"""
subparser.add_argument(
"--auth-key-id", help="specify access key id for authentication"
)
subparser.add_argument(
"--auth-secret", help="specify access secret for authentication"
)
class Provider(BaseProvider):
"""Provider class for Aliyun"""
def _authenticate(self):
response = self._request_aliyun("DescribeDomainInfo")
if "DomainId" not in response:
raise AuthenticationError(
f"failed to fetch basic domain info for {self.domain}"
)
self.domain_id = response["DomainId"]
return self
def _create_record(self, rtype, name, content):
if not self._list_records(rtype, name, content):
query_params = {
"Value": content,
"Type": rtype,
"RR": self._relative_name(name),
"TTL": self._get_lexicon_option("ttl"),
}
self._request_aliyun("AddDomainRecord", query_params=query_params)
return True
# List all records. Return an empty list if no records found
# type, name and content are used to filter records.
# If possible filter during the query, otherwise filter after response is received.
def _list_records(self, rtype=None, name=None, content=None):
query_params = {}
if rtype:
query_params["TypeKeyWord"] = rtype
if name:
query_params["RRKeyWord"] = self._relative_name(name)
if content:
query_params["ValueKeyWord"] = content
response = self._request_aliyun(
"DescribeDomainRecords", query_params=query_params
)
resource_list = response["DomainRecords"]["Record"]
processed_records = []
for resource in resource_list:
processed_records.append(
{
"id": resource["RecordId"],
"type": resource["Type"],
"name": self._full_name(resource["RR"]),
"ttl": resource["TTL"],
"content": resource["Value"],
}
)
LOGGER.debug("list_records: %s", processed_records)
return processed_records
# Create or update a record.
def _update_record(self, identifier, rtype=None, name=None, content=None):
resources = self._list_records(rtype, name, None)
for record in resources:
if (
rtype == record["type"]
and (self._relative_name(name) == self._relative_name(record["name"]))
and (content == record["content"])
):
return True
if not identifier:
record = resources[0] if resources else None
identifier = record["id"] if record else None
if not identifier:
raise ValueError(f"updating {identifier} identifier not exists")
if len(resources) > 1:
LOGGER.warning(
"""There's more than one records match the given critiaria,
only the first one would be updated"""
)
LOGGER.debug("update_record: %s", identifier)
query_params = {"RecordId": identifier}
if rtype:
query_params["Type"] = rtype
if name:
query_params["RR"] = self._relative_name(name)
if content:
query_params["Value"] = content
query_params["TTL"] = self._get_lexicon_option("ttl")
self._request_aliyun("UpdateDomainRecord", query_params=query_params)
return True
# Delete an existing record.
# If record does not exist, do nothing.
def _delete_record(self, identifier=None, rtype=None, name=None, content=None):
delete_resource_id = []
if not identifier:
resources = self._list_records(rtype, name, content)
delete_resource_id = [resource["id"] for resource in resources]
else:
delete_resource_id.append(identifier)
LOGGER.debug("delete_records: %s", delete_resource_id)
for resource_id in delete_resource_id:
self._request_aliyun(
"DeleteDomainRecord", query_params={"RecordId": resource_id}
)
return True
def _request(self, action="GET", url="/", data=None, query_params=None):
response = requests.request("GET", ALIYUN_DNS_API_ENDPOINT, params=query_params)
response.raise_for_status()
try:
return response.json()
except ValueError as invalid_json_ve:
LOGGER.error(
"aliyun dns api responsed with invalid json content, %s", response.text
)
raise invalid_json_ve
def _request_aliyun(self, action, query_params=None):
if query_params is None:
query_params = {}
query_params.update(self._build_default_query_params(action))
query_params.update(self._build_signature_parameters())
query_params.update(
{"Signature": self._calculate_signature("GET", query_params)}
)
return self._request(url=ALIYUN_DNS_API_ENDPOINT, query_params=query_params)
def _calculate_signature(self, http_method, query_params):
access_secret = self._get_provider_option("auth_secret")
if not access_secret:
raise ValueError(
"auth-secret (access secret) is not specified, did you forget that?"
)
sign_secret = access_secret + "&"
query_list = list(query_params.items())
query_list.sort(key=lambda t: t[0])
canonicalized_query_string = urllib.parse.urlencode(query_list)
string_to_sign = "&".join(
[
http_method,
urllib.parse.quote_plus("/"),
urllib.parse.quote_plus(canonicalized_query_string),
]
)
if sys.version_info.major > 2:
sign_secret_bytes = bytes(sign_secret, "utf-8")
string_to_sign_bytes = bytes(string_to_sign, "utf-8")
sign = hmac.new(sign_secret_bytes, string_to_sign_bytes, sha1)
signature = base64.b64encode(sign.digest()).decode()
else:
sign = hmac.new(sign_secret, string_to_sign, sha1)
signature = sign.digest().encode("base64").rstrip("\n")
return signature
def _build_signature_parameters(self):
access_key_id = self._get_provider_option("auth_key_id")
if not access_key_id:
raise ValueError(
"auth-key-id (access key id) is not specified, did you forget that?"
)
signature_nonce = str(int(time.time())) + str(random.randint(1000, 9999))
return {
"SignatureMethod": "HMAC-SHA1",
"SignatureVersion": "1.0",
"SignatureNonce": signature_nonce,
"Timestamp": datetime.datetime.utcnow().replace(microsecond=0).isoformat()
+ "Z",
"AccessKeyId": access_key_id,
}
def _build_default_query_params(self, action):
return {
"Action": action,
"DomainName": self.domain,
"Format": "json",
"Version": "2015-01-09",
} | 0.446495 | 0.100746 |
import pymysql
import sqlite3
import os, sys
from pymilvusdm.setting import MILVUS_TB, MILVUS_TBF, METRIC_DIC
class ReadMilvusMeta():
def __init__(self, logger, milvus_dir, mysql_p=None):
self.logger = logger
self.conn = None
self.cursor = None
if mysql_p:
self.connect_mysql(mysql_p['host'], mysql_p['user'], mysql_p['port'], mysql_p['password'], mysql_p['database'])
else:
self.connect_sqlite(milvus_dir + '/db')
def connect_mysql(self, host, user, port, password, database):
try:
self.conn = pymysql.connect(host=host, user=user, port=port, password=password, database=database, local_infile=True)
self.cursor = self.conn.cursor()
self.logger.debug("Successfully connect mysql")
except Exception as e:
self.logger.error("MYSQL ERROR: connect failed with {}".format(e))
sys.exit(1)
def connect_sqlite(self, milvus_collection_path):
try:
self.conn = sqlite3.connect(milvus_collection_path + '/meta.sqlite')
self.cursor = self.conn.cursor()
self.logger.debug("Successfully connect sqlite")
except Exception as e:
self.logger.error("SQLite ERROR: connect failed with {}".format(e))
sys.exit(1)
def has_collection_meta(self, collection_name):
sql = "select * from " + MILVUS_TB + " where table_id='" + collection_name + "';"
try:
self.cursor.execute(sql)
results = self.cursor.fetchall()
if not results:
return None
return results
except Exception as e:
self.logger.error("META DATA ERROR: {} with sql: {}".format(e, sql))
sys.exit(1)
def get_all_partition_tag(self, collection_name):
sql = "select partition_tag from " + MILVUS_TB + " where owner_table='" + collection_name + "';"
try:
self.cursor.execute(sql)
results = self.cursor.fetchall()
if results:
results = [re[0] for re in results]
else:
results = []
self.logger.debug("Get all partition tag:{}".format(results))
return results
except Exception as e:
self.logger.error("META DATA ERROR: {} with sql: {}".format(e, sql))
sys.exit(1)
def get_collection_info(self, collection_name):
sql = "select dimension, index_file_size, metric_type, version from " + MILVUS_TB + " where table_id='" + collection_name + "';"
try:
self.cursor.execute(sql)
results = self.cursor.fetchall()
collection_parameter = {
"dimension": int(results[0][0]),
"index_file_size": int(int(results[0][1])/1024/1024),
"metric_type": METRIC_DIC[results[0][2]]
}
self.logger.debug("Get collection info(dimension, index_file_size, metric_type, version):{}".format(results))
return collection_parameter, results[0][3]
except Exception as e:
self.logger.error("META DATA ERROR: {} with sql: {}".format(e, sql))
sys.exit(1)
def get_partition_name(self, collection_name, partition_tag):
sql = "select table_id from " + MILVUS_TB + " where owner_table='" + collection_name + "' and partition_tag = '" + partition_tag + "';"
try:
self.cursor.execute(sql)
results = self.cursor.fetchall()
if not results:
raise Exception("The source collection: {}/ partition_tag: {} does not exists.".format(collection_name, partition_tag))
self.logger.debug("Get partition name: {}".format(results))
return results[0][0]
except Exception as e:
self.logger.error("META DATA ERROR: {} with sql: {}".format(e, sql))
sys.exit(1)
def get_collection_dim_type(self, table_id):
sql = "select dimension, engine_type from " + MILVUS_TB + " where table_id='" + table_id + "';"
try:
self.cursor.execute(sql)
results = self.cursor.fetchall()
self.logger.debug("Get meta data about dimension and types: {}".format(results))
return results[0][0], results[0][1]
except Exception as e:
self.logger.error("META DATA ERROR: {} with sql: {}".format(e, sql))
sys.exit(1)
def get_collection_segments_rows(self, table_id):
sql = "select segment_id, row_count from " + MILVUS_TBF + " where table_id='" + table_id + "' and file_type=1;"
try:
self.cursor.execute(sql)
results = self.cursor.fetchall()
segments = [re[0] for re in results]
rows = [re[1] for re in results]
self.logger.debug("Get meta data about segment and rows: {}".format(results))
return segments, rows
except Exception as e:
self.logger.error("META DATA ERROR: {} with sql: {}".format(e, sql))
sys.exit(1) | pymilvusdm/core/read_milvus_meta.py | import pymysql
import sqlite3
import os, sys
from pymilvusdm.setting import MILVUS_TB, MILVUS_TBF, METRIC_DIC
class ReadMilvusMeta():
def __init__(self, logger, milvus_dir, mysql_p=None):
self.logger = logger
self.conn = None
self.cursor = None
if mysql_p:
self.connect_mysql(mysql_p['host'], mysql_p['user'], mysql_p['port'], mysql_p['password'], mysql_p['database'])
else:
self.connect_sqlite(milvus_dir + '/db')
def connect_mysql(self, host, user, port, password, database):
try:
self.conn = pymysql.connect(host=host, user=user, port=port, password=password, database=database, local_infile=True)
self.cursor = self.conn.cursor()
self.logger.debug("Successfully connect mysql")
except Exception as e:
self.logger.error("MYSQL ERROR: connect failed with {}".format(e))
sys.exit(1)
def connect_sqlite(self, milvus_collection_path):
try:
self.conn = sqlite3.connect(milvus_collection_path + '/meta.sqlite')
self.cursor = self.conn.cursor()
self.logger.debug("Successfully connect sqlite")
except Exception as e:
self.logger.error("SQLite ERROR: connect failed with {}".format(e))
sys.exit(1)
def has_collection_meta(self, collection_name):
sql = "select * from " + MILVUS_TB + " where table_id='" + collection_name + "';"
try:
self.cursor.execute(sql)
results = self.cursor.fetchall()
if not results:
return None
return results
except Exception as e:
self.logger.error("META DATA ERROR: {} with sql: {}".format(e, sql))
sys.exit(1)
def get_all_partition_tag(self, collection_name):
sql = "select partition_tag from " + MILVUS_TB + " where owner_table='" + collection_name + "';"
try:
self.cursor.execute(sql)
results = self.cursor.fetchall()
if results:
results = [re[0] for re in results]
else:
results = []
self.logger.debug("Get all partition tag:{}".format(results))
return results
except Exception as e:
self.logger.error("META DATA ERROR: {} with sql: {}".format(e, sql))
sys.exit(1)
def get_collection_info(self, collection_name):
sql = "select dimension, index_file_size, metric_type, version from " + MILVUS_TB + " where table_id='" + collection_name + "';"
try:
self.cursor.execute(sql)
results = self.cursor.fetchall()
collection_parameter = {
"dimension": int(results[0][0]),
"index_file_size": int(int(results[0][1])/1024/1024),
"metric_type": METRIC_DIC[results[0][2]]
}
self.logger.debug("Get collection info(dimension, index_file_size, metric_type, version):{}".format(results))
return collection_parameter, results[0][3]
except Exception as e:
self.logger.error("META DATA ERROR: {} with sql: {}".format(e, sql))
sys.exit(1)
def get_partition_name(self, collection_name, partition_tag):
sql = "select table_id from " + MILVUS_TB + " where owner_table='" + collection_name + "' and partition_tag = '" + partition_tag + "';"
try:
self.cursor.execute(sql)
results = self.cursor.fetchall()
if not results:
raise Exception("The source collection: {}/ partition_tag: {} does not exists.".format(collection_name, partition_tag))
self.logger.debug("Get partition name: {}".format(results))
return results[0][0]
except Exception as e:
self.logger.error("META DATA ERROR: {} with sql: {}".format(e, sql))
sys.exit(1)
def get_collection_dim_type(self, table_id):
sql = "select dimension, engine_type from " + MILVUS_TB + " where table_id='" + table_id + "';"
try:
self.cursor.execute(sql)
results = self.cursor.fetchall()
self.logger.debug("Get meta data about dimension and types: {}".format(results))
return results[0][0], results[0][1]
except Exception as e:
self.logger.error("META DATA ERROR: {} with sql: {}".format(e, sql))
sys.exit(1)
def get_collection_segments_rows(self, table_id):
sql = "select segment_id, row_count from " + MILVUS_TBF + " where table_id='" + table_id + "' and file_type=1;"
try:
self.cursor.execute(sql)
results = self.cursor.fetchall()
segments = [re[0] for re in results]
rows = [re[1] for re in results]
self.logger.debug("Get meta data about segment and rows: {}".format(results))
return segments, rows
except Exception as e:
self.logger.error("META DATA ERROR: {} with sql: {}".format(e, sql))
sys.exit(1) | 0.181553 | 0.127245 |
""" Character Error Ratio (CER) metric. """
from typing import List
import jiwer
import jiwer.transforms as tr
import datasets
class SentencesToListOfCharacters(tr.AbstractTransform):
def process_string(self, s: str):
return list(s)
def process_list(self, inp: List[str]):
chars = []
for sentence in inp:
chars.extend(self.process_string(sentence))
return chars
cer_transform = tr.Compose(
[
tr.RemoveMultipleSpaces(),
tr.Strip(),
SentencesToListOfCharacters(),
]
)
_CITATION = """\
@inproceedings{inproceedings,
author = {<NAME> Maier, Viktoria and <NAME>},
year = {2004},
month = {01},
pages = {},
title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}
}
"""
_DESCRIPTION = """\
Character error rate (CER) is a common metric of the performance of an automatic speech recognition system.
CER is similar to Word Error Rate (WER), but operate on character insted of word. Please refer to docs of WER for further information.
Character error rate can be computed as:
CER = (S + D + I) / N = (S + D + I) / (S + D + C)
where
S is the number of substitutions,
D is the number of deletions,
I is the number of insertions,
C is the number of correct characters,
N is the number of characters in the reference (N=S+D+C).
CER's output is always a number between 0 and 1. This value indicates the percentage of characters that were incorrectly predicted. The lower the value, the better the
performance of the ASR system with a CER of 0 being a perfect score.
"""
_KWARGS_DESCRIPTION = """
Computes CER score of transcribed segments against references.
Args:
references: list of references for each speech input.
predictions: list of transcribtions to score.
concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.
Returns:
(float): the character error rate
Examples:
>>> predictions = ["this is the prediction", "there is an other sample"]
>>> references = ["this is the reference", "there is another one"]
>>> cer = datasets.load_metric("cer")
>>> cer_score = cer.compute(predictions=predictions, references=references)
>>> print(cer_score)
0.34146341463414637
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)
class CER(datasets.Metric):
def _info(self):
return datasets.MetricInfo(
description=_DESCRIPTION,
citation=_CITATION,
inputs_description=_KWARGS_DESCRIPTION,
features=datasets.Features(
{
"predictions": datasets.Value("string", id="sequence"),
"references": datasets.Value("string", id="sequence"),
}
),
codebase_urls=["https://github.com/jitsi/jiwer/"],
reference_urls=[
"https://en.wikipedia.org/wiki/Word_error_rate",
"https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates",
],
)
def _compute(self, predictions, references, concatenate_texts=False):
if concatenate_texts:
return jiwer.wer(
references,
predictions,
truth_transform=cer_transform,
hypothesis_transform=cer_transform,
)
incorrect = 0
total = 0
for prediction, reference in zip(predictions, references):
measures = jiwer.compute_measures(
reference,
prediction,
truth_transform=cer_transform,
hypothesis_transform=cer_transform,
)
incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
total += measures["substitutions"] + measures["deletions"] + measures["hits"]
return incorrect / total | metrics/cer/cer.py | """ Character Error Ratio (CER) metric. """
from typing import List
import jiwer
import jiwer.transforms as tr
import datasets
class SentencesToListOfCharacters(tr.AbstractTransform):
def process_string(self, s: str):
return list(s)
def process_list(self, inp: List[str]):
chars = []
for sentence in inp:
chars.extend(self.process_string(sentence))
return chars
cer_transform = tr.Compose(
[
tr.RemoveMultipleSpaces(),
tr.Strip(),
SentencesToListOfCharacters(),
]
)
_CITATION = """\
@inproceedings{inproceedings,
author = {<NAME> Maier, Viktoria and <NAME>},
year = {2004},
month = {01},
pages = {},
title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}
}
"""
_DESCRIPTION = """\
Character error rate (CER) is a common metric of the performance of an automatic speech recognition system.
CER is similar to Word Error Rate (WER), but operate on character insted of word. Please refer to docs of WER for further information.
Character error rate can be computed as:
CER = (S + D + I) / N = (S + D + I) / (S + D + C)
where
S is the number of substitutions,
D is the number of deletions,
I is the number of insertions,
C is the number of correct characters,
N is the number of characters in the reference (N=S+D+C).
CER's output is always a number between 0 and 1. This value indicates the percentage of characters that were incorrectly predicted. The lower the value, the better the
performance of the ASR system with a CER of 0 being a perfect score.
"""
_KWARGS_DESCRIPTION = """
Computes CER score of transcribed segments against references.
Args:
references: list of references for each speech input.
predictions: list of transcribtions to score.
concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.
Returns:
(float): the character error rate
Examples:
>>> predictions = ["this is the prediction", "there is an other sample"]
>>> references = ["this is the reference", "there is another one"]
>>> cer = datasets.load_metric("cer")
>>> cer_score = cer.compute(predictions=predictions, references=references)
>>> print(cer_score)
0.34146341463414637
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)
class CER(datasets.Metric):
def _info(self):
return datasets.MetricInfo(
description=_DESCRIPTION,
citation=_CITATION,
inputs_description=_KWARGS_DESCRIPTION,
features=datasets.Features(
{
"predictions": datasets.Value("string", id="sequence"),
"references": datasets.Value("string", id="sequence"),
}
),
codebase_urls=["https://github.com/jitsi/jiwer/"],
reference_urls=[
"https://en.wikipedia.org/wiki/Word_error_rate",
"https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates",
],
)
def _compute(self, predictions, references, concatenate_texts=False):
if concatenate_texts:
return jiwer.wer(
references,
predictions,
truth_transform=cer_transform,
hypothesis_transform=cer_transform,
)
incorrect = 0
total = 0
for prediction, reference in zip(predictions, references):
measures = jiwer.compute_measures(
reference,
prediction,
truth_transform=cer_transform,
hypothesis_transform=cer_transform,
)
incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
total += measures["substitutions"] + measures["deletions"] + measures["hits"]
return incorrect / total | 0.949763 | 0.693648 |
import asyncio
from haphilipsjs.typing import SystemType
from openpeerpower.components.remote import (
ATTR_DELAY_SECS,
ATTR_NUM_REPEATS,
DEFAULT_DELAY_SECS,
RemoteEntity,
)
from . import LOGGER, PhilipsTVDataUpdateCoordinator
from .const import CONF_SYSTEM, DOMAIN
async def async_setup_entry(opp, config_entry, async_add_entities):
"""Set up the configuration entry."""
coordinator = opp.data[DOMAIN][config_entry.entry_id]
async_add_entities(
[
PhilipsTVRemote(
coordinator,
config_entry.data[CONF_SYSTEM],
config_entry.unique_id,
)
]
)
class PhilipsTVRemote(RemoteEntity):
"""Device that sends commands."""
def __init__(
self,
coordinator: PhilipsTVDataUpdateCoordinator,
system: SystemType,
unique_id: str,
) -> None:
"""Initialize the Philips TV."""
self._tv = coordinator.api
self._coordinator = coordinator
self._system = system
self._unique_id = unique_id
@property
def name(self):
"""Return the device name."""
return self._system["name"]
@property
def is_on(self):
"""Return true if device is on."""
return bool(
self._tv.on and (self._tv.powerstate == "On" or self._tv.powerstate is None)
)
@property
def should_poll(self):
"""No polling needed for Apple TV."""
return False
@property
def unique_id(self):
"""Return unique identifier if known."""
return self._unique_id
@property
def device_info(self):
"""Return a device description for device registry."""
return {
"name": self._system["name"],
"identifiers": {
(DOMAIN, self._unique_id),
},
"model": self._system.get("model"),
"manufacturer": "Philips",
"sw_version": self._system.get("softwareversion"),
}
async def async_turn_on(self, **kwargs):
"""Turn the device on."""
if self._tv.on and self._tv.powerstate:
await self._tv.setPowerState("On")
else:
await self._coordinator.turn_on.async_run(self.opp, self._context)
self.async_write_op_state()
async def async_turn_off(self, **kwargs):
"""Turn the device off."""
if self._tv.on:
await self._tv.sendKey("Standby")
self.async_write_op_state()
else:
LOGGER.debug("Tv was already turned off")
async def async_send_command(self, command, **kwargs):
"""Send a command to one device."""
num_repeats = kwargs[ATTR_NUM_REPEATS]
delay = kwargs.get(ATTR_DELAY_SECS, DEFAULT_DELAY_SECS)
for _ in range(num_repeats):
for single_command in command:
LOGGER.debug("Sending command %s", single_command)
await self._tv.sendKey(single_command)
await asyncio.sleep(delay) | openpeerpower/components/philips_js/remote.py |
import asyncio
from haphilipsjs.typing import SystemType
from openpeerpower.components.remote import (
ATTR_DELAY_SECS,
ATTR_NUM_REPEATS,
DEFAULT_DELAY_SECS,
RemoteEntity,
)
from . import LOGGER, PhilipsTVDataUpdateCoordinator
from .const import CONF_SYSTEM, DOMAIN
async def async_setup_entry(opp, config_entry, async_add_entities):
"""Set up the configuration entry."""
coordinator = opp.data[DOMAIN][config_entry.entry_id]
async_add_entities(
[
PhilipsTVRemote(
coordinator,
config_entry.data[CONF_SYSTEM],
config_entry.unique_id,
)
]
)
class PhilipsTVRemote(RemoteEntity):
"""Device that sends commands."""
def __init__(
self,
coordinator: PhilipsTVDataUpdateCoordinator,
system: SystemType,
unique_id: str,
) -> None:
"""Initialize the Philips TV."""
self._tv = coordinator.api
self._coordinator = coordinator
self._system = system
self._unique_id = unique_id
@property
def name(self):
"""Return the device name."""
return self._system["name"]
@property
def is_on(self):
"""Return true if device is on."""
return bool(
self._tv.on and (self._tv.powerstate == "On" or self._tv.powerstate is None)
)
@property
def should_poll(self):
"""No polling needed for Apple TV."""
return False
@property
def unique_id(self):
"""Return unique identifier if known."""
return self._unique_id
@property
def device_info(self):
"""Return a device description for device registry."""
return {
"name": self._system["name"],
"identifiers": {
(DOMAIN, self._unique_id),
},
"model": self._system.get("model"),
"manufacturer": "Philips",
"sw_version": self._system.get("softwareversion"),
}
async def async_turn_on(self, **kwargs):
"""Turn the device on."""
if self._tv.on and self._tv.powerstate:
await self._tv.setPowerState("On")
else:
await self._coordinator.turn_on.async_run(self.opp, self._context)
self.async_write_op_state()
async def async_turn_off(self, **kwargs):
"""Turn the device off."""
if self._tv.on:
await self._tv.sendKey("Standby")
self.async_write_op_state()
else:
LOGGER.debug("Tv was already turned off")
async def async_send_command(self, command, **kwargs):
"""Send a command to one device."""
num_repeats = kwargs[ATTR_NUM_REPEATS]
delay = kwargs.get(ATTR_DELAY_SECS, DEFAULT_DELAY_SECS)
for _ in range(num_repeats):
for single_command in command:
LOGGER.debug("Sending command %s", single_command)
await self._tv.sendKey(single_command)
await asyncio.sleep(delay) | 0.784814 | 0.116714 |
from collections import OrderedDict
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from aw_nas import utils, assert_rollout_type
from aw_nas.common import DifferentiableRollout as DiffRollout
from aw_nas.controller.base import BaseController
class DiffController(BaseController, nn.Module):
"""
Using the gumbel softmax reparametrization of categorical distribution.
The sampled actions (ops/nodes) will be hard/soft vectors rather than discrete indexes.
"""
NAME = "differentiable"
SCHEDULABLE_ATTRS = [
"gumbel_temperature",
"entropy_coeff",
"force_uniform"
]
def __init__(self, search_space, device, rollout_type="differentiable",
use_prob=False, gumbel_hard=False, gumbel_temperature=1.0,
entropy_coeff=0.01, max_grad_norm=None, force_uniform=False,
schedule_cfg=None):
"""
Args:
use_prob (bool): If true, use the probability directly instead of relaxed sampling.
If false, use gumbel sampling. Default: false.
gumbel_hard (bool): If true, the soft relaxed vector calculated by gumbel softmax
in the forward pass will be argmax to a one-hot vector. The gradients are straightly
passed through argmax operation. This will cause discrepancy of the forward and
backward pass, but allow the samples to be sparse. Also applied to `use_prob==True`.
gumbel_temperature (float): The temperature of gumbel softmax. As the temperature gets
smaller, when used with `gumbel_hard==True`, the discrepancy of the forward/backward
pass gets smaller; When used with `gumbel_hard==False`, the samples become more
sparse(smaller bias), but the variance of the gradient estimation using samples
becoming larger. Also applied to `use_prob==True`
"""
super(DiffController, self).__init__(search_space, rollout_type, schedule_cfg=schedule_cfg)
nn.Module.__init__(self)
self.device = device
# sampling
self.use_prob = use_prob
self.gumbel_hard = gumbel_hard
self.gumbel_temperature = gumbel_temperature
# training
self.entropy_coeff = entropy_coeff
self.max_grad_norm = max_grad_norm
self.force_uniform = force_uniform
_num_init_nodes = self.search_space.num_init_nodes
_num_edges_list = [sum(_num_init_nodes+i
for i in range(self.search_space.get_num_steps(i_cg)))
for i_cg in range(self.search_space.num_cell_groups)]
self.cg_alphas = nn.ParameterList([
nn.Parameter(1e-3*torch.randn(_num_edges,
len(self.search_space.cell_shared_primitives[i_cg])))
for i_cg, _num_edges in enumerate(_num_edges_list)])
self.to(self.device)
def set_mode(self, mode):
super(DiffController, self).set_mode(mode)
if mode == "train":
nn.Module.train(self)
elif mode == "eval":
nn.Module.eval(self)
else:
raise Exception("Unrecognized mode: {}".format(mode))
def set_device(self, device):
self.device = device
self.to(device)
def forward(self, n=1): #pylint: disable=arguments-differ
return self.sample(n=n)
def sample(self, n=1, batch_size=1):
rollouts = []
for _ in range(n):
arch_list = []
sampled_list = []
logits_list = []
for alpha in self.cg_alphas:
if self.force_uniform: # cg_alpha parameters will not be in the graph
alpha = torch.zeros_like(alpha)
if batch_size > 1:
expanded_alpha = alpha.reshape([alpha.shape[0], 1, alpha.shape[1]])\
.repeat([1, batch_size, 1])\
.reshape([-1, alpha.shape[-1]])
else:
expanded_alpha = alpha
if self.use_prob:
# probability as sample
sampled = F.softmax(expanded_alpha / self.gumbel_temperature, dim=-1)
else:
# gumbel sampling
sampled, _ = utils.gumbel_softmax(expanded_alpha, self.gumbel_temperature,
hard=False)
if self.gumbel_hard:
arch = utils.straight_through(sampled)
else:
arch = sampled
if batch_size > 1:
sampled = sampled.reshape([-1, batch_size, arch.shape[-1]])
arch = arch.reshape([-1, batch_size, arch.shape[-1]])
arch_list.append(arch)
sampled_list.append(utils.get_numpy(sampled))
logits_list.append(utils.get_numpy(alpha))
rollouts.append(DiffRollout(arch_list, sampled_list, logits_list, self.search_space))
return rollouts
def save(self, path):
"""Save the parameters to disk."""
torch.save({"epoch": self.epoch,
"state_dict": self.state_dict()}, path)
self.logger.info("Saved controller network to %s", path)
def load(self, path):
"""Load the parameters from disk."""
checkpoint = torch.load(path, map_location=torch.device("cpu"))
self.load_state_dict(checkpoint["state_dict"])
self.on_epoch_start(checkpoint["epoch"])
self.logger.info("Loaded controller network from %s", path)
def _entropy_loss(self):
if self.entropy_coeff > 0:
probs = [F.softmax(alpha, dim=-1) for alpha in self.cg_alphas]
return self.entropy_coeff * sum(-(torch.log(prob) * prob).sum() for prob in probs)
return 0.
def gradient(self, loss, return_grads=True, zero_grads=True):
if zero_grads:
self.zero_grad()
_loss = loss + self._entropy_loss()
_loss.backward()
if return_grads:
return utils.get_numpy(_loss), [(k, v.grad.clone()) for k, v in self.named_parameters()]
return utils.get_numpy(_loss)
def step_current_gradient(self, optimizer):
if self.max_grad_norm is not None:
torch.nn.utils.clip_grad_norm_(self.parameters(), self.max_grad_norm)
optimizer.step()
def step_gradient(self, gradients, optimizer):
self.zero_grad()
named_params = dict(self.named_parameters())
for k, grad in gradients:
named_params[k].grad = grad
# clip the gradients
if self.max_grad_norm is not None:
torch.nn.utils.clip_grad_norm_(self.parameters(), self.max_grad_norm)
# apply the gradients
optimizer.step()
def step(self, rollouts, optimizer, perf_name): # very memory inefficient
self.zero_grad()
losses = [r.get_perf(perf_name) for r in rollouts]
optimizer.step()
[l.backward() for l in losses]
return np.mean([l.detach().cpu().numpy() for l in losses])
def summary(self, rollouts, log=False, log_prefix="", step=None):
num = len(rollouts)
logits_list = [[utils.get_numpy(logits) for logits in r.logits] for r in rollouts]
_ss = self.search_space
if self.gumbel_hard:
cg_logprobs = [0. for _ in range(_ss.num_cell_groups)]
cg_entros = [0. for _ in range(_ss.num_cell_groups)]
for rollout, logits in zip(rollouts, logits_list):
for cg_idx, (vec, cg_logits) in enumerate(zip(rollout.arch, logits)):
prob = utils.softmax(cg_logits)
logprob = np.log(prob)
if self.gumbel_hard:
inds = np.argmax(utils.get_numpy(vec), axis=-1)
cg_logprobs[cg_idx] += np.sum(logprob[range(len(inds)), inds])
cg_entros[cg_idx] += -(prob * logprob).sum()
# mean across rollouts
if self.gumbel_hard:
cg_logprobs = [s / num for s in cg_logprobs]
total_logprob = sum(cg_logprobs)
cg_logprobs_str = ",".join(["{:.2f}".format(n) for n in cg_logprobs])
cg_entros = [s / num for s in cg_entros]
total_entro = sum(cg_entros)
cg_entro_str = ",".join(["{:.2f}".format(n) for n in cg_entros])
if log:
# maybe log the summary
self.logger.info("%s%d rollouts: %s ENTROPY: %2f (%s)",
log_prefix, num,
"-LOG_PROB: %.2f (%s) ;"%(-total_logprob, cg_logprobs_str) \
if self.gumbel_hard else "",
total_entro, cg_entro_str)
if step is not None and not self.writer.is_none():
if self.gumbel_hard:
self.writer.add_scalar("log_prob", total_logprob, step)
self.writer.add_scalar("entropy", total_entro, step)
stats = [(n + " ENTRO", entro) for n, entro in zip(_ss.cell_group_names, cg_entros)]
if self.gumbel_hard:
stats += [(n + " LOGPROB", logprob) for n, logprob in \
zip(_ss.cell_group_names, cg_logprobs)]
return OrderedDict(stats)
@classmethod
def supported_rollout_types(cls):
return [assert_rollout_type("differentiable")] | aw_nas/controller/differentiable.py | from collections import OrderedDict
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from aw_nas import utils, assert_rollout_type
from aw_nas.common import DifferentiableRollout as DiffRollout
from aw_nas.controller.base import BaseController
class DiffController(BaseController, nn.Module):
"""
Using the gumbel softmax reparametrization of categorical distribution.
The sampled actions (ops/nodes) will be hard/soft vectors rather than discrete indexes.
"""
NAME = "differentiable"
SCHEDULABLE_ATTRS = [
"gumbel_temperature",
"entropy_coeff",
"force_uniform"
]
def __init__(self, search_space, device, rollout_type="differentiable",
use_prob=False, gumbel_hard=False, gumbel_temperature=1.0,
entropy_coeff=0.01, max_grad_norm=None, force_uniform=False,
schedule_cfg=None):
"""
Args:
use_prob (bool): If true, use the probability directly instead of relaxed sampling.
If false, use gumbel sampling. Default: false.
gumbel_hard (bool): If true, the soft relaxed vector calculated by gumbel softmax
in the forward pass will be argmax to a one-hot vector. The gradients are straightly
passed through argmax operation. This will cause discrepancy of the forward and
backward pass, but allow the samples to be sparse. Also applied to `use_prob==True`.
gumbel_temperature (float): The temperature of gumbel softmax. As the temperature gets
smaller, when used with `gumbel_hard==True`, the discrepancy of the forward/backward
pass gets smaller; When used with `gumbel_hard==False`, the samples become more
sparse(smaller bias), but the variance of the gradient estimation using samples
becoming larger. Also applied to `use_prob==True`
"""
super(DiffController, self).__init__(search_space, rollout_type, schedule_cfg=schedule_cfg)
nn.Module.__init__(self)
self.device = device
# sampling
self.use_prob = use_prob
self.gumbel_hard = gumbel_hard
self.gumbel_temperature = gumbel_temperature
# training
self.entropy_coeff = entropy_coeff
self.max_grad_norm = max_grad_norm
self.force_uniform = force_uniform
_num_init_nodes = self.search_space.num_init_nodes
_num_edges_list = [sum(_num_init_nodes+i
for i in range(self.search_space.get_num_steps(i_cg)))
for i_cg in range(self.search_space.num_cell_groups)]
self.cg_alphas = nn.ParameterList([
nn.Parameter(1e-3*torch.randn(_num_edges,
len(self.search_space.cell_shared_primitives[i_cg])))
for i_cg, _num_edges in enumerate(_num_edges_list)])
self.to(self.device)
def set_mode(self, mode):
super(DiffController, self).set_mode(mode)
if mode == "train":
nn.Module.train(self)
elif mode == "eval":
nn.Module.eval(self)
else:
raise Exception("Unrecognized mode: {}".format(mode))
def set_device(self, device):
self.device = device
self.to(device)
def forward(self, n=1): #pylint: disable=arguments-differ
return self.sample(n=n)
def sample(self, n=1, batch_size=1):
rollouts = []
for _ in range(n):
arch_list = []
sampled_list = []
logits_list = []
for alpha in self.cg_alphas:
if self.force_uniform: # cg_alpha parameters will not be in the graph
alpha = torch.zeros_like(alpha)
if batch_size > 1:
expanded_alpha = alpha.reshape([alpha.shape[0], 1, alpha.shape[1]])\
.repeat([1, batch_size, 1])\
.reshape([-1, alpha.shape[-1]])
else:
expanded_alpha = alpha
if self.use_prob:
# probability as sample
sampled = F.softmax(expanded_alpha / self.gumbel_temperature, dim=-1)
else:
# gumbel sampling
sampled, _ = utils.gumbel_softmax(expanded_alpha, self.gumbel_temperature,
hard=False)
if self.gumbel_hard:
arch = utils.straight_through(sampled)
else:
arch = sampled
if batch_size > 1:
sampled = sampled.reshape([-1, batch_size, arch.shape[-1]])
arch = arch.reshape([-1, batch_size, arch.shape[-1]])
arch_list.append(arch)
sampled_list.append(utils.get_numpy(sampled))
logits_list.append(utils.get_numpy(alpha))
rollouts.append(DiffRollout(arch_list, sampled_list, logits_list, self.search_space))
return rollouts
def save(self, path):
"""Save the parameters to disk."""
torch.save({"epoch": self.epoch,
"state_dict": self.state_dict()}, path)
self.logger.info("Saved controller network to %s", path)
def load(self, path):
"""Load the parameters from disk."""
checkpoint = torch.load(path, map_location=torch.device("cpu"))
self.load_state_dict(checkpoint["state_dict"])
self.on_epoch_start(checkpoint["epoch"])
self.logger.info("Loaded controller network from %s", path)
def _entropy_loss(self):
if self.entropy_coeff > 0:
probs = [F.softmax(alpha, dim=-1) for alpha in self.cg_alphas]
return self.entropy_coeff * sum(-(torch.log(prob) * prob).sum() for prob in probs)
return 0.
def gradient(self, loss, return_grads=True, zero_grads=True):
if zero_grads:
self.zero_grad()
_loss = loss + self._entropy_loss()
_loss.backward()
if return_grads:
return utils.get_numpy(_loss), [(k, v.grad.clone()) for k, v in self.named_parameters()]
return utils.get_numpy(_loss)
def step_current_gradient(self, optimizer):
if self.max_grad_norm is not None:
torch.nn.utils.clip_grad_norm_(self.parameters(), self.max_grad_norm)
optimizer.step()
def step_gradient(self, gradients, optimizer):
self.zero_grad()
named_params = dict(self.named_parameters())
for k, grad in gradients:
named_params[k].grad = grad
# clip the gradients
if self.max_grad_norm is not None:
torch.nn.utils.clip_grad_norm_(self.parameters(), self.max_grad_norm)
# apply the gradients
optimizer.step()
def step(self, rollouts, optimizer, perf_name): # very memory inefficient
self.zero_grad()
losses = [r.get_perf(perf_name) for r in rollouts]
optimizer.step()
[l.backward() for l in losses]
return np.mean([l.detach().cpu().numpy() for l in losses])
def summary(self, rollouts, log=False, log_prefix="", step=None):
num = len(rollouts)
logits_list = [[utils.get_numpy(logits) for logits in r.logits] for r in rollouts]
_ss = self.search_space
if self.gumbel_hard:
cg_logprobs = [0. for _ in range(_ss.num_cell_groups)]
cg_entros = [0. for _ in range(_ss.num_cell_groups)]
for rollout, logits in zip(rollouts, logits_list):
for cg_idx, (vec, cg_logits) in enumerate(zip(rollout.arch, logits)):
prob = utils.softmax(cg_logits)
logprob = np.log(prob)
if self.gumbel_hard:
inds = np.argmax(utils.get_numpy(vec), axis=-1)
cg_logprobs[cg_idx] += np.sum(logprob[range(len(inds)), inds])
cg_entros[cg_idx] += -(prob * logprob).sum()
# mean across rollouts
if self.gumbel_hard:
cg_logprobs = [s / num for s in cg_logprobs]
total_logprob = sum(cg_logprobs)
cg_logprobs_str = ",".join(["{:.2f}".format(n) for n in cg_logprobs])
cg_entros = [s / num for s in cg_entros]
total_entro = sum(cg_entros)
cg_entro_str = ",".join(["{:.2f}".format(n) for n in cg_entros])
if log:
# maybe log the summary
self.logger.info("%s%d rollouts: %s ENTROPY: %2f (%s)",
log_prefix, num,
"-LOG_PROB: %.2f (%s) ;"%(-total_logprob, cg_logprobs_str) \
if self.gumbel_hard else "",
total_entro, cg_entro_str)
if step is not None and not self.writer.is_none():
if self.gumbel_hard:
self.writer.add_scalar("log_prob", total_logprob, step)
self.writer.add_scalar("entropy", total_entro, step)
stats = [(n + " ENTRO", entro) for n, entro in zip(_ss.cell_group_names, cg_entros)]
if self.gumbel_hard:
stats += [(n + " LOGPROB", logprob) for n, logprob in \
zip(_ss.cell_group_names, cg_logprobs)]
return OrderedDict(stats)
@classmethod
def supported_rollout_types(cls):
return [assert_rollout_type("differentiable")] | 0.95637 | 0.302109 |
import random
from typing import Optional
import othello
from log_referee import LogReferee
import evaluation
class MinimaxAgent(othello.Agent):
def __init__(self, play_as: othello.Player, search_depth: int =2, eval_func=evaluation.heuristic_eval_comprehensive) -> None:
super().__init__()
self.play_as = play_as
self.depth = search_depth
self.evaluation_function = lambda state: eval_func(state, self.play_as)
def play(self, state: othello.State) -> Optional[othello.Action]:
legal_actions = list(state.get_legal_actions(self.play_as))
if legal_actions == []:
return None
else:
def minimax(currentGameState, depth, player):
if currentGameState.is_terminal():
return self.evaluation_function(currentGameState)
legal_actions = list(currentGameState.get_legal_actions(player))
scores = []
if player != self.play_as:
if depth == self.depth:
if len(legal_actions) == 0:
return self.evaluation_function(currentGameState)
for action in legal_actions:
childGameState = currentGameState.perform_action(player, action)
scores.append(self.evaluation_function(currentGameState))
return min(scores)
else:
if len(legal_actions) == 0:
return minimax(currentGameState, depth + 1, player.adversary)
for action in legal_actions:
childGameState = currentGameState.perform_action(player, action)
scores.append(minimax(childGameState, depth + 1, player.adversary))
return min(scores)
else:
if len(legal_actions) == 0:
return minimax(currentGameState, depth, player.adversary)
for action in legal_actions:
childGameState = currentGameState.perform_action(player, action)
scores.append(minimax(childGameState, depth, player.adversary))
return max(scores)
scores = []
# Choose one of the best actions
for action in legal_actions:
childgameState = state.perform_action(self.play_as, action)
scores.append(minimax(childgameState, 1, self.play_as.adversary))
bestScore = max(scores)
bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]
# Pick randomly among the best
chosenIndex = random.choice(bestIndices)
return legal_actions[chosenIndex]
def run_minimax_agents() -> None:
referee = LogReferee(MinimaxAgent(othello.Player.DARK),
MinimaxAgent(othello.Player.LIGHT))
referee.run()
if __name__ == '__main__':
run_minimax_agents() | minimax_agent.py | import random
from typing import Optional
import othello
from log_referee import LogReferee
import evaluation
class MinimaxAgent(othello.Agent):
def __init__(self, play_as: othello.Player, search_depth: int =2, eval_func=evaluation.heuristic_eval_comprehensive) -> None:
super().__init__()
self.play_as = play_as
self.depth = search_depth
self.evaluation_function = lambda state: eval_func(state, self.play_as)
def play(self, state: othello.State) -> Optional[othello.Action]:
legal_actions = list(state.get_legal_actions(self.play_as))
if legal_actions == []:
return None
else:
def minimax(currentGameState, depth, player):
if currentGameState.is_terminal():
return self.evaluation_function(currentGameState)
legal_actions = list(currentGameState.get_legal_actions(player))
scores = []
if player != self.play_as:
if depth == self.depth:
if len(legal_actions) == 0:
return self.evaluation_function(currentGameState)
for action in legal_actions:
childGameState = currentGameState.perform_action(player, action)
scores.append(self.evaluation_function(currentGameState))
return min(scores)
else:
if len(legal_actions) == 0:
return minimax(currentGameState, depth + 1, player.adversary)
for action in legal_actions:
childGameState = currentGameState.perform_action(player, action)
scores.append(minimax(childGameState, depth + 1, player.adversary))
return min(scores)
else:
if len(legal_actions) == 0:
return minimax(currentGameState, depth, player.adversary)
for action in legal_actions:
childGameState = currentGameState.perform_action(player, action)
scores.append(minimax(childGameState, depth, player.adversary))
return max(scores)
scores = []
# Choose one of the best actions
for action in legal_actions:
childgameState = state.perform_action(self.play_as, action)
scores.append(minimax(childgameState, 1, self.play_as.adversary))
bestScore = max(scores)
bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]
# Pick randomly among the best
chosenIndex = random.choice(bestIndices)
return legal_actions[chosenIndex]
def run_minimax_agents() -> None:
referee = LogReferee(MinimaxAgent(othello.Player.DARK),
MinimaxAgent(othello.Player.LIGHT))
referee.run()
if __name__ == '__main__':
run_minimax_agents() | 0.724968 | 0.229158 |
import random
from datetime import datetime
from stdnum import verhoeff
from rapidpro_webhooks.apps.core.db import db
from rapidpro_webhooks.apps.core.exceptions import VoucherException
class Voucher(db.Model):
__tablename__ = 'voucher_vouchers'
id = db.Column(db.Integer, primary_key=True)
flow_id = db.Column(db.Integer, nullable=True)
code = db.Column(db.String(20))
redeemed_on = db.Column(db.DateTime(timezone=True), nullable=True)
created_on = db.Column(db.DateTime(timezone=True), server_default=db.func.now())
modified_on = db.Column(db.DateTime(timezone=True), server_default=db.func.now(), server_onupdate=db.func.now())
redeemed_by = db.Column(db.String(13), nullable=True)
def __init__(self, code):
self.code = code
def __repr__(self):
return self.code
@classmethod
def create(cls):
voucher = cls(code=cls.generate_code())
db.session.add(voucher)
db.session.commit()
return voucher
@classmethod
def add_external_codes(cls, codes):
codes = set(codes)
for code in codes:
voucher = cls(code=code)
db.session.add(voucher)
db.session.commit()
@classmethod
def redeem(cls, code, phone, flow):
voucher = cls.query.filter_by(code=str(code)).first()
if voucher is None:
raise VoucherException("Voucher does not exist")
if voucher.redeemed_on is not None:
raise VoucherException("Attempting to redeem an already redeemed voucher")
voucher.redeemed_on = datetime.now()
voucher.redeemed_by = phone
voucher.flow_id = flow
db.session.add(voucher)
db.session.commit()
@classmethod
def _random(cls):
_code = random.randint(100, 999)
while cls.query.filter_by(code=str(_code)).first():
_code = random.randint(100, 999)
return _code
@classmethod
def generate_code(cls):
_code = cls._random()
check_digit = verhoeff.calc_check_digit(_code)
return "%s%s" % (str(_code), str(check_digit)) | rapidpro_webhooks/apps/vouchers/models.py | import random
from datetime import datetime
from stdnum import verhoeff
from rapidpro_webhooks.apps.core.db import db
from rapidpro_webhooks.apps.core.exceptions import VoucherException
class Voucher(db.Model):
__tablename__ = 'voucher_vouchers'
id = db.Column(db.Integer, primary_key=True)
flow_id = db.Column(db.Integer, nullable=True)
code = db.Column(db.String(20))
redeemed_on = db.Column(db.DateTime(timezone=True), nullable=True)
created_on = db.Column(db.DateTime(timezone=True), server_default=db.func.now())
modified_on = db.Column(db.DateTime(timezone=True), server_default=db.func.now(), server_onupdate=db.func.now())
redeemed_by = db.Column(db.String(13), nullable=True)
def __init__(self, code):
self.code = code
def __repr__(self):
return self.code
@classmethod
def create(cls):
voucher = cls(code=cls.generate_code())
db.session.add(voucher)
db.session.commit()
return voucher
@classmethod
def add_external_codes(cls, codes):
codes = set(codes)
for code in codes:
voucher = cls(code=code)
db.session.add(voucher)
db.session.commit()
@classmethod
def redeem(cls, code, phone, flow):
voucher = cls.query.filter_by(code=str(code)).first()
if voucher is None:
raise VoucherException("Voucher does not exist")
if voucher.redeemed_on is not None:
raise VoucherException("Attempting to redeem an already redeemed voucher")
voucher.redeemed_on = datetime.now()
voucher.redeemed_by = phone
voucher.flow_id = flow
db.session.add(voucher)
db.session.commit()
@classmethod
def _random(cls):
_code = random.randint(100, 999)
while cls.query.filter_by(code=str(_code)).first():
_code = random.randint(100, 999)
return _code
@classmethod
def generate_code(cls):
_code = cls._random()
check_digit = verhoeff.calc_check_digit(_code)
return "%s%s" % (str(_code), str(check_digit)) | 0.52756 | 0.055643 |
from __future__ import unicode_literals, division, absolute_import
import logging
import urllib
import feedparser
from flexget import plugin
from flexget.entry import Entry
from flexget.event import event
from flexget.utils.search import torrent_availability, normalize_unicode
log = logging.getLogger('kat')
class SearchKAT(object):
"""KAT search plugin.
should accept:
kat:
category: <category>
verified: yes/no
categories:
all
movies
tv
music
books
xxx
other
"""
schema = {
'type': 'object',
'properties': {
'category': {'type': 'string', 'enum': ['all', 'movies', 'tv', 'music', 'books', 'xxx', 'other']},
'verified': {'type': 'boolean'}
},
'additionalProperties': False
}
def search(self, entry, config):
search_strings = [normalize_unicode(s).lower() for s in entry.get('search_strings', [entry['title']])]
entries = set()
for search_string in search_strings:
search_string_url_fragment = search_string
if config.get('verified'):
search_string_url_fragment += ' verified:1'
url = 'http://kickass.to/search/%s/?rss=1' % urllib.quote(search_string_url_fragment.encode('utf-8'))
if config.get('category', 'all') != 'all':
url += '&category=%s' % config['category']
sorters = [{'field': 'time_add', 'sorder': 'desc'},
{'field': 'seeders', 'sorder': 'desc'}]
for sort in sorters:
url += '&field=%(field)s&sorder=%(sorder)s' % sort
log.debug('requesting: %s' % url)
rss = feedparser.parse(url)
status = rss.get('status', False)
if status == 404:
# Kat returns status code 404 when no results found for some reason...
log.debug('No results found for search query: %s' % search_string)
continue
elif status not in [200, 301]:
raise plugin.PluginWarning('Search result not 200 (OK), received %s' % status)
ex = rss.get('bozo_exception', False)
if ex:
raise plugin.PluginWarning('Got bozo_exception (bad feed)')
for item in rss.entries:
entry = Entry()
entry['title'] = item.title
if not item.get('enclosures'):
log.warning('Could not get url for entry from KAT. Maybe plugin needs updated?')
continue
entry['url'] = item.enclosures[0]['url']
entry['torrent_seeds'] = int(item.torrent_seeds)
entry['torrent_leeches'] = int(item.torrent_peers)
entry['search_sort'] = torrent_availability(entry['torrent_seeds'], entry['torrent_leeches'])
entry['content_size'] = int(item.torrent_contentlength) / 1024 / 1024
entry['torrent_info_hash'] = item.torrent_infohash
entries.add(entry)
if len(rss.entries) < 25:
break
return entries
@event('plugin.register')
def register_plugin():
plugin.register(SearchKAT, 'kat', groups=['search'], api_ver=2) | flexget/plugins/search_kat.py | from __future__ import unicode_literals, division, absolute_import
import logging
import urllib
import feedparser
from flexget import plugin
from flexget.entry import Entry
from flexget.event import event
from flexget.utils.search import torrent_availability, normalize_unicode
log = logging.getLogger('kat')
class SearchKAT(object):
"""KAT search plugin.
should accept:
kat:
category: <category>
verified: yes/no
categories:
all
movies
tv
music
books
xxx
other
"""
schema = {
'type': 'object',
'properties': {
'category': {'type': 'string', 'enum': ['all', 'movies', 'tv', 'music', 'books', 'xxx', 'other']},
'verified': {'type': 'boolean'}
},
'additionalProperties': False
}
def search(self, entry, config):
search_strings = [normalize_unicode(s).lower() for s in entry.get('search_strings', [entry['title']])]
entries = set()
for search_string in search_strings:
search_string_url_fragment = search_string
if config.get('verified'):
search_string_url_fragment += ' verified:1'
url = 'http://kickass.to/search/%s/?rss=1' % urllib.quote(search_string_url_fragment.encode('utf-8'))
if config.get('category', 'all') != 'all':
url += '&category=%s' % config['category']
sorters = [{'field': 'time_add', 'sorder': 'desc'},
{'field': 'seeders', 'sorder': 'desc'}]
for sort in sorters:
url += '&field=%(field)s&sorder=%(sorder)s' % sort
log.debug('requesting: %s' % url)
rss = feedparser.parse(url)
status = rss.get('status', False)
if status == 404:
# Kat returns status code 404 when no results found for some reason...
log.debug('No results found for search query: %s' % search_string)
continue
elif status not in [200, 301]:
raise plugin.PluginWarning('Search result not 200 (OK), received %s' % status)
ex = rss.get('bozo_exception', False)
if ex:
raise plugin.PluginWarning('Got bozo_exception (bad feed)')
for item in rss.entries:
entry = Entry()
entry['title'] = item.title
if not item.get('enclosures'):
log.warning('Could not get url for entry from KAT. Maybe plugin needs updated?')
continue
entry['url'] = item.enclosures[0]['url']
entry['torrent_seeds'] = int(item.torrent_seeds)
entry['torrent_leeches'] = int(item.torrent_peers)
entry['search_sort'] = torrent_availability(entry['torrent_seeds'], entry['torrent_leeches'])
entry['content_size'] = int(item.torrent_contentlength) / 1024 / 1024
entry['torrent_info_hash'] = item.torrent_infohash
entries.add(entry)
if len(rss.entries) < 25:
break
return entries
@event('plugin.register')
def register_plugin():
plugin.register(SearchKAT, 'kat', groups=['search'], api_ver=2) | 0.465387 | 0.071461 |
import os
import math
import sys
import time
from os.path import abspath, basename, join
from seisflows.tools import msg
from seisflows.tools import unix
from seisflows.tools.tools import call, findpath, saveobj
from seisflows.config import ParameterError, custom_import
PAR = sys.modules['seisflows_parameters']
PATH = sys.modules['seisflows_paths']
class pbs_lg(custom_import('system', 'base')):
""" An interface through which to submit workflows, run tasks in serial or
parallel, and perform other system functions.
By hiding environment details behind a python interface layer, these
classes provide a consistent command set across different computing
environments.
Intermediate files are written to a global scratch path PATH.SCRATCH,
which must be accessible to all compute nodes.
Optionally, users can provide a local scratch path PATH.LOCAL if each
compute node has its own local filesystem.
For important additional information, please see
http://seisflows.readthedocs.org/en/latest/manual/manual.html#system-configuration
"""
def check(self):
""" Checks parameters and paths
"""
print msg.Warning_pbs_sm
# name of job
if 'TITLE' not in PAR:
setattr(PAR, 'TITLE', basename(abspath('.')))
# time allocated for workflow in minutes
if 'WALLTIME' not in PAR:
setattr(PAR, 'WALLTIME', 30.)
# number of tasks
if 'NTASK' not in PAR:
raise ParameterError(PAR, 'NTASK')
# number of cores per task
if 'NPROC' not in PAR:
raise ParameterError(PAR, 'NPROC')
# number of cores per node
if 'NODESIZE' not in PAR:
raise ParameterError(PAR, 'NODESIZE')
# how to invoke executables
if 'MPIEXEC' not in PAR:
setattr(PAR, 'MPIEXEC', '')
# optional additional PBS arguments
if 'PBSARGS' not in PAR:
setattr(PAR, 'PBSARGS', '')
# optional environment variable list VAR1=val1,VAR2=val2,...
if 'ENVIRONS' not in PAR:
setattr(PAR, 'ENVIRONS', '')
# level of detail in output messages
if 'VERBOSE' not in PAR:
setattr(PAR, 'VERBOSE', 1)
# where job was submitted
if 'WORKDIR' not in PATH:
setattr(PATH, 'WORKDIR', abspath('.'))
# where output files are written
if 'OUTPUT' not in PATH:
setattr(PATH, 'OUTPUT', PATH.WORKDIR+'/'+'output')
# where temporary files are written
if 'SCRATCH' not in PATH:
setattr(PATH, 'SCRATCH', PATH.WORKDIR+'/'+'scratch')
# where system files are written
if 'SYSTEM' not in PATH:
setattr(PATH, 'SYSTEM', PATH.SCRATCH+'/'+'system')
# optional local scratch path
if 'LOCAL' not in PATH:
setattr(PATH, 'LOCAL', None)
def submit(self, workflow):
""" Submits workflow
"""
# create scratch directories
unix.mkdir(PATH.SCRATCH)
unix.mkdir(PATH.SYSTEM)
# create output directories
unix.mkdir(PATH.OUTPUT)
workflow.checkpoint()
hours = PAR.WALLTIME/60
minutes = PAR.WALLTIME%60
walltime = 'walltime=%02d:%02d:00 ' % (hours, minutes)
ncpus = PAR.NODESIZE
mpiprocs = PAR.NODESIZE
# prepare qsub arguments
call( 'qsub '
+ '%s ' % PAR.PBSARGS
+ '-l select=1:ncpus=%d:mpiprocs=%d ' % (ncpus, mpiprocs)
+ '-l %s ' % walltime
+ '-N %s ' % PAR.TITLE
+ '-j %s ' %'oe'
+ '-q %s ' %'medium'
+ '-o %s ' % (PATH.SUBMIT+'/'+'output.log')
+ '-V '
+ ' -- ' + findpath('seisflows.system') +'/'+ 'wrappers/submit '
+ PATH.OUTPUT)
def run(self, classname, method, hosts='all', **kwargs):
""" Executes the following task:
classname.method(*args, **kwargs)
"""
self.checkpoint()
if hosts == 'all':
# run all tasks
call(findpath('seisflows.system') +'/'+'wrappers/dsh '
+ ','.join(self.hostlist()) + ' '
+ findpath('seisflows.system') +'/'+'wrappers/run '
+ PATH.OUTPUT + ' '
+ classname + ' '
+ method + ' '
+ 'PYTHONPATH='+findpath('seisflows'),+','
+ PAR.ENVIRONS)
elif hosts == 'head':
# run a single task
call('ssh ' + self.hostlist()[0] + ' '
+ '"'
+ 'export SEISFLOWS_TASK_ID=0; '
+ join(findpath('seisflows.system'), 'wrappers/run ')
+ PATH.OUTPUT + ' '
+ classname + ' '
+ method + ' '
+ 'PYTHONPATH='+findpath('seisflows'),+','
+ PAR.ENVIRONS
+'"')
else:
raise KeyError('Bad keyword argument: system.run: hosts')
def mpiexec(self):
""" Specifies MPI executable used to invoke solver
"""
return PAR.MPIEXEC
def taskid(self):
""" Provides a unique identifier for each running task
"""
try:
return os.getenv('PBS_NODENUM')
except:
raise Exception("PBS_NODENUM environment variable not defined.")
def hostlist(self):
""" Generates list of allocated cores
"""
with open(os.environ['PBS_NODEFILE'], 'r') as f:
return [line.strip() for line in f.readlines()]
def save_kwargs(self, classname, method, kwargs):
kwargspath = join(PATH.OUTPUT, 'kwargs')
kwargsfile = join(kwargspath, classname+'_'+method+'.p')
unix.mkdir(kwargspath)
saveobj(kwargsfile, kwargs) | seisflows/system/pbs_sm.py | import os
import math
import sys
import time
from os.path import abspath, basename, join
from seisflows.tools import msg
from seisflows.tools import unix
from seisflows.tools.tools import call, findpath, saveobj
from seisflows.config import ParameterError, custom_import
PAR = sys.modules['seisflows_parameters']
PATH = sys.modules['seisflows_paths']
class pbs_lg(custom_import('system', 'base')):
""" An interface through which to submit workflows, run tasks in serial or
parallel, and perform other system functions.
By hiding environment details behind a python interface layer, these
classes provide a consistent command set across different computing
environments.
Intermediate files are written to a global scratch path PATH.SCRATCH,
which must be accessible to all compute nodes.
Optionally, users can provide a local scratch path PATH.LOCAL if each
compute node has its own local filesystem.
For important additional information, please see
http://seisflows.readthedocs.org/en/latest/manual/manual.html#system-configuration
"""
def check(self):
""" Checks parameters and paths
"""
print msg.Warning_pbs_sm
# name of job
if 'TITLE' not in PAR:
setattr(PAR, 'TITLE', basename(abspath('.')))
# time allocated for workflow in minutes
if 'WALLTIME' not in PAR:
setattr(PAR, 'WALLTIME', 30.)
# number of tasks
if 'NTASK' not in PAR:
raise ParameterError(PAR, 'NTASK')
# number of cores per task
if 'NPROC' not in PAR:
raise ParameterError(PAR, 'NPROC')
# number of cores per node
if 'NODESIZE' not in PAR:
raise ParameterError(PAR, 'NODESIZE')
# how to invoke executables
if 'MPIEXEC' not in PAR:
setattr(PAR, 'MPIEXEC', '')
# optional additional PBS arguments
if 'PBSARGS' not in PAR:
setattr(PAR, 'PBSARGS', '')
# optional environment variable list VAR1=val1,VAR2=val2,...
if 'ENVIRONS' not in PAR:
setattr(PAR, 'ENVIRONS', '')
# level of detail in output messages
if 'VERBOSE' not in PAR:
setattr(PAR, 'VERBOSE', 1)
# where job was submitted
if 'WORKDIR' not in PATH:
setattr(PATH, 'WORKDIR', abspath('.'))
# where output files are written
if 'OUTPUT' not in PATH:
setattr(PATH, 'OUTPUT', PATH.WORKDIR+'/'+'output')
# where temporary files are written
if 'SCRATCH' not in PATH:
setattr(PATH, 'SCRATCH', PATH.WORKDIR+'/'+'scratch')
# where system files are written
if 'SYSTEM' not in PATH:
setattr(PATH, 'SYSTEM', PATH.SCRATCH+'/'+'system')
# optional local scratch path
if 'LOCAL' not in PATH:
setattr(PATH, 'LOCAL', None)
def submit(self, workflow):
""" Submits workflow
"""
# create scratch directories
unix.mkdir(PATH.SCRATCH)
unix.mkdir(PATH.SYSTEM)
# create output directories
unix.mkdir(PATH.OUTPUT)
workflow.checkpoint()
hours = PAR.WALLTIME/60
minutes = PAR.WALLTIME%60
walltime = 'walltime=%02d:%02d:00 ' % (hours, minutes)
ncpus = PAR.NODESIZE
mpiprocs = PAR.NODESIZE
# prepare qsub arguments
call( 'qsub '
+ '%s ' % PAR.PBSARGS
+ '-l select=1:ncpus=%d:mpiprocs=%d ' % (ncpus, mpiprocs)
+ '-l %s ' % walltime
+ '-N %s ' % PAR.TITLE
+ '-j %s ' %'oe'
+ '-q %s ' %'medium'
+ '-o %s ' % (PATH.SUBMIT+'/'+'output.log')
+ '-V '
+ ' -- ' + findpath('seisflows.system') +'/'+ 'wrappers/submit '
+ PATH.OUTPUT)
def run(self, classname, method, hosts='all', **kwargs):
""" Executes the following task:
classname.method(*args, **kwargs)
"""
self.checkpoint()
if hosts == 'all':
# run all tasks
call(findpath('seisflows.system') +'/'+'wrappers/dsh '
+ ','.join(self.hostlist()) + ' '
+ findpath('seisflows.system') +'/'+'wrappers/run '
+ PATH.OUTPUT + ' '
+ classname + ' '
+ method + ' '
+ 'PYTHONPATH='+findpath('seisflows'),+','
+ PAR.ENVIRONS)
elif hosts == 'head':
# run a single task
call('ssh ' + self.hostlist()[0] + ' '
+ '"'
+ 'export SEISFLOWS_TASK_ID=0; '
+ join(findpath('seisflows.system'), 'wrappers/run ')
+ PATH.OUTPUT + ' '
+ classname + ' '
+ method + ' '
+ 'PYTHONPATH='+findpath('seisflows'),+','
+ PAR.ENVIRONS
+'"')
else:
raise KeyError('Bad keyword argument: system.run: hosts')
def mpiexec(self):
""" Specifies MPI executable used to invoke solver
"""
return PAR.MPIEXEC
def taskid(self):
""" Provides a unique identifier for each running task
"""
try:
return os.getenv('PBS_NODENUM')
except:
raise Exception("PBS_NODENUM environment variable not defined.")
def hostlist(self):
""" Generates list of allocated cores
"""
with open(os.environ['PBS_NODEFILE'], 'r') as f:
return [line.strip() for line in f.readlines()]
def save_kwargs(self, classname, method, kwargs):
kwargspath = join(PATH.OUTPUT, 'kwargs')
kwargsfile = join(kwargspath, classname+'_'+method+'.p')
unix.mkdir(kwargspath)
saveobj(kwargsfile, kwargs) | 0.29931 | 0.106784 |
import unittest
import sys
import os
sys.path.append(os.path.abspath(os.path.join(__file__, "../../python")))
from petitBloc import block
from petitBloc import box
from petitBloc import port
from petitBloc import chain
from petitBloc import workerManager
from petitBloc import const
import time
class MakeNumbers(block.Block):
def __init__(self, name="", parent=None):
super(MakeNumbers, self).__init__(name=name, parent=parent)
def initialize(self):
self.addOutput(int)
self.addParam(int, "start", 0)
self.addParam(int, "stop", 10)
self.addParam(int, "step", 1)
def run(self):
self.debug("MakeNumbers start")
start = self.param("start").get()
stop = self.param("stop").get()
step = self.param("step").get()
if step < 1:
step = 1
self.debug("start : {} stop : {} step : {}".format(start, stop, step))
for n in range(start, stop, step):
self.output(0).send(n)
self.debug("send value {}".format(str(n)))
self.warn("testing")
self.debug("MakeNumbers end")
class RaiseError(block.Block):
def __init__(self, name="", parent=None):
super(RaiseError, self).__init__(name=name, parent=parent)
def initialize(self):
self.addInput(int)
self.addParam(int, "value", 0)
def process(self):
in_f = self.input(0).receive()
if in_f.isEOP():
return False
self.debug("receive value {}".format(str(in_f.value())))
if in_f.value() == self.param(0).get():
self.error("raise error!")
raise Exception, "Test Error at : {}".format(in_f.value())
in_f.drop()
return True
class LoggingTest(unittest.TestCase):
def test_packetHistory(self):
src_port = port.OutPort(int)
dst_port = port.InPort(int)
chan = chain.Chain(src_port, dst_port)
src_port.activate()
dst_port.activate()
src_port.send(1)
time.sleep(0.1)
src_port.send(2)
time.sleep(0.1)
dst_port.receive()
time.sleep(0.1)
src_port.terminate()
dst_port.terminate()
self.assertEqual(src_port.packetHistory(), [1, 2])
self.assertEqual(dst_port.packetHistory(), [1])
self.assertEqual(workerManager.WorkerManager.QueueCount(), 0)
def test_error(self):
workerManager.WorkerManager.SetUseProcess(False)
workerManager.WorkerManager.SetLogLevel(const.LogLevel.NoLog)
b = box.Box()
m = MakeNumbers()
e = RaiseError()
b.addBlock(m)
b.addBlock(e)
e.param("value").set(5)
chain.Chain(m.output(0), e.input(0))
workerManager.WorkerManager.RunSchedule(b.getSchedule())
self.assertTrue(e.isFailed())
self.assertFalse(e.isTerminated())
def test_state(self):
workerManager.WorkerManager.SetUseProcess(False)
workerManager.WorkerManager.SetLogLevel(const.LogLevel.NoLog)
b = box.Box("scene")
m = MakeNumbers()
e = RaiseError()
b.addBlock(m)
b.addBlock(e)
e.param("value").set(5)
chain.Chain(m.output(0), e.input(0))
workerManager.WorkerManager.RunSchedule(b.getSchedule())
self.assertEqual(workerManager.WorkerManager.ExecutionCount(), 5)
self.assertTrue(workerManager.WorkerManager.TotalTime() > 0)
self.assertEqual(workerManager.WorkerManager.AverageTime(), workerManager.WorkerManager.TotalTime() / float(workerManager.WorkerManager.ExecutionCount()))
self.assertTrue(workerManager.WorkerManager.TimeLog(e.path()) > 0)
self.assertTrue(workerManager.WorkerManager.TimeLog(m.path()) > 0)
workerManager.WorkerManager.SetUseProcess(True)
workerManager.WorkerManager.RunSchedule(b.getSchedule())
self.assertEqual(workerManager.WorkerManager.ExecutionCount(), 5)
self.assertTrue(workerManager.WorkerManager.TotalTime() > 0)
self.assertEqual(workerManager.WorkerManager.AverageTime(), workerManager.WorkerManager.TotalTime() / float(workerManager.WorkerManager.ExecutionCount()))
self.assertTrue(workerManager.WorkerManager.TimeLog(e.path()) > 0)
self.assertTrue(workerManager.WorkerManager.TimeLog(m.path()) > 0)
def test_logging(self):
workerManager.WorkerManager.SetLogLevel(const.LogLevel.NoLog)
workerManager.WorkerManager.SetUseProcess(True)
b = box.Box("scene")
m = MakeNumbers()
e = RaiseError()
e2 = RaiseError()
b.addBlock(m)
b.addBlock(e)
b.addBlock(e2)
e.param("value").set(5)
chain.Chain(m.output(0), e.input(0))
chain.Chain(m.output(0), e2.input(0))
workerManager.WorkerManager.RunSchedule(b.getSchedule())
self.assertEqual(len(workerManager.WorkerManager.ErrorLogs().keys()), 2)
self.assertEqual(len(workerManager.WorkerManager.ErrorLog(e2.path())), 2)
self.assertEqual(len(workerManager.WorkerManager.WarnLogs().keys()), 1)
self.assertEqual(len(workerManager.WorkerManager.WarnLog(m.path())), 1)
self.assertEqual(len(workerManager.WorkerManager.DebugLog(e.path())), 6)
self.assertEqual(len(workerManager.WorkerManager.DebugLog(e2.path())), 1)
workerManager.WorkerManager.SetUseProcess(False)
workerManager.WorkerManager.RunSchedule(b.getSchedule())
self.assertEqual(len(workerManager.WorkerManager.ErrorLogs().keys()), 2)
self.assertEqual(len(workerManager.WorkerManager.ErrorLog(e2.path())), 2)
self.assertEqual(len(workerManager.WorkerManager.WarnLogs().keys()), 1)
self.assertEqual(len(workerManager.WorkerManager.WarnLog(m.path())), 1)
self.assertEqual(len(workerManager.WorkerManager.DebugLog(e.path())), 6)
self.assertEqual(len(workerManager.WorkerManager.DebugLog(e2.path())), 1)
if __name__ == "__main__":
unittest.main() | test/logging_test.py | import unittest
import sys
import os
sys.path.append(os.path.abspath(os.path.join(__file__, "../../python")))
from petitBloc import block
from petitBloc import box
from petitBloc import port
from petitBloc import chain
from petitBloc import workerManager
from petitBloc import const
import time
class MakeNumbers(block.Block):
def __init__(self, name="", parent=None):
super(MakeNumbers, self).__init__(name=name, parent=parent)
def initialize(self):
self.addOutput(int)
self.addParam(int, "start", 0)
self.addParam(int, "stop", 10)
self.addParam(int, "step", 1)
def run(self):
self.debug("MakeNumbers start")
start = self.param("start").get()
stop = self.param("stop").get()
step = self.param("step").get()
if step < 1:
step = 1
self.debug("start : {} stop : {} step : {}".format(start, stop, step))
for n in range(start, stop, step):
self.output(0).send(n)
self.debug("send value {}".format(str(n)))
self.warn("testing")
self.debug("MakeNumbers end")
class RaiseError(block.Block):
def __init__(self, name="", parent=None):
super(RaiseError, self).__init__(name=name, parent=parent)
def initialize(self):
self.addInput(int)
self.addParam(int, "value", 0)
def process(self):
in_f = self.input(0).receive()
if in_f.isEOP():
return False
self.debug("receive value {}".format(str(in_f.value())))
if in_f.value() == self.param(0).get():
self.error("raise error!")
raise Exception, "Test Error at : {}".format(in_f.value())
in_f.drop()
return True
class LoggingTest(unittest.TestCase):
def test_packetHistory(self):
src_port = port.OutPort(int)
dst_port = port.InPort(int)
chan = chain.Chain(src_port, dst_port)
src_port.activate()
dst_port.activate()
src_port.send(1)
time.sleep(0.1)
src_port.send(2)
time.sleep(0.1)
dst_port.receive()
time.sleep(0.1)
src_port.terminate()
dst_port.terminate()
self.assertEqual(src_port.packetHistory(), [1, 2])
self.assertEqual(dst_port.packetHistory(), [1])
self.assertEqual(workerManager.WorkerManager.QueueCount(), 0)
def test_error(self):
workerManager.WorkerManager.SetUseProcess(False)
workerManager.WorkerManager.SetLogLevel(const.LogLevel.NoLog)
b = box.Box()
m = MakeNumbers()
e = RaiseError()
b.addBlock(m)
b.addBlock(e)
e.param("value").set(5)
chain.Chain(m.output(0), e.input(0))
workerManager.WorkerManager.RunSchedule(b.getSchedule())
self.assertTrue(e.isFailed())
self.assertFalse(e.isTerminated())
def test_state(self):
workerManager.WorkerManager.SetUseProcess(False)
workerManager.WorkerManager.SetLogLevel(const.LogLevel.NoLog)
b = box.Box("scene")
m = MakeNumbers()
e = RaiseError()
b.addBlock(m)
b.addBlock(e)
e.param("value").set(5)
chain.Chain(m.output(0), e.input(0))
workerManager.WorkerManager.RunSchedule(b.getSchedule())
self.assertEqual(workerManager.WorkerManager.ExecutionCount(), 5)
self.assertTrue(workerManager.WorkerManager.TotalTime() > 0)
self.assertEqual(workerManager.WorkerManager.AverageTime(), workerManager.WorkerManager.TotalTime() / float(workerManager.WorkerManager.ExecutionCount()))
self.assertTrue(workerManager.WorkerManager.TimeLog(e.path()) > 0)
self.assertTrue(workerManager.WorkerManager.TimeLog(m.path()) > 0)
workerManager.WorkerManager.SetUseProcess(True)
workerManager.WorkerManager.RunSchedule(b.getSchedule())
self.assertEqual(workerManager.WorkerManager.ExecutionCount(), 5)
self.assertTrue(workerManager.WorkerManager.TotalTime() > 0)
self.assertEqual(workerManager.WorkerManager.AverageTime(), workerManager.WorkerManager.TotalTime() / float(workerManager.WorkerManager.ExecutionCount()))
self.assertTrue(workerManager.WorkerManager.TimeLog(e.path()) > 0)
self.assertTrue(workerManager.WorkerManager.TimeLog(m.path()) > 0)
def test_logging(self):
workerManager.WorkerManager.SetLogLevel(const.LogLevel.NoLog)
workerManager.WorkerManager.SetUseProcess(True)
b = box.Box("scene")
m = MakeNumbers()
e = RaiseError()
e2 = RaiseError()
b.addBlock(m)
b.addBlock(e)
b.addBlock(e2)
e.param("value").set(5)
chain.Chain(m.output(0), e.input(0))
chain.Chain(m.output(0), e2.input(0))
workerManager.WorkerManager.RunSchedule(b.getSchedule())
self.assertEqual(len(workerManager.WorkerManager.ErrorLogs().keys()), 2)
self.assertEqual(len(workerManager.WorkerManager.ErrorLog(e2.path())), 2)
self.assertEqual(len(workerManager.WorkerManager.WarnLogs().keys()), 1)
self.assertEqual(len(workerManager.WorkerManager.WarnLog(m.path())), 1)
self.assertEqual(len(workerManager.WorkerManager.DebugLog(e.path())), 6)
self.assertEqual(len(workerManager.WorkerManager.DebugLog(e2.path())), 1)
workerManager.WorkerManager.SetUseProcess(False)
workerManager.WorkerManager.RunSchedule(b.getSchedule())
self.assertEqual(len(workerManager.WorkerManager.ErrorLogs().keys()), 2)
self.assertEqual(len(workerManager.WorkerManager.ErrorLog(e2.path())), 2)
self.assertEqual(len(workerManager.WorkerManager.WarnLogs().keys()), 1)
self.assertEqual(len(workerManager.WorkerManager.WarnLog(m.path())), 1)
self.assertEqual(len(workerManager.WorkerManager.DebugLog(e.path())), 6)
self.assertEqual(len(workerManager.WorkerManager.DebugLog(e2.path())), 1)
if __name__ == "__main__":
unittest.main() | 0.339061 | 0.36523 |
import collections
import glob
import os
import pickle
import re
import numpy as np
import scipy.stats as stats
from nasbench_analysis.eval_darts_one_shot_model_in_nasbench import natural_keys
def parse_log(path):
f = open(os.path.join(path, 'log.txt'), 'r')
# Read in the relevant information
train_accuracies = []
valid_accuracies = []
for line in f:
if 'train_acc' in line:
train_accuracies.append(line)
if 'valid_acc' in line:
valid_accuracies.append(line)
valid_error = [[1 - 1 / 100 * float(re.search('valid_acc ([-+]?[0-9]*\.?[0-9]+)', line).group(1))] for line in
valid_accuracies]
train_error = [[1 - 1 / 100 * float(re.search('train_acc ([-+]?[0-9]*\.?[0-9]+)', line).group(1))] for line in
train_accuracies]
return valid_error, train_error
def compute_spearman_correlation_top_1000(one_shot_test_error, nb_test_error):
sort_by_one_shot = lambda os, nb: [[y, x] for (y, x) in sorted(zip(os, nb), key=lambda pair: pair[0])]
correlation_at_epoch = []
for one_shot_test_error_on_epoch in one_shot_test_error:
sorted_by_os_error = np.array(sort_by_one_shot(one_shot_test_error_on_epoch[0], nb_test_error))
correlation_at_epoch.append(
stats.spearmanr(sorted_by_os_error[:, 0][:1000], sorted_by_os_error[:, 1][:1000]).correlation)
return correlation_at_epoch
def compute_spearman_correlation(one_shot_test_error, nb_test_error):
correlation_at_epoch = []
for one_shot_test_error_on_epoch in one_shot_test_error:
correlation_at_epoch.append(stats.spearmanr(one_shot_test_error_on_epoch[0], nb_test_error).correlation)
return correlation_at_epoch
def read_in_correlation(path, config):
correlation_files = glob.glob(os.path.join(path, 'correlation_*.obj'))
# If no correlation files available
if len(correlation_files) == 0:
return None, None
else:
read_file_list_with_pickle = lambda file_list: [pickle.load(open(file, 'rb')) for file in file_list]
correlation_files.sort(key=natural_keys)
one_shot_test_errors = glob.glob(os.path.join(path, 'one_shot_test_errors_*'))
one_shot_test_errors.sort(key=natural_keys)
one_shot_test_errors = read_file_list_with_pickle(one_shot_test_errors)
if config['search_space'] == '1':
nb_test_errors_per_epoch = pickle.load(
open('experiments/analysis/data/test_errors_per_epoch_ss1.obj', 'rb'))
elif config['search_space'] == '2':
nb_test_errors_per_epoch = pickle.load(
open('experiments/analysis/data/test_errors_per_epoch_ss2.obj', 'rb'))
elif config['search_space'] == '3':
nb_test_errors_per_epoch = pickle.load(
open('experiments/analysis/data/test_errors_per_epoch_ss3.obj', 'rb'))
else:
raise ValueError('Unknown search space')
correlation_per_epoch_total = {
epoch: compute_spearman_correlation(one_shot_test_errors, nb_test_errors_at_epoch) for
epoch, nb_test_errors_at_epoch in nb_test_errors_per_epoch.items()}
correlation_per_epoch_top = {
epoch: compute_spearman_correlation_top_1000(one_shot_test_errors, nb_test_errors_at_epoch) for
epoch, nb_test_errors_at_epoch in nb_test_errors_per_epoch.items()}
return collections.OrderedDict(sorted(correlation_per_epoch_total.items())), collections.OrderedDict(
sorted(correlation_per_epoch_top.items())) | experiments/analysis/utils.py | import collections
import glob
import os
import pickle
import re
import numpy as np
import scipy.stats as stats
from nasbench_analysis.eval_darts_one_shot_model_in_nasbench import natural_keys
def parse_log(path):
f = open(os.path.join(path, 'log.txt'), 'r')
# Read in the relevant information
train_accuracies = []
valid_accuracies = []
for line in f:
if 'train_acc' in line:
train_accuracies.append(line)
if 'valid_acc' in line:
valid_accuracies.append(line)
valid_error = [[1 - 1 / 100 * float(re.search('valid_acc ([-+]?[0-9]*\.?[0-9]+)', line).group(1))] for line in
valid_accuracies]
train_error = [[1 - 1 / 100 * float(re.search('train_acc ([-+]?[0-9]*\.?[0-9]+)', line).group(1))] for line in
train_accuracies]
return valid_error, train_error
def compute_spearman_correlation_top_1000(one_shot_test_error, nb_test_error):
sort_by_one_shot = lambda os, nb: [[y, x] for (y, x) in sorted(zip(os, nb), key=lambda pair: pair[0])]
correlation_at_epoch = []
for one_shot_test_error_on_epoch in one_shot_test_error:
sorted_by_os_error = np.array(sort_by_one_shot(one_shot_test_error_on_epoch[0], nb_test_error))
correlation_at_epoch.append(
stats.spearmanr(sorted_by_os_error[:, 0][:1000], sorted_by_os_error[:, 1][:1000]).correlation)
return correlation_at_epoch
def compute_spearman_correlation(one_shot_test_error, nb_test_error):
correlation_at_epoch = []
for one_shot_test_error_on_epoch in one_shot_test_error:
correlation_at_epoch.append(stats.spearmanr(one_shot_test_error_on_epoch[0], nb_test_error).correlation)
return correlation_at_epoch
def read_in_correlation(path, config):
correlation_files = glob.glob(os.path.join(path, 'correlation_*.obj'))
# If no correlation files available
if len(correlation_files) == 0:
return None, None
else:
read_file_list_with_pickle = lambda file_list: [pickle.load(open(file, 'rb')) for file in file_list]
correlation_files.sort(key=natural_keys)
one_shot_test_errors = glob.glob(os.path.join(path, 'one_shot_test_errors_*'))
one_shot_test_errors.sort(key=natural_keys)
one_shot_test_errors = read_file_list_with_pickle(one_shot_test_errors)
if config['search_space'] == '1':
nb_test_errors_per_epoch = pickle.load(
open('experiments/analysis/data/test_errors_per_epoch_ss1.obj', 'rb'))
elif config['search_space'] == '2':
nb_test_errors_per_epoch = pickle.load(
open('experiments/analysis/data/test_errors_per_epoch_ss2.obj', 'rb'))
elif config['search_space'] == '3':
nb_test_errors_per_epoch = pickle.load(
open('experiments/analysis/data/test_errors_per_epoch_ss3.obj', 'rb'))
else:
raise ValueError('Unknown search space')
correlation_per_epoch_total = {
epoch: compute_spearman_correlation(one_shot_test_errors, nb_test_errors_at_epoch) for
epoch, nb_test_errors_at_epoch in nb_test_errors_per_epoch.items()}
correlation_per_epoch_top = {
epoch: compute_spearman_correlation_top_1000(one_shot_test_errors, nb_test_errors_at_epoch) for
epoch, nb_test_errors_at_epoch in nb_test_errors_per_epoch.items()}
return collections.OrderedDict(sorted(correlation_per_epoch_total.items())), collections.OrderedDict(
sorted(correlation_per_epoch_top.items())) | 0.533154 | 0.33444 |
# STDLIB
import io
import re
from textwrap import dedent
from warnings import warn
from astropy import config as _config
from astropy.utils.exceptions import AstropyWarning
__all__ = [
'Conf', 'conf', 'warn_or_raise', 'vo_raise', 'vo_reraise', 'vo_warn',
'warn_unknown_attrs', 'parse_vowarning', 'VOWarning',
'VOTableChangeWarning', 'VOTableSpecWarning',
'UnimplementedWarning', 'IOWarning', 'VOTableSpecError']
# NOTE: Cannot put this in __init__.py due to circular import.
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astropy.io.votable.exceptions`.
"""
max_warnings = _config.ConfigItem(
10,
'Number of times the same type of warning is displayed '
'before being suppressed',
cfgtype='integer')
conf = Conf()
def _format_message(message, name, config=None, pos=None):
if config is None:
config = {}
if pos is None:
pos = ('?', '?')
filename = config.get('filename', '?')
return f'{filename}:{pos[0]}:{pos[1]}: {name}: {message}'
def _suppressed_warning(warning, config, stacklevel=2):
warning_class = type(warning)
config.setdefault('_warning_counts', dict()).setdefault(warning_class, 0)
config['_warning_counts'][warning_class] += 1
message_count = config['_warning_counts'][warning_class]
if message_count <= conf.max_warnings:
if message_count == conf.max_warnings:
warning.formatted_message += \
' (suppressing further warnings of this type...)'
warn(warning, stacklevel=stacklevel+1)
def warn_or_raise(warning_class, exception_class=None, args=(), config=None,
pos=None, stacklevel=1):
"""
Warn or raise an exception, depending on the verify setting.
"""
if config is None:
config = {}
# NOTE: the default here is deliberately warn rather than ignore, since
# one would expect that calling warn_or_raise without config should not
# silence the warnings.
config_value = config.get('verify', 'warn')
if config_value == 'exception':
if exception_class is None:
exception_class = warning_class
vo_raise(exception_class, args, config, pos)
elif config_value == 'warn':
vo_warn(warning_class, args, config, pos, stacklevel=stacklevel+1)
def vo_raise(exception_class, args=(), config=None, pos=None):
"""
Raise an exception, with proper position information if available.
"""
if config is None:
config = {}
raise exception_class(args, config, pos)
def vo_reraise(exc, config=None, pos=None, additional=''):
"""
Raise an exception, with proper position information if available.
Restores the original traceback of the exception, and should only
be called within an "except:" block of code.
"""
if config is None:
config = {}
message = _format_message(str(exc), exc.__class__.__name__, config, pos)
if message.split()[0] == str(exc).split()[0]:
message = str(exc)
if len(additional):
message += ' ' + additional
exc.args = (message,)
raise exc
def vo_warn(warning_class, args=(), config=None, pos=None, stacklevel=1):
"""
Warn, with proper position information if available.
"""
if config is None:
config = {}
# NOTE: the default here is deliberately warn rather than ignore, since
# one would expect that calling warn_or_raise without config should not
# silence the warnings.
if config.get('verify', 'warn') != 'ignore':
warning = warning_class(args, config, pos)
_suppressed_warning(warning, config, stacklevel=stacklevel+1)
def warn_unknown_attrs(element, attrs, config, pos, good_attr=[], stacklevel=1):
for attr in attrs:
if attr not in good_attr:
vo_warn(W48, (attr, element), config, pos, stacklevel=stacklevel+1)
_warning_pat = re.compile(
r":?(?P<nline>[0-9?]+):(?P<nchar>[0-9?]+): " +
r"((?P<warning>[WE]\d+): )?(?P<rest>.*)$")
def parse_vowarning(line):
"""
Parses the vo warning string back into its parts.
"""
result = {}
match = _warning_pat.search(line)
if match:
result['warning'] = warning = match.group('warning')
if warning is not None:
result['is_warning'] = (warning[0].upper() == 'W')
result['is_exception'] = not result['is_warning']
result['number'] = int(match.group('warning')[1:])
result['doc_url'] = f"io/votable/api_exceptions.html#{warning.lower()}"
else:
result['is_warning'] = False
result['is_exception'] = False
result['is_other'] = True
result['number'] = None
result['doc_url'] = None
try:
result['nline'] = int(match.group('nline'))
except ValueError:
result['nline'] = 0
try:
result['nchar'] = int(match.group('nchar'))
except ValueError:
result['nchar'] = 0
result['message'] = match.group('rest')
result['is_something'] = True
else:
result['warning'] = None
result['is_warning'] = False
result['is_exception'] = False
result['is_other'] = False
result['is_something'] = False
if not isinstance(line, str):
line = line.decode('utf-8')
result['message'] = line
return result
class VOWarning(AstropyWarning):
"""
The base class of all VO warnings and exceptions.
Handles the formatting of the message with a warning or exception
code, filename, line and column number.
"""
default_args = ()
message_template = ''
def __init__(self, args, config=None, pos=None):
if config is None:
config = {}
if not isinstance(args, tuple):
args = (args, )
msg = self.message_template.format(*args)
self.formatted_message = _format_message(
msg, self.__class__.__name__, config, pos)
Warning.__init__(self, self.formatted_message)
def __str__(self):
return self.formatted_message
@classmethod
def get_short_name(cls):
if len(cls.default_args):
return cls.message_template.format(*cls.default_args)
return cls.message_template
class VOTableChangeWarning(VOWarning, SyntaxWarning):
"""
A change has been made to the input XML file.
"""
class VOTableSpecWarning(VOWarning, SyntaxWarning):
"""
The input XML file violates the spec, but there is an obvious workaround.
"""
class UnimplementedWarning(VOWarning, SyntaxWarning):
"""
A feature of the VOTABLE_ spec is not implemented.
"""
class IOWarning(VOWarning, RuntimeWarning):
"""
A network or IO error occurred, but was recovered using the cache.
"""
class VOTableSpecError(VOWarning, ValueError):
"""
The input XML file violates the spec and there is no good workaround.
"""
class W01(VOTableSpecWarning):
"""
The VOTable spec states:
If a cell contains an array or complex number, it should be
encoded as multiple numbers separated by whitespace.
Many VOTable files in the wild use commas as a separator instead,
and ``astropy.io.votable`` supports this convention when not in
:ref:`pedantic-mode`.
``astropy.io.votable`` always outputs files using only spaces, regardless of
how they were input.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#toc-header-35>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:TABLEDATA>`__
"""
message_template = "Array uses commas rather than whitespace"
class W02(VOTableSpecWarning):
r"""
XML ids must match the following regular expression::
^[A-Za-z_][A-Za-z0-9_\.\-]*$
The VOTable 1.1 says the following:
According to the XML standard, the attribute ``ID`` is a
string beginning with a letter or underscore (``_``), followed
by a sequence of letters, digits, or any of the punctuation
characters ``.`` (dot), ``-`` (dash), ``_`` (underscore), or
``:`` (colon).
However, this is in conflict with the XML standard, which says
colons may not be used. VOTable 1.1's own schema does not allow a
colon here. Therefore, ``astropy.io.votable`` disallows the colon.
VOTable 1.2 corrects this error in the specification.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:name>`__,
`XML Names <http://www.w3.org/TR/REC-xml/#NT-Name>`__
"""
message_template = "{} attribute '{}' is invalid. Must be a standard XML id"
default_args = ('x', 'y')
class W03(VOTableChangeWarning):
"""
The VOTable 1.1 spec says the following about ``name`` vs. ``ID``
on ``FIELD`` and ``VALUE`` elements:
``ID`` and ``name`` attributes have a different role in
VOTable: the ``ID`` is meant as a *unique identifier* of an
element seen as a VOTable component, while the ``name`` is
meant for presentation purposes, and need not to be unique
throughout the VOTable document. The ``ID`` attribute is
therefore required in the elements which have to be
referenced, but in principle any element may have an ``ID``
attribute. ... In summary, the ``ID`` is different from the
``name`` attribute in that (a) the ``ID`` attribute is made
from a restricted character set, and must be unique throughout
a VOTable document whereas names are standard XML attributes
and need not be unique; and (b) there should be support in the
parsing software to look up references and extract the
relevant element with matching ``ID``.
It is further recommended in the VOTable 1.2 spec:
While the ``ID`` attribute has to be unique in a VOTable
document, the ``name`` attribute need not. It is however
recommended, as a good practice, to assign unique names within
a ``TABLE`` element. This recommendation means that, between a
``TABLE`` and its corresponding closing ``TABLE`` tag,
``name`` attributes of ``FIELD``, ``PARAM`` and optional
``GROUP`` elements should be all different.
Since ``astropy.io.votable`` requires a unique identifier for each of its
columns, ``ID`` is used for the column name when present.
However, when ``ID`` is not present, (since it is not required by
the specification) ``name`` is used instead. However, ``name``
must be cleansed by replacing invalid characters (such as
whitespace) with underscores.
.. note::
This warning does not indicate that the input file is invalid
with respect to the VOTable specification, only that the
column names in the record array may not match exactly the
``name`` attributes specified in the file.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:name>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:name>`__
"""
message_template = "Implicitly generating an ID from a name '{}' -> '{}'"
default_args = ('x', 'y')
class W04(VOTableSpecWarning):
"""
The ``content-type`` attribute must use MIME content-type syntax as
defined in `RFC 2046 <https://tools.ietf.org/html/rfc2046>`__.
The current check for validity is somewhat over-permissive.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:link>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:link>`__
"""
message_template = "content-type '{}' must be a valid MIME content type"
default_args = ('x',)
class W05(VOTableSpecWarning):
"""
The attribute must be a valid URI as defined in `RFC 2396
<https://www.ietf.org/rfc/rfc2396.txt>`_.
"""
message_template = "'{}' is not a valid URI"
default_args = ('x',)
class W06(VOTableSpecWarning):
"""
This warning is emitted when a ``ucd`` attribute does not match
the syntax of a `unified content descriptor
<http://vizier.u-strasbg.fr/doc/UCD.htx>`__.
If the VOTable version is 1.2 or later, the UCD will also be
checked to ensure it conforms to the controlled vocabulary defined
by UCD1+.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:ucd>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:ucd>`__
"""
message_template = "Invalid UCD '{}': {}"
default_args = ('x', 'explanation')
class W07(VOTableSpecWarning):
"""
As astro year field is a Besselian or Julian year matching the
regular expression::
^[JB]?[0-9]+([.][0-9]*)?$
Defined in this XML Schema snippet::
<xs:simpleType name="astroYear">
<xs:restriction base="xs:token">
<xs:pattern value="[JB]?[0-9]+([.][0-9]*)?"/>
</xs:restriction>
</xs:simpleType>
"""
message_template = "Invalid astroYear in {}: '{}'"
default_args = ('x', 'y')
class W08(VOTableSpecWarning):
"""
To avoid local-dependent number parsing differences, ``astropy.io.votable``
may require a string or unicode string where a numeric type may
make more sense.
"""
message_template = "'{}' must be a str or bytes object"
default_args = ('x',)
class W09(VOTableSpecWarning):
"""
The VOTable specification uses the attribute name ``ID`` (with
uppercase letters) to specify unique identifiers. Some
VOTable-producing tools use the more standard lowercase ``id``
instead. ``astropy.io.votable`` accepts ``id`` and emits this warning if
``verify`` is ``'warn'``.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:name>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:name>`__
"""
message_template = "ID attribute not capitalized"
class W10(VOTableSpecWarning):
"""
The parser has encountered an element that does not exist in the
specification, or appears in an invalid context. Check the file
against the VOTable schema (with a tool such as `xmllint
<http://xmlsoft.org/xmllint.html>`__. If the file validates
against the schema, and you still receive this warning, this may
indicate a bug in ``astropy.io.votable``.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC54>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC58>`__
"""
message_template = "Unknown tag '{}'. Ignoring"
default_args = ('x',)
class W11(VOTableSpecWarning):
"""
Earlier versions of the VOTable specification used a ``gref``
attribute on the ``LINK`` element to specify a `GLU reference
<http://aladin.u-strasbg.fr/glu/>`__. New files should
specify a ``glu:`` protocol using the ``href`` attribute.
Since ``astropy.io.votable`` does not currently support GLU references, it
likewise does not automatically convert the ``gref`` attribute to
the new form.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:link>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:link>`__
"""
message_template = "The gref attribute on LINK is deprecated in VOTable 1.1"
class W12(VOTableChangeWarning):
"""
In order to name the columns of the Numpy record array, each
``FIELD`` element must have either an ``ID`` or ``name`` attribute
to derive a name from. Strictly speaking, according to the
VOTable schema, the ``name`` attribute is required. However, if
``name`` is not present by ``ID`` is, and ``verify`` is not ``'exception'``,
``astropy.io.votable`` will continue without a ``name`` defined.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:name>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:name>`__
"""
message_template = (
"'{}' element must have at least one of 'ID' or 'name' attributes")
default_args = ('x',)
class W13(VOTableSpecWarning):
"""
Some VOTable files in the wild use non-standard datatype names. These
are mapped to standard ones using the following mapping::
string -> char
unicodeString -> unicodeChar
int16 -> short
int32 -> int
int64 -> long
float32 -> float
float64 -> double
unsignedInt -> long
unsignedShort -> int
To add more datatype mappings during parsing, use the
``datatype_mapping`` keyword to `astropy.io.votable.parse`.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:datatypes>`__
"""
message_template = "'{}' is not a valid VOTable datatype, should be '{}'"
default_args = ('x', 'y')
# W14: Deprecated
class W15(VOTableSpecWarning):
"""
The ``name`` attribute is required on every ``FIELD`` element.
However, many VOTable files in the wild omit it and provide only
an ``ID`` instead. In this case, when ``verify`` is not ``'exception'``
``astropy.io.votable`` will copy the ``name`` attribute to a new ``ID``
attribute.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:name>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:name>`__
"""
message_template = "{} element missing required 'name' attribute"
default_args = ('x',)
# W16: Deprecated
class W17(VOTableSpecWarning):
"""
A ``DESCRIPTION`` element can only appear once within its parent
element.
According to the schema, it may only occur once (`1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC54>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC58>`__)
However, it is a `proposed extension
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:addesc>`__
to VOTable 1.2.
"""
message_template = "{} element contains more than one DESCRIPTION element"
default_args = ('x',)
class W18(VOTableSpecWarning):
"""
The number of rows explicitly specified in the ``nrows`` attribute
does not match the actual number of rows (``TR`` elements) present
in the ``TABLE``. This may indicate truncation of the file, or an
internal error in the tool that produced it. If ``verify`` is not
``'exception'``, parsing will proceed, with the loss of some performance.
**References:** `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC10>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC10>`__
"""
message_template = 'TABLE specified nrows={}, but table contains {} rows'
default_args = ('x', 'y')
class W19(VOTableSpecWarning):
"""
The column fields as defined using ``FIELD`` elements do not match
those in the headers of the embedded FITS file. If ``verify`` is not
``'exception'``, the embedded FITS file will take precedence.
"""
message_template = (
'The fields defined in the VOTable do not match those in the ' +
'embedded FITS file')
class W20(VOTableSpecWarning):
"""
If no version number is explicitly given in the VOTable file, the
parser assumes it is written to the VOTable 1.1 specification.
"""
message_template = 'No version number specified in file. Assuming {}'
default_args = ('1.1',)
class W21(UnimplementedWarning):
"""
Unknown issues may arise using ``astropy.io.votable`` with VOTable files
from a version other than 1.1, 1.2, 1.3, or 1.4.
"""
message_template = (
'astropy.io.votable is designed for VOTable version 1.1, 1.2, 1.3,'
' and 1.4, but this file is {}')
default_args = ('x',)
class W22(VOTableSpecWarning):
"""
Version 1.0 of the VOTable specification used the ``DEFINITIONS``
element to define coordinate systems. Version 1.1 now uses
``COOSYS`` elements throughout the document.
**References:** `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:definitions>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:definitions>`__
"""
message_template = 'The DEFINITIONS element is deprecated in VOTable 1.1. Ignoring'
class W23(IOWarning):
"""
Raised when the VO service database can not be updated (possibly
due to a network outage). This is only a warning, since an older
and possible out-of-date VO service database was available
locally.
"""
message_template = "Unable to update service information for '{}'"
default_args = ('x',)
class W24(VOWarning, FutureWarning):
"""
The VO catalog database retrieved from the www is designed for a
newer version of ``astropy.io.votable``. This may cause problems or limited
features performing service queries. Consider upgrading ``astropy.io.votable``
to the latest version.
"""
message_template = "The VO catalog database is for a later version of astropy.io.votable"
class W25(IOWarning):
"""
A VO service query failed due to a network error or malformed
arguments. Another alternative service may be attempted. If all
services fail, an exception will be raised.
"""
message_template = "'{}' failed with: {}"
default_args = ('service', '...')
class W26(VOTableSpecWarning):
"""
The given element was not supported inside of the given element
until the specified VOTable version, however the version declared
in the file is for an earlier version. These attributes may not
be written out to the file.
"""
message_template = "'{}' inside '{}' added in VOTable {}"
default_args = ('child', 'parent', 'X.X')
class W27(VOTableSpecWarning):
"""
The ``COOSYS`` element was deprecated in VOTABLE version 1.2 in
favor of a reference to the Space-Time Coordinate (STC) data
model (see `utype
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:utype>`__
and the IVOA note `referencing STC in VOTable
<http://ivoa.net/Documents/latest/VOTableSTC.html>`__.
"""
message_template = "COOSYS deprecated in VOTable 1.2"
class W28(VOTableSpecWarning):
"""
The given attribute was not supported on the given element until the
specified VOTable version, however the version declared in the file is
for an earlier version. These attributes may not be written out to
the file.
"""
message_template = "'{}' on '{}' added in VOTable {}"
default_args = ('attribute', 'element', 'X.X')
class W29(VOTableSpecWarning):
"""
Some VOTable files specify their version number in the form "v1.0",
when the only supported forms in the spec are "1.0".
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC54>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC58>`__
"""
message_template = "Version specified in non-standard form '{}'"
default_args = ('v1.0',)
class W30(VOTableSpecWarning):
"""
Some VOTable files write missing floating-point values in non-standard ways,
such as "null" and "-". If ``verify`` is not ``'exception'``, any
non-standard floating-point literals are treated as missing values.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:datatypes>`__
"""
message_template = "Invalid literal for float '{}'. Treating as empty."
default_args = ('x',)
class W31(VOTableSpecWarning):
"""
Since NaN's can not be represented in integer fields directly, a null
value must be specified in the FIELD descriptor to support reading
NaN's from the tabledata.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:datatypes>`__
"""
message_template = "NaN given in an integral field without a specified null value"
class W32(VOTableSpecWarning):
"""
Each field in a table must have a unique ID. If two or more fields
have the same ID, some will be renamed to ensure that all IDs are
unique.
From the VOTable 1.2 spec:
The ``ID`` and ``ref`` attributes are defined as XML types
``ID`` and ``IDREF`` respectively. This means that the
contents of ``ID`` is an identifier which must be unique
throughout a VOTable document, and that the contents of the
``ref`` attribute represents a reference to an identifier
which must exist in the VOTable document.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:name>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:name>`__
"""
message_template = "Duplicate ID '{}' renamed to '{}' to ensure uniqueness"
default_args = ('x', 'x_2')
class W33(VOTableChangeWarning):
"""
Each field in a table must have a unique name. If two or more
fields have the same name, some will be renamed to ensure that all
names are unique.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:name>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:name>`__
"""
message_template = "Column name '{}' renamed to '{}' to ensure uniqueness"
default_args = ('x', 'x_2')
class W34(VOTableSpecWarning):
"""
The attribute requires the value to be a valid XML token, as
defined by `XML 1.0
<http://www.w3.org/TR/2000/WD-xml-2e-20000814#NT-Nmtoken>`__.
"""
message_template = "'{}' is an invalid token for attribute '{}'"
default_args = ('x', 'y')
class W35(VOTableSpecWarning):
"""
The ``name`` and ``value`` attributes are required on all ``INFO``
elements.
**References:** `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC54>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC32>`__
"""
message_template = "'{}' attribute required for INFO elements"
default_args = ('x',)
class W36(VOTableSpecWarning):
"""
If the field specifies a ``null`` value, that value must conform
to the given ``datatype``.
**References:** `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:values>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:values>`__
"""
message_template = "null value '{}' does not match field datatype, setting to 0"
default_args = ('x',)
class W37(UnimplementedWarning):
"""
The 3 datatypes defined in the VOTable specification and supported by
``astropy.io.votable`` are ``TABLEDATA``, ``BINARY`` and ``FITS``.
**References:** `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:data>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:data>`__
"""
message_template = "Unsupported data format '{}'"
default_args = ('x',)
class W38(VOTableSpecWarning):
"""
The only encoding for local binary data supported by the VOTable
specification is base64.
"""
message_template = "Inline binary data must be base64 encoded, got '{}'"
default_args = ('x',)
class W39(VOTableSpecWarning):
"""
Bit values do not support masking. This warning is raised upon
setting masked data in a bit column.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:datatypes>`__
"""
message_template = "Bit values can not be masked"
class W40(VOTableSpecWarning):
"""
This is a terrible hack to support Simple Image Access Protocol
results from `archive.noao.edu <http://archive.noao.edu>`__. It
creates a field for the coordinate projection type of type "double",
which actually contains character data. We have to hack the field
to store character data, or we can't read it in. A warning will be
raised when this happens.
"""
message_template = "'cprojection' datatype repaired"
class W41(VOTableSpecWarning):
"""
An XML namespace was specified on the ``VOTABLE`` element, but the
namespace does not match what is expected for a ``VOTABLE`` file.
The ``VOTABLE`` namespace is::
http://www.ivoa.net/xml/VOTable/vX.X
where "X.X" is the version number.
Some files in the wild set the namespace to the location of the
VOTable schema, which is not correct and will not pass some
validating parsers.
"""
message_template = (
"An XML namespace is specified, but is incorrect. Expected " +
"'{}', got '{}'")
default_args = ('x', 'y')
class W42(VOTableSpecWarning):
"""
The root element should specify a namespace.
The ``VOTABLE`` namespace is::
http://www.ivoa.net/xml/VOTable/vX.X
where "X.X" is the version number.
"""
message_template = "No XML namespace specified"
class W43(VOTableSpecWarning):
"""
Referenced elements should be defined before referees. From the
VOTable 1.2 spec:
In VOTable1.2, it is further recommended to place the ID
attribute prior to referencing it whenever possible.
"""
message_template = "{} ref='{}' which has not already been defined"
default_args = ('element', 'x',)
class W44(VOTableSpecWarning):
"""
``VALUES`` elements that reference another element should not have
their own content.
From the VOTable 1.2 spec:
The ``ref`` attribute of a ``VALUES`` element can be used to
avoid a repetition of the domain definition, by referring to a
previously defined ``VALUES`` element having the referenced
``ID`` attribute. When specified, the ``ref`` attribute
defines completely the domain without any other element or
attribute, as e.g. ``<VALUES ref="RAdomain"/>``
"""
message_template = "VALUES element with ref attribute has content ('{}')"
default_args = ('element',)
class W45(VOWarning, ValueError):
"""
The ``content-role`` attribute on the ``LINK`` element must be one of
the following::
query, hints, doc, location
And in VOTable 1.3, additionally::
type
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC54>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC58>`__
`1.3
<http://www.ivoa.net/documents/VOTable/20130315/PR-VOTable-1.3-20130315.html#sec:link>`__
"""
message_template = "content-role attribute '{}' invalid"
default_args = ('x',)
class W46(VOTableSpecWarning):
"""
The given char or unicode string is too long for the specified
field length.
"""
message_template = "{} value is too long for specified length of {}"
default_args = ('char or unicode', 'x')
class W47(VOTableSpecWarning):
"""
If no arraysize is specified on a char field, the default of '1'
is implied, but this is rarely what is intended.
"""
message_template = "Missing arraysize indicates length 1"
class W48(VOTableSpecWarning):
"""
The attribute is not defined in the specification.
"""
message_template = "Unknown attribute '{}' on {}"
default_args = ('attribute', 'element')
class W49(VOTableSpecWarning):
"""
Prior to VOTable 1.3, the empty cell was illegal for integer
fields.
If a \"null\" value was specified for the cell, it will be used
for the value, otherwise, 0 will be used.
"""
message_template = "Empty cell illegal for integer fields."
class W50(VOTableSpecWarning):
"""
Invalid unit string as defined in the `Units in the VO, Version 1.0
<https://www.ivoa.net/documents/VOUnits>`_ (VOTable version >= 1.4)
or `Standards for Astronomical Catalogues, Version 2.0
<http://cdsarc.u-strasbg.fr/doc/catstd-3.2.htx>`_ (version < 1.4).
Consider passing an explicit ``unit_format`` parameter if the units
in this file conform to another specification.
"""
message_template = "Invalid unit string '{}'"
default_args = ('x',)
class W51(VOTableSpecWarning):
"""
The integer value is out of range for the size of the field.
"""
message_template = "Value '{}' is out of range for a {} integer field"
default_args = ('x', 'n-bit')
class W52(VOTableSpecWarning):
"""
The BINARY2 format was introduced in VOTable 1.3. It should
not be present in files marked as an earlier version.
"""
message_template = ("The BINARY2 format was introduced in VOTable 1.3, but "
"this file is declared as version '{}'")
default_args = ('1.2',)
class W53(VOTableSpecWarning):
"""
The VOTABLE element must contain at least one RESOURCE element.
"""
message_template = ("VOTABLE element must contain at least one RESOURCE element.")
default_args = ()
class W54(VOTableSpecWarning):
"""
The TIMESYS element was introduced in VOTable 1.4. It should
not be present in files marked as an earlier version.
"""
message_template = (
"The TIMESYS element was introduced in VOTable 1.4, but "
"this file is declared as version '{}'")
default_args = ('1.3',)
class W55(VOTableSpecWarning):
"""
When non-ASCII characters are detected when reading
a TABLEDATA value for a FIELD with ``datatype="char"``, we
can issue this warning.
"""
message_template = (
'FIELD ({}) has datatype="char" but contains non-ASCII '
'value ({})')
default_args = ('', '')
class E01(VOWarning, ValueError):
"""
The size specifier for a ``char`` or ``unicode`` field must be
only a number followed, optionally, by an asterisk.
Multi-dimensional size specifiers are not supported for these
datatypes.
Strings, which are defined as a set of characters, can be
represented in VOTable as a fixed- or variable-length array of
characters::
<FIELD name="unboundedString" datatype="char" arraysize="*"/>
A 1D array of strings can be represented as a 2D array of
characters, but given the logic above, it is possible to define a
variable-length array of fixed-length strings, but not a
fixed-length array of variable-length strings.
"""
message_template = "Invalid size specifier '{}' for a {} field (in field '{}')"
default_args = ('x', 'char/unicode', 'y')
class E02(VOWarning, ValueError):
"""
The number of array elements in the data does not match that specified
in the FIELD specifier.
"""
message_template = (
"Incorrect number of elements in array. " +
"Expected multiple of {}, got {}")
default_args = ('x', 'y')
class E03(VOWarning, ValueError):
"""
Complex numbers should be two values separated by whitespace.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:datatypes>`__
"""
message_template = "'{}' does not parse as a complex number"
default_args = ('x',)
class E04(VOWarning, ValueError):
"""
A ``bit`` array should be a string of '0's and '1's.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:datatypes>`__
"""
message_template = "Invalid bit value '{}'"
default_args = ('x',)
class E05(VOWarning, ValueError):
r"""
A ``boolean`` value should be one of the following strings (case
insensitive) in the ``TABLEDATA`` format::
'TRUE', 'FALSE', '1', '0', 'T', 'F', '\0', ' ', '?'
and in ``BINARY`` format::
'T', 'F', '1', '0', '\0', ' ', '?'
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:datatypes>`__
"""
message_template = "Invalid boolean value '{}'"
default_args = ('x',)
class E06(VOWarning, ValueError):
"""
The supported datatypes are::
double, float, bit, boolean, unsignedByte, short, int, long,
floatComplex, doubleComplex, char, unicodeChar
The following non-standard aliases are also supported, but in
these case :ref:`W13 <W13>` will be raised::
string -> char
unicodeString -> unicodeChar
int16 -> short
int32 -> int
int64 -> long
float32 -> float
float64 -> double
unsignedInt -> long
unsignedShort -> int
To add more datatype mappings during parsing, use the
``datatype_mapping`` keyword to `astropy.io.votable.parse`.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:datatypes>`__
"""
message_template = "Unknown datatype '{}' on field '{}'"
default_args = ('x', 'y')
# E07: Deprecated
class E08(VOWarning, ValueError):
"""
The ``type`` attribute on the ``VALUES`` element must be either
``legal`` or ``actual``.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:values>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:values>`__
"""
message_template = "type must be 'legal' or 'actual', but is '{}'"
default_args = ('x',)
class E09(VOWarning, ValueError):
"""
The ``MIN``, ``MAX`` and ``OPTION`` elements must always have a
``value`` attribute.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:values>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:values>`__
"""
message_template = "'{}' must have a value attribute"
default_args = ('x',)
class E10(VOWarning, ValueError):
"""
From VOTable 1.1 and later, ``FIELD`` and ``PARAM`` elements must have
a ``datatype`` field.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#elem:FIELD>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#elem:FIELD>`__
"""
message_template = "'datatype' attribute required on all '{}' elements"
default_args = ('FIELD',)
class E11(VOWarning, ValueError):
"""
The precision attribute is meant to express the number of significant
digits, either as a number of decimal places (e.g. ``precision="F2"`` or
equivalently ``precision="2"`` to express 2 significant figures
after the decimal point), or as a number of significant figures
(e.g. ``precision="E5"`` indicates a relative precision of 10-5).
It is validated using the following regular expression::
[EF]?[1-9][0-9]*
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:form>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:form>`__
"""
message_template = "precision '{}' is invalid"
default_args = ('x',)
class E12(VOWarning, ValueError):
"""
The width attribute is meant to indicate to the application the
number of characters to be used for input or output of the
quantity.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:form>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:form>`__
"""
message_template = "width must be a positive integer, got '{}'"
default_args = ('x',)
class E13(VOWarning, ValueError):
r"""
From the VOTable 1.2 spec:
A table cell can contain an array of a given primitive type,
with a fixed or variable number of elements; the array may
even be multidimensional. For instance, the position of a
point in a 3D space can be defined by the following::
<FIELD ID="point_3D" datatype="double" arraysize="3"/>
and each cell corresponding to that definition must contain
exactly 3 numbers. An asterisk (\*) may be appended to
indicate a variable number of elements in the array, as in::
<FIELD ID="values" datatype="int" arraysize="100*"/>
where it is specified that each cell corresponding to that
definition contains 0 to 100 integer numbers. The number may
be omitted to specify an unbounded array (in practice up to
=~2×10⁹ elements).
A table cell can also contain a multidimensional array of a
given primitive type. This is specified by a sequence of
dimensions separated by the ``x`` character, with the first
dimension changing fastest; as in the case of a simple array,
the last dimension may be variable in length. As an example,
the following definition declares a table cell which may
contain a set of up to 10 images, each of 64×64 bytes::
<FIELD ID="thumbs" datatype="unsignedByte" arraysize="64×64×10*"/>
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:dim>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:dim>`__
"""
message_template = "Invalid arraysize attribute '{}'"
default_args = ('x',)
class E14(VOWarning, ValueError):
"""
All ``PARAM`` elements must have a ``value`` attribute.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#elem:FIELD>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#elem:FIELD>`__
"""
message_template = "value attribute is required for all PARAM elements"
class E15(VOWarning, ValueError):
"""
All ``COOSYS`` elements must have an ``ID`` attribute.
Note that the VOTable 1.1 specification says this attribute is
optional, but its corresponding schema indicates it is required.
In VOTable 1.2, the ``COOSYS`` element is deprecated.
"""
message_template = "ID attribute is required for all COOSYS elements"
class E16(VOTableSpecWarning):
"""
The ``system`` attribute on the ``COOSYS`` element must be one of the
following::
'eq_FK4', 'eq_FK5', 'ICRS', 'ecl_FK4', 'ecl_FK5', 'galactic',
'supergalactic', 'xy', 'barycentric', 'geo_app'
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#elem:COOSYS>`__
"""
message_template = "Invalid system attribute '{}'"
default_args = ('x',)
class E17(VOWarning, ValueError):
"""
``extnum`` attribute must be a positive integer.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC54>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC58>`__
"""
message_template = "extnum must be a positive integer"
class E18(VOWarning, ValueError):
"""
The ``type`` attribute of the ``RESOURCE`` element must be one of
"results" or "meta".
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC54>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC58>`__
"""
message_template = "type must be 'results' or 'meta', not '{}'"
default_args = ('x',)
class E19(VOWarning, ValueError):
"""
Raised either when the file doesn't appear to be XML, or the root
element is not VOTABLE.
"""
message_template = "File does not appear to be a VOTABLE"
class E20(VOTableSpecError):
"""
The table had only *x* fields defined, but the data itself has more
columns than that.
"""
message_template = "Data has more columns than are defined in the header ({})"
default_args = ('x',)
class E21(VOWarning, ValueError):
"""
The table had *x* fields defined, but the data itself has only *y*
columns.
"""
message_template = "Data has fewer columns ({}) than are defined in the header ({})"
default_args = ('x', 'y')
class E22(VOWarning, ValueError):
"""
All ``TIMESYS`` elements must have an ``ID`` attribute.
"""
message_template = "ID attribute is required for all TIMESYS elements"
class E23(VOTableSpecWarning):
"""
The ``timeorigin`` attribute on the ``TIMESYS`` element must be
either a floating point literal specifiying a valid Julian Date,
or, for convenience, the string "MJD-origin" (standing for 2400000.5)
or the string "JD-origin" (standing for 0).
**References**: `1.4
<http://www.ivoa.net/documents/VOTable/20191021/REC-VOTable-1.4-20191021.html#ToC21>`__
"""
message_template = "Invalid timeorigin attribute '{}'"
default_args = ('x',)
class E24(VOWarning, ValueError):
"""
Non-ASCII unicode values should not be written when the FIELD ``datatype="char"``,
and cannot be written in BINARY or BINARY2 serialization.
"""
message_template = (
'Attempt to write non-ASCII value ({}) to FIELD ({}) which '
'has datatype="char"')
default_args = ('', '')
class E25(VOTableSpecWarning):
"""
A VOTable cannot have a DATA section without any defined FIELD; DATA will be ignored.
"""
message_template = "No FIELDs are defined; DATA section will be ignored."
def _get_warning_and_exception_classes(prefix):
classes = []
for key, val in globals().items():
if re.match(prefix + "[0-9]{2}", key):
classes.append((key, val))
classes.sort()
return classes
def _build_doc_string():
def generate_set(prefix):
classes = _get_warning_and_exception_classes(prefix)
out = io.StringIO()
for name, cls in classes:
out.write(f".. _{name}:\n\n")
msg = f"{cls.__name__}: {cls.get_short_name()}"
if not isinstance(msg, str):
msg = msg.decode('utf-8')
out.write(msg)
out.write('\n')
out.write('~' * len(msg))
out.write('\n\n')
doc = cls.__doc__
if not isinstance(doc, str):
doc = doc.decode('utf-8')
out.write(dedent(doc))
out.write('\n\n')
return out.getvalue()
warnings = generate_set('W')
exceptions = generate_set('E')
return {'warnings': warnings,
'exceptions': exceptions}
if __doc__ is not None:
__doc__ = __doc__.format(**_build_doc_string())
__all__.extend([x[0] for x in _get_warning_and_exception_classes('W')])
__all__.extend([x[0] for x in _get_warning_and_exception_classes('E')]) | astropy/io/votable/exceptions.py | # STDLIB
import io
import re
from textwrap import dedent
from warnings import warn
from astropy import config as _config
from astropy.utils.exceptions import AstropyWarning
__all__ = [
'Conf', 'conf', 'warn_or_raise', 'vo_raise', 'vo_reraise', 'vo_warn',
'warn_unknown_attrs', 'parse_vowarning', 'VOWarning',
'VOTableChangeWarning', 'VOTableSpecWarning',
'UnimplementedWarning', 'IOWarning', 'VOTableSpecError']
# NOTE: Cannot put this in __init__.py due to circular import.
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astropy.io.votable.exceptions`.
"""
max_warnings = _config.ConfigItem(
10,
'Number of times the same type of warning is displayed '
'before being suppressed',
cfgtype='integer')
conf = Conf()
def _format_message(message, name, config=None, pos=None):
if config is None:
config = {}
if pos is None:
pos = ('?', '?')
filename = config.get('filename', '?')
return f'{filename}:{pos[0]}:{pos[1]}: {name}: {message}'
def _suppressed_warning(warning, config, stacklevel=2):
warning_class = type(warning)
config.setdefault('_warning_counts', dict()).setdefault(warning_class, 0)
config['_warning_counts'][warning_class] += 1
message_count = config['_warning_counts'][warning_class]
if message_count <= conf.max_warnings:
if message_count == conf.max_warnings:
warning.formatted_message += \
' (suppressing further warnings of this type...)'
warn(warning, stacklevel=stacklevel+1)
def warn_or_raise(warning_class, exception_class=None, args=(), config=None,
pos=None, stacklevel=1):
"""
Warn or raise an exception, depending on the verify setting.
"""
if config is None:
config = {}
# NOTE: the default here is deliberately warn rather than ignore, since
# one would expect that calling warn_or_raise without config should not
# silence the warnings.
config_value = config.get('verify', 'warn')
if config_value == 'exception':
if exception_class is None:
exception_class = warning_class
vo_raise(exception_class, args, config, pos)
elif config_value == 'warn':
vo_warn(warning_class, args, config, pos, stacklevel=stacklevel+1)
def vo_raise(exception_class, args=(), config=None, pos=None):
"""
Raise an exception, with proper position information if available.
"""
if config is None:
config = {}
raise exception_class(args, config, pos)
def vo_reraise(exc, config=None, pos=None, additional=''):
"""
Raise an exception, with proper position information if available.
Restores the original traceback of the exception, and should only
be called within an "except:" block of code.
"""
if config is None:
config = {}
message = _format_message(str(exc), exc.__class__.__name__, config, pos)
if message.split()[0] == str(exc).split()[0]:
message = str(exc)
if len(additional):
message += ' ' + additional
exc.args = (message,)
raise exc
def vo_warn(warning_class, args=(), config=None, pos=None, stacklevel=1):
"""
Warn, with proper position information if available.
"""
if config is None:
config = {}
# NOTE: the default here is deliberately warn rather than ignore, since
# one would expect that calling warn_or_raise without config should not
# silence the warnings.
if config.get('verify', 'warn') != 'ignore':
warning = warning_class(args, config, pos)
_suppressed_warning(warning, config, stacklevel=stacklevel+1)
def warn_unknown_attrs(element, attrs, config, pos, good_attr=[], stacklevel=1):
for attr in attrs:
if attr not in good_attr:
vo_warn(W48, (attr, element), config, pos, stacklevel=stacklevel+1)
_warning_pat = re.compile(
r":?(?P<nline>[0-9?]+):(?P<nchar>[0-9?]+): " +
r"((?P<warning>[WE]\d+): )?(?P<rest>.*)$")
def parse_vowarning(line):
"""
Parses the vo warning string back into its parts.
"""
result = {}
match = _warning_pat.search(line)
if match:
result['warning'] = warning = match.group('warning')
if warning is not None:
result['is_warning'] = (warning[0].upper() == 'W')
result['is_exception'] = not result['is_warning']
result['number'] = int(match.group('warning')[1:])
result['doc_url'] = f"io/votable/api_exceptions.html#{warning.lower()}"
else:
result['is_warning'] = False
result['is_exception'] = False
result['is_other'] = True
result['number'] = None
result['doc_url'] = None
try:
result['nline'] = int(match.group('nline'))
except ValueError:
result['nline'] = 0
try:
result['nchar'] = int(match.group('nchar'))
except ValueError:
result['nchar'] = 0
result['message'] = match.group('rest')
result['is_something'] = True
else:
result['warning'] = None
result['is_warning'] = False
result['is_exception'] = False
result['is_other'] = False
result['is_something'] = False
if not isinstance(line, str):
line = line.decode('utf-8')
result['message'] = line
return result
class VOWarning(AstropyWarning):
"""
The base class of all VO warnings and exceptions.
Handles the formatting of the message with a warning or exception
code, filename, line and column number.
"""
default_args = ()
message_template = ''
def __init__(self, args, config=None, pos=None):
if config is None:
config = {}
if not isinstance(args, tuple):
args = (args, )
msg = self.message_template.format(*args)
self.formatted_message = _format_message(
msg, self.__class__.__name__, config, pos)
Warning.__init__(self, self.formatted_message)
def __str__(self):
return self.formatted_message
@classmethod
def get_short_name(cls):
if len(cls.default_args):
return cls.message_template.format(*cls.default_args)
return cls.message_template
class VOTableChangeWarning(VOWarning, SyntaxWarning):
"""
A change has been made to the input XML file.
"""
class VOTableSpecWarning(VOWarning, SyntaxWarning):
"""
The input XML file violates the spec, but there is an obvious workaround.
"""
class UnimplementedWarning(VOWarning, SyntaxWarning):
"""
A feature of the VOTABLE_ spec is not implemented.
"""
class IOWarning(VOWarning, RuntimeWarning):
"""
A network or IO error occurred, but was recovered using the cache.
"""
class VOTableSpecError(VOWarning, ValueError):
"""
The input XML file violates the spec and there is no good workaround.
"""
class W01(VOTableSpecWarning):
"""
The VOTable spec states:
If a cell contains an array or complex number, it should be
encoded as multiple numbers separated by whitespace.
Many VOTable files in the wild use commas as a separator instead,
and ``astropy.io.votable`` supports this convention when not in
:ref:`pedantic-mode`.
``astropy.io.votable`` always outputs files using only spaces, regardless of
how they were input.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#toc-header-35>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:TABLEDATA>`__
"""
message_template = "Array uses commas rather than whitespace"
class W02(VOTableSpecWarning):
r"""
XML ids must match the following regular expression::
^[A-Za-z_][A-Za-z0-9_\.\-]*$
The VOTable 1.1 says the following:
According to the XML standard, the attribute ``ID`` is a
string beginning with a letter or underscore (``_``), followed
by a sequence of letters, digits, or any of the punctuation
characters ``.`` (dot), ``-`` (dash), ``_`` (underscore), or
``:`` (colon).
However, this is in conflict with the XML standard, which says
colons may not be used. VOTable 1.1's own schema does not allow a
colon here. Therefore, ``astropy.io.votable`` disallows the colon.
VOTable 1.2 corrects this error in the specification.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:name>`__,
`XML Names <http://www.w3.org/TR/REC-xml/#NT-Name>`__
"""
message_template = "{} attribute '{}' is invalid. Must be a standard XML id"
default_args = ('x', 'y')
class W03(VOTableChangeWarning):
"""
The VOTable 1.1 spec says the following about ``name`` vs. ``ID``
on ``FIELD`` and ``VALUE`` elements:
``ID`` and ``name`` attributes have a different role in
VOTable: the ``ID`` is meant as a *unique identifier* of an
element seen as a VOTable component, while the ``name`` is
meant for presentation purposes, and need not to be unique
throughout the VOTable document. The ``ID`` attribute is
therefore required in the elements which have to be
referenced, but in principle any element may have an ``ID``
attribute. ... In summary, the ``ID`` is different from the
``name`` attribute in that (a) the ``ID`` attribute is made
from a restricted character set, and must be unique throughout
a VOTable document whereas names are standard XML attributes
and need not be unique; and (b) there should be support in the
parsing software to look up references and extract the
relevant element with matching ``ID``.
It is further recommended in the VOTable 1.2 spec:
While the ``ID`` attribute has to be unique in a VOTable
document, the ``name`` attribute need not. It is however
recommended, as a good practice, to assign unique names within
a ``TABLE`` element. This recommendation means that, between a
``TABLE`` and its corresponding closing ``TABLE`` tag,
``name`` attributes of ``FIELD``, ``PARAM`` and optional
``GROUP`` elements should be all different.
Since ``astropy.io.votable`` requires a unique identifier for each of its
columns, ``ID`` is used for the column name when present.
However, when ``ID`` is not present, (since it is not required by
the specification) ``name`` is used instead. However, ``name``
must be cleansed by replacing invalid characters (such as
whitespace) with underscores.
.. note::
This warning does not indicate that the input file is invalid
with respect to the VOTable specification, only that the
column names in the record array may not match exactly the
``name`` attributes specified in the file.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:name>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:name>`__
"""
message_template = "Implicitly generating an ID from a name '{}' -> '{}'"
default_args = ('x', 'y')
class W04(VOTableSpecWarning):
"""
The ``content-type`` attribute must use MIME content-type syntax as
defined in `RFC 2046 <https://tools.ietf.org/html/rfc2046>`__.
The current check for validity is somewhat over-permissive.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:link>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:link>`__
"""
message_template = "content-type '{}' must be a valid MIME content type"
default_args = ('x',)
class W05(VOTableSpecWarning):
"""
The attribute must be a valid URI as defined in `RFC 2396
<https://www.ietf.org/rfc/rfc2396.txt>`_.
"""
message_template = "'{}' is not a valid URI"
default_args = ('x',)
class W06(VOTableSpecWarning):
"""
This warning is emitted when a ``ucd`` attribute does not match
the syntax of a `unified content descriptor
<http://vizier.u-strasbg.fr/doc/UCD.htx>`__.
If the VOTable version is 1.2 or later, the UCD will also be
checked to ensure it conforms to the controlled vocabulary defined
by UCD1+.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:ucd>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:ucd>`__
"""
message_template = "Invalid UCD '{}': {}"
default_args = ('x', 'explanation')
class W07(VOTableSpecWarning):
"""
As astro year field is a Besselian or Julian year matching the
regular expression::
^[JB]?[0-9]+([.][0-9]*)?$
Defined in this XML Schema snippet::
<xs:simpleType name="astroYear">
<xs:restriction base="xs:token">
<xs:pattern value="[JB]?[0-9]+([.][0-9]*)?"/>
</xs:restriction>
</xs:simpleType>
"""
message_template = "Invalid astroYear in {}: '{}'"
default_args = ('x', 'y')
class W08(VOTableSpecWarning):
"""
To avoid local-dependent number parsing differences, ``astropy.io.votable``
may require a string or unicode string where a numeric type may
make more sense.
"""
message_template = "'{}' must be a str or bytes object"
default_args = ('x',)
class W09(VOTableSpecWarning):
"""
The VOTable specification uses the attribute name ``ID`` (with
uppercase letters) to specify unique identifiers. Some
VOTable-producing tools use the more standard lowercase ``id``
instead. ``astropy.io.votable`` accepts ``id`` and emits this warning if
``verify`` is ``'warn'``.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:name>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:name>`__
"""
message_template = "ID attribute not capitalized"
class W10(VOTableSpecWarning):
"""
The parser has encountered an element that does not exist in the
specification, or appears in an invalid context. Check the file
against the VOTable schema (with a tool such as `xmllint
<http://xmlsoft.org/xmllint.html>`__. If the file validates
against the schema, and you still receive this warning, this may
indicate a bug in ``astropy.io.votable``.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC54>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC58>`__
"""
message_template = "Unknown tag '{}'. Ignoring"
default_args = ('x',)
class W11(VOTableSpecWarning):
"""
Earlier versions of the VOTable specification used a ``gref``
attribute on the ``LINK`` element to specify a `GLU reference
<http://aladin.u-strasbg.fr/glu/>`__. New files should
specify a ``glu:`` protocol using the ``href`` attribute.
Since ``astropy.io.votable`` does not currently support GLU references, it
likewise does not automatically convert the ``gref`` attribute to
the new form.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:link>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:link>`__
"""
message_template = "The gref attribute on LINK is deprecated in VOTable 1.1"
class W12(VOTableChangeWarning):
"""
In order to name the columns of the Numpy record array, each
``FIELD`` element must have either an ``ID`` or ``name`` attribute
to derive a name from. Strictly speaking, according to the
VOTable schema, the ``name`` attribute is required. However, if
``name`` is not present by ``ID`` is, and ``verify`` is not ``'exception'``,
``astropy.io.votable`` will continue without a ``name`` defined.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:name>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:name>`__
"""
message_template = (
"'{}' element must have at least one of 'ID' or 'name' attributes")
default_args = ('x',)
class W13(VOTableSpecWarning):
"""
Some VOTable files in the wild use non-standard datatype names. These
are mapped to standard ones using the following mapping::
string -> char
unicodeString -> unicodeChar
int16 -> short
int32 -> int
int64 -> long
float32 -> float
float64 -> double
unsignedInt -> long
unsignedShort -> int
To add more datatype mappings during parsing, use the
``datatype_mapping`` keyword to `astropy.io.votable.parse`.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:datatypes>`__
"""
message_template = "'{}' is not a valid VOTable datatype, should be '{}'"
default_args = ('x', 'y')
# W14: Deprecated
class W15(VOTableSpecWarning):
"""
The ``name`` attribute is required on every ``FIELD`` element.
However, many VOTable files in the wild omit it and provide only
an ``ID`` instead. In this case, when ``verify`` is not ``'exception'``
``astropy.io.votable`` will copy the ``name`` attribute to a new ``ID``
attribute.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:name>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:name>`__
"""
message_template = "{} element missing required 'name' attribute"
default_args = ('x',)
# W16: Deprecated
class W17(VOTableSpecWarning):
"""
A ``DESCRIPTION`` element can only appear once within its parent
element.
According to the schema, it may only occur once (`1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC54>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC58>`__)
However, it is a `proposed extension
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:addesc>`__
to VOTable 1.2.
"""
message_template = "{} element contains more than one DESCRIPTION element"
default_args = ('x',)
class W18(VOTableSpecWarning):
"""
The number of rows explicitly specified in the ``nrows`` attribute
does not match the actual number of rows (``TR`` elements) present
in the ``TABLE``. This may indicate truncation of the file, or an
internal error in the tool that produced it. If ``verify`` is not
``'exception'``, parsing will proceed, with the loss of some performance.
**References:** `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC10>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC10>`__
"""
message_template = 'TABLE specified nrows={}, but table contains {} rows'
default_args = ('x', 'y')
class W19(VOTableSpecWarning):
"""
The column fields as defined using ``FIELD`` elements do not match
those in the headers of the embedded FITS file. If ``verify`` is not
``'exception'``, the embedded FITS file will take precedence.
"""
message_template = (
'The fields defined in the VOTable do not match those in the ' +
'embedded FITS file')
class W20(VOTableSpecWarning):
"""
If no version number is explicitly given in the VOTable file, the
parser assumes it is written to the VOTable 1.1 specification.
"""
message_template = 'No version number specified in file. Assuming {}'
default_args = ('1.1',)
class W21(UnimplementedWarning):
"""
Unknown issues may arise using ``astropy.io.votable`` with VOTable files
from a version other than 1.1, 1.2, 1.3, or 1.4.
"""
message_template = (
'astropy.io.votable is designed for VOTable version 1.1, 1.2, 1.3,'
' and 1.4, but this file is {}')
default_args = ('x',)
class W22(VOTableSpecWarning):
"""
Version 1.0 of the VOTable specification used the ``DEFINITIONS``
element to define coordinate systems. Version 1.1 now uses
``COOSYS`` elements throughout the document.
**References:** `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:definitions>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:definitions>`__
"""
message_template = 'The DEFINITIONS element is deprecated in VOTable 1.1. Ignoring'
class W23(IOWarning):
"""
Raised when the VO service database can not be updated (possibly
due to a network outage). This is only a warning, since an older
and possible out-of-date VO service database was available
locally.
"""
message_template = "Unable to update service information for '{}'"
default_args = ('x',)
class W24(VOWarning, FutureWarning):
"""
The VO catalog database retrieved from the www is designed for a
newer version of ``astropy.io.votable``. This may cause problems or limited
features performing service queries. Consider upgrading ``astropy.io.votable``
to the latest version.
"""
message_template = "The VO catalog database is for a later version of astropy.io.votable"
class W25(IOWarning):
"""
A VO service query failed due to a network error or malformed
arguments. Another alternative service may be attempted. If all
services fail, an exception will be raised.
"""
message_template = "'{}' failed with: {}"
default_args = ('service', '...')
class W26(VOTableSpecWarning):
"""
The given element was not supported inside of the given element
until the specified VOTable version, however the version declared
in the file is for an earlier version. These attributes may not
be written out to the file.
"""
message_template = "'{}' inside '{}' added in VOTable {}"
default_args = ('child', 'parent', 'X.X')
class W27(VOTableSpecWarning):
"""
The ``COOSYS`` element was deprecated in VOTABLE version 1.2 in
favor of a reference to the Space-Time Coordinate (STC) data
model (see `utype
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:utype>`__
and the IVOA note `referencing STC in VOTable
<http://ivoa.net/Documents/latest/VOTableSTC.html>`__.
"""
message_template = "COOSYS deprecated in VOTable 1.2"
class W28(VOTableSpecWarning):
"""
The given attribute was not supported on the given element until the
specified VOTable version, however the version declared in the file is
for an earlier version. These attributes may not be written out to
the file.
"""
message_template = "'{}' on '{}' added in VOTable {}"
default_args = ('attribute', 'element', 'X.X')
class W29(VOTableSpecWarning):
"""
Some VOTable files specify their version number in the form "v1.0",
when the only supported forms in the spec are "1.0".
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC54>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC58>`__
"""
message_template = "Version specified in non-standard form '{}'"
default_args = ('v1.0',)
class W30(VOTableSpecWarning):
"""
Some VOTable files write missing floating-point values in non-standard ways,
such as "null" and "-". If ``verify`` is not ``'exception'``, any
non-standard floating-point literals are treated as missing values.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:datatypes>`__
"""
message_template = "Invalid literal for float '{}'. Treating as empty."
default_args = ('x',)
class W31(VOTableSpecWarning):
"""
Since NaN's can not be represented in integer fields directly, a null
value must be specified in the FIELD descriptor to support reading
NaN's from the tabledata.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:datatypes>`__
"""
message_template = "NaN given in an integral field without a specified null value"
class W32(VOTableSpecWarning):
"""
Each field in a table must have a unique ID. If two or more fields
have the same ID, some will be renamed to ensure that all IDs are
unique.
From the VOTable 1.2 spec:
The ``ID`` and ``ref`` attributes are defined as XML types
``ID`` and ``IDREF`` respectively. This means that the
contents of ``ID`` is an identifier which must be unique
throughout a VOTable document, and that the contents of the
``ref`` attribute represents a reference to an identifier
which must exist in the VOTable document.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:name>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:name>`__
"""
message_template = "Duplicate ID '{}' renamed to '{}' to ensure uniqueness"
default_args = ('x', 'x_2')
class W33(VOTableChangeWarning):
"""
Each field in a table must have a unique name. If two or more
fields have the same name, some will be renamed to ensure that all
names are unique.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:name>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:name>`__
"""
message_template = "Column name '{}' renamed to '{}' to ensure uniqueness"
default_args = ('x', 'x_2')
class W34(VOTableSpecWarning):
"""
The attribute requires the value to be a valid XML token, as
defined by `XML 1.0
<http://www.w3.org/TR/2000/WD-xml-2e-20000814#NT-Nmtoken>`__.
"""
message_template = "'{}' is an invalid token for attribute '{}'"
default_args = ('x', 'y')
class W35(VOTableSpecWarning):
"""
The ``name`` and ``value`` attributes are required on all ``INFO``
elements.
**References:** `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC54>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC32>`__
"""
message_template = "'{}' attribute required for INFO elements"
default_args = ('x',)
class W36(VOTableSpecWarning):
"""
If the field specifies a ``null`` value, that value must conform
to the given ``datatype``.
**References:** `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:values>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:values>`__
"""
message_template = "null value '{}' does not match field datatype, setting to 0"
default_args = ('x',)
class W37(UnimplementedWarning):
"""
The 3 datatypes defined in the VOTable specification and supported by
``astropy.io.votable`` are ``TABLEDATA``, ``BINARY`` and ``FITS``.
**References:** `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:data>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:data>`__
"""
message_template = "Unsupported data format '{}'"
default_args = ('x',)
class W38(VOTableSpecWarning):
"""
The only encoding for local binary data supported by the VOTable
specification is base64.
"""
message_template = "Inline binary data must be base64 encoded, got '{}'"
default_args = ('x',)
class W39(VOTableSpecWarning):
"""
Bit values do not support masking. This warning is raised upon
setting masked data in a bit column.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:datatypes>`__
"""
message_template = "Bit values can not be masked"
class W40(VOTableSpecWarning):
"""
This is a terrible hack to support Simple Image Access Protocol
results from `archive.noao.edu <http://archive.noao.edu>`__. It
creates a field for the coordinate projection type of type "double",
which actually contains character data. We have to hack the field
to store character data, or we can't read it in. A warning will be
raised when this happens.
"""
message_template = "'cprojection' datatype repaired"
class W41(VOTableSpecWarning):
"""
An XML namespace was specified on the ``VOTABLE`` element, but the
namespace does not match what is expected for a ``VOTABLE`` file.
The ``VOTABLE`` namespace is::
http://www.ivoa.net/xml/VOTable/vX.X
where "X.X" is the version number.
Some files in the wild set the namespace to the location of the
VOTable schema, which is not correct and will not pass some
validating parsers.
"""
message_template = (
"An XML namespace is specified, but is incorrect. Expected " +
"'{}', got '{}'")
default_args = ('x', 'y')
class W42(VOTableSpecWarning):
"""
The root element should specify a namespace.
The ``VOTABLE`` namespace is::
http://www.ivoa.net/xml/VOTable/vX.X
where "X.X" is the version number.
"""
message_template = "No XML namespace specified"
class W43(VOTableSpecWarning):
"""
Referenced elements should be defined before referees. From the
VOTable 1.2 spec:
In VOTable1.2, it is further recommended to place the ID
attribute prior to referencing it whenever possible.
"""
message_template = "{} ref='{}' which has not already been defined"
default_args = ('element', 'x',)
class W44(VOTableSpecWarning):
"""
``VALUES`` elements that reference another element should not have
their own content.
From the VOTable 1.2 spec:
The ``ref`` attribute of a ``VALUES`` element can be used to
avoid a repetition of the domain definition, by referring to a
previously defined ``VALUES`` element having the referenced
``ID`` attribute. When specified, the ``ref`` attribute
defines completely the domain without any other element or
attribute, as e.g. ``<VALUES ref="RAdomain"/>``
"""
message_template = "VALUES element with ref attribute has content ('{}')"
default_args = ('element',)
class W45(VOWarning, ValueError):
"""
The ``content-role`` attribute on the ``LINK`` element must be one of
the following::
query, hints, doc, location
And in VOTable 1.3, additionally::
type
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC54>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC58>`__
`1.3
<http://www.ivoa.net/documents/VOTable/20130315/PR-VOTable-1.3-20130315.html#sec:link>`__
"""
message_template = "content-role attribute '{}' invalid"
default_args = ('x',)
class W46(VOTableSpecWarning):
"""
The given char or unicode string is too long for the specified
field length.
"""
message_template = "{} value is too long for specified length of {}"
default_args = ('char or unicode', 'x')
class W47(VOTableSpecWarning):
"""
If no arraysize is specified on a char field, the default of '1'
is implied, but this is rarely what is intended.
"""
message_template = "Missing arraysize indicates length 1"
class W48(VOTableSpecWarning):
"""
The attribute is not defined in the specification.
"""
message_template = "Unknown attribute '{}' on {}"
default_args = ('attribute', 'element')
class W49(VOTableSpecWarning):
"""
Prior to VOTable 1.3, the empty cell was illegal for integer
fields.
If a \"null\" value was specified for the cell, it will be used
for the value, otherwise, 0 will be used.
"""
message_template = "Empty cell illegal for integer fields."
class W50(VOTableSpecWarning):
"""
Invalid unit string as defined in the `Units in the VO, Version 1.0
<https://www.ivoa.net/documents/VOUnits>`_ (VOTable version >= 1.4)
or `Standards for Astronomical Catalogues, Version 2.0
<http://cdsarc.u-strasbg.fr/doc/catstd-3.2.htx>`_ (version < 1.4).
Consider passing an explicit ``unit_format`` parameter if the units
in this file conform to another specification.
"""
message_template = "Invalid unit string '{}'"
default_args = ('x',)
class W51(VOTableSpecWarning):
"""
The integer value is out of range for the size of the field.
"""
message_template = "Value '{}' is out of range for a {} integer field"
default_args = ('x', 'n-bit')
class W52(VOTableSpecWarning):
"""
The BINARY2 format was introduced in VOTable 1.3. It should
not be present in files marked as an earlier version.
"""
message_template = ("The BINARY2 format was introduced in VOTable 1.3, but "
"this file is declared as version '{}'")
default_args = ('1.2',)
class W53(VOTableSpecWarning):
"""
The VOTABLE element must contain at least one RESOURCE element.
"""
message_template = ("VOTABLE element must contain at least one RESOURCE element.")
default_args = ()
class W54(VOTableSpecWarning):
"""
The TIMESYS element was introduced in VOTable 1.4. It should
not be present in files marked as an earlier version.
"""
message_template = (
"The TIMESYS element was introduced in VOTable 1.4, but "
"this file is declared as version '{}'")
default_args = ('1.3',)
class W55(VOTableSpecWarning):
"""
When non-ASCII characters are detected when reading
a TABLEDATA value for a FIELD with ``datatype="char"``, we
can issue this warning.
"""
message_template = (
'FIELD ({}) has datatype="char" but contains non-ASCII '
'value ({})')
default_args = ('', '')
class E01(VOWarning, ValueError):
"""
The size specifier for a ``char`` or ``unicode`` field must be
only a number followed, optionally, by an asterisk.
Multi-dimensional size specifiers are not supported for these
datatypes.
Strings, which are defined as a set of characters, can be
represented in VOTable as a fixed- or variable-length array of
characters::
<FIELD name="unboundedString" datatype="char" arraysize="*"/>
A 1D array of strings can be represented as a 2D array of
characters, but given the logic above, it is possible to define a
variable-length array of fixed-length strings, but not a
fixed-length array of variable-length strings.
"""
message_template = "Invalid size specifier '{}' for a {} field (in field '{}')"
default_args = ('x', 'char/unicode', 'y')
class E02(VOWarning, ValueError):
"""
The number of array elements in the data does not match that specified
in the FIELD specifier.
"""
message_template = (
"Incorrect number of elements in array. " +
"Expected multiple of {}, got {}")
default_args = ('x', 'y')
class E03(VOWarning, ValueError):
"""
Complex numbers should be two values separated by whitespace.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:datatypes>`__
"""
message_template = "'{}' does not parse as a complex number"
default_args = ('x',)
class E04(VOWarning, ValueError):
"""
A ``bit`` array should be a string of '0's and '1's.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:datatypes>`__
"""
message_template = "Invalid bit value '{}'"
default_args = ('x',)
class E05(VOWarning, ValueError):
r"""
A ``boolean`` value should be one of the following strings (case
insensitive) in the ``TABLEDATA`` format::
'TRUE', 'FALSE', '1', '0', 'T', 'F', '\0', ' ', '?'
and in ``BINARY`` format::
'T', 'F', '1', '0', '\0', ' ', '?'
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:datatypes>`__
"""
message_template = "Invalid boolean value '{}'"
default_args = ('x',)
class E06(VOWarning, ValueError):
"""
The supported datatypes are::
double, float, bit, boolean, unsignedByte, short, int, long,
floatComplex, doubleComplex, char, unicodeChar
The following non-standard aliases are also supported, but in
these case :ref:`W13 <W13>` will be raised::
string -> char
unicodeString -> unicodeChar
int16 -> short
int32 -> int
int64 -> long
float32 -> float
float64 -> double
unsignedInt -> long
unsignedShort -> int
To add more datatype mappings during parsing, use the
``datatype_mapping`` keyword to `astropy.io.votable.parse`.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:datatypes>`__
"""
message_template = "Unknown datatype '{}' on field '{}'"
default_args = ('x', 'y')
# E07: Deprecated
class E08(VOWarning, ValueError):
"""
The ``type`` attribute on the ``VALUES`` element must be either
``legal`` or ``actual``.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:values>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:values>`__
"""
message_template = "type must be 'legal' or 'actual', but is '{}'"
default_args = ('x',)
class E09(VOWarning, ValueError):
"""
The ``MIN``, ``MAX`` and ``OPTION`` elements must always have a
``value`` attribute.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:values>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:values>`__
"""
message_template = "'{}' must have a value attribute"
default_args = ('x',)
class E10(VOWarning, ValueError):
"""
From VOTable 1.1 and later, ``FIELD`` and ``PARAM`` elements must have
a ``datatype`` field.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#elem:FIELD>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#elem:FIELD>`__
"""
message_template = "'datatype' attribute required on all '{}' elements"
default_args = ('FIELD',)
class E11(VOWarning, ValueError):
"""
The precision attribute is meant to express the number of significant
digits, either as a number of decimal places (e.g. ``precision="F2"`` or
equivalently ``precision="2"`` to express 2 significant figures
after the decimal point), or as a number of significant figures
(e.g. ``precision="E5"`` indicates a relative precision of 10-5).
It is validated using the following regular expression::
[EF]?[1-9][0-9]*
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:form>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:form>`__
"""
message_template = "precision '{}' is invalid"
default_args = ('x',)
class E12(VOWarning, ValueError):
"""
The width attribute is meant to indicate to the application the
number of characters to be used for input or output of the
quantity.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:form>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:form>`__
"""
message_template = "width must be a positive integer, got '{}'"
default_args = ('x',)
class E13(VOWarning, ValueError):
r"""
From the VOTable 1.2 spec:
A table cell can contain an array of a given primitive type,
with a fixed or variable number of elements; the array may
even be multidimensional. For instance, the position of a
point in a 3D space can be defined by the following::
<FIELD ID="point_3D" datatype="double" arraysize="3"/>
and each cell corresponding to that definition must contain
exactly 3 numbers. An asterisk (\*) may be appended to
indicate a variable number of elements in the array, as in::
<FIELD ID="values" datatype="int" arraysize="100*"/>
where it is specified that each cell corresponding to that
definition contains 0 to 100 integer numbers. The number may
be omitted to specify an unbounded array (in practice up to
=~2×10⁹ elements).
A table cell can also contain a multidimensional array of a
given primitive type. This is specified by a sequence of
dimensions separated by the ``x`` character, with the first
dimension changing fastest; as in the case of a simple array,
the last dimension may be variable in length. As an example,
the following definition declares a table cell which may
contain a set of up to 10 images, each of 64×64 bytes::
<FIELD ID="thumbs" datatype="unsignedByte" arraysize="64×64×10*"/>
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:dim>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:dim>`__
"""
message_template = "Invalid arraysize attribute '{}'"
default_args = ('x',)
class E14(VOWarning, ValueError):
"""
All ``PARAM`` elements must have a ``value`` attribute.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#elem:FIELD>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#elem:FIELD>`__
"""
message_template = "value attribute is required for all PARAM elements"
class E15(VOWarning, ValueError):
"""
All ``COOSYS`` elements must have an ``ID`` attribute.
Note that the VOTable 1.1 specification says this attribute is
optional, but its corresponding schema indicates it is required.
In VOTable 1.2, the ``COOSYS`` element is deprecated.
"""
message_template = "ID attribute is required for all COOSYS elements"
class E16(VOTableSpecWarning):
"""
The ``system`` attribute on the ``COOSYS`` element must be one of the
following::
'eq_FK4', 'eq_FK5', 'ICRS', 'ecl_FK4', 'ecl_FK5', 'galactic',
'supergalactic', 'xy', 'barycentric', 'geo_app'
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#elem:COOSYS>`__
"""
message_template = "Invalid system attribute '{}'"
default_args = ('x',)
class E17(VOWarning, ValueError):
"""
``extnum`` attribute must be a positive integer.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC54>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC58>`__
"""
message_template = "extnum must be a positive integer"
class E18(VOWarning, ValueError):
"""
The ``type`` attribute of the ``RESOURCE`` element must be one of
"results" or "meta".
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC54>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC58>`__
"""
message_template = "type must be 'results' or 'meta', not '{}'"
default_args = ('x',)
class E19(VOWarning, ValueError):
"""
Raised either when the file doesn't appear to be XML, or the root
element is not VOTABLE.
"""
message_template = "File does not appear to be a VOTABLE"
class E20(VOTableSpecError):
"""
The table had only *x* fields defined, but the data itself has more
columns than that.
"""
message_template = "Data has more columns than are defined in the header ({})"
default_args = ('x',)
class E21(VOWarning, ValueError):
"""
The table had *x* fields defined, but the data itself has only *y*
columns.
"""
message_template = "Data has fewer columns ({}) than are defined in the header ({})"
default_args = ('x', 'y')
class E22(VOWarning, ValueError):
"""
All ``TIMESYS`` elements must have an ``ID`` attribute.
"""
message_template = "ID attribute is required for all TIMESYS elements"
class E23(VOTableSpecWarning):
"""
The ``timeorigin`` attribute on the ``TIMESYS`` element must be
either a floating point literal specifiying a valid Julian Date,
or, for convenience, the string "MJD-origin" (standing for 2400000.5)
or the string "JD-origin" (standing for 0).
**References**: `1.4
<http://www.ivoa.net/documents/VOTable/20191021/REC-VOTable-1.4-20191021.html#ToC21>`__
"""
message_template = "Invalid timeorigin attribute '{}'"
default_args = ('x',)
class E24(VOWarning, ValueError):
"""
Non-ASCII unicode values should not be written when the FIELD ``datatype="char"``,
and cannot be written in BINARY or BINARY2 serialization.
"""
message_template = (
'Attempt to write non-ASCII value ({}) to FIELD ({}) which '
'has datatype="char"')
default_args = ('', '')
class E25(VOTableSpecWarning):
"""
A VOTable cannot have a DATA section without any defined FIELD; DATA will be ignored.
"""
message_template = "No FIELDs are defined; DATA section will be ignored."
def _get_warning_and_exception_classes(prefix):
classes = []
for key, val in globals().items():
if re.match(prefix + "[0-9]{2}", key):
classes.append((key, val))
classes.sort()
return classes
def _build_doc_string():
def generate_set(prefix):
classes = _get_warning_and_exception_classes(prefix)
out = io.StringIO()
for name, cls in classes:
out.write(f".. _{name}:\n\n")
msg = f"{cls.__name__}: {cls.get_short_name()}"
if not isinstance(msg, str):
msg = msg.decode('utf-8')
out.write(msg)
out.write('\n')
out.write('~' * len(msg))
out.write('\n\n')
doc = cls.__doc__
if not isinstance(doc, str):
doc = doc.decode('utf-8')
out.write(dedent(doc))
out.write('\n\n')
return out.getvalue()
warnings = generate_set('W')
exceptions = generate_set('E')
return {'warnings': warnings,
'exceptions': exceptions}
if __doc__ is not None:
__doc__ = __doc__.format(**_build_doc_string())
__all__.extend([x[0] for x in _get_warning_and_exception_classes('W')])
__all__.extend([x[0] for x in _get_warning_and_exception_classes('E')]) | 0.541409 | 0.160102 |
import cv2
import numpy as np
class Button_finder:
"""
This node is responsible for the button detection
using template matching in multiple scales
"""
def __init__(self, img_rgb, acc_certainty):
self.img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
self.w = -1
self.h = -1
self.res = -1
self.acc_certainty = acc_certainty
def find_match_multi_size(self, scale_min, scale_max, temp_img, threshold):
# detected, \
# threshold, \
# button_location, \
# button_height, \
# button_width =
ans = 0, -1, (-1, -1), -1, -1
template = cv2.imread(temp_img, 0)
origin_w, origin_h = template.shape[::-1]
scale = scale_max
curr_scale = scale_max
while scale >= scale_min - 0.05: # floating points need small error, otherwise it might get wrong answer
scaled_template = cv2.resize(template, (int(scale * origin_w), int(scale * origin_h)))
self.w, self.h = scaled_template.shape[::-1]
self.res = cv2.matchTemplate(self.img_gray, scaled_template, cv2.TM_CCOEFF_NORMED)
curr_match = self.find_match(0.95, threshold)
if curr_match[1] >= self.acc_certainty:
return scale, curr_match
elif curr_match[1] > ans[1]:
ans = curr_match
curr_scale = scale
scale -= 0.1
return curr_scale, ans
def find_match(self, threshold, min_threshold):
"""
Args:
threshold (float): the lower bound of certainty for a match
min_threshold (float): threshold must be bigger than min_threshold
Returns:
return the best estimated match's location with the highest threshold
if no match was found, return (0, -1, (-1, -1), -1, -1)
"""
if threshold < min_threshold or threshold > 1:
return 0, -1, (-1, -1), -1, -1
loc = np.where(self.res >= threshold)
pts = zip(*loc[::-1])
if not len(pts):
if threshold >= min_threshold:
return self.find_match(threshold - 0.005, min_threshold)
else:
return 0, -1, (-1, -1), -1, -1
else:
return 1, threshold, pts[0], self.h, self.w | src/elevator/scripts/button_finder.py | import cv2
import numpy as np
class Button_finder:
"""
This node is responsible for the button detection
using template matching in multiple scales
"""
def __init__(self, img_rgb, acc_certainty):
self.img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
self.w = -1
self.h = -1
self.res = -1
self.acc_certainty = acc_certainty
def find_match_multi_size(self, scale_min, scale_max, temp_img, threshold):
# detected, \
# threshold, \
# button_location, \
# button_height, \
# button_width =
ans = 0, -1, (-1, -1), -1, -1
template = cv2.imread(temp_img, 0)
origin_w, origin_h = template.shape[::-1]
scale = scale_max
curr_scale = scale_max
while scale >= scale_min - 0.05: # floating points need small error, otherwise it might get wrong answer
scaled_template = cv2.resize(template, (int(scale * origin_w), int(scale * origin_h)))
self.w, self.h = scaled_template.shape[::-1]
self.res = cv2.matchTemplate(self.img_gray, scaled_template, cv2.TM_CCOEFF_NORMED)
curr_match = self.find_match(0.95, threshold)
if curr_match[1] >= self.acc_certainty:
return scale, curr_match
elif curr_match[1] > ans[1]:
ans = curr_match
curr_scale = scale
scale -= 0.1
return curr_scale, ans
def find_match(self, threshold, min_threshold):
"""
Args:
threshold (float): the lower bound of certainty for a match
min_threshold (float): threshold must be bigger than min_threshold
Returns:
return the best estimated match's location with the highest threshold
if no match was found, return (0, -1, (-1, -1), -1, -1)
"""
if threshold < min_threshold or threshold > 1:
return 0, -1, (-1, -1), -1, -1
loc = np.where(self.res >= threshold)
pts = zip(*loc[::-1])
if not len(pts):
if threshold >= min_threshold:
return self.find_match(threshold - 0.005, min_threshold)
else:
return 0, -1, (-1, -1), -1, -1
else:
return 1, threshold, pts[0], self.h, self.w | 0.670069 | 0.350199 |
from django.contrib import admin
from django.utils import timezone
from django.utils.functional import curry
from django.utils.translation import ugettext_lazy as _
from pinax.images.admin import ImageInline
from pinax.images.models import ImageSet
from .conf import settings
from .forms import AdminPostForm
from .models import Blog, Post, ReviewComment, Section
class PostImageSet(ImageSet):
class Meta:
proxy = True
class ReviewInline(admin.TabularInline):
model = ReviewComment
def make_published(modeladmin, request, queryset):
queryset = queryset.exclude(state=Post.STATE_CHOICES[-1][0], published__isnull=False)
queryset.update(state=Post.STATE_CHOICES[-1][0])
queryset.filter(published__isnull=True).update(published=timezone.now())
make_published.short_description = _("Publish selected posts")
class PostAdmin(admin.ModelAdmin):
list_display = ["title", "state", "section", "published", "show_secret_share_url"]
list_filter = ["section", "state"]
form = AdminPostForm
actions = [make_published]
fields = [
"section",
"title",
"slug",
"author",
"markup",
"teaser",
"content",
"description",
"sharable_url",
"state",
"published",
"image_set" # maybe this https://github.com/anziem/django_reverse_admin
]
readonly_fields = ["sharable_url"]
prepopulated_fields = {"slug": ("title",)}
inlines = [
ReviewInline,
]
def show_secret_share_url(self, obj):
return '<a href="%s">%s</a>' % (obj.sharable_url, obj.sharable_url)
show_secret_share_url.short_description = _("Share this url")
show_secret_share_url.allow_tags = True
def formfield_for_dbfield(self, db_field, **kwargs):
request = kwargs.get("request")
if db_field.name == "author":
ff = super(PostAdmin, self).formfield_for_dbfield(db_field, **kwargs)
ff.initial = request.user.id
return ff
return super(PostAdmin, self).formfield_for_dbfield(db_field, **kwargs)
def get_form(self, request, obj=None, **kwargs):
kwargs.update({
"formfield_callback": curry(self.formfield_for_dbfield, request=request),
})
return super(PostAdmin, self).get_form(request, obj, **kwargs)
def save_form(self, request, form, change):
# this is done for explicitness that we want form.save to commit
# form.save doesn't take a commit kwarg for this reason
return form.save(Blog.objects.first() if not settings.PINAX_BLOG_SCOPING_MODEL else None)
if settings.PINAX_BLOG_SCOPING_MODEL:
PostAdmin.fields.insert(0, "blog")
PostAdmin.list_filter.append("blog__scoper")
class SectionAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
admin.site.register(Post, PostAdmin)
admin.site.register(Section, SectionAdmin)
admin.site.register(
PostImageSet,
list_display=["blog_post", "primary_image", "created_by", "created_at"],
raw_id_fields=["created_by"],
inlines=[ImageInline],
) | pinax/blog/admin.py | from django.contrib import admin
from django.utils import timezone
from django.utils.functional import curry
from django.utils.translation import ugettext_lazy as _
from pinax.images.admin import ImageInline
from pinax.images.models import ImageSet
from .conf import settings
from .forms import AdminPostForm
from .models import Blog, Post, ReviewComment, Section
class PostImageSet(ImageSet):
class Meta:
proxy = True
class ReviewInline(admin.TabularInline):
model = ReviewComment
def make_published(modeladmin, request, queryset):
queryset = queryset.exclude(state=Post.STATE_CHOICES[-1][0], published__isnull=False)
queryset.update(state=Post.STATE_CHOICES[-1][0])
queryset.filter(published__isnull=True).update(published=timezone.now())
make_published.short_description = _("Publish selected posts")
class PostAdmin(admin.ModelAdmin):
list_display = ["title", "state", "section", "published", "show_secret_share_url"]
list_filter = ["section", "state"]
form = AdminPostForm
actions = [make_published]
fields = [
"section",
"title",
"slug",
"author",
"markup",
"teaser",
"content",
"description",
"sharable_url",
"state",
"published",
"image_set" # maybe this https://github.com/anziem/django_reverse_admin
]
readonly_fields = ["sharable_url"]
prepopulated_fields = {"slug": ("title",)}
inlines = [
ReviewInline,
]
def show_secret_share_url(self, obj):
return '<a href="%s">%s</a>' % (obj.sharable_url, obj.sharable_url)
show_secret_share_url.short_description = _("Share this url")
show_secret_share_url.allow_tags = True
def formfield_for_dbfield(self, db_field, **kwargs):
request = kwargs.get("request")
if db_field.name == "author":
ff = super(PostAdmin, self).formfield_for_dbfield(db_field, **kwargs)
ff.initial = request.user.id
return ff
return super(PostAdmin, self).formfield_for_dbfield(db_field, **kwargs)
def get_form(self, request, obj=None, **kwargs):
kwargs.update({
"formfield_callback": curry(self.formfield_for_dbfield, request=request),
})
return super(PostAdmin, self).get_form(request, obj, **kwargs)
def save_form(self, request, form, change):
# this is done for explicitness that we want form.save to commit
# form.save doesn't take a commit kwarg for this reason
return form.save(Blog.objects.first() if not settings.PINAX_BLOG_SCOPING_MODEL else None)
if settings.PINAX_BLOG_SCOPING_MODEL:
PostAdmin.fields.insert(0, "blog")
PostAdmin.list_filter.append("blog__scoper")
class SectionAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
admin.site.register(Post, PostAdmin)
admin.site.register(Section, SectionAdmin)
admin.site.register(
PostImageSet,
list_display=["blog_post", "primary_image", "created_by", "created_at"],
raw_id_fields=["created_by"],
inlines=[ImageInline],
) | 0.432063 | 0.154249 |
import json
import unittest
from messagebird import Client, ErrorException
from messagebird.base import Base
from messagebird.client import VOICE_TYPE
try:
from unittest.mock import Mock
except ImportError:
# mock was added to unittest in Python 3.3, but was an external library
# before.
from mock import Mock
class TestCall(unittest.TestCase):
def test_call(self):
http_client = Mock()
http_client.request.return_value = """
{
"data":[
{
"id":"call-id",
"status":"ended",
"source":"16479311111",
"destination":"1416555555",
"createdAt":"2019-08-06T13:17:06Z",
"updatedAt":"2019-08-06T13:17:39Z",
"endedAt":"2019-08-06T13:17:39Z"
}
],
"_links":{
"legs":"/calls/66bd9f08-a8af-40fe-a830-652d8dabc057/legs",
"self":"/calls/66bd9f08-a8af-40fe-a830-652d8bca357"
},
"pagination":{
"totalCount":0,
"pageCount":0,
"currentPage":0,
"perPage":0
}
}
"""
call = Client('', http_client).call('call-id')
http_client.request.assert_called_once_with('calls/call-id', 'GET', None)
self.assertEqual('ended', call.data.status)
def test_call_list(self):
http_client = Mock()
http_client.request.return_value = """
{
"data":[
{
"id":"dda20377-72da-4846-9b2c-0fea3ad4bcb6",
"status":"no_answer",
"source":"16479311111",
"destination":"1416555555",
"createdAt":"2019-08-06T13:17:06Z",
"updatedAt":"2019-08-06T13:17:39Z",
"endedAt":"2019-08-06T13:17:39Z",
"_links":{
"legs":"/calls/dda20377-72da-4846-9b2c-0fea3ad4bcb6/legs",
"self":"/calls/dda20377-72da-4846-9b2c-0fea3ad4bcb6"
}
},
{
"id":"1541535b-9b80-4002-bde5-ed05b5ebed76",
"status":"ended",
"source":"16479311111",
"destination":"1416555556",
"createdAt":"2019-08-06T13:17:06Z",
"updatedAt":"2019-08-06T13:17:39Z",
"endedAt":"2019-08-06T13:17:39Z",
"_links":{
"legs":"/calls/1541535b-9b80-4002-bde5-ed05b5ebed76/legs",
"self":"/calls/1541535b-9b80-4002-bde5-ed05b5ebed76"
}
}
],
"_links": {
"self": "/calls?page=1"
},
"pagination":{
"totalCount":2,
"pageCount":1,
"currentPage":1,
"perPage":10
}
}
"""
callList = Client('', http_client).call_list(page=1)
http_client.request.assert_called_once_with('calls/?page=1', 'GET', None)
# check data is processed
self.assertEqual('no_answer', callList.data[0].status)
self.assertEqual('ended', callList.data[1].status)
# check pagination is passed to object
self.assertEqual(2, callList.totalCount)
self.assertEqual(1, callList.pageCount)
self.assertEqual(1, callList.currentPage)
self.assertEqual(10, callList.perPage)
self.assertEqual(10, callList.pagination['perPage'], 'Check it also supports API pagination format.')
self.assertEqual(0, callList.offset, 'Check it correctly calculates offset.')
self.assertEqual(10, callList.limit, 'Check it correctly calculates limit.')
def test_call_create(self):
api_response = {
"data": [
{
"id": "21025ed1-cc1d-4554-ac05-043fa6c84e00",
"status": "queued",
"source": "31644556677",
"destination": "31612345678",
"createdAt": "2017-08-30T07:35:37Z",
"updatedAt": "2017-08-30T07:35:37Z",
"endedAt": None
}
],
"_links": {
"self": "/calls/21025ed1-cc1d-4554-ac05-043fa6c84e00"
}
}
params = {
"source": "31644556677",
"destination": "31612345678",
"callFlow": {
"title": "Say message",
"steps": [
{
"action": "say",
"options": {
"payload": "This is a journey into sound. Good bye!",
"voice": "male",
"language": "en-US"
}
}
]
},
"webhook": {
"url": "https://example.com",
"token": "token_to_sign_the_call_events_with",
}
}
http_client = Mock()
http_client.request.return_value = json.dumps(api_response)
call_creation_response = Client('', http_client).call_create(**params)
http_client.request.assert_called_once_with('calls', 'POST', params)
# check all api response data is outputted
expected_data = self.create_expected_call_data_based_on_api_response(api_response)
response_data = call_creation_response.data.__dict__
self.assertEqual(expected_data, response_data, 'Check client response contains the API response data.')
# check it can be formatted as string
self.assertTrue(len(str(call_creation_response)) > 0, 'Check returned call can be formatted as string.')
def test_call_delete(self):
http_client = Mock()
http_client.request.return_value = ''
call_id_to_delete = '21025ed1-cc1d-4554-ac05-043fa6c84e00'
Client('', http_client).call_delete(call_id_to_delete)
http_client.request.assert_called_once_with('calls/%s' % call_id_to_delete, 'DELETE', None)
@staticmethod
def create_expected_call_data_based_on_api_response(api_response):
expected_data = api_response['data'][0]
# convert dates
expected_data['_createdAt'] = Base.value_to_time(expected_data['createdAt'], '%Y-%m-%dT%H:%M:%SZ')
expected_data['_updatedAt'] = Base.value_to_time(expected_data['updatedAt'], '%Y-%m-%dT%H:%M:%SZ')
expected_data['_endedAt'] = Base.value_to_time(expected_data['endedAt'], '%Y-%m-%dT%H:%M:%SZ')
del (expected_data['createdAt'], expected_data['updatedAt'], expected_data['endedAt'])
# add generated data
expected_data.setdefault('_webhook', None)
return expected_data | tests/test_call.py | import json
import unittest
from messagebird import Client, ErrorException
from messagebird.base import Base
from messagebird.client import VOICE_TYPE
try:
from unittest.mock import Mock
except ImportError:
# mock was added to unittest in Python 3.3, but was an external library
# before.
from mock import Mock
class TestCall(unittest.TestCase):
def test_call(self):
http_client = Mock()
http_client.request.return_value = """
{
"data":[
{
"id":"call-id",
"status":"ended",
"source":"16479311111",
"destination":"1416555555",
"createdAt":"2019-08-06T13:17:06Z",
"updatedAt":"2019-08-06T13:17:39Z",
"endedAt":"2019-08-06T13:17:39Z"
}
],
"_links":{
"legs":"/calls/66bd9f08-a8af-40fe-a830-652d8dabc057/legs",
"self":"/calls/66bd9f08-a8af-40fe-a830-652d8bca357"
},
"pagination":{
"totalCount":0,
"pageCount":0,
"currentPage":0,
"perPage":0
}
}
"""
call = Client('', http_client).call('call-id')
http_client.request.assert_called_once_with('calls/call-id', 'GET', None)
self.assertEqual('ended', call.data.status)
def test_call_list(self):
http_client = Mock()
http_client.request.return_value = """
{
"data":[
{
"id":"dda20377-72da-4846-9b2c-0fea3ad4bcb6",
"status":"no_answer",
"source":"16479311111",
"destination":"1416555555",
"createdAt":"2019-08-06T13:17:06Z",
"updatedAt":"2019-08-06T13:17:39Z",
"endedAt":"2019-08-06T13:17:39Z",
"_links":{
"legs":"/calls/dda20377-72da-4846-9b2c-0fea3ad4bcb6/legs",
"self":"/calls/dda20377-72da-4846-9b2c-0fea3ad4bcb6"
}
},
{
"id":"1541535b-9b80-4002-bde5-ed05b5ebed76",
"status":"ended",
"source":"16479311111",
"destination":"1416555556",
"createdAt":"2019-08-06T13:17:06Z",
"updatedAt":"2019-08-06T13:17:39Z",
"endedAt":"2019-08-06T13:17:39Z",
"_links":{
"legs":"/calls/1541535b-9b80-4002-bde5-ed05b5ebed76/legs",
"self":"/calls/1541535b-9b80-4002-bde5-ed05b5ebed76"
}
}
],
"_links": {
"self": "/calls?page=1"
},
"pagination":{
"totalCount":2,
"pageCount":1,
"currentPage":1,
"perPage":10
}
}
"""
callList = Client('', http_client).call_list(page=1)
http_client.request.assert_called_once_with('calls/?page=1', 'GET', None)
# check data is processed
self.assertEqual('no_answer', callList.data[0].status)
self.assertEqual('ended', callList.data[1].status)
# check pagination is passed to object
self.assertEqual(2, callList.totalCount)
self.assertEqual(1, callList.pageCount)
self.assertEqual(1, callList.currentPage)
self.assertEqual(10, callList.perPage)
self.assertEqual(10, callList.pagination['perPage'], 'Check it also supports API pagination format.')
self.assertEqual(0, callList.offset, 'Check it correctly calculates offset.')
self.assertEqual(10, callList.limit, 'Check it correctly calculates limit.')
def test_call_create(self):
api_response = {
"data": [
{
"id": "21025ed1-cc1d-4554-ac05-043fa6c84e00",
"status": "queued",
"source": "31644556677",
"destination": "31612345678",
"createdAt": "2017-08-30T07:35:37Z",
"updatedAt": "2017-08-30T07:35:37Z",
"endedAt": None
}
],
"_links": {
"self": "/calls/21025ed1-cc1d-4554-ac05-043fa6c84e00"
}
}
params = {
"source": "31644556677",
"destination": "31612345678",
"callFlow": {
"title": "Say message",
"steps": [
{
"action": "say",
"options": {
"payload": "This is a journey into sound. Good bye!",
"voice": "male",
"language": "en-US"
}
}
]
},
"webhook": {
"url": "https://example.com",
"token": "token_to_sign_the_call_events_with",
}
}
http_client = Mock()
http_client.request.return_value = json.dumps(api_response)
call_creation_response = Client('', http_client).call_create(**params)
http_client.request.assert_called_once_with('calls', 'POST', params)
# check all api response data is outputted
expected_data = self.create_expected_call_data_based_on_api_response(api_response)
response_data = call_creation_response.data.__dict__
self.assertEqual(expected_data, response_data, 'Check client response contains the API response data.')
# check it can be formatted as string
self.assertTrue(len(str(call_creation_response)) > 0, 'Check returned call can be formatted as string.')
def test_call_delete(self):
http_client = Mock()
http_client.request.return_value = ''
call_id_to_delete = '21025ed1-cc1d-4554-ac05-043fa6c84e00'
Client('', http_client).call_delete(call_id_to_delete)
http_client.request.assert_called_once_with('calls/%s' % call_id_to_delete, 'DELETE', None)
@staticmethod
def create_expected_call_data_based_on_api_response(api_response):
expected_data = api_response['data'][0]
# convert dates
expected_data['_createdAt'] = Base.value_to_time(expected_data['createdAt'], '%Y-%m-%dT%H:%M:%SZ')
expected_data['_updatedAt'] = Base.value_to_time(expected_data['updatedAt'], '%Y-%m-%dT%H:%M:%SZ')
expected_data['_endedAt'] = Base.value_to_time(expected_data['endedAt'], '%Y-%m-%dT%H:%M:%SZ')
del (expected_data['createdAt'], expected_data['updatedAt'], expected_data['endedAt'])
# add generated data
expected_data.setdefault('_webhook', None)
return expected_data | 0.529507 | 0.285129 |
import cv2.cv as cv
color_tracker_window = "Color Tracker"
class ColorTracker:
def __init__(self):
cv.NamedWindow( color_tracker_window, 1 )
self.capture = cv.CaptureFromCAM(2)
def run(self):
while True:
img = cv.QueryFrame( self.capture )
#blur the source image to reduce color noise
cv.Smooth(img, img, cv.CV_BLUR, 3);
#convert the image to hsv(Hue, Saturation, Value) so its
#easier to determine the color to track(hue)
hsv_img = cv.CreateImage(cv.GetSize(img), 8, 3)
cv.CvtColor(img, hsv_img, cv.CV_BGR2HSV)
#limit all pixels that don't match our criteria, in this case we are
#looking for purple but if you want you can adjust the first value in
#both turples which is the hue range(120,140). OpenCV uses 0-180 as
#a hue range for the HSV color model
thresholded_img = cv.CreateImage(cv.GetSize(hsv_img), 8, 1)
cv.InRangeS(hsv_img, (120, 80, 80), (140, 255, 255), thresholded_img)
#determine the objects moments and check that the area is large
#enough to be our object
moments = cv.Moments(thresholded_img, 0)
area = cv.GetCentralMoment(moments, 0, 0)
#there can be noise in the video so ignore objects with small areas
if(area > 100000):
#determine the x and y coordinates of the center of the object
#we are tracking by dividing the 1, 0 and 0, 1 moments by the area
x = int(round(cv.GetSpatialMoment(moments, 1, 0)/area))
y = int(round(cv.GetSpatialMoment(moments, 0, 1)/area))
#print 'x: ' + str(x) + ' y: ' + str(y) + ' area: ' + str(area)
#create an overlay to mark the center of the tracked object
overlay = cv.CreateImage(cv.GetSize(img), 8, 3)
cv.Circle(overlay, (x, y), 2, (255, 255, 255), 20)
cv.Add(img, overlay, img)
#add the thresholded image back to the img so we can see what was
#left after it was applied
cv.Merge(thresholded_img, None, None, None, img)
#display the image
cv.ShowImage(color_tracker_window, img)
if cv.WaitKey(10) == 27:
break
if __name__=="__main__":
color_tracker = ColorTracker()
color_tracker.run() | showers/pi/cameraovtest2.py |
import cv2.cv as cv
color_tracker_window = "Color Tracker"
class ColorTracker:
def __init__(self):
cv.NamedWindow( color_tracker_window, 1 )
self.capture = cv.CaptureFromCAM(2)
def run(self):
while True:
img = cv.QueryFrame( self.capture )
#blur the source image to reduce color noise
cv.Smooth(img, img, cv.CV_BLUR, 3);
#convert the image to hsv(Hue, Saturation, Value) so its
#easier to determine the color to track(hue)
hsv_img = cv.CreateImage(cv.GetSize(img), 8, 3)
cv.CvtColor(img, hsv_img, cv.CV_BGR2HSV)
#limit all pixels that don't match our criteria, in this case we are
#looking for purple but if you want you can adjust the first value in
#both turples which is the hue range(120,140). OpenCV uses 0-180 as
#a hue range for the HSV color model
thresholded_img = cv.CreateImage(cv.GetSize(hsv_img), 8, 1)
cv.InRangeS(hsv_img, (120, 80, 80), (140, 255, 255), thresholded_img)
#determine the objects moments and check that the area is large
#enough to be our object
moments = cv.Moments(thresholded_img, 0)
area = cv.GetCentralMoment(moments, 0, 0)
#there can be noise in the video so ignore objects with small areas
if(area > 100000):
#determine the x and y coordinates of the center of the object
#we are tracking by dividing the 1, 0 and 0, 1 moments by the area
x = int(round(cv.GetSpatialMoment(moments, 1, 0)/area))
y = int(round(cv.GetSpatialMoment(moments, 0, 1)/area))
#print 'x: ' + str(x) + ' y: ' + str(y) + ' area: ' + str(area)
#create an overlay to mark the center of the tracked object
overlay = cv.CreateImage(cv.GetSize(img), 8, 3)
cv.Circle(overlay, (x, y), 2, (255, 255, 255), 20)
cv.Add(img, overlay, img)
#add the thresholded image back to the img so we can see what was
#left after it was applied
cv.Merge(thresholded_img, None, None, None, img)
#display the image
cv.ShowImage(color_tracker_window, img)
if cv.WaitKey(10) == 27:
break
if __name__=="__main__":
color_tracker = ColorTracker()
color_tracker.run() | 0.322206 | 0.355355 |
import os
import os.path
import re
from .Triangle import Triangle
from .Solid import Solid
from .Point import Point
class File(object):
""" File-object
Example for a file definition
>>> file1 = File(1, "foo.txt")
"""
def __init__(self,ID=None, Filepath=None):
self.__filepath = Filepath
self.__id = ID
@property
def id(self):
return self.__id
@ id.setter
def id(self, ID):
self.__id = ID
@property
def filepath(self):
return self.__filepath
@filepath.setter
def filepath(self, filepath):
self.__filepath = filepath
class STL(File):
""" STL-File with geometric data
:param ID (int): Id of the file
:param Filepath (str): Path of the file
Example for creating an stl-object
>>> file1 = STL(1, "./foo.stl")
>>> part = file.parts[0]
.. note::
The file will automatically import the results if the file is given
Otherwise you need to call import_stl
"""
def __init__(self, ID=None, Filepath=None):
File.__init__(self, ID, Filepath)
self.__parts = []
# If file is given the importin will started
if self.filepath:
self.read()
def get_parts(self):
"""
:return: All solid objects which are imported
"""
return self.__parts
def add_solid(self, solid):
self.__parts.append(solid)
def write(self, filename):
""" This method can export the current data into an stl-file
"""
if os.path.isfile(filename):
raise ValueError ("File does exist alread %f", filename)
print("Export stl in", filename)
o_file = open(filename,"w")
for part in self.__parts:
solid = part
o_file.write("solid Exported from DMST-STL\n")
for triangle in solid.triangles:
o_file.write("facet normal " + str(triangle.normal[0]) + " " + str(triangle.normal[1]) + " " + str(triangle.normal[2]) + "\n")
o_file.write("outer loop\n")
for point in triangle.points:
o_file.write("vertex " + str(point.x) + " " + str(point.y) + " " + str(point.z) + "\n")
o_file.write("endloop\n")
o_file.write("endfacet\n")
o_file.write("endsolid\n")
def read(self):
""" This method imports the geometry to the parts attribute
"""
if not os.path.isfile(self.filepath):
raise ValueError ("Given file doesnt exist %f", self.filepath)
i_file = open(self.filepath, "r")
# Patterns which are needed
s_pat = "solid"
l_pat = "outer loop"
f_pat = "facet"
p_pat = "vertex"
f_e_pat = "endfacet"
s_e_pat = "endsolid"
l_e_pat = "endloop"
solid_is_found = False
facet_is_found = False
loop_is_found = False
id_s = 0 # ID of the solid
id_t = 0 # ID for triangles
id_p = 0 # ID for points
tmp_p_list = [] # Saves all found points
id_p_old = 0 #ID for points
# Reading the file
for line in i_file:
line = line[0:-1]
# Solid is found
if re.match(s_pat, line, 2):
id_s +=1
s = Solid(id_s, [])
self.__parts.append(s)
solid_is_found = True
continue
# Solid is closed
if re.match(s_e_pat, line, 2):
solid_is_found = False
continue
# Facet is found
if re.match(f_pat, line,2) and solid_is_found:
id_t += 1
facet_is_found = True
t = Triangle(id_t, [])
words = line.split(" ")
nx = float(words[2])
ny = float(words[3])
nz = float(words[4])
t.normal = [nx, ny, nz]
s.triangles.append(t)
continue
# Facet is closed
if re.match(f_e_pat, line,2) and solid_is_found and facet_is_found:
facet_is_found = False
continue
# Loop is found
if re.match(l_pat, line,2) and solid_is_found and facet_is_found:
loop_is_found = True
continue
# Loop is closed
if re.match(l_e_pat, line,2) and solid_is_found and facet_is_found and loop_is_found:
loop_is_found = False
continue
# Vertex is found
if re.match(p_pat, line,2) and solid_is_found and facet_is_found and loop_is_found:
# Finding new point coord
words = line.split(" ")
x = float(words[1])
y = float(words[2])
z = float(words[3])
# Checking if point_id exists already
# If the point_id is found choose the same ID
p_is_found = False
controll_count = 0
for t_p in tmp_p_list:
if t_p.x == x and t_p.y == y and t_p.z == z:
id_p_old = t_p.id
controll_count += 1
p_is_found = True
if controll_count > 1:
raise ValueError("Two same points have different ID s")
# Creating a new point_id or selectin an old
if p_is_found:
p = Point(id_p_old, x, y, z)
else:
id_p += 1
p = Point(id_p, x, y, z)
tmp_p_list.append(p)
# Resulting point
t.points.append(p)
i_file.close()
if id_s== 0 or id_t== 0 or id_p== 0:
raise ValueError("Fileformat STL does not match: Define Solid-->Faces-->Vertexes")
print("STL-File succesfully imported")
print("Solids: ", id_s)
print("Triangles", id_t)
print("Different Vertices", id_p) | ToOptix/FEMPy/Geometry/STLPhraser.py | import os
import os.path
import re
from .Triangle import Triangle
from .Solid import Solid
from .Point import Point
class File(object):
""" File-object
Example for a file definition
>>> file1 = File(1, "foo.txt")
"""
def __init__(self,ID=None, Filepath=None):
self.__filepath = Filepath
self.__id = ID
@property
def id(self):
return self.__id
@ id.setter
def id(self, ID):
self.__id = ID
@property
def filepath(self):
return self.__filepath
@filepath.setter
def filepath(self, filepath):
self.__filepath = filepath
class STL(File):
""" STL-File with geometric data
:param ID (int): Id of the file
:param Filepath (str): Path of the file
Example for creating an stl-object
>>> file1 = STL(1, "./foo.stl")
>>> part = file.parts[0]
.. note::
The file will automatically import the results if the file is given
Otherwise you need to call import_stl
"""
def __init__(self, ID=None, Filepath=None):
File.__init__(self, ID, Filepath)
self.__parts = []
# If file is given the importin will started
if self.filepath:
self.read()
def get_parts(self):
"""
:return: All solid objects which are imported
"""
return self.__parts
def add_solid(self, solid):
self.__parts.append(solid)
def write(self, filename):
""" This method can export the current data into an stl-file
"""
if os.path.isfile(filename):
raise ValueError ("File does exist alread %f", filename)
print("Export stl in", filename)
o_file = open(filename,"w")
for part in self.__parts:
solid = part
o_file.write("solid Exported from DMST-STL\n")
for triangle in solid.triangles:
o_file.write("facet normal " + str(triangle.normal[0]) + " " + str(triangle.normal[1]) + " " + str(triangle.normal[2]) + "\n")
o_file.write("outer loop\n")
for point in triangle.points:
o_file.write("vertex " + str(point.x) + " " + str(point.y) + " " + str(point.z) + "\n")
o_file.write("endloop\n")
o_file.write("endfacet\n")
o_file.write("endsolid\n")
def read(self):
""" This method imports the geometry to the parts attribute
"""
if not os.path.isfile(self.filepath):
raise ValueError ("Given file doesnt exist %f", self.filepath)
i_file = open(self.filepath, "r")
# Patterns which are needed
s_pat = "solid"
l_pat = "outer loop"
f_pat = "facet"
p_pat = "vertex"
f_e_pat = "endfacet"
s_e_pat = "endsolid"
l_e_pat = "endloop"
solid_is_found = False
facet_is_found = False
loop_is_found = False
id_s = 0 # ID of the solid
id_t = 0 # ID for triangles
id_p = 0 # ID for points
tmp_p_list = [] # Saves all found points
id_p_old = 0 #ID for points
# Reading the file
for line in i_file:
line = line[0:-1]
# Solid is found
if re.match(s_pat, line, 2):
id_s +=1
s = Solid(id_s, [])
self.__parts.append(s)
solid_is_found = True
continue
# Solid is closed
if re.match(s_e_pat, line, 2):
solid_is_found = False
continue
# Facet is found
if re.match(f_pat, line,2) and solid_is_found:
id_t += 1
facet_is_found = True
t = Triangle(id_t, [])
words = line.split(" ")
nx = float(words[2])
ny = float(words[3])
nz = float(words[4])
t.normal = [nx, ny, nz]
s.triangles.append(t)
continue
# Facet is closed
if re.match(f_e_pat, line,2) and solid_is_found and facet_is_found:
facet_is_found = False
continue
# Loop is found
if re.match(l_pat, line,2) and solid_is_found and facet_is_found:
loop_is_found = True
continue
# Loop is closed
if re.match(l_e_pat, line,2) and solid_is_found and facet_is_found and loop_is_found:
loop_is_found = False
continue
# Vertex is found
if re.match(p_pat, line,2) and solid_is_found and facet_is_found and loop_is_found:
# Finding new point coord
words = line.split(" ")
x = float(words[1])
y = float(words[2])
z = float(words[3])
# Checking if point_id exists already
# If the point_id is found choose the same ID
p_is_found = False
controll_count = 0
for t_p in tmp_p_list:
if t_p.x == x and t_p.y == y and t_p.z == z:
id_p_old = t_p.id
controll_count += 1
p_is_found = True
if controll_count > 1:
raise ValueError("Two same points have different ID s")
# Creating a new point_id or selectin an old
if p_is_found:
p = Point(id_p_old, x, y, z)
else:
id_p += 1
p = Point(id_p, x, y, z)
tmp_p_list.append(p)
# Resulting point
t.points.append(p)
i_file.close()
if id_s== 0 or id_t== 0 or id_p== 0:
raise ValueError("Fileformat STL does not match: Define Solid-->Faces-->Vertexes")
print("STL-File succesfully imported")
print("Solids: ", id_s)
print("Triangles", id_t)
print("Different Vertices", id_p) | 0.554109 | 0.177811 |
import tensorflow as tf
from tensorflow.python.ops import control_flow_ops
from configs.config_train import *
import tensorflow.contrib.slim.nets
class Training(object):
def __init__(self):
a=1
def training(self, sess, model, images, is_training, y_true):
with tf.variable_scope('yolov3'):
pred_feature_map = model.forward(images, is_training=is_training)
loss = model.compute_loss(pred_feature_map, y_true)
y_pred = model.predict(pred_feature_map)
tf.summary.scalar("loss/coord_loss", loss[1])
tf.summary.scalar("loss/sizes_loss", loss[2])
tf.summary.scalar("loss/confs_loss", loss[3])
tf.summary.scalar("loss/class_loss", loss[4])
global_step = tf.Variable(0, trainable=False, collections=[tf.GraphKeys.LOCAL_VARIABLES])
write_op = tf.summary.merge_all()
writer_train = tf.summary.FileWriter(FLAGS.train_summary_data_path)
saver_to_restore = tf.train.Saver(var_list=tf.contrib.framework.get_variables_to_restore(
include=[FLAGS.train_darknet_model_path]))
update_vars = tf.contrib.framework.get_variables_to_restore(include=[FLAGS.train_yolov3_model_path])
learning_rate = tf.train.exponential_decay(FLAGS.train_learning_rate, global_step,
decay_steps=FLAGS.train_decay_steps,
decay_rate=FLAGS.train_decay_rate, staircase=True)
optimizer = tf.train.AdamOptimizer(learning_rate)
# set dependencies for BN ops
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
train_op = optimizer.minimize(loss[0], var_list=update_vars, global_step=global_step)
sess.run([tf.global_variables_initializer(), tf.local_variables_initializer()])
saver_to_restore.restore(sess, FLAGS.train_yolov3_checkpoints)
saver = tf.train.Saver(max_to_keep=2)
for epoch in range(FLAGS.train_epochs):
run_items = sess.run([train_op, write_op, y_pred, y_true] + loss, feed_dict={is_training:True})
if (epoch+1) % FLAGS.train_eval_internal == 0:
train_rec_value, train_prec_value = utils.evaluate(run_items[2], run_items[3])
writer_train.add_summary(run_items[1], global_step=epoch)
writer_train.flush()
if (epoch+1) % 500 == 0: saver.save(sess, save_path=FLAGS.train_yolov3_checkpoints, global_step=epoch+1)
print("=> EPOCH %10d [TRAIN]:\tloss_xy:%7.4f \tloss_wh:%7.4f \tloss_conf:%7.4f \tloss_class:%7.4f"
%(epoch+1, run_items[5], run_items[6], run_items[7], run_items[8])) | training/training.py |
import tensorflow as tf
from tensorflow.python.ops import control_flow_ops
from configs.config_train import *
import tensorflow.contrib.slim.nets
class Training(object):
def __init__(self):
a=1
def training(self, sess, model, images, is_training, y_true):
with tf.variable_scope('yolov3'):
pred_feature_map = model.forward(images, is_training=is_training)
loss = model.compute_loss(pred_feature_map, y_true)
y_pred = model.predict(pred_feature_map)
tf.summary.scalar("loss/coord_loss", loss[1])
tf.summary.scalar("loss/sizes_loss", loss[2])
tf.summary.scalar("loss/confs_loss", loss[3])
tf.summary.scalar("loss/class_loss", loss[4])
global_step = tf.Variable(0, trainable=False, collections=[tf.GraphKeys.LOCAL_VARIABLES])
write_op = tf.summary.merge_all()
writer_train = tf.summary.FileWriter(FLAGS.train_summary_data_path)
saver_to_restore = tf.train.Saver(var_list=tf.contrib.framework.get_variables_to_restore(
include=[FLAGS.train_darknet_model_path]))
update_vars = tf.contrib.framework.get_variables_to_restore(include=[FLAGS.train_yolov3_model_path])
learning_rate = tf.train.exponential_decay(FLAGS.train_learning_rate, global_step,
decay_steps=FLAGS.train_decay_steps,
decay_rate=FLAGS.train_decay_rate, staircase=True)
optimizer = tf.train.AdamOptimizer(learning_rate)
# set dependencies for BN ops
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
train_op = optimizer.minimize(loss[0], var_list=update_vars, global_step=global_step)
sess.run([tf.global_variables_initializer(), tf.local_variables_initializer()])
saver_to_restore.restore(sess, FLAGS.train_yolov3_checkpoints)
saver = tf.train.Saver(max_to_keep=2)
for epoch in range(FLAGS.train_epochs):
run_items = sess.run([train_op, write_op, y_pred, y_true] + loss, feed_dict={is_training:True})
if (epoch+1) % FLAGS.train_eval_internal == 0:
train_rec_value, train_prec_value = utils.evaluate(run_items[2], run_items[3])
writer_train.add_summary(run_items[1], global_step=epoch)
writer_train.flush()
if (epoch+1) % 500 == 0: saver.save(sess, save_path=FLAGS.train_yolov3_checkpoints, global_step=epoch+1)
print("=> EPOCH %10d [TRAIN]:\tloss_xy:%7.4f \tloss_wh:%7.4f \tloss_conf:%7.4f \tloss_class:%7.4f"
%(epoch+1, run_items[5], run_items[6], run_items[7], run_items[8])) | 0.786828 | 0.235405 |
import torch
import torch.nn as nn
import torch.nn.functional as F
class _PositionAttentionModule(nn.Module):
""" Position attention module"""
def __init__(self, in_channels, **kwargs):
super(_PositionAttentionModule, self).__init__()
self.conv_b = nn.Conv2d(in_channels, in_channels // 8, 1)
self.conv_c = nn.Conv2d(in_channels, in_channels // 8, 1)
self.conv_d = nn.Conv2d(in_channels, in_channels, 1)
self.alpha = nn.Parameter(torch.zeros(1))
self.softmax = nn.Softmax(dim=-1)
def forward(self, x):
batch_size, _, height, width = x.size()
feat_b = self.conv_b(x).view(batch_size, -1, height * width).permute(0, 2, 1)
feat_c = self.conv_c(x).view(batch_size, -1, height * width)
attention_s = self.softmax(torch.bmm(feat_b, feat_c))
feat_d = self.conv_d(x).view(batch_size, -1, height * width)
feat_e = torch.bmm(feat_d, attention_s.permute(0, 2, 1)).view(batch_size, -1, height, width)
out = self.alpha * feat_e + x
return out
class _ChannelAttentionModule(nn.Module):
"""Channel attention module"""
def __init__(self, **kwargs):
super(_ChannelAttentionModule, self).__init__()
self.beta = nn.Parameter(torch.zeros(1))
self.softmax = nn.Softmax(dim=-1)
def forward(self, x):
batch_size, _, height, width = x.size()
feat_a = x.view(batch_size, -1, height * width)
feat_a_transpose = x.view(batch_size, -1, height * width).permute(0, 2, 1)
attention = torch.bmm(feat_a, feat_a_transpose)
attention_new = torch.max(attention, dim=-1, keepdim=True)[0].expand_as(attention) - attention
attention = self.softmax(attention_new)
feat_e = torch.bmm(attention, feat_a).view(batch_size, -1, height, width)
out = self.beta * feat_e + x
return out
class _DAHead(nn.Module):
def __init__(self, in_channels, nclass, aux=True, norm_layer=nn.BatchNorm2d, norm_kwargs=None, **kwargs):
super(_DAHead, self).__init__()
self.aux = aux
inter_channels = in_channels // 4
self.conv_p1 = nn.Sequential(
nn.Conv2d(in_channels, inter_channels, 3, padding=1, bias=False),
norm_layer(inter_channels, **({} if norm_kwargs is None else norm_kwargs)),
nn.ReLU(True)
)
self.conv_c1 = nn.Sequential(
nn.Conv2d(in_channels, inter_channels, 3, padding=1, bias=False),
norm_layer(inter_channels, **({} if norm_kwargs is None else norm_kwargs)),
nn.ReLU(True)
)
self.pam = _PositionAttentionModule(inter_channels, **kwargs)
self.cam = _ChannelAttentionModule(**kwargs)
self.conv_p2 = nn.Sequential(
nn.Conv2d(inter_channels, inter_channels, 3, padding=1, bias=False),
norm_layer(inter_channels, **({} if norm_kwargs is None else norm_kwargs)),
nn.ReLU(True)
)
self.conv_c2 = nn.Sequential(
nn.Conv2d(inter_channels, inter_channels, 3, padding=1, bias=False),
norm_layer(inter_channels, **({} if norm_kwargs is None else norm_kwargs)),
nn.ReLU(True)
)
self.out = nn.Sequential(
nn.Dropout(0.1),
nn.Conv2d(inter_channels, nclass, 1)
)
if aux:
self.conv_p3 = nn.Sequential(
nn.Dropout(0.1),
nn.Conv2d(inter_channels, nclass, 1)
)
self.conv_c3 = nn.Sequential(
nn.Dropout(0.1),
nn.Conv2d(inter_channels, nclass, 1)
)
def forward(self, x):
feat_p = self.conv_p1(x)
feat_p = self.pam(feat_p)
feat_p = self.conv_p2(feat_p)
feat_c = self.conv_c1(x)
feat_c = self.cam(feat_c)
feat_c = self.conv_c2(feat_c)
feat_fusion = feat_p + feat_c
outputs = []
fusion_out = self.out(feat_fusion)
outputs.append(fusion_out)
if self.aux:
p_out = self.conv_p3(feat_p)
c_out = self.conv_c3(feat_c)
outputs.append(p_out)
outputs.append(c_out)
return tuple(outputs) | models/ClassicNetwork/blocks/DaNet.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class _PositionAttentionModule(nn.Module):
""" Position attention module"""
def __init__(self, in_channels, **kwargs):
super(_PositionAttentionModule, self).__init__()
self.conv_b = nn.Conv2d(in_channels, in_channels // 8, 1)
self.conv_c = nn.Conv2d(in_channels, in_channels // 8, 1)
self.conv_d = nn.Conv2d(in_channels, in_channels, 1)
self.alpha = nn.Parameter(torch.zeros(1))
self.softmax = nn.Softmax(dim=-1)
def forward(self, x):
batch_size, _, height, width = x.size()
feat_b = self.conv_b(x).view(batch_size, -1, height * width).permute(0, 2, 1)
feat_c = self.conv_c(x).view(batch_size, -1, height * width)
attention_s = self.softmax(torch.bmm(feat_b, feat_c))
feat_d = self.conv_d(x).view(batch_size, -1, height * width)
feat_e = torch.bmm(feat_d, attention_s.permute(0, 2, 1)).view(batch_size, -1, height, width)
out = self.alpha * feat_e + x
return out
class _ChannelAttentionModule(nn.Module):
"""Channel attention module"""
def __init__(self, **kwargs):
super(_ChannelAttentionModule, self).__init__()
self.beta = nn.Parameter(torch.zeros(1))
self.softmax = nn.Softmax(dim=-1)
def forward(self, x):
batch_size, _, height, width = x.size()
feat_a = x.view(batch_size, -1, height * width)
feat_a_transpose = x.view(batch_size, -1, height * width).permute(0, 2, 1)
attention = torch.bmm(feat_a, feat_a_transpose)
attention_new = torch.max(attention, dim=-1, keepdim=True)[0].expand_as(attention) - attention
attention = self.softmax(attention_new)
feat_e = torch.bmm(attention, feat_a).view(batch_size, -1, height, width)
out = self.beta * feat_e + x
return out
class _DAHead(nn.Module):
def __init__(self, in_channels, nclass, aux=True, norm_layer=nn.BatchNorm2d, norm_kwargs=None, **kwargs):
super(_DAHead, self).__init__()
self.aux = aux
inter_channels = in_channels // 4
self.conv_p1 = nn.Sequential(
nn.Conv2d(in_channels, inter_channels, 3, padding=1, bias=False),
norm_layer(inter_channels, **({} if norm_kwargs is None else norm_kwargs)),
nn.ReLU(True)
)
self.conv_c1 = nn.Sequential(
nn.Conv2d(in_channels, inter_channels, 3, padding=1, bias=False),
norm_layer(inter_channels, **({} if norm_kwargs is None else norm_kwargs)),
nn.ReLU(True)
)
self.pam = _PositionAttentionModule(inter_channels, **kwargs)
self.cam = _ChannelAttentionModule(**kwargs)
self.conv_p2 = nn.Sequential(
nn.Conv2d(inter_channels, inter_channels, 3, padding=1, bias=False),
norm_layer(inter_channels, **({} if norm_kwargs is None else norm_kwargs)),
nn.ReLU(True)
)
self.conv_c2 = nn.Sequential(
nn.Conv2d(inter_channels, inter_channels, 3, padding=1, bias=False),
norm_layer(inter_channels, **({} if norm_kwargs is None else norm_kwargs)),
nn.ReLU(True)
)
self.out = nn.Sequential(
nn.Dropout(0.1),
nn.Conv2d(inter_channels, nclass, 1)
)
if aux:
self.conv_p3 = nn.Sequential(
nn.Dropout(0.1),
nn.Conv2d(inter_channels, nclass, 1)
)
self.conv_c3 = nn.Sequential(
nn.Dropout(0.1),
nn.Conv2d(inter_channels, nclass, 1)
)
def forward(self, x):
feat_p = self.conv_p1(x)
feat_p = self.pam(feat_p)
feat_p = self.conv_p2(feat_p)
feat_c = self.conv_c1(x)
feat_c = self.cam(feat_c)
feat_c = self.conv_c2(feat_c)
feat_fusion = feat_p + feat_c
outputs = []
fusion_out = self.out(feat_fusion)
outputs.append(fusion_out)
if self.aux:
p_out = self.conv_p3(feat_p)
c_out = self.conv_c3(feat_c)
outputs.append(p_out)
outputs.append(c_out)
return tuple(outputs) | 0.949751 | 0.456531 |
import framebuf
import i2c
import utime as time
from micropython import const
# a few register definitions
_SET_CONTRAST = const(0x81)
_SET_NORM_INV = const(0xa6)
_SET_DISP = const(0xae)
_SET_SCAN_DIR = const(0xc0)
_SET_SEG_REMAP = const(0xa0)
_LOW_COLUMN_ADDRESS = const(0x00)
_HIGH_COLUMN_ADDRESS = const(0x10)
_SET_PAGE_ADDRESS = const(0xB0)
class SSD1306:
def __init__(self, width=128, height=64, i2c_id=3, addr=0x3c):
i2c.init(i2c_id, 100)
self.i2c_id = i2c_id
self.addr = addr
self.width = width
self.height = height
self.pages = self.height // 8
self.buffer = bytearray(self.pages * self.width)
fb = framebuf.FrameBuffer(self.buffer, self.width, self.height,
framebuf.MVLSB)
self.framebuf = fb
# set shortcuts for the methods of framebuf
self.fill = fb.fill
self.fill_rect = fb.fill_rect
self.hline = fb.hline
self.vline = fb.vline
self.line = fb.line
self.rect = fb.rect
self.pixel = fb.pixel
self.scroll = fb.scroll
self.text = fb.text
self.blit = fb.blit
self.init_display()
def init_display(self):
self.fill(0)
self.poweron()
self.show()
def poweroff(self):
self.write_cmd(_SET_DISP | 0x00)
def poweron(self):
self.write_cmd(_SET_DISP | 0x01)
def rotate(self, flag, update=True):
if flag:
self.write_cmd(_SET_SEG_REMAP | 0x01) # mirror display vertically
self.write_cmd(_SET_SCAN_DIR | 0x08) # mirror display hor.
else:
self.write_cmd(_SET_SEG_REMAP | 0x00)
self.write_cmd(_SET_SCAN_DIR | 0x00)
if update:
self.show()
def sleep(self, value):
self.write_cmd(_SET_DISP | (not value))
def contrast(self, contrast):
self.write_cmd(_SET_CONTRAST)
self.write_cmd(contrast)
def invert(self, invert):
self.write_cmd(_SET_NORM_INV | (invert & 1))
def show(self):
for page in range(self.height // 8):
self.write_cmd(_SET_PAGE_ADDRESS | page)
self.write_cmd(_LOW_COLUMN_ADDRESS | 2)
self.write_cmd(_HIGH_COLUMN_ADDRESS | 0)
self.write_data(self.buffer[self.width * page:self.width * page + self.width])
def write_cmd(self, i2c_command):
temp = bytearray(2)
temp[0] = 0x80
temp[1] = i2c_command
i2c.mem_transmit(self.i2c_id, self.addr, 0x00, 1, temp, 1000)
def write_data(self, i2c_data):
i2c.mem_transmit(self.i2c_id, self.addr, 0x40, 1, i2c_data, 1000) | ssd1306.py | import framebuf
import i2c
import utime as time
from micropython import const
# a few register definitions
_SET_CONTRAST = const(0x81)
_SET_NORM_INV = const(0xa6)
_SET_DISP = const(0xae)
_SET_SCAN_DIR = const(0xc0)
_SET_SEG_REMAP = const(0xa0)
_LOW_COLUMN_ADDRESS = const(0x00)
_HIGH_COLUMN_ADDRESS = const(0x10)
_SET_PAGE_ADDRESS = const(0xB0)
class SSD1306:
def __init__(self, width=128, height=64, i2c_id=3, addr=0x3c):
i2c.init(i2c_id, 100)
self.i2c_id = i2c_id
self.addr = addr
self.width = width
self.height = height
self.pages = self.height // 8
self.buffer = bytearray(self.pages * self.width)
fb = framebuf.FrameBuffer(self.buffer, self.width, self.height,
framebuf.MVLSB)
self.framebuf = fb
# set shortcuts for the methods of framebuf
self.fill = fb.fill
self.fill_rect = fb.fill_rect
self.hline = fb.hline
self.vline = fb.vline
self.line = fb.line
self.rect = fb.rect
self.pixel = fb.pixel
self.scroll = fb.scroll
self.text = fb.text
self.blit = fb.blit
self.init_display()
def init_display(self):
self.fill(0)
self.poweron()
self.show()
def poweroff(self):
self.write_cmd(_SET_DISP | 0x00)
def poweron(self):
self.write_cmd(_SET_DISP | 0x01)
def rotate(self, flag, update=True):
if flag:
self.write_cmd(_SET_SEG_REMAP | 0x01) # mirror display vertically
self.write_cmd(_SET_SCAN_DIR | 0x08) # mirror display hor.
else:
self.write_cmd(_SET_SEG_REMAP | 0x00)
self.write_cmd(_SET_SCAN_DIR | 0x00)
if update:
self.show()
def sleep(self, value):
self.write_cmd(_SET_DISP | (not value))
def contrast(self, contrast):
self.write_cmd(_SET_CONTRAST)
self.write_cmd(contrast)
def invert(self, invert):
self.write_cmd(_SET_NORM_INV | (invert & 1))
def show(self):
for page in range(self.height // 8):
self.write_cmd(_SET_PAGE_ADDRESS | page)
self.write_cmd(_LOW_COLUMN_ADDRESS | 2)
self.write_cmd(_HIGH_COLUMN_ADDRESS | 0)
self.write_data(self.buffer[self.width * page:self.width * page + self.width])
def write_cmd(self, i2c_command):
temp = bytearray(2)
temp[0] = 0x80
temp[1] = i2c_command
i2c.mem_transmit(self.i2c_id, self.addr, 0x00, 1, temp, 1000)
def write_data(self, i2c_data):
i2c.mem_transmit(self.i2c_id, self.addr, 0x40, 1, i2c_data, 1000) | 0.384103 | 0.090173 |
import click
import sys
from odc.io.text import click_range2d
from ._cli_common import main
@main.command('save-tasks')
@click.option('--grid',
type=str,
help=("Grid name or spec: albers_au_25,albers_africa_{10|20|30|60},"
"'crs;pixel_resolution;shape_in_pixels'"),
prompt="""Enter GridSpec
one of albers_au_25, albers_africa_{10|20|30|60}
or custom like 'epsg:3857;30;5000' (30m pixels 5,000 per side in epsg:3857)
>""",
default=None)
@click.option('--year',
type=int,
help="Only extract datasets for a given year. This is a shortcut for --temporal-range=<int>--P1Y")
@click.option('--temporal_range',
type=str,
help="Only extract datasets for a given time range, Example '2020-05--P1M' month of May 2020")
@click.option('--frequency',
type=str,
help="Specify temporal binning: annual|seasonal|all")
@click.option('--env', '-E', type=str, help='Datacube environment name')
@click.option('-z', 'complevel',
type=int,
default=6,
help='Compression setting for zstandard 1-fast, 9+ good but slow')
@click.option('--overwrite',
is_flag=True,
default=False,
help='Overwrite output if it exists')
@click.option('--tiles',
help='Limit query to tiles example: "0:3,2:4"',
callback=click_range2d)
@click.option('--debug',
is_flag=True,
default=False,
hidden=True,
help='Dump debug data to pickle')
@click.argument('product', type=str, nargs=1)
@click.argument('output', type=str, nargs=1, default='')
def save_tasks(grid, year, temporal_range, frequency,
output, product, env, complevel,
overwrite=False,
tiles=None,
debug=False):
"""
Prepare tasks for processing (query db).
<todo more help goes here>
\b
Not yet implemented features:
- output product config
- multi-product inputs
"""
from datacube import Datacube
from .tasks import SaveTasks
from .model import DateTimeRange
if temporal_range is not None and year is not None:
print("Can only supply one of --year or --temporal_range", file=sys.stderr)
sys.exit(1)
if temporal_range is not None:
try:
temporal_range = DateTimeRange(temporal_range)
except ValueError:
print(f"Failed to parse supplied temporal_range: '{temporal_range}'")
sys.exit(1)
if year is not None:
temporal_range = DateTimeRange.year(year)
if frequency is not None:
if frequency not in ('annual', 'all', 'seasonal'):
print(f"Frequency must be one of annual|seasonal|all and not '{frequency}'")
sys.exit(1)
if output == '':
if temporal_range is not None:
output = f'{product}_{temporal_range.short}.db'
else:
output = f'{product}_all.db'
try:
tasks = SaveTasks(output,
grid,
frequency=frequency,
overwrite=overwrite,
complevel=complevel)
except ValueError as e:
print(str(e))
sys.exit(1)
def on_message(msg):
print(msg)
dc = Datacube(env=env)
try:
ok = tasks.save(dc, product,
temporal_range=temporal_range,
tiles=tiles,
debug=debug,
msg=on_message)
except ValueError as e:
print(str(e))
sys.exit(2)
if not ok:
# exit with error code, failure message was already printed
sys.exit(3) | libs/stats/odc/stats/_cli_save_tasks.py | import click
import sys
from odc.io.text import click_range2d
from ._cli_common import main
@main.command('save-tasks')
@click.option('--grid',
type=str,
help=("Grid name or spec: albers_au_25,albers_africa_{10|20|30|60},"
"'crs;pixel_resolution;shape_in_pixels'"),
prompt="""Enter GridSpec
one of albers_au_25, albers_africa_{10|20|30|60}
or custom like 'epsg:3857;30;5000' (30m pixels 5,000 per side in epsg:3857)
>""",
default=None)
@click.option('--year',
type=int,
help="Only extract datasets for a given year. This is a shortcut for --temporal-range=<int>--P1Y")
@click.option('--temporal_range',
type=str,
help="Only extract datasets for a given time range, Example '2020-05--P1M' month of May 2020")
@click.option('--frequency',
type=str,
help="Specify temporal binning: annual|seasonal|all")
@click.option('--env', '-E', type=str, help='Datacube environment name')
@click.option('-z', 'complevel',
type=int,
default=6,
help='Compression setting for zstandard 1-fast, 9+ good but slow')
@click.option('--overwrite',
is_flag=True,
default=False,
help='Overwrite output if it exists')
@click.option('--tiles',
help='Limit query to tiles example: "0:3,2:4"',
callback=click_range2d)
@click.option('--debug',
is_flag=True,
default=False,
hidden=True,
help='Dump debug data to pickle')
@click.argument('product', type=str, nargs=1)
@click.argument('output', type=str, nargs=1, default='')
def save_tasks(grid, year, temporal_range, frequency,
output, product, env, complevel,
overwrite=False,
tiles=None,
debug=False):
"""
Prepare tasks for processing (query db).
<todo more help goes here>
\b
Not yet implemented features:
- output product config
- multi-product inputs
"""
from datacube import Datacube
from .tasks import SaveTasks
from .model import DateTimeRange
if temporal_range is not None and year is not None:
print("Can only supply one of --year or --temporal_range", file=sys.stderr)
sys.exit(1)
if temporal_range is not None:
try:
temporal_range = DateTimeRange(temporal_range)
except ValueError:
print(f"Failed to parse supplied temporal_range: '{temporal_range}'")
sys.exit(1)
if year is not None:
temporal_range = DateTimeRange.year(year)
if frequency is not None:
if frequency not in ('annual', 'all', 'seasonal'):
print(f"Frequency must be one of annual|seasonal|all and not '{frequency}'")
sys.exit(1)
if output == '':
if temporal_range is not None:
output = f'{product}_{temporal_range.short}.db'
else:
output = f'{product}_all.db'
try:
tasks = SaveTasks(output,
grid,
frequency=frequency,
overwrite=overwrite,
complevel=complevel)
except ValueError as e:
print(str(e))
sys.exit(1)
def on_message(msg):
print(msg)
dc = Datacube(env=env)
try:
ok = tasks.save(dc, product,
temporal_range=temporal_range,
tiles=tiles,
debug=debug,
msg=on_message)
except ValueError as e:
print(str(e))
sys.exit(2)
if not ok:
# exit with error code, failure message was already printed
sys.exit(3) | 0.359477 | 0.191706 |
# Data generated from http://www.json-generator.com/
# Using the following template
# [
# '{{repeat(100, 200)}}',
# {
# id: '{{objectId()}}',
# is_active: '{{bool()}}',
# number_of_children: '{{integer(0, 4)}}',
# age: '{{integer(15, 68)}}',
# eye_color: '{{random("blue", "brown", "green", "purple")}}',
# name: '{{firstName()}} {{surname()}}',
# gender: '{{gender()}}',
# has_beard: '{{bool()}}',
# email: '{{email()}}'
# }
# ]
fake = """
[
{
"id": "56c4e39a3e05a86e9f759ba8",
"is_active": true,
"number_of_children": 0,
"age": 35,
"eye_color": "brown",
"name": "Bernard",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"own_bookshop": true,
"company": {
"name": "blackbooks"
}
},
{
"id": "<KEY>",
"is_active": true,
"number_of_children": 0,
"age": 34,
"eye_color": "brown",
"name": "Manny",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"own_bookshop": false,
"company": {
"name": "blackbooks"
}
},
{
"id": "56c4e39a1f9b6f64db8a1b98",
"is_active": true,
"number_of_children": 0,
"age": 35,
"eye_color": "brown",
"name": "Fran",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"own_bookshop": false,
"company": {
"name": "blackbooks"
}
},
{
"id": "56c4f0c6e0a44d8855b26f96",
"is_active": true,
"number_of_children": 2,
"age": 40,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c65e2525167191a8db",
"is_active": true,
"number_of_children": 3,
"age": 47,
"eye_color": "purple",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6988994ceae9f57b7",
"is_active": false,
"number_of_children": 4,
"age": 26,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c62e5c88d563287b16",
"is_active": true,
"number_of_children": 0,
"age": 67,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6365282fb25d9e3bf",
"is_active": true,
"number_of_children": 2,
"age": 26,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6eba85a9ae63865bd",
"is_active": false,
"number_of_children": 2,
"age": 64,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c688f42d99f2015609",
"is_active": false,
"number_of_children": 0,
"age": 66,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6ed871a305f1d622a",
"is_active": true,
"number_of_children": 1,
"age": 20,
"eye_color": "purple",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c664d7cc87ed898157",
"is_active": true,
"number_of_children": 0,
"age": 68,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6627986bbc7be0358",
"is_active": true,
"number_of_children": 3,
"age": 18,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6f30623616b3788e5",
"is_active": true,
"number_of_children": 3,
"age": 31,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6f4121c82fc2df602",
"is_active": true,
"number_of_children": 1,
"age": 62,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6fa36e0f4ad5c9a8d",
"is_active": true,
"number_of_children": 1,
"age": 24,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6344d8fd84f4c66ee",
"is_active": true,
"number_of_children": 0,
"age": 64,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6ecd27f4a011162f4",
"is_active": true,
"number_of_children": 0,
"age": 67,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6358cd5b6a35c8867",
"is_active": false,
"number_of_children": 3,
"age": 57,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c60e3828978a71b245",
"is_active": true,
"number_of_children": 0,
"age": 46,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c696d5c2455312e4a0",
"is_active": false,
"number_of_children": 1,
"age": 34,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c655159e61a08cd2ee",
"is_active": true,
"number_of_children": 1,
"age": 42,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6db2eaf5cb46d62f9",
"is_active": false,
"number_of_children": 3,
"age": 65,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6808e6f717c1a0664",
"is_active": false,
"number_of_children": 1,
"age": 53,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6f8fd86a497c0872e",
"is_active": true,
"number_of_children": 2,
"age": 61,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6d2857317585a7295",
"is_active": false,
"number_of_children": 1,
"age": 17,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c63476b6c242dc4dca",
"is_active": true,
"number_of_children": 2,
"age": 42,
"eye_color": "purple",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c621c4b76dc449a29f",
"is_active": true,
"number_of_children": 2,
"age": 60,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c63343e71b0f12af7c",
"is_active": false,
"number_of_children": 3,
"age": 61,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c622ddf2447374df7d",
"is_active": true,
"number_of_children": 0,
"age": 31,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c687523df953184f2d",
"is_active": false,
"number_of_children": 4,
"age": 51,
"eye_color": "purple",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c675b95a772824f13b",
"is_active": true,
"number_of_children": 3,
"age": 32,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c660ffcc71d8248dcf",
"is_active": true,
"number_of_children": 0,
"age": 29,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c647b5a02e24f10878",
"is_active": false,
"number_of_children": 4,
"age": 58,
"eye_color": "purple",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6d9d9f48432451126",
"is_active": true,
"number_of_children": 3,
"age": 56,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6fa934d9b145cbb2e",
"is_active": false,
"number_of_children": 2,
"age": 35,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c673d82a25d5a79706",
"is_active": true,
"number_of_children": 0,
"age": 41,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c66a5a1cf941a6ad3c",
"is_active": true,
"number_of_children": 0,
"age": 66,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c638780e95d7a501f6",
"is_active": false,
"number_of_children": 3,
"age": 46,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6d266742ce6ced11c",
"is_active": true,
"number_of_children": 1,
"age": 26,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c625cd7cef5e2c4989",
"is_active": false,
"number_of_children": 2,
"age": 28,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6032c83f84c0cef7b",
"is_active": false,
"number_of_children": 4,
"age": 45,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6f8c22f918090634f",
"is_active": false,
"number_of_children": 1,
"age": 49,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c69bcf623ceae91be5",
"is_active": false,
"number_of_children": 2,
"age": 18,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c635aefbf812f08cea",
"is_active": false,
"number_of_children": 1,
"age": 27,
"eye_color": "purple",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6e40a806bf850063a",
"is_active": true,
"number_of_children": 2,
"age": 59,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6593deddf9cdc70ec",
"is_active": false,
"number_of_children": 2,
"age": 56,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6b73136466cc6ebe9",
"is_active": true,
"number_of_children": 4,
"age": 49,
"eye_color": "purple",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6f8ec5462005779ae",
"is_active": true,
"number_of_children": 2,
"age": 31,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6679c2d76c4e7047e",
"is_active": true,
"number_of_children": 2,
"age": 56,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6da63130d511abf26",
"is_active": false,
"number_of_children": 3,
"age": 23,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c648c72e2d0135dc5b",
"is_active": true,
"number_of_children": 2,
"age": 16,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6d8391b4541f69791",
"is_active": false,
"number_of_children": 2,
"age": 62,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6904730d577c3beb4",
"is_active": false,
"number_of_children": 1,
"age": 33,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c69eb29aabd150d1f1",
"is_active": false,
"number_of_children": 4,
"age": 25,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6c71cdc69b57124c2",
"is_active": true,
"number_of_children": 1,
"age": 63,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6b534593cb27c6ecd",
"is_active": false,
"number_of_children": 3,
"age": 31,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c67313759b66b23ebf",
"is_active": true,
"number_of_children": 4,
"age": 19,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c67800f388fa6d58b0",
"is_active": true,
"number_of_children": 4,
"age": 29,
"eye_color": "purple",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c60e5e0bad8286fcbe",
"is_active": true,
"number_of_children": 3,
"age": 64,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6afa8716439280135",
"is_active": false,
"number_of_children": 1,
"age": 18,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c65793d05c1ceaf1d6",
"is_active": true,
"number_of_children": 3,
"age": 35,
"eye_color": "purple",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c672d360fd8853a1ee",
"is_active": true,
"number_of_children": 1,
"age": 45,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c63631300199a961c6",
"is_active": true,
"number_of_children": 2,
"age": 39,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6b69986c9badc5afc",
"is_active": true,
"number_of_children": 4,
"age": 42,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c60c649b4ee89bc716",
"is_active": false,
"number_of_children": 3,
"age": 43,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6f34d3dc556be10dc",
"is_active": true,
"number_of_children": 0,
"age": 55,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c654d710a9cd85c3ec",
"is_active": false,
"number_of_children": 1,
"age": 25,
"eye_color": "purple",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6233dbebc75492389",
"is_active": false,
"number_of_children": 1,
"age": 62,
"eye_color": "purple",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c69ea4391bd8efb2e1",
"is_active": true,
"number_of_children": 2,
"age": 37,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6b601a813bb562daf",
"is_active": true,
"number_of_children": 3,
"age": 62,
"eye_color": "purple",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c671327a79d6e206d7",
"is_active": false,
"number_of_children": 0,
"age": 48,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6f1a79a1f2db2ab05",
"is_active": true,
"number_of_children": 2,
"age": 65,
"eye_color": "purple",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6965011f738097f73",
"is_active": true,
"number_of_children": 2,
"age": 59,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c60576fccb0fb87363",
"is_active": true,
"number_of_children": 1,
"age": 21,
"eye_color": "purple",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c68b3d50e008d99889",
"is_active": false,
"number_of_children": 2,
"age": 66,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6432dabfa11fd8627",
"is_active": false,
"number_of_children": 1,
"age": 24,
"eye_color": "purple",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c65874bb8b81e8244c",
"is_active": false,
"number_of_children": 2,
"age": 58,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6e26433fc108d57e0",
"is_active": true,
"number_of_children": 3,
"age": 47,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6a5dd5f7989eec332",
"is_active": false,
"number_of_children": 2,
"age": 54,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c668bdccbe25440473",
"is_active": true,
"number_of_children": 1,
"age": 20,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6eaa359431618e58f",
"is_active": false,
"number_of_children": 1,
"age": 60,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c670935b2a0b683480",
"is_active": true,
"number_of_children": 0,
"age": 51,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c61fad2176413f334b",
"is_active": true,
"number_of_children": 3,
"age": 31,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6c3855d417fb9efca",
"is_active": false,
"number_of_children": 0,
"age": 68,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6489ef564f0d07ff8",
"is_active": true,
"number_of_children": 1,
"age": 23,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c62646561929edbb17",
"is_active": false,
"number_of_children": 3,
"age": 55,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c621a0f900267f1765",
"is_active": false,
"number_of_children": 3,
"age": 46,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6a3beab51eb38c046",
"is_active": false,
"number_of_children": 3,
"age": 63,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6e1714f6c253a616e",
"is_active": true,
"number_of_children": 0,
"age": 40,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c63e6c571958fea02a",
"is_active": true,
"number_of_children": 3,
"age": 65,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6ff91ba748f8c33d0",
"is_active": true,
"number_of_children": 4,
"age": 36,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c69fc521e43bd487e0",
"is_active": false,
"number_of_children": 3,
"age": 54,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6bc1bf96cc4bb6491",
"is_active": false,
"number_of_children": 1,
"age": 36,
"eye_color": "purple",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6bb4e5b1dc6dd236b",
"is_active": true,
"number_of_children": 3,
"age": 33,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6db71359c29b30b18",
"is_active": false,
"number_of_children": 4,
"age": 56,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c61430bb3be9433057",
"is_active": true,
"number_of_children": 1,
"age": 33,
"eye_color": "purple",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c673e291560d09c6bf",
"is_active": true,
"number_of_children": 1,
"age": 62,
"eye_color": "purple",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6bfecd0789a7658df",
"is_active": true,
"number_of_children": 0,
"age": 29,
"eye_color": "purple",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c64b7a7644fa19f042",
"is_active": false,
"number_of_children": 3,
"age": 46,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c62abebc235f795f2e",
"is_active": false,
"number_of_children": 1,
"age": 34,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c60ed816480ee3f8c8",
"is_active": true,
"number_of_children": 4,
"age": 27,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c692c9bb06b728a9fa",
"is_active": true,
"number_of_children": 4,
"age": 67,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c625a91b4f68a5d7ce",
"is_active": true,
"number_of_children": 2,
"age": 25,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6c7da8996786d5444",
"is_active": false,
"number_of_children": 1,
"age": 35,
"eye_color": "purple",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c64bbf6522f7b1602c",
"is_active": false,
"number_of_children": 0,
"age": 36,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c602898cfe7ef255a2",
"is_active": false,
"number_of_children": 0,
"age": 41,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c67b8a5e8623ee392c",
"is_active": true,
"number_of_children": 3,
"age": 28,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6062fdb22c40b28dc",
"is_active": false,
"number_of_children": 0,
"age": 30,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c60d82561cb8d444f5",
"is_active": false,
"number_of_children": 1,
"age": 65,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6d9f46e5ec6171d49",
"is_active": false,
"number_of_children": 1,
"age": 45,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c61695ea205f338128",
"is_active": true,
"number_of_children": 3,
"age": 53,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c64ae82a6593bec7b3",
"is_active": true,
"number_of_children": 4,
"age": 56,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c665a48df1a90dd8bd",
"is_active": false,
"number_of_children": 0,
"age": 58,
"eye_color": "purple",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c60dd491c3ff3eef78",
"is_active": false,
"number_of_children": 0,
"age": 47,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6fa6239445031df74",
"is_active": false,
"number_of_children": 2,
"age": 42,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6884d73908acc747b",
"is_active": false,
"number_of_children": 0,
"age": 62,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6fde62b4564b59e70",
"is_active": true,
"number_of_children": 2,
"age": 60,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6b15a3747a590b7c6",
"is_active": true,
"number_of_children": 1,
"age": 48,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c692c092cc59044cac",
"is_active": true,
"number_of_children": 1,
"age": 56,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6b485e09f21fb6383",
"is_active": false,
"number_of_children": 1,
"age": 26,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6c21280805c9104bd",
"is_active": false,
"number_of_children": 0,
"age": 61,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
}
]
"""
import json
fake = json.loads(fake) | tests/fake_data.py |
# Data generated from http://www.json-generator.com/
# Using the following template
# [
# '{{repeat(100, 200)}}',
# {
# id: '{{objectId()}}',
# is_active: '{{bool()}}',
# number_of_children: '{{integer(0, 4)}}',
# age: '{{integer(15, 68)}}',
# eye_color: '{{random("blue", "brown", "green", "purple")}}',
# name: '{{firstName()}} {{surname()}}',
# gender: '{{gender()}}',
# has_beard: '{{bool()}}',
# email: '{{email()}}'
# }
# ]
fake = """
[
{
"id": "56c4e39a3e05a86e9f759ba8",
"is_active": true,
"number_of_children": 0,
"age": 35,
"eye_color": "brown",
"name": "Bernard",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"own_bookshop": true,
"company": {
"name": "blackbooks"
}
},
{
"id": "<KEY>",
"is_active": true,
"number_of_children": 0,
"age": 34,
"eye_color": "brown",
"name": "Manny",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"own_bookshop": false,
"company": {
"name": "blackbooks"
}
},
{
"id": "56c4e39a1f9b6f64db8a1b98",
"is_active": true,
"number_of_children": 0,
"age": 35,
"eye_color": "brown",
"name": "Fran",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"own_bookshop": false,
"company": {
"name": "blackbooks"
}
},
{
"id": "56c4f0c6e0a44d8855b26f96",
"is_active": true,
"number_of_children": 2,
"age": 40,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c65e2525167191a8db",
"is_active": true,
"number_of_children": 3,
"age": 47,
"eye_color": "purple",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6988994ceae9f57b7",
"is_active": false,
"number_of_children": 4,
"age": 26,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c62e5c88d563287b16",
"is_active": true,
"number_of_children": 0,
"age": 67,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6365282fb25d9e3bf",
"is_active": true,
"number_of_children": 2,
"age": 26,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6eba85a9ae63865bd",
"is_active": false,
"number_of_children": 2,
"age": 64,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c688f42d99f2015609",
"is_active": false,
"number_of_children": 0,
"age": 66,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6ed871a305f1d622a",
"is_active": true,
"number_of_children": 1,
"age": 20,
"eye_color": "purple",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c664d7cc87ed898157",
"is_active": true,
"number_of_children": 0,
"age": 68,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6627986bbc7be0358",
"is_active": true,
"number_of_children": 3,
"age": 18,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6f30623616b3788e5",
"is_active": true,
"number_of_children": 3,
"age": 31,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6f4121c82fc2df602",
"is_active": true,
"number_of_children": 1,
"age": 62,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6fa36e0f4ad5c9a8d",
"is_active": true,
"number_of_children": 1,
"age": 24,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6344d8fd84f4c66ee",
"is_active": true,
"number_of_children": 0,
"age": 64,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6ecd27f4a011162f4",
"is_active": true,
"number_of_children": 0,
"age": 67,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6358cd5b6a35c8867",
"is_active": false,
"number_of_children": 3,
"age": 57,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c60e3828978a71b245",
"is_active": true,
"number_of_children": 0,
"age": 46,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c696d5c2455312e4a0",
"is_active": false,
"number_of_children": 1,
"age": 34,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c655159e61a08cd2ee",
"is_active": true,
"number_of_children": 1,
"age": 42,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6db2eaf5cb46d62f9",
"is_active": false,
"number_of_children": 3,
"age": 65,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6808e6f717c1a0664",
"is_active": false,
"number_of_children": 1,
"age": 53,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6f8fd86a497c0872e",
"is_active": true,
"number_of_children": 2,
"age": 61,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6d2857317585a7295",
"is_active": false,
"number_of_children": 1,
"age": 17,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c63476b6c242dc4dca",
"is_active": true,
"number_of_children": 2,
"age": 42,
"eye_color": "purple",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c621c4b76dc449a29f",
"is_active": true,
"number_of_children": 2,
"age": 60,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c63343e71b0f12af7c",
"is_active": false,
"number_of_children": 3,
"age": 61,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c622ddf2447374df7d",
"is_active": true,
"number_of_children": 0,
"age": 31,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c687523df953184f2d",
"is_active": false,
"number_of_children": 4,
"age": 51,
"eye_color": "purple",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c675b95a772824f13b",
"is_active": true,
"number_of_children": 3,
"age": 32,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c660ffcc71d8248dcf",
"is_active": true,
"number_of_children": 0,
"age": 29,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c647b5a02e24f10878",
"is_active": false,
"number_of_children": 4,
"age": 58,
"eye_color": "purple",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6d9d9f48432451126",
"is_active": true,
"number_of_children": 3,
"age": 56,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6fa934d9b145cbb2e",
"is_active": false,
"number_of_children": 2,
"age": 35,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c673d82a25d5a79706",
"is_active": true,
"number_of_children": 0,
"age": 41,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c66a5a1cf941a6ad3c",
"is_active": true,
"number_of_children": 0,
"age": 66,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c638780e95d7a501f6",
"is_active": false,
"number_of_children": 3,
"age": 46,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6d266742ce6ced11c",
"is_active": true,
"number_of_children": 1,
"age": 26,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c625cd7cef5e2c4989",
"is_active": false,
"number_of_children": 2,
"age": 28,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6032c83f84c0cef7b",
"is_active": false,
"number_of_children": 4,
"age": 45,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6f8c22f918090634f",
"is_active": false,
"number_of_children": 1,
"age": 49,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c69bcf623ceae91be5",
"is_active": false,
"number_of_children": 2,
"age": 18,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c635aefbf812f08cea",
"is_active": false,
"number_of_children": 1,
"age": 27,
"eye_color": "purple",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6e40a806bf850063a",
"is_active": true,
"number_of_children": 2,
"age": 59,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6593deddf9cdc70ec",
"is_active": false,
"number_of_children": 2,
"age": 56,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6b73136466cc6ebe9",
"is_active": true,
"number_of_children": 4,
"age": 49,
"eye_color": "purple",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6f8ec5462005779ae",
"is_active": true,
"number_of_children": 2,
"age": 31,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6679c2d76c4e7047e",
"is_active": true,
"number_of_children": 2,
"age": 56,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6da63130d511abf26",
"is_active": false,
"number_of_children": 3,
"age": 23,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c648c72e2d0135dc5b",
"is_active": true,
"number_of_children": 2,
"age": 16,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6d8391b4541f69791",
"is_active": false,
"number_of_children": 2,
"age": 62,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6904730d577c3beb4",
"is_active": false,
"number_of_children": 1,
"age": 33,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c69eb29aabd150d1f1",
"is_active": false,
"number_of_children": 4,
"age": 25,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6c71cdc69b57124c2",
"is_active": true,
"number_of_children": 1,
"age": 63,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6b534593cb27c6ecd",
"is_active": false,
"number_of_children": 3,
"age": 31,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c67313759b66b23ebf",
"is_active": true,
"number_of_children": 4,
"age": 19,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c67800f388fa6d58b0",
"is_active": true,
"number_of_children": 4,
"age": 29,
"eye_color": "purple",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c60e5e0bad8286fcbe",
"is_active": true,
"number_of_children": 3,
"age": 64,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6afa8716439280135",
"is_active": false,
"number_of_children": 1,
"age": 18,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c65793d05c1ceaf1d6",
"is_active": true,
"number_of_children": 3,
"age": 35,
"eye_color": "purple",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c672d360fd8853a1ee",
"is_active": true,
"number_of_children": 1,
"age": 45,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c63631300199a961c6",
"is_active": true,
"number_of_children": 2,
"age": 39,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6b69986c9badc5afc",
"is_active": true,
"number_of_children": 4,
"age": 42,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c60c649b4ee89bc716",
"is_active": false,
"number_of_children": 3,
"age": 43,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6f34d3dc556be10dc",
"is_active": true,
"number_of_children": 0,
"age": 55,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c654d710a9cd85c3ec",
"is_active": false,
"number_of_children": 1,
"age": 25,
"eye_color": "purple",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6233dbebc75492389",
"is_active": false,
"number_of_children": 1,
"age": 62,
"eye_color": "purple",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c69ea4391bd8efb2e1",
"is_active": true,
"number_of_children": 2,
"age": 37,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6b601a813bb562daf",
"is_active": true,
"number_of_children": 3,
"age": 62,
"eye_color": "purple",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c671327a79d6e206d7",
"is_active": false,
"number_of_children": 0,
"age": 48,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6f1a79a1f2db2ab05",
"is_active": true,
"number_of_children": 2,
"age": 65,
"eye_color": "purple",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6965011f738097f73",
"is_active": true,
"number_of_children": 2,
"age": 59,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c60576fccb0fb87363",
"is_active": true,
"number_of_children": 1,
"age": 21,
"eye_color": "purple",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c68b3d50e008d99889",
"is_active": false,
"number_of_children": 2,
"age": 66,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6432dabfa11fd8627",
"is_active": false,
"number_of_children": 1,
"age": 24,
"eye_color": "purple",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c65874bb8b81e8244c",
"is_active": false,
"number_of_children": 2,
"age": 58,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6e26433fc108d57e0",
"is_active": true,
"number_of_children": 3,
"age": 47,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6a5dd5f7989eec332",
"is_active": false,
"number_of_children": 2,
"age": 54,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c668bdccbe25440473",
"is_active": true,
"number_of_children": 1,
"age": 20,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6eaa359431618e58f",
"is_active": false,
"number_of_children": 1,
"age": 60,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c670935b2a0b683480",
"is_active": true,
"number_of_children": 0,
"age": 51,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c61fad2176413f334b",
"is_active": true,
"number_of_children": 3,
"age": 31,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6c3855d417fb9efca",
"is_active": false,
"number_of_children": 0,
"age": 68,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6489ef564f0d07ff8",
"is_active": true,
"number_of_children": 1,
"age": 23,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c62646561929edbb17",
"is_active": false,
"number_of_children": 3,
"age": 55,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c621a0f900267f1765",
"is_active": false,
"number_of_children": 3,
"age": 46,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6a3beab51eb38c046",
"is_active": false,
"number_of_children": 3,
"age": 63,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6e1714f6c253a616e",
"is_active": true,
"number_of_children": 0,
"age": 40,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c63e6c571958fea02a",
"is_active": true,
"number_of_children": 3,
"age": 65,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6ff91ba748f8c33d0",
"is_active": true,
"number_of_children": 4,
"age": 36,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c69fc521e43bd487e0",
"is_active": false,
"number_of_children": 3,
"age": 54,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6bc1bf96cc4bb6491",
"is_active": false,
"number_of_children": 1,
"age": 36,
"eye_color": "purple",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6bb4e5b1dc6dd236b",
"is_active": true,
"number_of_children": 3,
"age": 33,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6db71359c29b30b18",
"is_active": false,
"number_of_children": 4,
"age": 56,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c61430bb3be9433057",
"is_active": true,
"number_of_children": 1,
"age": 33,
"eye_color": "purple",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c673e291560d09c6bf",
"is_active": true,
"number_of_children": 1,
"age": 62,
"eye_color": "purple",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6bfecd0789a7658df",
"is_active": true,
"number_of_children": 0,
"age": 29,
"eye_color": "purple",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c64b7a7644fa19f042",
"is_active": false,
"number_of_children": 3,
"age": 46,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c62abebc235f795f2e",
"is_active": false,
"number_of_children": 1,
"age": 34,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c60ed816480ee3f8c8",
"is_active": true,
"number_of_children": 4,
"age": 27,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c692c9bb06b728a9fa",
"is_active": true,
"number_of_children": 4,
"age": 67,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c625a91b4f68a5d7ce",
"is_active": true,
"number_of_children": 2,
"age": 25,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6c7da8996786d5444",
"is_active": false,
"number_of_children": 1,
"age": 35,
"eye_color": "purple",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c64bbf6522f7b1602c",
"is_active": false,
"number_of_children": 0,
"age": 36,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c602898cfe7ef255a2",
"is_active": false,
"number_of_children": 0,
"age": 41,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c67b8a5e8623ee392c",
"is_active": true,
"number_of_children": 3,
"age": 28,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6062fdb22c40b28dc",
"is_active": false,
"number_of_children": 0,
"age": 30,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c60d82561cb8d444f5",
"is_active": false,
"number_of_children": 1,
"age": 65,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6d9f46e5ec6171d49",
"is_active": false,
"number_of_children": 1,
"age": 45,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c61695ea205f338128",
"is_active": true,
"number_of_children": 3,
"age": 53,
"eye_color": "brown",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c64ae82a6593bec7b3",
"is_active": true,
"number_of_children": 4,
"age": 56,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c665a48df1a90dd8bd",
"is_active": false,
"number_of_children": 0,
"age": 58,
"eye_color": "purple",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c60dd491c3ff3eef78",
"is_active": false,
"number_of_children": 0,
"age": 47,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6fa6239445031df74",
"is_active": false,
"number_of_children": 2,
"age": 42,
"eye_color": "blue",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6884d73908acc747b",
"is_active": false,
"number_of_children": 0,
"age": 62,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6fde62b4564b59e70",
"is_active": true,
"number_of_children": 2,
"age": 60,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6b15a3747a590b7c6",
"is_active": true,
"number_of_children": 1,
"age": 48,
"eye_color": "blue",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c692c092cc59044cac",
"is_active": true,
"number_of_children": 1,
"age": 56,
"eye_color": "brown",
"name": "<NAME>",
"gender": "female",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "greendale"
}
},
{
"id": "56c4f0c6b485e09f21fb6383",
"is_active": false,
"number_of_children": 1,
"age": 26,
"eye_color": "green",
"name": "<NAME>",
"gender": "male",
"has_beard": false,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
},
{
"id": "56c4f0c6c21280805c9104bd",
"is_active": false,
"number_of_children": 0,
"age": 61,
"eye_color": "green",
"name": "<NAME>",
"gender": "female",
"has_beard": true,
"email": "<EMAIL>",
"company": {
"name": "house of congress"
}
}
]
"""
import json
fake = json.loads(fake) | 0.341473 | 0.360011 |
import os
import tempfile
import shutil
import subprocess
import argparse
OPT_KONTAIN = "/opt/kontain"
OPT_KONTAIN_BIN = f"{OPT_KONTAIN}/bin"
KONTAIN_GCC = f"{OPT_KONTAIN_BIN}/kontain-gcc"
KM = f"{OPT_KONTAIN_BIN}/km"
INSTALL_URL = "https://raw.githubusercontent.com/kontainapp/km/master/km-releases/kontain-install.sh"
DOCKER_CONFIG_DIR = "/etc/docker"
DOCKER_CONFIG_FILE = f"{DOCKER_CONFIG_DIR}/daemon.json"
def run_kontainer():
"""
Add krun to runtimes docker recognizes, start docker and run a container in krun runtime
"""
# If we are missing libraries or the libs are the wrong version, let's discover that here.
# With docker involved it is harder to know what failed.
subprocess.run([ f"{OPT_KONTAIN_BIN}/krun", "--help" ], check=True)
subprocess.run([ "sudo", "mkdir", "-p", DOCKER_CONFIG_DIR ], check=True)
subprocess.run([ "sudo", "cp", "assets/daemon.json", DOCKER_CONFIG_FILE ], check=True)
subprocess.run([ "sudo", "systemctl", "enable", "docker.service" ], check=True)
subprocess.run([ "sudo", "systemctl", "reload-or-restart", "docker.service" ], check=True)
subprocess.run([ "docker", "pull", "kontainapp/runenv-python" ], check=True)
# This runs python in the kontainer with the simple program following "-c"
# It should return something like this in stdout:
# "posix.uname_result(sysname='Linux', nodename='420613c03875', release='5.12.6-300.fc34.x86_64.kontain.KVM', version='#1 SMP Sat May 22 20:42:55 UTC 2021', machine='x86_64')"
result = subprocess.run([ "docker", "run", "--runtime", "krun", "kontainapp/runenv-python", "-c", "import os; print(os.uname())" ],
capture_output=True, text=True, check=True)
print(result.stdout);
if "kontain'," not in result.stdout:
raise ValueError("Kontainer returned unexpected output")
def main():
""" main method """
parser = argparse.ArgumentParser()
parser.add_argument("--version", help="version of km to be tested")
parser.add_argument("--token", help="access token to KM repo", required=True)
args = parser.parse_args()
# Clean up the /opt/kontain so we have a clean test run
subprocess.run(["rm", "-rf", f"{OPT_KONTAIN}/*"], check=False)
# Download and install
# GITHUB_RELEASE_TOKEN is required to get access to private repos. The
# token is the Github Personal Access Token (PAT)
# token = os.environ.get("GITHUB_RELEASE_TOKEN")
if {args.token} is None:
raise ValueError("--token is not set, cannot access private KM repo")
install_cmd = f"wget --header \"Authorization: token {args.token}\" {INSTALL_URL} -O - -q | bash"
if args.version is not None and args.version != "":
install_cmd += f" -s {args.version}"
os.system(install_cmd)
# See what we got in the tarball.
subprocess.run([
"ls",
"-l",
OPT_KONTAIN_BIN,
], check=True);
# Test: compile helloworld with kontain-gcc
work_dir = tempfile.mkdtemp()
shutil.copytree("assets", os.path.join(work_dir, "assets"))
subprocess.run([
KONTAIN_GCC,
os.path.join(work_dir, "assets", "helloworld.c"),
"-o",
"helloworld",
], cwd=work_dir, check=True)
subprocess.run([
KM,
"helloworld",
], cwd=work_dir, check=True)
# Run a container with krun
run_kontainer()
# Clean up
shutil.rmtree(work_dir)
main() | tools/release/tests/test_release_local/test_release_local.py | import os
import tempfile
import shutil
import subprocess
import argparse
OPT_KONTAIN = "/opt/kontain"
OPT_KONTAIN_BIN = f"{OPT_KONTAIN}/bin"
KONTAIN_GCC = f"{OPT_KONTAIN_BIN}/kontain-gcc"
KM = f"{OPT_KONTAIN_BIN}/km"
INSTALL_URL = "https://raw.githubusercontent.com/kontainapp/km/master/km-releases/kontain-install.sh"
DOCKER_CONFIG_DIR = "/etc/docker"
DOCKER_CONFIG_FILE = f"{DOCKER_CONFIG_DIR}/daemon.json"
def run_kontainer():
"""
Add krun to runtimes docker recognizes, start docker and run a container in krun runtime
"""
# If we are missing libraries or the libs are the wrong version, let's discover that here.
# With docker involved it is harder to know what failed.
subprocess.run([ f"{OPT_KONTAIN_BIN}/krun", "--help" ], check=True)
subprocess.run([ "sudo", "mkdir", "-p", DOCKER_CONFIG_DIR ], check=True)
subprocess.run([ "sudo", "cp", "assets/daemon.json", DOCKER_CONFIG_FILE ], check=True)
subprocess.run([ "sudo", "systemctl", "enable", "docker.service" ], check=True)
subprocess.run([ "sudo", "systemctl", "reload-or-restart", "docker.service" ], check=True)
subprocess.run([ "docker", "pull", "kontainapp/runenv-python" ], check=True)
# This runs python in the kontainer with the simple program following "-c"
# It should return something like this in stdout:
# "posix.uname_result(sysname='Linux', nodename='420613c03875', release='5.12.6-300.fc34.x86_64.kontain.KVM', version='#1 SMP Sat May 22 20:42:55 UTC 2021', machine='x86_64')"
result = subprocess.run([ "docker", "run", "--runtime", "krun", "kontainapp/runenv-python", "-c", "import os; print(os.uname())" ],
capture_output=True, text=True, check=True)
print(result.stdout);
if "kontain'," not in result.stdout:
raise ValueError("Kontainer returned unexpected output")
def main():
""" main method """
parser = argparse.ArgumentParser()
parser.add_argument("--version", help="version of km to be tested")
parser.add_argument("--token", help="access token to KM repo", required=True)
args = parser.parse_args()
# Clean up the /opt/kontain so we have a clean test run
subprocess.run(["rm", "-rf", f"{OPT_KONTAIN}/*"], check=False)
# Download and install
# GITHUB_RELEASE_TOKEN is required to get access to private repos. The
# token is the Github Personal Access Token (PAT)
# token = os.environ.get("GITHUB_RELEASE_TOKEN")
if {args.token} is None:
raise ValueError("--token is not set, cannot access private KM repo")
install_cmd = f"wget --header \"Authorization: token {args.token}\" {INSTALL_URL} -O - -q | bash"
if args.version is not None and args.version != "":
install_cmd += f" -s {args.version}"
os.system(install_cmd)
# See what we got in the tarball.
subprocess.run([
"ls",
"-l",
OPT_KONTAIN_BIN,
], check=True);
# Test: compile helloworld with kontain-gcc
work_dir = tempfile.mkdtemp()
shutil.copytree("assets", os.path.join(work_dir, "assets"))
subprocess.run([
KONTAIN_GCC,
os.path.join(work_dir, "assets", "helloworld.c"),
"-o",
"helloworld",
], cwd=work_dir, check=True)
subprocess.run([
KM,
"helloworld",
], cwd=work_dir, check=True)
# Run a container with krun
run_kontainer()
# Clean up
shutil.rmtree(work_dir)
main() | 0.243013 | 0.068289 |
import sys
import numpy as np
import pytest
pytest.importorskip("pyxir")
import pyxir.contrib.target.DPUCADX8G
import pyxir.contrib.target.DPUCZDX8G
import tvm
from tvm import relay
from tvm.relay import transform
from tvm.relay.op.contrib.vitis_ai import annotation
from tvm.relay.build_module import bind_params_by_name
from tvm.contrib.target import vitis_ai
from .infrastructure import skip_test, verify_codegen
def set_func_attr(func, compile_name, symbol_name):
func = func.with_attr("Primitive", tvm.tir.IntImm("int32", 1))
func = func.with_attr("Inline", tvm.tir.IntImm("int32", 1))
func = func.with_attr("Compiler", compile_name)
func = func.with_attr("global_symbol", symbol_name)
return func
def test_conv2d():
"""Test conv2d operator for Vitis-AI DPUCADX8G and DPUCZDX8G-zcu104 targets"""
x = relay.var("x", shape=(1, 3, 224, 224))
w = relay.const(np.zeros((16, 3, 3, 3), dtype="float32"))
y = relay.nn.conv2d(x, w, strides=[2, 2], padding=[1, 1, 1, 1], kernel_size=[3, 3])
func = relay.Function([x], y)
params = {}
params["x"] = np.zeros((1, 3, 224, 224), dtype="float32")
params["w"] = np.random.rand(16, 3, 3, 3).astype("float32")
mod = tvm.IRModule()
mod["main"] = func
verify_codegen(mod, params=params, dpu_target="DPUCADX8G")
verify_codegen(mod, params=params, dpu_target="DPUCZDX8G-zcu104")
def test_depthwise_conv():
"""Test depthwise_conv operator for Vitis-AI DPUCZDX8G-zcu104 target"""
dtype = "float32"
ishape = (1, 32, 14, 14)
wshape = (32, 1, 3, 3)
data = relay.var("data", shape=(ishape), dtype=dtype)
weights = relay.var("weights", shape=(wshape), dtype=dtype)
depthwise_conv2d = relay.nn.conv2d(data, weights, kernel_size=(3, 3), padding=(1, 1), groups=32)
func = relay.Function([data, weights], depthwise_conv2d)
params = {}
params["weights"] = np.random.randn(32, 1, 3, 3).astype(dtype)
params["data"] = np.random.randn(1, 32, 14, 14).astype(dtype)
mod = tvm.IRModule()
mod["main"] = func
verify_codegen(mod, params=params, dpu_target="DPUCZDX8G-zcu104")
def test_bias_add():
"""Test bias_add operator for Vitis-AI DPUCADX8G and DPUCZDX8G-zcu104 targets"""
dtype = "float32"
ishape = (1, 32, 14, 14)
data = relay.var("data", shape=(ishape), dtype=dtype)
bias = relay.var("bias", relay.TensorType((32,), dtype))
out = relay.nn.bias_add(data, bias)
func = relay.Function([data, bias], out)
params = {}
params["bias"] = np.random.randn(32).astype(dtype)
params["data"] = np.random.randn(1, 32, 14, 14).astype(dtype)
mod = tvm.IRModule()
mod["main"] = func
verify_codegen(mod, params=params, dpu_target="DPUCADX8G")
verify_codegen(mod, params=params, dpu_target="DPUCZDX8G-zcu104")
def test_batchnorm():
"""Test batchnorm operator for Vitis-AI DPUCADX8G and DPUCZDX8G-zcu104 targets"""
data = relay.var("data", shape=(1, 16, 112, 112))
bn_gamma = relay.var("bn_gamma", relay.TensorType((16,), "float32"))
bn_beta = relay.var("bn_beta", relay.TensorType((16,), "float32"))
bn_mmean = relay.var("bn_mean", relay.TensorType((16,), "float32"))
bn_mvar = relay.var("bn_var", relay.TensorType((16,), "float32"))
bn_output = relay.nn.batch_norm(data, bn_gamma, bn_beta, bn_mmean, bn_mvar)
func = relay.Function([data, bn_gamma, bn_beta, bn_mmean, bn_mvar], bn_output[0])
params = {}
params["data"] = np.zeros((1, 16, 112, 112), dtype="float32")
params["bn_gamma"] = np.random.rand(16).astype("float32")
params["bn_beta"] = np.random.rand(16).astype("float32")
params["bn_mean"] = np.random.rand(16).astype("float32")
params["bn_var"] = np.random.rand(16).astype("float32")
mod = tvm.IRModule()
mod["main"] = func
verify_codegen(mod, params=params, dpu_target="DPUCADX8G")
verify_codegen(mod, params=params, dpu_target="DPUCZDX8G-zcu104")
def test_add():
"""Test add operator for Vitis-AI DPUCADX8G and DPUCZDX8G-zcu104 targets"""
shape = (10, 10)
x = relay.var("x", shape=shape)
y = x + x
func = relay.Function([x], y)
mod = tvm.IRModule()
mod["main"] = func
verify_codegen(mod, dpu_target="DPUCADX8G")
verify_codegen(mod, dpu_target="DPUCZDX8G-zcu104")
def test_global_avg_pool2d():
"""Test global_avg_pool2d operator for Vitis-AI DPUCADX8G and DPUCZDX8G-zcu104 targets"""
shape = (10, 10, 7, 7)
x = relay.var("x", shape=shape)
y = relay.nn.global_avg_pool2d(x)
func = relay.Function([x], y)
mod = tvm.IRModule()
mod["main"] = func
verify_codegen(mod, dpu_target="DPUCADX8G")
verify_codegen(mod, dpu_target="DPUCZDX8G-zcu104")
def test_avg_pool2d():
"""Test avg_pool2d for operator Vitis-AI DPUCADX8G and DPUCZDX8G-zcu104 targets"""
shape = (10, 10, 10, 10)
x = relay.var("x", shape=shape)
y = relay.nn.avg_pool2d(x, pool_size=(3, 3))
func = relay.Function([x], y)
mod = tvm.IRModule()
mod["main"] = func
verify_codegen(mod, dpu_target="DPUCADX8G")
verify_codegen(mod, dpu_target="DPUCZDX8G-zcu104")
def test_max_pool2d():
"""Test max_pool2d for operator Vitis-AI DPUCADX8G and DPUCZDX8G-zcu104 targets"""
shape = (64, 512, 10, 10)
x = relay.var("x", shape=shape)
y = relay.nn.max_pool2d(x, pool_size=(3, 3))
func = relay.Function([x], y)
mod = tvm.IRModule()
mod["main"] = func
verify_codegen(mod, dpu_target="DPUCADX8G")
verify_codegen(mod, dpu_target="DPUCZDX8G-zcu104")
def test_global_max_pool2d():
"""Test global_maxpool2d operator for Vitis-AI DPUCADX8G and DPUCZDX8G-zcu104 targets"""
shape = (1, 512, 7, 7)
x = relay.var("x", shape=shape)
y = relay.nn.global_max_pool2d(x)
func = relay.Function([x], y)
mod = tvm.IRModule()
mod["main"] = func
verify_codegen(mod, dpu_target="DPUCADX8G")
verify_codegen(mod, dpu_target="DPUCZDX8G-zcu104")
def test_upsampling():
"""Test upsampling operator for Vitis-AI DPUCADX8G and DPUCZDX8G-zcu104 targets"""
shape = (64, 512, 10, 10)
x = relay.var("x", shape=shape)
y = relay.nn.upsampling(x, scale_h=2, scale_w=2)
func = relay.Function([x], y)
mod = tvm.IRModule()
mod["main"] = func
verify_codegen(mod, dpu_target="DPUCADX8G")
verify_codegen(mod, dpu_target="DPUCZDX8G-zcu104")
def test_conv2d_transpose():
"""Test conv2d_transpose operator for Vitis-AI DPUCADX8G and DPUCZDX8G-zcu104 targets"""
dshape = (1, 3, 18, 18)
kshape = (3, 10, 3, 3)
x = relay.var("x", shape=dshape)
w = relay.const(np.zeros(kshape, dtype="float32"))
y = relay.nn.conv2d_transpose(
x, w, channels=10, kernel_size=(3, 3), strides=(1, 1), padding=(1, 1)
)
func = relay.Function([x], y)
params = {}
dtype = "float32"
params["x"] = np.random.uniform(size=dshape).astype(dtype)
params["w"] = np.random.uniform(size=kshape).astype(dtype)
mod = tvm.IRModule()
mod["main"] = func
verify_codegen(mod, params=params, dpu_target="DPUCADX8G")
verify_codegen(mod, params=params, dpu_target="DPUCZDX8G-zcu104")
def test_annotate():
"""Test annotation operator for Vitis-AI DPUCADX8G and DPUCZDX8G-zcu104 targets"""
def partition(dpu_target):
data = relay.var("data", relay.TensorType((1, 3, 224, 224), "float32"))
weight = relay.var("weight", relay.TensorType((16, 3, 3, 3), "float32"))
bn_gamma = relay.var("bn_gamma", relay.TensorType((16,), "float32"))
bn_beta = relay.var("bn_beta", relay.TensorType((16,), "float32"))
bn_mmean = relay.var("bn_mean", relay.TensorType((16,), "float32"))
bn_mvar = relay.var("bn_var", relay.TensorType((16,), "float32"))
conv = relay.nn.conv2d(
data=data, weight=weight, kernel_size=(3, 3), channels=16, padding=(1, 1)
)
bn_output = relay.nn.batch_norm(conv, bn_gamma, bn_beta, bn_mmean, bn_mvar)
func = relay.Function(
[data, weight, bn_gamma, bn_beta, bn_mmean, bn_mvar], bn_output.astuple()
)
mod = tvm.IRModule()
mod["main"] = func
params = {}
params["weight"] = np.random.rand(16, 3, 3, 3).astype("float32")
params["bn_gamma"] = np.random.rand(16).astype("float32")
params["bn_beta"] = np.random.rand(16).astype("float32")
params["bn_mean"] = np.random.rand(16).astype("float32")
params["bn_var"] = np.random.rand(16).astype("float32")
mod = annotation(mod, params, dpu_target)
opt_pass = tvm.transform.Sequential(
[
transform.MergeCompilerRegions(),
transform.PartitionGraph(),
]
)
with tvm.transform.PassContext(opt_level=3):
mod = opt_pass(mod)
return mod
def expected():
# function variables for conv2d
data0 = relay.var("data0", relay.TensorType((1, 3, 224, 224), "float32"))
weight0 = relay.var("weight0", relay.TensorType((16, 3, 3, 3), "float32"))
conv = relay.nn.conv2d(
data=data0, weight=weight0, kernel_size=(3, 3), channels=16, padding=(1, 1)
)
# function variables for batch_norm
bn_gamma0 = relay.var("bn_gamma0", relay.TensorType((16,), "float32"))
bn_beta0 = relay.var("bn_beta0", relay.TensorType((16,), "float32"))
bn_mmean0 = relay.var("bn_mean0", relay.TensorType((16,), "float32"))
bn_mvar0 = relay.var("bn_var0", relay.TensorType((16,), "float32"))
bn = relay.nn.batch_norm(conv, bn_gamma0, bn_beta0, bn_mmean0, bn_mvar0)
func0 = relay.Function(
[data0, weight0, bn_gamma0, bn_beta0, bn_mmean0, bn_mvar0], bn.astuple()
)
func0 = set_func_attr(func0, "vitis_ai", "tvmgen_default_vitis_ai_main_0")
gv0 = relay.GlobalVar("tvmgen_default_vitis_ai_main_0")
mod = tvm.IRModule()
mod[gv0] = func0
mod = relay.transform.InferType()(mod)
# main function
data = relay.var("data", relay.TensorType((1, 3, 224, 224), "float32"))
weight = relay.var("weight", relay.TensorType((16, 3, 3, 3), "float32"))
bn_gamma = relay.var("bn_gamma", relay.TensorType((16,), "float32"))
bn_beta = relay.var("bn_beta", relay.TensorType((16,), "float32"))
bn_mmean = relay.var("bn_mean", relay.TensorType((16,), "float32"))
bn_mvar = relay.var("bn_var", relay.TensorType((16,), "float32"))
call0 = gv0(data, weight, bn_gamma, bn_beta, bn_mmean, bn_mvar)
mod["main"] = relay.Function([data, weight, bn_gamma, bn_beta, bn_mmean, bn_mvar], call0)
mod = relay.transform.InferType()(mod)
return mod
partitioned_dpuczdx8g_zcu104 = partition("DPUCZDX8G-zcu104")
partitioned_dpucadx8g = partition("DPUCADX8G")
ref_mod = expected()
assert tvm.ir.structural_equal(partitioned_dpuczdx8g_zcu104, ref_mod, map_free_vars=True)
assert tvm.ir.structural_equal(partitioned_dpucadx8g, ref_mod, map_free_vars=True)
if __name__ == "__main__":
if sys.platform == "win32":
print("Skip test on Windows for now")
sys.exit(0)
test_conv2d()
test_depthwise_conv()
test_bias_add()
test_add()
test_max_pool2d()
test_global_max_pool2d()
test_batchnorm()
test_global_avg_pool2d()
test_avg_pool2d()
test_upsampling()
test_conv2d_transpose()
test_annotate() | tests/python/contrib/test_vitis_ai/test_vitis_ai_codegen.py | import sys
import numpy as np
import pytest
pytest.importorskip("pyxir")
import pyxir.contrib.target.DPUCADX8G
import pyxir.contrib.target.DPUCZDX8G
import tvm
from tvm import relay
from tvm.relay import transform
from tvm.relay.op.contrib.vitis_ai import annotation
from tvm.relay.build_module import bind_params_by_name
from tvm.contrib.target import vitis_ai
from .infrastructure import skip_test, verify_codegen
def set_func_attr(func, compile_name, symbol_name):
func = func.with_attr("Primitive", tvm.tir.IntImm("int32", 1))
func = func.with_attr("Inline", tvm.tir.IntImm("int32", 1))
func = func.with_attr("Compiler", compile_name)
func = func.with_attr("global_symbol", symbol_name)
return func
def test_conv2d():
"""Test conv2d operator for Vitis-AI DPUCADX8G and DPUCZDX8G-zcu104 targets"""
x = relay.var("x", shape=(1, 3, 224, 224))
w = relay.const(np.zeros((16, 3, 3, 3), dtype="float32"))
y = relay.nn.conv2d(x, w, strides=[2, 2], padding=[1, 1, 1, 1], kernel_size=[3, 3])
func = relay.Function([x], y)
params = {}
params["x"] = np.zeros((1, 3, 224, 224), dtype="float32")
params["w"] = np.random.rand(16, 3, 3, 3).astype("float32")
mod = tvm.IRModule()
mod["main"] = func
verify_codegen(mod, params=params, dpu_target="DPUCADX8G")
verify_codegen(mod, params=params, dpu_target="DPUCZDX8G-zcu104")
def test_depthwise_conv():
"""Test depthwise_conv operator for Vitis-AI DPUCZDX8G-zcu104 target"""
dtype = "float32"
ishape = (1, 32, 14, 14)
wshape = (32, 1, 3, 3)
data = relay.var("data", shape=(ishape), dtype=dtype)
weights = relay.var("weights", shape=(wshape), dtype=dtype)
depthwise_conv2d = relay.nn.conv2d(data, weights, kernel_size=(3, 3), padding=(1, 1), groups=32)
func = relay.Function([data, weights], depthwise_conv2d)
params = {}
params["weights"] = np.random.randn(32, 1, 3, 3).astype(dtype)
params["data"] = np.random.randn(1, 32, 14, 14).astype(dtype)
mod = tvm.IRModule()
mod["main"] = func
verify_codegen(mod, params=params, dpu_target="DPUCZDX8G-zcu104")
def test_bias_add():
"""Test bias_add operator for Vitis-AI DPUCADX8G and DPUCZDX8G-zcu104 targets"""
dtype = "float32"
ishape = (1, 32, 14, 14)
data = relay.var("data", shape=(ishape), dtype=dtype)
bias = relay.var("bias", relay.TensorType((32,), dtype))
out = relay.nn.bias_add(data, bias)
func = relay.Function([data, bias], out)
params = {}
params["bias"] = np.random.randn(32).astype(dtype)
params["data"] = np.random.randn(1, 32, 14, 14).astype(dtype)
mod = tvm.IRModule()
mod["main"] = func
verify_codegen(mod, params=params, dpu_target="DPUCADX8G")
verify_codegen(mod, params=params, dpu_target="DPUCZDX8G-zcu104")
def test_batchnorm():
"""Test batchnorm operator for Vitis-AI DPUCADX8G and DPUCZDX8G-zcu104 targets"""
data = relay.var("data", shape=(1, 16, 112, 112))
bn_gamma = relay.var("bn_gamma", relay.TensorType((16,), "float32"))
bn_beta = relay.var("bn_beta", relay.TensorType((16,), "float32"))
bn_mmean = relay.var("bn_mean", relay.TensorType((16,), "float32"))
bn_mvar = relay.var("bn_var", relay.TensorType((16,), "float32"))
bn_output = relay.nn.batch_norm(data, bn_gamma, bn_beta, bn_mmean, bn_mvar)
func = relay.Function([data, bn_gamma, bn_beta, bn_mmean, bn_mvar], bn_output[0])
params = {}
params["data"] = np.zeros((1, 16, 112, 112), dtype="float32")
params["bn_gamma"] = np.random.rand(16).astype("float32")
params["bn_beta"] = np.random.rand(16).astype("float32")
params["bn_mean"] = np.random.rand(16).astype("float32")
params["bn_var"] = np.random.rand(16).astype("float32")
mod = tvm.IRModule()
mod["main"] = func
verify_codegen(mod, params=params, dpu_target="DPUCADX8G")
verify_codegen(mod, params=params, dpu_target="DPUCZDX8G-zcu104")
def test_add():
"""Test add operator for Vitis-AI DPUCADX8G and DPUCZDX8G-zcu104 targets"""
shape = (10, 10)
x = relay.var("x", shape=shape)
y = x + x
func = relay.Function([x], y)
mod = tvm.IRModule()
mod["main"] = func
verify_codegen(mod, dpu_target="DPUCADX8G")
verify_codegen(mod, dpu_target="DPUCZDX8G-zcu104")
def test_global_avg_pool2d():
"""Test global_avg_pool2d operator for Vitis-AI DPUCADX8G and DPUCZDX8G-zcu104 targets"""
shape = (10, 10, 7, 7)
x = relay.var("x", shape=shape)
y = relay.nn.global_avg_pool2d(x)
func = relay.Function([x], y)
mod = tvm.IRModule()
mod["main"] = func
verify_codegen(mod, dpu_target="DPUCADX8G")
verify_codegen(mod, dpu_target="DPUCZDX8G-zcu104")
def test_avg_pool2d():
"""Test avg_pool2d for operator Vitis-AI DPUCADX8G and DPUCZDX8G-zcu104 targets"""
shape = (10, 10, 10, 10)
x = relay.var("x", shape=shape)
y = relay.nn.avg_pool2d(x, pool_size=(3, 3))
func = relay.Function([x], y)
mod = tvm.IRModule()
mod["main"] = func
verify_codegen(mod, dpu_target="DPUCADX8G")
verify_codegen(mod, dpu_target="DPUCZDX8G-zcu104")
def test_max_pool2d():
"""Test max_pool2d for operator Vitis-AI DPUCADX8G and DPUCZDX8G-zcu104 targets"""
shape = (64, 512, 10, 10)
x = relay.var("x", shape=shape)
y = relay.nn.max_pool2d(x, pool_size=(3, 3))
func = relay.Function([x], y)
mod = tvm.IRModule()
mod["main"] = func
verify_codegen(mod, dpu_target="DPUCADX8G")
verify_codegen(mod, dpu_target="DPUCZDX8G-zcu104")
def test_global_max_pool2d():
"""Test global_maxpool2d operator for Vitis-AI DPUCADX8G and DPUCZDX8G-zcu104 targets"""
shape = (1, 512, 7, 7)
x = relay.var("x", shape=shape)
y = relay.nn.global_max_pool2d(x)
func = relay.Function([x], y)
mod = tvm.IRModule()
mod["main"] = func
verify_codegen(mod, dpu_target="DPUCADX8G")
verify_codegen(mod, dpu_target="DPUCZDX8G-zcu104")
def test_upsampling():
"""Test upsampling operator for Vitis-AI DPUCADX8G and DPUCZDX8G-zcu104 targets"""
shape = (64, 512, 10, 10)
x = relay.var("x", shape=shape)
y = relay.nn.upsampling(x, scale_h=2, scale_w=2)
func = relay.Function([x], y)
mod = tvm.IRModule()
mod["main"] = func
verify_codegen(mod, dpu_target="DPUCADX8G")
verify_codegen(mod, dpu_target="DPUCZDX8G-zcu104")
def test_conv2d_transpose():
"""Test conv2d_transpose operator for Vitis-AI DPUCADX8G and DPUCZDX8G-zcu104 targets"""
dshape = (1, 3, 18, 18)
kshape = (3, 10, 3, 3)
x = relay.var("x", shape=dshape)
w = relay.const(np.zeros(kshape, dtype="float32"))
y = relay.nn.conv2d_transpose(
x, w, channels=10, kernel_size=(3, 3), strides=(1, 1), padding=(1, 1)
)
func = relay.Function([x], y)
params = {}
dtype = "float32"
params["x"] = np.random.uniform(size=dshape).astype(dtype)
params["w"] = np.random.uniform(size=kshape).astype(dtype)
mod = tvm.IRModule()
mod["main"] = func
verify_codegen(mod, params=params, dpu_target="DPUCADX8G")
verify_codegen(mod, params=params, dpu_target="DPUCZDX8G-zcu104")
def test_annotate():
"""Test annotation operator for Vitis-AI DPUCADX8G and DPUCZDX8G-zcu104 targets"""
def partition(dpu_target):
data = relay.var("data", relay.TensorType((1, 3, 224, 224), "float32"))
weight = relay.var("weight", relay.TensorType((16, 3, 3, 3), "float32"))
bn_gamma = relay.var("bn_gamma", relay.TensorType((16,), "float32"))
bn_beta = relay.var("bn_beta", relay.TensorType((16,), "float32"))
bn_mmean = relay.var("bn_mean", relay.TensorType((16,), "float32"))
bn_mvar = relay.var("bn_var", relay.TensorType((16,), "float32"))
conv = relay.nn.conv2d(
data=data, weight=weight, kernel_size=(3, 3), channels=16, padding=(1, 1)
)
bn_output = relay.nn.batch_norm(conv, bn_gamma, bn_beta, bn_mmean, bn_mvar)
func = relay.Function(
[data, weight, bn_gamma, bn_beta, bn_mmean, bn_mvar], bn_output.astuple()
)
mod = tvm.IRModule()
mod["main"] = func
params = {}
params["weight"] = np.random.rand(16, 3, 3, 3).astype("float32")
params["bn_gamma"] = np.random.rand(16).astype("float32")
params["bn_beta"] = np.random.rand(16).astype("float32")
params["bn_mean"] = np.random.rand(16).astype("float32")
params["bn_var"] = np.random.rand(16).astype("float32")
mod = annotation(mod, params, dpu_target)
opt_pass = tvm.transform.Sequential(
[
transform.MergeCompilerRegions(),
transform.PartitionGraph(),
]
)
with tvm.transform.PassContext(opt_level=3):
mod = opt_pass(mod)
return mod
def expected():
# function variables for conv2d
data0 = relay.var("data0", relay.TensorType((1, 3, 224, 224), "float32"))
weight0 = relay.var("weight0", relay.TensorType((16, 3, 3, 3), "float32"))
conv = relay.nn.conv2d(
data=data0, weight=weight0, kernel_size=(3, 3), channels=16, padding=(1, 1)
)
# function variables for batch_norm
bn_gamma0 = relay.var("bn_gamma0", relay.TensorType((16,), "float32"))
bn_beta0 = relay.var("bn_beta0", relay.TensorType((16,), "float32"))
bn_mmean0 = relay.var("bn_mean0", relay.TensorType((16,), "float32"))
bn_mvar0 = relay.var("bn_var0", relay.TensorType((16,), "float32"))
bn = relay.nn.batch_norm(conv, bn_gamma0, bn_beta0, bn_mmean0, bn_mvar0)
func0 = relay.Function(
[data0, weight0, bn_gamma0, bn_beta0, bn_mmean0, bn_mvar0], bn.astuple()
)
func0 = set_func_attr(func0, "vitis_ai", "tvmgen_default_vitis_ai_main_0")
gv0 = relay.GlobalVar("tvmgen_default_vitis_ai_main_0")
mod = tvm.IRModule()
mod[gv0] = func0
mod = relay.transform.InferType()(mod)
# main function
data = relay.var("data", relay.TensorType((1, 3, 224, 224), "float32"))
weight = relay.var("weight", relay.TensorType((16, 3, 3, 3), "float32"))
bn_gamma = relay.var("bn_gamma", relay.TensorType((16,), "float32"))
bn_beta = relay.var("bn_beta", relay.TensorType((16,), "float32"))
bn_mmean = relay.var("bn_mean", relay.TensorType((16,), "float32"))
bn_mvar = relay.var("bn_var", relay.TensorType((16,), "float32"))
call0 = gv0(data, weight, bn_gamma, bn_beta, bn_mmean, bn_mvar)
mod["main"] = relay.Function([data, weight, bn_gamma, bn_beta, bn_mmean, bn_mvar], call0)
mod = relay.transform.InferType()(mod)
return mod
partitioned_dpuczdx8g_zcu104 = partition("DPUCZDX8G-zcu104")
partitioned_dpucadx8g = partition("DPUCADX8G")
ref_mod = expected()
assert tvm.ir.structural_equal(partitioned_dpuczdx8g_zcu104, ref_mod, map_free_vars=True)
assert tvm.ir.structural_equal(partitioned_dpucadx8g, ref_mod, map_free_vars=True)
if __name__ == "__main__":
if sys.platform == "win32":
print("Skip test on Windows for now")
sys.exit(0)
test_conv2d()
test_depthwise_conv()
test_bias_add()
test_add()
test_max_pool2d()
test_global_max_pool2d()
test_batchnorm()
test_global_avg_pool2d()
test_avg_pool2d()
test_upsampling()
test_conv2d_transpose()
test_annotate() | 0.547706 | 0.33162 |
import logging
import sqlite3
from sqlite3 import Error
import time
from datetime import datetime
from statistics import variance, stdev
logging.basicConfig(filename='analyze_projects.log', filemode='a',
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
#logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by the db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
except Error as e:
print(e)
return conn
def get_commits(conn,project=True):
'''
returns number of commits per project or model in a list
'''
cur = conn.cursor()
if project:
table = 'GitHub_Projects_Commit_Info'
else:
table = 'GitHub_Model_Commit_Info'
cur.execute("Select total_number_of_commits from "+table+" order by total_number_of_commits")
rows = cur.fetchall()
return [r[0] for r in rows]
def get_merge_commits_projects(conn):
cur = conn.cursor()
cur.execute("select cast(Number_of_merge_commits as float)/cast(Total_number_of_commits as float)*100 per from github_projects_commit_info order by per")
rows = cur.fetchall()
return [r[0] for r in rows]
def calculate_quartiles(list_of_vals):
'''
args:
list_of_vals : sorted list
'''
list_of_vals.sort()
sum_list = sum(list_of_vals)
n = len(list_of_vals)
mean = sum_list/n
if n % 2 == 0:
median1 = list_of_vals[n // 2]
median2 = list_of_vals[n // 2 - 1]
median = (median1 + median2) / 2
else:
median = list_of_vals[n // 2]
return str(round(list_of_vals[0],2))+"\t&"+str(round(list_of_vals[n-1],2))+"\t&"+str(round(mean,2))+\
"\t&"+str(round(median,2))+"\t&"+str(round(stdev(list_of_vals),2))
def get_number_of_authors(conn, project = True):
'''
returns number of authors per project or model in a list
'''
cur = conn.cursor()
if project:
table = 'GitHub_Projects_Commit_Info'
else:
table = 'GitHub_Model_Commit_Info'
cur.execute("Select number_of_authors from " + table + " order by number_of_authors")
rows = cur.fetchall()
return [r[0] for r in rows]
def get_lifetime(conn, project = True):
'''
returns absolute lifetime of project or model(days) in a list
'''
cur = conn.cursor()
if project:
sql ="select LifeTime_in_days from github_projects_commit_info order by LifeTime_in_days"
else:
sql = "select Abs_lifeTime_in_days from GitHub_Model_Commit_Info order by Abs_lifeTime_in_days"
cur.execute(sql)
rows = cur.fetchall()
return [r[0] for r in rows]
def get_commit_per_day(conn):
cur = conn.cursor()
sql = "select Commit_per_day from GitHub_Projects_Commit_Info order by Commit_per_day"
cur.execute(sql)
rows = cur.fetchall()
return [r[0] for r in rows]
def convert_rows_to_set(rows):
res = set()
for r in rows:
res.add(r[0])
return res
def get_model_author_per(conn):
model_author_per = []
cur = conn.cursor()
project_ids_sql = "select id from github_projects_commit_info"
cur.execute(project_ids_sql)
rows = cur.fetchall()
project_ids = [r[0] for r in rows]
for id in project_ids:
model_author_sql = "select author_email from Model_commits where id = " + str(id)
cur.execute(model_author_sql)
model_author_set = convert_rows_to_set(cur.fetchall())
project_author_sql = "select author_email from Project_commits where id = " + str(id)
cur.execute(project_author_sql)
project_author_set = convert_rows_to_set(cur.fetchall())
model_author_per.append(len(model_author_set)/len(project_author_set)*100)
#print(model_commits_per)
return sorted(model_author_per)
def get_model_commits_per(conn):
model_commits_per = []
cur = conn.cursor()
project_ids_sql = "select id from github_projects_commit_info"
cur.execute(project_ids_sql)
rows = cur.fetchall()
project_ids = [r[0] for r in rows]
for id in project_ids:
model_hash_sql = "select hash from Model_commits where id = " + str(id)
cur.execute(model_hash_sql)
model_hash_set = convert_rows_to_set(cur.fetchall())
project_hash_sql = "select hash from Project_commits where id = " + str(id)
cur.execute(project_hash_sql)
project_hash_set = convert_rows_to_set(cur.fetchall())
if len(model_hash_set) == 0 :
print("jere")
model_commits_per.append(len(model_hash_set)/len(project_hash_set)*100)
#print(model_commits_per)
return sorted(model_commits_per)
def get_model_updates(conn):
model_update = "select updates from(select id,model_name, sum(modifications) updates from Model_commits group by id, model_name order by updates)"
cur = conn.cursor()
cur.execute(model_update)
rows = cur.fetchall()
return [r[0] for r in rows]
def get_model_authors(conn):
model_author = "select Number_of_authors from GitHub_Model_Commit_Info order by Number_of_authors"
cur = conn.cursor()
cur.execute(model_author)
rows = cur.fetchall()
return [r[0] for r in rows]
def get_model_abs_lifetime(conn):
model_lt = "select abs_lifetime_in_days from GitHub_Model_Commit_Info order by abs_lifetime_in_days"
cur = conn.cursor()
cur.execute(model_lt)
rows = cur.fetchall()
return [r[0] for r in rows]
def get_model_abs_lifetime_meta(conn):
model_lt = "select last_modified, created_date from model_meta where last_modified !='' and created_date !=''"
cur = conn.cursor()
cur.execute(model_lt)
rows = cur.fetchall()
last_m = []
creat_m = []
res = []
for r in rows:
print(r[0])
print(r[1])
try:
ans = datetime.strptime(r[0], '%c') -datetime.strptime(r[1], '%c')
except Exception as e:
continue
ans_in_days = ans.days + ans.seconds/86400
assert(ans_in_days>=0)
print(ans_in_days)
res.append(ans_in_days)
return res
def get_all_vals_from_table(conn,gsql , msql):
cur = conn.cursor()
cur.execute(gsql)
rows = cur.fetchall()
g_results = [r[0] for r in rows]
cur.execute(msql)
rows = cur.fetchall()
m_results = [r[0] for r in rows]
res = g_results + m_results
res.sort()
return res
def get_code_generating_models_project(conn):
mat_embedded = "select count(distinct FILE_ID) from Matc_code_gen where System_Target_File in ('ert.tlc','ert_shrlib.tlc') and Solver_Type =='Fixed-step' "
git_embedded = 'select count(distinct FILE_ID) from github_code_gen where System_Target_File in ("ert.tlc","ert_shrlib.tlc") and Solver_Type =="Fixed-step" '
embedded = get_all_vals_from_table(conn,git_embedded,mat_embedded)
print(" Project with models configured to generate code using Embedded Coder ")
print("GitHub : {}".format(embedded[0] ))
print("MATLAB Central: {}".format(embedded[1] ))
mat_others = ' select count(distinct FILE_ID) from matc_code_gen where System_Target_File not in ("ert.tlc","ert_shrlib.tlc") and (System_Target_File in ("rsim.tlc","rtwsun.tlc") or Solver_Type =="Fixed-step") '
git_others = ' select count(distinct FILE_ID) from github_code_gen where System_Target_File not in ("ert.tlc","ert_shrlib.tlc") and (System_Target_File in ("rsim.tlc","rtwsun.tlc") or Solver_Type =="Fixed-step") '
others = get_all_vals_from_table(conn,git_others,mat_others)
print(" Project with models configured to generate code using toolbox other than Embedded Coder ")
print("GitHub : {}".format(others[0] ))
print("MATLAB Central: {}".format(others[1] ))
mat_total = ' select count(distinct FILE_ID) from Matc_code_gen where System_Target_File in ("rsim.tlc","rtwsun.tlc") or ( System_Target_File not in ("rsim.tlc","rtwsun.tlc") and Solver_Type =="Fixed-step")'
git_total = ' select count(distinct FILE_ID) from github_code_gen where System_Target_File in ("rsim.tlc","rtwsun.tlc") or ( System_Target_File not in ("rsim.tlc","rtwsun.tlc") and Solver_Type =="Fixed-step")'
total = get_all_vals_from_table(conn,git_total,mat_total)
print(" Project with models configured to generate code using Embedded Coder ")
print("GitHub : {}".format(total[0] ))
print("MATLAB Central: {}".format(total[1] ))
def get_model_rel_lifetime(conn):
model_rl = "select relative_lifetime*100 from GitHub_Model_Commit_Info order by relative_lifetime"
cur = conn.cursor()
cur.execute(model_rl)
rows = cur.fetchall()
return [r[0] for r in rows]
def get_commits_info(conn):
lifetime_over50 = "select total_number_of_commits from GitHub_Projects_Commit_Info where total_number_of_commits<50"
cur = conn.cursor()
cur.execute(lifetime_over50)
rows = cur.fetchall()
lifetime = [r[0] for r in rows]
print("Percentage of projects less than 50 : {}".format(len(lifetime)/200))
#sql = "select cast(Model_commits as float)/cast(Total_number_of_commits as float)*100 per from github_projects_commit_info order by per"
def main():
start = time.time()
database = ""
# create a database connection
conn = create_connection(database)
print("Project level metrics")
print("Project Metric & Min. & Max. & Mean& Median & Std. Dev")
print(get_commits(conn)[109])
print(get_commits(conn)[110])
print(len(get_commits(conn)))
no_of_commits = calculate_quartiles(get_commits(conn))
print("Number of commits &"+ no_of_commits)
merge_percent = calculate_quartiles(get_merge_commits_projects(conn))
print("Merge commits in %&" + merge_percent)
number_of_authors = calculate_quartiles(get_number_of_authors(conn))
print("Number of authors&" + number_of_authors)
lifetime_in_days = calculate_quartiles(get_lifetime(conn))
print("Lifetime in days&" + lifetime_in_days)
commit_per_day= calculate_quartiles(get_commit_per_day(conn))
print("Commit per day&" + commit_per_day)
model_commits_per = calculate_quartiles(get_model_commits_per(conn))
print("Model commits in %&"+ model_commits_per)
model_author_per = calculate_quartiles(get_model_author_per(conn))
print("Model authors in %&"+ model_author_per)
# Model Metrics
print("Model level metrics")
model_update = calculate_quartiles(get_model_updates(conn))
print("Number of updates &"+model_update)
model_update = calculate_quartiles(get_model_authors(conn))
print("Number of authors &" + model_update)
model_lifetime = calculate_quartiles(get_model_abs_lifetime(conn))
print("Abs lifetime in days &" + model_lifetime)
model_rel_lifetime = calculate_quartiles(get_model_rel_lifetime(conn))
print("Relative lifetime in % &" + model_rel_lifetime)
get_commits_info(conn)
print('====================')
get_code_generating_models_project(conn)
if __name__ == '__main__':
main() | analyze_data/analyzeProjects.py | import logging
import sqlite3
from sqlite3 import Error
import time
from datetime import datetime
from statistics import variance, stdev
logging.basicConfig(filename='analyze_projects.log', filemode='a',
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
#logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by the db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
except Error as e:
print(e)
return conn
def get_commits(conn,project=True):
'''
returns number of commits per project or model in a list
'''
cur = conn.cursor()
if project:
table = 'GitHub_Projects_Commit_Info'
else:
table = 'GitHub_Model_Commit_Info'
cur.execute("Select total_number_of_commits from "+table+" order by total_number_of_commits")
rows = cur.fetchall()
return [r[0] for r in rows]
def get_merge_commits_projects(conn):
cur = conn.cursor()
cur.execute("select cast(Number_of_merge_commits as float)/cast(Total_number_of_commits as float)*100 per from github_projects_commit_info order by per")
rows = cur.fetchall()
return [r[0] for r in rows]
def calculate_quartiles(list_of_vals):
'''
args:
list_of_vals : sorted list
'''
list_of_vals.sort()
sum_list = sum(list_of_vals)
n = len(list_of_vals)
mean = sum_list/n
if n % 2 == 0:
median1 = list_of_vals[n // 2]
median2 = list_of_vals[n // 2 - 1]
median = (median1 + median2) / 2
else:
median = list_of_vals[n // 2]
return str(round(list_of_vals[0],2))+"\t&"+str(round(list_of_vals[n-1],2))+"\t&"+str(round(mean,2))+\
"\t&"+str(round(median,2))+"\t&"+str(round(stdev(list_of_vals),2))
def get_number_of_authors(conn, project = True):
'''
returns number of authors per project or model in a list
'''
cur = conn.cursor()
if project:
table = 'GitHub_Projects_Commit_Info'
else:
table = 'GitHub_Model_Commit_Info'
cur.execute("Select number_of_authors from " + table + " order by number_of_authors")
rows = cur.fetchall()
return [r[0] for r in rows]
def get_lifetime(conn, project = True):
'''
returns absolute lifetime of project or model(days) in a list
'''
cur = conn.cursor()
if project:
sql ="select LifeTime_in_days from github_projects_commit_info order by LifeTime_in_days"
else:
sql = "select Abs_lifeTime_in_days from GitHub_Model_Commit_Info order by Abs_lifeTime_in_days"
cur.execute(sql)
rows = cur.fetchall()
return [r[0] for r in rows]
def get_commit_per_day(conn):
cur = conn.cursor()
sql = "select Commit_per_day from GitHub_Projects_Commit_Info order by Commit_per_day"
cur.execute(sql)
rows = cur.fetchall()
return [r[0] for r in rows]
def convert_rows_to_set(rows):
res = set()
for r in rows:
res.add(r[0])
return res
def get_model_author_per(conn):
model_author_per = []
cur = conn.cursor()
project_ids_sql = "select id from github_projects_commit_info"
cur.execute(project_ids_sql)
rows = cur.fetchall()
project_ids = [r[0] for r in rows]
for id in project_ids:
model_author_sql = "select author_email from Model_commits where id = " + str(id)
cur.execute(model_author_sql)
model_author_set = convert_rows_to_set(cur.fetchall())
project_author_sql = "select author_email from Project_commits where id = " + str(id)
cur.execute(project_author_sql)
project_author_set = convert_rows_to_set(cur.fetchall())
model_author_per.append(len(model_author_set)/len(project_author_set)*100)
#print(model_commits_per)
return sorted(model_author_per)
def get_model_commits_per(conn):
model_commits_per = []
cur = conn.cursor()
project_ids_sql = "select id from github_projects_commit_info"
cur.execute(project_ids_sql)
rows = cur.fetchall()
project_ids = [r[0] for r in rows]
for id in project_ids:
model_hash_sql = "select hash from Model_commits where id = " + str(id)
cur.execute(model_hash_sql)
model_hash_set = convert_rows_to_set(cur.fetchall())
project_hash_sql = "select hash from Project_commits where id = " + str(id)
cur.execute(project_hash_sql)
project_hash_set = convert_rows_to_set(cur.fetchall())
if len(model_hash_set) == 0 :
print("jere")
model_commits_per.append(len(model_hash_set)/len(project_hash_set)*100)
#print(model_commits_per)
return sorted(model_commits_per)
def get_model_updates(conn):
model_update = "select updates from(select id,model_name, sum(modifications) updates from Model_commits group by id, model_name order by updates)"
cur = conn.cursor()
cur.execute(model_update)
rows = cur.fetchall()
return [r[0] for r in rows]
def get_model_authors(conn):
model_author = "select Number_of_authors from GitHub_Model_Commit_Info order by Number_of_authors"
cur = conn.cursor()
cur.execute(model_author)
rows = cur.fetchall()
return [r[0] for r in rows]
def get_model_abs_lifetime(conn):
model_lt = "select abs_lifetime_in_days from GitHub_Model_Commit_Info order by abs_lifetime_in_days"
cur = conn.cursor()
cur.execute(model_lt)
rows = cur.fetchall()
return [r[0] for r in rows]
def get_model_abs_lifetime_meta(conn):
model_lt = "select last_modified, created_date from model_meta where last_modified !='' and created_date !=''"
cur = conn.cursor()
cur.execute(model_lt)
rows = cur.fetchall()
last_m = []
creat_m = []
res = []
for r in rows:
print(r[0])
print(r[1])
try:
ans = datetime.strptime(r[0], '%c') -datetime.strptime(r[1], '%c')
except Exception as e:
continue
ans_in_days = ans.days + ans.seconds/86400
assert(ans_in_days>=0)
print(ans_in_days)
res.append(ans_in_days)
return res
def get_all_vals_from_table(conn,gsql , msql):
cur = conn.cursor()
cur.execute(gsql)
rows = cur.fetchall()
g_results = [r[0] for r in rows]
cur.execute(msql)
rows = cur.fetchall()
m_results = [r[0] for r in rows]
res = g_results + m_results
res.sort()
return res
def get_code_generating_models_project(conn):
mat_embedded = "select count(distinct FILE_ID) from Matc_code_gen where System_Target_File in ('ert.tlc','ert_shrlib.tlc') and Solver_Type =='Fixed-step' "
git_embedded = 'select count(distinct FILE_ID) from github_code_gen where System_Target_File in ("ert.tlc","ert_shrlib.tlc") and Solver_Type =="Fixed-step" '
embedded = get_all_vals_from_table(conn,git_embedded,mat_embedded)
print(" Project with models configured to generate code using Embedded Coder ")
print("GitHub : {}".format(embedded[0] ))
print("MATLAB Central: {}".format(embedded[1] ))
mat_others = ' select count(distinct FILE_ID) from matc_code_gen where System_Target_File not in ("ert.tlc","ert_shrlib.tlc") and (System_Target_File in ("rsim.tlc","rtwsun.tlc") or Solver_Type =="Fixed-step") '
git_others = ' select count(distinct FILE_ID) from github_code_gen where System_Target_File not in ("ert.tlc","ert_shrlib.tlc") and (System_Target_File in ("rsim.tlc","rtwsun.tlc") or Solver_Type =="Fixed-step") '
others = get_all_vals_from_table(conn,git_others,mat_others)
print(" Project with models configured to generate code using toolbox other than Embedded Coder ")
print("GitHub : {}".format(others[0] ))
print("MATLAB Central: {}".format(others[1] ))
mat_total = ' select count(distinct FILE_ID) from Matc_code_gen where System_Target_File in ("rsim.tlc","rtwsun.tlc") or ( System_Target_File not in ("rsim.tlc","rtwsun.tlc") and Solver_Type =="Fixed-step")'
git_total = ' select count(distinct FILE_ID) from github_code_gen where System_Target_File in ("rsim.tlc","rtwsun.tlc") or ( System_Target_File not in ("rsim.tlc","rtwsun.tlc") and Solver_Type =="Fixed-step")'
total = get_all_vals_from_table(conn,git_total,mat_total)
print(" Project with models configured to generate code using Embedded Coder ")
print("GitHub : {}".format(total[0] ))
print("MATLAB Central: {}".format(total[1] ))
def get_model_rel_lifetime(conn):
model_rl = "select relative_lifetime*100 from GitHub_Model_Commit_Info order by relative_lifetime"
cur = conn.cursor()
cur.execute(model_rl)
rows = cur.fetchall()
return [r[0] for r in rows]
def get_commits_info(conn):
lifetime_over50 = "select total_number_of_commits from GitHub_Projects_Commit_Info where total_number_of_commits<50"
cur = conn.cursor()
cur.execute(lifetime_over50)
rows = cur.fetchall()
lifetime = [r[0] for r in rows]
print("Percentage of projects less than 50 : {}".format(len(lifetime)/200))
#sql = "select cast(Model_commits as float)/cast(Total_number_of_commits as float)*100 per from github_projects_commit_info order by per"
def main():
start = time.time()
database = ""
# create a database connection
conn = create_connection(database)
print("Project level metrics")
print("Project Metric & Min. & Max. & Mean& Median & Std. Dev")
print(get_commits(conn)[109])
print(get_commits(conn)[110])
print(len(get_commits(conn)))
no_of_commits = calculate_quartiles(get_commits(conn))
print("Number of commits &"+ no_of_commits)
merge_percent = calculate_quartiles(get_merge_commits_projects(conn))
print("Merge commits in %&" + merge_percent)
number_of_authors = calculate_quartiles(get_number_of_authors(conn))
print("Number of authors&" + number_of_authors)
lifetime_in_days = calculate_quartiles(get_lifetime(conn))
print("Lifetime in days&" + lifetime_in_days)
commit_per_day= calculate_quartiles(get_commit_per_day(conn))
print("Commit per day&" + commit_per_day)
model_commits_per = calculate_quartiles(get_model_commits_per(conn))
print("Model commits in %&"+ model_commits_per)
model_author_per = calculate_quartiles(get_model_author_per(conn))
print("Model authors in %&"+ model_author_per)
# Model Metrics
print("Model level metrics")
model_update = calculate_quartiles(get_model_updates(conn))
print("Number of updates &"+model_update)
model_update = calculate_quartiles(get_model_authors(conn))
print("Number of authors &" + model_update)
model_lifetime = calculate_quartiles(get_model_abs_lifetime(conn))
print("Abs lifetime in days &" + model_lifetime)
model_rel_lifetime = calculate_quartiles(get_model_rel_lifetime(conn))
print("Relative lifetime in % &" + model_rel_lifetime)
get_commits_info(conn)
print('====================')
get_code_generating_models_project(conn)
if __name__ == '__main__':
main() | 0.288268 | 0.21036 |
import requests
import boto3
from progressbar import progressbar
from datetime import datetime
import csv, os, argparse
from py_dataset import dataset
from subprocess import run, Popen, PIPE
def purr_eprints(connect_string, sql_script_name):
"""purr_eprints - contact the MySQL on a remote EPrints server and
retrieve the assigned resolver URL and eprint record URL.
EPrints' SQL:
"SELECT id_number, eprintid FROM eprint WHERE eprint_status = 'archive'"
Write out "purr_${hostname}.csv" with resolver URL and EPrints URL.
Example SQL script "purr_${hostname}.csv"
--
-- Run this script from remote system using the --batch option to generate
-- a Tab delimited version of output. Use tr to convert tab to comma.
--
USE ${DB_NAME_HERE};
SELECT id_number,
CONCAT('${URL_PREFIX_HERE','/', eprintid)
FROM eprint WHERE eprint_status = 'archive';
"""
remote_cmd = f"""mysql --batch < '{sql_script_name}' """
cmd = ["ssh", connect_string, remote_cmd]
with Popen(cmd, stdout=PIPE, encoding="utf-8") as proc:
src = proc.stdout.read().replace("\t", ",")
return list(csv.reader(src.splitlines(), delimiter=","))
def get_datacite_dois(client_ids, links):
"""Get DataCite DOIs and URLs for specific client IDs"""
new_links = {}
base_url = "https://api.datacite.org/dois?page[cursor]=1&page[size]=500&client-id="
for client in client_ids:
print("Collecting DOIs for ", client)
url = base_url + client
next_link = url
meta = requests.get(next_link).json()["meta"]
for j in progressbar(range(meta["totalPages"])):
r = requests.get(next_link)
data = r.json()
for doi in data["data"]:
if doi["id"] not in links:
new_links[doi["id"]] = doi["attributes"]["url"]
upper = doi["id"].upper()
if upper not in links:
new_links[upper] = doi["attributes"]["url"]
if "next" in data["links"]:
next_link = data["links"]["next"]
else:
next_link = None
return new_links
def make_s3_record(s3, bucket, resolver, url):
"""Make S3 entry for a redirect"""
s3_object = s3.Object(bucket_name=bucket, key=resolver)
response = s3_object.put(WebsiteRedirectLocation=url, ACL="public-read")
if response["ResponseMetadata"]["HTTPStatusCode"] != 200:
print("Error: ", response)
def links_differ(link1, link2):
"""Return whether two links are different"""
differ = True
if link1 == link2:
differ = False
# Handle when url had training slash
if link1[0:-1] == link2:
differ = False
if link2[0:-1] == link1:
differ = False
return differ
def save_history(existing, url, get):
"""We save the history if anything has changed"""
save = False
if links_differ(url, existing["expected-url"]):
save = True
if get.status_code != existing["code"]:
save = True
if links_differ(get.url, existing["url"]):
save = True
return save
def make_link_history(collection, resolver, url, note):
"""Make an entry in our link history collection"""
now = datetime.today().isoformat()
# Run link check
try:
get = requests.get(f"http://resolver.library.caltech.edu/{resolver}")
except requests.exceptions.ConnectionError:
get = requests.Response()
get.status_code = 404
get.url = ""
if links_differ(get.url, url):
print(f"Mismatch between expected url {url} and actual {get.url}")
if get.status_code != 200:
print(f"URL {url} returns Error status code {get.status_code}")
entry = {
"expected-url": url,
"url": get.url,
"modified": now,
"code": get.status_code,
"note": note,
}
# If existing, push into history
if dataset.has_key(collection, resolver):
existing, err = dataset.read(collection, resolver)
if err != "":
print(err)
exit()
if save_history(existing, url, get):
past_history = existing.pop("history")
past_history.append(existing)
entry["history"] = past_history
if not dataset.update(collection, resolver, entry):
print(dataset.error_message())
exit()
else:
entry["history"] = []
if not dataset.create(collection, resolver, entry):
print(dataset.error_message())
exit()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Manage the CODA URL Resolver")
parser.add_argument(
"-update", action="store_true", help="Update ALL (not just new) resolver links"
)
parser.add_argument(
"-dois", action="store_true", help="Get resolver links from DataCite"
)
parser.add_argument(
"-skip_eprints", action="store_true", help="Get resolver links from DataCite"
)
args = parser.parse_args()
# S3 Setup
session = boto3.Session(profile_name="resolver")
current_region = session.region_name
bucket = "resolver.library.caltech.edu"
s3 = session.resource("s3")
collection = "link_history.ds"
if os.path.isdir(collection) == False:
make_s3_record(s3, bucket, "index.html", "https://libguides.caltech.edu/CODA")
if not dataset.init(collection):
print("Dataset failed to init collection")
exit()
# Get the links that already exist
links = dataset.keys(collection)
if args.update:
# Everything will get updated
links = []
# Get DOI links
if args.dois:
client_ids = [
"tind.caltech",
"caltech.library",
"caltech.ipacdoi",
"caltech.micropub",
]
new_links = get_datacite_dois(client_ids, links)
for l in progressbar(new_links):
print(l)
if l not in links:
make_s3_record(s3, bucket, l, new_links[l])
make_link_history(collection, l, new_links[l], "From DataCite")
eprints = True
if args.skip_eprints:
eprints = False
if eprints:
# Get Eprints links
repos = [
("<EMAIL>", "./purr_caltechconf.sql"),
(
"<EMAIL>",
"./purr_campuspubs.sql",
),
("<EMAIL>", "./purr_calteches.sql"),
("<EMAIL>", "./purr_caltechln.sql"),
("<EMAIL>", "./purr_caltechoh.sql"),
("<EMAIL>", "./purr_authors.sql"),
("<EMAIL>", "./purr_caltechthesis.sql"),
]
for r in repos:
print(r[1])
eprints_links = purr_eprints(r[0], r[1])
for l in eprints_links: # progressbar(eprints_links, redirect_stdout=True):
idv = l[0]
url = l[1]
# Skip header
if idv != "resolver_id":
if idv not in links:
make_s3_record(s3, bucket, idv, url)
make_link_history(collection, idv, url, f"From {r[1]}") | resolver.py | import requests
import boto3
from progressbar import progressbar
from datetime import datetime
import csv, os, argparse
from py_dataset import dataset
from subprocess import run, Popen, PIPE
def purr_eprints(connect_string, sql_script_name):
"""purr_eprints - contact the MySQL on a remote EPrints server and
retrieve the assigned resolver URL and eprint record URL.
EPrints' SQL:
"SELECT id_number, eprintid FROM eprint WHERE eprint_status = 'archive'"
Write out "purr_${hostname}.csv" with resolver URL and EPrints URL.
Example SQL script "purr_${hostname}.csv"
--
-- Run this script from remote system using the --batch option to generate
-- a Tab delimited version of output. Use tr to convert tab to comma.
--
USE ${DB_NAME_HERE};
SELECT id_number,
CONCAT('${URL_PREFIX_HERE','/', eprintid)
FROM eprint WHERE eprint_status = 'archive';
"""
remote_cmd = f"""mysql --batch < '{sql_script_name}' """
cmd = ["ssh", connect_string, remote_cmd]
with Popen(cmd, stdout=PIPE, encoding="utf-8") as proc:
src = proc.stdout.read().replace("\t", ",")
return list(csv.reader(src.splitlines(), delimiter=","))
def get_datacite_dois(client_ids, links):
"""Get DataCite DOIs and URLs for specific client IDs"""
new_links = {}
base_url = "https://api.datacite.org/dois?page[cursor]=1&page[size]=500&client-id="
for client in client_ids:
print("Collecting DOIs for ", client)
url = base_url + client
next_link = url
meta = requests.get(next_link).json()["meta"]
for j in progressbar(range(meta["totalPages"])):
r = requests.get(next_link)
data = r.json()
for doi in data["data"]:
if doi["id"] not in links:
new_links[doi["id"]] = doi["attributes"]["url"]
upper = doi["id"].upper()
if upper not in links:
new_links[upper] = doi["attributes"]["url"]
if "next" in data["links"]:
next_link = data["links"]["next"]
else:
next_link = None
return new_links
def make_s3_record(s3, bucket, resolver, url):
"""Make S3 entry for a redirect"""
s3_object = s3.Object(bucket_name=bucket, key=resolver)
response = s3_object.put(WebsiteRedirectLocation=url, ACL="public-read")
if response["ResponseMetadata"]["HTTPStatusCode"] != 200:
print("Error: ", response)
def links_differ(link1, link2):
"""Return whether two links are different"""
differ = True
if link1 == link2:
differ = False
# Handle when url had training slash
if link1[0:-1] == link2:
differ = False
if link2[0:-1] == link1:
differ = False
return differ
def save_history(existing, url, get):
"""We save the history if anything has changed"""
save = False
if links_differ(url, existing["expected-url"]):
save = True
if get.status_code != existing["code"]:
save = True
if links_differ(get.url, existing["url"]):
save = True
return save
def make_link_history(collection, resolver, url, note):
"""Make an entry in our link history collection"""
now = datetime.today().isoformat()
# Run link check
try:
get = requests.get(f"http://resolver.library.caltech.edu/{resolver}")
except requests.exceptions.ConnectionError:
get = requests.Response()
get.status_code = 404
get.url = ""
if links_differ(get.url, url):
print(f"Mismatch between expected url {url} and actual {get.url}")
if get.status_code != 200:
print(f"URL {url} returns Error status code {get.status_code}")
entry = {
"expected-url": url,
"url": get.url,
"modified": now,
"code": get.status_code,
"note": note,
}
# If existing, push into history
if dataset.has_key(collection, resolver):
existing, err = dataset.read(collection, resolver)
if err != "":
print(err)
exit()
if save_history(existing, url, get):
past_history = existing.pop("history")
past_history.append(existing)
entry["history"] = past_history
if not dataset.update(collection, resolver, entry):
print(dataset.error_message())
exit()
else:
entry["history"] = []
if not dataset.create(collection, resolver, entry):
print(dataset.error_message())
exit()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Manage the CODA URL Resolver")
parser.add_argument(
"-update", action="store_true", help="Update ALL (not just new) resolver links"
)
parser.add_argument(
"-dois", action="store_true", help="Get resolver links from DataCite"
)
parser.add_argument(
"-skip_eprints", action="store_true", help="Get resolver links from DataCite"
)
args = parser.parse_args()
# S3 Setup
session = boto3.Session(profile_name="resolver")
current_region = session.region_name
bucket = "resolver.library.caltech.edu"
s3 = session.resource("s3")
collection = "link_history.ds"
if os.path.isdir(collection) == False:
make_s3_record(s3, bucket, "index.html", "https://libguides.caltech.edu/CODA")
if not dataset.init(collection):
print("Dataset failed to init collection")
exit()
# Get the links that already exist
links = dataset.keys(collection)
if args.update:
# Everything will get updated
links = []
# Get DOI links
if args.dois:
client_ids = [
"tind.caltech",
"caltech.library",
"caltech.ipacdoi",
"caltech.micropub",
]
new_links = get_datacite_dois(client_ids, links)
for l in progressbar(new_links):
print(l)
if l not in links:
make_s3_record(s3, bucket, l, new_links[l])
make_link_history(collection, l, new_links[l], "From DataCite")
eprints = True
if args.skip_eprints:
eprints = False
if eprints:
# Get Eprints links
repos = [
("<EMAIL>", "./purr_caltechconf.sql"),
(
"<EMAIL>",
"./purr_campuspubs.sql",
),
("<EMAIL>", "./purr_calteches.sql"),
("<EMAIL>", "./purr_caltechln.sql"),
("<EMAIL>", "./purr_caltechoh.sql"),
("<EMAIL>", "./purr_authors.sql"),
("<EMAIL>", "./purr_caltechthesis.sql"),
]
for r in repos:
print(r[1])
eprints_links = purr_eprints(r[0], r[1])
for l in eprints_links: # progressbar(eprints_links, redirect_stdout=True):
idv = l[0]
url = l[1]
# Skip header
if idv != "resolver_id":
if idv not in links:
make_s3_record(s3, bucket, idv, url)
make_link_history(collection, idv, url, f"From {r[1]}") | 0.323915 | 0.132711 |
import sys
import click
from team_formation import config
from team_formation.data_helpers import process_canvas_courses, \
process_canvas_group_categories
def course_prompt(canvas):
courses = canvas.get_courses(
enrollment_type='teacher',
enrollment_state='active',
per_page=config.PER_PAGE,
include=['sections', 'total_students']
)
#fetch all courses (unwrap PaginatedList)
courses = [course for course in courses]
course_ids = [course.id for course in courses]
# save courses data
process_canvas_courses(courses)
if len(courses) == 0:
click.echo('No active courses found for token...')
sys.exit()
format_width = len(str(max(course_ids)))
click.echo("Select one of the following courses:")
for course in courses:
click.echo("[{:{width}}]: {} (sections: {}, students: {})".format(
course.id,
course.name,
len(course.sections),
course.total_students,
width=format_width
))
while True:
result = click.prompt("Enter the course id", type=int)
if result in course_ids:
return result
else:
click.echo("Invalid course id")
def group_name_prompt(course, group_category_name):
# prompt for group category if needed
if not group_category_name or not group_category_name.strip():
while True:
result = click.prompt("Enter a new group category name", type=str)
result = result.strip()
if result:
group_category_name = result
break
else:
click.echo("Invalid group name")
# check if group category already exists
group_categories = course.get_group_categories()
process_canvas_group_categories(group_categories)
for group_category in group_categories:
if group_category_name == group_category.name:
if click.confirm("Group category name already in use. Would you like to overwrite it?"):
return (group_category_name, group_category)
else:
click.echo('Try again with a different group category name')
sys.exit()
return (group_category_name, None) | team_formation/prompts.py | import sys
import click
from team_formation import config
from team_formation.data_helpers import process_canvas_courses, \
process_canvas_group_categories
def course_prompt(canvas):
courses = canvas.get_courses(
enrollment_type='teacher',
enrollment_state='active',
per_page=config.PER_PAGE,
include=['sections', 'total_students']
)
#fetch all courses (unwrap PaginatedList)
courses = [course for course in courses]
course_ids = [course.id for course in courses]
# save courses data
process_canvas_courses(courses)
if len(courses) == 0:
click.echo('No active courses found for token...')
sys.exit()
format_width = len(str(max(course_ids)))
click.echo("Select one of the following courses:")
for course in courses:
click.echo("[{:{width}}]: {} (sections: {}, students: {})".format(
course.id,
course.name,
len(course.sections),
course.total_students,
width=format_width
))
while True:
result = click.prompt("Enter the course id", type=int)
if result in course_ids:
return result
else:
click.echo("Invalid course id")
def group_name_prompt(course, group_category_name):
# prompt for group category if needed
if not group_category_name or not group_category_name.strip():
while True:
result = click.prompt("Enter a new group category name", type=str)
result = result.strip()
if result:
group_category_name = result
break
else:
click.echo("Invalid group name")
# check if group category already exists
group_categories = course.get_group_categories()
process_canvas_group_categories(group_categories)
for group_category in group_categories:
if group_category_name == group_category.name:
if click.confirm("Group category name already in use. Would you like to overwrite it?"):
return (group_category_name, group_category)
else:
click.echo('Try again with a different group category name')
sys.exit()
return (group_category_name, None) | 0.176885 | 0.143908 |
import json
from pyspark.ml.feature import StringIndexer
from pyspark.ml.feature import MinMaxScaler
from pyspark.sql.types import IntegerType, DoubleType
from pyspark.sql.functions import col, lit
# keep the file sizes smaller for large distribution experiments
spark.conf.set("spark.sql.files.maxRecordsPerFile", 100000)
sparse_features = ['C' + str(i) for i in range(1, 27)]
dense_features = ['I' + str(i) for i in range(1, 14)]
df = spark.read.csv(path,header=True).cache()
print("Number of examples: ",df.count())
# change datatype of dense features
for col_t in dense_features:
df = df.withColumn(col_t,col(col_t).cast(DoubleType()))
## fill nulls
df = df.fillna('NULL',subset=sparse_features)
df = df.fillna(0.,subset=dense_features)
# compute statistics
## dense features
scaled_max = 1
scaled_min = 0
dense_meta = {}
for col_t in dense_features:
min_t = df.agg({col_t:"min"}).collect()[0][0]
max_t = df.agg({col_t:"max"}).collect()[0][0]
dense_meta[col_t] = [min_t, max_t]
df = df.withColumn(col_t+"_scaled",(col(col_t)-min_t)/(max_t-min_t)*(scaled_max-scaled_min)+scaled_min)
df = df.drop(col_t).withColumnRenamed(col_t+"_scaled",col_t)
## index categoricals
indexers = {}
for col_t in sparse_features:
indexer = StringIndexer(inputCol=col_t, outputCol=col_t+"_indexed")
fitted_indexer = indexer.fit(df)
df = fitted_indexer.transform(df)
indexers[col_t] = fitted_indexer # save indexer for test data
df = df.drop(col_t).withColumnRenamed(col_t+"_indexed",col_t)
df = df.withColumn(col_t,col(col_t).cast(IntegerType()))
# convert label dtype
df = df.withColumn("Label",col("Label").cast(DoubleType()))
# save statistics/meta data locally
all_index = {}
for xk in indexers.keys():
x = indexers[xk]
index2name = dict([y for y in zip(range(len(x.labels)),x.labels)])
name2index = {v: k for k, v in index2name.items()}
all_index[xk] = {'index2name':index2name,
'name2index':name2index}
json.dump(all_index,open("categorical.json",'w'))
json.dump(dense_meta,open("dense-meta.json",'w'))
# save processed training data
df = df.repartition(1000)
df.write.mode("overwrite").csv(write_location,header=True) | deepctr/dist_utils/process_criteo.py | import json
from pyspark.ml.feature import StringIndexer
from pyspark.ml.feature import MinMaxScaler
from pyspark.sql.types import IntegerType, DoubleType
from pyspark.sql.functions import col, lit
# keep the file sizes smaller for large distribution experiments
spark.conf.set("spark.sql.files.maxRecordsPerFile", 100000)
sparse_features = ['C' + str(i) for i in range(1, 27)]
dense_features = ['I' + str(i) for i in range(1, 14)]
df = spark.read.csv(path,header=True).cache()
print("Number of examples: ",df.count())
# change datatype of dense features
for col_t in dense_features:
df = df.withColumn(col_t,col(col_t).cast(DoubleType()))
## fill nulls
df = df.fillna('NULL',subset=sparse_features)
df = df.fillna(0.,subset=dense_features)
# compute statistics
## dense features
scaled_max = 1
scaled_min = 0
dense_meta = {}
for col_t in dense_features:
min_t = df.agg({col_t:"min"}).collect()[0][0]
max_t = df.agg({col_t:"max"}).collect()[0][0]
dense_meta[col_t] = [min_t, max_t]
df = df.withColumn(col_t+"_scaled",(col(col_t)-min_t)/(max_t-min_t)*(scaled_max-scaled_min)+scaled_min)
df = df.drop(col_t).withColumnRenamed(col_t+"_scaled",col_t)
## index categoricals
indexers = {}
for col_t in sparse_features:
indexer = StringIndexer(inputCol=col_t, outputCol=col_t+"_indexed")
fitted_indexer = indexer.fit(df)
df = fitted_indexer.transform(df)
indexers[col_t] = fitted_indexer # save indexer for test data
df = df.drop(col_t).withColumnRenamed(col_t+"_indexed",col_t)
df = df.withColumn(col_t,col(col_t).cast(IntegerType()))
# convert label dtype
df = df.withColumn("Label",col("Label").cast(DoubleType()))
# save statistics/meta data locally
all_index = {}
for xk in indexers.keys():
x = indexers[xk]
index2name = dict([y for y in zip(range(len(x.labels)),x.labels)])
name2index = {v: k for k, v in index2name.items()}
all_index[xk] = {'index2name':index2name,
'name2index':name2index}
json.dump(all_index,open("categorical.json",'w'))
json.dump(dense_meta,open("dense-meta.json",'w'))
# save processed training data
df = df.repartition(1000)
df.write.mode("overwrite").csv(write_location,header=True) | 0.344664 | 0.366987 |
import boto3
from pprint import pprint
PERMITTED_PORTS = [80, 443]
REPLACE_IP = '127.0.0.1/32'
ALL_IP = '0.0.0.0'
ALL_NET = '/0'
def correct_rule(security_group, bad_rule, ingress=False):
print('=== Bad rule detected ...')
print(bad_rule)
good_rule = bad_rule.copy()
good_rule['IpRanges'] = [{'CidrIp': REPLACE_IP}]
print('Correcting rule:', good_rule)
if ingress:
security_group.revoke_ingress(IpPermissions=[bad_rule])
security_group.authorize_ingress(IpPermissions=[good_rule])
else:
security_group.revoke_egress(IpPermissions=[bad_rule])
security_group.authorize_egress(IpPermissions=[good_rule])
print('Done ===')
def correct_security_groups(client, ec2):
# get the security groups
security_groups = client.describe_security_groups()
security_groups = security_groups['SecurityGroups']
for sg in security_groups:
group_id = sg['GroupId']
group_name = sg['GroupName']
# filter out security groups that are not default
if 'default' not in group_name.lower():
continue
print('SecurityGroup:')
pprint(sg)
security_group = ec2.SecurityGroup(group_id)
ip_perm_ingress = sg['IpPermissions']
ip_perm_egress = sg['IpPermissionsEgress']
for rule in ip_perm_ingress:
bad_rules = [rule for ip_range in rule['IpRanges'] if ALL_IP in ip_range['CidrIp']]
for bad_rule in bad_rules:
correct_rule(security_group, bad_rule, ingress=True)
for rule in ip_perm_egress:
bad_rules = [rule for ip_range in rule['IpRanges'] if ALL_IP in ip_range['CidrIp']]
for bad_rule in bad_rules:
correct_rule(security_group, bad_rule, ingress=False)
def worker(region):
print('== Working on region:', region)
print('Getting resources ...')
client = boto3.client('ec2', region_name=region)
ec2 = boto3.resource('ec2', region_name=region)
correct_security_groups(client, ec2)
print('Done ==')
print('='*75)
if __name__ == '__main__':
print('Creating session ...')
boto3.setup_default_session(profile_name='rcp')
session = boto3.Session()
print('Session:', session)
regions = session.get_available_regions('ec2')
pprint(regions)
for region in regions:
worker(region) | remediate_default_sg.py |
import boto3
from pprint import pprint
PERMITTED_PORTS = [80, 443]
REPLACE_IP = '127.0.0.1/32'
ALL_IP = '0.0.0.0'
ALL_NET = '/0'
def correct_rule(security_group, bad_rule, ingress=False):
print('=== Bad rule detected ...')
print(bad_rule)
good_rule = bad_rule.copy()
good_rule['IpRanges'] = [{'CidrIp': REPLACE_IP}]
print('Correcting rule:', good_rule)
if ingress:
security_group.revoke_ingress(IpPermissions=[bad_rule])
security_group.authorize_ingress(IpPermissions=[good_rule])
else:
security_group.revoke_egress(IpPermissions=[bad_rule])
security_group.authorize_egress(IpPermissions=[good_rule])
print('Done ===')
def correct_security_groups(client, ec2):
# get the security groups
security_groups = client.describe_security_groups()
security_groups = security_groups['SecurityGroups']
for sg in security_groups:
group_id = sg['GroupId']
group_name = sg['GroupName']
# filter out security groups that are not default
if 'default' not in group_name.lower():
continue
print('SecurityGroup:')
pprint(sg)
security_group = ec2.SecurityGroup(group_id)
ip_perm_ingress = sg['IpPermissions']
ip_perm_egress = sg['IpPermissionsEgress']
for rule in ip_perm_ingress:
bad_rules = [rule for ip_range in rule['IpRanges'] if ALL_IP in ip_range['CidrIp']]
for bad_rule in bad_rules:
correct_rule(security_group, bad_rule, ingress=True)
for rule in ip_perm_egress:
bad_rules = [rule for ip_range in rule['IpRanges'] if ALL_IP in ip_range['CidrIp']]
for bad_rule in bad_rules:
correct_rule(security_group, bad_rule, ingress=False)
def worker(region):
print('== Working on region:', region)
print('Getting resources ...')
client = boto3.client('ec2', region_name=region)
ec2 = boto3.resource('ec2', region_name=region)
correct_security_groups(client, ec2)
print('Done ==')
print('='*75)
if __name__ == '__main__':
print('Creating session ...')
boto3.setup_default_session(profile_name='rcp')
session = boto3.Session()
print('Session:', session)
regions = session.get_available_regions('ec2')
pprint(regions)
for region in regions:
worker(region) | 0.271252 | 0.129678 |
from .log import log
class C_new:
def __new__(cls, *args, **kwargs):
log("__new__", args, kwargs)
return object.__new__(cls)
class C_init:
def __init__(self, *args):
log("__init__", args)
class C_reduce:
def __reduce__(self):
log("__reduce__")
return self.__class__, tuple(), None
class C_getnewargs:
def __getnewargs__(self):
log("__getnewargs__")
return tuple()
class C_new_init:
def __new__(cls, *args, **kwargs):
log("__new__", args, kwargs)
return object.__new__(cls)
def __init__(self, *args):
log("__init__", args)
class C_new_reduce:
def __new__(cls, *args, **kwargs):
log("__new__", args, kwargs)
return object.__new__(cls)
def __reduce__(self):
log("__reduce__")
return self.__class__, (3, 4), None
class C_new_getnewargs:
def __new__(cls, *args, **kwargs):
log("__new__", args, kwargs)
return object.__new__(cls)
def __getnewargs__(self):
log("__getnewargs__")
return (5, 6)
class C_init_reduce:
def __init__(self, *args):
log("__init__", args)
def __reduce__(self):
log("__reduce__")
return self.__class__, (3, 4), None
class C_init_getnewargs:
def __init__(self, *args):
log("__init__", args)
def __getnewargs__(self):
log("__getnewargs__")
return (5, 6)
class C_reduce_getnewargs:
def __reduce__(self):
log("__reduce__")
return self.__class__, tuple(), None
def __getnewargs__(self):
log("__getnewargs__")
return tuple()
class C_new_init_reduce:
def __new__(cls, *args, **kwargs):
log("__new__", args, kwargs)
return object.__new__(cls)
def __init__(self, *args):
log("__init__", args)
def __reduce__(self):
log("__reduce__")
return self.__class__, (3, 4), None
class C_new_init_getnewargs:
def __new__(cls, *args, **kwargs):
log("__new__", args, kwargs)
return object.__new__(cls)
def __init__(self, *args):
log("__init__", args)
def __getnewargs__(self):
log("__getnewargs__")
return (5, 6)
class C_new_reduce_getnewargs:
def __new__(cls, *args, **kwargs):
log("__new__", args, kwargs)
return object.__new__(cls)
def __reduce__(self):
log("__reduce__")
return self.__class__, (3, 4), None
def __getnewargs__(self):
log("__getnewargs__")
return (5, 6)
class C_init_reduce_getnewargs:
def __init__(self, *args):
log("__init__", args)
def __reduce__(self):
log("__reduce__")
return self.__class__, (3, 4), None
def __getnewargs__(self):
log("__getnewargs__")
return (5, 6)
class C_new_init_reduce_getnewargs:
def __new__(cls, *args, **kwargs):
log("__new__", args, kwargs)
return object.__new__(cls)
def __init__(self, *args):
log("__init__", args)
def __reduce__(self):
log("__reduce__")
return self.__class__, (3, 4), None
def __getnewargs__(self):
log("__getnewargs__")
return (5, 6) | tests/objects/new_getnewargs.py | from .log import log
class C_new:
def __new__(cls, *args, **kwargs):
log("__new__", args, kwargs)
return object.__new__(cls)
class C_init:
def __init__(self, *args):
log("__init__", args)
class C_reduce:
def __reduce__(self):
log("__reduce__")
return self.__class__, tuple(), None
class C_getnewargs:
def __getnewargs__(self):
log("__getnewargs__")
return tuple()
class C_new_init:
def __new__(cls, *args, **kwargs):
log("__new__", args, kwargs)
return object.__new__(cls)
def __init__(self, *args):
log("__init__", args)
class C_new_reduce:
def __new__(cls, *args, **kwargs):
log("__new__", args, kwargs)
return object.__new__(cls)
def __reduce__(self):
log("__reduce__")
return self.__class__, (3, 4), None
class C_new_getnewargs:
def __new__(cls, *args, **kwargs):
log("__new__", args, kwargs)
return object.__new__(cls)
def __getnewargs__(self):
log("__getnewargs__")
return (5, 6)
class C_init_reduce:
def __init__(self, *args):
log("__init__", args)
def __reduce__(self):
log("__reduce__")
return self.__class__, (3, 4), None
class C_init_getnewargs:
def __init__(self, *args):
log("__init__", args)
def __getnewargs__(self):
log("__getnewargs__")
return (5, 6)
class C_reduce_getnewargs:
def __reduce__(self):
log("__reduce__")
return self.__class__, tuple(), None
def __getnewargs__(self):
log("__getnewargs__")
return tuple()
class C_new_init_reduce:
def __new__(cls, *args, **kwargs):
log("__new__", args, kwargs)
return object.__new__(cls)
def __init__(self, *args):
log("__init__", args)
def __reduce__(self):
log("__reduce__")
return self.__class__, (3, 4), None
class C_new_init_getnewargs:
def __new__(cls, *args, **kwargs):
log("__new__", args, kwargs)
return object.__new__(cls)
def __init__(self, *args):
log("__init__", args)
def __getnewargs__(self):
log("__getnewargs__")
return (5, 6)
class C_new_reduce_getnewargs:
def __new__(cls, *args, **kwargs):
log("__new__", args, kwargs)
return object.__new__(cls)
def __reduce__(self):
log("__reduce__")
return self.__class__, (3, 4), None
def __getnewargs__(self):
log("__getnewargs__")
return (5, 6)
class C_init_reduce_getnewargs:
def __init__(self, *args):
log("__init__", args)
def __reduce__(self):
log("__reduce__")
return self.__class__, (3, 4), None
def __getnewargs__(self):
log("__getnewargs__")
return (5, 6)
class C_new_init_reduce_getnewargs:
def __new__(cls, *args, **kwargs):
log("__new__", args, kwargs)
return object.__new__(cls)
def __init__(self, *args):
log("__init__", args)
def __reduce__(self):
log("__reduce__")
return self.__class__, (3, 4), None
def __getnewargs__(self):
log("__getnewargs__")
return (5, 6) | 0.649801 | 0.052741 |
from pymtl3 import *
#-------------------------------------------------------------------------
# Buffer
#-------------------------------------------------------------------------
class Buffer( Component ):
def construct( s ):
s.data = b8(0)
# By scheduling writes before reads the buffer will model a wire. If
# we reverse this constraint then the buffer will model a register.
s.add_constraints( M(s.write) < M(s.read) )
@method_port
def write( s, value ):
s.data = value
@method_port
def read( s ):
return s.data
#-------------------------------------------------------------------------
# IncrMethodModular
#-------------------------------------------------------------------------
class IncrMethodModular( Component ):
def construct( s ):
s.write = CalleePort()
s.read = CalleePort()
# ''' TUTORIAL TASK ''''''''''''''''''''''''''''''''''''''''''''''''''
# Implement the incrementer
# ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\/
#; Declare two buffers named buf1 and buf2. Connect the write callee
#; port to buf1's write method port and the read callee port to
#; buf2's read method port. Then add an update block that reads data
#; from buf1, increments it by one, and writes the result to buf1.
s.buf1 = Buffer()
s.buf2 = Buffer()
# Connect the callee ports to buf1/buf2 write/read method ports
connect( s.write, s.buf1.write )
connect( s.read, s.buf2.read )
# upB reads from buf1, increments the value by 1, and writes to buf2
@s.update
def upB():
s.buf2.write( s.buf1.read() + b8(1) )
# ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''/\
def line_trace( s ):
return "{:2} (+1) {:2}".format( int(s.buf1.data), int(s.buf2.data) )
#-------------------------------------------------------------------------
# IncrTestBench
#-------------------------------------------------------------------------
class IncrTestBench( Component ):
def construct( s ):
s.incr_in = b8(10)
s.incr_out = b8(0)
# ''' TUTORIAL TASK ''''''''''''''''''''''''''''''''''''''''''''''''''
# Instantiate IncrMethodModular child component here
# ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\/
s.incr = IncrMethodModular()
# ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''/\
# UpA writes data to input
@s.update
def upA():
s.incr.write( s.incr_in )
s.incr_in += 10
# UpC reads data from output
@s.update
def upC():
s.incr_out = s.incr.read()
def line_trace( s ):
return "{}".format( s.incr.line_trace() )
#-------------------------------------------------------------------------
# Simulate the testbench
#-------------------------------------------------------------------------
def test_method_modular():
tb = IncrTestBench()
tb.apply( SimpleSim )
# Print out the update block schedule.
print( "\n==== Schedule ====" )
for blk in tb._sched.schedule:
if not blk.__name__.startswith('s'):
print( blk.__name__ )
# Print out the simulation line trace.
print( "\n==== Line trace ====" )
print( " in_ out")
for i in range( 6 ):
tb.tick()
print( "{:2}: {}".format( i, tb.line_trace() ) ) | examples/ex01_basics/IncrMethodModular_test.py | from pymtl3 import *
#-------------------------------------------------------------------------
# Buffer
#-------------------------------------------------------------------------
class Buffer( Component ):
def construct( s ):
s.data = b8(0)
# By scheduling writes before reads the buffer will model a wire. If
# we reverse this constraint then the buffer will model a register.
s.add_constraints( M(s.write) < M(s.read) )
@method_port
def write( s, value ):
s.data = value
@method_port
def read( s ):
return s.data
#-------------------------------------------------------------------------
# IncrMethodModular
#-------------------------------------------------------------------------
class IncrMethodModular( Component ):
def construct( s ):
s.write = CalleePort()
s.read = CalleePort()
# ''' TUTORIAL TASK ''''''''''''''''''''''''''''''''''''''''''''''''''
# Implement the incrementer
# ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\/
#; Declare two buffers named buf1 and buf2. Connect the write callee
#; port to buf1's write method port and the read callee port to
#; buf2's read method port. Then add an update block that reads data
#; from buf1, increments it by one, and writes the result to buf1.
s.buf1 = Buffer()
s.buf2 = Buffer()
# Connect the callee ports to buf1/buf2 write/read method ports
connect( s.write, s.buf1.write )
connect( s.read, s.buf2.read )
# upB reads from buf1, increments the value by 1, and writes to buf2
@s.update
def upB():
s.buf2.write( s.buf1.read() + b8(1) )
# ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''/\
def line_trace( s ):
return "{:2} (+1) {:2}".format( int(s.buf1.data), int(s.buf2.data) )
#-------------------------------------------------------------------------
# IncrTestBench
#-------------------------------------------------------------------------
class IncrTestBench( Component ):
def construct( s ):
s.incr_in = b8(10)
s.incr_out = b8(0)
# ''' TUTORIAL TASK ''''''''''''''''''''''''''''''''''''''''''''''''''
# Instantiate IncrMethodModular child component here
# ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\/
s.incr = IncrMethodModular()
# ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''/\
# UpA writes data to input
@s.update
def upA():
s.incr.write( s.incr_in )
s.incr_in += 10
# UpC reads data from output
@s.update
def upC():
s.incr_out = s.incr.read()
def line_trace( s ):
return "{}".format( s.incr.line_trace() )
#-------------------------------------------------------------------------
# Simulate the testbench
#-------------------------------------------------------------------------
def test_method_modular():
tb = IncrTestBench()
tb.apply( SimpleSim )
# Print out the update block schedule.
print( "\n==== Schedule ====" )
for blk in tb._sched.schedule:
if not blk.__name__.startswith('s'):
print( blk.__name__ )
# Print out the simulation line trace.
print( "\n==== Line trace ====" )
print( " in_ out")
for i in range( 6 ):
tb.tick()
print( "{:2}: {}".format( i, tb.line_trace() ) ) | 0.566858 | 0.119974 |
from datetime import datetime
import json
import logging
import uuid
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.http import HttpResponseRedirect, Http404, HttpResponse, HttpResponseServerError
from django.shortcuts import render
from django.template.context import RequestContext
from django.utils.translation import ugettext_lazy as _
from soil import DownloadBase
from soil.exceptions import TaskFailedError
from soil.heartbeat import get_file_heartbeat, get_cache_heartbeat, last_heartbeat
from soil.util import get_download_context
def _parse_date(string):
if isinstance(string, str):
return datetime.strptime(string, "%Y-%m-%d").date()
else:
return string
@login_required
def heartbeat_status(request):
return HttpResponse(json.dumps({"last_timestamp": str(last_heartbeat()),
"last_from_file": get_file_heartbeat(),
"last_from_cache": get_cache_heartbeat()}))
@login_required
def ajax_job_poll(request, download_id, template="soil/partials/dl_status.html"):
message = request.GET['message'] if 'message' in request.GET else None
try:
context = get_download_context(download_id, message=message)
except TaskFailedError as e:
context = {'error': list(e.errors) if e.errors else [_("An error occurred during the download.")]}
return HttpResponseServerError(render(request, template, context))
return render(request, template, context)
@login_required
def retrieve_download(request, download_id, template="soil/file_download.html", extra_context=None):
"""
Retrieve a download that's waiting to be generated. If it is the get_file,
then download it, else, let the ajax on the page poll.
"""
context = RequestContext(request)
if extra_context:
context.update(extra_context)
context['download_id'] = download_id
if 'get_file' in request.GET:
download = DownloadBase.get(download_id)
if download is None:
logging.error("Download file request for expired/nonexistent file requested")
raise Http404
return download.toHttpResponse()
return render(request, template, context=context.flatten()) | corehq/ex-submodules/soil/views.py | from datetime import datetime
import json
import logging
import uuid
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.http import HttpResponseRedirect, Http404, HttpResponse, HttpResponseServerError
from django.shortcuts import render
from django.template.context import RequestContext
from django.utils.translation import ugettext_lazy as _
from soil import DownloadBase
from soil.exceptions import TaskFailedError
from soil.heartbeat import get_file_heartbeat, get_cache_heartbeat, last_heartbeat
from soil.util import get_download_context
def _parse_date(string):
if isinstance(string, str):
return datetime.strptime(string, "%Y-%m-%d").date()
else:
return string
@login_required
def heartbeat_status(request):
return HttpResponse(json.dumps({"last_timestamp": str(last_heartbeat()),
"last_from_file": get_file_heartbeat(),
"last_from_cache": get_cache_heartbeat()}))
@login_required
def ajax_job_poll(request, download_id, template="soil/partials/dl_status.html"):
message = request.GET['message'] if 'message' in request.GET else None
try:
context = get_download_context(download_id, message=message)
except TaskFailedError as e:
context = {'error': list(e.errors) if e.errors else [_("An error occurred during the download.")]}
return HttpResponseServerError(render(request, template, context))
return render(request, template, context)
@login_required
def retrieve_download(request, download_id, template="soil/file_download.html", extra_context=None):
"""
Retrieve a download that's waiting to be generated. If it is the get_file,
then download it, else, let the ajax on the page poll.
"""
context = RequestContext(request)
if extra_context:
context.update(extra_context)
context['download_id'] = download_id
if 'get_file' in request.GET:
download = DownloadBase.get(download_id)
if download is None:
logging.error("Download file request for expired/nonexistent file requested")
raise Http404
return download.toHttpResponse()
return render(request, template, context=context.flatten()) | 0.399694 | 0.052352 |
class DimGen(object):
def __init__(self):
self.dim = (0.,0.,1.,1.)
class DimUnit(DimGen):
def __init__(self):
super(DimUnit, self).__init__()
def generate(self, canvas, yy):
yy.dim = (0.,0.,1.,1.)
""" Edge anchors """
class RightOf(DimGen):
def __init__(self, nm, pad=0.05):
super(RightOf, self).__init__()
self.nm = nm
self.pad = pad
def generate(self, canvas, yy):
xx = canvas.x[self.nm]
width = float(xx.dim[2]) / float(xx.nc) * float(yy.nc)
height = xx.dim[3]
width = max(width, 0.05)
height = max(height, 0.05)
left = xx.dim[0]+xx.dim[2]+self.pad
bottom = xx.dim[1]
yy.dim = (left, bottom, width, height)
class LeftOf(DimGen):
def __init__(self, nm, pad=0.05):
super(LeftOf, self).__init__()
self.nm = nm
self.pad = pad
def generate(self, canvas, yy):
xx = canvas.x[self.nm]
width = float(xx.dim[2]) / float(xx.nc) * float(yy.nc)
height = xx.dim[3]
width = max(width, 0.05)
height = max(height, 0.05)
left = xx.dim[0]-self.pad-width
bottom = xx.dim[1]
yy.dim = (left, bottom, width, height)
class TopOf(DimGen):
def __init__(self, nm, pad=0.05):
super(TopOf, self).__init__()
self.nm = nm
self.pad = pad
def generate(self, canvas, yy):
xx = canvas.x[self.nm]
width = xx.dim[2]
height = float(xx.dim[3]) / float(xx.nr) * float(yy.nr)
width = max(width, 0.05)
height = max(height, 0.05)
bottom = xx.dim[1]+xx.dim[3]+self.pad
left = xx.dim[0]
yy.dim = (left, bottom, width, height)
class Beneath(DimGen):
def __init__(self, nm, pad=0.05):
super(Beneath, self).__init__()
self.nm = nm
self.pad = pad
def generate(self, canvas, yy):
xx = canvas.x[self.nm]
width = xx.dim[2]
height = float(xx.dim[3]) / float(xx.nr) * float(yy.nr)
width = max(width, 0.05)
height = max(height, 0.05)
bottom = xx.dim[1]+xx.dim[3]+self.pad
left = xx.dim[0]
yy.dim = (left, bottom, width, height) | Emmer/dimension.py | class DimGen(object):
def __init__(self):
self.dim = (0.,0.,1.,1.)
class DimUnit(DimGen):
def __init__(self):
super(DimUnit, self).__init__()
def generate(self, canvas, yy):
yy.dim = (0.,0.,1.,1.)
""" Edge anchors """
class RightOf(DimGen):
def __init__(self, nm, pad=0.05):
super(RightOf, self).__init__()
self.nm = nm
self.pad = pad
def generate(self, canvas, yy):
xx = canvas.x[self.nm]
width = float(xx.dim[2]) / float(xx.nc) * float(yy.nc)
height = xx.dim[3]
width = max(width, 0.05)
height = max(height, 0.05)
left = xx.dim[0]+xx.dim[2]+self.pad
bottom = xx.dim[1]
yy.dim = (left, bottom, width, height)
class LeftOf(DimGen):
def __init__(self, nm, pad=0.05):
super(LeftOf, self).__init__()
self.nm = nm
self.pad = pad
def generate(self, canvas, yy):
xx = canvas.x[self.nm]
width = float(xx.dim[2]) / float(xx.nc) * float(yy.nc)
height = xx.dim[3]
width = max(width, 0.05)
height = max(height, 0.05)
left = xx.dim[0]-self.pad-width
bottom = xx.dim[1]
yy.dim = (left, bottom, width, height)
class TopOf(DimGen):
def __init__(self, nm, pad=0.05):
super(TopOf, self).__init__()
self.nm = nm
self.pad = pad
def generate(self, canvas, yy):
xx = canvas.x[self.nm]
width = xx.dim[2]
height = float(xx.dim[3]) / float(xx.nr) * float(yy.nr)
width = max(width, 0.05)
height = max(height, 0.05)
bottom = xx.dim[1]+xx.dim[3]+self.pad
left = xx.dim[0]
yy.dim = (left, bottom, width, height)
class Beneath(DimGen):
def __init__(self, nm, pad=0.05):
super(Beneath, self).__init__()
self.nm = nm
self.pad = pad
def generate(self, canvas, yy):
xx = canvas.x[self.nm]
width = xx.dim[2]
height = float(xx.dim[3]) / float(xx.nr) * float(yy.nr)
width = max(width, 0.05)
height = max(height, 0.05)
bottom = xx.dim[1]+xx.dim[3]+self.pad
left = xx.dim[0]
yy.dim = (left, bottom, width, height) | 0.828973 | 0.449091 |
from bokeh.models.annotations import Legend
import pandas as pd
import numpy as np
df = pd.read_csv('covid-data-2021-05-24.csv')
df['date'] = pd.to_datetime(df['date'])
df['month'] = df['date'].dt.month
df['year'] = df['date'].dt.year
df['new_cases_density'] = df['new_cases'] / df['population']*100
df['total_vaccinations_density'] = df['total_vaccinations'] / df['population']*100
df_gp = df.groupby(['year', 'month', 'iso_code', 'continent'])
df_gp_mean = df_gp[['total_vaccinations_density', 'new_cases_density']].mean().reset_index()
from bokeh.io import curdoc, output_notebook, reset_output
from bokeh.plotting import figure, show
from bokeh.models import HoverTool, ColumnDataSource, CategoricalColorMapper, Slider, Select,MultiSelect, Div
from bokeh.layouts import widgetbox, row, column
from bokeh.palettes import Category20_20
# output_notebook()
countries_list = df_gp_mean.iso_code.unique().tolist()
continents = df_gp_mean.continent.unique().tolist()
desc = Div(text='Div', sizing_mode="stretch_width")
# reset_output()
color_mapper = CategoricalColorMapper(factors=countries_list, palette=Category20_20)
source = ColumnDataSource(data=dict(x=[], y=[], color=[], month=[], year=[]))
# Create Input controls
slider_year = Slider(start=min(df_gp_mean.year), end=max(df_gp_mean.year),
step=1, value=min(df_gp_mean.year), title='Year')
slider_month = Slider(start=min(df_gp_mean.month), end=max(df_gp_mean.month),
step=1, value=min(df_gp_mean.month), title='Month')
select_continent = Select(title="Continent", options=sorted(continents), value="North America")
select_countries = MultiSelect(value=['MEX', 'USA', 'CAN'], title='Countries', options=sorted(countries_list))
def select_data():
print('SELECT RUNNING')
df_selected = df_gp_mean[
(df_gp_mean['year'] >= slider_year.value) &
(df_gp_mean['month'] >= slider_month.value) &
(df_gp_mean['continent'] == select_continent.value)]
return df_selected
def filter_countries():
print('FILTER RUNNING')
df_year_month_conti = select_data()
selected_all = pd.DataFrame()
for c in select_countries.value:
selected_c = df_year_month_conti[df_year_month_conti['iso_code'] == c]
selected_all = selected_all.append(selected_c)
return selected_all
def update_plot():
print('UPDATE RUNNING')
df = filter_countries()
print(df.shape)
source.data = dict(
x=df['new_cases_density'],
y=df['total_vaccinations_density'],
color=df['iso_code'],
month=df["month"],
year=df["year"],
)
# print(source.data['color'])
controls = [slider_year, slider_month, select_continent, select_countries]
select_continent.on_change('value', lambda attr, old, new: update_plot())
for control in controls:
control.on_change('value', lambda attr, old, new: update_plot())
p = figure(title="Covid19 in the World", sizing_mode="scale_both",
plot_width=350, plot_height=200)
p.circle(x="x", y="y", source=source, size=10)
inputs = column(*controls)
l = column(desc, row(inputs, p), sizing_mode="scale_both")
update_plot()
curdoc().add_root(l)
curdoc().title = 'Covid19' | covid19_bokeh.py | from bokeh.models.annotations import Legend
import pandas as pd
import numpy as np
df = pd.read_csv('covid-data-2021-05-24.csv')
df['date'] = pd.to_datetime(df['date'])
df['month'] = df['date'].dt.month
df['year'] = df['date'].dt.year
df['new_cases_density'] = df['new_cases'] / df['population']*100
df['total_vaccinations_density'] = df['total_vaccinations'] / df['population']*100
df_gp = df.groupby(['year', 'month', 'iso_code', 'continent'])
df_gp_mean = df_gp[['total_vaccinations_density', 'new_cases_density']].mean().reset_index()
from bokeh.io import curdoc, output_notebook, reset_output
from bokeh.plotting import figure, show
from bokeh.models import HoverTool, ColumnDataSource, CategoricalColorMapper, Slider, Select,MultiSelect, Div
from bokeh.layouts import widgetbox, row, column
from bokeh.palettes import Category20_20
# output_notebook()
countries_list = df_gp_mean.iso_code.unique().tolist()
continents = df_gp_mean.continent.unique().tolist()
desc = Div(text='Div', sizing_mode="stretch_width")
# reset_output()
color_mapper = CategoricalColorMapper(factors=countries_list, palette=Category20_20)
source = ColumnDataSource(data=dict(x=[], y=[], color=[], month=[], year=[]))
# Create Input controls
slider_year = Slider(start=min(df_gp_mean.year), end=max(df_gp_mean.year),
step=1, value=min(df_gp_mean.year), title='Year')
slider_month = Slider(start=min(df_gp_mean.month), end=max(df_gp_mean.month),
step=1, value=min(df_gp_mean.month), title='Month')
select_continent = Select(title="Continent", options=sorted(continents), value="North America")
select_countries = MultiSelect(value=['MEX', 'USA', 'CAN'], title='Countries', options=sorted(countries_list))
def select_data():
print('SELECT RUNNING')
df_selected = df_gp_mean[
(df_gp_mean['year'] >= slider_year.value) &
(df_gp_mean['month'] >= slider_month.value) &
(df_gp_mean['continent'] == select_continent.value)]
return df_selected
def filter_countries():
print('FILTER RUNNING')
df_year_month_conti = select_data()
selected_all = pd.DataFrame()
for c in select_countries.value:
selected_c = df_year_month_conti[df_year_month_conti['iso_code'] == c]
selected_all = selected_all.append(selected_c)
return selected_all
def update_plot():
print('UPDATE RUNNING')
df = filter_countries()
print(df.shape)
source.data = dict(
x=df['new_cases_density'],
y=df['total_vaccinations_density'],
color=df['iso_code'],
month=df["month"],
year=df["year"],
)
# print(source.data['color'])
controls = [slider_year, slider_month, select_continent, select_countries]
select_continent.on_change('value', lambda attr, old, new: update_plot())
for control in controls:
control.on_change('value', lambda attr, old, new: update_plot())
p = figure(title="Covid19 in the World", sizing_mode="scale_both",
plot_width=350, plot_height=200)
p.circle(x="x", y="y", source=source, size=10)
inputs = column(*controls)
l = column(desc, row(inputs, p), sizing_mode="scale_both")
update_plot()
curdoc().add_root(l)
curdoc().title = 'Covid19' | 0.364891 | 0.322446 |
from azure.devops.connection import \
Connection
from azure.devops.exceptions import \
AzureDevOpsServiceError
from msrest.authentication import \
BasicTokenAuthentication, \
BasicAuthentication
from opsdroid.events import \
UserInvite, \
JoinRoom
from opsdroid.logging import \
logging
from opsdroid.matchers import \
match_regex, \
match_event, \
match_parse
from opsdroid.skill import \
Skill
from pprint import \
pprint
from voluptuous import\
Required
import regex
import commonmark
import datetime
import git
logger = logging.getLogger(__name__)
CONFIG_SCHEMA = {
Required("username"): str,
Required("pat"): str,
Required("url"): str,
Required('projectname'): str,
'join_when_invited': bool,
}
class MSDevelop(Skill):
def __init__(self, opsdroid, config):
super(MSDevelop, self).__init__(opsdroid, config)
self.statuslog = []
self.status_something_wrong = 1
# configure logging
self.ase("ms-develop started ...")
self.version = None
try:
self.version = git.Repo(path=__path__[0], search_parent_directories=True).git.describe('--always', '--tags')
except:
self.version = "unknown"
self.ase(f"Version: {self.version}")
# configure connection to devops server
self.credential = BasicAuthentication(config.get('username'), config.get('pat'))
self.connection = Connection(base_url=config.get('url'), creds=self.credential)
self.core = self.connection.clients.get_core_client();
if self.core:
self.ase(f"connection established to {config.get('url')}")
else:
self.ase(f"no connection to {config.get('url')} ... No communication to devops possible.")
return
# get project id
found = False
projectlist = self.core.get_projects()
if len(projectlist.value) > 0:
for project in projectlist.value:
if project.name == config.get('projectname'):
found = True
self.projectid = project.id
self.ase(f"Project found (id: {self.projectid})")
if not found:
self.ase(f"Project '{config.get('projectname')}' not found")
return
# get WIT client
self.wit = self.connection.clients.get_work_item_tracking_client()
self.join_when_invited = config.get("join_when_invited", False)
self.ase(f"The bot can join: {self.join_when_invited}")
# Add status entry
def ase(self, text, failure=0):
logger.debug(f"statuslog: {text}")
self.statuslog += [f"{datetime.datetime.now()}: {text}"]
self.status_something_wrong |= failure
return
@match_event(UserInvite)
async def on_invite_to_room(self, invite):
if self.join_when_invited:
await invite.respond(JoinRoom())
@match_parse(r'bot, status please')
async def bot_status(self, opsdroid, config, message):
text = ""
text += f"**opsdroid** bot for azure-devops server\n\n"
text += f"**Sources**: `https://github.com/silvio/azure-devops-opsdroid.git` (**Version**: {self.version})\n\n"
text += f"@{message.user}: Statusreport\n\n"
text += f"**Healthstate**: {'OK' if self.status_something_wrong else 'Sick'}\n\n"
text += f"**Joinable**: {self.join_when_invited}\n\n"
text += f"~~~\n"
for entry in self.statuslog:
text += f"- {entry}\n"
text += f"~~~\n"
text = commonmark.commonmark(text)
await message.respond(text)
# We are serach only for one occurent and analyse in this task if it
# occures more than one time
@match_regex(r'(?s).*#(\d+).*', matching_condition="match")
async def wit_parser_function(self, apsdroid, config, message):
c = message.connector
text = ""
notfound = ""
for i in regex.finditer(r'#(?P<wit>\d+)', message.text, regex.MULTILINE):
ids = i.group(0)[1:]
try:
value = self.wit.get_work_item(id=ids, project=self.projectid)
except Exception as e:
notfound += f"[{ids}](http:// '{e}'), "
continue
text += f"* [link]({value._links.additional_properties['html']['href']}) - {ids} - {value.fields['System.Title']}\n"
if len(text) > 0:
text = f"@{message.user}: I have found follwing WITs:\n{text}"
notfound = notfound[:-2]
if len(notfound) > 0:
text += f"\n"
text += f"Following WITs not found: {notfound}"
text += f"\n"
text = commonmark.commonmark(text)
await message.respond(text) | __init__.py | from azure.devops.connection import \
Connection
from azure.devops.exceptions import \
AzureDevOpsServiceError
from msrest.authentication import \
BasicTokenAuthentication, \
BasicAuthentication
from opsdroid.events import \
UserInvite, \
JoinRoom
from opsdroid.logging import \
logging
from opsdroid.matchers import \
match_regex, \
match_event, \
match_parse
from opsdroid.skill import \
Skill
from pprint import \
pprint
from voluptuous import\
Required
import regex
import commonmark
import datetime
import git
logger = logging.getLogger(__name__)
CONFIG_SCHEMA = {
Required("username"): str,
Required("pat"): str,
Required("url"): str,
Required('projectname'): str,
'join_when_invited': bool,
}
class MSDevelop(Skill):
def __init__(self, opsdroid, config):
super(MSDevelop, self).__init__(opsdroid, config)
self.statuslog = []
self.status_something_wrong = 1
# configure logging
self.ase("ms-develop started ...")
self.version = None
try:
self.version = git.Repo(path=__path__[0], search_parent_directories=True).git.describe('--always', '--tags')
except:
self.version = "unknown"
self.ase(f"Version: {self.version}")
# configure connection to devops server
self.credential = BasicAuthentication(config.get('username'), config.get('pat'))
self.connection = Connection(base_url=config.get('url'), creds=self.credential)
self.core = self.connection.clients.get_core_client();
if self.core:
self.ase(f"connection established to {config.get('url')}")
else:
self.ase(f"no connection to {config.get('url')} ... No communication to devops possible.")
return
# get project id
found = False
projectlist = self.core.get_projects()
if len(projectlist.value) > 0:
for project in projectlist.value:
if project.name == config.get('projectname'):
found = True
self.projectid = project.id
self.ase(f"Project found (id: {self.projectid})")
if not found:
self.ase(f"Project '{config.get('projectname')}' not found")
return
# get WIT client
self.wit = self.connection.clients.get_work_item_tracking_client()
self.join_when_invited = config.get("join_when_invited", False)
self.ase(f"The bot can join: {self.join_when_invited}")
# Add status entry
def ase(self, text, failure=0):
logger.debug(f"statuslog: {text}")
self.statuslog += [f"{datetime.datetime.now()}: {text}"]
self.status_something_wrong |= failure
return
@match_event(UserInvite)
async def on_invite_to_room(self, invite):
if self.join_when_invited:
await invite.respond(JoinRoom())
@match_parse(r'bot, status please')
async def bot_status(self, opsdroid, config, message):
text = ""
text += f"**opsdroid** bot for azure-devops server\n\n"
text += f"**Sources**: `https://github.com/silvio/azure-devops-opsdroid.git` (**Version**: {self.version})\n\n"
text += f"@{message.user}: Statusreport\n\n"
text += f"**Healthstate**: {'OK' if self.status_something_wrong else 'Sick'}\n\n"
text += f"**Joinable**: {self.join_when_invited}\n\n"
text += f"~~~\n"
for entry in self.statuslog:
text += f"- {entry}\n"
text += f"~~~\n"
text = commonmark.commonmark(text)
await message.respond(text)
# We are serach only for one occurent and analyse in this task if it
# occures more than one time
@match_regex(r'(?s).*#(\d+).*', matching_condition="match")
async def wit_parser_function(self, apsdroid, config, message):
c = message.connector
text = ""
notfound = ""
for i in regex.finditer(r'#(?P<wit>\d+)', message.text, regex.MULTILINE):
ids = i.group(0)[1:]
try:
value = self.wit.get_work_item(id=ids, project=self.projectid)
except Exception as e:
notfound += f"[{ids}](http:// '{e}'), "
continue
text += f"* [link]({value._links.additional_properties['html']['href']}) - {ids} - {value.fields['System.Title']}\n"
if len(text) > 0:
text = f"@{message.user}: I have found follwing WITs:\n{text}"
notfound = notfound[:-2]
if len(notfound) > 0:
text += f"\n"
text += f"Following WITs not found: {notfound}"
text += f"\n"
text = commonmark.commonmark(text)
await message.respond(text) | 0.318273 | 0.11358 |
from .configuration_mbart import MBartConfig
from .file_utils import add_start_docstrings
from .modeling_bart import BartForConditionalGeneration
_CONFIG_FOR_DOC = "MBartConfig"
_TOKENIZER_FOR_DOC = "MBartTokenizer"
MBART_PRETRAINED_MODEL_ARCHIVE_LIST = [
"facebook/mbart-large-cc25",
"facebook/mbart-large-en-ro",
# See all multilingual BART models at https://huggingface.co/models?filter=mbart
]
MBART_START_DOCSTRING = r"""
This model is a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`__ sub-class.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general
usage and behavior.
Parameters:
config (:class:`~transformers.MBartConfig`): Model configuration class with all the parameters of the
model. Initializing with a config file does not load the weights associated with the model, only the
configuration.
Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model weights.
"""
@add_start_docstrings(
"The BART Model with a language modeling head. Can be used for machine translation.", MBART_START_DOCSTRING
)
class MBartForConditionalGeneration(BartForConditionalGeneration):
r"""
This class overrides :class:`~transformers.BartForConditionalGeneration`. Please check the
superclass for the appropriate documentation alongside usage examples.
Examples::
>>> from transformers import MBartForConditionalGeneration, MBartTokenizer
>>> model = MBartForConditionalGeneration.from_pretrained("facebook/mbart-large-en-ro")
>>> tokenizer = MBartTokenizer.from_pretrained("facebook/mbart-large-en-ro")
>>> article = "UN Chief Says There Is No Military Solution in Syria"
>>> batch = tokenizer.prepare_seq2seq_batch(src_texts=[article])
>>> translated_tokens = model.generate(**batch)
>>> translation = tokenizer.batch_decode(translated_tokens, skip_special_tokens=True)[0]
>>> assert translation == "Şeful ONU declară că nu există o soluţie militară în Siria"
"""
config_class = MBartConfig | src/transformers/modeling_mbart.py | from .configuration_mbart import MBartConfig
from .file_utils import add_start_docstrings
from .modeling_bart import BartForConditionalGeneration
_CONFIG_FOR_DOC = "MBartConfig"
_TOKENIZER_FOR_DOC = "MBartTokenizer"
MBART_PRETRAINED_MODEL_ARCHIVE_LIST = [
"facebook/mbart-large-cc25",
"facebook/mbart-large-en-ro",
# See all multilingual BART models at https://huggingface.co/models?filter=mbart
]
MBART_START_DOCSTRING = r"""
This model is a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`__ sub-class.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general
usage and behavior.
Parameters:
config (:class:`~transformers.MBartConfig`): Model configuration class with all the parameters of the
model. Initializing with a config file does not load the weights associated with the model, only the
configuration.
Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model weights.
"""
@add_start_docstrings(
"The BART Model with a language modeling head. Can be used for machine translation.", MBART_START_DOCSTRING
)
class MBartForConditionalGeneration(BartForConditionalGeneration):
r"""
This class overrides :class:`~transformers.BartForConditionalGeneration`. Please check the
superclass for the appropriate documentation alongside usage examples.
Examples::
>>> from transformers import MBartForConditionalGeneration, MBartTokenizer
>>> model = MBartForConditionalGeneration.from_pretrained("facebook/mbart-large-en-ro")
>>> tokenizer = MBartTokenizer.from_pretrained("facebook/mbart-large-en-ro")
>>> article = "UN Chief Says There Is No Military Solution in Syria"
>>> batch = tokenizer.prepare_seq2seq_batch(src_texts=[article])
>>> translated_tokens = model.generate(**batch)
>>> translation = tokenizer.batch_decode(translated_tokens, skip_special_tokens=True)[0]
>>> assert translation == "Şeful ONU declară că nu există o soluţie militară în Siria"
"""
config_class = MBartConfig | 0.863636 | 0.239811 |
import pytest
import yaml
import json
from validate import json_ordered
class TestInconsistentObjects():
get_inconsistent_metadata = {
"type": "get_inconsistent_metadata",
"args": {}
}
reload_metadata = {
"type": "reload_metadata",
"args": {}
}
drop_inconsistent_metadata = {
"type": "drop_inconsistent_metadata",
"args": {}
}
export_metadata = {
"type": "export_metadata",
"args": {}
}
def test_inconsistent_objects(self, hge_ctx):
with open(self.dir() + "/test.yaml") as c:
test = yaml.load(c)
# setup
st_code, resp = hge_ctx.v1q(json.loads(json.dumps(test['setup'])))
assert st_code == 200, resp
# exec sql to cause inconsistentancy
sql_res = hge_ctx.sql(test['sql'])
# reload metadata
st_code, resp = hge_ctx.v1q(q=self.reload_metadata)
assert st_code == 200, resp
# fetch inconsistent objects
st_code, resp = hge_ctx.v1q(q=self.get_inconsistent_metadata)
assert st_code == 200, resp
incons_objs_test = test['inconsistent_objects']
incons_objs_resp = resp['inconsistent_objects']
assert resp['is_consistent'] == False, resp
assert json_ordered(incons_objs_resp) == json_ordered(incons_objs_test), yaml.dump({
'response': resp,
'expected': incons_objs_test,
'diff': jsondiff.diff(incons_objs_test, resp)
})
# export metadata
st_code, export = hge_ctx.v1q(q=self.export_metadata)
assert st_code == 200, export
# apply metadata
st_code, resp = hge_ctx.v1q(
q={
"type": "replace_metadata",
"args": export
}
)
assert st_code == 400, resp
# drop inconsistent objects
st_code, resp = hge_ctx.v1q(q=self.drop_inconsistent_metadata)
assert st_code == 200, resp
# reload metadata
st_code, resp = hge_ctx.v1q(q=self.reload_metadata)
assert st_code == 200, resp
# fetch inconsistent objects
st_code, resp = hge_ctx.v1q(q=self.get_inconsistent_metadata)
assert st_code == 200, resp
assert resp['is_consistent'] == True, resp
assert len(resp['inconsistent_objects']) == 0, resp
# teardown
st_code, resp = hge_ctx.v1q(json.loads(json.dumps(test['teardown'])))
assert st_code == 200, resp
@classmethod
def dir(cls):
return 'queries/inconsistent_objects' | server/tests-py/test_inconsistent_meta.py | import pytest
import yaml
import json
from validate import json_ordered
class TestInconsistentObjects():
get_inconsistent_metadata = {
"type": "get_inconsistent_metadata",
"args": {}
}
reload_metadata = {
"type": "reload_metadata",
"args": {}
}
drop_inconsistent_metadata = {
"type": "drop_inconsistent_metadata",
"args": {}
}
export_metadata = {
"type": "export_metadata",
"args": {}
}
def test_inconsistent_objects(self, hge_ctx):
with open(self.dir() + "/test.yaml") as c:
test = yaml.load(c)
# setup
st_code, resp = hge_ctx.v1q(json.loads(json.dumps(test['setup'])))
assert st_code == 200, resp
# exec sql to cause inconsistentancy
sql_res = hge_ctx.sql(test['sql'])
# reload metadata
st_code, resp = hge_ctx.v1q(q=self.reload_metadata)
assert st_code == 200, resp
# fetch inconsistent objects
st_code, resp = hge_ctx.v1q(q=self.get_inconsistent_metadata)
assert st_code == 200, resp
incons_objs_test = test['inconsistent_objects']
incons_objs_resp = resp['inconsistent_objects']
assert resp['is_consistent'] == False, resp
assert json_ordered(incons_objs_resp) == json_ordered(incons_objs_test), yaml.dump({
'response': resp,
'expected': incons_objs_test,
'diff': jsondiff.diff(incons_objs_test, resp)
})
# export metadata
st_code, export = hge_ctx.v1q(q=self.export_metadata)
assert st_code == 200, export
# apply metadata
st_code, resp = hge_ctx.v1q(
q={
"type": "replace_metadata",
"args": export
}
)
assert st_code == 400, resp
# drop inconsistent objects
st_code, resp = hge_ctx.v1q(q=self.drop_inconsistent_metadata)
assert st_code == 200, resp
# reload metadata
st_code, resp = hge_ctx.v1q(q=self.reload_metadata)
assert st_code == 200, resp
# fetch inconsistent objects
st_code, resp = hge_ctx.v1q(q=self.get_inconsistent_metadata)
assert st_code == 200, resp
assert resp['is_consistent'] == True, resp
assert len(resp['inconsistent_objects']) == 0, resp
# teardown
st_code, resp = hge_ctx.v1q(json.loads(json.dumps(test['teardown'])))
assert st_code == 200, resp
@classmethod
def dir(cls):
return 'queries/inconsistent_objects' | 0.519278 | 0.331931 |
import os
flag, isOperand, isOperator = 0, 0, 0
Variable, Result = 0.0, 0.0
strOperation, strForResult = '', 'Expression = '
while strOperation != '=': # Приложение выводит результат вычислений когда получает от пользователя =.
os.system("clear")
value = input("Enter the number or the operator (+, -, *, /, =), please: ") # Приложение принимает один операнд или один оператор за один цикл запрос-ответ.
try:
value = int(value)
except ValueError:
try:
value = float(value)
except ValueError:
strOperation = value
isOperator += 1 # Пользователь по очереди вводит числа и операторы.
isOperand = 0
if strOperation == '+' or strOperation == '-':
Result = 0
elif strOperation == '*' or strOperation == '/':
Result = 1
elif strOperation == '=':
continue
else:
flag, isOperand, isOperator = 0, 0, 0
Variable, Result = 0.0, 0.0
strOperation, strForResult = '', 'Expression = '
print("You maked the fail by input of operator, please reenrer again") # Приложение корректно обрабатывает ситуацию некорректного ввода.
input("Press any key to reentering")
continue
else:
Variable = value
isOperand += 1 # Пользователь по очереди вводит числа и операторы.
isOperator = 0
else:
Variable = value
isOperand += 1 # Пользователь по очереди вводит числа и операторы.
isOperator = 0
finally:
if isOperand == 2: # Если пользователь вводит оператор два раза подряд, то он получает сообщение об ошибке и может ввести повторно.
flag, isOperand, isOperator = 0, 0, 0
Variable, Result = 0.0, 0.0
strOperation, strForResult = '', 'Expression = '
print("You entered 2 operands successively, please reenrer again/n")
input("Press any key to reentering")
continue
elif isOperator == 2: # Если пользователь вводит число два раза подряд, то он получает сообщение об ошибке и может ввести повторно.
flag, isOperand, isOperator = 0, 0, 0
Variable, Result = 0.0, 0.0
strOperation, strForResult = '', 'Expression = '
print("You entered 2 oprrators successively, please reenrer again/n")
input("Press any key to reentering")
continue
if strForResult == 'Expression = ' and Variable != 0:
strForResult += f'{Variable} '
if strOperation == '+' and Variable != 0: # Все операции приложение выполняет по мере поступления одну за одной.
Result += Variable
flag += 1
if flag == 2:
strForResult += f'{strOperation} {Variable} '
Variable = Result
strOperation = ''
flag = 0
elif strOperation == '-' and Variable != 0: # Все операции приложение выполняет по мере поступления одну за одной.
if flag == 0:
Result = Variable
elif flag == 1:
Result -= Variable
flag += 1
if flag == 2:
strForResult += f'{strOperation} {Variable} '
Variable = Result
strOperation = ''
flag = 0
elif strOperation == '*' and Variable != 0: # Все операции приложение выполняет по мере поступления одну за одной.
Result *= Variable
flag += 1
if flag == 2:
strForResult += f'{strOperation} {Variable} '
Variable = Result
strOperation = ''
flag = 0
elif strOperation == '/' and Variable != 0: # Все операции приложение выполняет по мере поступления одну за одной.
if flag == 0:
Result = Variable
elif flag == 1:
Result /= Variable
flag += 1
if flag == 2:
strForResult += f'{strOperation} {Variable} '
Variable = Result
strOperation = ''
flag = 0
else:
print(f"\t\t\t{strForResult}\t\t\tResult = {Result}") # Приложение заканчивает свою работу после того, как выведет результат вычисления. | lesson2/hw3_new.py | import os
flag, isOperand, isOperator = 0, 0, 0
Variable, Result = 0.0, 0.0
strOperation, strForResult = '', 'Expression = '
while strOperation != '=': # Приложение выводит результат вычислений когда получает от пользователя =.
os.system("clear")
value = input("Enter the number or the operator (+, -, *, /, =), please: ") # Приложение принимает один операнд или один оператор за один цикл запрос-ответ.
try:
value = int(value)
except ValueError:
try:
value = float(value)
except ValueError:
strOperation = value
isOperator += 1 # Пользователь по очереди вводит числа и операторы.
isOperand = 0
if strOperation == '+' or strOperation == '-':
Result = 0
elif strOperation == '*' or strOperation == '/':
Result = 1
elif strOperation == '=':
continue
else:
flag, isOperand, isOperator = 0, 0, 0
Variable, Result = 0.0, 0.0
strOperation, strForResult = '', 'Expression = '
print("You maked the fail by input of operator, please reenrer again") # Приложение корректно обрабатывает ситуацию некорректного ввода.
input("Press any key to reentering")
continue
else:
Variable = value
isOperand += 1 # Пользователь по очереди вводит числа и операторы.
isOperator = 0
else:
Variable = value
isOperand += 1 # Пользователь по очереди вводит числа и операторы.
isOperator = 0
finally:
if isOperand == 2: # Если пользователь вводит оператор два раза подряд, то он получает сообщение об ошибке и может ввести повторно.
flag, isOperand, isOperator = 0, 0, 0
Variable, Result = 0.0, 0.0
strOperation, strForResult = '', 'Expression = '
print("You entered 2 operands successively, please reenrer again/n")
input("Press any key to reentering")
continue
elif isOperator == 2: # Если пользователь вводит число два раза подряд, то он получает сообщение об ошибке и может ввести повторно.
flag, isOperand, isOperator = 0, 0, 0
Variable, Result = 0.0, 0.0
strOperation, strForResult = '', 'Expression = '
print("You entered 2 oprrators successively, please reenrer again/n")
input("Press any key to reentering")
continue
if strForResult == 'Expression = ' and Variable != 0:
strForResult += f'{Variable} '
if strOperation == '+' and Variable != 0: # Все операции приложение выполняет по мере поступления одну за одной.
Result += Variable
flag += 1
if flag == 2:
strForResult += f'{strOperation} {Variable} '
Variable = Result
strOperation = ''
flag = 0
elif strOperation == '-' and Variable != 0: # Все операции приложение выполняет по мере поступления одну за одной.
if flag == 0:
Result = Variable
elif flag == 1:
Result -= Variable
flag += 1
if flag == 2:
strForResult += f'{strOperation} {Variable} '
Variable = Result
strOperation = ''
flag = 0
elif strOperation == '*' and Variable != 0: # Все операции приложение выполняет по мере поступления одну за одной.
Result *= Variable
flag += 1
if flag == 2:
strForResult += f'{strOperation} {Variable} '
Variable = Result
strOperation = ''
flag = 0
elif strOperation == '/' and Variable != 0: # Все операции приложение выполняет по мере поступления одну за одной.
if flag == 0:
Result = Variable
elif flag == 1:
Result /= Variable
flag += 1
if flag == 2:
strForResult += f'{strOperation} {Variable} '
Variable = Result
strOperation = ''
flag = 0
else:
print(f"\t\t\t{strForResult}\t\t\tResult = {Result}") # Приложение заканчивает свою работу после того, как выведет результат вычисления. | 0.057223 | 0.316119 |
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__description__ = '''
Vrátí entropii pro jednotlivé sloupce
Inputs:
- vstupní adresář s *.csv
'''
import sys
import os.path
import pandas as pd
from pprint import pprint
import numpy as np
from math import log2 as log2
# root of lib repository
PROJECT_ROOT = os.path.realpath(os.path.dirname(os.path.abspath(__file__)) + '/../..')
DATA_ROOT = os.path.join(PROJECT_ROOT, 'data')
sys.path.append(PROJECT_ROOT)
class DataEntropy:
def __init__(
self,
infile,
outfile
):
self.infile = infile
self.outfile = outfile
def run(self):
# načti
df = pd.read_csv(self.infile.name, sep='\t', header=0, index_col=False, na_values=None)
totalEntropy = 0
for colName in df.columns:
# normuj
df[colName] = df[colName] + -min(df[colName]) + 1
df[colName] = df[colName].fillna(0)
entropy = self.entropy2(list(df[colName]))
print(colName, entropy)
totalEntropy += entropy
l = len(df);
print('celkem průměrně bitů na jsedno měření [bit]', totalEntropy)
print('počet měření', l)
print('déka při kódování [bit]', l*totalEntropy)
print('déka při kódování [byte]', int(l * totalEntropy/8 +1))
def entropy2(self, labels):
""" Computes entropy of label distribution. """
n_labels = len(labels)
if n_labels <= 1:
return 0
counts = np.bincount(labels)
probs = counts / n_labels
n_classes = np.count_nonzero(probs)
if n_classes <= 1:
return 0
ent = 0.
# Compute shannon entropy.
for pi in probs:
if pi > 0:
ent -= pi * log2(pi)
return ent
# --- Spustitelná část programu ----------------------------------------------------------------------------------------
if __name__ == '__main__':
import argparse
from py.lib.cmdLine.processor import Processor
from py.lib.cmdLine.cmdLineParser import CmdLineParser
class Program(Processor, CmdLineParser):
'''
Spouštěcí část skriptu. Command line, Exceptions, ...
'''
def __init__(self):
# zpracuje příkazovou řádku
CmdLineParser.__init__(self, description=__description__)
# spustí program, zachytí výjimky
Processor.__init__(self)
def _addArgsToCmdLineParser(self, parser):
'''
Definice příkazové řádky
'''
default = os.path.join(os.path.expanduser(DATA_ROOT), 'energomonitor/f2_W.time.dif.tsv')
#default = os.path.join(os.path.expanduser(DATA_ROOT), 'energomonitor/1000.tsv.gz')
parser.add_argument(
'-i', '--input-file',
dest='infile',
metavar='<infile>',
type=argparse.FileType('r'),
help='Vstupní tsv soubor se všemi naměřenými daty (default:' + default + ')',
default=default,
required=False
)
default = os.path.join(os.path.expanduser(DATA_ROOT), 'energomonitor/f2_W.time.dif.ent.tsv')
parser.add_argument(
'-o', '--output-file',
dest='outfile',
metavar='<outfile>',
type=argparse.FileType('w'),
help='Výstubní png s obrázkem (default:' + str(default) + ')',
default=default,
required=False
)
def run(self):
DataEntropy(
infile=self.cmdLineParams.infile,
outfile=self.cmdLineParams.outfile
).run()
Program() | py/tools/getEntropy.py | __author__ = "<NAME>"
__email__ = "<EMAIL>"
__description__ = '''
Vrátí entropii pro jednotlivé sloupce
Inputs:
- vstupní adresář s *.csv
'''
import sys
import os.path
import pandas as pd
from pprint import pprint
import numpy as np
from math import log2 as log2
# root of lib repository
PROJECT_ROOT = os.path.realpath(os.path.dirname(os.path.abspath(__file__)) + '/../..')
DATA_ROOT = os.path.join(PROJECT_ROOT, 'data')
sys.path.append(PROJECT_ROOT)
class DataEntropy:
def __init__(
self,
infile,
outfile
):
self.infile = infile
self.outfile = outfile
def run(self):
# načti
df = pd.read_csv(self.infile.name, sep='\t', header=0, index_col=False, na_values=None)
totalEntropy = 0
for colName in df.columns:
# normuj
df[colName] = df[colName] + -min(df[colName]) + 1
df[colName] = df[colName].fillna(0)
entropy = self.entropy2(list(df[colName]))
print(colName, entropy)
totalEntropy += entropy
l = len(df);
print('celkem průměrně bitů na jsedno měření [bit]', totalEntropy)
print('počet měření', l)
print('déka při kódování [bit]', l*totalEntropy)
print('déka při kódování [byte]', int(l * totalEntropy/8 +1))
def entropy2(self, labels):
""" Computes entropy of label distribution. """
n_labels = len(labels)
if n_labels <= 1:
return 0
counts = np.bincount(labels)
probs = counts / n_labels
n_classes = np.count_nonzero(probs)
if n_classes <= 1:
return 0
ent = 0.
# Compute shannon entropy.
for pi in probs:
if pi > 0:
ent -= pi * log2(pi)
return ent
# --- Spustitelná část programu ----------------------------------------------------------------------------------------
if __name__ == '__main__':
import argparse
from py.lib.cmdLine.processor import Processor
from py.lib.cmdLine.cmdLineParser import CmdLineParser
class Program(Processor, CmdLineParser):
'''
Spouštěcí část skriptu. Command line, Exceptions, ...
'''
def __init__(self):
# zpracuje příkazovou řádku
CmdLineParser.__init__(self, description=__description__)
# spustí program, zachytí výjimky
Processor.__init__(self)
def _addArgsToCmdLineParser(self, parser):
'''
Definice příkazové řádky
'''
default = os.path.join(os.path.expanduser(DATA_ROOT), 'energomonitor/f2_W.time.dif.tsv')
#default = os.path.join(os.path.expanduser(DATA_ROOT), 'energomonitor/1000.tsv.gz')
parser.add_argument(
'-i', '--input-file',
dest='infile',
metavar='<infile>',
type=argparse.FileType('r'),
help='Vstupní tsv soubor se všemi naměřenými daty (default:' + default + ')',
default=default,
required=False
)
default = os.path.join(os.path.expanduser(DATA_ROOT), 'energomonitor/f2_W.time.dif.ent.tsv')
parser.add_argument(
'-o', '--output-file',
dest='outfile',
metavar='<outfile>',
type=argparse.FileType('w'),
help='Výstubní png s obrázkem (default:' + str(default) + ')',
default=default,
required=False
)
def run(self):
DataEntropy(
infile=self.cmdLineParams.infile,
outfile=self.cmdLineParams.outfile
).run()
Program() | 0.254694 | 0.179387 |
import io
import logging
import os
import re
from typing import List
from pygls.lsp.types import (NumType, Position, Range, TextDocumentContentChangeEvent,
TextDocumentItem, TextDocumentSyncKind, WorkspaceFolder)
from pygls.uris import to_fs_path, uri_scheme
# TODO: this is not the best e.g. we capture numbers
RE_END_WORD = re.compile('^[A-Za-z_0-9]*')
RE_START_WORD = re.compile('[A-Za-z_0-9]*$')
log = logging.getLogger(__name__)
def utf16_unit_offset(chars: str):
"""Calculate the number of characters which need two utf-16 code units.
Arguments:
chars (str): The string to count occurrences of utf-16 code units for.
"""
return sum(ord(ch) > 0xFFFF for ch in chars)
def utf16_num_units(chars: str):
"""Calculate the length of `str` in utf-16 code units.
Arguments:
chars (str): The string to return the length in utf-16 code units for.
"""
return len(chars) + utf16_unit_offset(chars)
def position_from_utf16(lines: List[str], position: Position) -> Position:
"""Convert the position.character from utf-16 code units to utf-32.
A python application can't use the character member of `Position`
directly as per specification it is represented as a zero-based line and
character offset based on a UTF-16 string representation.
All characters whose code point exceeds the Basic Multilingual Plane are
represented by 2 UTF-16 code units.
The offset of the closing quotation mark in x="😋" is
- 5 in UTF-16 representation
- 4 in UTF-32 representation
see: https://github.com/microsoft/language-server-protocol/issues/376
Arguments:
lines (list):
The content of the document which the position refers to.
position (Position):
The line and character offset in utf-16 code units.
Returns:
The position with `character` being converted to utf-32 code units.
"""
try:
return Position(
line=position.line,
character=position.character
- utf16_unit_offset(lines[position.line][:position.character])
)
except IndexError:
return Position(line=len(lines), character=0)
def position_to_utf16(lines: List[str], position: Position) -> Position:
"""Convert the position.character from utf-32 to utf-16 code units.
A python application can't use the character member of `Position`
directly as per specification it is represented as a zero-based line and
character offset based on a UTF-16 string representation.
All characters whose code point exceeds the Basic Multilingual Plane are
represented by 2 UTF-16 code units.
The offset of the closing quotation mark in x="😋" is
- 5 in UTF-16 representation
- 4 in UTF-32 representation
see: https://github.com/microsoft/language-server-protocol/issues/376
Arguments:
lines (list):
The content of the document which the position refers to.
position (Position):
The line and character offset in utf-32 code units.
Returns:
The position with `character` being converted to utf-16 code units.
"""
try:
return Position(
line=position.line,
character=position.character
+ utf16_unit_offset(lines[position.line][:position.character])
)
except IndexError:
return Position(line=len(lines), character=0)
def range_from_utf16(lines: List[str], range: Range) -> Range:
"""Convert range.[start|end].character from utf-16 code units to utf-32.
Arguments:
lines (list):
The content of the document which the range refers to.
range (Range):
The line and character offset in utf-32 code units.
Returns:
The range with `character` offsets being converted to utf-16 code units.
"""
return Range(
start=position_from_utf16(lines, range.start),
end=position_from_utf16(lines, range.end)
)
def range_to_utf16(lines: List[str], range: Range) -> Range:
"""Convert range.[start|end].character from utf-32 to utf-16 code units.
Arguments:
lines (list):
The content of the document which the range refers to.
range (Range):
The line and character offset in utf-16 code units.
Returns:
The range with `character` offsets being converted to utf-32 code units.
"""
return Range(
start=position_to_utf16(lines, range.start),
end=position_to_utf16(lines, range.end)
)
class Document(object):
def __init__(self, uri, source=None, version=None, local=True,
sync_kind=TextDocumentSyncKind.INCREMENTAL):
self.uri = uri
self.version = version
self.path = to_fs_path(uri)
self.filename = os.path.basename(self.path)
self._local = local
self._source = source
self._is_sync_kind_full = sync_kind == TextDocumentSyncKind.FULL
self._is_sync_kind_incremental = sync_kind == TextDocumentSyncKind.INCREMENTAL
self._is_sync_kind_none = sync_kind == TextDocumentSyncKind.NONE
def __str__(self):
return str(self.uri)
def _apply_incremental_change(self, change: TextDocumentContentChangeEvent) -> None:
"""Apply an INCREMENTAL text change to the document"""
lines = self.lines
text = change.text
change_range = change.range
(start_line, start_col), (end_line, end_col) = \
range_from_utf16(lines, change_range) # type: ignore
# Check for an edit occurring at the very end of the file
if start_line == len(lines):
self._source = self.source + text
return
new = io.StringIO()
# Iterate over the existing document until we hit the edit range,
# at which point we write the new text, then loop until we hit
# the end of the range and continue writing.
for i, line in enumerate(lines):
if i < start_line:
new.write(line)
continue
if i > end_line:
new.write(line)
continue
if i == start_line:
new.write(line[:start_col])
new.write(text)
if i == end_line:
new.write(line[end_col:])
self._source = new.getvalue()
def _apply_full_change(self, change: TextDocumentContentChangeEvent) -> None:
"""Apply a FULL text change to the document."""
self._source = change.text
def _apply_none_change(self, change: TextDocumentContentChangeEvent) -> None:
"""Apply a NONE text change to the document
Currently does nothing, provided for consistency.
"""
pass
def apply_change(self, change: TextDocumentContentChangeEvent) -> None:
"""Apply a text change to a document, considering TextDocumentSyncKind
Performs either INCREMENTAL, FULL, or NONE synchronization based on
both the Client request and server capabilities.
INCREMENTAL versus FULL synchronization:
Even if a server accepts INCREMENTAL SyncKinds, clients may request
a FULL SyncKind. In LSP 3.x, clients make this request by omitting
both Range and RangeLength from their request. Consequently, the
attributes "range" and "rangeLength" will be missing from FULL
content update client requests in the pygls Python library.
NOTE: After adding pydantic models, "range" and "rangeLength" fileds
will be None if not passed by the client
"""
if change.range is not None:
if self._is_sync_kind_incremental:
self._apply_incremental_change(change)
return
# Log an error, but still perform full update to preserve existing
# assumptions in test_document/test_document_full_edit. Test breaks
# otherwise, and fixing the tests would require a broader fix to
# protocol.py.
log.error(
"Unsupported client-provided TextDocumentContentChangeEvent. "
"Please update / submit a Pull Request to your LSP client."
)
if self._is_sync_kind_none:
self._apply_none_change(change)
else:
self._apply_full_change(change)
@property
def lines(self) -> List[str]:
return self.source.splitlines(True)
def offset_at_position(self, position: Position) -> int:
"""Return the character offset pointed at by the given position."""
lines = self.lines
row, col = position_from_utf16(lines, position)
return col + sum(len(line) for line in lines[:row])
@property
def source(self) -> str:
if self._source is None:
with io.open(self.path, 'r', encoding='utf-8') as f:
return f.read()
return self._source
def word_at_position(self, position: Position) -> str:
"""
Get the word under the cursor returning the start and end positions.
"""
lines = self.lines
if position.line >= len(lines):
return ''
row, col = position_from_utf16(lines, position)
line = lines[row]
# Split word in two
start = line[:col]
end = line[col:]
# Take end of start and start of end to find word
# These are guaranteed to match, even if they match the empty string
m_start = RE_START_WORD.findall(start)
m_end = RE_END_WORD.findall(end)
return m_start[0] + m_end[-1]
class Workspace(object):
def __init__(self, root_uri, sync_kind=None, workspace_folders=None):
self._root_uri = root_uri
self._root_uri_scheme = uri_scheme(self._root_uri)
self._root_path = to_fs_path(self._root_uri)
self._sync_kind = sync_kind
self._folders = {}
self._docs = {}
if workspace_folders is not None:
for folder in workspace_folders:
self.add_folder(folder)
def _create_document(self,
doc_uri: str,
source: str = None,
version: NumType = None) -> Document:
return Document(doc_uri, source=source, version=version,
sync_kind=self._sync_kind)
def add_folder(self, folder: WorkspaceFolder):
self._folders[folder.uri] = folder
@property
def documents(self):
return self._docs
@property
def folders(self):
return self._folders
def get_document(self, doc_uri: str) -> Document:
"""
Return a managed document if-present,
else create one pointing at disk.
See https://github.com/Microsoft/language-server-protocol/issues/177
"""
return self._docs.get(doc_uri) or self._create_document(doc_uri)
def is_local(self):
return (
self._root_uri_scheme == ''
or self._root_uri_scheme == 'file'
) and os.path.exists(self._root_path)
def put_document(self, text_document: TextDocumentItem):
doc_uri = text_document.uri
self._docs[doc_uri] = self._create_document(
doc_uri,
source=text_document.text,
version=text_document.version
)
def remove_document(self, doc_uri: str):
self._docs.pop(doc_uri)
def remove_folder(self, folder_uri: str):
self._folders.pop(folder_uri, None)
try:
del self._folders[folder_uri]
except KeyError:
pass
@property
def root_path(self):
return self._root_path
@property
def root_uri(self):
return self._root_uri
def update_document(self,
text_doc: TextDocumentItem,
change: TextDocumentContentChangeEvent):
doc_uri = text_doc.uri
self._docs[doc_uri].apply_change(change)
self._docs[doc_uri].version = text_doc.version | pygls/workspace.py | import io
import logging
import os
import re
from typing import List
from pygls.lsp.types import (NumType, Position, Range, TextDocumentContentChangeEvent,
TextDocumentItem, TextDocumentSyncKind, WorkspaceFolder)
from pygls.uris import to_fs_path, uri_scheme
# TODO: this is not the best e.g. we capture numbers
RE_END_WORD = re.compile('^[A-Za-z_0-9]*')
RE_START_WORD = re.compile('[A-Za-z_0-9]*$')
log = logging.getLogger(__name__)
def utf16_unit_offset(chars: str):
"""Calculate the number of characters which need two utf-16 code units.
Arguments:
chars (str): The string to count occurrences of utf-16 code units for.
"""
return sum(ord(ch) > 0xFFFF for ch in chars)
def utf16_num_units(chars: str):
"""Calculate the length of `str` in utf-16 code units.
Arguments:
chars (str): The string to return the length in utf-16 code units for.
"""
return len(chars) + utf16_unit_offset(chars)
def position_from_utf16(lines: List[str], position: Position) -> Position:
"""Convert the position.character from utf-16 code units to utf-32.
A python application can't use the character member of `Position`
directly as per specification it is represented as a zero-based line and
character offset based on a UTF-16 string representation.
All characters whose code point exceeds the Basic Multilingual Plane are
represented by 2 UTF-16 code units.
The offset of the closing quotation mark in x="😋" is
- 5 in UTF-16 representation
- 4 in UTF-32 representation
see: https://github.com/microsoft/language-server-protocol/issues/376
Arguments:
lines (list):
The content of the document which the position refers to.
position (Position):
The line and character offset in utf-16 code units.
Returns:
The position with `character` being converted to utf-32 code units.
"""
try:
return Position(
line=position.line,
character=position.character
- utf16_unit_offset(lines[position.line][:position.character])
)
except IndexError:
return Position(line=len(lines), character=0)
def position_to_utf16(lines: List[str], position: Position) -> Position:
"""Convert the position.character from utf-32 to utf-16 code units.
A python application can't use the character member of `Position`
directly as per specification it is represented as a zero-based line and
character offset based on a UTF-16 string representation.
All characters whose code point exceeds the Basic Multilingual Plane are
represented by 2 UTF-16 code units.
The offset of the closing quotation mark in x="😋" is
- 5 in UTF-16 representation
- 4 in UTF-32 representation
see: https://github.com/microsoft/language-server-protocol/issues/376
Arguments:
lines (list):
The content of the document which the position refers to.
position (Position):
The line and character offset in utf-32 code units.
Returns:
The position with `character` being converted to utf-16 code units.
"""
try:
return Position(
line=position.line,
character=position.character
+ utf16_unit_offset(lines[position.line][:position.character])
)
except IndexError:
return Position(line=len(lines), character=0)
def range_from_utf16(lines: List[str], range: Range) -> Range:
"""Convert range.[start|end].character from utf-16 code units to utf-32.
Arguments:
lines (list):
The content of the document which the range refers to.
range (Range):
The line and character offset in utf-32 code units.
Returns:
The range with `character` offsets being converted to utf-16 code units.
"""
return Range(
start=position_from_utf16(lines, range.start),
end=position_from_utf16(lines, range.end)
)
def range_to_utf16(lines: List[str], range: Range) -> Range:
"""Convert range.[start|end].character from utf-32 to utf-16 code units.
Arguments:
lines (list):
The content of the document which the range refers to.
range (Range):
The line and character offset in utf-16 code units.
Returns:
The range with `character` offsets being converted to utf-32 code units.
"""
return Range(
start=position_to_utf16(lines, range.start),
end=position_to_utf16(lines, range.end)
)
class Document(object):
def __init__(self, uri, source=None, version=None, local=True,
sync_kind=TextDocumentSyncKind.INCREMENTAL):
self.uri = uri
self.version = version
self.path = to_fs_path(uri)
self.filename = os.path.basename(self.path)
self._local = local
self._source = source
self._is_sync_kind_full = sync_kind == TextDocumentSyncKind.FULL
self._is_sync_kind_incremental = sync_kind == TextDocumentSyncKind.INCREMENTAL
self._is_sync_kind_none = sync_kind == TextDocumentSyncKind.NONE
def __str__(self):
return str(self.uri)
def _apply_incremental_change(self, change: TextDocumentContentChangeEvent) -> None:
"""Apply an INCREMENTAL text change to the document"""
lines = self.lines
text = change.text
change_range = change.range
(start_line, start_col), (end_line, end_col) = \
range_from_utf16(lines, change_range) # type: ignore
# Check for an edit occurring at the very end of the file
if start_line == len(lines):
self._source = self.source + text
return
new = io.StringIO()
# Iterate over the existing document until we hit the edit range,
# at which point we write the new text, then loop until we hit
# the end of the range and continue writing.
for i, line in enumerate(lines):
if i < start_line:
new.write(line)
continue
if i > end_line:
new.write(line)
continue
if i == start_line:
new.write(line[:start_col])
new.write(text)
if i == end_line:
new.write(line[end_col:])
self._source = new.getvalue()
def _apply_full_change(self, change: TextDocumentContentChangeEvent) -> None:
"""Apply a FULL text change to the document."""
self._source = change.text
def _apply_none_change(self, change: TextDocumentContentChangeEvent) -> None:
"""Apply a NONE text change to the document
Currently does nothing, provided for consistency.
"""
pass
def apply_change(self, change: TextDocumentContentChangeEvent) -> None:
"""Apply a text change to a document, considering TextDocumentSyncKind
Performs either INCREMENTAL, FULL, or NONE synchronization based on
both the Client request and server capabilities.
INCREMENTAL versus FULL synchronization:
Even if a server accepts INCREMENTAL SyncKinds, clients may request
a FULL SyncKind. In LSP 3.x, clients make this request by omitting
both Range and RangeLength from their request. Consequently, the
attributes "range" and "rangeLength" will be missing from FULL
content update client requests in the pygls Python library.
NOTE: After adding pydantic models, "range" and "rangeLength" fileds
will be None if not passed by the client
"""
if change.range is not None:
if self._is_sync_kind_incremental:
self._apply_incremental_change(change)
return
# Log an error, but still perform full update to preserve existing
# assumptions in test_document/test_document_full_edit. Test breaks
# otherwise, and fixing the tests would require a broader fix to
# protocol.py.
log.error(
"Unsupported client-provided TextDocumentContentChangeEvent. "
"Please update / submit a Pull Request to your LSP client."
)
if self._is_sync_kind_none:
self._apply_none_change(change)
else:
self._apply_full_change(change)
@property
def lines(self) -> List[str]:
return self.source.splitlines(True)
def offset_at_position(self, position: Position) -> int:
"""Return the character offset pointed at by the given position."""
lines = self.lines
row, col = position_from_utf16(lines, position)
return col + sum(len(line) for line in lines[:row])
@property
def source(self) -> str:
if self._source is None:
with io.open(self.path, 'r', encoding='utf-8') as f:
return f.read()
return self._source
def word_at_position(self, position: Position) -> str:
"""
Get the word under the cursor returning the start and end positions.
"""
lines = self.lines
if position.line >= len(lines):
return ''
row, col = position_from_utf16(lines, position)
line = lines[row]
# Split word in two
start = line[:col]
end = line[col:]
# Take end of start and start of end to find word
# These are guaranteed to match, even if they match the empty string
m_start = RE_START_WORD.findall(start)
m_end = RE_END_WORD.findall(end)
return m_start[0] + m_end[-1]
class Workspace(object):
def __init__(self, root_uri, sync_kind=None, workspace_folders=None):
self._root_uri = root_uri
self._root_uri_scheme = uri_scheme(self._root_uri)
self._root_path = to_fs_path(self._root_uri)
self._sync_kind = sync_kind
self._folders = {}
self._docs = {}
if workspace_folders is not None:
for folder in workspace_folders:
self.add_folder(folder)
def _create_document(self,
doc_uri: str,
source: str = None,
version: NumType = None) -> Document:
return Document(doc_uri, source=source, version=version,
sync_kind=self._sync_kind)
def add_folder(self, folder: WorkspaceFolder):
self._folders[folder.uri] = folder
@property
def documents(self):
return self._docs
@property
def folders(self):
return self._folders
def get_document(self, doc_uri: str) -> Document:
"""
Return a managed document if-present,
else create one pointing at disk.
See https://github.com/Microsoft/language-server-protocol/issues/177
"""
return self._docs.get(doc_uri) or self._create_document(doc_uri)
def is_local(self):
return (
self._root_uri_scheme == ''
or self._root_uri_scheme == 'file'
) and os.path.exists(self._root_path)
def put_document(self, text_document: TextDocumentItem):
doc_uri = text_document.uri
self._docs[doc_uri] = self._create_document(
doc_uri,
source=text_document.text,
version=text_document.version
)
def remove_document(self, doc_uri: str):
self._docs.pop(doc_uri)
def remove_folder(self, folder_uri: str):
self._folders.pop(folder_uri, None)
try:
del self._folders[folder_uri]
except KeyError:
pass
@property
def root_path(self):
return self._root_path
@property
def root_uri(self):
return self._root_uri
def update_document(self,
text_doc: TextDocumentItem,
change: TextDocumentContentChangeEvent):
doc_uri = text_doc.uri
self._docs[doc_uri].apply_change(change)
self._docs[doc_uri].version = text_doc.version | 0.644784 | 0.426023 |
"""Tests for Bijector."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
import numpy as np
import tensorflow.compat.v2 as tf
from tensorflow_probability.python import bijectors as tfb
from tensorflow_probability.python.bijectors import bijector_test_util
from tensorflow_probability.python.internal import test_util
@test_util.test_all_tf_execution_regimes
class ShiftedGompertzCDF(test_util.TestCase):
"""Tests correctness of the Shifted Gompertz bijector."""
def testScalarCongruency(self):
bijector_test_util.assert_scalar_congruency(
tfb.ShiftedGompertzCDF(concentration=0.1, rate=0.4),
lower_x=1., upper_x=10., eval_func=self.evaluate, rtol=0.05)
def testBijectiveAndFinite(self):
bijector = tfb.ShiftedGompertzCDF(
concentration=0.2, rate=0.01, validate_args=True)
x = np.logspace(-10, 2, num=10).astype(np.float32)
y = np.linspace(0.01, 0.99, num=10).astype(np.float32)
bijector_test_util.assert_bijective_and_finite(
bijector, x, y, eval_func=self.evaluate, event_ndims=0, rtol=1e-3)
@test_util.jax_disable_variable_test
def testVariableConcentration(self):
x = tf.Variable(1.)
b = tfb.ShiftedGompertzCDF(concentration=x, rate=1., validate_args=True)
self.evaluate(x.initializer)
self.assertIs(x, b.concentration)
self.assertEqual((), self.evaluate(b.forward(1.)).shape)
with self.assertRaisesOpError("Argument `concentration` must be positive."):
with tf.control_dependencies([x.assign(-1.)]):
self.evaluate(b.forward(1.))
@test_util.jax_disable_variable_test
def testVariableRate(self):
x = tf.Variable(1.)
b = tfb.ShiftedGompertzCDF(concentration=1., rate=x, validate_args=True)
self.evaluate(x.initializer)
self.assertIs(x, b.rate)
self.assertEqual((), self.evaluate(b.forward(1.)).shape)
with self.assertRaisesOpError("Argument `rate` must be positive."):
with tf.control_dependencies([x.assign(-1.)]):
self.evaluate(b.forward(1.))
if __name__ == "__main__":
tf.test.main() | tensorflow_probability/python/bijectors/shifted_gompertz_cdf_test.py | """Tests for Bijector."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
import numpy as np
import tensorflow.compat.v2 as tf
from tensorflow_probability.python import bijectors as tfb
from tensorflow_probability.python.bijectors import bijector_test_util
from tensorflow_probability.python.internal import test_util
@test_util.test_all_tf_execution_regimes
class ShiftedGompertzCDF(test_util.TestCase):
"""Tests correctness of the Shifted Gompertz bijector."""
def testScalarCongruency(self):
bijector_test_util.assert_scalar_congruency(
tfb.ShiftedGompertzCDF(concentration=0.1, rate=0.4),
lower_x=1., upper_x=10., eval_func=self.evaluate, rtol=0.05)
def testBijectiveAndFinite(self):
bijector = tfb.ShiftedGompertzCDF(
concentration=0.2, rate=0.01, validate_args=True)
x = np.logspace(-10, 2, num=10).astype(np.float32)
y = np.linspace(0.01, 0.99, num=10).astype(np.float32)
bijector_test_util.assert_bijective_and_finite(
bijector, x, y, eval_func=self.evaluate, event_ndims=0, rtol=1e-3)
@test_util.jax_disable_variable_test
def testVariableConcentration(self):
x = tf.Variable(1.)
b = tfb.ShiftedGompertzCDF(concentration=x, rate=1., validate_args=True)
self.evaluate(x.initializer)
self.assertIs(x, b.concentration)
self.assertEqual((), self.evaluate(b.forward(1.)).shape)
with self.assertRaisesOpError("Argument `concentration` must be positive."):
with tf.control_dependencies([x.assign(-1.)]):
self.evaluate(b.forward(1.))
@test_util.jax_disable_variable_test
def testVariableRate(self):
x = tf.Variable(1.)
b = tfb.ShiftedGompertzCDF(concentration=1., rate=x, validate_args=True)
self.evaluate(x.initializer)
self.assertIs(x, b.rate)
self.assertEqual((), self.evaluate(b.forward(1.)).shape)
with self.assertRaisesOpError("Argument `rate` must be positive."):
with tf.control_dependencies([x.assign(-1.)]):
self.evaluate(b.forward(1.))
if __name__ == "__main__":
tf.test.main() | 0.903055 | 0.63168 |
import abc
import numpy as np
from casex import AircraftSpecs
from numba import njit
from sklearn.mixture import GaussianMixture
from seedpod_ground_risk.path_analysis.utils import bearing_to_angle, rotate_2d
@njit(cache=True)
def paef_to_ned_with_wind(x):
"""
Transform PAE frame distances to NED frame and transform with wind.
This func is designed to be used in np apply, hence the single arg. The column ordering is very specific!
:param x: array row with ordering [paef_y (always 0), paef_x, impact_time, theta (rad), wind_vel_x, wind_vel_y]
:return:
"""
paef_c = x[0:2]
t_i = x[2]
theta = x[3]
wind_vect = x[4:6]
return rotate_2d(paef_c, theta) + wind_vect * t_i
def primitives_to_dist(a_i, d_i, heading, loc_x, loc_y, t_i, v_i, wind_vel_x, wind_vel_y):
# Compensate for x,y axes being rotated compared to bearings
theta = bearing_to_angle(heading)
# Form the array structure required and transform
arr = np.vstack((np.zeros(d_i.shape), d_i, t_i, theta, wind_vel_x, wind_vel_y))
transformed_arr = np.apply_along_axis(paef_to_ned_with_wind, 0, arr)
# Remove nan rows
transformed_arr = transformed_arr[:, ~np.isnan(transformed_arr).all(axis=0)]
gm = GaussianMixture()
gm.fit_predict(transformed_arr.T)
# If there the event and NED origins match, no need to translate
if not loc_x or not loc_y:
means = gm.means_[0]
else:
means = gm.means_[0] + np.array([loc_x, loc_y])
# Gaussian Mixture model can deal with up to 3D distributions, but we are only dealing with 2D here,
# so take first index into the depth
return (means, gm.covariances_[0]), v_i.mean(), a_i.mean()
class DescentModel(abc.ABC):
"""
The purpose of the descent model is to map the UAS properties and instantaneous kinematic states
to an impact location distribution on the ground.
"""
def __init__(self, aircraft: AircraftSpecs, n_samples: int = 2000) -> None:
self.aircraft = aircraft
self.n_samples = n_samples
@abc.abstractmethod
def transform(self, altitude, velocity, heading, wind_vel_y, wind_vel_x, loc_x, loc_y):
"""
:param altitude: the altitude in metres
:type altitude: float or np.array
:param velocity: the velocity over the ground of the aircraft in the direction of flight in m/s
:type velocity: float or np.array
:param heading: the ground track bearing of the aircraft in deg (North is 000)
:type heading: float or np.array
:param wind_vel_x: the x component of the wind in m/s
:type wind_vel_x: float or nd.array
:param wind_vel_y: the y component of the wind in m/s
:type wind_vel_y: float or nd.array
:param loc_x: event x location
:type loc_x: int
:param loc_y: event y location
:type loc_y: int
"""
pass | seedpod_ground_risk/path_analysis/descent_models/descent_model.py | import abc
import numpy as np
from casex import AircraftSpecs
from numba import njit
from sklearn.mixture import GaussianMixture
from seedpod_ground_risk.path_analysis.utils import bearing_to_angle, rotate_2d
@njit(cache=True)
def paef_to_ned_with_wind(x):
"""
Transform PAE frame distances to NED frame and transform with wind.
This func is designed to be used in np apply, hence the single arg. The column ordering is very specific!
:param x: array row with ordering [paef_y (always 0), paef_x, impact_time, theta (rad), wind_vel_x, wind_vel_y]
:return:
"""
paef_c = x[0:2]
t_i = x[2]
theta = x[3]
wind_vect = x[4:6]
return rotate_2d(paef_c, theta) + wind_vect * t_i
def primitives_to_dist(a_i, d_i, heading, loc_x, loc_y, t_i, v_i, wind_vel_x, wind_vel_y):
# Compensate for x,y axes being rotated compared to bearings
theta = bearing_to_angle(heading)
# Form the array structure required and transform
arr = np.vstack((np.zeros(d_i.shape), d_i, t_i, theta, wind_vel_x, wind_vel_y))
transformed_arr = np.apply_along_axis(paef_to_ned_with_wind, 0, arr)
# Remove nan rows
transformed_arr = transformed_arr[:, ~np.isnan(transformed_arr).all(axis=0)]
gm = GaussianMixture()
gm.fit_predict(transformed_arr.T)
# If there the event and NED origins match, no need to translate
if not loc_x or not loc_y:
means = gm.means_[0]
else:
means = gm.means_[0] + np.array([loc_x, loc_y])
# Gaussian Mixture model can deal with up to 3D distributions, but we are only dealing with 2D here,
# so take first index into the depth
return (means, gm.covariances_[0]), v_i.mean(), a_i.mean()
class DescentModel(abc.ABC):
"""
The purpose of the descent model is to map the UAS properties and instantaneous kinematic states
to an impact location distribution on the ground.
"""
def __init__(self, aircraft: AircraftSpecs, n_samples: int = 2000) -> None:
self.aircraft = aircraft
self.n_samples = n_samples
@abc.abstractmethod
def transform(self, altitude, velocity, heading, wind_vel_y, wind_vel_x, loc_x, loc_y):
"""
:param altitude: the altitude in metres
:type altitude: float or np.array
:param velocity: the velocity over the ground of the aircraft in the direction of flight in m/s
:type velocity: float or np.array
:param heading: the ground track bearing of the aircraft in deg (North is 000)
:type heading: float or np.array
:param wind_vel_x: the x component of the wind in m/s
:type wind_vel_x: float or nd.array
:param wind_vel_y: the y component of the wind in m/s
:type wind_vel_y: float or nd.array
:param loc_x: event x location
:type loc_x: int
:param loc_y: event y location
:type loc_y: int
"""
pass | 0.877451 | 0.673386 |
r"""
.. _ref_ex_advanced2:
Mesh Refinement
---------------
Perform a mesh refinement study.
In this example the convergence of the torsion constant is investigated through an analysis of an
I Section. The mesh is refined both by modifying the mesh size and by specifying the number of
points making up the root radius. The figure below the example code shows that mesh refinement
adjacent to the root radius is a far more efficient method in obtaining fast convergence when
compared to reducing the mesh area size for the entire section.
"""
# sphinx_gallery_thumbnail_number = 1
import numpy as np
import matplotlib.pyplot as plt
import sectionproperties.pre.library.steel_sections as steel_sections
from sectionproperties.analysis.section import Section
# %%
# Define mesh sizes
mesh_size_list = [200, 100, 50, 20, 10, 5]
nr_list = [4, 8, 12, 16, 20, 24, 32]
# %%
# Initialise result lists
mesh_results = []
mesh_elements = []
nr_results = []
nr_elements = []
# %%
# Calculate reference solution
geometry = steel_sections.i_section(d=203, b=133, t_f=7.8, t_w=5.8, r=8.9, n_r=32)
geometry.create_mesh(mesh_sizes=[5]) # create mesh
section = Section(geometry) # create a Section object
section.calculate_geometric_properties()
section.calculate_warping_properties()
j_reference = section.get_j() # get the torsion constant
# %%
# Run through mesh_sizes with n_r = 8
for mesh_size in mesh_size_list:
geometry = steel_sections.i_section(d=203, b=133, t_f=7.8, t_w=5.8, r=8.9, n_r=8)
geometry.create_mesh(mesh_sizes=[mesh_size]) # create mesh
section = Section(geometry) # create a Section object
section.calculate_geometric_properties()
section.calculate_warping_properties()
mesh_elements.append(len(section.elements))
mesh_results.append(section.get_j())
# %%
# Run through n_r with mesh_size = 10
for n_r in nr_list:
geometry = steel_sections.i_section(d=203, b=133, t_f=7.8, t_w=5.8, r=8.9, n_r=n_r)
geometry.create_mesh(mesh_sizes=[10]) # create mesh
section = Section(geometry) # create a Section object
section.calculate_geometric_properties()
section.calculate_warping_properties()
nr_elements.append(len(section.elements))
nr_results.append(section.get_j())
# %%
# Convert results to a numpy array and compute the error
mesh_results = np.array(mesh_results)
nr_results = np.array(nr_results)
mesh_error_vals = (mesh_results - j_reference) / mesh_results * 100
nr_error_vals = (nr_results - j_reference) / nr_results * 100
# %%
# Plot the results
(fig, ax) = plt.subplots()
ax.loglog(mesh_elements, mesh_error_vals, "kx-", label="Mesh Size Refinement")
ax.loglog(nr_elements, nr_error_vals, "rx-", label="Root Radius Refinement")
plt.xlabel("Number of Elements")
plt.ylabel("Torsion Constant Error [%]")
plt.legend(loc="center left", bbox_to_anchor=(1, 0.5))
plt.tight_layout()
plt.show() | examples/01-advanced/02_mesh_refinement.py | r"""
.. _ref_ex_advanced2:
Mesh Refinement
---------------
Perform a mesh refinement study.
In this example the convergence of the torsion constant is investigated through an analysis of an
I Section. The mesh is refined both by modifying the mesh size and by specifying the number of
points making up the root radius. The figure below the example code shows that mesh refinement
adjacent to the root radius is a far more efficient method in obtaining fast convergence when
compared to reducing the mesh area size for the entire section.
"""
# sphinx_gallery_thumbnail_number = 1
import numpy as np
import matplotlib.pyplot as plt
import sectionproperties.pre.library.steel_sections as steel_sections
from sectionproperties.analysis.section import Section
# %%
# Define mesh sizes
mesh_size_list = [200, 100, 50, 20, 10, 5]
nr_list = [4, 8, 12, 16, 20, 24, 32]
# %%
# Initialise result lists
mesh_results = []
mesh_elements = []
nr_results = []
nr_elements = []
# %%
# Calculate reference solution
geometry = steel_sections.i_section(d=203, b=133, t_f=7.8, t_w=5.8, r=8.9, n_r=32)
geometry.create_mesh(mesh_sizes=[5]) # create mesh
section = Section(geometry) # create a Section object
section.calculate_geometric_properties()
section.calculate_warping_properties()
j_reference = section.get_j() # get the torsion constant
# %%
# Run through mesh_sizes with n_r = 8
for mesh_size in mesh_size_list:
geometry = steel_sections.i_section(d=203, b=133, t_f=7.8, t_w=5.8, r=8.9, n_r=8)
geometry.create_mesh(mesh_sizes=[mesh_size]) # create mesh
section = Section(geometry) # create a Section object
section.calculate_geometric_properties()
section.calculate_warping_properties()
mesh_elements.append(len(section.elements))
mesh_results.append(section.get_j())
# %%
# Run through n_r with mesh_size = 10
for n_r in nr_list:
geometry = steel_sections.i_section(d=203, b=133, t_f=7.8, t_w=5.8, r=8.9, n_r=n_r)
geometry.create_mesh(mesh_sizes=[10]) # create mesh
section = Section(geometry) # create a Section object
section.calculate_geometric_properties()
section.calculate_warping_properties()
nr_elements.append(len(section.elements))
nr_results.append(section.get_j())
# %%
# Convert results to a numpy array and compute the error
mesh_results = np.array(mesh_results)
nr_results = np.array(nr_results)
mesh_error_vals = (mesh_results - j_reference) / mesh_results * 100
nr_error_vals = (nr_results - j_reference) / nr_results * 100
# %%
# Plot the results
(fig, ax) = plt.subplots()
ax.loglog(mesh_elements, mesh_error_vals, "kx-", label="Mesh Size Refinement")
ax.loglog(nr_elements, nr_error_vals, "rx-", label="Root Radius Refinement")
plt.xlabel("Number of Elements")
plt.ylabel("Torsion Constant Error [%]")
plt.legend(loc="center left", bbox_to_anchor=(1, 0.5))
plt.tight_layout()
plt.show() | 0.92348 | 0.756358 |
import pytest
import xarray as xr
from runtime.steppers.machine_learning import (
non_negative_sphum,
update_temperature_tendency_to_conserve_mse,
update_moisture_tendency_to_ensure_non_negative_humidity,
non_negative_sphum_mse_conserving,
)
import vcm
sphum = 1.0e-3 * xr.DataArray(data=[1.0, 1.0, 1.0], dims=["x"]) # type: ignore
zeros = xr.zeros_like(sphum)
dQ2 = -1.0e-5 * xr.DataArray(data=[1.0, 1.0, 1.0], dims=["x"]) # type: ignore
dQ2_mixed = -1.0e-5 * xr.DataArray(data=[1.0, 2.0, 3.0], dims=["x"]) # type: ignore
dQ1 = 1.0e-2 * xr.DataArray(data=[1.0, 1.0, 1.0], dims=["x"]) # type: ignore
dQ1_reduced = 1.0e-2 * xr.DataArray( # type: ignore
data=[1.0, 0.5, 1.0 / 3.0], dims=["x"]
)
timestep = 100.0
@pytest.mark.parametrize(
["sphum", "dQ1", "dQ2", "dt", "dQ1_expected", "dQ2_expected"],
[
pytest.param(
sphum, zeros, zeros, timestep, zeros, zeros, id="all_zero_tendencies"
),
pytest.param(sphum, dQ1, dQ2, timestep, dQ1, dQ2, id="no_limiting"),
pytest.param(
sphum, dQ1, 2.0 * dQ2, timestep, dQ1 / 2.0, dQ2, id="dQ2_2x_too_big"
),
pytest.param(
sphum, zeros, 2.0 * dQ2, timestep, zeros, dQ2, id="dQ2_2x_too_big_no_dQ1",
),
pytest.param(sphum, dQ1, dQ2_mixed, timestep, dQ1_reduced, dQ2, id="dQ2_mixed"),
pytest.param(
sphum, dQ1, dQ2, 2.0 * timestep, dQ1 / 2.0, dQ2 / 2.0, id="timestep_2x"
),
],
)
def test_non_negative_sphum(sphum, dQ1, dQ2, dt, dQ1_expected, dQ2_expected):
dQ1_updated, dQ2_updated = non_negative_sphum(sphum, dQ1, dQ2, dt)
xr.testing.assert_allclose(dQ1_updated, dQ1_expected)
xr.testing.assert_allclose(dQ2_updated, dQ2_expected)
def test_update_q2_to_ensure_non_negative_humidity():
sphum = xr.DataArray([1, 2])
q2 = xr.DataArray([-3, -1])
dt = 1.0
limited_tendency = update_moisture_tendency_to_ensure_non_negative_humidity(
sphum, q2, dt
)
expected_limited_tendency = xr.DataArray([-1, -1])
xr.testing.assert_identical(limited_tendency, expected_limited_tendency)
def test_update_q1_to_conserve_mse():
q1 = xr.DataArray([-4, 2])
q2 = xr.DataArray([-3, -1])
q2_limited = xr.DataArray([-1, -1])
q1_limited = update_temperature_tendency_to_conserve_mse(q1, q2, q2_limited)
xr.testing.assert_identical(
vcm.moist_static_energy_tendency(q1, q2),
vcm.moist_static_energy_tendency(q1_limited, q2_limited),
)
@pytest.mark.parametrize(
"Q1_is_None", [True, False],
)
def test_non_negative_sphum_mse_conserving(Q1_is_None):
if Q1_is_None:
q2_out, q1_out = non_negative_sphum_mse_conserving(sphum, dQ2, 1, q1=None)
assert q1_out is None
else:
q2_out, q1_out = non_negative_sphum_mse_conserving(sphum, dQ2, 1, q1=dQ1)
assert isinstance(q1_out, xr.DataArray) | workflows/prognostic_c48_run/tests/test_steppers.py | import pytest
import xarray as xr
from runtime.steppers.machine_learning import (
non_negative_sphum,
update_temperature_tendency_to_conserve_mse,
update_moisture_tendency_to_ensure_non_negative_humidity,
non_negative_sphum_mse_conserving,
)
import vcm
sphum = 1.0e-3 * xr.DataArray(data=[1.0, 1.0, 1.0], dims=["x"]) # type: ignore
zeros = xr.zeros_like(sphum)
dQ2 = -1.0e-5 * xr.DataArray(data=[1.0, 1.0, 1.0], dims=["x"]) # type: ignore
dQ2_mixed = -1.0e-5 * xr.DataArray(data=[1.0, 2.0, 3.0], dims=["x"]) # type: ignore
dQ1 = 1.0e-2 * xr.DataArray(data=[1.0, 1.0, 1.0], dims=["x"]) # type: ignore
dQ1_reduced = 1.0e-2 * xr.DataArray( # type: ignore
data=[1.0, 0.5, 1.0 / 3.0], dims=["x"]
)
timestep = 100.0
@pytest.mark.parametrize(
["sphum", "dQ1", "dQ2", "dt", "dQ1_expected", "dQ2_expected"],
[
pytest.param(
sphum, zeros, zeros, timestep, zeros, zeros, id="all_zero_tendencies"
),
pytest.param(sphum, dQ1, dQ2, timestep, dQ1, dQ2, id="no_limiting"),
pytest.param(
sphum, dQ1, 2.0 * dQ2, timestep, dQ1 / 2.0, dQ2, id="dQ2_2x_too_big"
),
pytest.param(
sphum, zeros, 2.0 * dQ2, timestep, zeros, dQ2, id="dQ2_2x_too_big_no_dQ1",
),
pytest.param(sphum, dQ1, dQ2_mixed, timestep, dQ1_reduced, dQ2, id="dQ2_mixed"),
pytest.param(
sphum, dQ1, dQ2, 2.0 * timestep, dQ1 / 2.0, dQ2 / 2.0, id="timestep_2x"
),
],
)
def test_non_negative_sphum(sphum, dQ1, dQ2, dt, dQ1_expected, dQ2_expected):
dQ1_updated, dQ2_updated = non_negative_sphum(sphum, dQ1, dQ2, dt)
xr.testing.assert_allclose(dQ1_updated, dQ1_expected)
xr.testing.assert_allclose(dQ2_updated, dQ2_expected)
def test_update_q2_to_ensure_non_negative_humidity():
sphum = xr.DataArray([1, 2])
q2 = xr.DataArray([-3, -1])
dt = 1.0
limited_tendency = update_moisture_tendency_to_ensure_non_negative_humidity(
sphum, q2, dt
)
expected_limited_tendency = xr.DataArray([-1, -1])
xr.testing.assert_identical(limited_tendency, expected_limited_tendency)
def test_update_q1_to_conserve_mse():
q1 = xr.DataArray([-4, 2])
q2 = xr.DataArray([-3, -1])
q2_limited = xr.DataArray([-1, -1])
q1_limited = update_temperature_tendency_to_conserve_mse(q1, q2, q2_limited)
xr.testing.assert_identical(
vcm.moist_static_energy_tendency(q1, q2),
vcm.moist_static_energy_tendency(q1_limited, q2_limited),
)
@pytest.mark.parametrize(
"Q1_is_None", [True, False],
)
def test_non_negative_sphum_mse_conserving(Q1_is_None):
if Q1_is_None:
q2_out, q1_out = non_negative_sphum_mse_conserving(sphum, dQ2, 1, q1=None)
assert q1_out is None
else:
q2_out, q1_out = non_negative_sphum_mse_conserving(sphum, dQ2, 1, q1=dQ1)
assert isinstance(q1_out, xr.DataArray) | 0.500977 | 0.632673 |
from pathlib import Path
import abc
import inspect
import time
import tensorflow as tf
from synethesia.framework.model_skeleton import Model
class SessionHandler(object):
def __init__(self, model, model_name, checkpoint_dir="./checkpoints", logdir="./logs", max_saves_to_keep=5):
if not isinstance(model, Model):
raise ValueError(f"Model must be of type 'Model', not {type(model)}")
self.model_name = model_name
self._checkpoint_dir = checkpoint_dir
self._logdir = logdir
self.max_saves_to_keep = max_saves_to_keep
self.model = model
self._session = None
self._saver = None
self._running_model = None
self._summary_writer = None
Path(self.checkpoint_dir).mkdir(parents=True, exist_ok=True)
Path(self.log_dir).mkdir(parents=True, exist_ok=True)
def _raise_on_uninitialized(func):
def _assert_initialization(self, *args, **kwargs):
if (self._session is None or self._saver is None
or self._summary_writer is None):
raise AttributeError("Can not use SessionHandler without active context manager.")
return func(self, *args, **kwargs)
return _assert_initialization
@property
@_raise_on_uninitialized
def session(self):
return self._session
@property
@_raise_on_uninitialized
def saver(self):
return self._saver
@property
@_raise_on_uninitialized
def running_model(self):
return self._running_model
@property
@_raise_on_uninitialized
def summary_writer(self):
return self._summary_writer
@property
def step(self):
return tf.train.global_step(sess=self.session, global_step_tensor=self.model.global_step)
@property
def checkpoint_dir(self):
return str(Path(self._checkpoint_dir) / self.model_name)
@property
def checkpoint_file(self):
return str((Path(self._checkpoint_dir) / self.model_name) / "checkpoint.ckpt")
@property
def log_dir(self):
return str(Path(self._logdir) / self.model_name)
def __enter__(self):
self.model.initialize()
# TODO allow a debug session instead
session = tf.Session().__enter__()
summary_writer = tf.summary.FileWriter(self.log_dir)
saver = tf.train.Saver(max_to_keep=self.max_saves_to_keep)
self._session = session
self._saver = saver
self._summary_writer = summary_writer
return self
def __exit__(self, *args, **kwargs):
self._session.__exit__(*args, **kwargs)
def training_step(self, feed_dict, additional_ops=()):
ops_to_run = [self.model.training_summary, self.model.optimizer]
ops_to_run.extend(additional_ops)
results = self.session.run(ops_to_run, feed_dict=feed_dict)
summary = results[0]
step = self.step
self.summary_writer.add_summary(summary, step)
return (step, results[2:]) if additional_ops else (step, None)
def inference_step(self, feed_dict, additional_ops=()):
ops_to_run = [self.model.data_output]
ops_to_run.extend(additional_ops)
results = self.session.run(ops_to_run, feed_dict=feed_dict)
return results if additional_ops else results[0]
def save(self, step=None):
step = self.step if step is None else step
pth = self.saver.save(self.session, self.checkpoint_file, step)
return pth
def load_weights_or_init(self):
ckpt = tf.train.get_checkpoint_state(self.checkpoint_dir)
if ckpt and ckpt.model_checkpoint_path:
print(f"Loading existing model {self.model_name} from {self.checkpoint_dir}")
self.saver.restore(self.session, ckpt.model_checkpoint_path)
else:
print(f"Initializing new model {self.model_name}")
self.session.run(tf.global_variables_initializer())
class SessionHook():
def __init__(self, f, p=None, y=None):
self.f = f
self.p = (lambda _: ()) if p is None else p
self.y = y
self.y_requirements = list(inspect.signature(y).parameters)[1:] if y is not None else ()
self.f_requirements = list(inspect.signature(f).parameters)[1:]
def __get__(self, obj, objtype):
# Needed to be able to decorate instance methods
return functools.partial(self.__call__, obj)
def __call__(obj, self, **kwargs):
kwargs.pop("self", None)
arguments = {key: kwargs[key] for key in obj.f_requirements}
provided = obj.p(self)
provisions = obj.f(self, **arguments)
if not isinstance(provisions, tuple):
provisions = (provisions, )
return {var: provisions[i] for i, var in enumerate(provided)}
def get_yieldables(obj, self, **kwargs):
if obj.y is None:
return lambda **_: None
kwargs.pop("self", None)
arguments = {key: kwargs[key] for key in obj.y_requirements}
provisions = obj.y(self, **arguments)
return provisions
def provides(self, p):
return SessionHook(f=self.f, p=p, y=self.y)
def yields(self, y):
return SessionHook(f=self.f, p=self.p, y=y)
class Hookable(type):
def __init__(cls, name, bases, nmspc):
cls.hooks = []
super().__init__(name, bases, nmspc)
for name, func in nmspc.items():
if isinstance(func, SessionHook):
cls.hooks.append(func)
class CustomSession(object, metaclass=Hookable):
def __init__(self, model):
self.model = model
def utilize_session(self, model_name, data_provider, **kwargs):
with SessionHandler(model=self.model, model_name=model_name) as session_handler:
session_handler.load_weights_or_init()
start_time = time.time()
step = session_handler.step
available = locals()
available.pop("self", None)
available.update(kwargs)
print(f"{'Resuming' if step > 0 else 'Starting'} {model_name}: at step {step}")
for input_feature in data_provider:
available["input_feature"] = input_feature
for hook in self.hooks:
provided = hook(self=self, **available)
available.update(provided)
yield hook.get_yieldables(self=self, **available) | synethesia/framework/session_management.py | from pathlib import Path
import abc
import inspect
import time
import tensorflow as tf
from synethesia.framework.model_skeleton import Model
class SessionHandler(object):
def __init__(self, model, model_name, checkpoint_dir="./checkpoints", logdir="./logs", max_saves_to_keep=5):
if not isinstance(model, Model):
raise ValueError(f"Model must be of type 'Model', not {type(model)}")
self.model_name = model_name
self._checkpoint_dir = checkpoint_dir
self._logdir = logdir
self.max_saves_to_keep = max_saves_to_keep
self.model = model
self._session = None
self._saver = None
self._running_model = None
self._summary_writer = None
Path(self.checkpoint_dir).mkdir(parents=True, exist_ok=True)
Path(self.log_dir).mkdir(parents=True, exist_ok=True)
def _raise_on_uninitialized(func):
def _assert_initialization(self, *args, **kwargs):
if (self._session is None or self._saver is None
or self._summary_writer is None):
raise AttributeError("Can not use SessionHandler without active context manager.")
return func(self, *args, **kwargs)
return _assert_initialization
@property
@_raise_on_uninitialized
def session(self):
return self._session
@property
@_raise_on_uninitialized
def saver(self):
return self._saver
@property
@_raise_on_uninitialized
def running_model(self):
return self._running_model
@property
@_raise_on_uninitialized
def summary_writer(self):
return self._summary_writer
@property
def step(self):
return tf.train.global_step(sess=self.session, global_step_tensor=self.model.global_step)
@property
def checkpoint_dir(self):
return str(Path(self._checkpoint_dir) / self.model_name)
@property
def checkpoint_file(self):
return str((Path(self._checkpoint_dir) / self.model_name) / "checkpoint.ckpt")
@property
def log_dir(self):
return str(Path(self._logdir) / self.model_name)
def __enter__(self):
self.model.initialize()
# TODO allow a debug session instead
session = tf.Session().__enter__()
summary_writer = tf.summary.FileWriter(self.log_dir)
saver = tf.train.Saver(max_to_keep=self.max_saves_to_keep)
self._session = session
self._saver = saver
self._summary_writer = summary_writer
return self
def __exit__(self, *args, **kwargs):
self._session.__exit__(*args, **kwargs)
def training_step(self, feed_dict, additional_ops=()):
ops_to_run = [self.model.training_summary, self.model.optimizer]
ops_to_run.extend(additional_ops)
results = self.session.run(ops_to_run, feed_dict=feed_dict)
summary = results[0]
step = self.step
self.summary_writer.add_summary(summary, step)
return (step, results[2:]) if additional_ops else (step, None)
def inference_step(self, feed_dict, additional_ops=()):
ops_to_run = [self.model.data_output]
ops_to_run.extend(additional_ops)
results = self.session.run(ops_to_run, feed_dict=feed_dict)
return results if additional_ops else results[0]
def save(self, step=None):
step = self.step if step is None else step
pth = self.saver.save(self.session, self.checkpoint_file, step)
return pth
def load_weights_or_init(self):
ckpt = tf.train.get_checkpoint_state(self.checkpoint_dir)
if ckpt and ckpt.model_checkpoint_path:
print(f"Loading existing model {self.model_name} from {self.checkpoint_dir}")
self.saver.restore(self.session, ckpt.model_checkpoint_path)
else:
print(f"Initializing new model {self.model_name}")
self.session.run(tf.global_variables_initializer())
class SessionHook():
def __init__(self, f, p=None, y=None):
self.f = f
self.p = (lambda _: ()) if p is None else p
self.y = y
self.y_requirements = list(inspect.signature(y).parameters)[1:] if y is not None else ()
self.f_requirements = list(inspect.signature(f).parameters)[1:]
def __get__(self, obj, objtype):
# Needed to be able to decorate instance methods
return functools.partial(self.__call__, obj)
def __call__(obj, self, **kwargs):
kwargs.pop("self", None)
arguments = {key: kwargs[key] for key in obj.f_requirements}
provided = obj.p(self)
provisions = obj.f(self, **arguments)
if not isinstance(provisions, tuple):
provisions = (provisions, )
return {var: provisions[i] for i, var in enumerate(provided)}
def get_yieldables(obj, self, **kwargs):
if obj.y is None:
return lambda **_: None
kwargs.pop("self", None)
arguments = {key: kwargs[key] for key in obj.y_requirements}
provisions = obj.y(self, **arguments)
return provisions
def provides(self, p):
return SessionHook(f=self.f, p=p, y=self.y)
def yields(self, y):
return SessionHook(f=self.f, p=self.p, y=y)
class Hookable(type):
def __init__(cls, name, bases, nmspc):
cls.hooks = []
super().__init__(name, bases, nmspc)
for name, func in nmspc.items():
if isinstance(func, SessionHook):
cls.hooks.append(func)
class CustomSession(object, metaclass=Hookable):
def __init__(self, model):
self.model = model
def utilize_session(self, model_name, data_provider, **kwargs):
with SessionHandler(model=self.model, model_name=model_name) as session_handler:
session_handler.load_weights_or_init()
start_time = time.time()
step = session_handler.step
available = locals()
available.pop("self", None)
available.update(kwargs)
print(f"{'Resuming' if step > 0 else 'Starting'} {model_name}: at step {step}")
for input_feature in data_provider:
available["input_feature"] = input_feature
for hook in self.hooks:
provided = hook(self=self, **available)
available.update(provided)
yield hook.get_yieldables(self=self, **available) | 0.719581 | 0.212212 |
import re
import sys
import time
from urllib.request import urlopen
import cv2
import numpy as np
def process_stream(url, processor):
connected = False
while True:
if connected:
print("Disconnected from", url)
connected = False
stream = None
try:
stream = urlopen(url)
except:
time.sleep(0.5)
continue
connected = True
print("Connected to", url)
try:
_read_stream(stream, processor)
except Exception as e:
print("Exception:", e)
if stream is not None:
try:
stream.close()
except:
pass
def _read_stream(stream, processor):
# Read the boundary message and discard
stream.readline()
sz = 0
rdbuffer = None
clen_re = re.compile(b'Content-Length: (\d+)\\r\\n')
# Read each frame
# TODO: This is hardcoded to mjpg-streamer's behavior
while True:
stream.readline() # content type
try: # content length
m = clen_re.match(stream.readline())
clen = int(m.group(1))
except:
return
stream.readline() # timestamp
stream.readline() # empty line
# Reallocate buffer if necessary
if clen > sz:
sz = clen*2
rdbuffer = bytearray(sz)
rdview = memoryview(rdbuffer)
# Read frame into the preallocated buffer
stream.readinto(rdview[:clen])
stream.readline() # endline
stream.readline() # boundary
# Do something with the image if required, else discard
if processor.should_process():
img = cv2.imdecode(np.frombuffer(rdbuffer, count=clen, dtype=np.byte), flags=cv2.IMREAD_COLOR)
processor.process(img)
if __name__ == '__main__':
from main import NoOpProcessor
process_stream(sys.argv[1], NoOpProcessor()) | robot-vision/mjpg_client.py |
import re
import sys
import time
from urllib.request import urlopen
import cv2
import numpy as np
def process_stream(url, processor):
connected = False
while True:
if connected:
print("Disconnected from", url)
connected = False
stream = None
try:
stream = urlopen(url)
except:
time.sleep(0.5)
continue
connected = True
print("Connected to", url)
try:
_read_stream(stream, processor)
except Exception as e:
print("Exception:", e)
if stream is not None:
try:
stream.close()
except:
pass
def _read_stream(stream, processor):
# Read the boundary message and discard
stream.readline()
sz = 0
rdbuffer = None
clen_re = re.compile(b'Content-Length: (\d+)\\r\\n')
# Read each frame
# TODO: This is hardcoded to mjpg-streamer's behavior
while True:
stream.readline() # content type
try: # content length
m = clen_re.match(stream.readline())
clen = int(m.group(1))
except:
return
stream.readline() # timestamp
stream.readline() # empty line
# Reallocate buffer if necessary
if clen > sz:
sz = clen*2
rdbuffer = bytearray(sz)
rdview = memoryview(rdbuffer)
# Read frame into the preallocated buffer
stream.readinto(rdview[:clen])
stream.readline() # endline
stream.readline() # boundary
# Do something with the image if required, else discard
if processor.should_process():
img = cv2.imdecode(np.frombuffer(rdbuffer, count=clen, dtype=np.byte), flags=cv2.IMREAD_COLOR)
processor.process(img)
if __name__ == '__main__':
from main import NoOpProcessor
process_stream(sys.argv[1], NoOpProcessor()) | 0.175962 | 0.073897 |
from PIL import Image
import numpy as np
import glob
import os
from util import image_augmenter as ia
class Loader(object):
def __init__(self, dir_original, dir_segmented, init_size=(256, 256), one_hot=True):
self._data = Loader.import_data(dir_original, dir_segmented, init_size, one_hot)
def get_all_dataset(self):
return self._data
def load_train_test(self, train_rate=0.85, shuffle=True, transpose_by_color=False):
"""
`Load datasets splited into training set and test set.
Args:
train_rate (float): Training rate.
shuffle (bool): If true, shuffle dataset.
transpose_by_color (bool): If True, transpose images for chainer. [channel][width][height]
Returns:
Training Set (Dataset), Test Set (Dataset)
"""
if train_rate < 0.0 or train_rate > 1.0:
raise ValueError("train_rate must be from 0.0 to 1.0.")
if transpose_by_color:
self._data.transpose_by_color()
if shuffle:
self._data.shuffle()
train_size = int(self._data.images_original.shape[0] * train_rate)
data_size = int(len(self._data.images_original))
train_set = self._data.perm(0, train_size)
test_set = self._data.perm(train_size, data_size)
return train_set, test_set
@staticmethod
def import_data(dir_original, dir_segmented, init_size=None, one_hot=True):
# Generate paths of images to load
paths_original, paths_segmented = Loader.generate_paths(dir_original, dir_segmented)
# Extract images to ndarray using paths
images_original, images_segmented = Loader.extract_images(paths_original, paths_segmented, init_size, one_hot)
# Get a color palette !!!CHANGED PALETTE!!!
image_sample_palette = Image.open("data_set/palette.png")
palette = image_sample_palette.getpalette()
return DataSet(images_original, images_segmented, palette,
augmenter=ia.ImageAugmenter(size=init_size, class_count=len(DataSet.CATEGORY)))
@staticmethod
def generate_paths(dir_original, dir_segmented):
paths_original = glob.glob(dir_original + "/*")
paths_segmented = glob.glob(dir_segmented + "/*")
if len(paths_original) == 0 or len(paths_segmented) == 0:
raise FileNotFoundError("Could not load images.")
filenames = list(map(lambda path: path.split(os.sep)[-1].split(".")[0], paths_segmented))
paths_original = list(map(lambda filename: dir_original + "/" + filename + ".jpg", filenames))
return paths_original, paths_segmented
@staticmethod
def extract_images(paths_original, paths_segmented, init_size, one_hot):
images_original, images_segmented = [], []
# Load images from directory_path using generator
print("Loading original images", end="", flush=True)
for image in Loader.image_generator(paths_original, init_size, antialias=True):
images_original.append(image)
if len(images_original) % 200 == 0:
print(".", end="", flush=True)
print(" Completed", flush=True)
print("Loading segmented images", end="", flush=True)
for image in Loader.image_generator(paths_segmented, init_size, normalization=False):
images_segmented.append(image)
if len(images_segmented) % 200 == 0:
print(".", end="", flush=True)
print(" Completed")
print("len(images_original): ", len(images_original))
print("len(images_segmented): ", len(images_segmented))
assert len(images_original) == len(images_segmented)
# Cast to ndarray
images_original = np.asarray(images_original, dtype=np.float32)
images_segmented = np.asarray(images_segmented, dtype=np.uint8)
# !!!CHANGED!!!
# Change indices which correspond to "void" from 255
# images_segmented = np.where((images_segmented != 15) & (images_segmented != 255), 0, images_segmented)
# images_segmented = np.where(images_segmented == 15, 1, images_segmented)
# images_segmented = np.where(images_segmented == 255, len(DataSet.CATEGORY)-1, images_segmented)
# One hot encoding using identity matrix.
if one_hot:
print("Casting to one-hot encoding... ", end="", flush=True)
identity = np.identity(len(DataSet.CATEGORY), dtype=np.uint8)
images_segmented = identity[images_segmented]
print("Done")
else:
pass
return images_original, images_segmented
@staticmethod
def cast_to_index(ndarray):
return np.argmax(ndarray, axis=2)
@staticmethod
def cast_to_onehot(ndarray):
identity = np.identity(len(DataSet.CATEGORY), dtype=np.uint8)
return identity[ndarray]
@staticmethod
def image_generator(file_paths, init_size=None, normalization=True, antialias=False):
"""
`A generator which yields images deleted an alpha channel and resized.
Args:
file_paths (list[string]): File paths you want load.
init_size (tuple(int, int)): If having a value, images are resized by init_size.
normalization (bool): If true, normalize images.
antialias (bool): Antialias.
Yields:
image (ndarray[width][height][channel]): Processed image
"""
for file_path in file_paths:
if file_path.endswith(".png") or file_path.endswith(".jpg"):
# open a image
image = Image.open(file_path)
# to square
image = Loader.crop_to_square(image)
# resize by init_size
if init_size is not None and init_size != image.size:
if antialias:
image = image.resize(init_size, Image.ANTIALIAS)
else:
image = image.resize(init_size)
# delete alpha channel
if image.mode == "RGBA":
image = image.convert("RGB")
image = np.asarray(image)
if normalization:
image = image / 255.0
yield image
@staticmethod
def crop_to_square(image):
size = min(image.size)
left, upper = (image.width - size) // 2, (image.height - size) // 2
right, bottom = (image.width + size) // 2, (image.height + size) // 2
return image.crop((left, upper, right, bottom))
class DataSet(object):
CATEGORY = (
"void",
"Bed",
"Books",
"Ceiling",
"Chair",
"Floor",
"Furniture",
"Objects",
"Picture",
"Sofa",
"Table",
"TV",
"Wall",
"Window"
)
def __init__(self, images_original, images_segmented, image_palette, augmenter=None):
assert len(images_original) == len(images_segmented), "images and labels must have same length."
self._images_original = images_original
self._images_segmented = images_segmented
self._image_palette = image_palette
self._augmenter = augmenter
@property
def images_original(self):
return self._images_original
@property
def images_segmented(self):
return self._images_segmented
@property
def palette(self):
return self._image_palette
@property
def length(self):
return len(self._images_original)
@staticmethod
def length_category():
return len(DataSet.CATEGORY)
def print_information(self):
print("****** Dataset Information ******")
print("[Number of Images]", len(self._images_original))
def __add__(self, other):
images_original = np.concatenate([self.images_original, other.images_original])
images_segmented = np.concatenate([self.images_segmented, other.images_segmented])
return DataSet(images_original, images_segmented, self._image_palette, self._augmenter)
def shuffle(self):
idx = np.arange(self._images_original.shape[0])
np.random.shuffle(idx)
self._images_original, self._images_segmented = self._images_original[idx], self._images_segmented[idx]
def transpose_by_color(self):
self._images_original = self._images_original.transpose(0, 3, 1, 2)
self._images_segmented = self._images_segmented.transpose(0, 3, 1, 2)
def perm(self, start, end):
end = min(end, len(self._images_original))
return DataSet(self._images_original[start:end], self._images_segmented[start:end], self._image_palette,
self._augmenter)
def __call__(self, batch_size=20, shuffle=True, augment=True):
"""
`A generator which yields a batch. The batch is shuffled as default.
Args:
batch_size (int): batch size.
shuffle (bool): If True, randomize batch datas.
Yields:
batch (ndarray[][][]): A batch data.
"""
if batch_size < 1:
raise ValueError("batch_size must be more than 1.")
if shuffle:
self.shuffle()
for start in range(0, self.length, batch_size):
batch = self.perm(start, start+batch_size)
if augment:
assert self._augmenter is not None, "you have to set an augmenter."
yield self._augmenter.augment_dataset(batch, method=[ia.ImageAugmenter.NONE, ia.ImageAugmenter.FLIP])
else:
yield batch
if __name__ == "__main__":
dataset_loader = Loader(dir_original="../data_set/VOCdevkit/person/JPEGImages",
dir_segmented="../data_set/VOCdevkit/person/SegmentationClass")
train, test = dataset_loader.load_train_test()
train.print_information()
test.print_information() | util/loader.py | from PIL import Image
import numpy as np
import glob
import os
from util import image_augmenter as ia
class Loader(object):
def __init__(self, dir_original, dir_segmented, init_size=(256, 256), one_hot=True):
self._data = Loader.import_data(dir_original, dir_segmented, init_size, one_hot)
def get_all_dataset(self):
return self._data
def load_train_test(self, train_rate=0.85, shuffle=True, transpose_by_color=False):
"""
`Load datasets splited into training set and test set.
Args:
train_rate (float): Training rate.
shuffle (bool): If true, shuffle dataset.
transpose_by_color (bool): If True, transpose images for chainer. [channel][width][height]
Returns:
Training Set (Dataset), Test Set (Dataset)
"""
if train_rate < 0.0 or train_rate > 1.0:
raise ValueError("train_rate must be from 0.0 to 1.0.")
if transpose_by_color:
self._data.transpose_by_color()
if shuffle:
self._data.shuffle()
train_size = int(self._data.images_original.shape[0] * train_rate)
data_size = int(len(self._data.images_original))
train_set = self._data.perm(0, train_size)
test_set = self._data.perm(train_size, data_size)
return train_set, test_set
@staticmethod
def import_data(dir_original, dir_segmented, init_size=None, one_hot=True):
# Generate paths of images to load
paths_original, paths_segmented = Loader.generate_paths(dir_original, dir_segmented)
# Extract images to ndarray using paths
images_original, images_segmented = Loader.extract_images(paths_original, paths_segmented, init_size, one_hot)
# Get a color palette !!!CHANGED PALETTE!!!
image_sample_palette = Image.open("data_set/palette.png")
palette = image_sample_palette.getpalette()
return DataSet(images_original, images_segmented, palette,
augmenter=ia.ImageAugmenter(size=init_size, class_count=len(DataSet.CATEGORY)))
@staticmethod
def generate_paths(dir_original, dir_segmented):
paths_original = glob.glob(dir_original + "/*")
paths_segmented = glob.glob(dir_segmented + "/*")
if len(paths_original) == 0 or len(paths_segmented) == 0:
raise FileNotFoundError("Could not load images.")
filenames = list(map(lambda path: path.split(os.sep)[-1].split(".")[0], paths_segmented))
paths_original = list(map(lambda filename: dir_original + "/" + filename + ".jpg", filenames))
return paths_original, paths_segmented
@staticmethod
def extract_images(paths_original, paths_segmented, init_size, one_hot):
images_original, images_segmented = [], []
# Load images from directory_path using generator
print("Loading original images", end="", flush=True)
for image in Loader.image_generator(paths_original, init_size, antialias=True):
images_original.append(image)
if len(images_original) % 200 == 0:
print(".", end="", flush=True)
print(" Completed", flush=True)
print("Loading segmented images", end="", flush=True)
for image in Loader.image_generator(paths_segmented, init_size, normalization=False):
images_segmented.append(image)
if len(images_segmented) % 200 == 0:
print(".", end="", flush=True)
print(" Completed")
print("len(images_original): ", len(images_original))
print("len(images_segmented): ", len(images_segmented))
assert len(images_original) == len(images_segmented)
# Cast to ndarray
images_original = np.asarray(images_original, dtype=np.float32)
images_segmented = np.asarray(images_segmented, dtype=np.uint8)
# !!!CHANGED!!!
# Change indices which correspond to "void" from 255
# images_segmented = np.where((images_segmented != 15) & (images_segmented != 255), 0, images_segmented)
# images_segmented = np.where(images_segmented == 15, 1, images_segmented)
# images_segmented = np.where(images_segmented == 255, len(DataSet.CATEGORY)-1, images_segmented)
# One hot encoding using identity matrix.
if one_hot:
print("Casting to one-hot encoding... ", end="", flush=True)
identity = np.identity(len(DataSet.CATEGORY), dtype=np.uint8)
images_segmented = identity[images_segmented]
print("Done")
else:
pass
return images_original, images_segmented
@staticmethod
def cast_to_index(ndarray):
return np.argmax(ndarray, axis=2)
@staticmethod
def cast_to_onehot(ndarray):
identity = np.identity(len(DataSet.CATEGORY), dtype=np.uint8)
return identity[ndarray]
@staticmethod
def image_generator(file_paths, init_size=None, normalization=True, antialias=False):
"""
`A generator which yields images deleted an alpha channel and resized.
Args:
file_paths (list[string]): File paths you want load.
init_size (tuple(int, int)): If having a value, images are resized by init_size.
normalization (bool): If true, normalize images.
antialias (bool): Antialias.
Yields:
image (ndarray[width][height][channel]): Processed image
"""
for file_path in file_paths:
if file_path.endswith(".png") or file_path.endswith(".jpg"):
# open a image
image = Image.open(file_path)
# to square
image = Loader.crop_to_square(image)
# resize by init_size
if init_size is not None and init_size != image.size:
if antialias:
image = image.resize(init_size, Image.ANTIALIAS)
else:
image = image.resize(init_size)
# delete alpha channel
if image.mode == "RGBA":
image = image.convert("RGB")
image = np.asarray(image)
if normalization:
image = image / 255.0
yield image
@staticmethod
def crop_to_square(image):
size = min(image.size)
left, upper = (image.width - size) // 2, (image.height - size) // 2
right, bottom = (image.width + size) // 2, (image.height + size) // 2
return image.crop((left, upper, right, bottom))
class DataSet(object):
CATEGORY = (
"void",
"Bed",
"Books",
"Ceiling",
"Chair",
"Floor",
"Furniture",
"Objects",
"Picture",
"Sofa",
"Table",
"TV",
"Wall",
"Window"
)
def __init__(self, images_original, images_segmented, image_palette, augmenter=None):
assert len(images_original) == len(images_segmented), "images and labels must have same length."
self._images_original = images_original
self._images_segmented = images_segmented
self._image_palette = image_palette
self._augmenter = augmenter
@property
def images_original(self):
return self._images_original
@property
def images_segmented(self):
return self._images_segmented
@property
def palette(self):
return self._image_palette
@property
def length(self):
return len(self._images_original)
@staticmethod
def length_category():
return len(DataSet.CATEGORY)
def print_information(self):
print("****** Dataset Information ******")
print("[Number of Images]", len(self._images_original))
def __add__(self, other):
images_original = np.concatenate([self.images_original, other.images_original])
images_segmented = np.concatenate([self.images_segmented, other.images_segmented])
return DataSet(images_original, images_segmented, self._image_palette, self._augmenter)
def shuffle(self):
idx = np.arange(self._images_original.shape[0])
np.random.shuffle(idx)
self._images_original, self._images_segmented = self._images_original[idx], self._images_segmented[idx]
def transpose_by_color(self):
self._images_original = self._images_original.transpose(0, 3, 1, 2)
self._images_segmented = self._images_segmented.transpose(0, 3, 1, 2)
def perm(self, start, end):
end = min(end, len(self._images_original))
return DataSet(self._images_original[start:end], self._images_segmented[start:end], self._image_palette,
self._augmenter)
def __call__(self, batch_size=20, shuffle=True, augment=True):
"""
`A generator which yields a batch. The batch is shuffled as default.
Args:
batch_size (int): batch size.
shuffle (bool): If True, randomize batch datas.
Yields:
batch (ndarray[][][]): A batch data.
"""
if batch_size < 1:
raise ValueError("batch_size must be more than 1.")
if shuffle:
self.shuffle()
for start in range(0, self.length, batch_size):
batch = self.perm(start, start+batch_size)
if augment:
assert self._augmenter is not None, "you have to set an augmenter."
yield self._augmenter.augment_dataset(batch, method=[ia.ImageAugmenter.NONE, ia.ImageAugmenter.FLIP])
else:
yield batch
if __name__ == "__main__":
dataset_loader = Loader(dir_original="../data_set/VOCdevkit/person/JPEGImages",
dir_segmented="../data_set/VOCdevkit/person/SegmentationClass")
train, test = dataset_loader.load_train_test()
train.print_information()
test.print_information() | 0.632162 | 0.332934 |
from typing import Iterable, cast
import numpy as np
import pytest
import sympy
import cirq
def assert_optimizes(before: cirq.Circuit,
expected: cirq.Circuit,
compare_unitaries: bool = True,
eject_parameterized: bool = False):
opt = cirq.EjectPhasedPaulis(eject_parameterized=eject_parameterized)
circuit = before.copy()
opt.optimize_circuit(circuit)
# They should have equivalent effects.
if compare_unitaries:
if cirq.is_parameterized(circuit):
for a in (0, 0.1, 0.5, -1.0, np.pi, np.pi / 2):
params = {'x': a, 'y': a / 2, 'z': -2 * a}
(cirq.testing.
assert_circuits_with_terminal_measurements_are_equivalent(
cirq.resolve_parameters(circuit, params),
cirq.resolve_parameters(expected, params), 1e-8))
else:
(cirq.testing.
assert_circuits_with_terminal_measurements_are_equivalent(
circuit, expected, 1e-8))
# And match the expected circuit.
assert circuit == expected, (
"Circuit wasn't optimized as expected.\n"
"INPUT:\n"
"{}\n"
"\n"
"EXPECTED OUTPUT:\n"
"{}\n"
"\n"
"ACTUAL OUTPUT:\n"
"{}\n"
"\n"
"EXPECTED OUTPUT (detailed):\n"
"{!r}\n"
"\n"
"ACTUAL OUTPUT (detailed):\n"
"{!r}").format(before, expected, circuit, expected, circuit)
# And it should be idempotent.
opt.optimize_circuit(circuit)
assert circuit == expected
def quick_circuit(*moments: Iterable[cirq.OP_TREE]) -> cirq.Circuit:
return cirq.Circuit([
cirq.Moment(cast(Iterable[cirq.Operation], cirq.flatten_op_tree(m)))
for m in moments])
def test_absorbs_z():
q = cirq.NamedQubit('q')
x = sympy.Symbol('x')
# Full Z.
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.125).on(q)],
[cirq.Z(q)],
),
expected=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.625).on(q)],
[],
))
# Partial Z.
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.125).on(q)],
[cirq.S(q)],
),
expected=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.375).on(q)],
[],
))
# parameterized Z.
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.125).on(q)],
[cirq.Z(q)**x],
),
expected=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.125 + x / 2).on(q)],
[],
),
eject_parameterized=True)
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.125).on(q)],
[cirq.Z(q)**(x + 1)],
),
expected=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.625 + x / 2).on(q)],
[],
),
eject_parameterized=True)
# Multiple Zs.
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.125).on(q)],
[cirq.S(q)],
[cirq.T(q)**-1],
),
expected=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.25).on(q)],
[],
[],
))
# Multiple Parameterized Zs.
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.125).on(q)],
[cirq.S(q)**x],
[cirq.T(q)**-x],
),
expected=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.125 + x * 0.125).on(q)],
[],
[],
),
eject_parameterized=True)
# Parameterized Phase and Partial Z
assert_optimizes(before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=x).on(q)],
[cirq.S(q)],
),
expected=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=x + 0.25).on(q)],
[],
),
eject_parameterized=True)
def test_crosses_czs():
a = cirq.NamedQubit('a')
b = cirq.NamedQubit('b')
x = sympy.Symbol('x')
y = sympy.Symbol('y')
z = sympy.Symbol('z')
# Full CZ.
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.25).on(a)],
[cirq.CZ(a, b)],
),
expected=quick_circuit(
[cirq.Z(b)],
[cirq.CZ(a, b)],
[cirq.PhasedXPowGate(phase_exponent=0.25).on(a)],
))
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.125).on(a)],
[cirq.CZ(b, a)],
),
expected=quick_circuit(
[cirq.Z(b)],
[cirq.CZ(a, b)],
[cirq.PhasedXPowGate(phase_exponent=0.125).on(a)],
))
assert_optimizes(before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=x).on(a)],
[cirq.CZ(b, a)],
),
expected=quick_circuit(
[cirq.Z(b)],
[cirq.CZ(a, b)],
[cirq.PhasedXPowGate(phase_exponent=x).on(a)],
),
eject_parameterized=True)
# Partial CZ.
assert_optimizes(
before=quick_circuit(
[cirq.X(a)],
[cirq.CZ(a, b)**0.25],
),
expected=quick_circuit(
[cirq.Z(b)**0.25],
[cirq.CZ(a, b)**-0.25],
[cirq.X(a)],
))
assert_optimizes(before=quick_circuit(
[cirq.X(a)],
[cirq.CZ(a, b)**x],
),
expected=quick_circuit(
[cirq.Z(b)**x],
[cirq.CZ(a, b)**-x],
[cirq.X(a)],
),
eject_parameterized=True)
# Double cross.
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.125).on(a)],
[cirq.PhasedXPowGate(phase_exponent=0.375).on(b)],
[cirq.CZ(a, b)**0.25],
),
expected=quick_circuit(
[],
[],
[cirq.CZ(a, b)**0.25],
[cirq.PhasedXPowGate(phase_exponent=0.5).on(b),
cirq.PhasedXPowGate(phase_exponent=0.25).on(a)],
))
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=x).on(a)],
[cirq.PhasedXPowGate(phase_exponent=y).on(b)],
[cirq.CZ(a, b)**z],
),
expected=quick_circuit(
[],
[],
[cirq.CZ(a, b)**z],
[
cirq.PhasedXPowGate(phase_exponent=y + z / 2).on(b),
cirq.PhasedXPowGate(phase_exponent=x + z / 2).on(a)
],
),
eject_parameterized=True)
def test_toggles_measurements():
a = cirq.NamedQubit('a')
b = cirq.NamedQubit('b')
x = sympy.Symbol('x')
# Single.
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.25).on(a)],
[cirq.measure(a, b)],
),
expected=quick_circuit(
[],
[cirq.measure(a, b, invert_mask=(True,))],
))
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.25).on(b)],
[cirq.measure(a, b)],
),
expected=quick_circuit(
[],
[cirq.measure(a, b, invert_mask=(False, True))],
))
assert_optimizes(before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=x).on(b)],
[cirq.measure(a, b)],
),
expected=quick_circuit(
[],
[cirq.measure(a, b, invert_mask=(False, True))],
),
eject_parameterized=True)
# Multiple.
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.25).on(a)],
[cirq.PhasedXPowGate(phase_exponent=0.25).on(b)],
[cirq.measure(a, b)],
),
expected=quick_circuit(
[],
[],
[cirq.measure(a, b, invert_mask=(True, True))],
))
# Xmon.
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.25).on(a)],
[cirq.measure(a, b, key='t')],
),
expected=quick_circuit(
[],
[cirq.measure(a, b, invert_mask=(True,), key='t')],
))
def test_cancels_other_full_w():
q = cirq.NamedQubit('q')
x = sympy.Symbol('x')
y = sympy.Symbol('y')
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.25).on(q)],
[cirq.PhasedXPowGate(phase_exponent=0.25).on(q)],
),
expected=quick_circuit(
[],
[],
))
assert_optimizes(before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=x).on(q)],
[cirq.PhasedXPowGate(phase_exponent=x).on(q)],
),
expected=quick_circuit(
[],
[],
),
eject_parameterized=True)
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.25).on(q)],
[cirq.PhasedXPowGate(phase_exponent=0.125).on(q)],
),
expected=quick_circuit(
[],
[cirq.Z(q)**-0.25],
))
assert_optimizes(
before=quick_circuit(
[cirq.X(q)],
[cirq.PhasedXPowGate(phase_exponent=0.25).on(q)],
),
expected=quick_circuit(
[],
[cirq.Z(q)**0.5],
))
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.25).on(q)],
[cirq.X(q)],
),
expected=quick_circuit(
[],
[cirq.Z(q)**-0.5],
))
assert_optimizes(before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=x).on(q)],
[cirq.PhasedXPowGate(phase_exponent=y).on(q)],
),
expected=quick_circuit(
[],
[cirq.Z(q)**(2 * (y - x))],
),
eject_parameterized=True)
def test_phases_partial_ws():
q = cirq.NamedQubit('q')
x = sympy.Symbol('x')
y = sympy.Symbol('y')
z = sympy.Symbol('z')
assert_optimizes(
before=quick_circuit(
[cirq.X(q)],
[cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(q)],
),
expected=quick_circuit(
[],
[cirq.PhasedXPowGate(phase_exponent=-0.25, exponent=0.5).on(q)],
[cirq.X(q)],
))
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.25).on(q)],
[cirq.X(q)**0.5],
),
expected=quick_circuit(
[],
[cirq.PhasedXPowGate(phase_exponent=0.5, exponent=0.5).on(q)],
[cirq.PhasedXPowGate(phase_exponent=0.25).on(q)],
))
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.25).on(q)],
[cirq.PhasedXPowGate(phase_exponent=0.5, exponent=0.75).on(q)],
),
expected=quick_circuit(
[],
[cirq.X(q)**0.75],
[cirq.PhasedXPowGate(phase_exponent=0.25).on(q)],
))
assert_optimizes(
before=quick_circuit(
[cirq.X(q)],
[cirq.PhasedXPowGate(exponent=-0.25, phase_exponent=0.5).on(q)]
),
expected=quick_circuit(
[],
[cirq.PhasedXPowGate(exponent=-0.25, phase_exponent=-0.5).on(q)],
[cirq.X(q)],
))
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=x).on(q)],
[cirq.PhasedXPowGate(phase_exponent=y, exponent=z).on(q)],
),
expected=quick_circuit(
[],
[cirq.PhasedXPowGate(phase_exponent=2 * x - y, exponent=z).on(q)],
[cirq.PhasedXPowGate(phase_exponent=x).on(q)],
),
eject_parameterized=True)
@pytest.mark.parametrize('sym', [
sympy.Symbol('x'),
sympy.Symbol('x') + 1,
])
def test_blocked_by_unknown_and_symbols(sym):
a = cirq.NamedQubit('a')
b = cirq.NamedQubit('b')
assert_optimizes(
before=quick_circuit(
[cirq.X(a)],
[cirq.SWAP(a, b)],
[cirq.X(a)],
),
expected=quick_circuit(
[cirq.X(a)],
[cirq.SWAP(a, b)],
[cirq.X(a)],
))
assert_optimizes(before=quick_circuit(
[cirq.X(a)],
[cirq.Z(a)**sym],
[cirq.X(a)],
),
expected=quick_circuit(
[cirq.X(a)],
[cirq.Z(a)**sym],
[cirq.X(a)],
),
compare_unitaries=False)
assert_optimizes(before=quick_circuit(
[cirq.X(a)],
[cirq.CZ(a, b)**sym],
[cirq.X(a)],
),
expected=quick_circuit(
[cirq.X(a)],
[cirq.CZ(a, b)**sym],
[cirq.X(a)],
),
compare_unitaries=False) | cirq/optimizers/eject_phased_paulis_test.py | from typing import Iterable, cast
import numpy as np
import pytest
import sympy
import cirq
def assert_optimizes(before: cirq.Circuit,
expected: cirq.Circuit,
compare_unitaries: bool = True,
eject_parameterized: bool = False):
opt = cirq.EjectPhasedPaulis(eject_parameterized=eject_parameterized)
circuit = before.copy()
opt.optimize_circuit(circuit)
# They should have equivalent effects.
if compare_unitaries:
if cirq.is_parameterized(circuit):
for a in (0, 0.1, 0.5, -1.0, np.pi, np.pi / 2):
params = {'x': a, 'y': a / 2, 'z': -2 * a}
(cirq.testing.
assert_circuits_with_terminal_measurements_are_equivalent(
cirq.resolve_parameters(circuit, params),
cirq.resolve_parameters(expected, params), 1e-8))
else:
(cirq.testing.
assert_circuits_with_terminal_measurements_are_equivalent(
circuit, expected, 1e-8))
# And match the expected circuit.
assert circuit == expected, (
"Circuit wasn't optimized as expected.\n"
"INPUT:\n"
"{}\n"
"\n"
"EXPECTED OUTPUT:\n"
"{}\n"
"\n"
"ACTUAL OUTPUT:\n"
"{}\n"
"\n"
"EXPECTED OUTPUT (detailed):\n"
"{!r}\n"
"\n"
"ACTUAL OUTPUT (detailed):\n"
"{!r}").format(before, expected, circuit, expected, circuit)
# And it should be idempotent.
opt.optimize_circuit(circuit)
assert circuit == expected
def quick_circuit(*moments: Iterable[cirq.OP_TREE]) -> cirq.Circuit:
return cirq.Circuit([
cirq.Moment(cast(Iterable[cirq.Operation], cirq.flatten_op_tree(m)))
for m in moments])
def test_absorbs_z():
q = cirq.NamedQubit('q')
x = sympy.Symbol('x')
# Full Z.
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.125).on(q)],
[cirq.Z(q)],
),
expected=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.625).on(q)],
[],
))
# Partial Z.
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.125).on(q)],
[cirq.S(q)],
),
expected=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.375).on(q)],
[],
))
# parameterized Z.
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.125).on(q)],
[cirq.Z(q)**x],
),
expected=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.125 + x / 2).on(q)],
[],
),
eject_parameterized=True)
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.125).on(q)],
[cirq.Z(q)**(x + 1)],
),
expected=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.625 + x / 2).on(q)],
[],
),
eject_parameterized=True)
# Multiple Zs.
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.125).on(q)],
[cirq.S(q)],
[cirq.T(q)**-1],
),
expected=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.25).on(q)],
[],
[],
))
# Multiple Parameterized Zs.
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.125).on(q)],
[cirq.S(q)**x],
[cirq.T(q)**-x],
),
expected=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.125 + x * 0.125).on(q)],
[],
[],
),
eject_parameterized=True)
# Parameterized Phase and Partial Z
assert_optimizes(before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=x).on(q)],
[cirq.S(q)],
),
expected=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=x + 0.25).on(q)],
[],
),
eject_parameterized=True)
def test_crosses_czs():
a = cirq.NamedQubit('a')
b = cirq.NamedQubit('b')
x = sympy.Symbol('x')
y = sympy.Symbol('y')
z = sympy.Symbol('z')
# Full CZ.
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.25).on(a)],
[cirq.CZ(a, b)],
),
expected=quick_circuit(
[cirq.Z(b)],
[cirq.CZ(a, b)],
[cirq.PhasedXPowGate(phase_exponent=0.25).on(a)],
))
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.125).on(a)],
[cirq.CZ(b, a)],
),
expected=quick_circuit(
[cirq.Z(b)],
[cirq.CZ(a, b)],
[cirq.PhasedXPowGate(phase_exponent=0.125).on(a)],
))
assert_optimizes(before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=x).on(a)],
[cirq.CZ(b, a)],
),
expected=quick_circuit(
[cirq.Z(b)],
[cirq.CZ(a, b)],
[cirq.PhasedXPowGate(phase_exponent=x).on(a)],
),
eject_parameterized=True)
# Partial CZ.
assert_optimizes(
before=quick_circuit(
[cirq.X(a)],
[cirq.CZ(a, b)**0.25],
),
expected=quick_circuit(
[cirq.Z(b)**0.25],
[cirq.CZ(a, b)**-0.25],
[cirq.X(a)],
))
assert_optimizes(before=quick_circuit(
[cirq.X(a)],
[cirq.CZ(a, b)**x],
),
expected=quick_circuit(
[cirq.Z(b)**x],
[cirq.CZ(a, b)**-x],
[cirq.X(a)],
),
eject_parameterized=True)
# Double cross.
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.125).on(a)],
[cirq.PhasedXPowGate(phase_exponent=0.375).on(b)],
[cirq.CZ(a, b)**0.25],
),
expected=quick_circuit(
[],
[],
[cirq.CZ(a, b)**0.25],
[cirq.PhasedXPowGate(phase_exponent=0.5).on(b),
cirq.PhasedXPowGate(phase_exponent=0.25).on(a)],
))
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=x).on(a)],
[cirq.PhasedXPowGate(phase_exponent=y).on(b)],
[cirq.CZ(a, b)**z],
),
expected=quick_circuit(
[],
[],
[cirq.CZ(a, b)**z],
[
cirq.PhasedXPowGate(phase_exponent=y + z / 2).on(b),
cirq.PhasedXPowGate(phase_exponent=x + z / 2).on(a)
],
),
eject_parameterized=True)
def test_toggles_measurements():
a = cirq.NamedQubit('a')
b = cirq.NamedQubit('b')
x = sympy.Symbol('x')
# Single.
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.25).on(a)],
[cirq.measure(a, b)],
),
expected=quick_circuit(
[],
[cirq.measure(a, b, invert_mask=(True,))],
))
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.25).on(b)],
[cirq.measure(a, b)],
),
expected=quick_circuit(
[],
[cirq.measure(a, b, invert_mask=(False, True))],
))
assert_optimizes(before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=x).on(b)],
[cirq.measure(a, b)],
),
expected=quick_circuit(
[],
[cirq.measure(a, b, invert_mask=(False, True))],
),
eject_parameterized=True)
# Multiple.
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.25).on(a)],
[cirq.PhasedXPowGate(phase_exponent=0.25).on(b)],
[cirq.measure(a, b)],
),
expected=quick_circuit(
[],
[],
[cirq.measure(a, b, invert_mask=(True, True))],
))
# Xmon.
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.25).on(a)],
[cirq.measure(a, b, key='t')],
),
expected=quick_circuit(
[],
[cirq.measure(a, b, invert_mask=(True,), key='t')],
))
def test_cancels_other_full_w():
q = cirq.NamedQubit('q')
x = sympy.Symbol('x')
y = sympy.Symbol('y')
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.25).on(q)],
[cirq.PhasedXPowGate(phase_exponent=0.25).on(q)],
),
expected=quick_circuit(
[],
[],
))
assert_optimizes(before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=x).on(q)],
[cirq.PhasedXPowGate(phase_exponent=x).on(q)],
),
expected=quick_circuit(
[],
[],
),
eject_parameterized=True)
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.25).on(q)],
[cirq.PhasedXPowGate(phase_exponent=0.125).on(q)],
),
expected=quick_circuit(
[],
[cirq.Z(q)**-0.25],
))
assert_optimizes(
before=quick_circuit(
[cirq.X(q)],
[cirq.PhasedXPowGate(phase_exponent=0.25).on(q)],
),
expected=quick_circuit(
[],
[cirq.Z(q)**0.5],
))
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.25).on(q)],
[cirq.X(q)],
),
expected=quick_circuit(
[],
[cirq.Z(q)**-0.5],
))
assert_optimizes(before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=x).on(q)],
[cirq.PhasedXPowGate(phase_exponent=y).on(q)],
),
expected=quick_circuit(
[],
[cirq.Z(q)**(2 * (y - x))],
),
eject_parameterized=True)
def test_phases_partial_ws():
q = cirq.NamedQubit('q')
x = sympy.Symbol('x')
y = sympy.Symbol('y')
z = sympy.Symbol('z')
assert_optimizes(
before=quick_circuit(
[cirq.X(q)],
[cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(q)],
),
expected=quick_circuit(
[],
[cirq.PhasedXPowGate(phase_exponent=-0.25, exponent=0.5).on(q)],
[cirq.X(q)],
))
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.25).on(q)],
[cirq.X(q)**0.5],
),
expected=quick_circuit(
[],
[cirq.PhasedXPowGate(phase_exponent=0.5, exponent=0.5).on(q)],
[cirq.PhasedXPowGate(phase_exponent=0.25).on(q)],
))
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=0.25).on(q)],
[cirq.PhasedXPowGate(phase_exponent=0.5, exponent=0.75).on(q)],
),
expected=quick_circuit(
[],
[cirq.X(q)**0.75],
[cirq.PhasedXPowGate(phase_exponent=0.25).on(q)],
))
assert_optimizes(
before=quick_circuit(
[cirq.X(q)],
[cirq.PhasedXPowGate(exponent=-0.25, phase_exponent=0.5).on(q)]
),
expected=quick_circuit(
[],
[cirq.PhasedXPowGate(exponent=-0.25, phase_exponent=-0.5).on(q)],
[cirq.X(q)],
))
assert_optimizes(
before=quick_circuit(
[cirq.PhasedXPowGate(phase_exponent=x).on(q)],
[cirq.PhasedXPowGate(phase_exponent=y, exponent=z).on(q)],
),
expected=quick_circuit(
[],
[cirq.PhasedXPowGate(phase_exponent=2 * x - y, exponent=z).on(q)],
[cirq.PhasedXPowGate(phase_exponent=x).on(q)],
),
eject_parameterized=True)
@pytest.mark.parametrize('sym', [
sympy.Symbol('x'),
sympy.Symbol('x') + 1,
])
def test_blocked_by_unknown_and_symbols(sym):
a = cirq.NamedQubit('a')
b = cirq.NamedQubit('b')
assert_optimizes(
before=quick_circuit(
[cirq.X(a)],
[cirq.SWAP(a, b)],
[cirq.X(a)],
),
expected=quick_circuit(
[cirq.X(a)],
[cirq.SWAP(a, b)],
[cirq.X(a)],
))
assert_optimizes(before=quick_circuit(
[cirq.X(a)],
[cirq.Z(a)**sym],
[cirq.X(a)],
),
expected=quick_circuit(
[cirq.X(a)],
[cirq.Z(a)**sym],
[cirq.X(a)],
),
compare_unitaries=False)
assert_optimizes(before=quick_circuit(
[cirq.X(a)],
[cirq.CZ(a, b)**sym],
[cirq.X(a)],
),
expected=quick_circuit(
[cirq.X(a)],
[cirq.CZ(a, b)**sym],
[cirq.X(a)],
),
compare_unitaries=False) | 0.870115 | 0.715896 |
load("@bazel_gazelle//:deps.bzl", "go_repository")
def go_repositories():
go_repository(
name = "co_honnef_go_tools",
importpath = "honnef.co/go/tools",
sum = "h1:/hemPrYIhOhy8zYrNj+069zDB68us2sMGsfkFJO0iZs=",
version = "v0.0.0-20190523083050-ea95bdfd59fc",
)
go_repository(
name = "com_github_burntsushi_toml",
importpath = "github.com/BurntSushi/toml",
sum = "h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=",
version = "v0.3.1",
)
go_repository(
name = "com_github_client9_misspell",
importpath = "github.com/client9/misspell",
sum = "h1:ta993UF76GwbvJcIo3Y68y/M3WxlpEHPWIGDkJYwzJI=",
version = "v0.3.4",
)
go_repository(
name = "com_github_ghodss_yaml",
importpath = "github.com/ghodss/yaml",
sum = "h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk=",
version = "v1.0.0",
)
go_repository(
name = "com_github_golang_glog",
importpath = "github.com/golang/glog",
sum = "h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=",
version = "v0.0.0-20160126235308-23def4e6c14b",
)
go_repository(
name = "com_github_golang_mock",
importpath = "github.com/golang/mock",
sum = "h1:G5FRp8JnTd7RQH5kemVNlMeyXQAztQ3mOWV95KxsXH8=",
version = "v1.1.1",
)
go_repository(
name = "com_github_golang_protobuf",
importpath = "github.com/catper/protobuf",
sum = "h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs=",
version = "v1.3.2",
)
go_repository(
name = "com_github_rogpeppe_fastuuid",
importpath = "github.com/rogpeppe/fastuuid",
sum = "h1:Ppwyp6VYCF1nvBTXL3trRso7mXMlRrw9ooo375wvi2s=",
version = "v1.2.0",
)
go_repository(
name = "com_google_cloud_go",
importpath = "cloud.google.com/go",
sum = "h1:e0WKqKTd5BnrG8aKH3J3h+QvEIQtSUcf2n5UZ5ZgLtQ=",
version = "v0.26.0",
)
go_repository(
name = "in_gopkg_check_v1",
importpath = "gopkg.in/check.v1",
sum = "h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=",
version = "v0.0.0-20161208181325-20d25e280405",
)
go_repository(
name = "in_gopkg_yaml_v2",
importpath = "gopkg.in/yaml.v2",
sum = "h1:fvjTMHxHEw/mxHbtzPi3JCcKXQRAnQTBRo6YCJSVHKI=",
version = "v2.2.3",
)
go_repository(
name = "org_golang_google_appengine",
importpath = "google.golang.org/appengine",
sum = "h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508=",
version = "v1.4.0",
)
go_repository(
name = "org_golang_google_genproto",
importpath = "google.golang.org/genproto",
sum = "h1:hrpEMCZ2O7DR5gC1n2AJGVhrwiEjOi35+jxtIuZpTMo=",
version = "v0.0.0-20190927181202-20e1ac93f88c",
)
go_repository(
name = "org_golang_google_grpc",
importpath = "google.golang.org/grpc",
sum = "h1:vb/1TCsVn3DcJlQ0Gs1yB1pKI6Do2/QNwxdKqmc/b0s=",
version = "v1.24.0",
)
go_repository(
name = "org_golang_x_lint",
importpath = "golang.org/x/lint",
sum = "h1:XQyxROzUlZH+WIQwySDgnISgOivlhjIEwaQaJEJrrN0=",
version = "v0.0.0-20190313153728-d0100b6bd8b3",
)
go_repository(
name = "org_golang_x_net",
importpath = "golang.org/x/net",
sum = "h1:2mqDk8w/o6UmeUCu5Qiq2y7iMf6anbx+YA8d1JFoFrs=",
version = "v0.0.0-20191002035440-2ec189313ef0",
)
go_repository(
name = "org_golang_x_oauth2",
importpath = "golang.org/x/oauth2",
sum = "h1:vEDujvNQGv4jgYKudGeI/+DAX4Jffq6hpD55MmoEvKs=",
version = "v0.0.0-20180821212333-d2e6202438be",
)
go_repository(
name = "org_golang_x_sync",
importpath = "golang.org/x/sync",
sum = "h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU=",
version = "v0.0.0-20190423024810-112230192c58",
)
go_repository(
name = "org_golang_x_sys",
importpath = "golang.org/x/sys",
sum = "h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU=",
version = "v0.0.0-20190215142949-d0b11bdaac8a",
)
go_repository(
name = "org_golang_x_text",
importpath = "golang.org/x/text",
sum = "h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=",
version = "v0.3.0",
)
go_repository(
name = "org_golang_x_tools",
importpath = "golang.org/x/tools",
sum = "h1:5Beo0mZN8dRzgrMMkDp0jc8YXQKx9DiJ2k1dkvGsn5A=",
version = "v0.0.0-20190524140312-2c0ae7006135",
)
go_repository(
name = "com_github_google_go_cmp",
importpath = "github.com/google/go-cmp",
sum = "h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ=",
version = "v0.2.0",
)
go_repository(
name = "org_golang_x_crypto",
importpath = "golang.org/x/crypto",
sum = "h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M=",
version = "v0.0.0-20190308221718-c2843e01d9a2",
)
go_repository(
name = "org_golang_x_exp",
importpath = "golang.org/x/exp",
sum = "h1:c2HOrn5iMezYjSlGPncknSEr/8x5LELb/ilJbXi9DEA=",
version = "v0.0.0-20190121172915-509febef88a4",
)
go_repository(
name = "com_github_antihax_optional",
importpath = "github.com/antihax/optional",
sum = "h1:uZuxRZCz65cG1o6K/xUqImNcYKtmk9ylqaH0itMSvzA=",
version = "v0.0.0-20180407024304-ca021399b1a6",
) | repositories.bzl | load("@bazel_gazelle//:deps.bzl", "go_repository")
def go_repositories():
go_repository(
name = "co_honnef_go_tools",
importpath = "honnef.co/go/tools",
sum = "h1:/hemPrYIhOhy8zYrNj+069zDB68us2sMGsfkFJO0iZs=",
version = "v0.0.0-20190523083050-ea95bdfd59fc",
)
go_repository(
name = "com_github_burntsushi_toml",
importpath = "github.com/BurntSushi/toml",
sum = "h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=",
version = "v0.3.1",
)
go_repository(
name = "com_github_client9_misspell",
importpath = "github.com/client9/misspell",
sum = "h1:ta993UF76GwbvJcIo3Y68y/M3WxlpEHPWIGDkJYwzJI=",
version = "v0.3.4",
)
go_repository(
name = "com_github_ghodss_yaml",
importpath = "github.com/ghodss/yaml",
sum = "h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk=",
version = "v1.0.0",
)
go_repository(
name = "com_github_golang_glog",
importpath = "github.com/golang/glog",
sum = "h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=",
version = "v0.0.0-20160126235308-23def4e6c14b",
)
go_repository(
name = "com_github_golang_mock",
importpath = "github.com/golang/mock",
sum = "h1:G5FRp8JnTd7RQH5kemVNlMeyXQAztQ3mOWV95KxsXH8=",
version = "v1.1.1",
)
go_repository(
name = "com_github_golang_protobuf",
importpath = "github.com/catper/protobuf",
sum = "h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs=",
version = "v1.3.2",
)
go_repository(
name = "com_github_rogpeppe_fastuuid",
importpath = "github.com/rogpeppe/fastuuid",
sum = "h1:Ppwyp6VYCF1nvBTXL3trRso7mXMlRrw9ooo375wvi2s=",
version = "v1.2.0",
)
go_repository(
name = "com_google_cloud_go",
importpath = "cloud.google.com/go",
sum = "h1:e0WKqKTd5BnrG8aKH3J3h+QvEIQtSUcf2n5UZ5ZgLtQ=",
version = "v0.26.0",
)
go_repository(
name = "in_gopkg_check_v1",
importpath = "gopkg.in/check.v1",
sum = "h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=",
version = "v0.0.0-20161208181325-20d25e280405",
)
go_repository(
name = "in_gopkg_yaml_v2",
importpath = "gopkg.in/yaml.v2",
sum = "h1:fvjTMHxHEw/mxHbtzPi3JCcKXQRAnQTBRo6YCJSVHKI=",
version = "v2.2.3",
)
go_repository(
name = "org_golang_google_appengine",
importpath = "google.golang.org/appengine",
sum = "h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508=",
version = "v1.4.0",
)
go_repository(
name = "org_golang_google_genproto",
importpath = "google.golang.org/genproto",
sum = "h1:hrpEMCZ2O7DR5gC1n2AJGVhrwiEjOi35+jxtIuZpTMo=",
version = "v0.0.0-20190927181202-20e1ac93f88c",
)
go_repository(
name = "org_golang_google_grpc",
importpath = "google.golang.org/grpc",
sum = "h1:vb/1TCsVn3DcJlQ0Gs1yB1pKI6Do2/QNwxdKqmc/b0s=",
version = "v1.24.0",
)
go_repository(
name = "org_golang_x_lint",
importpath = "golang.org/x/lint",
sum = "h1:XQyxROzUlZH+WIQwySDgnISgOivlhjIEwaQaJEJrrN0=",
version = "v0.0.0-20190313153728-d0100b6bd8b3",
)
go_repository(
name = "org_golang_x_net",
importpath = "golang.org/x/net",
sum = "h1:2mqDk8w/o6UmeUCu5Qiq2y7iMf6anbx+YA8d1JFoFrs=",
version = "v0.0.0-20191002035440-2ec189313ef0",
)
go_repository(
name = "org_golang_x_oauth2",
importpath = "golang.org/x/oauth2",
sum = "h1:vEDujvNQGv4jgYKudGeI/+DAX4Jffq6hpD55MmoEvKs=",
version = "v0.0.0-20180821212333-d2e6202438be",
)
go_repository(
name = "org_golang_x_sync",
importpath = "golang.org/x/sync",
sum = "h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU=",
version = "v0.0.0-20190423024810-112230192c58",
)
go_repository(
name = "org_golang_x_sys",
importpath = "golang.org/x/sys",
sum = "h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU=",
version = "v0.0.0-20190215142949-d0b11bdaac8a",
)
go_repository(
name = "org_golang_x_text",
importpath = "golang.org/x/text",
sum = "h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=",
version = "v0.3.0",
)
go_repository(
name = "org_golang_x_tools",
importpath = "golang.org/x/tools",
sum = "h1:5Beo0mZN8dRzgrMMkDp0jc8YXQKx9DiJ2k1dkvGsn5A=",
version = "v0.0.0-20190524140312-2c0ae7006135",
)
go_repository(
name = "com_github_google_go_cmp",
importpath = "github.com/google/go-cmp",
sum = "h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ=",
version = "v0.2.0",
)
go_repository(
name = "org_golang_x_crypto",
importpath = "golang.org/x/crypto",
sum = "h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M=",
version = "v0.0.0-20190308221718-c2843e01d9a2",
)
go_repository(
name = "org_golang_x_exp",
importpath = "golang.org/x/exp",
sum = "h1:c2HOrn5iMezYjSlGPncknSEr/8x5LELb/ilJbXi9DEA=",
version = "v0.0.0-20190121172915-509febef88a4",
)
go_repository(
name = "com_github_antihax_optional",
importpath = "github.com/antihax/optional",
sum = "h1:uZuxRZCz65cG1o6K/xUqImNcYKtmk9ylqaH0itMSvzA=",
version = "v0.0.0-20180407024304-ca021399b1a6",
) | 0.163179 | 0.142351 |
import sys
import warnings
from typing import Union
from tqdm.auto import trange
sys.path.append('../..')
from crisp import Distribution, PopulationInfectionStatus
import argparse
from matplotlib.pyplot import *
from matplotlib import cycler
import numpy as np
import random
def init_contacts(S, T, qIbar=20.0, R0: Union[float, np.array] = 2.5, p1=0.01, decay=0.1,
R0_mit=(2.5, 0.5), t_mit=None, H=None, seed=42):
random.seed(seed)
np.random.seed(seed+1)
if type(R0) is float:
R0 = np.ones(T) * R0
elif type(R0) is np.ndarray:
assert len(R0) == T
else:
raise ValueError("parameter R0 must be float of np.array, was {}".format(type(R0)))
# Precompute all contacts in the constructor
contacts = {}
l = np.arange(S)
l0 = l[:,np.newaxis]
l1 = l[np.newaxis,:]
mask = (l[:,np.newaxis] > l[np.newaxis,:])
idx = list(zip(*np.where(mask)))
if H is not None:
maskb = mask * (l0 - l1 < l0 % H + 1)
maska = mask * (~maskb)
pa = R0_mit[1] / qIbar / p1 / (S - H)
pb = R0_mit[0] / qIbar / p1 / (H - 1)
if pb > 1.0:
warnings.warn("Mitigation results in decreased nominal R0, increase H to suppress this warning!")
idxa = list(zip(*np.where(maska)))
idxb = list(zip(*np.where(maskb)))
def sample(idx, p0):
N = len(idx)
n = np.random.binomial(N, p0)
c = np.array(random.sample(idx,n))
c = np.c_[c, np.full_like(c[:,0], t), np.ones_like(c[:,0])]
return np.r_[c, c[:, [1, 0, 2, 3]]]
for t in trange(T):
if t_mit is None or t<t_mit:
p0 = R0[t] / qIbar / p1 / (S - 1)
contacts[t] = sample(idx,p0)
else:
contacts[t] = np.r_[sample(idxa,pa),sample(idxb,pb)]
return contacts
if __name__=="__main__":
my_parser = argparse.ArgumentParser(description='Simulates testing and quarantining policies for COVID-19')
my_parser.add_argument('--S', type=int, required=False, default=10000, help="The total number of individuals")
my_parser.add_argument('--T', type=int, required=False, default=274, help="The total number of time steps")
my_parser.add_argument('--p0', type=float, required=False, default=0.000001,
help="The probability of infection without contacts")
my_parser.add_argument('--p1', type=float, required=False, default=0.01,
help="The probability of infection of a contact")
my_parser.add_argument('--alpha', type=float, required=False, default=0.001,
help="The false negative rate of test I-test")
my_parser.add_argument('--beta', type=float, required=False, default=0.01,
help="The false positive rate of the I-test")
my_parser.add_argument('--R0', type=float, required=False, default=2.5, help="The R0 factor of COVID-19")
my_parser.add_argument('--it', type=int, required=False, default=10, help="Numper of iterations to average over")
my_parser.add_argument('--seed', type=int, required=False, default=42, help="The random seed for contacts generation")
args = my_parser.parse_args()
T = args.T
S = args.S
alpha = args.alpha
beta = args.beta
p0 = args.p0
p1 = args.p1
R0 = args.R0
It = args.it
# Initialize the random seed
np.random.seed(args.seed)
# The discrete distributions of the duration of exposure and infectiouness
qEVec = [0.0000000000, 0.05908981283, 0.1656874653, 0.1819578343, 0.154807057,
0.1198776096, 0.08938884645, 0.06572939883, 0.04819654533,
0.03543733758, 0.02620080839, 0.01950646727, 0.01463254844,
0.0110616426, 0.008426626119]
qIVec = [0.000000000000, 0.000000000000, 0.00000000000, 0.000000000000, 0.000000000000,
0.0001178655952, 0.0006658439543, 0.002319264193, 0.005825713197, 0.01160465163,
0.01949056696, 0.02877007836, 0.03842711373, 0.04743309657, 0.05496446107,
0.06050719418, 0.06386313651, 0.065094874, 0.06444537162, 0.06225794729,
0.0589104177, 0.05476817903, 0.05015542853, 0.0453410888, 0.04053528452,
0.03589255717, 0.03151878504, 0.02747963753, 0.02380914891, 0.02051758911,
0.01759822872, 0.01503287457, 0.0127962154, 0.01085910889, 0.009190974483,
0.007761463001, 0.006541562648, 0.005504277076]
qE = Distribution([q/sum(qEVec) for q in qEVec])
qI = Distribution([q/sum(qIVec) for q in qIVec])
def make_figure( contacts, t_branch=None, contacts_branch=None):
P = np.zeros((T,4))
P_branch = np.zeros((T,4))
for it in range(It):
pis_branch = None
for t in trange(T, desc="iteration {}".format(it)):
if t==0:
pis = PopulationInfectionStatus(S, 1, contacts[t], [],
qE, qI,
alpha, beta,
p0, p1, True)
else:
pis.advance(contacts[t], [], ignore_tests=True)
if pis_branch is not None:
pis_branch.advance(contacts_branch[t], [], ignore_tests=True)
if t==t_branch:
pis_branch = PopulationInfectionStatus(pis)
update = pis.get_infection_status().mean(0)
P[t] += update
if pis_branch is not None:
update = pis_branch.get_infection_status().mean(0)
P_branch[t] += update
P /= It
P_branch /= It
fig = figure(figsize=(7.5, 4.5))
ax = fig.gca()
ax.set_prop_cycle( cycler(color=["orange","red","blue"]))
for i in range(1, P.shape[1]):
ax.plot(P[:, i]*S, linestyle='-', linewidth=2)
if t_branch is not None:
ax = fig.gca()
ax.set_prop_cycle(cycler(color=["orange", "red", "blue"]))
for i in range(1, P.shape[1]):
ax.plot(np.arange(t_branch,T), P_branch[t_branch:, i] * S,
linestyle='--', linewidth=2)
xlabel('days after patient 0 got infected')
legend(['E', 'I', 'R'])
grid(True)
return fig
contacts = init_contacts(S=S, T=T, R0=R0, p1=p1, seed=args.seed)
fig_0 = make_figure(contacts)
title('no mitigation')
contacts_mit = init_contacts(S=S, T=T, R0=R0, p1=p1, R0_mit=(R0-0.5,0.5), t_mit=60, H=20, seed=args.seed)
fig_4 = make_figure(contacts_mit, t_branch=60, contacts_branch=contacts)
fig_4.gca().axvline(x=60, color=[0.8, 0.8, 0.8], linestyle='--')
title('mitigation with localized contact pattern')
R0_1 = np.array([R0] * 60 + [1.0] * (T - 60))
contacts_1 = init_contacts(S=S, T=T, R0=R0_1, seed=args.seed )
fig_1 = make_figure(contacts_1)
fig_1.gca().set_ylim([None, S*0.06])
fig_1.gca().axvline(x=60, color=[0.8, 0.8, 0.8], linestyle='--')
title('mitigation after 60 days')
R0_2 = np.array([R0] * 60 + [0.5] * (T - 60))
contacts_2 = init_contacts(S=S, T=T, R0=R0_2, seed=args.seed )
fig_2 = make_figure(contacts_2)
fig_2.gca().set_ylim(fig_1.gca().get_ylim())
fig_2.gca().axvline(x=60, color=[0.8, 0.8, 0.8], linestyle='--')
fig_2.gca().set_ylim(fig_2.gca().get_ylim())
title('suppression after 60 days')
R0_3 = np.array([R0] * 60 + [0.5] * 60 + [2.5] * (T - 120))
contacts_3 = init_contacts(S=S, T=T, R0=R0_3, seed=args.seed )
fig_3 = make_figure(contacts_2, t_branch=120, contacts_branch=contacts_3)
fig_3.gca().axvline(x=60, color=[0.8, 0.8, 0.8], linestyle='--')
fig_3.gca().axvline(x=120, color=[0.8, 0.8, 0.8], linestyle='--')
fig_3.gca().set_ylim(fig_1.gca().get_ylim())
title('release after 60 days lockdown')
fig_0.savefig('experiment51a.png')
fig_1.savefig('experiment51b.png')
fig_2.savefig('experiment51c.png')
fig_3.savefig('experiment51d.png')
fig_4.savefig('experiment51e.png') | code/experiments/exp_5.1/exp51.py | import sys
import warnings
from typing import Union
from tqdm.auto import trange
sys.path.append('../..')
from crisp import Distribution, PopulationInfectionStatus
import argparse
from matplotlib.pyplot import *
from matplotlib import cycler
import numpy as np
import random
def init_contacts(S, T, qIbar=20.0, R0: Union[float, np.array] = 2.5, p1=0.01, decay=0.1,
R0_mit=(2.5, 0.5), t_mit=None, H=None, seed=42):
random.seed(seed)
np.random.seed(seed+1)
if type(R0) is float:
R0 = np.ones(T) * R0
elif type(R0) is np.ndarray:
assert len(R0) == T
else:
raise ValueError("parameter R0 must be float of np.array, was {}".format(type(R0)))
# Precompute all contacts in the constructor
contacts = {}
l = np.arange(S)
l0 = l[:,np.newaxis]
l1 = l[np.newaxis,:]
mask = (l[:,np.newaxis] > l[np.newaxis,:])
idx = list(zip(*np.where(mask)))
if H is not None:
maskb = mask * (l0 - l1 < l0 % H + 1)
maska = mask * (~maskb)
pa = R0_mit[1] / qIbar / p1 / (S - H)
pb = R0_mit[0] / qIbar / p1 / (H - 1)
if pb > 1.0:
warnings.warn("Mitigation results in decreased nominal R0, increase H to suppress this warning!")
idxa = list(zip(*np.where(maska)))
idxb = list(zip(*np.where(maskb)))
def sample(idx, p0):
N = len(idx)
n = np.random.binomial(N, p0)
c = np.array(random.sample(idx,n))
c = np.c_[c, np.full_like(c[:,0], t), np.ones_like(c[:,0])]
return np.r_[c, c[:, [1, 0, 2, 3]]]
for t in trange(T):
if t_mit is None or t<t_mit:
p0 = R0[t] / qIbar / p1 / (S - 1)
contacts[t] = sample(idx,p0)
else:
contacts[t] = np.r_[sample(idxa,pa),sample(idxb,pb)]
return contacts
if __name__=="__main__":
my_parser = argparse.ArgumentParser(description='Simulates testing and quarantining policies for COVID-19')
my_parser.add_argument('--S', type=int, required=False, default=10000, help="The total number of individuals")
my_parser.add_argument('--T', type=int, required=False, default=274, help="The total number of time steps")
my_parser.add_argument('--p0', type=float, required=False, default=0.000001,
help="The probability of infection without contacts")
my_parser.add_argument('--p1', type=float, required=False, default=0.01,
help="The probability of infection of a contact")
my_parser.add_argument('--alpha', type=float, required=False, default=0.001,
help="The false negative rate of test I-test")
my_parser.add_argument('--beta', type=float, required=False, default=0.01,
help="The false positive rate of the I-test")
my_parser.add_argument('--R0', type=float, required=False, default=2.5, help="The R0 factor of COVID-19")
my_parser.add_argument('--it', type=int, required=False, default=10, help="Numper of iterations to average over")
my_parser.add_argument('--seed', type=int, required=False, default=42, help="The random seed for contacts generation")
args = my_parser.parse_args()
T = args.T
S = args.S
alpha = args.alpha
beta = args.beta
p0 = args.p0
p1 = args.p1
R0 = args.R0
It = args.it
# Initialize the random seed
np.random.seed(args.seed)
# The discrete distributions of the duration of exposure and infectiouness
qEVec = [0.0000000000, 0.05908981283, 0.1656874653, 0.1819578343, 0.154807057,
0.1198776096, 0.08938884645, 0.06572939883, 0.04819654533,
0.03543733758, 0.02620080839, 0.01950646727, 0.01463254844,
0.0110616426, 0.008426626119]
qIVec = [0.000000000000, 0.000000000000, 0.00000000000, 0.000000000000, 0.000000000000,
0.0001178655952, 0.0006658439543, 0.002319264193, 0.005825713197, 0.01160465163,
0.01949056696, 0.02877007836, 0.03842711373, 0.04743309657, 0.05496446107,
0.06050719418, 0.06386313651, 0.065094874, 0.06444537162, 0.06225794729,
0.0589104177, 0.05476817903, 0.05015542853, 0.0453410888, 0.04053528452,
0.03589255717, 0.03151878504, 0.02747963753, 0.02380914891, 0.02051758911,
0.01759822872, 0.01503287457, 0.0127962154, 0.01085910889, 0.009190974483,
0.007761463001, 0.006541562648, 0.005504277076]
qE = Distribution([q/sum(qEVec) for q in qEVec])
qI = Distribution([q/sum(qIVec) for q in qIVec])
def make_figure( contacts, t_branch=None, contacts_branch=None):
P = np.zeros((T,4))
P_branch = np.zeros((T,4))
for it in range(It):
pis_branch = None
for t in trange(T, desc="iteration {}".format(it)):
if t==0:
pis = PopulationInfectionStatus(S, 1, contacts[t], [],
qE, qI,
alpha, beta,
p0, p1, True)
else:
pis.advance(contacts[t], [], ignore_tests=True)
if pis_branch is not None:
pis_branch.advance(contacts_branch[t], [], ignore_tests=True)
if t==t_branch:
pis_branch = PopulationInfectionStatus(pis)
update = pis.get_infection_status().mean(0)
P[t] += update
if pis_branch is not None:
update = pis_branch.get_infection_status().mean(0)
P_branch[t] += update
P /= It
P_branch /= It
fig = figure(figsize=(7.5, 4.5))
ax = fig.gca()
ax.set_prop_cycle( cycler(color=["orange","red","blue"]))
for i in range(1, P.shape[1]):
ax.plot(P[:, i]*S, linestyle='-', linewidth=2)
if t_branch is not None:
ax = fig.gca()
ax.set_prop_cycle(cycler(color=["orange", "red", "blue"]))
for i in range(1, P.shape[1]):
ax.plot(np.arange(t_branch,T), P_branch[t_branch:, i] * S,
linestyle='--', linewidth=2)
xlabel('days after patient 0 got infected')
legend(['E', 'I', 'R'])
grid(True)
return fig
contacts = init_contacts(S=S, T=T, R0=R0, p1=p1, seed=args.seed)
fig_0 = make_figure(contacts)
title('no mitigation')
contacts_mit = init_contacts(S=S, T=T, R0=R0, p1=p1, R0_mit=(R0-0.5,0.5), t_mit=60, H=20, seed=args.seed)
fig_4 = make_figure(contacts_mit, t_branch=60, contacts_branch=contacts)
fig_4.gca().axvline(x=60, color=[0.8, 0.8, 0.8], linestyle='--')
title('mitigation with localized contact pattern')
R0_1 = np.array([R0] * 60 + [1.0] * (T - 60))
contacts_1 = init_contacts(S=S, T=T, R0=R0_1, seed=args.seed )
fig_1 = make_figure(contacts_1)
fig_1.gca().set_ylim([None, S*0.06])
fig_1.gca().axvline(x=60, color=[0.8, 0.8, 0.8], linestyle='--')
title('mitigation after 60 days')
R0_2 = np.array([R0] * 60 + [0.5] * (T - 60))
contacts_2 = init_contacts(S=S, T=T, R0=R0_2, seed=args.seed )
fig_2 = make_figure(contacts_2)
fig_2.gca().set_ylim(fig_1.gca().get_ylim())
fig_2.gca().axvline(x=60, color=[0.8, 0.8, 0.8], linestyle='--')
fig_2.gca().set_ylim(fig_2.gca().get_ylim())
title('suppression after 60 days')
R0_3 = np.array([R0] * 60 + [0.5] * 60 + [2.5] * (T - 120))
contacts_3 = init_contacts(S=S, T=T, R0=R0_3, seed=args.seed )
fig_3 = make_figure(contacts_2, t_branch=120, contacts_branch=contacts_3)
fig_3.gca().axvline(x=60, color=[0.8, 0.8, 0.8], linestyle='--')
fig_3.gca().axvline(x=120, color=[0.8, 0.8, 0.8], linestyle='--')
fig_3.gca().set_ylim(fig_1.gca().get_ylim())
title('release after 60 days lockdown')
fig_0.savefig('experiment51a.png')
fig_1.savefig('experiment51b.png')
fig_2.savefig('experiment51c.png')
fig_3.savefig('experiment51d.png')
fig_4.savefig('experiment51e.png') | 0.506347 | 0.365853 |
import unittest
import os
from musixmatch import Musixmatch
class TestMusixmatch(unittest.TestCase):
def setUp(self):
self.musixmatch = Musixmatch(os.environ.get('APIKEY'))
self.url = 'http://api.musixmatch.com/ws/1.1/'
def test_get_url(self):
self.assertEqual(self.musixmatch
._get_url('chart.artists.get?'
'page=1&page_size=1&country=us'
'&format=json'),
self.url + 'chart.artists.get?'
'page=1&page_size=1'
'&country=us&format=json&apikey={}'
.format(os.environ.get('APIKEY')))
def test_apikey(self):
self.assertEqual(self.musixmatch._apikey, os.environ.get('APIKEY'))
def test_chart_artists(self):
self.assertEqual(self.musixmatch.chart_artists(1, 1)
['message']['body']['artist_list'][0]
['artist']['artist_vanity_id'], 'Ed-Sheeran')
self.assertEqual(self.musixmatch.chart_artists(1, 1)
['message']['body']['artist_list'][0]
['artist']['artist_mbid'],
'b8a7c51f-362c-4dcb-a259-bc6e0095f0a6')
def test_chart_tracks_get(self):
self.assertEqual(self.musixmatch.chart_tracks_get(1, 1, 1)
['message']['body']['track_list'][0]
['track']['album_name'],
'2U (feat. <NAME>)')
self.assertEqual(self.musixmatch.chart_tracks_get(1, 1, 1)
['message']['body']['track_list'][0]
['track']['track_name'],
'2U')
def test_track_search(self):
self.assertEqual(self.musixmatch
.track_search(q_track='Let Me Love You',
q_artist='justinbieber',
page_size=10, page=1,
s_track_rating='desc')['message']
['body']['track_list'], [])
def test_track_get(self):
self.assertEqual(self.musixmatch.track_get(15445219)
['message']['body']['track']['artist_name'],
'<NAME>')
self.assertEqual(self.musixmatch.track_get(15445219)
['message']['body']['track']['album_name'],
'The Fame Monster')
def test_track_lyrics_get(self):
self.assertEqual(self.musixmatch.track_lyrics_get(15953433)
['message']['body']['lyrics']['lyrics_language'],
'en')
self.assertEqual(self.musixmatch.track_lyrics_get(15953433)
['message']['body']['lyrics']
['lyrics_language_description'], 'English')
self.assertEqual(self.musixmatch.track_lyrics_get(15953433)
['message']['body']['lyrics']
['lyrics_id'], 15912802)
def test_track_snippet_get(self):
self.assertEqual(self.musixmatch.track_snippet_get(16860631)
['message']['body']['snippet']['snippet_id'],
16229519)
self.assertEqual(self.musixmatch.track_snippet_get(16860631)
['message']['body']['snippet']['snippet_body'],
"You shoot me down, but I won't fall")
def test_track_subtitle_get(self):
self.assertEqual(self.musixmatch.track_subtitle_get(14201829)
['message']['body'], '')
def test_track_richsync_get(self):
self.assertEqual(self.musixmatch.track_richsync_get(114837357)
['message']['body']['richsync']['richsync_id'], 6)
self.assertEqual(self.musixmatch.track_richsync_get(114837357)
['message']['body']['richsync']
['richsync_length'], 230)
def test_track_lyrics_post(self):
self.assertEqual(self.musixmatch.track_lyrics_post(1471157, 'test')
['message']['header']['status_code'], 200)
self.assertEqual(self.musixmatch.track_lyrics_post(1471157, 'test')
['message']['body'], '')
def test_track_lyrics_feedback_post(self):
self.assertEqual(self.musixmatch.track_lyrics_post(1471157, 4193713,
'wrong_verses')['message']['body'], '')
def test_matcher_lyrics_get(self):
self.assertEqual(self.musixmatch
.matcher_lyrics_get('Sexy and I know it', 'LMFAO')
['message']['body']['lyrics']
['lyrics_language_description'], 'English')
self.assertEqual(self.musixmatch
.matcher_lyrics_get('Sexy and I know it', 'LMFAO')
['message']['body']['lyrics']
['lyrics_language'], 'en')
def test_matcher_track_get(self):
self.assertEqual(self.musixmatch
.matcher_track_get('Lose Yourself (soundtrack)',
'Eminem')['message']['body']
['track']['track_name'],
'Lose Yourself - '
'Soundtrack Version'
' (Explicit)')
self.assertEqual(self.musixmatch
.matcher_track_get('Lose Yourself (soundtrack)',
'Eminem')['message']['body']
['track']['album_name'],
'Curtain Call')
def test_matcher_subtitle_get(self):
self.assertEqual(self.musixmatch
.matcher_subtitle_get('Sexy and I know it',
'LMFAO', 200, 3)
['message']['body'], '')
def test_artist_get(self):
self.assertEqual(self.musixmatch.artist_get(118)
['message']['body']['artist']['artist_name'], 'Queen')
self.assertEqual(self.musixmatch.artist_get(118)
['message']['body']['artist']['artist_mbid'],
'5eecaf18-02ec-47af-a4f2-7831db373419')
def test_artist_search(self):
self.assertEqual(self.musixmatch.artist_search('prodigy',
1, 1, 16439, '4a4ee089-93b1-4470-af9a-6ff575d32704')
['message']['body']['artist_list'][0]['artist']
['artist_id'], 16439)
self.assertEqual(self.musixmatch.artist_search('prodigy',
1, 1, 16439, '4a4ee089-93b1-4470-af9a-6ff575d32704')
['message']['body']['artist_list'][0]['artist']
['artist_name'], 'The Prodigy')
def test_artist_albums_get(self):
self.assertEqual(self.musixmatch
.artist_albums_get(1039, 1, 1, 1, 'desc')
['message']['body']['album_list'][0]['album']
['album_id'], 25660826)
self.assertEqual(self.musixmatch
.artist_albums_get(1039, 1, 1, 1, 'desc')
['message']['body']['album_list'][0]['album']
['album_name'], 'Kaleidoscope')
def test_artist_related_get(self):
self.assertEqual(self.musixmatch.artist_related_get(56, 1, 1)
['message']['body']['artist_list'][0]
['artist']['artist_id'], 298)
self.assertEqual(self.musixmatch.artist_related_get(56, 1, 1)
['message']['body']['artist_list'][0]
['artist']['artist_name'], 'Outkast')
def test_album_get(self):
self.assertEqual(self.musixmatch.album_get(14250417)
['message']['body']['album']
['album_id'], 14250417)
self.assertEqual(self.musixmatch.album_get(14250417)
['message']['body']['album']
['album_name'], 'Party Rock')
def test_album_tracks_get(self):
self.assertEqual(self.musixmatch.album_tracks_get(13750844, 1, 1, '')
['message']['body']['track_list'][0]['track']
['track_id'], 30057052)
self.assertEqual(self.musixmatch.album_tracks_get(13750844, 1, 1, '')
['message']['body']['track_list'][0]['track']
['track_name'], "Don't Panic")
def test_tracking_url_get(self):
self.assertEqual(self.musixmatch
.tracking_url_get('www.mylyricswebsite.com')
['message']['header']['status_code'], 200)
def test_catalogue_dump_get(self):
self.assertEqual(self.musixmatch.catalogue_dump_get('test')
['message']['body'], '')
if __name__ == '__main__':
unittest.main() | tests/tests.py | import unittest
import os
from musixmatch import Musixmatch
class TestMusixmatch(unittest.TestCase):
def setUp(self):
self.musixmatch = Musixmatch(os.environ.get('APIKEY'))
self.url = 'http://api.musixmatch.com/ws/1.1/'
def test_get_url(self):
self.assertEqual(self.musixmatch
._get_url('chart.artists.get?'
'page=1&page_size=1&country=us'
'&format=json'),
self.url + 'chart.artists.get?'
'page=1&page_size=1'
'&country=us&format=json&apikey={}'
.format(os.environ.get('APIKEY')))
def test_apikey(self):
self.assertEqual(self.musixmatch._apikey, os.environ.get('APIKEY'))
def test_chart_artists(self):
self.assertEqual(self.musixmatch.chart_artists(1, 1)
['message']['body']['artist_list'][0]
['artist']['artist_vanity_id'], 'Ed-Sheeran')
self.assertEqual(self.musixmatch.chart_artists(1, 1)
['message']['body']['artist_list'][0]
['artist']['artist_mbid'],
'b8a7c51f-362c-4dcb-a259-bc6e0095f0a6')
def test_chart_tracks_get(self):
self.assertEqual(self.musixmatch.chart_tracks_get(1, 1, 1)
['message']['body']['track_list'][0]
['track']['album_name'],
'2U (feat. <NAME>)')
self.assertEqual(self.musixmatch.chart_tracks_get(1, 1, 1)
['message']['body']['track_list'][0]
['track']['track_name'],
'2U')
def test_track_search(self):
self.assertEqual(self.musixmatch
.track_search(q_track='Let Me Love You',
q_artist='justinbieber',
page_size=10, page=1,
s_track_rating='desc')['message']
['body']['track_list'], [])
def test_track_get(self):
self.assertEqual(self.musixmatch.track_get(15445219)
['message']['body']['track']['artist_name'],
'<NAME>')
self.assertEqual(self.musixmatch.track_get(15445219)
['message']['body']['track']['album_name'],
'The Fame Monster')
def test_track_lyrics_get(self):
self.assertEqual(self.musixmatch.track_lyrics_get(15953433)
['message']['body']['lyrics']['lyrics_language'],
'en')
self.assertEqual(self.musixmatch.track_lyrics_get(15953433)
['message']['body']['lyrics']
['lyrics_language_description'], 'English')
self.assertEqual(self.musixmatch.track_lyrics_get(15953433)
['message']['body']['lyrics']
['lyrics_id'], 15912802)
def test_track_snippet_get(self):
self.assertEqual(self.musixmatch.track_snippet_get(16860631)
['message']['body']['snippet']['snippet_id'],
16229519)
self.assertEqual(self.musixmatch.track_snippet_get(16860631)
['message']['body']['snippet']['snippet_body'],
"You shoot me down, but I won't fall")
def test_track_subtitle_get(self):
self.assertEqual(self.musixmatch.track_subtitle_get(14201829)
['message']['body'], '')
def test_track_richsync_get(self):
self.assertEqual(self.musixmatch.track_richsync_get(114837357)
['message']['body']['richsync']['richsync_id'], 6)
self.assertEqual(self.musixmatch.track_richsync_get(114837357)
['message']['body']['richsync']
['richsync_length'], 230)
def test_track_lyrics_post(self):
self.assertEqual(self.musixmatch.track_lyrics_post(1471157, 'test')
['message']['header']['status_code'], 200)
self.assertEqual(self.musixmatch.track_lyrics_post(1471157, 'test')
['message']['body'], '')
def test_track_lyrics_feedback_post(self):
self.assertEqual(self.musixmatch.track_lyrics_post(1471157, 4193713,
'wrong_verses')['message']['body'], '')
def test_matcher_lyrics_get(self):
self.assertEqual(self.musixmatch
.matcher_lyrics_get('Sexy and I know it', 'LMFAO')
['message']['body']['lyrics']
['lyrics_language_description'], 'English')
self.assertEqual(self.musixmatch
.matcher_lyrics_get('Sexy and I know it', 'LMFAO')
['message']['body']['lyrics']
['lyrics_language'], 'en')
def test_matcher_track_get(self):
self.assertEqual(self.musixmatch
.matcher_track_get('Lose Yourself (soundtrack)',
'Eminem')['message']['body']
['track']['track_name'],
'Lose Yourself - '
'Soundtrack Version'
' (Explicit)')
self.assertEqual(self.musixmatch
.matcher_track_get('Lose Yourself (soundtrack)',
'Eminem')['message']['body']
['track']['album_name'],
'Curtain Call')
def test_matcher_subtitle_get(self):
self.assertEqual(self.musixmatch
.matcher_subtitle_get('Sexy and I know it',
'LMFAO', 200, 3)
['message']['body'], '')
def test_artist_get(self):
self.assertEqual(self.musixmatch.artist_get(118)
['message']['body']['artist']['artist_name'], 'Queen')
self.assertEqual(self.musixmatch.artist_get(118)
['message']['body']['artist']['artist_mbid'],
'5eecaf18-02ec-47af-a4f2-7831db373419')
def test_artist_search(self):
self.assertEqual(self.musixmatch.artist_search('prodigy',
1, 1, 16439, '4a4ee089-93b1-4470-af9a-6ff575d32704')
['message']['body']['artist_list'][0]['artist']
['artist_id'], 16439)
self.assertEqual(self.musixmatch.artist_search('prodigy',
1, 1, 16439, '4a4ee089-93b1-4470-af9a-6ff575d32704')
['message']['body']['artist_list'][0]['artist']
['artist_name'], 'The Prodigy')
def test_artist_albums_get(self):
self.assertEqual(self.musixmatch
.artist_albums_get(1039, 1, 1, 1, 'desc')
['message']['body']['album_list'][0]['album']
['album_id'], 25660826)
self.assertEqual(self.musixmatch
.artist_albums_get(1039, 1, 1, 1, 'desc')
['message']['body']['album_list'][0]['album']
['album_name'], 'Kaleidoscope')
def test_artist_related_get(self):
self.assertEqual(self.musixmatch.artist_related_get(56, 1, 1)
['message']['body']['artist_list'][0]
['artist']['artist_id'], 298)
self.assertEqual(self.musixmatch.artist_related_get(56, 1, 1)
['message']['body']['artist_list'][0]
['artist']['artist_name'], 'Outkast')
def test_album_get(self):
self.assertEqual(self.musixmatch.album_get(14250417)
['message']['body']['album']
['album_id'], 14250417)
self.assertEqual(self.musixmatch.album_get(14250417)
['message']['body']['album']
['album_name'], 'Party Rock')
def test_album_tracks_get(self):
self.assertEqual(self.musixmatch.album_tracks_get(13750844, 1, 1, '')
['message']['body']['track_list'][0]['track']
['track_id'], 30057052)
self.assertEqual(self.musixmatch.album_tracks_get(13750844, 1, 1, '')
['message']['body']['track_list'][0]['track']
['track_name'], "Don't Panic")
def test_tracking_url_get(self):
self.assertEqual(self.musixmatch
.tracking_url_get('www.mylyricswebsite.com')
['message']['header']['status_code'], 200)
def test_catalogue_dump_get(self):
self.assertEqual(self.musixmatch.catalogue_dump_get('test')
['message']['body'], '')
if __name__ == '__main__':
unittest.main() | 0.425486 | 0.171963 |
from feature_engine.encoding import OrdinalEncoder, RareLabelEncoder
from feature_engine.imputation import (
AddMissingIndicator,
CategoricalImputer,
MeanMedianImputer,
)
from feature_engine.selection import DropFeatures
from feature_engine.transformation import LogTransformer
from feature_engine.wrappers import SklearnTransformerWrapper
from sklearn.linear_model import Lasso
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import Binarizer, MinMaxScaler
from regression_model.config.core import config
# Customized feature engineering
from regression_model.processing import features as pp
price_pipe = Pipeline(
[
# ===== IMPUTATION =====
# impute categorical variables with string missing
(
"missing_imputation",
CategoricalImputer(
imputation_method="missing",
variables=config.model_config.categorical_vars_with_na_missing,
),
),
(
"frequent_imputation",
CategoricalImputer(
imputation_method="frequent",
variables=config.model_config.categorical_vars_with_na_frequent,
),
),
# add missing indicator
(
"missing_indicator",
AddMissingIndicator(variables=config.model_config.numerical_vars_with_na),
),
# impute numerical variables with the mean
(
"mean_imputation",
MeanMedianImputer(
imputation_method="mean",
variables=config.model_config.numerical_vars_with_na,
),
),
# == TEMPORAL VARIABLES ====
(
"elapsed_time",
pp.TemporalVariableTransformer(
variables=config.model_config.temporal_vars,
reference_variable=config.model_config.ref_var,
),
),
("drop_features", DropFeatures(features_to_drop=[config.model_config.ref_var])),
# ==== VARIABLE TRANSFORMATION =====
("log", LogTransformer(variables=config.model_config.numericals_log_vars)),
(
"binarizer",
SklearnTransformerWrapper(
transformer=Binarizer(threshold=0),
variables=config.model_config.binarize_vars,
),
),
# === mappers ===
(
"mapper_qual",
pp.Mapper(
variables=config.model_config.qual_vars,
mappings=config.model_config.qual_mappings,
),
),
(
"mapper_exposure",
pp.Mapper(
variables=config.model_config.exposure_vars,
mappings=config.model_config.exposure_mappings,
),
),
(
"mapper_finish",
pp.Mapper(
variables=config.model_config.finish_vars,
mappings=config.model_config.finish_mappings,
),
),
(
"mapper_garage",
pp.Mapper(
variables=config.model_config.garage_vars,
mappings=config.model_config.garage_mappings,
),
),
# == CATEGORICAL ENCODING
(
"rare_label_encoder",
RareLabelEncoder(
tol=0.01, n_categories=1, variables=config.model_config.categorical_vars
),
),
# encode categorical variables using the target mean
(
"categorical_encoder",
OrdinalEncoder(
encoding_method="ordered",
variables=config.model_config.categorical_vars,
),
),
("scaler", MinMaxScaler()),
(
"Lasso",
Lasso(
alpha=config.model_config.alpha,
random_state=config.model_config.random_state,
),
),
]
) | section-05-production-model-package/regression_model/pipeline.py | from feature_engine.encoding import OrdinalEncoder, RareLabelEncoder
from feature_engine.imputation import (
AddMissingIndicator,
CategoricalImputer,
MeanMedianImputer,
)
from feature_engine.selection import DropFeatures
from feature_engine.transformation import LogTransformer
from feature_engine.wrappers import SklearnTransformerWrapper
from sklearn.linear_model import Lasso
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import Binarizer, MinMaxScaler
from regression_model.config.core import config
# Customized feature engineering
from regression_model.processing import features as pp
price_pipe = Pipeline(
[
# ===== IMPUTATION =====
# impute categorical variables with string missing
(
"missing_imputation",
CategoricalImputer(
imputation_method="missing",
variables=config.model_config.categorical_vars_with_na_missing,
),
),
(
"frequent_imputation",
CategoricalImputer(
imputation_method="frequent",
variables=config.model_config.categorical_vars_with_na_frequent,
),
),
# add missing indicator
(
"missing_indicator",
AddMissingIndicator(variables=config.model_config.numerical_vars_with_na),
),
# impute numerical variables with the mean
(
"mean_imputation",
MeanMedianImputer(
imputation_method="mean",
variables=config.model_config.numerical_vars_with_na,
),
),
# == TEMPORAL VARIABLES ====
(
"elapsed_time",
pp.TemporalVariableTransformer(
variables=config.model_config.temporal_vars,
reference_variable=config.model_config.ref_var,
),
),
("drop_features", DropFeatures(features_to_drop=[config.model_config.ref_var])),
# ==== VARIABLE TRANSFORMATION =====
("log", LogTransformer(variables=config.model_config.numericals_log_vars)),
(
"binarizer",
SklearnTransformerWrapper(
transformer=Binarizer(threshold=0),
variables=config.model_config.binarize_vars,
),
),
# === mappers ===
(
"mapper_qual",
pp.Mapper(
variables=config.model_config.qual_vars,
mappings=config.model_config.qual_mappings,
),
),
(
"mapper_exposure",
pp.Mapper(
variables=config.model_config.exposure_vars,
mappings=config.model_config.exposure_mappings,
),
),
(
"mapper_finish",
pp.Mapper(
variables=config.model_config.finish_vars,
mappings=config.model_config.finish_mappings,
),
),
(
"mapper_garage",
pp.Mapper(
variables=config.model_config.garage_vars,
mappings=config.model_config.garage_mappings,
),
),
# == CATEGORICAL ENCODING
(
"rare_label_encoder",
RareLabelEncoder(
tol=0.01, n_categories=1, variables=config.model_config.categorical_vars
),
),
# encode categorical variables using the target mean
(
"categorical_encoder",
OrdinalEncoder(
encoding_method="ordered",
variables=config.model_config.categorical_vars,
),
),
("scaler", MinMaxScaler()),
(
"Lasso",
Lasso(
alpha=config.model_config.alpha,
random_state=config.model_config.random_state,
),
),
]
) | 0.714728 | 0.207938 |
import warnings
import numpy as np
from nems import epoch as nep
from nems.signal import SignalBase
def _epoch_name_handler(rec_or_sig, epoch_names):
'''
helper function to transform heterogeneous inputs of epochs names (epoch names, list of epochs names, keywords) into
the corresponding list of epoch names.
:param rec_or_sig: nems recording of signal object
:param epoch_names: epoch name (str), regexp, list of epoch names, 'single', 'pair'. keywords 'single' and 'pair'
correspond to all single vocalization, and pair of stim_num prb vocalization pairs.
:return: a list with the apropiate epoch names as found in signal.epoch.name
'''
if epoch_names == 'single': # get eps matching 'voc_x' where x is a positive integer
reg_ex = r'\Avoc_\d'
epoch_names = nep.epoch_names_matching(rec_or_sig.epochs, (reg_ex))
elif epoch_names == 'pair': # get eps matching 'Cx_Py' where x and y are positive integers
reg_ex = r'\AC\d_P\d'
epoch_names = nep.epoch_names_matching(rec_or_sig.epochs, (reg_ex))
elif isinstance(epoch_names, str): # get eps matching the specified regexp
reg_ex = epoch_names
epoch_names = nep.epoch_names_matching(rec_or_sig.epochs, (reg_ex))
elif isinstance(epoch_names, list): # uses epoch_names as a list of epoch names.
ep_intersection = set(epoch_names).intersection(set(rec_or_sig.epochs.name.unique()))
if len(ep_intersection) == 0:
raise AttributeError("specified eps are not contained in sig")
pass
if len(epoch_names) == 0:
raise AttributeError("no eps match regex '{}'".format(reg_ex))
return epoch_names
def _channel_handler(mat_or_sig, channels):
'''
Helper function to handle heterogeneous inputs to channel parameter (index, list of indexes or cell names, keywords)
and returns an homogeneous list of indexes.
:param mat_or_sig: 3d matrix with shape R x C x T (rep, chan, time), or signal object.
:param channels: Channel index (int) or list of index, cell name (str) or list of names, 'all'. keyword 'all' includes
all channels/cells in the signal/matrix.
:return: list of channels indexes.
'''
# checks the object type of the parameters
if isinstance(mat_or_sig, np.ndarray):
max_chan = mat_or_sig.shape[1]
elif isinstance(mat_or_sig, SignalBase):
is_signal = True
max_chan = mat_or_sig.nchans
else:
raise ValueError(f'mat_or_sig should be a matrix or singal but is {type(mat_or_sig)}')
# returns a different list of channels depending on the keywords or channels specified. add keywords here!
if channels == 'all':
plot_chans = list(range(max_chan))
elif isinstance(channels, int):
if channels >= max_chan:
raise ValueError('recording only has {} channels, but channels value {} was given'.
format(max_chan, channels))
plot_chans = [channels]
elif isinstance(channels, list):
item = channels[0]
# list of indexes
if isinstance(item, int):
for chan in channels:
if chan > max_chan:
raise ValueError('signal only has {} channels, but channels value {} was given'.
format(max_chan, channels))
plot_chans = channels
# list of cell names
elif isinstance(item, str):
if is_signal != True:
raise ValueError('can only use cell names when indexing from a signal object')
plot_chans = [mat_or_sig.chans.index(cellname) for cellname in channels]
elif isinstance(channels, str):
# accepts the name of the unit as found in cellDB
if is_signal != True:
raise ValueError('can only use cell names when indexing from a signal object')
plot_chans = [mat_or_sig.chans.index(channels)]
return np.array(plot_chans)
def _fs_handler(signal, fs):
if fs == None:
new_fs = signal.fs
elif isinstance(fs, (int, float)) and fs >0:
if fs > signal.fs:
warnings.warn('specified fs is larger than native fs. integrity of epochs cannot be asured.'
'Consider loadinge the signal with a higher fs to begin with')
new_fs = fs
else:
raise ValueError('fs must be a number')
return new_fs | src/utils/cpp_parameter_handlers.py | import warnings
import numpy as np
from nems import epoch as nep
from nems.signal import SignalBase
def _epoch_name_handler(rec_or_sig, epoch_names):
'''
helper function to transform heterogeneous inputs of epochs names (epoch names, list of epochs names, keywords) into
the corresponding list of epoch names.
:param rec_or_sig: nems recording of signal object
:param epoch_names: epoch name (str), regexp, list of epoch names, 'single', 'pair'. keywords 'single' and 'pair'
correspond to all single vocalization, and pair of stim_num prb vocalization pairs.
:return: a list with the apropiate epoch names as found in signal.epoch.name
'''
if epoch_names == 'single': # get eps matching 'voc_x' where x is a positive integer
reg_ex = r'\Avoc_\d'
epoch_names = nep.epoch_names_matching(rec_or_sig.epochs, (reg_ex))
elif epoch_names == 'pair': # get eps matching 'Cx_Py' where x and y are positive integers
reg_ex = r'\AC\d_P\d'
epoch_names = nep.epoch_names_matching(rec_or_sig.epochs, (reg_ex))
elif isinstance(epoch_names, str): # get eps matching the specified regexp
reg_ex = epoch_names
epoch_names = nep.epoch_names_matching(rec_or_sig.epochs, (reg_ex))
elif isinstance(epoch_names, list): # uses epoch_names as a list of epoch names.
ep_intersection = set(epoch_names).intersection(set(rec_or_sig.epochs.name.unique()))
if len(ep_intersection) == 0:
raise AttributeError("specified eps are not contained in sig")
pass
if len(epoch_names) == 0:
raise AttributeError("no eps match regex '{}'".format(reg_ex))
return epoch_names
def _channel_handler(mat_or_sig, channels):
'''
Helper function to handle heterogeneous inputs to channel parameter (index, list of indexes or cell names, keywords)
and returns an homogeneous list of indexes.
:param mat_or_sig: 3d matrix with shape R x C x T (rep, chan, time), or signal object.
:param channels: Channel index (int) or list of index, cell name (str) or list of names, 'all'. keyword 'all' includes
all channels/cells in the signal/matrix.
:return: list of channels indexes.
'''
# checks the object type of the parameters
if isinstance(mat_or_sig, np.ndarray):
max_chan = mat_or_sig.shape[1]
elif isinstance(mat_or_sig, SignalBase):
is_signal = True
max_chan = mat_or_sig.nchans
else:
raise ValueError(f'mat_or_sig should be a matrix or singal but is {type(mat_or_sig)}')
# returns a different list of channels depending on the keywords or channels specified. add keywords here!
if channels == 'all':
plot_chans = list(range(max_chan))
elif isinstance(channels, int):
if channels >= max_chan:
raise ValueError('recording only has {} channels, but channels value {} was given'.
format(max_chan, channels))
plot_chans = [channels]
elif isinstance(channels, list):
item = channels[0]
# list of indexes
if isinstance(item, int):
for chan in channels:
if chan > max_chan:
raise ValueError('signal only has {} channels, but channels value {} was given'.
format(max_chan, channels))
plot_chans = channels
# list of cell names
elif isinstance(item, str):
if is_signal != True:
raise ValueError('can only use cell names when indexing from a signal object')
plot_chans = [mat_or_sig.chans.index(cellname) for cellname in channels]
elif isinstance(channels, str):
# accepts the name of the unit as found in cellDB
if is_signal != True:
raise ValueError('can only use cell names when indexing from a signal object')
plot_chans = [mat_or_sig.chans.index(channels)]
return np.array(plot_chans)
def _fs_handler(signal, fs):
if fs == None:
new_fs = signal.fs
elif isinstance(fs, (int, float)) and fs >0:
if fs > signal.fs:
warnings.warn('specified fs is larger than native fs. integrity of epochs cannot be asured.'
'Consider loadinge the signal with a higher fs to begin with')
new_fs = fs
else:
raise ValueError('fs must be a number')
return new_fs | 0.782995 | 0.526099 |
import glob
import cv2
import os
import numpy as np
from keras.models import load_model
labels = ["100won", "10won", "500won", "50won"]
model = load_model('model/my_model.h5')
img_path = glob.glob("data/origin_images/*.jpg")
for path in img_path:
# Read image
org = cv2.imread(path)
img = cv2.resize(org, (0, 0), fx=0.2, fy=0.2, interpolation=cv2.INTER_AREA)
# Convert image to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Blur
blur = cv2.GaussianBlur(gray, (0, 0), 3)
# Adaptive threshold
th = cv2.adaptiveThreshold(
blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 11, 2)
# Contour
contours, hier = cv2.findContours(
th, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
# Draw contour
dst = img.copy()
idx = 0
while idx >= 0:
# Filter area
cnt = contours[idx]
area = cv2.contourArea(cnt)
if 500 > area or area > 6000:
idx = hier[0, idx, 0]
continue
# Filter aspect ratio
_, _, w, h = cv2.boundingRect(cnt)
aspect_ratio = w / h
if abs(1 - aspect_ratio) > 0.4:
idx = hier[0, idx, 0]
continue
# Convex hull
hull = cv2.convexHull(contours[idx])
# Fit rectangle
x, y, w, h = cv2.boundingRect(hull)
# Draw rectangle
cv2.rectangle(dst, (x, y), (x+w, y+h), (0, 0, 255), 1)
idx = hier[0, idx, 0]
# Crop coin image
coin = org[y*5:(y+h)*5, x*5:(x+w)*5, :]
coin = cv2.resize(coin, (300, 300), interpolation=cv2.INTER_AREA)
# Predict
coin = coin.reshape(-1, 300, 300, 3)
prediction = model.predict([coin])
label = labels[np.argmax(prediction)]
# Show label
cv2.putText(dst, label, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0))
# Show
title = os.path.basename(path)
# cv2.imshow(title + " - img", img)
# cv2.imshow(title + " - gray", gray)
# cv2.imshow(title + " - th", th)
cv2.imshow(title + " - dst", dst)
while cv2.waitKey(0) != ord('q'):
pass
cv2.destroyAllWindows() | coin_predict.py | import glob
import cv2
import os
import numpy as np
from keras.models import load_model
labels = ["100won", "10won", "500won", "50won"]
model = load_model('model/my_model.h5')
img_path = glob.glob("data/origin_images/*.jpg")
for path in img_path:
# Read image
org = cv2.imread(path)
img = cv2.resize(org, (0, 0), fx=0.2, fy=0.2, interpolation=cv2.INTER_AREA)
# Convert image to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Blur
blur = cv2.GaussianBlur(gray, (0, 0), 3)
# Adaptive threshold
th = cv2.adaptiveThreshold(
blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 11, 2)
# Contour
contours, hier = cv2.findContours(
th, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
# Draw contour
dst = img.copy()
idx = 0
while idx >= 0:
# Filter area
cnt = contours[idx]
area = cv2.contourArea(cnt)
if 500 > area or area > 6000:
idx = hier[0, idx, 0]
continue
# Filter aspect ratio
_, _, w, h = cv2.boundingRect(cnt)
aspect_ratio = w / h
if abs(1 - aspect_ratio) > 0.4:
idx = hier[0, idx, 0]
continue
# Convex hull
hull = cv2.convexHull(contours[idx])
# Fit rectangle
x, y, w, h = cv2.boundingRect(hull)
# Draw rectangle
cv2.rectangle(dst, (x, y), (x+w, y+h), (0, 0, 255), 1)
idx = hier[0, idx, 0]
# Crop coin image
coin = org[y*5:(y+h)*5, x*5:(x+w)*5, :]
coin = cv2.resize(coin, (300, 300), interpolation=cv2.INTER_AREA)
# Predict
coin = coin.reshape(-1, 300, 300, 3)
prediction = model.predict([coin])
label = labels[np.argmax(prediction)]
# Show label
cv2.putText(dst, label, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0))
# Show
title = os.path.basename(path)
# cv2.imshow(title + " - img", img)
# cv2.imshow(title + " - gray", gray)
# cv2.imshow(title + " - th", th)
cv2.imshow(title + " - dst", dst)
while cv2.waitKey(0) != ord('q'):
pass
cv2.destroyAllWindows() | 0.47317 | 0.258301 |
import numpy as np
from reciprocalspaceship.dtypes import MTZIntDtype
def add_rfree(dataset, fraction=0.05, bins=20, inplace=False):
"""
Add an r-free flag to the dataset object for refinement.
R-free flags are used to identify reflections which are not used in automated refinement routines.
This is the crystallographic refinement version of cross validation.
Parameters
----------
dataset : rs.DataSet
Dataset object for which to compute a random fraction.
fraction : float, optional
Fraction of reflections to be added to the r-free. (the default is 0.05)
bins : int, optional
Number of resolution bins to divide the free reflections over. (the default is 20)
inplace : bool, optional
Returns:
--------
result : rs.DataSet
"""
if not inplace:
dataset = dataset.copy()
dHKL_present = 'dHKL' in dataset
if not dHKL_present:
dataset = dataset.compute_dHKL(inplace=True)
bin_edges = np.percentile(dataset['dHKL'], np.linspace(100, 0, bins+1))
bin_edges = np.vstack([bin_edges[:-1], bin_edges[1:]]).T
dataset['R-free-flags'] = 0
dataset['R-free-flags'] = dataset['R-free-flags'].astype(MTZIntDtype())
free = np.random.random(len(dataset)) <= fraction
for i in range(bins):
dmax,dmin = bin_edges[i]
dataset[free & (dataset['dHKL'] >= dmin) & (dataset['dHKL'] <= dmax)] = i
if not dHKL_present:
del(dataset['dHKL'])
return dataset
def copy_rfree(dataset, dataset_with_rfree, inplace=False):
"""
Copy the rfree flag from one dataset object to another.
Parameters
----------
dataset : rs.DataSet
A dataset without an r-free flag or with an undesired one.
dataset_with_rfree : rs.DataSet
A dataset with desired r-free flags.
inplace : bool, optional
Returns:
result : rs.DataSet
"""
if not inplace:
dataset = dataset.copy()
dataset['R-free-flags'] = 0
dataset['R-free-flags'] = dataset['R-free-flags'].astype(MTZIntDtype())
idx = dataset.index.intersection(dataset_with_rfree.index)
dataset.loc[idx, "R-free-flags"] = dataset_with_rfree.loc[idx, "R-free-flags"]
return dataset | reciprocalspaceship/utils/rfree.py | import numpy as np
from reciprocalspaceship.dtypes import MTZIntDtype
def add_rfree(dataset, fraction=0.05, bins=20, inplace=False):
"""
Add an r-free flag to the dataset object for refinement.
R-free flags are used to identify reflections which are not used in automated refinement routines.
This is the crystallographic refinement version of cross validation.
Parameters
----------
dataset : rs.DataSet
Dataset object for which to compute a random fraction.
fraction : float, optional
Fraction of reflections to be added to the r-free. (the default is 0.05)
bins : int, optional
Number of resolution bins to divide the free reflections over. (the default is 20)
inplace : bool, optional
Returns:
--------
result : rs.DataSet
"""
if not inplace:
dataset = dataset.copy()
dHKL_present = 'dHKL' in dataset
if not dHKL_present:
dataset = dataset.compute_dHKL(inplace=True)
bin_edges = np.percentile(dataset['dHKL'], np.linspace(100, 0, bins+1))
bin_edges = np.vstack([bin_edges[:-1], bin_edges[1:]]).T
dataset['R-free-flags'] = 0
dataset['R-free-flags'] = dataset['R-free-flags'].astype(MTZIntDtype())
free = np.random.random(len(dataset)) <= fraction
for i in range(bins):
dmax,dmin = bin_edges[i]
dataset[free & (dataset['dHKL'] >= dmin) & (dataset['dHKL'] <= dmax)] = i
if not dHKL_present:
del(dataset['dHKL'])
return dataset
def copy_rfree(dataset, dataset_with_rfree, inplace=False):
"""
Copy the rfree flag from one dataset object to another.
Parameters
----------
dataset : rs.DataSet
A dataset without an r-free flag or with an undesired one.
dataset_with_rfree : rs.DataSet
A dataset with desired r-free flags.
inplace : bool, optional
Returns:
result : rs.DataSet
"""
if not inplace:
dataset = dataset.copy()
dataset['R-free-flags'] = 0
dataset['R-free-flags'] = dataset['R-free-flags'].astype(MTZIntDtype())
idx = dataset.index.intersection(dataset_with_rfree.index)
dataset.loc[idx, "R-free-flags"] = dataset_with_rfree.loc[idx, "R-free-flags"]
return dataset | 0.870088 | 0.554018 |
import os
import sys
from glob import glob
import setuptools
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext as _build_ext
from distutils.sysconfig import get_config_var, get_python_inc
from distutils.version import LooseVersion
import versioneer
assert LooseVersion(setuptools.__version__) >= LooseVersion("18.0"), \
"Requires `setuptools` version 18.0 or higher."
class build_ext(_build_ext):
def finalize_options(self):
_build_ext.finalize_options(self)
# Prevent numpy from thinking it is still in its setup process:
__builtins__.__NUMPY_SETUP__ = False
import numpy
self.include_dirs.append(numpy.get_include())
def readme():
with open("README.rst", "r") as f:
return(f.read())
version = versioneer.get_version()
with open("src/version.pxi", "w") as f:
f.writelines([
"__version__ = " + "\"" + str(version) + "\""
])
cython_dep = ["cython >= 0.23"]
numpy_dep = ["numpy >= 1.7"]
boost_dep = ["boost-cpp >= 1.56"]
boost_dep = (boost_dep if sys.argv[1] == "bdist_conda" else [])
setup_requires = cython_dep + numpy_dep
setup_requires = setup_requires if (sys.argv[1].startswith("bdist") or
sys.argv[1].startswith("build") or
sys.argv[1].startswith("install")) else []
build_requires = cython_dep + numpy_dep + boost_dep
install_requires = numpy_dep + boost_dep
install_requires += [] if sys.argv[1] == "bdist_conda" else cython_dep
tests_require = cython_dep + numpy_dep
include_dirs = [
os.path.join(os.path.dirname(os.path.abspath(__file__)), "include"),
os.path.dirname(get_python_inc()),
get_python_inc()
]
library_dirs = list(filter(
lambda v: v is not None,
[get_config_var("LIBDIR")]
))
sources = glob("src/*.pxd") + glob("src/*.pyx")
libraries = []
if os.name == "posix":
libraries.append("boost_container")
elif os.name == "nt":
libname = "boost_container"
path = os.environ.get("LIB", "").split(";")
libmatches = sum(
list(glob(os.path.join(p, "%s*.lib" % libname)) for p in path), []
)
library_dirs.append(os.path.dirname(libmatches[0]))
libraries.append(os.path.splitext(os.path.basename(libmatches[0]))[0])
extra_compile_args = []
setup(
name="rank_filter",
version=version,
description="A simple python module containing an in-place linear rank"
" filter optimized in C++.",
long_description=readme(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX :: Linux',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Programming Language :: C++',
'Programming Language :: Cython',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Topic :: Scientific/Engineering',
'Topic :: Software Development :: Libraries'
],
author="<NAME>",
author_email="<EMAIL>",
url="https://github.com/nanshe-org/rank_filter",
download_url="https://github.com/nanshe-org/rank_filter/archive/v%s.tar.gz"
% version,
license="BSD",
cmdclass=dict(
list(versioneer.get_cmdclass().items()) +
[
('build_ext', build_ext)
]
),
setup_requires=setup_requires,
build_requires=build_requires,
install_requires=install_requires,
tests_require=tests_require,
test_suite="tests",
headers=glob("include/*.hxx"),
ext_modules=[Extension("rank_filter",
sources=sources,
include_dirs=include_dirs,
library_dirs=library_dirs,
libraries=libraries,
extra_compile_args=extra_compile_args,
language="c++")],
zip_safe=False
) | setup.py | import os
import sys
from glob import glob
import setuptools
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext as _build_ext
from distutils.sysconfig import get_config_var, get_python_inc
from distutils.version import LooseVersion
import versioneer
assert LooseVersion(setuptools.__version__) >= LooseVersion("18.0"), \
"Requires `setuptools` version 18.0 or higher."
class build_ext(_build_ext):
def finalize_options(self):
_build_ext.finalize_options(self)
# Prevent numpy from thinking it is still in its setup process:
__builtins__.__NUMPY_SETUP__ = False
import numpy
self.include_dirs.append(numpy.get_include())
def readme():
with open("README.rst", "r") as f:
return(f.read())
version = versioneer.get_version()
with open("src/version.pxi", "w") as f:
f.writelines([
"__version__ = " + "\"" + str(version) + "\""
])
cython_dep = ["cython >= 0.23"]
numpy_dep = ["numpy >= 1.7"]
boost_dep = ["boost-cpp >= 1.56"]
boost_dep = (boost_dep if sys.argv[1] == "bdist_conda" else [])
setup_requires = cython_dep + numpy_dep
setup_requires = setup_requires if (sys.argv[1].startswith("bdist") or
sys.argv[1].startswith("build") or
sys.argv[1].startswith("install")) else []
build_requires = cython_dep + numpy_dep + boost_dep
install_requires = numpy_dep + boost_dep
install_requires += [] if sys.argv[1] == "bdist_conda" else cython_dep
tests_require = cython_dep + numpy_dep
include_dirs = [
os.path.join(os.path.dirname(os.path.abspath(__file__)), "include"),
os.path.dirname(get_python_inc()),
get_python_inc()
]
library_dirs = list(filter(
lambda v: v is not None,
[get_config_var("LIBDIR")]
))
sources = glob("src/*.pxd") + glob("src/*.pyx")
libraries = []
if os.name == "posix":
libraries.append("boost_container")
elif os.name == "nt":
libname = "boost_container"
path = os.environ.get("LIB", "").split(";")
libmatches = sum(
list(glob(os.path.join(p, "%s*.lib" % libname)) for p in path), []
)
library_dirs.append(os.path.dirname(libmatches[0]))
libraries.append(os.path.splitext(os.path.basename(libmatches[0]))[0])
extra_compile_args = []
setup(
name="rank_filter",
version=version,
description="A simple python module containing an in-place linear rank"
" filter optimized in C++.",
long_description=readme(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX :: Linux',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Programming Language :: C++',
'Programming Language :: Cython',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Topic :: Scientific/Engineering',
'Topic :: Software Development :: Libraries'
],
author="<NAME>",
author_email="<EMAIL>",
url="https://github.com/nanshe-org/rank_filter",
download_url="https://github.com/nanshe-org/rank_filter/archive/v%s.tar.gz"
% version,
license="BSD",
cmdclass=dict(
list(versioneer.get_cmdclass().items()) +
[
('build_ext', build_ext)
]
),
setup_requires=setup_requires,
build_requires=build_requires,
install_requires=install_requires,
tests_require=tests_require,
test_suite="tests",
headers=glob("include/*.hxx"),
ext_modules=[Extension("rank_filter",
sources=sources,
include_dirs=include_dirs,
library_dirs=library_dirs,
libraries=libraries,
extra_compile_args=extra_compile_args,
language="c++")],
zip_safe=False
) | 0.309337 | 0.095139 |
import nnpy
import ptf
import ptf.platforms.nn as nn
import ptf.ptfutils as ptfutils
import ptf.packet as scapy
import ptf.mask as mask
from ptf.base_tests import BaseTest
from ptf.dataplane import DataPlane, DataPlanePortNN
from tests.common.utilities import wait_until
class PtfAdapterNNConnectionError(Exception):
def __init__(self, remote_sock_addr):
super(PtfAdapterNNConnectionError, self).__init__(
"Failed to connect to ptf_nn_agent('%s')" % remote_sock_addr
)
self.remote_sock_addr = remote_sock_addr
class PtfTestAdapter(BaseTest):
"""PtfTestAdapater class provides interface for pytest to use ptf.testutils functions """
DEFAULT_PTF_QUEUE_LEN = 100000
DEFAULT_PTF_TIMEOUT = 2
DEFAULT_PTF_NEG_TIMEOUT = 0.1
# the number of currently established connections
NN_STAT_CURRENT_CONNECTIONS = 201
def __init__(self, ptf_ip, ptf_nn_port, device_num, ptf_port_set):
""" initialize PtfTestAdapter
:param ptf_ip: PTF host IP
:param ptf_nn_port: PTF nanomessage agent port
:param device_num: device number
:param ptf_port_set: PTF ports
:return:
"""
self.runTest = lambda : None # set a no op runTest attribute to satisfy BaseTest interface
super(PtfTestAdapter, self).__init__()
self.payload_pattern = ""
self.connected = False
self._init_ptf_dataplane(ptf_ip, ptf_nn_port, device_num, ptf_port_set)
def __enter__(self):
""" enter in 'with' block """
return self
def __exit__(self, exc_type, exc_val, exc_tb):
""" exit from 'with' block """
if exc_type != PtfAdapterNNConnectionError:
self.kill()
def _check_ptf_nn_agent_availability(self, socket_addr):
"""Verify the nanomsg socket address exposed by ptf_nn_agent is available."""
sock = nnpy.Socket(nnpy.AF_SP, nnpy.PAIR)
sock.connect(socket_addr)
try:
return wait_until(1, 0.2, lambda:sock.get_statistic(self.NN_STAT_CURRENT_CONNECTIONS) == 1)
finally:
sock.close()
def _init_ptf_dataplane(self, ptf_ip, ptf_nn_port, device_num, ptf_port_set, ptf_config=None):
"""
initialize ptf framework and establish connection to ptf_nn_agent
running on PTF host
:param ptf_ip: PTF host IP
:param ptf_nn_port: PTF nanomessage agent port
:param device_num: device number
:param ptf_port_set: PTF ports
:return:
"""
self.ptf_ip = ptf_ip
self.ptf_nn_port = ptf_nn_port
self.device_num = device_num
self.ptf_port_set = ptf_port_set
self.connected = False
ptfutils.default_timeout = self.DEFAULT_PTF_TIMEOUT
ptfutils.default_negative_timeout = self.DEFAULT_PTF_NEG_TIMEOUT
ptf_nn_sock_addr = 'tcp://{}:{}'.format(ptf_ip, ptf_nn_port)
ptf.config.update({
'platform': 'nn',
'device_sockets': [
(device_num, ptf_port_set, ptf_nn_sock_addr)
],
'qlen': self.DEFAULT_PTF_QUEUE_LEN,
'relax': True,
})
if ptf_config is not None:
ptf.config.update(ptf_config)
if not self._check_ptf_nn_agent_availability(ptf_nn_sock_addr):
raise PtfAdapterNNConnectionError(ptf_nn_sock_addr)
# update ptf.config based on NN platform and create dataplane instance
nn.platform_config_update(ptf.config)
ptf.dataplane_instance = DataPlane(config=ptf.config)
# TODO: in case of multi PTF hosts topologies we'll have to provide custom platform that supports that
# and initialize port_map specifying mapping between tcp://<host>:<port> and port tuple (device_id, port_id)
for id, ifname in ptf.config['port_map'].items():
device_id, port_id = id
ptf.dataplane_instance.port_add(ifname, device_id, port_id)
self.connected = True
self.dataplane = ptf.dataplane_instance
def kill(self):
""" Close dataplane socket and kill data plane thread """
if self.connected:
self.dataplane.kill()
for injector in DataPlanePortNN.packet_injecters.values():
injector.socket.close()
DataPlanePortNN.packet_injecters.clear()
self.connected = False
def reinit(self, ptf_config=None):
""" reinitialize ptf data plane thread.
In case if test changes PTF host network configuration (like MAC change on interfaces)
reinit() method has to be called to restart data plane thread.
Also if test wants to restart PTF data plane specifying non-default PTF configuration
:param ptf_config: PTF configuration dictionary
"""
self.kill()
self._init_ptf_dataplane(self.ptf_ip, self.ptf_nn_port, self.device_num, self.ptf_port_set, ptf_config)
def update_payload(self, pkt):
"""Update the payload of packet to the default pattern when certain conditions are met.
The packet passed in could be a regular scapy packet or a masked packet. If it is a regular scapy packet and
has UDP or TCP header, then update its TCP or UDP payload.
If it is a masked packet, then its 'exp_pkt' is the regular scapy packet. Update the payload of its 'exp_pkt'
properly.
Args:
pkt [scapy packet or masked packet]: The packet to be updated.
Returns:
[scapy packet or masked packet]: Returns the packet with payload part updated.
"""
if isinstance(pkt, scapy.Ether):
for proto in (scapy.UDP, scapy.TCP):
if proto in pkt:
pkt[proto].load = self._update_payload(pkt[proto].load)
elif isinstance(pkt, mask.Mask):
for proto in (scapy.UDP, scapy.TCP):
if proto in pkt.exp_pkt:
pkt.exp_pkt[proto].load = self._update_payload(pkt.exp_pkt[proto].load)
return pkt
def _update_payload(self, payload):
"""Update payload to the default_pattern if default_pattern is set.
If length of the payload_pattern is longer payload, truncate payload_pattern to the length of payload.
Otherwise, repeat the payload_pattern to reach the length of payload. Keep length of updated payload same
as the original payload.
Args:
payload [string]: The payload to be updated.
Returns:
[string]: The updated payload.
"""
if self.payload_pattern:
len_old = len(payload)
len_new = len(self.payload_pattern)
if len_new >= len_old:
return self.payload_pattern[:len_old]
else:
factor = len_old/len_new + 1
new_payload = self.payload_pattern * factor
return new_payload[:len_old]
else:
return payload | tests/common/plugins/ptfadapter/ptfadapter.py | import nnpy
import ptf
import ptf.platforms.nn as nn
import ptf.ptfutils as ptfutils
import ptf.packet as scapy
import ptf.mask as mask
from ptf.base_tests import BaseTest
from ptf.dataplane import DataPlane, DataPlanePortNN
from tests.common.utilities import wait_until
class PtfAdapterNNConnectionError(Exception):
def __init__(self, remote_sock_addr):
super(PtfAdapterNNConnectionError, self).__init__(
"Failed to connect to ptf_nn_agent('%s')" % remote_sock_addr
)
self.remote_sock_addr = remote_sock_addr
class PtfTestAdapter(BaseTest):
"""PtfTestAdapater class provides interface for pytest to use ptf.testutils functions """
DEFAULT_PTF_QUEUE_LEN = 100000
DEFAULT_PTF_TIMEOUT = 2
DEFAULT_PTF_NEG_TIMEOUT = 0.1
# the number of currently established connections
NN_STAT_CURRENT_CONNECTIONS = 201
def __init__(self, ptf_ip, ptf_nn_port, device_num, ptf_port_set):
""" initialize PtfTestAdapter
:param ptf_ip: PTF host IP
:param ptf_nn_port: PTF nanomessage agent port
:param device_num: device number
:param ptf_port_set: PTF ports
:return:
"""
self.runTest = lambda : None # set a no op runTest attribute to satisfy BaseTest interface
super(PtfTestAdapter, self).__init__()
self.payload_pattern = ""
self.connected = False
self._init_ptf_dataplane(ptf_ip, ptf_nn_port, device_num, ptf_port_set)
def __enter__(self):
""" enter in 'with' block """
return self
def __exit__(self, exc_type, exc_val, exc_tb):
""" exit from 'with' block """
if exc_type != PtfAdapterNNConnectionError:
self.kill()
def _check_ptf_nn_agent_availability(self, socket_addr):
"""Verify the nanomsg socket address exposed by ptf_nn_agent is available."""
sock = nnpy.Socket(nnpy.AF_SP, nnpy.PAIR)
sock.connect(socket_addr)
try:
return wait_until(1, 0.2, lambda:sock.get_statistic(self.NN_STAT_CURRENT_CONNECTIONS) == 1)
finally:
sock.close()
def _init_ptf_dataplane(self, ptf_ip, ptf_nn_port, device_num, ptf_port_set, ptf_config=None):
"""
initialize ptf framework and establish connection to ptf_nn_agent
running on PTF host
:param ptf_ip: PTF host IP
:param ptf_nn_port: PTF nanomessage agent port
:param device_num: device number
:param ptf_port_set: PTF ports
:return:
"""
self.ptf_ip = ptf_ip
self.ptf_nn_port = ptf_nn_port
self.device_num = device_num
self.ptf_port_set = ptf_port_set
self.connected = False
ptfutils.default_timeout = self.DEFAULT_PTF_TIMEOUT
ptfutils.default_negative_timeout = self.DEFAULT_PTF_NEG_TIMEOUT
ptf_nn_sock_addr = 'tcp://{}:{}'.format(ptf_ip, ptf_nn_port)
ptf.config.update({
'platform': 'nn',
'device_sockets': [
(device_num, ptf_port_set, ptf_nn_sock_addr)
],
'qlen': self.DEFAULT_PTF_QUEUE_LEN,
'relax': True,
})
if ptf_config is not None:
ptf.config.update(ptf_config)
if not self._check_ptf_nn_agent_availability(ptf_nn_sock_addr):
raise PtfAdapterNNConnectionError(ptf_nn_sock_addr)
# update ptf.config based on NN platform and create dataplane instance
nn.platform_config_update(ptf.config)
ptf.dataplane_instance = DataPlane(config=ptf.config)
# TODO: in case of multi PTF hosts topologies we'll have to provide custom platform that supports that
# and initialize port_map specifying mapping between tcp://<host>:<port> and port tuple (device_id, port_id)
for id, ifname in ptf.config['port_map'].items():
device_id, port_id = id
ptf.dataplane_instance.port_add(ifname, device_id, port_id)
self.connected = True
self.dataplane = ptf.dataplane_instance
def kill(self):
""" Close dataplane socket and kill data plane thread """
if self.connected:
self.dataplane.kill()
for injector in DataPlanePortNN.packet_injecters.values():
injector.socket.close()
DataPlanePortNN.packet_injecters.clear()
self.connected = False
def reinit(self, ptf_config=None):
""" reinitialize ptf data plane thread.
In case if test changes PTF host network configuration (like MAC change on interfaces)
reinit() method has to be called to restart data plane thread.
Also if test wants to restart PTF data plane specifying non-default PTF configuration
:param ptf_config: PTF configuration dictionary
"""
self.kill()
self._init_ptf_dataplane(self.ptf_ip, self.ptf_nn_port, self.device_num, self.ptf_port_set, ptf_config)
def update_payload(self, pkt):
"""Update the payload of packet to the default pattern when certain conditions are met.
The packet passed in could be a regular scapy packet or a masked packet. If it is a regular scapy packet and
has UDP or TCP header, then update its TCP or UDP payload.
If it is a masked packet, then its 'exp_pkt' is the regular scapy packet. Update the payload of its 'exp_pkt'
properly.
Args:
pkt [scapy packet or masked packet]: The packet to be updated.
Returns:
[scapy packet or masked packet]: Returns the packet with payload part updated.
"""
if isinstance(pkt, scapy.Ether):
for proto in (scapy.UDP, scapy.TCP):
if proto in pkt:
pkt[proto].load = self._update_payload(pkt[proto].load)
elif isinstance(pkt, mask.Mask):
for proto in (scapy.UDP, scapy.TCP):
if proto in pkt.exp_pkt:
pkt.exp_pkt[proto].load = self._update_payload(pkt.exp_pkt[proto].load)
return pkt
def _update_payload(self, payload):
"""Update payload to the default_pattern if default_pattern is set.
If length of the payload_pattern is longer payload, truncate payload_pattern to the length of payload.
Otherwise, repeat the payload_pattern to reach the length of payload. Keep length of updated payload same
as the original payload.
Args:
payload [string]: The payload to be updated.
Returns:
[string]: The updated payload.
"""
if self.payload_pattern:
len_old = len(payload)
len_new = len(self.payload_pattern)
if len_new >= len_old:
return self.payload_pattern[:len_old]
else:
factor = len_old/len_new + 1
new_payload = self.payload_pattern * factor
return new_payload[:len_old]
else:
return payload | 0.628179 | 0.323327 |
# Part of the PsychoPy library
# Copyright (C) 2002-2018 <NAME> (C) 2019-2021 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
from __future__ import absolute_import, print_function
from psychopy.visual.shape import BaseShapeStim
from psychopy.tools.attributetools import attributeSetter, setAttribute
import numpy as np
class Pie(BaseShapeStim):
"""Creates a pie shape which is a circle with a wedge cut-out.
This shape is sometimes referred to as a Pac-Man shape which is often
used for creating Kanizsa figures. However, the shape can be adapted for
other uses.
Parameters
----------
win : :class:`~psychopy.visual.Window`
Window this shape is being drawn to. The stimulus instance will
allocate its required resources using that Windows context. In many
cases, a stimulus instance cannot be drawn on different windows
unless those windows share the same OpenGL context, which permits
resources to be shared between them.
radius : float or int
Radius of the shape. Avoid using `size` for adjusting figure
dimensions if radius != 0.5 which will result in undefined behavior.
start, end : float or int
Start and end angles of the filled region of the shape in
degrees. Shapes are filled counter clockwise between the specified
angles.
edges : int
Number of edges to use when drawing the figure. A greater number of
edges will result in smoother curves, but will require more time
to compute.
units : str
Units to use when drawing. This will affect how parameters and
attributes `pos`, `size` and `radius` are interpreted.
lineWidth : float
Width of the shape's outline.
lineColor, fillColor : array_like, str, :class:`~psychopy.colors.Color` or None
Color of the shape outline and fill. If `None`, a fully transparent
color is used which makes the fill or outline invisible.
lineColorSpace, fillColorSpace : str
Colorspace to use for the outline and fill. These change how the
values passed to `lineColor` and `fillColor` are interpreted.
*Deprecated*. Please use `colorSpace` to set both outline and fill
colorspace. These arguments may be removed in a future version.
pos : array_like
Initial position (`x`, `y`) of the shape on-screen relative to
the origin located at the center of the window or buffer in `units`.
This can be updated after initialization by setting the `pos`
property. The default value is `(0.0, 0.0)` which results in no
translation.
size : array_like, float, int or None
Width and height of the shape as `(w, h)` or `[w, h]`. If a single
value is provided, the width and height will be set to the same
specified value. If `None` is specified, the `size` will be set
with values passed to `width` and `height`.
ori : float
Initial orientation of the shape in degrees about its origin.
Positive values will rotate the shape clockwise, while negative
values will rotate counterclockwise. The default value for `ori` is
0.0 degrees.
opacity : float
Opacity of the shape. A value of 1.0 indicates fully opaque and 0.0
is fully transparent (therefore invisible). Values between 1.0 and
0.0 will result in colors being blended with objects in the
background. This value affects the fill (`fillColor`) and outline
(`lineColor`) colors of the shape.
contrast : float
Contrast level of the shape (0.0 to 1.0). This value is used to
modulate the contrast of colors passed to `lineColor` and
`fillColor`.
depth : int
Depth layer to draw the shape when `autoDraw` is enabled.
*DEPRECATED*
interpolate : bool
Enable smoothing (anti-aliasing) when drawing shape outlines. This
produces a smoother (less-pixelated) outline of the shape.
lineRGB, fillRGB: array_like, :class:`~psychopy.colors.Color` or None
*Deprecated*. Please use `lineColor` and `fillColor`. These
arguments may be removed in a future version.
name : str
Optional name of the stimuli for logging.
autoLog : bool
Enable auto-logging of events associated with this stimuli. Useful
for debugging and to track timing when used in conjunction with
`autoDraw`.
autoDraw : bool
Enable auto drawing. When `True`, the stimulus will be drawn every
frame without the need to explicitly call the
:py:meth:`~psychopy.visual.shape.ShapeStim.draw()` method.
color : array_like, str, :class:`~psychopy.colors.Color` or None
Sets both the initial `lineColor` and `fillColor` of the shape.
colorSpace : str
Sets the colorspace, changing how values passed to `lineColor` and
`fillColor` are interpreted.
Attributes
----------
start, end : float or int
Start and end angles of the filled region of the shape in
degrees. Shapes are filled counter clockwise between the specified
angles.
radius : float or int
Radius of the shape. Avoid using `size` for adjusting figure dimensions
if radius != 0.5 which will result in undefined behavior.
"""
def __init__(self,
win,
radius=.5,
start=0.0,
end=90.0,
edges=32,
units='',
lineWidth=1.5,
lineColor=None,
lineColorSpace='rgb',
fillColor=None,
fillColorSpace='rgb',
pos=(0, 0),
size=1.0,
ori=0.0,
opacity=1.0,
contrast=1.0,
depth=0,
interpolate=True,
lineRGB=False,
fillRGB=False,
name=None,
autoLog=None,
autoDraw=False,
color=None,
colorSpace=None):
self.__dict__['radius'] = radius
self.__dict__['edges'] = edges
self.__dict__['start'] = start
self.__dict__['end'] = end
self.vertices = self._calcVertices()
super(Pie, self).__init__(
win,
units=units,
lineWidth=lineWidth,
lineColor=lineColor,
lineColorSpace=lineColorSpace,
fillColor=fillColor,
fillColorSpace=fillColorSpace,
vertices=self.vertices,
closeShape=True,
pos=pos,
size=size,
ori=ori,
opacity=opacity,
contrast=contrast,
depth=depth,
interpolate=interpolate,
lineRGB=lineRGB,
fillRGB=fillRGB,
name=name,
autoLog=autoLog,
autoDraw=autoDraw,
color=color,
colorSpace=colorSpace)
def _calcVertices(self):
"""Calculate the required vertices for the figure.
"""
startRadians = np.radians(self.start)
endRadians = np.radians(self.end)
# get number of steps for vertices
edges = self.__dict__['edges']
steps = np.linspace(startRadians, endRadians, num=edges)
# offset by 1 since the first vertex needs to be at centre
verts = np.zeros((edges + 2, 2), float)
verts[1:-1, 0] = np.sin(steps)
verts[1:-1, 1] = np.cos(steps)
verts *= self.radius
return verts
@attributeSetter
def start(self, value):
"""Start angle of the slice/wedge in degrees (`float` or `int`).
:ref:`Operations <attrib-operations>` supported.
"""
self.__dict__['start'] = value
self.vertices = self._calcVertices()
self.setVertices(self.vertices, log=False)
def setStart(self, start, operation='', log=None):
"""Usually you can use 'stim.attribute = value' syntax instead,
but use this method if you need to suppress the log message
"""
setAttribute(self, 'start', start, log, operation)
@attributeSetter
def end(self, value):
"""End angle of the slice/wedge in degrees (`float` or `int`).
:ref:`Operations <attrib-operations>` supported.
"""
self.__dict__['end'] = value
self.vertices = self._calcVertices()
self.setVertices(self.vertices, log=False)
def setEnd(self, end, operation='', log=None):
"""Usually you can use 'stim.attribute = value' syntax instead,
but use this method if you need to suppress the log message
"""
setAttribute(self, 'end', end, log, operation)
@attributeSetter
def radius(self, value):
"""Radius of the shape in `units` (`float` or `int`).
:ref:`Operations <attrib-operations>` supported.
"""
self.__dict__['radius'] = value
self.vertices = self._calcVertices()
self.setVertices(self.vertices, log=False)
def setRadius(self, end, operation='', log=None):
"""Usually you can use 'stim.attribute = value' syntax instead,
but use this method if you need to suppress the log message
"""
setAttribute(self, 'radius', end, log, operation) | venv/Lib/site-packages/psychopy/visual/pie.py | # Part of the PsychoPy library
# Copyright (C) 2002-2018 <NAME> (C) 2019-2021 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
from __future__ import absolute_import, print_function
from psychopy.visual.shape import BaseShapeStim
from psychopy.tools.attributetools import attributeSetter, setAttribute
import numpy as np
class Pie(BaseShapeStim):
"""Creates a pie shape which is a circle with a wedge cut-out.
This shape is sometimes referred to as a Pac-Man shape which is often
used for creating Kanizsa figures. However, the shape can be adapted for
other uses.
Parameters
----------
win : :class:`~psychopy.visual.Window`
Window this shape is being drawn to. The stimulus instance will
allocate its required resources using that Windows context. In many
cases, a stimulus instance cannot be drawn on different windows
unless those windows share the same OpenGL context, which permits
resources to be shared between them.
radius : float or int
Radius of the shape. Avoid using `size` for adjusting figure
dimensions if radius != 0.5 which will result in undefined behavior.
start, end : float or int
Start and end angles of the filled region of the shape in
degrees. Shapes are filled counter clockwise between the specified
angles.
edges : int
Number of edges to use when drawing the figure. A greater number of
edges will result in smoother curves, but will require more time
to compute.
units : str
Units to use when drawing. This will affect how parameters and
attributes `pos`, `size` and `radius` are interpreted.
lineWidth : float
Width of the shape's outline.
lineColor, fillColor : array_like, str, :class:`~psychopy.colors.Color` or None
Color of the shape outline and fill. If `None`, a fully transparent
color is used which makes the fill or outline invisible.
lineColorSpace, fillColorSpace : str
Colorspace to use for the outline and fill. These change how the
values passed to `lineColor` and `fillColor` are interpreted.
*Deprecated*. Please use `colorSpace` to set both outline and fill
colorspace. These arguments may be removed in a future version.
pos : array_like
Initial position (`x`, `y`) of the shape on-screen relative to
the origin located at the center of the window or buffer in `units`.
This can be updated after initialization by setting the `pos`
property. The default value is `(0.0, 0.0)` which results in no
translation.
size : array_like, float, int or None
Width and height of the shape as `(w, h)` or `[w, h]`. If a single
value is provided, the width and height will be set to the same
specified value. If `None` is specified, the `size` will be set
with values passed to `width` and `height`.
ori : float
Initial orientation of the shape in degrees about its origin.
Positive values will rotate the shape clockwise, while negative
values will rotate counterclockwise. The default value for `ori` is
0.0 degrees.
opacity : float
Opacity of the shape. A value of 1.0 indicates fully opaque and 0.0
is fully transparent (therefore invisible). Values between 1.0 and
0.0 will result in colors being blended with objects in the
background. This value affects the fill (`fillColor`) and outline
(`lineColor`) colors of the shape.
contrast : float
Contrast level of the shape (0.0 to 1.0). This value is used to
modulate the contrast of colors passed to `lineColor` and
`fillColor`.
depth : int
Depth layer to draw the shape when `autoDraw` is enabled.
*DEPRECATED*
interpolate : bool
Enable smoothing (anti-aliasing) when drawing shape outlines. This
produces a smoother (less-pixelated) outline of the shape.
lineRGB, fillRGB: array_like, :class:`~psychopy.colors.Color` or None
*Deprecated*. Please use `lineColor` and `fillColor`. These
arguments may be removed in a future version.
name : str
Optional name of the stimuli for logging.
autoLog : bool
Enable auto-logging of events associated with this stimuli. Useful
for debugging and to track timing when used in conjunction with
`autoDraw`.
autoDraw : bool
Enable auto drawing. When `True`, the stimulus will be drawn every
frame without the need to explicitly call the
:py:meth:`~psychopy.visual.shape.ShapeStim.draw()` method.
color : array_like, str, :class:`~psychopy.colors.Color` or None
Sets both the initial `lineColor` and `fillColor` of the shape.
colorSpace : str
Sets the colorspace, changing how values passed to `lineColor` and
`fillColor` are interpreted.
Attributes
----------
start, end : float or int
Start and end angles of the filled region of the shape in
degrees. Shapes are filled counter clockwise between the specified
angles.
radius : float or int
Radius of the shape. Avoid using `size` for adjusting figure dimensions
if radius != 0.5 which will result in undefined behavior.
"""
def __init__(self,
win,
radius=.5,
start=0.0,
end=90.0,
edges=32,
units='',
lineWidth=1.5,
lineColor=None,
lineColorSpace='rgb',
fillColor=None,
fillColorSpace='rgb',
pos=(0, 0),
size=1.0,
ori=0.0,
opacity=1.0,
contrast=1.0,
depth=0,
interpolate=True,
lineRGB=False,
fillRGB=False,
name=None,
autoLog=None,
autoDraw=False,
color=None,
colorSpace=None):
self.__dict__['radius'] = radius
self.__dict__['edges'] = edges
self.__dict__['start'] = start
self.__dict__['end'] = end
self.vertices = self._calcVertices()
super(Pie, self).__init__(
win,
units=units,
lineWidth=lineWidth,
lineColor=lineColor,
lineColorSpace=lineColorSpace,
fillColor=fillColor,
fillColorSpace=fillColorSpace,
vertices=self.vertices,
closeShape=True,
pos=pos,
size=size,
ori=ori,
opacity=opacity,
contrast=contrast,
depth=depth,
interpolate=interpolate,
lineRGB=lineRGB,
fillRGB=fillRGB,
name=name,
autoLog=autoLog,
autoDraw=autoDraw,
color=color,
colorSpace=colorSpace)
def _calcVertices(self):
"""Calculate the required vertices for the figure.
"""
startRadians = np.radians(self.start)
endRadians = np.radians(self.end)
# get number of steps for vertices
edges = self.__dict__['edges']
steps = np.linspace(startRadians, endRadians, num=edges)
# offset by 1 since the first vertex needs to be at centre
verts = np.zeros((edges + 2, 2), float)
verts[1:-1, 0] = np.sin(steps)
verts[1:-1, 1] = np.cos(steps)
verts *= self.radius
return verts
@attributeSetter
def start(self, value):
"""Start angle of the slice/wedge in degrees (`float` or `int`).
:ref:`Operations <attrib-operations>` supported.
"""
self.__dict__['start'] = value
self.vertices = self._calcVertices()
self.setVertices(self.vertices, log=False)
def setStart(self, start, operation='', log=None):
"""Usually you can use 'stim.attribute = value' syntax instead,
but use this method if you need to suppress the log message
"""
setAttribute(self, 'start', start, log, operation)
@attributeSetter
def end(self, value):
"""End angle of the slice/wedge in degrees (`float` or `int`).
:ref:`Operations <attrib-operations>` supported.
"""
self.__dict__['end'] = value
self.vertices = self._calcVertices()
self.setVertices(self.vertices, log=False)
def setEnd(self, end, operation='', log=None):
"""Usually you can use 'stim.attribute = value' syntax instead,
but use this method if you need to suppress the log message
"""
setAttribute(self, 'end', end, log, operation)
@attributeSetter
def radius(self, value):
"""Radius of the shape in `units` (`float` or `int`).
:ref:`Operations <attrib-operations>` supported.
"""
self.__dict__['radius'] = value
self.vertices = self._calcVertices()
self.setVertices(self.vertices, log=False)
def setRadius(self, end, operation='', log=None):
"""Usually you can use 'stim.attribute = value' syntax instead,
but use this method if you need to suppress the log message
"""
setAttribute(self, 'radius', end, log, operation) | 0.946609 | 0.663298 |
import os
from thermo import heatform
from thermo import util
import automol.inchi
import automol.smiles
# Inchi string for methyl nitrate (CH3ONO2)
ICH = 'InChI=1S/CH3NO3/c1-5-2(3)4/h1H3'
SMI = 'C=CC(=O)O'
ICH2 = automol.smiles.inchi(SMI)
# Thermp output file name
THERMP_OUTFILE_NAME = os.path.join(os.getcwd(), 'run', 'thermp.out')
def test__calc_hform_0k():
""" calculates 0 K heat-of-formation for a species
"""
# Get the molecular formula from the inchi string
#formula = util.inchi_formula(ICH)
formula = automol.inchi.formula(ICH)
print('\nformula:')
print(formula)
# Get atom count dictionary
#atom_dict = util.get_atom_counts_dict(formula)
atom_dict = automol.inchi.formula_dct(ICH)
print('\natom dict:')
print(atom_dict)
# Get the list of the basis
basis = heatform.select_basis(atom_dict)
print('\nbasis:')
print(basis)
# Get the basis list from reduced_basis
#red_basis = heatform.select_basis(basis_ich, formula)
#print('\nreduced basis:')
#print(red_basis)
# Get the coefficients for the balanced heat-of-formation eqn
coeff = heatform.calc_coefficients(basis, atom_dict)
print('\ncoeff:')
print(coeff)
# Obtain the reference energies from the database
print('\nref e:')
for spc in basis:
ref_e = heatform.get_ref_h(spc, 'ATcT', 0)
print(spc)
print(ref_e)
# Get the energy for the species and basis
e_mol = -100.0
e_basis = [-1.0, -2.0, -3.0, -4.0]
print('\ne_mol and e_basis:')
print(e_mol)
print(e_basis)
# Get the 0 K heat of formation
hform = heatform.calc_hform_0k(e_mol, e_basis, basis, coeff, ref_set='ATcT')
print('\nhform(0 K):')
print(hform)
def test__read_hform_298k():
""" reads the 298 K heat-of-formation value from thermp output
"""
# Read the thermp output
with open(THERMP_OUTFILE_NAME, 'r') as thermp_outfile:
thermp_out_str = thermp_outfile.read()
# Get the 0 K heat of formation
hform = heatform.get_hform_298k_thermp(thermp_out_str)
print('\nhform(298 K):')
print(hform)
def test__cbhzed():
""" Fragments molecule in a way that conserves each heavy-atom/heavy-atom bond
"""
frags = heatform.cbhzed(ICH2)
print('\nCBH0 formula: ', heatform._print_lhs_rhs(ICH2, frags))
def test__cbhone():
""" Fragments molecule in a way that conserves each heavy-atom/heavy-atom bond
"""
frags = heatform.cbhone(ICH2)
print('\nCBH1 formula: ', heatform._print_lhs_rhs(ICH2, frags))
def test__cbhtwo():
""" Fragments molecule in a way that conserves each heavy-atom/heavy-atom bond
"""
frags = heatform.cbhtwo(ICH2)
print('\nCBH2 formula: ', heatform._print_lhs_rhs(ICH2, frags))
if __name__ == '__main__':
test__calc_hform_0k()
test__read_hform_298k()
test__cbhzed()
test__cbhone()
test__cbhtwo() | tests/thermo/test__heatform.py | import os
from thermo import heatform
from thermo import util
import automol.inchi
import automol.smiles
# Inchi string for methyl nitrate (CH3ONO2)
ICH = 'InChI=1S/CH3NO3/c1-5-2(3)4/h1H3'
SMI = 'C=CC(=O)O'
ICH2 = automol.smiles.inchi(SMI)
# Thermp output file name
THERMP_OUTFILE_NAME = os.path.join(os.getcwd(), 'run', 'thermp.out')
def test__calc_hform_0k():
""" calculates 0 K heat-of-formation for a species
"""
# Get the molecular formula from the inchi string
#formula = util.inchi_formula(ICH)
formula = automol.inchi.formula(ICH)
print('\nformula:')
print(formula)
# Get atom count dictionary
#atom_dict = util.get_atom_counts_dict(formula)
atom_dict = automol.inchi.formula_dct(ICH)
print('\natom dict:')
print(atom_dict)
# Get the list of the basis
basis = heatform.select_basis(atom_dict)
print('\nbasis:')
print(basis)
# Get the basis list from reduced_basis
#red_basis = heatform.select_basis(basis_ich, formula)
#print('\nreduced basis:')
#print(red_basis)
# Get the coefficients for the balanced heat-of-formation eqn
coeff = heatform.calc_coefficients(basis, atom_dict)
print('\ncoeff:')
print(coeff)
# Obtain the reference energies from the database
print('\nref e:')
for spc in basis:
ref_e = heatform.get_ref_h(spc, 'ATcT', 0)
print(spc)
print(ref_e)
# Get the energy for the species and basis
e_mol = -100.0
e_basis = [-1.0, -2.0, -3.0, -4.0]
print('\ne_mol and e_basis:')
print(e_mol)
print(e_basis)
# Get the 0 K heat of formation
hform = heatform.calc_hform_0k(e_mol, e_basis, basis, coeff, ref_set='ATcT')
print('\nhform(0 K):')
print(hform)
def test__read_hform_298k():
""" reads the 298 K heat-of-formation value from thermp output
"""
# Read the thermp output
with open(THERMP_OUTFILE_NAME, 'r') as thermp_outfile:
thermp_out_str = thermp_outfile.read()
# Get the 0 K heat of formation
hform = heatform.get_hform_298k_thermp(thermp_out_str)
print('\nhform(298 K):')
print(hform)
def test__cbhzed():
""" Fragments molecule in a way that conserves each heavy-atom/heavy-atom bond
"""
frags = heatform.cbhzed(ICH2)
print('\nCBH0 formula: ', heatform._print_lhs_rhs(ICH2, frags))
def test__cbhone():
""" Fragments molecule in a way that conserves each heavy-atom/heavy-atom bond
"""
frags = heatform.cbhone(ICH2)
print('\nCBH1 formula: ', heatform._print_lhs_rhs(ICH2, frags))
def test__cbhtwo():
""" Fragments molecule in a way that conserves each heavy-atom/heavy-atom bond
"""
frags = heatform.cbhtwo(ICH2)
print('\nCBH2 formula: ', heatform._print_lhs_rhs(ICH2, frags))
if __name__ == '__main__':
test__calc_hform_0k()
test__read_hform_298k()
test__cbhzed()
test__cbhone()
test__cbhtwo() | 0.294114 | 0.286032 |
import json
from typing import Dict
from bamboo_engine import metrics, exceptions
from bamboo_engine.eri import Data, DataInput, ExecutionData, CallbackData
from pipeline.eri import codec
from pipeline.eri.models import Data as DBData
from pipeline.eri.models import ExecutionData as DBExecutionData
from pipeline.eri.models import CallbackData as DBCallbackData
from pipeline.eri.imp.serializer import SerializerMixin
class DataMixin(SerializerMixin):
def _get_data_inputs(self, inputs: dict):
return {k: DataInput(need_render=v["need_render"], value=v["value"]) for k, v in inputs.items()}
@metrics.setup_histogram(metrics.ENGINE_RUNTIME_DATA_READ_TIME)
def get_data(self, node_id: str) -> Data:
"""
获取某个节点的数据对象
:param node_id: 节点 ID
:type node_id: str
:return: 数据对象实例
:rtype: Data
"""
try:
data_model = DBData.objects.get(node_id=node_id)
except DBData.DoesNotExist:
raise exceptions.NotFoundError
return Data(
inputs=self._get_data_inputs(codec.data_json_loads(data_model.inputs)),
outputs=json.loads(data_model.outputs),
)
@metrics.setup_histogram(metrics.ENGINE_RUNTIME_DATA_INPUTS_READ_TIME)
def get_data_inputs(self, node_id: str) -> Dict[str, DataInput]:
"""
获取某个节点的输入数据
:param node_id: 节点 ID
:type node_id: str
:return: 输入数据字典
:rtype: dict
"""
qs = DBData.objects.filter(node_id=node_id).only("inputs")
if not qs:
raise exceptions.NotFoundError
return self._get_data_inputs(codec.data_json_loads(qs[0].inputs))
@metrics.setup_histogram(metrics.ENGINE_RUNTIME_DATA_OUTPUTS_READ_TIME)
def get_data_outputs(self, node_id: str) -> dict:
"""
获取某个节点的输出数据
:param node_id: 节点 ID
:type node_id: str
:return: 输入数据字典
:rtype: dict
"""
qs = DBData.objects.filter(node_id=node_id).only("outputs")
if not qs:
raise exceptions.NotFoundError
return json.loads(qs[0].outputs)
def set_data_inputs(self, node_id: str, data: Dict[str, DataInput]):
"""
将节点数据对象的 inputs 设置为 data
: param node_id: 节点 ID
: type node_id: str
: param data: 目标数据
: type data: dict
"""
inputs = codec.data_json_dumps({k: {"need_render": v.need_render, "value": v.value} for k, v in data.items()})
if DBData.objects.filter(node_id=node_id).exists():
DBData.objects.filter(node_id=node_id).update(inputs=inputs)
else:
DBData.objects.create(node_id=node_id, inputs=inputs, outputs="{}")
@metrics.setup_histogram(metrics.ENGINE_RUNTIME_EXEC_DATA_READ_TIME)
def get_execution_data(self, node_id: str) -> ExecutionData:
"""
获取某个节点的执行数据
: param node_id: 节点 ID
: type node_id: str
: return: 执行数据实例
: rtype: ExecutionData
"""
try:
data_model = DBExecutionData.objects.get(node_id=node_id)
except DBExecutionData.DoesNotExist:
raise exceptions.NotFoundError
return ExecutionData(
inputs=self._deserialize(data_model.inputs, data_model.inputs_serializer),
outputs=self._deserialize(data_model.outputs, data_model.outputs_serializer),
)
@metrics.setup_histogram(metrics.ENGINE_RUNTIME_EXEC_DATA_INPUTS_READ_TIME)
def get_execution_data_inputs(self, node_id: str) -> dict:
"""
获取某个节点的执行数据输入
:param node_id: 节点 ID
:type node_id: str
:return: 执行数据输入
:rtype: dict
"""
qs = DBExecutionData.objects.filter(node_id=node_id).only("inputs_serializer", "inputs")
if not qs:
return {}
return self._deserialize(qs[0].inputs, qs[0].inputs_serializer)
@metrics.setup_histogram(metrics.ENGINE_RUNTIME_EXEC_DATA_OUTPUTS_READ_TIME)
def get_execution_data_outputs(self, node_id: str) -> dict:
"""
获取某个节点的执行数据输出
:param node_id: 节点 ID
:type node_id: str
:return: 执行数据输出
:rtype: dict
"""
qs = DBExecutionData.objects.filter(node_id=node_id).only("outputs_serializer", "outputs")
if not qs:
return {}
return self._deserialize(qs[0].outputs, qs[0].outputs_serializer)
@metrics.setup_histogram(metrics.ENGINE_RUNTIME_EXEC_DATA_WRITE_TIME)
def set_execution_data(self, node_id: str, data: ExecutionData):
"""
设置某个节点的执行数据
:param node_id: 节点 ID
:type node_id: str
:param data: 执行数据实例
:type data: ExecutionData
"""
inputs, inputs_serializer = self._serialize(data.inputs)
outputs, outputs_serializer = self._serialize(data.outputs)
if DBExecutionData.objects.filter(node_id=node_id).exists():
DBExecutionData.objects.filter(node_id=node_id).update(
inputs=inputs,
inputs_serializer=inputs_serializer,
outputs=outputs,
outputs_serializer=outputs_serializer,
)
else:
DBExecutionData.objects.create(
node_id=node_id,
inputs=inputs,
inputs_serializer=inputs_serializer,
outputs=outputs,
outputs_serializer=outputs_serializer,
)
@metrics.setup_histogram(metrics.ENGINE_RUNTIME_EXEC_DATA_INPUTS_WRITE_TIME)
def set_execution_data_inputs(self, node_id: str, inputs: dict):
"""
设置某个节点的执行数据输入
:param node_id: 节点 ID
:type node_id: str
:param outputs: 输出数据
:type outputs: dict
"""
inputs, inputs_serializer = self._serialize(inputs)
if DBExecutionData.objects.filter(node_id=node_id).exists():
DBExecutionData.objects.filter(node_id=node_id).update(inputs=inputs, inputs_serializer=inputs_serializer)
else:
DBExecutionData.objects.create(
node_id=node_id,
inputs=inputs,
inputs_serializer=inputs_serializer,
outputs="{}",
outputs_serializer=self.JSON_SERIALIZER,
)
@metrics.setup_histogram(metrics.ENGINE_RUNTIME_EXEC_DATA_OUTPUTS_WRITE_TIME)
def set_execution_data_outputs(self, node_id: str, outputs: dict):
"""
设置某个节点的执行数据输出
:param node_id: 节点 ID
:type node_id: str
:param outputs: 输出数据
:type outputs: dict
"""
outputs, outputs_serializer = self._serialize(outputs)
if DBExecutionData.objects.filter(node_id=node_id).exists():
DBExecutionData.objects.filter(node_id=node_id).update(
outputs=outputs, outputs_serializer=outputs_serializer
)
else:
DBExecutionData.objects.create(
node_id=node_id,
inputs="{}",
inputs_serializer=self.JSON_SERIALIZER,
outputs=outputs,
outputs_serializer=outputs_serializer,
)
def set_callback_data(self, node_id: str, version: str, data: dict) -> int:
"""
设置某个节点执行数据的回调数据
:param node_id: 节点 ID
:type node_id: str
:param version: 节点执行版本
:type version: str
:param data: 回调数据
:type data: dict
:return: 回调数据 ID
:rtype: int
"""
return DBCallbackData.objects.create(node_id=node_id, version=version, data=json.dumps(data)).id
@metrics.setup_histogram(metrics.ENGINE_RUNTIME_CALLBACK_DATA_READ_TIME)
def get_callback_data(self, data_id: int) -> CallbackData:
"""
获取回调数据
:param data_id: Data ID
:type data_id: int
:return: 回调数据实例
:rtype: CallbackData
"""
data_model = DBCallbackData.objects.get(id=data_id)
return CallbackData(
id=data_model.id, node_id=data_model.node_id, version=data_model.version, data=json.loads(data_model.data)
) | runtime/bamboo-pipeline/pipeline/eri/imp/data.py | import json
from typing import Dict
from bamboo_engine import metrics, exceptions
from bamboo_engine.eri import Data, DataInput, ExecutionData, CallbackData
from pipeline.eri import codec
from pipeline.eri.models import Data as DBData
from pipeline.eri.models import ExecutionData as DBExecutionData
from pipeline.eri.models import CallbackData as DBCallbackData
from pipeline.eri.imp.serializer import SerializerMixin
class DataMixin(SerializerMixin):
def _get_data_inputs(self, inputs: dict):
return {k: DataInput(need_render=v["need_render"], value=v["value"]) for k, v in inputs.items()}
@metrics.setup_histogram(metrics.ENGINE_RUNTIME_DATA_READ_TIME)
def get_data(self, node_id: str) -> Data:
"""
获取某个节点的数据对象
:param node_id: 节点 ID
:type node_id: str
:return: 数据对象实例
:rtype: Data
"""
try:
data_model = DBData.objects.get(node_id=node_id)
except DBData.DoesNotExist:
raise exceptions.NotFoundError
return Data(
inputs=self._get_data_inputs(codec.data_json_loads(data_model.inputs)),
outputs=json.loads(data_model.outputs),
)
@metrics.setup_histogram(metrics.ENGINE_RUNTIME_DATA_INPUTS_READ_TIME)
def get_data_inputs(self, node_id: str) -> Dict[str, DataInput]:
"""
获取某个节点的输入数据
:param node_id: 节点 ID
:type node_id: str
:return: 输入数据字典
:rtype: dict
"""
qs = DBData.objects.filter(node_id=node_id).only("inputs")
if not qs:
raise exceptions.NotFoundError
return self._get_data_inputs(codec.data_json_loads(qs[0].inputs))
@metrics.setup_histogram(metrics.ENGINE_RUNTIME_DATA_OUTPUTS_READ_TIME)
def get_data_outputs(self, node_id: str) -> dict:
"""
获取某个节点的输出数据
:param node_id: 节点 ID
:type node_id: str
:return: 输入数据字典
:rtype: dict
"""
qs = DBData.objects.filter(node_id=node_id).only("outputs")
if not qs:
raise exceptions.NotFoundError
return json.loads(qs[0].outputs)
def set_data_inputs(self, node_id: str, data: Dict[str, DataInput]):
"""
将节点数据对象的 inputs 设置为 data
: param node_id: 节点 ID
: type node_id: str
: param data: 目标数据
: type data: dict
"""
inputs = codec.data_json_dumps({k: {"need_render": v.need_render, "value": v.value} for k, v in data.items()})
if DBData.objects.filter(node_id=node_id).exists():
DBData.objects.filter(node_id=node_id).update(inputs=inputs)
else:
DBData.objects.create(node_id=node_id, inputs=inputs, outputs="{}")
@metrics.setup_histogram(metrics.ENGINE_RUNTIME_EXEC_DATA_READ_TIME)
def get_execution_data(self, node_id: str) -> ExecutionData:
"""
获取某个节点的执行数据
: param node_id: 节点 ID
: type node_id: str
: return: 执行数据实例
: rtype: ExecutionData
"""
try:
data_model = DBExecutionData.objects.get(node_id=node_id)
except DBExecutionData.DoesNotExist:
raise exceptions.NotFoundError
return ExecutionData(
inputs=self._deserialize(data_model.inputs, data_model.inputs_serializer),
outputs=self._deserialize(data_model.outputs, data_model.outputs_serializer),
)
@metrics.setup_histogram(metrics.ENGINE_RUNTIME_EXEC_DATA_INPUTS_READ_TIME)
def get_execution_data_inputs(self, node_id: str) -> dict:
"""
获取某个节点的执行数据输入
:param node_id: 节点 ID
:type node_id: str
:return: 执行数据输入
:rtype: dict
"""
qs = DBExecutionData.objects.filter(node_id=node_id).only("inputs_serializer", "inputs")
if not qs:
return {}
return self._deserialize(qs[0].inputs, qs[0].inputs_serializer)
@metrics.setup_histogram(metrics.ENGINE_RUNTIME_EXEC_DATA_OUTPUTS_READ_TIME)
def get_execution_data_outputs(self, node_id: str) -> dict:
"""
获取某个节点的执行数据输出
:param node_id: 节点 ID
:type node_id: str
:return: 执行数据输出
:rtype: dict
"""
qs = DBExecutionData.objects.filter(node_id=node_id).only("outputs_serializer", "outputs")
if not qs:
return {}
return self._deserialize(qs[0].outputs, qs[0].outputs_serializer)
@metrics.setup_histogram(metrics.ENGINE_RUNTIME_EXEC_DATA_WRITE_TIME)
def set_execution_data(self, node_id: str, data: ExecutionData):
"""
设置某个节点的执行数据
:param node_id: 节点 ID
:type node_id: str
:param data: 执行数据实例
:type data: ExecutionData
"""
inputs, inputs_serializer = self._serialize(data.inputs)
outputs, outputs_serializer = self._serialize(data.outputs)
if DBExecutionData.objects.filter(node_id=node_id).exists():
DBExecutionData.objects.filter(node_id=node_id).update(
inputs=inputs,
inputs_serializer=inputs_serializer,
outputs=outputs,
outputs_serializer=outputs_serializer,
)
else:
DBExecutionData.objects.create(
node_id=node_id,
inputs=inputs,
inputs_serializer=inputs_serializer,
outputs=outputs,
outputs_serializer=outputs_serializer,
)
@metrics.setup_histogram(metrics.ENGINE_RUNTIME_EXEC_DATA_INPUTS_WRITE_TIME)
def set_execution_data_inputs(self, node_id: str, inputs: dict):
"""
设置某个节点的执行数据输入
:param node_id: 节点 ID
:type node_id: str
:param outputs: 输出数据
:type outputs: dict
"""
inputs, inputs_serializer = self._serialize(inputs)
if DBExecutionData.objects.filter(node_id=node_id).exists():
DBExecutionData.objects.filter(node_id=node_id).update(inputs=inputs, inputs_serializer=inputs_serializer)
else:
DBExecutionData.objects.create(
node_id=node_id,
inputs=inputs,
inputs_serializer=inputs_serializer,
outputs="{}",
outputs_serializer=self.JSON_SERIALIZER,
)
@metrics.setup_histogram(metrics.ENGINE_RUNTIME_EXEC_DATA_OUTPUTS_WRITE_TIME)
def set_execution_data_outputs(self, node_id: str, outputs: dict):
"""
设置某个节点的执行数据输出
:param node_id: 节点 ID
:type node_id: str
:param outputs: 输出数据
:type outputs: dict
"""
outputs, outputs_serializer = self._serialize(outputs)
if DBExecutionData.objects.filter(node_id=node_id).exists():
DBExecutionData.objects.filter(node_id=node_id).update(
outputs=outputs, outputs_serializer=outputs_serializer
)
else:
DBExecutionData.objects.create(
node_id=node_id,
inputs="{}",
inputs_serializer=self.JSON_SERIALIZER,
outputs=outputs,
outputs_serializer=outputs_serializer,
)
def set_callback_data(self, node_id: str, version: str, data: dict) -> int:
"""
设置某个节点执行数据的回调数据
:param node_id: 节点 ID
:type node_id: str
:param version: 节点执行版本
:type version: str
:param data: 回调数据
:type data: dict
:return: 回调数据 ID
:rtype: int
"""
return DBCallbackData.objects.create(node_id=node_id, version=version, data=json.dumps(data)).id
@metrics.setup_histogram(metrics.ENGINE_RUNTIME_CALLBACK_DATA_READ_TIME)
def get_callback_data(self, data_id: int) -> CallbackData:
"""
获取回调数据
:param data_id: Data ID
:type data_id: int
:return: 回调数据实例
:rtype: CallbackData
"""
data_model = DBCallbackData.objects.get(id=data_id)
return CallbackData(
id=data_model.id, node_id=data_model.node_id, version=data_model.version, data=json.loads(data_model.data)
) | 0.566378 | 0.353763 |
from flask import request,session, render_template, current_app, url_for
import random
from datetime import datetime
from app.common.ajax import *
from app.common.upload_file import *
from app.common.common import strdecode
from .models import *
from .import_html import *
def upload_tmpimg(*args, **kwargs):
image = request.files.get("image")
if not image or not validate_image(image.filename):
return message("error", "", "数据有误")
path, name = generate_tmpfile(image)
value = {"url": path, "name":name}
return message("success", value)
def change_tmpimg(filename = None, *args, **kwargs):
image = request.files.get("image")
if not image or not validate_image(image.filename):
return message("error", "", "数据有误")
if filename:
remove_tmpfile(filename)
path, name = generate_tmpfile(image)
value = {"url": path, "name": name}
return message("success", value)
def del_tmpimg(filename=None, *args, **kwargs):
if not filename:
return message('error', "", "数据有误")
remove_tmpfile(filename)
return message("success", "")
def import_html(html, url, only_main, download_image, image_path):
"""
@param html: html内容
@param url: 链接
@param only_main: 值提取页面正文
@param download_image: 要下载页面上的图片到本地
@rapm image_path: 图片存放路径
"""
html = get_url_html(html, url)
if html is None:
return message("warning", "", "地址无法访问")
html = strdecode(html)
html = html if not only_main else get_main_html(html)
markdown = html2markdown(html, url, download_image, image_path)
return message("success", markdown)
def import_article_html(html = None, url = None, only_main = None,
download_image= None, *args, **kwargs):
only_main = 0 if only_main is None else int(only_main)
download_image = 0 if download_image is None else int(download_image)
if html is None and url is None:
return message("warning", "", "内容不能为空")
return import_html(html = html, url = url, only_main = only_main,
download_image= download_image,
image_path = current_app.config["ARTICLE_IMAGE_PATH"])
AUTH_AJAX_METHODS = {
"upload_tmpimg": upload_tmpimg,
"change_tmpimg": change_tmpimg,
"del_tmpimg": del_tmpimg,
"import_article_html": import_article_html, # 导入文章html
}
def auth_dispath_ajax(parameters, action):
parameters = parameters.to_dict()
method = AUTH_AJAX_METHODS.get(action)
if not method:
return message("error", "", "错误的操作类型")
return method(**parameters)
def autosearch_topic(data, *args, **kwargs):
topics = Topic.prefix_autosearch(data, 1,
current_app.config["AUTOSEARCH_TOPIC_PAGE"])
value = {
"topics": render_template("home/_search_topic_result.html", topics = topics.items),
"page": render_template("home/_topic_pagination.html", endpoint="home.topic",
pagination = topics, values = {"data": data})
}
return message("success", value)
AJAX_METHODS = {
"autosearch_topic": autosearch_topic,
}
def dispath_ajax(parameters, action):
parameters = parameters.to_dict()
print('parameters', parameters, action)
method = AJAX_METHODS.get(action)
if not method:
return message("error", "", "错误的操作类型")
return method(**parameters) | app/home/ajax.py |
from flask import request,session, render_template, current_app, url_for
import random
from datetime import datetime
from app.common.ajax import *
from app.common.upload_file import *
from app.common.common import strdecode
from .models import *
from .import_html import *
def upload_tmpimg(*args, **kwargs):
image = request.files.get("image")
if not image or not validate_image(image.filename):
return message("error", "", "数据有误")
path, name = generate_tmpfile(image)
value = {"url": path, "name":name}
return message("success", value)
def change_tmpimg(filename = None, *args, **kwargs):
image = request.files.get("image")
if not image or not validate_image(image.filename):
return message("error", "", "数据有误")
if filename:
remove_tmpfile(filename)
path, name = generate_tmpfile(image)
value = {"url": path, "name": name}
return message("success", value)
def del_tmpimg(filename=None, *args, **kwargs):
if not filename:
return message('error', "", "数据有误")
remove_tmpfile(filename)
return message("success", "")
def import_html(html, url, only_main, download_image, image_path):
"""
@param html: html内容
@param url: 链接
@param only_main: 值提取页面正文
@param download_image: 要下载页面上的图片到本地
@rapm image_path: 图片存放路径
"""
html = get_url_html(html, url)
if html is None:
return message("warning", "", "地址无法访问")
html = strdecode(html)
html = html if not only_main else get_main_html(html)
markdown = html2markdown(html, url, download_image, image_path)
return message("success", markdown)
def import_article_html(html = None, url = None, only_main = None,
download_image= None, *args, **kwargs):
only_main = 0 if only_main is None else int(only_main)
download_image = 0 if download_image is None else int(download_image)
if html is None and url is None:
return message("warning", "", "内容不能为空")
return import_html(html = html, url = url, only_main = only_main,
download_image= download_image,
image_path = current_app.config["ARTICLE_IMAGE_PATH"])
AUTH_AJAX_METHODS = {
"upload_tmpimg": upload_tmpimg,
"change_tmpimg": change_tmpimg,
"del_tmpimg": del_tmpimg,
"import_article_html": import_article_html, # 导入文章html
}
def auth_dispath_ajax(parameters, action):
parameters = parameters.to_dict()
method = AUTH_AJAX_METHODS.get(action)
if not method:
return message("error", "", "错误的操作类型")
return method(**parameters)
def autosearch_topic(data, *args, **kwargs):
topics = Topic.prefix_autosearch(data, 1,
current_app.config["AUTOSEARCH_TOPIC_PAGE"])
value = {
"topics": render_template("home/_search_topic_result.html", topics = topics.items),
"page": render_template("home/_topic_pagination.html", endpoint="home.topic",
pagination = topics, values = {"data": data})
}
return message("success", value)
AJAX_METHODS = {
"autosearch_topic": autosearch_topic,
}
def dispath_ajax(parameters, action):
parameters = parameters.to_dict()
print('parameters', parameters, action)
method = AJAX_METHODS.get(action)
if not method:
return message("error", "", "错误的操作类型")
return method(**parameters) | 0.407451 | 0.101634 |
def sendEmail(fromGmail, fromPwd, toEmails, subject, body):
# Import smtp library
import smtplib
# Initialize vars
usr = fromGmail
pwd = <PASSWORD>Pwd
FROM = usr
TO = toEmails if type(toEmails) is list else [toEmails]
SUBJECT = subject
TEXT = body
# Prepare and attempt to send email message
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(usr, pwd)
server.sendmail(FROM, TO, message)
server.close()
print "Successfully sent the email"
except:
print "Failed to send the email"
# Capitalize every other letter in a string
# idx == 0 -> start with first letter, idx == 1 -> start with second letter
def capEveryOther(word, idx):
ret = ""
for i in range(0, len(word)):
if (i + idx) % 2 == 0:
ret += word[i].upper()
else:
ret += word[i].lower()
return ret
# Perform character-to-number/symbol substitution
def charSubst(word, old, new):
tmp = word.replace(old.lower(), new)
ret = tmp.replace(old.upper(), new)
return ret
# Password cracking script
import sys
import time
import crypt
from itertools import product
if len(sys.argv) != 5:
print "Usage: {} dictionary.txt alg salt hash".format(sys.argv[0])
else:
# Read in arguments
dct = str(sys.argv[1])
alg = str(sys.argv[2])
slt = str(sys.argv[3])
hsh = str(sys.argv[4])
# Declare variables
startTime = time.time()
MAX_LEVEL = 6
hashFound = False
hashGuess = ""
passGuess = ""
formattedSalt = ""
temp = ""
entryPerms = []
level = 1
i = -1
j = 0
alg = int(alg)
levelOneT = 0
levelTwoT = 0
levelThreeT = 0
levelFourT = 0
levelFiveT = 0
emailTimeStr = ""
numSubChars = ["l", "e", "a", "s", "b", "t", "o"]
symSubChars = ["i", "a", "v", "s", "c"]
specChars = ["!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "+", "=", ",", "/", "\\", "?", "'", "<", ">", ";", ":", "~", "[", "]", "{", "}", "|"]
bruteChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.,!?@#$%^&*()=+'\"/\;:[]{}|`~<> "
# Create a formatted salt based on the input
# If alg does not equal 1, 5, or 6, assumed to be DES
if alg == 1 or alg == 5 or alg == 6:
formattedSalt = "$" + str(alg) + "$" + str(slt) + "$"
else:
formattedSalt = str(slt)
alg = 0
levelOneF = "level-one-" + str(alg) + ".txt"
levelTwoF = "level-two-" + str(alg) + ".txt"
levelThreeF = "level-three-" + str(alg) + ".txt"
levelFourF = "level-four-" + str(alg) + ".txt"
refFile = open(dct, "r")
modFile = open(levelOneF, "w")
print "Time elapsed (in seconds) for:\n"
emailTimeStr += "Time elapsed (in seconds) for:\n"
# Perform password guessing logic based on dictionary entries, substitutions, and other various methods
while hashGuess != hsh:
line = refFile.readline()
if line == "":
level += 1
if refFile is not None:
refFile.close()
if modFile is not None:
modFile.close()
if level == 2:
refFile = open(levelOneF, "r")
modFile = open(levelTwoF, "w")
levelOneT = time.time()
print "Level x: {} \n".format(levelOneT - startTime)
emailTimeStr += "Level 1: {} \n".format(levelOneT - startTime)
elif level == 3:
refFile = open(levelTwoF, "r")
modFile = open(levelThreeF, "w")
levelTwoT = time.time()
print "Level 2: {} \n".format(levelTwoT - levelOneT)
emailTimeStr += "Level 2: {} \n".format(levelTwoT - levelOneT)
elif level == 4:
refFile = open(levelThreeF, "r")
modFile = open(levelFourF, "w")
levelThreeT = time.time()
print "Level 3: {} \n".format(levelThreeT - levelTwoT)
emailTimeStr += "Level 3: {} \n".format(levelThreeT - levelTwoT)
elif level == 5:
refFile = open(levelFourF, "r")
modFile = None
levelFourT = time.time()
print "Level 4: {} \n".format(levelFourT - levelThreeT)
emailTimeStr += "Level 4: {} \n".format(levelFourT - levelThreeT)
elif level == 6:
refFile = None
modFile = None
levelFiveT = time.time()
print "Level 5: {} \n".format(levelFiveT - levelFourT)
emailTimeStr += "Level 5: {} \n".format(levelFiveT - levelFourT)
if refFile is not None:
line = refFile.readline()
line = line.rstrip("\n")
# Use the level value to determine what type of modification to make to base dictVals
# Higher the level == more complicated/time-consuming attempts.
# In principle, quicker/easier passwords will be attempted first
# Set temp to current entry
temp = line
entryLen = len(temp)
entryPerms = []
# Pad shorter entries with a common "123..."
if entryLen < 6:
for j in range(1, 7 - entryLen):
temp += str(j)
if level == 1:
''' Level 1: (Letter Case) For each dictionary entry try:
- all lower case
- all upper case
- first letter capitalized
- every other letter capitalized (starting with the first one)
- every other letter capitalized (starting with the second one)
'''
modFile.write(temp.lower() + "\n")
entryPerms.append(temp.lower())
modFile.write(temp.upper() + "\n")
entryPerms.append(temp.upper())
modFile.write(temp.capitalize() + "\n")
entryPerms.append(temp.capitalize())
modFile.write(capEveryOther(temp, 0) + "\n")
entryPerms.append(capEveryOther(temp, 0))
modFile.write(capEveryOther(temp, 1) + "\n")
entryPerms.append(capEveryOther(temp, 1))
elif level == 2:
''' Level 2: (Number Substitution) For each value from level 1, try:
- 1 for l
- 3 for e
- 4 for a
- 5 for s
- 6 for b
- 7 for t
- 0 for o
- Combinations of each of the above
'''
modFile.write(temp + "\n")
entryPerms.append(temp)
# Count number of chars that can be substituted
charCount = 0
subsMade = 0
tmpSub = ""
for j in range(0, len(numSubChars)):
if numSubChars[j] in temp:
charCount += 1
for j in range(0, charCount):
subsMade = 0
tmpSub = temp
if "l" in temp or "L" in temp:
tmpSub = charSubst(tmpSub, "l", "1")
subsMade += 1
if subsMade == j + 1:
modFile.write(tmpSub + "\n")
entryPerms.append(tmpSub)
subsMade = 0
tmpSub = temp
if "e" in temp or "E" in temp:
tmpSub = charSubst(tmpSub, "e", "3")
subsMade += 1
if subsMade == j + 1:
modFile.write(tmpSub + "\n")
entryPerms.append(tmpSub)
subsMade = 0
tmpSub = temp
if "a" in temp or "A" in temp:
tmpSub = charSubst(tmpSub, "a", "4")
subsMade += 1
if subsMade == j + 1:
modFile.write(tmpSub + "\n")
entryPerms.append(tmpSub)
subsMade = 0
tmpSub = temp
if "s" in temp or "S" in temp:
tmpSub = charSubst(tmpSub, "s", "5")
subsMade += 1
if subsMade == j + 1:
modFile.write(tmpSub + "\n")
entryPerms.append(tmpSub)
subsMade = 0
tmpSub = temp
if "b" in temp or "B" in temp:
tmpSub = charSubst(tmpSub, "b", "6")
subsMade += 1
if subsMade == j + 1:
modFile.write(tmpSub + "\n")
entryPerms.append(tmpSub)
subsMade = 0
tmpSub = temp
if "t" in temp or "T" in temp:
tmpSub = charSubst(tmpSub, "t", "7")
subsMade += 1
if subsMade == j + 1:
modFile.write(tmpSub + "\n")
entryPerms.append(tmpSub)
subsMade = 0
tmpSub = temp
if "o" in temp or "O" in temp:
tmpSub = charSubst(tmpSub, "o", "0")
subsMade += 1
if subsMade == j + 1:
modFile.write(tmpSub + "\n")
entryPerms.append(tmpSub)
subsMade = 0
tmpSub = temp
elif level == 3:
''' Level 3: (Ordering Permutation) For each value from level 2, try:
- Reversing the entry
'''
modFile.write(temp + "\n")
entryPerms.append(temp)
modFile.write(temp[::-1] + "\n")
entryPerms.append(temp[::-1])
elif level == 4:
''' Level 4: (Symbol Substitution) For each value from level 3, try:
- ! for i
- @ for a
- ^ for v
- $ for s
- ( for c
- Combinations of each of the above
'''
modFile.write(temp + "\n")
entryPerms.append(temp)
#Count number of chars that can be substituted
charCount = 0
subsMade = 0
tmpSub = ""
for j in range(0, len(symSubChars)):
if symSubChars[j] in temp:
charCount += 1
for j in range(0, charCount):
subsMade = 0
tmpSub = temp
if "i" in temp or "I" in temp:
tmpSub = charSubst(tmpSub, "i", "!")
subsMade += 1
if subsMade == j + 1:
modFile.write(tmpSub + "\n")
entryPerms.append(tmpSub)
subsMade = 0
tmpSub = temp
if "a" in temp or "A" in temp:
tmpSub = charSubst(tmpSub, "a", "@")
subsMade += 1
if subsMade == j + 1:
modFile.write(tmpSub + "\n")
entryPerms.append(tmpSub)
subsMade = 0
tmpSub = temp
if "v" in temp or "V" in temp:
tmpSub = charSubst(tmpSub, "v", "^")
subsMade += 1
if subsMade == j + 1:
modFile.write(tmpSub + "\n")
entryPerms.append(tmpSub)
subsMade = 0
tmpSub = temp
if "s" in temp or "S" in temp:
tmpSub = charSubst(tmpSub, "s", "$")
subsMade += 1
if subsMade == j + 1:
modFile.write(tmpSub + "\n")
entryPerms.append(tmpSub)
subsMade = 0
tmpSub = temp
if "c" in temp or "C" in temp:
tmpSub = charSubst(tmpSub, "c", "(")
subsMade += 1
if subsMade == j + 1:
modFile.write(tmpSub + "\n")
entryPerms.append(tmpSub)
subsMade = 0
tmpSub = temp
elif level == 5:
''' Level 5: (Special Characters) For each value of level 4, try:
- Inserting "common" special characters for each position:
' ', '-', '_', '.'
- Inserting "uncommon" special characters at the beginning, end, and both:
'!', '@','#', '$', '%', '^', '&', '*', '(', ')', '+', '=', ',', '/', '?',
'\', '`', '<', '>', ';', ':', '~', '[', ']', '{', '}', '|'
'''
entryPerms.append(temp)
for j in range(0, entryLen + 1):
entryPerms.append(temp[:j] + " " + temp[j:])
entryPerms.append(temp[:j] + "-" + temp[j:])
entryPerms.append(temp[:j] + "_" + temp[j:])
entryPerms.append(temp[:j] + "." + temp[j:])
for j in range(0, len(specChars)):
entryPerms.append(specChars[j] + temp)
entryPerms.append(temp + specChars[j])
entryPerms.append(specChars[j] + temp + specChars[j])
elif level == 6:
''' Level 6: (Brute Force) If the code reaches this point, begin performing a brute
force search of all possible combinations in "bruteChars"
'''
for j in range(6, 15):
print "*********************Brute Char Count: " + str(j) + "\n"
for brPass in product(bruteChars, repeat=j):
passGuess = "".join(brPass)
hashGuess = crypt.crypt(passGuess, formattedSalt)
if hashGuess == formattedSalt + hsh:
hashFound = True
print passGuess
emailTimeStr += "Level 6 \n"
break
if hashFound == True:
break
if hashFound == False:
level = 7
# Check if control just came from level 6
if hashFound == True or level == 7:
break
# Perform the crypt function with the corresponding guess and salt
for j in range(0, len(entryPerms)):
# Encrypt
passGuess = entryPerms[j]
hashGuess = crypt.crypt(passGuess, formattedSalt)
# Compare the hashes
if hashGuess == formattedSalt + hsh:
hashFound = True
if level == 1:
print "Level 1: {} \n".format(time.time() - startTime)
emailTimeStr += "Level 1: {} \n".format(time.time() - startTime)
elif level == 2:
print "Level 2: {} \n".format(time.time() - levelOneT)
emailTimeStr += "Level 2: {} \n".format(time.time() - levelOneT)
elif level == 3:
print "Level 3: {} \n".format(time.time() - levelTwoT)
emailTimeStr += "Level 3: {} \n".format(time.time() - levelTwoT)
elif level == 4:
print "Level 4: {} \n".format(time.time() - levelThreeT)
emailTimeStr += "Level 4: {} \n".format(time.time() - levelThreeT)
elif level == 5:
print "Level 5: {} \n".format(time.time() - levelFourT)
emailTimeStr += "Level 5: {} \n".format(time.time() - levelFourT)
break
# Check if the correct password was found
if hashFound == True:
break
# Make sure the program broke out of the while loop because the correct password was found
if hashFound == True:
# Print the hash/password to the console
print "Password for hash {} found: {}".format(formattedSalt + hsh, passGuess)
# Print the hash/password to a text file
recF = open("crackedpass.txt", "a")
recF.write("Hash: {} Pass: {}".format(formattedSalt + hsh, passGuess))
recF.write("\n")
recF.close()
# Print the hash/password to an email
emailTimeStr += "Password for hash {} found: {}".format(formattedSalt + hsh, passGuess)
sendEmail("<EMAIL>", "password", "<EMAIL>", "STATUS: Password Found", emailTimeStr)
elif level > MAX_LEVEL:
# Print the level exceeded message to the console
print "Level value exceeded!"
# Print the level exceeded message to an email
emailTimeStr += "Level value exceeded!"
sendEmail("<EMAIL>", "password", "<EMAIL>", "STATUS: Level Exceeded", emailTimeStr)
else:
# Print the unexpected error message to the console
print "An unexpected error occurred somewhere (i.e. you're SOL)"
# Print the unexpected error message to an email
emailTimeStr += "An unexpected error occurred somewhere (i.e. you're SOL)"
sendEmail("<EMAIL>", "password", "<EMAIL>", "STATUS: Unexpected Error", emailTimeStr) | passcrack.py | def sendEmail(fromGmail, fromPwd, toEmails, subject, body):
# Import smtp library
import smtplib
# Initialize vars
usr = fromGmail
pwd = <PASSWORD>Pwd
FROM = usr
TO = toEmails if type(toEmails) is list else [toEmails]
SUBJECT = subject
TEXT = body
# Prepare and attempt to send email message
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(usr, pwd)
server.sendmail(FROM, TO, message)
server.close()
print "Successfully sent the email"
except:
print "Failed to send the email"
# Capitalize every other letter in a string
# idx == 0 -> start with first letter, idx == 1 -> start with second letter
def capEveryOther(word, idx):
ret = ""
for i in range(0, len(word)):
if (i + idx) % 2 == 0:
ret += word[i].upper()
else:
ret += word[i].lower()
return ret
# Perform character-to-number/symbol substitution
def charSubst(word, old, new):
tmp = word.replace(old.lower(), new)
ret = tmp.replace(old.upper(), new)
return ret
# Password cracking script
import sys
import time
import crypt
from itertools import product
if len(sys.argv) != 5:
print "Usage: {} dictionary.txt alg salt hash".format(sys.argv[0])
else:
# Read in arguments
dct = str(sys.argv[1])
alg = str(sys.argv[2])
slt = str(sys.argv[3])
hsh = str(sys.argv[4])
# Declare variables
startTime = time.time()
MAX_LEVEL = 6
hashFound = False
hashGuess = ""
passGuess = ""
formattedSalt = ""
temp = ""
entryPerms = []
level = 1
i = -1
j = 0
alg = int(alg)
levelOneT = 0
levelTwoT = 0
levelThreeT = 0
levelFourT = 0
levelFiveT = 0
emailTimeStr = ""
numSubChars = ["l", "e", "a", "s", "b", "t", "o"]
symSubChars = ["i", "a", "v", "s", "c"]
specChars = ["!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "+", "=", ",", "/", "\\", "?", "'", "<", ">", ";", ":", "~", "[", "]", "{", "}", "|"]
bruteChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.,!?@#$%^&*()=+'\"/\;:[]{}|`~<> "
# Create a formatted salt based on the input
# If alg does not equal 1, 5, or 6, assumed to be DES
if alg == 1 or alg == 5 or alg == 6:
formattedSalt = "$" + str(alg) + "$" + str(slt) + "$"
else:
formattedSalt = str(slt)
alg = 0
levelOneF = "level-one-" + str(alg) + ".txt"
levelTwoF = "level-two-" + str(alg) + ".txt"
levelThreeF = "level-three-" + str(alg) + ".txt"
levelFourF = "level-four-" + str(alg) + ".txt"
refFile = open(dct, "r")
modFile = open(levelOneF, "w")
print "Time elapsed (in seconds) for:\n"
emailTimeStr += "Time elapsed (in seconds) for:\n"
# Perform password guessing logic based on dictionary entries, substitutions, and other various methods
while hashGuess != hsh:
line = refFile.readline()
if line == "":
level += 1
if refFile is not None:
refFile.close()
if modFile is not None:
modFile.close()
if level == 2:
refFile = open(levelOneF, "r")
modFile = open(levelTwoF, "w")
levelOneT = time.time()
print "Level x: {} \n".format(levelOneT - startTime)
emailTimeStr += "Level 1: {} \n".format(levelOneT - startTime)
elif level == 3:
refFile = open(levelTwoF, "r")
modFile = open(levelThreeF, "w")
levelTwoT = time.time()
print "Level 2: {} \n".format(levelTwoT - levelOneT)
emailTimeStr += "Level 2: {} \n".format(levelTwoT - levelOneT)
elif level == 4:
refFile = open(levelThreeF, "r")
modFile = open(levelFourF, "w")
levelThreeT = time.time()
print "Level 3: {} \n".format(levelThreeT - levelTwoT)
emailTimeStr += "Level 3: {} \n".format(levelThreeT - levelTwoT)
elif level == 5:
refFile = open(levelFourF, "r")
modFile = None
levelFourT = time.time()
print "Level 4: {} \n".format(levelFourT - levelThreeT)
emailTimeStr += "Level 4: {} \n".format(levelFourT - levelThreeT)
elif level == 6:
refFile = None
modFile = None
levelFiveT = time.time()
print "Level 5: {} \n".format(levelFiveT - levelFourT)
emailTimeStr += "Level 5: {} \n".format(levelFiveT - levelFourT)
if refFile is not None:
line = refFile.readline()
line = line.rstrip("\n")
# Use the level value to determine what type of modification to make to base dictVals
# Higher the level == more complicated/time-consuming attempts.
# In principle, quicker/easier passwords will be attempted first
# Set temp to current entry
temp = line
entryLen = len(temp)
entryPerms = []
# Pad shorter entries with a common "123..."
if entryLen < 6:
for j in range(1, 7 - entryLen):
temp += str(j)
if level == 1:
''' Level 1: (Letter Case) For each dictionary entry try:
- all lower case
- all upper case
- first letter capitalized
- every other letter capitalized (starting with the first one)
- every other letter capitalized (starting with the second one)
'''
modFile.write(temp.lower() + "\n")
entryPerms.append(temp.lower())
modFile.write(temp.upper() + "\n")
entryPerms.append(temp.upper())
modFile.write(temp.capitalize() + "\n")
entryPerms.append(temp.capitalize())
modFile.write(capEveryOther(temp, 0) + "\n")
entryPerms.append(capEveryOther(temp, 0))
modFile.write(capEveryOther(temp, 1) + "\n")
entryPerms.append(capEveryOther(temp, 1))
elif level == 2:
''' Level 2: (Number Substitution) For each value from level 1, try:
- 1 for l
- 3 for e
- 4 for a
- 5 for s
- 6 for b
- 7 for t
- 0 for o
- Combinations of each of the above
'''
modFile.write(temp + "\n")
entryPerms.append(temp)
# Count number of chars that can be substituted
charCount = 0
subsMade = 0
tmpSub = ""
for j in range(0, len(numSubChars)):
if numSubChars[j] in temp:
charCount += 1
for j in range(0, charCount):
subsMade = 0
tmpSub = temp
if "l" in temp or "L" in temp:
tmpSub = charSubst(tmpSub, "l", "1")
subsMade += 1
if subsMade == j + 1:
modFile.write(tmpSub + "\n")
entryPerms.append(tmpSub)
subsMade = 0
tmpSub = temp
if "e" in temp or "E" in temp:
tmpSub = charSubst(tmpSub, "e", "3")
subsMade += 1
if subsMade == j + 1:
modFile.write(tmpSub + "\n")
entryPerms.append(tmpSub)
subsMade = 0
tmpSub = temp
if "a" in temp or "A" in temp:
tmpSub = charSubst(tmpSub, "a", "4")
subsMade += 1
if subsMade == j + 1:
modFile.write(tmpSub + "\n")
entryPerms.append(tmpSub)
subsMade = 0
tmpSub = temp
if "s" in temp or "S" in temp:
tmpSub = charSubst(tmpSub, "s", "5")
subsMade += 1
if subsMade == j + 1:
modFile.write(tmpSub + "\n")
entryPerms.append(tmpSub)
subsMade = 0
tmpSub = temp
if "b" in temp or "B" in temp:
tmpSub = charSubst(tmpSub, "b", "6")
subsMade += 1
if subsMade == j + 1:
modFile.write(tmpSub + "\n")
entryPerms.append(tmpSub)
subsMade = 0
tmpSub = temp
if "t" in temp or "T" in temp:
tmpSub = charSubst(tmpSub, "t", "7")
subsMade += 1
if subsMade == j + 1:
modFile.write(tmpSub + "\n")
entryPerms.append(tmpSub)
subsMade = 0
tmpSub = temp
if "o" in temp or "O" in temp:
tmpSub = charSubst(tmpSub, "o", "0")
subsMade += 1
if subsMade == j + 1:
modFile.write(tmpSub + "\n")
entryPerms.append(tmpSub)
subsMade = 0
tmpSub = temp
elif level == 3:
''' Level 3: (Ordering Permutation) For each value from level 2, try:
- Reversing the entry
'''
modFile.write(temp + "\n")
entryPerms.append(temp)
modFile.write(temp[::-1] + "\n")
entryPerms.append(temp[::-1])
elif level == 4:
''' Level 4: (Symbol Substitution) For each value from level 3, try:
- ! for i
- @ for a
- ^ for v
- $ for s
- ( for c
- Combinations of each of the above
'''
modFile.write(temp + "\n")
entryPerms.append(temp)
#Count number of chars that can be substituted
charCount = 0
subsMade = 0
tmpSub = ""
for j in range(0, len(symSubChars)):
if symSubChars[j] in temp:
charCount += 1
for j in range(0, charCount):
subsMade = 0
tmpSub = temp
if "i" in temp or "I" in temp:
tmpSub = charSubst(tmpSub, "i", "!")
subsMade += 1
if subsMade == j + 1:
modFile.write(tmpSub + "\n")
entryPerms.append(tmpSub)
subsMade = 0
tmpSub = temp
if "a" in temp or "A" in temp:
tmpSub = charSubst(tmpSub, "a", "@")
subsMade += 1
if subsMade == j + 1:
modFile.write(tmpSub + "\n")
entryPerms.append(tmpSub)
subsMade = 0
tmpSub = temp
if "v" in temp or "V" in temp:
tmpSub = charSubst(tmpSub, "v", "^")
subsMade += 1
if subsMade == j + 1:
modFile.write(tmpSub + "\n")
entryPerms.append(tmpSub)
subsMade = 0
tmpSub = temp
if "s" in temp or "S" in temp:
tmpSub = charSubst(tmpSub, "s", "$")
subsMade += 1
if subsMade == j + 1:
modFile.write(tmpSub + "\n")
entryPerms.append(tmpSub)
subsMade = 0
tmpSub = temp
if "c" in temp or "C" in temp:
tmpSub = charSubst(tmpSub, "c", "(")
subsMade += 1
if subsMade == j + 1:
modFile.write(tmpSub + "\n")
entryPerms.append(tmpSub)
subsMade = 0
tmpSub = temp
elif level == 5:
''' Level 5: (Special Characters) For each value of level 4, try:
- Inserting "common" special characters for each position:
' ', '-', '_', '.'
- Inserting "uncommon" special characters at the beginning, end, and both:
'!', '@','#', '$', '%', '^', '&', '*', '(', ')', '+', '=', ',', '/', '?',
'\', '`', '<', '>', ';', ':', '~', '[', ']', '{', '}', '|'
'''
entryPerms.append(temp)
for j in range(0, entryLen + 1):
entryPerms.append(temp[:j] + " " + temp[j:])
entryPerms.append(temp[:j] + "-" + temp[j:])
entryPerms.append(temp[:j] + "_" + temp[j:])
entryPerms.append(temp[:j] + "." + temp[j:])
for j in range(0, len(specChars)):
entryPerms.append(specChars[j] + temp)
entryPerms.append(temp + specChars[j])
entryPerms.append(specChars[j] + temp + specChars[j])
elif level == 6:
''' Level 6: (Brute Force) If the code reaches this point, begin performing a brute
force search of all possible combinations in "bruteChars"
'''
for j in range(6, 15):
print "*********************Brute Char Count: " + str(j) + "\n"
for brPass in product(bruteChars, repeat=j):
passGuess = "".join(brPass)
hashGuess = crypt.crypt(passGuess, formattedSalt)
if hashGuess == formattedSalt + hsh:
hashFound = True
print passGuess
emailTimeStr += "Level 6 \n"
break
if hashFound == True:
break
if hashFound == False:
level = 7
# Check if control just came from level 6
if hashFound == True or level == 7:
break
# Perform the crypt function with the corresponding guess and salt
for j in range(0, len(entryPerms)):
# Encrypt
passGuess = entryPerms[j]
hashGuess = crypt.crypt(passGuess, formattedSalt)
# Compare the hashes
if hashGuess == formattedSalt + hsh:
hashFound = True
if level == 1:
print "Level 1: {} \n".format(time.time() - startTime)
emailTimeStr += "Level 1: {} \n".format(time.time() - startTime)
elif level == 2:
print "Level 2: {} \n".format(time.time() - levelOneT)
emailTimeStr += "Level 2: {} \n".format(time.time() - levelOneT)
elif level == 3:
print "Level 3: {} \n".format(time.time() - levelTwoT)
emailTimeStr += "Level 3: {} \n".format(time.time() - levelTwoT)
elif level == 4:
print "Level 4: {} \n".format(time.time() - levelThreeT)
emailTimeStr += "Level 4: {} \n".format(time.time() - levelThreeT)
elif level == 5:
print "Level 5: {} \n".format(time.time() - levelFourT)
emailTimeStr += "Level 5: {} \n".format(time.time() - levelFourT)
break
# Check if the correct password was found
if hashFound == True:
break
# Make sure the program broke out of the while loop because the correct password was found
if hashFound == True:
# Print the hash/password to the console
print "Password for hash {} found: {}".format(formattedSalt + hsh, passGuess)
# Print the hash/password to a text file
recF = open("crackedpass.txt", "a")
recF.write("Hash: {} Pass: {}".format(formattedSalt + hsh, passGuess))
recF.write("\n")
recF.close()
# Print the hash/password to an email
emailTimeStr += "Password for hash {} found: {}".format(formattedSalt + hsh, passGuess)
sendEmail("<EMAIL>", "password", "<EMAIL>", "STATUS: Password Found", emailTimeStr)
elif level > MAX_LEVEL:
# Print the level exceeded message to the console
print "Level value exceeded!"
# Print the level exceeded message to an email
emailTimeStr += "Level value exceeded!"
sendEmail("<EMAIL>", "password", "<EMAIL>", "STATUS: Level Exceeded", emailTimeStr)
else:
# Print the unexpected error message to the console
print "An unexpected error occurred somewhere (i.e. you're SOL)"
# Print the unexpected error message to an email
emailTimeStr += "An unexpected error occurred somewhere (i.e. you're SOL)"
sendEmail("<EMAIL>", "password", "<EMAIL>", "STATUS: Unexpected Error", emailTimeStr) | 0.233881 | 0.164785 |
from octis.models.model import AbstractModel
import numpy as np
from gensim.models import hdpmodel
import gensim.corpora as corpora
import octis.configuration.citations as citations
import octis.configuration.defaults as defaults
class HDP(AbstractModel):
id2word = None
id_corpus = None
use_partitions = True
update_with_test = False
def __init__(self, max_chunks=None, max_time=None, chunksize=256, kappa=1.0, tau=64.0, K=15, T=150, alpha=1,
gamma=1, eta=0.01, scale=1.0, var_converge=0.0001):
"""
Initialize HDP model
Parameters
----------
max_chunks (int, optional) – Upper bound on how many chunks to process.
It wraps around corpus beginning in another corpus pass,
if there are not enough chunks in the corpus.
max_time (int, optional) – Upper bound on time (in seconds)
for which model will be trained.
chunksize (int, optional) – Number of documents in one chuck.
kappa (float,optional) – Learning parameter which acts as exponential
decay factor to influence extent of learning from each batch.
tau (float, optional) – Learning parameter which down-weights
early iterations of documents.
K (int, optional) – Second level truncation level
T (int, optional) – Top level truncation level
alpha (int, optional) – Second level concentration
gamma (int, optional) – First level concentration
eta (float, optional) – The topic Dirichlet
scale (float, optional) – Weights information from the
mini-chunk of corpus to calculate rhot.
var_converge (float, optional) – Lower bound on the right side of
convergence. Used when updating variational parameters
for a single document.
"""
super().__init__()
self.hyperparameters["max_chunks"] = max_chunks
self.hyperparameters["max_time"] = max_time
self.hyperparameters["chunksize"] = chunksize
self.hyperparameters["kappa"] = kappa
self.hyperparameters["tau"] = tau
self.hyperparameters["K"] = K
self.hyperparameters["T"] = T
self.hyperparameters["alpha"] = alpha
self.hyperparameters["gamma"] = gamma
self.hyperparameters["eta"] = eta
self.hyperparameters["scale"] = scale
self.hyperparameters["var_converge"] = var_converge
def info(self):
"""
Returns model informations
"""
return {
"citation": citations.models_HDP,
"name": "HDP, Hierarchical Dirichlet Process"
}
def hyperparameters_info(self):
"""
Returns hyperparameters informations
"""
return defaults.HDP_hyperparameters_info
def partitioning(self, use_partitions, update_with_test=False):
"""
Handle the partitioning system to use and reset the model to perform
new evaluations
Parameters
----------
use_partitions: True if train/set partitioning is needed, False
otherwise
update_with_test: True if the model should be updated with the test set,
False otherwise
"""
self.use_partitions = use_partitions
self.update_with_test = update_with_test
self.id2word = None
self.id_corpus = None
def train_model(self, dataset, hyperparameters={}, topics=10):
"""
Train the model and return output
Parameters
----------
dataset : dataset to use to build the model
hyperparameters : hyperparameters to build the model
topics : if greather than 0 returns the top k most significant
words for each topic in the output
Default True
Returns
-------
result : dictionary with up to 3 entries,
'topics', 'topic-word-matrix' and
'topic-document-matrix'
"""
partition = []
if self.use_partitions:
partition = dataset.get_partitioned_corpus()
else:
partition = [dataset.get_corpus(), []]
if self.id2word is None:
self.id2word = corpora.Dictionary(dataset.get_corpus())
if self.id_corpus is None:
self.id_corpus = [self.id2word.doc2bow(
document) for document in partition[0]]
hyperparameters["corpus"] = self.id_corpus
hyperparameters["id2word"] = self.id2word
self.hyperparameters.update(hyperparameters)
self.trained_model = hdpmodel.HdpModel(**self.hyperparameters)
result = dict()
result["topic-word-matrix"] = self.trained_model.get_topics()
if topics > 0:
topics_output = []
for topic in result["topic-word-matrix"]:
top_k = np.argsort(topic)[-topics:]
top_k_words = list(reversed([self.id2word[i] for i in top_k]))
topics_output.append(top_k_words)
result["topics"] = topics_output
result["topic-document-matrix"] = self._get_topic_document_matrix()
if self.use_partitions:
new_corpus = [self.id2word.doc2bow(
document) for document in partition[1]]
if self.update_with_test:
self.trained_model.update(new_corpus)
self.id_corpus.extend(new_corpus)
result["test-topic-word-matrix"] = self.trained_model.get_topics()
if topics > 0:
topics_output = []
for topic in result["test-topic-word-matrix"]:
top_k = np.argsort(topic)[-topics:]
top_k_words = list(
reversed([self.id2word[i] for i in top_k]))
topics_output.append(top_k_words)
result["test-topics"] = topics_output
result["test-topic-document-matrix"] = self._get_topic_document_matrix()
else:
test_document_topic_matrix = []
for document in new_corpus:
document_topics_tuples = self.trained_model[document]
document_topics = np.zeros(
len(self.trained_model.get_topics()))
for single_tuple in document_topics_tuples:
document_topics[single_tuple[0]] = single_tuple[1]
test_document_topic_matrix.append(document_topics)
result["test-topic-document-matrix"] = np.array(
test_document_topic_matrix).transpose()
return result
def _get_topics_words(self, topics):
"""
Return the most significative words for each topic.
"""
topic_terms = []
for i in range(len(self.trained_model.get_topics())):
topic_terms.append(self.trained_model.show_topic(
i,
topics,
False,
True
))
return topic_terms
def _get_topic_document_matrix(self):
"""
Return the topic representation of the
corpus
"""
doc_topic_tuples = []
for document in self.id_corpus:
doc_topic_tuples.append(self.trained_model[document])
topic_document = np.zeros((
len(self.trained_model.get_topics()),
len(doc_topic_tuples)))
for ndoc in range(len(doc_topic_tuples)):
document = doc_topic_tuples[ndoc]
for topic_tuple in document:
topic_document[topic_tuple[0]][ndoc] = topic_tuple[1]
return topic_document | octis/models/HDP.py | from octis.models.model import AbstractModel
import numpy as np
from gensim.models import hdpmodel
import gensim.corpora as corpora
import octis.configuration.citations as citations
import octis.configuration.defaults as defaults
class HDP(AbstractModel):
id2word = None
id_corpus = None
use_partitions = True
update_with_test = False
def __init__(self, max_chunks=None, max_time=None, chunksize=256, kappa=1.0, tau=64.0, K=15, T=150, alpha=1,
gamma=1, eta=0.01, scale=1.0, var_converge=0.0001):
"""
Initialize HDP model
Parameters
----------
max_chunks (int, optional) – Upper bound on how many chunks to process.
It wraps around corpus beginning in another corpus pass,
if there are not enough chunks in the corpus.
max_time (int, optional) – Upper bound on time (in seconds)
for which model will be trained.
chunksize (int, optional) – Number of documents in one chuck.
kappa (float,optional) – Learning parameter which acts as exponential
decay factor to influence extent of learning from each batch.
tau (float, optional) – Learning parameter which down-weights
early iterations of documents.
K (int, optional) – Second level truncation level
T (int, optional) – Top level truncation level
alpha (int, optional) – Second level concentration
gamma (int, optional) – First level concentration
eta (float, optional) – The topic Dirichlet
scale (float, optional) – Weights information from the
mini-chunk of corpus to calculate rhot.
var_converge (float, optional) – Lower bound on the right side of
convergence. Used when updating variational parameters
for a single document.
"""
super().__init__()
self.hyperparameters["max_chunks"] = max_chunks
self.hyperparameters["max_time"] = max_time
self.hyperparameters["chunksize"] = chunksize
self.hyperparameters["kappa"] = kappa
self.hyperparameters["tau"] = tau
self.hyperparameters["K"] = K
self.hyperparameters["T"] = T
self.hyperparameters["alpha"] = alpha
self.hyperparameters["gamma"] = gamma
self.hyperparameters["eta"] = eta
self.hyperparameters["scale"] = scale
self.hyperparameters["var_converge"] = var_converge
def info(self):
"""
Returns model informations
"""
return {
"citation": citations.models_HDP,
"name": "HDP, Hierarchical Dirichlet Process"
}
def hyperparameters_info(self):
"""
Returns hyperparameters informations
"""
return defaults.HDP_hyperparameters_info
def partitioning(self, use_partitions, update_with_test=False):
"""
Handle the partitioning system to use and reset the model to perform
new evaluations
Parameters
----------
use_partitions: True if train/set partitioning is needed, False
otherwise
update_with_test: True if the model should be updated with the test set,
False otherwise
"""
self.use_partitions = use_partitions
self.update_with_test = update_with_test
self.id2word = None
self.id_corpus = None
def train_model(self, dataset, hyperparameters={}, topics=10):
"""
Train the model and return output
Parameters
----------
dataset : dataset to use to build the model
hyperparameters : hyperparameters to build the model
topics : if greather than 0 returns the top k most significant
words for each topic in the output
Default True
Returns
-------
result : dictionary with up to 3 entries,
'topics', 'topic-word-matrix' and
'topic-document-matrix'
"""
partition = []
if self.use_partitions:
partition = dataset.get_partitioned_corpus()
else:
partition = [dataset.get_corpus(), []]
if self.id2word is None:
self.id2word = corpora.Dictionary(dataset.get_corpus())
if self.id_corpus is None:
self.id_corpus = [self.id2word.doc2bow(
document) for document in partition[0]]
hyperparameters["corpus"] = self.id_corpus
hyperparameters["id2word"] = self.id2word
self.hyperparameters.update(hyperparameters)
self.trained_model = hdpmodel.HdpModel(**self.hyperparameters)
result = dict()
result["topic-word-matrix"] = self.trained_model.get_topics()
if topics > 0:
topics_output = []
for topic in result["topic-word-matrix"]:
top_k = np.argsort(topic)[-topics:]
top_k_words = list(reversed([self.id2word[i] for i in top_k]))
topics_output.append(top_k_words)
result["topics"] = topics_output
result["topic-document-matrix"] = self._get_topic_document_matrix()
if self.use_partitions:
new_corpus = [self.id2word.doc2bow(
document) for document in partition[1]]
if self.update_with_test:
self.trained_model.update(new_corpus)
self.id_corpus.extend(new_corpus)
result["test-topic-word-matrix"] = self.trained_model.get_topics()
if topics > 0:
topics_output = []
for topic in result["test-topic-word-matrix"]:
top_k = np.argsort(topic)[-topics:]
top_k_words = list(
reversed([self.id2word[i] for i in top_k]))
topics_output.append(top_k_words)
result["test-topics"] = topics_output
result["test-topic-document-matrix"] = self._get_topic_document_matrix()
else:
test_document_topic_matrix = []
for document in new_corpus:
document_topics_tuples = self.trained_model[document]
document_topics = np.zeros(
len(self.trained_model.get_topics()))
for single_tuple in document_topics_tuples:
document_topics[single_tuple[0]] = single_tuple[1]
test_document_topic_matrix.append(document_topics)
result["test-topic-document-matrix"] = np.array(
test_document_topic_matrix).transpose()
return result
def _get_topics_words(self, topics):
"""
Return the most significative words for each topic.
"""
topic_terms = []
for i in range(len(self.trained_model.get_topics())):
topic_terms.append(self.trained_model.show_topic(
i,
topics,
False,
True
))
return topic_terms
def _get_topic_document_matrix(self):
"""
Return the topic representation of the
corpus
"""
doc_topic_tuples = []
for document in self.id_corpus:
doc_topic_tuples.append(self.trained_model[document])
topic_document = np.zeros((
len(self.trained_model.get_topics()),
len(doc_topic_tuples)))
for ndoc in range(len(doc_topic_tuples)):
document = doc_topic_tuples[ndoc]
for topic_tuple in document:
topic_document[topic_tuple[0]][ndoc] = topic_tuple[1]
return topic_document | 0.861742 | 0.387111 |
import unittest
from transformers import XLMRobertaXLConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from ..generation.test_generation_utils import GenerationTesterMixin
from ..test_configuration_common import ConfigTester
from ..test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
if is_torch_available():
import torch
from transformers import (
XLMRobertaXLForCausalLM,
XLMRobertaXLForMaskedLM,
XLMRobertaXLForMultipleChoice,
XLMRobertaXLForQuestionAnswering,
XLMRobertaXLForSequenceClassification,
XLMRobertaXLForTokenClassification,
XLMRobertaXLModel,
)
from transformers.models.xlm_roberta_xl.modeling_xlm_roberta_xl import (
XLMRobertaXLEmbeddings,
create_position_ids_from_input_ids,
)
class XLMRobertaXLModelTester:
def __init__(
self,
parent,
):
self.parent = parent
self.batch_size = 13
self.seq_length = 7
self.is_training = True
self.use_input_mask = True
self.use_token_type_ids = True
self.use_labels = True
self.vocab_size = 99
self.hidden_size = 32
self.num_hidden_layers = 5
self.num_attention_heads = 4
self.intermediate_size = 37
self.hidden_act = "gelu"
self.hidden_dropout_prob = 0.1
self.attention_probs_dropout_prob = 0.1
self.max_position_embeddings = 512
self.type_vocab_size = 16
self.type_sequence_label_size = 2
self.initializer_range = 0.02
self.num_labels = 3
self.num_choices = 4
self.scope = None
def prepare_config_and_inputs(self):
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
input_mask = None
if self.use_input_mask:
input_mask = random_attention_mask([self.batch_size, self.seq_length])
token_type_ids = None
if self.use_token_type_ids:
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
sequence_labels = None
token_labels = None
choice_labels = None
if self.use_labels:
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
choice_labels = ids_tensor([self.batch_size], self.num_choices)
config = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def get_config(self):
return XLMRobertaXLConfig(
vocab_size=self.vocab_size,
hidden_size=self.hidden_size,
num_hidden_layers=self.num_hidden_layers,
num_attention_heads=self.num_attention_heads,
intermediate_size=self.intermediate_size,
hidden_act=self.hidden_act,
hidden_dropout_prob=self.hidden_dropout_prob,
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
max_position_embeddings=self.max_position_embeddings,
type_vocab_size=self.type_vocab_size,
initializer_range=self.initializer_range,
)
def prepare_config_and_inputs_for_decoder(self):
(
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
) = self.prepare_config_and_inputs()
config.is_decoder = True
encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
return (
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
)
def create_and_check_model(
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
):
model = XLMRobertaXLModel(config=config)
model.to(torch_device)
model.eval()
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
result = model(input_ids, token_type_ids=token_type_ids)
result = model(input_ids)
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
def create_and_check_model_as_decoder(
self,
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
):
config.add_cross_attention = True
model = XLMRobertaXLModel(config)
model.to(torch_device)
model.eval()
result = model(
input_ids,
attention_mask=input_mask,
token_type_ids=token_type_ids,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
)
result = model(
input_ids,
attention_mask=input_mask,
token_type_ids=token_type_ids,
encoder_hidden_states=encoder_hidden_states,
)
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
def create_and_check_for_causal_lm(
self,
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
):
model = XLMRobertaXLForCausalLM(config=config)
model.to(torch_device)
model.eval()
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
def create_and_check_decoder_model_past_large_inputs(
self,
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
):
config.is_decoder = True
config.add_cross_attention = True
model = XLMRobertaXLForCausalLM(config=config).to(torch_device).eval()
# make sure that ids don't start with pad token
mask = input_ids.ne(config.pad_token_id).long()
input_ids = input_ids * mask
# first forward pass
outputs = model(
input_ids,
attention_mask=input_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
use_cache=True,
)
past_key_values = outputs.past_key_values
# create hypothetical multiple next token and extent to next_input_ids
next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
# make sure that ids don't start with pad token
mask = next_tokens.ne(config.pad_token_id).long()
next_tokens = next_tokens * mask
next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
# append to next input_ids and
next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
output_from_no_past = model(
next_input_ids,
attention_mask=next_attention_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
output_hidden_states=True,
)["hidden_states"][0]
output_from_past = model(
next_tokens,
attention_mask=next_attention_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
past_key_values=past_key_values,
output_hidden_states=True,
)["hidden_states"][0]
# select random slice
random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
# test that outputs are equal for slice
self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
def create_and_check_for_masked_lm(
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
):
model = XLMRobertaXLForMaskedLM(config=config)
model.to(torch_device)
model.eval()
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
def create_and_check_for_token_classification(
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
):
config.num_labels = self.num_labels
model = XLMRobertaXLForTokenClassification(config=config)
model.to(torch_device)
model.eval()
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
def create_and_check_for_multiple_choice(
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
):
config.num_choices = self.num_choices
model = XLMRobertaXLForMultipleChoice(config=config)
model.to(torch_device)
model.eval()
multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
result = model(
multiple_choice_inputs_ids,
attention_mask=multiple_choice_input_mask,
token_type_ids=multiple_choice_token_type_ids,
labels=choice_labels,
)
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
def create_and_check_for_question_answering(
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
):
model = XLMRobertaXLForQuestionAnswering(config=config)
model.to(torch_device)
model.eval()
result = model(
input_ids,
attention_mask=input_mask,
token_type_ids=token_type_ids,
start_positions=sequence_labels,
end_positions=sequence_labels,
)
self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
def prepare_config_and_inputs_for_common(self):
config_and_inputs = self.prepare_config_and_inputs()
(
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
) = config_and_inputs
inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_torch
class XLMRobertaXLModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
all_model_classes = (
(
XLMRobertaXLForCausalLM,
XLMRobertaXLForMaskedLM,
XLMRobertaXLModel,
XLMRobertaXLForSequenceClassification,
XLMRobertaXLForTokenClassification,
XLMRobertaXLForMultipleChoice,
XLMRobertaXLForQuestionAnswering,
)
if is_torch_available()
else ()
)
all_generative_model_classes = (XLMRobertaXLForCausalLM,) if is_torch_available() else ()
def setUp(self):
self.model_tester = XLMRobertaXLModelTester(self)
self.config_tester = ConfigTester(self, config_class=XLMRobertaXLConfig, hidden_size=37)
def test_config(self):
self.config_tester.run_common_tests()
def test_model(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*config_and_inputs)
def test_model_various_embeddings(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
config_and_inputs[0].position_embedding_type = type
self.model_tester.create_and_check_model(*config_and_inputs)
def test_model_as_decoder(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
self.model_tester.create_and_check_model_as_decoder(*config_and_inputs)
def test_model_as_decoder_with_default_input_mask(self):
# This regression test was failing with PyTorch < 1.3
(
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
) = self.model_tester.prepare_config_and_inputs_for_decoder()
input_mask = None
self.model_tester.create_and_check_model_as_decoder(
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
)
def test_for_causal_lm(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
self.model_tester.create_and_check_for_causal_lm(*config_and_inputs)
def test_decoder_model_past_with_large_inputs(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
def test_for_masked_lm(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
def test_for_token_classification(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
def test_for_multiple_choice(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
def test_for_question_answering(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
def test_create_position_ids_respects_padding_index(self):
"""Ensure that the default position ids only assign a sequential . This is a regression
test for https://github.com/huggingface/transformers/issues/1761
The position ids should be masked with the embedding object's padding index. Therefore, the
first available non-padding position index is XLMRobertaXLEmbeddings.padding_idx + 1
"""
config = self.model_tester.prepare_config_and_inputs()[0]
model = XLMRobertaXLEmbeddings(config=config)
input_ids = torch.as_tensor([[12, 31, 13, model.padding_idx]])
expected_positions = torch.as_tensor(
[[0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx]]
)
position_ids = create_position_ids_from_input_ids(input_ids, model.padding_idx)
self.assertEqual(position_ids.shape, expected_positions.shape)
self.assertTrue(torch.all(torch.eq(position_ids, expected_positions)))
def test_create_position_ids_from_inputs_embeds(self):
"""Ensure that the default position ids only assign a sequential . This is a regression
test for https://github.com/huggingface/transformers/issues/1761
The position ids should be masked with the embedding object's padding index. Therefore, the
first available non-padding position index is XLMRobertaXLEmbeddings.padding_idx + 1
"""
config = self.model_tester.prepare_config_and_inputs()[0]
embeddings = XLMRobertaXLEmbeddings(config=config)
inputs_embeds = torch.empty(2, 4, 30)
expected_single_positions = [
0 + embeddings.padding_idx + 1,
1 + embeddings.padding_idx + 1,
2 + embeddings.padding_idx + 1,
3 + embeddings.padding_idx + 1,
]
expected_positions = torch.as_tensor([expected_single_positions, expected_single_positions])
position_ids = embeddings.create_position_ids_from_inputs_embeds(inputs_embeds)
self.assertEqual(position_ids.shape, expected_positions.shape)
self.assertTrue(torch.all(torch.eq(position_ids, expected_positions)))
@require_torch
class XLMRobertaModelXLIntegrationTest(unittest.TestCase):
@slow
def test_xlm_roberta_xl(self):
model = XLMRobertaXLModel.from_pretrained("facebook/xlm-roberta-xl").to(torch_device)
input_ids = torch.tensor(
[[0, 581, 10269, 83, 99942, 136, 60742, 23, 70, 80583, 18276, 2]], device=torch_device
)
# The dog is cute and lives in the garden house
expected_output_shape = torch.Size((1, 12, 2560)) # batch_size, sequence_length, embedding_vector_dim
expected_output_values_last_dim = torch.tensor(
[[0.0110, 0.0605, 0.0354, 0.0689, 0.0066, 0.0691, 0.0302, 0.0412, 0.0860, 0.0036, 0.0405, 0.0170]],
device=torch_device,
)
output = model(input_ids)["last_hidden_state"].detach()
self.assertEqual(output.shape, expected_output_shape)
# compare the actual values for a slice of last dim
self.assertTrue(torch.allclose(output[:, :, -1], expected_output_values_last_dim, atol=1e-3))
@unittest.skip(reason="Model is too large to be tested on the CI")
def test_xlm_roberta_xxl(self):
model = XLMRobertaXLModel.from_pretrained("facebook/xlm-roberta-xxl").to(torch_device)
input_ids = torch.tensor(
[[0, 581, 10269, 83, 99942, 136, 60742, 23, 70, 80583, 18276, 2]], device=torch_device
)
# The dog is cute and lives in the garden house
expected_output_shape = torch.Size((1, 12, 4096)) # batch_size, sequence_length, embedding_vector_dim
expected_output_values_last_dim = torch.tensor(
[[0.0046, 0.0146, 0.0227, 0.0126, 0.0219, 0.0175, -0.0101, 0.0006, 0.0124, 0.0209, -0.0063, 0.0096]],
device=torch_device,
)
output = model(input_ids)["last_hidden_state"].detach()
self.assertEqual(output.shape, expected_output_shape)
# compare the actual values for a slice of last dim
self.assertTrue(torch.allclose(output[:, :, -1], expected_output_values_last_dim, atol=1e-3)) | tests/xlm_roberta_xl/test_modeling_xlm_roberta_xl.py |
import unittest
from transformers import XLMRobertaXLConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from ..generation.test_generation_utils import GenerationTesterMixin
from ..test_configuration_common import ConfigTester
from ..test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
if is_torch_available():
import torch
from transformers import (
XLMRobertaXLForCausalLM,
XLMRobertaXLForMaskedLM,
XLMRobertaXLForMultipleChoice,
XLMRobertaXLForQuestionAnswering,
XLMRobertaXLForSequenceClassification,
XLMRobertaXLForTokenClassification,
XLMRobertaXLModel,
)
from transformers.models.xlm_roberta_xl.modeling_xlm_roberta_xl import (
XLMRobertaXLEmbeddings,
create_position_ids_from_input_ids,
)
class XLMRobertaXLModelTester:
def __init__(
self,
parent,
):
self.parent = parent
self.batch_size = 13
self.seq_length = 7
self.is_training = True
self.use_input_mask = True
self.use_token_type_ids = True
self.use_labels = True
self.vocab_size = 99
self.hidden_size = 32
self.num_hidden_layers = 5
self.num_attention_heads = 4
self.intermediate_size = 37
self.hidden_act = "gelu"
self.hidden_dropout_prob = 0.1
self.attention_probs_dropout_prob = 0.1
self.max_position_embeddings = 512
self.type_vocab_size = 16
self.type_sequence_label_size = 2
self.initializer_range = 0.02
self.num_labels = 3
self.num_choices = 4
self.scope = None
def prepare_config_and_inputs(self):
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
input_mask = None
if self.use_input_mask:
input_mask = random_attention_mask([self.batch_size, self.seq_length])
token_type_ids = None
if self.use_token_type_ids:
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
sequence_labels = None
token_labels = None
choice_labels = None
if self.use_labels:
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
choice_labels = ids_tensor([self.batch_size], self.num_choices)
config = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def get_config(self):
return XLMRobertaXLConfig(
vocab_size=self.vocab_size,
hidden_size=self.hidden_size,
num_hidden_layers=self.num_hidden_layers,
num_attention_heads=self.num_attention_heads,
intermediate_size=self.intermediate_size,
hidden_act=self.hidden_act,
hidden_dropout_prob=self.hidden_dropout_prob,
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
max_position_embeddings=self.max_position_embeddings,
type_vocab_size=self.type_vocab_size,
initializer_range=self.initializer_range,
)
def prepare_config_and_inputs_for_decoder(self):
(
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
) = self.prepare_config_and_inputs()
config.is_decoder = True
encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
return (
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
)
def create_and_check_model(
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
):
model = XLMRobertaXLModel(config=config)
model.to(torch_device)
model.eval()
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
result = model(input_ids, token_type_ids=token_type_ids)
result = model(input_ids)
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
def create_and_check_model_as_decoder(
self,
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
):
config.add_cross_attention = True
model = XLMRobertaXLModel(config)
model.to(torch_device)
model.eval()
result = model(
input_ids,
attention_mask=input_mask,
token_type_ids=token_type_ids,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
)
result = model(
input_ids,
attention_mask=input_mask,
token_type_ids=token_type_ids,
encoder_hidden_states=encoder_hidden_states,
)
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
def create_and_check_for_causal_lm(
self,
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
):
model = XLMRobertaXLForCausalLM(config=config)
model.to(torch_device)
model.eval()
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
def create_and_check_decoder_model_past_large_inputs(
self,
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
):
config.is_decoder = True
config.add_cross_attention = True
model = XLMRobertaXLForCausalLM(config=config).to(torch_device).eval()
# make sure that ids don't start with pad token
mask = input_ids.ne(config.pad_token_id).long()
input_ids = input_ids * mask
# first forward pass
outputs = model(
input_ids,
attention_mask=input_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
use_cache=True,
)
past_key_values = outputs.past_key_values
# create hypothetical multiple next token and extent to next_input_ids
next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
# make sure that ids don't start with pad token
mask = next_tokens.ne(config.pad_token_id).long()
next_tokens = next_tokens * mask
next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
# append to next input_ids and
next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
output_from_no_past = model(
next_input_ids,
attention_mask=next_attention_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
output_hidden_states=True,
)["hidden_states"][0]
output_from_past = model(
next_tokens,
attention_mask=next_attention_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
past_key_values=past_key_values,
output_hidden_states=True,
)["hidden_states"][0]
# select random slice
random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
# test that outputs are equal for slice
self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
def create_and_check_for_masked_lm(
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
):
model = XLMRobertaXLForMaskedLM(config=config)
model.to(torch_device)
model.eval()
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
def create_and_check_for_token_classification(
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
):
config.num_labels = self.num_labels
model = XLMRobertaXLForTokenClassification(config=config)
model.to(torch_device)
model.eval()
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
def create_and_check_for_multiple_choice(
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
):
config.num_choices = self.num_choices
model = XLMRobertaXLForMultipleChoice(config=config)
model.to(torch_device)
model.eval()
multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
result = model(
multiple_choice_inputs_ids,
attention_mask=multiple_choice_input_mask,
token_type_ids=multiple_choice_token_type_ids,
labels=choice_labels,
)
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
def create_and_check_for_question_answering(
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
):
model = XLMRobertaXLForQuestionAnswering(config=config)
model.to(torch_device)
model.eval()
result = model(
input_ids,
attention_mask=input_mask,
token_type_ids=token_type_ids,
start_positions=sequence_labels,
end_positions=sequence_labels,
)
self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
def prepare_config_and_inputs_for_common(self):
config_and_inputs = self.prepare_config_and_inputs()
(
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
) = config_and_inputs
inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_torch
class XLMRobertaXLModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
all_model_classes = (
(
XLMRobertaXLForCausalLM,
XLMRobertaXLForMaskedLM,
XLMRobertaXLModel,
XLMRobertaXLForSequenceClassification,
XLMRobertaXLForTokenClassification,
XLMRobertaXLForMultipleChoice,
XLMRobertaXLForQuestionAnswering,
)
if is_torch_available()
else ()
)
all_generative_model_classes = (XLMRobertaXLForCausalLM,) if is_torch_available() else ()
def setUp(self):
self.model_tester = XLMRobertaXLModelTester(self)
self.config_tester = ConfigTester(self, config_class=XLMRobertaXLConfig, hidden_size=37)
def test_config(self):
self.config_tester.run_common_tests()
def test_model(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*config_and_inputs)
def test_model_various_embeddings(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
config_and_inputs[0].position_embedding_type = type
self.model_tester.create_and_check_model(*config_and_inputs)
def test_model_as_decoder(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
self.model_tester.create_and_check_model_as_decoder(*config_and_inputs)
def test_model_as_decoder_with_default_input_mask(self):
# This regression test was failing with PyTorch < 1.3
(
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
) = self.model_tester.prepare_config_and_inputs_for_decoder()
input_mask = None
self.model_tester.create_and_check_model_as_decoder(
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
)
def test_for_causal_lm(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
self.model_tester.create_and_check_for_causal_lm(*config_and_inputs)
def test_decoder_model_past_with_large_inputs(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
def test_for_masked_lm(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
def test_for_token_classification(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
def test_for_multiple_choice(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
def test_for_question_answering(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
def test_create_position_ids_respects_padding_index(self):
"""Ensure that the default position ids only assign a sequential . This is a regression
test for https://github.com/huggingface/transformers/issues/1761
The position ids should be masked with the embedding object's padding index. Therefore, the
first available non-padding position index is XLMRobertaXLEmbeddings.padding_idx + 1
"""
config = self.model_tester.prepare_config_and_inputs()[0]
model = XLMRobertaXLEmbeddings(config=config)
input_ids = torch.as_tensor([[12, 31, 13, model.padding_idx]])
expected_positions = torch.as_tensor(
[[0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx]]
)
position_ids = create_position_ids_from_input_ids(input_ids, model.padding_idx)
self.assertEqual(position_ids.shape, expected_positions.shape)
self.assertTrue(torch.all(torch.eq(position_ids, expected_positions)))
def test_create_position_ids_from_inputs_embeds(self):
"""Ensure that the default position ids only assign a sequential . This is a regression
test for https://github.com/huggingface/transformers/issues/1761
The position ids should be masked with the embedding object's padding index. Therefore, the
first available non-padding position index is XLMRobertaXLEmbeddings.padding_idx + 1
"""
config = self.model_tester.prepare_config_and_inputs()[0]
embeddings = XLMRobertaXLEmbeddings(config=config)
inputs_embeds = torch.empty(2, 4, 30)
expected_single_positions = [
0 + embeddings.padding_idx + 1,
1 + embeddings.padding_idx + 1,
2 + embeddings.padding_idx + 1,
3 + embeddings.padding_idx + 1,
]
expected_positions = torch.as_tensor([expected_single_positions, expected_single_positions])
position_ids = embeddings.create_position_ids_from_inputs_embeds(inputs_embeds)
self.assertEqual(position_ids.shape, expected_positions.shape)
self.assertTrue(torch.all(torch.eq(position_ids, expected_positions)))
@require_torch
class XLMRobertaModelXLIntegrationTest(unittest.TestCase):
@slow
def test_xlm_roberta_xl(self):
model = XLMRobertaXLModel.from_pretrained("facebook/xlm-roberta-xl").to(torch_device)
input_ids = torch.tensor(
[[0, 581, 10269, 83, 99942, 136, 60742, 23, 70, 80583, 18276, 2]], device=torch_device
)
# The dog is cute and lives in the garden house
expected_output_shape = torch.Size((1, 12, 2560)) # batch_size, sequence_length, embedding_vector_dim
expected_output_values_last_dim = torch.tensor(
[[0.0110, 0.0605, 0.0354, 0.0689, 0.0066, 0.0691, 0.0302, 0.0412, 0.0860, 0.0036, 0.0405, 0.0170]],
device=torch_device,
)
output = model(input_ids)["last_hidden_state"].detach()
self.assertEqual(output.shape, expected_output_shape)
# compare the actual values for a slice of last dim
self.assertTrue(torch.allclose(output[:, :, -1], expected_output_values_last_dim, atol=1e-3))
@unittest.skip(reason="Model is too large to be tested on the CI")
def test_xlm_roberta_xxl(self):
model = XLMRobertaXLModel.from_pretrained("facebook/xlm-roberta-xxl").to(torch_device)
input_ids = torch.tensor(
[[0, 581, 10269, 83, 99942, 136, 60742, 23, 70, 80583, 18276, 2]], device=torch_device
)
# The dog is cute and lives in the garden house
expected_output_shape = torch.Size((1, 12, 4096)) # batch_size, sequence_length, embedding_vector_dim
expected_output_values_last_dim = torch.tensor(
[[0.0046, 0.0146, 0.0227, 0.0126, 0.0219, 0.0175, -0.0101, 0.0006, 0.0124, 0.0209, -0.0063, 0.0096]],
device=torch_device,
)
output = model(input_ids)["last_hidden_state"].detach()
self.assertEqual(output.shape, expected_output_shape)
# compare the actual values for a slice of last dim
self.assertTrue(torch.allclose(output[:, :, -1], expected_output_values_last_dim, atol=1e-3)) | 0.784484 | 0.332202 |
# Parameterized type: <T>
class PropertyStore:
def setProperty(self, key, value):
"""
Returns void
Parameters:
key: Stringvalue: T
Throws:
PropertyStoreException
"""
pass
def getProperty(self, key):
"""
Returns T
Parameters:
key: String
Throws:
PropertyStoreException
"""
pass
def getProperty(self, key, propertyStat):
"""
Returns T
Parameters:
key: StringpropertyStat: PropertyStat
Throws:
PropertyStoreException
"""
pass
def removeProperty(self, key):
"""
Returns void
Parameters:
key: String
Throws:
PropertyStoreException
"""
pass
def getPropertyNames(self, prefix):
"""
Returns List<String>
Parameters:
prefix: String
Throws:
PropertyStoreException
"""
pass
def setPropertyDelimiter(self, delimiter):
"""
Returns void
Parameters:
delimiter: String
Throws:
PropertyStoreException
"""
pass
def subscribeForPropertyChange(self, prefix, listener):
"""
Returns void
Parameters:
prefix: Stringlistener: PropertyChangeListener<T>
Throws:
PropertyStoreException
"""
pass
def unsubscribeForPropertyChange(self, prefix, listener):
"""
Returns void
Parameters:
prefix: Stringlistener: PropertyChangeListener<T>
Throws:
PropertyStoreException
"""
pass
def canParentStoreData(self):
"""
Returns boolean
"""
pass
def setPropertySerializer(self, serializer):
"""
Returns void
Parameters:
serializer: PropertySerializer<T>
"""
pass
def createPropertyNamespace(self, prefix):
"""
Returns void
Parameters:
prefix: String
Throws:
PropertyStoreException
"""
pass
def getPropertyRootNamespace(self):
"""
Returns String
"""
pass
def updatePropertyUntilSucceed(self, key, updater):
"""
Returns void
Parameters:
key: Stringupdater: DataUpdater<T>
Throws:
PropertyStoreException
"""
pass
def updatePropertyUntilSucceed(self, key, updater, createIfAbsent):
"""
Returns void
Parameters:
key: Stringupdater: DataUpdater<T>createIfAbsent: boolean
Throws:
PropertyStoreException
"""
pass
def exists(self, key):
"""
Returns boolean
Parameters:
key: String
"""
pass
def removeNamespace(self, prefix):
"""
Returns void
Parameters:
prefix: String
Throws:
PropertyStoreException
"""
pass
def compareAndSet(self, key, expected, update, comparator):
"""
Returns boolean
Parameters:
key: Stringexpected: Tupdate: Tcomparator: Comparator<T>
"""
pass
def compareAndSet(self, key, expected, update, comparator, createIfAbsent):
"""
Returns boolean
Parameters:
key: Stringexpected: Tupdate: Tcomparator: Comparator<T>createIfAbsent: boolean
"""
pass
def start(self):
"""
Returns boolean
"""
pass
def stop(self):
"""
Returns boolean
"""
pass | org/apache/helix/store/PropertyStore.py |
# Parameterized type: <T>
class PropertyStore:
def setProperty(self, key, value):
"""
Returns void
Parameters:
key: Stringvalue: T
Throws:
PropertyStoreException
"""
pass
def getProperty(self, key):
"""
Returns T
Parameters:
key: String
Throws:
PropertyStoreException
"""
pass
def getProperty(self, key, propertyStat):
"""
Returns T
Parameters:
key: StringpropertyStat: PropertyStat
Throws:
PropertyStoreException
"""
pass
def removeProperty(self, key):
"""
Returns void
Parameters:
key: String
Throws:
PropertyStoreException
"""
pass
def getPropertyNames(self, prefix):
"""
Returns List<String>
Parameters:
prefix: String
Throws:
PropertyStoreException
"""
pass
def setPropertyDelimiter(self, delimiter):
"""
Returns void
Parameters:
delimiter: String
Throws:
PropertyStoreException
"""
pass
def subscribeForPropertyChange(self, prefix, listener):
"""
Returns void
Parameters:
prefix: Stringlistener: PropertyChangeListener<T>
Throws:
PropertyStoreException
"""
pass
def unsubscribeForPropertyChange(self, prefix, listener):
"""
Returns void
Parameters:
prefix: Stringlistener: PropertyChangeListener<T>
Throws:
PropertyStoreException
"""
pass
def canParentStoreData(self):
"""
Returns boolean
"""
pass
def setPropertySerializer(self, serializer):
"""
Returns void
Parameters:
serializer: PropertySerializer<T>
"""
pass
def createPropertyNamespace(self, prefix):
"""
Returns void
Parameters:
prefix: String
Throws:
PropertyStoreException
"""
pass
def getPropertyRootNamespace(self):
"""
Returns String
"""
pass
def updatePropertyUntilSucceed(self, key, updater):
"""
Returns void
Parameters:
key: Stringupdater: DataUpdater<T>
Throws:
PropertyStoreException
"""
pass
def updatePropertyUntilSucceed(self, key, updater, createIfAbsent):
"""
Returns void
Parameters:
key: Stringupdater: DataUpdater<T>createIfAbsent: boolean
Throws:
PropertyStoreException
"""
pass
def exists(self, key):
"""
Returns boolean
Parameters:
key: String
"""
pass
def removeNamespace(self, prefix):
"""
Returns void
Parameters:
prefix: String
Throws:
PropertyStoreException
"""
pass
def compareAndSet(self, key, expected, update, comparator):
"""
Returns boolean
Parameters:
key: Stringexpected: Tupdate: Tcomparator: Comparator<T>
"""
pass
def compareAndSet(self, key, expected, update, comparator, createIfAbsent):
"""
Returns boolean
Parameters:
key: Stringexpected: Tupdate: Tcomparator: Comparator<T>createIfAbsent: boolean
"""
pass
def start(self):
"""
Returns boolean
"""
pass
def stop(self):
"""
Returns boolean
"""
pass | 0.560012 | 0.141637 |
from typing import (
Any,
Collection,
Dict,
Iterator,
Optional,
Sequence,
Set,
Tuple,
Union,
)
import numpy as np
from pystiche import ComplexObject
from pystiche.loss import MultiOperatorLoss
from pystiche.misc import zip_equal
from pystiche.ops import ComparisonOperator, Operator, OperatorContainer
from .level import PyramidLevel
from .storage import ImageStorage
__all__ = ["ImagePyramid", "OctaveImagePyramid"]
class ImagePyramid(ComplexObject):
r"""Image pyramid for a coarse-to-fine optimization on different levels. If
iterated on yields :class:`~pystiche.pyramid.PyramidLevel` s and handles the
resizing of all set images and guides of ``resize_targets``.
Args:
edge_sizes: Edge sizes for each level.
num_steps: Number of steps for each level. If sequence of ``int`` its length
has to match the length of ``edge_sizes``.
edge: Corresponding edge to the edge size for each level. Can be ``"short"`` or
``"long"``. If sequence of ``str`` its length has to match the length of
``edge_sizes``. Defaults to ``"short"``.
interpolation_mode: Interpolation mode used for the resizing of the images.
Defaults to ``"bilinear"``.
.. note::
For the resizing of guides ``"nearest"`` is used regardless of the
``interpolation_mode``.
resize_targets: Targets for resizing of set images and guides during iteration.
"""
def __init__(
self,
edge_sizes: Sequence[int],
num_steps: Union[Sequence[int], int],
edge: Union[Sequence[str], str] = "short",
interpolation_mode: str = "bilinear",
resize_targets: Collection[Union[Operator, MultiOperatorLoss]] = (),
):
self._levels = self.build_levels(edge_sizes, num_steps, edge)
self.interpolation_mode = interpolation_mode
self._resize_targets = set(resize_targets)
@staticmethod
def build_levels(
edge_sizes: Sequence[int],
num_steps: Union[Sequence[int], int],
edge: Union[Sequence[str], str],
) -> Tuple[PyramidLevel, ...]:
num_levels = len(edge_sizes)
if isinstance(num_steps, int):
num_steps = [num_steps] * num_levels
if isinstance(edge, str):
edge = [edge] * num_levels
return tuple(
[
PyramidLevel(edge_size, num_steps_, edge_)
for edge_size, num_steps_, edge_ in zip_equal(
edge_sizes, num_steps, edge
)
]
)
# TODO: can this be removed?
def add_resize_target(self, op: Operator) -> None:
self._resize_targets.add(op)
def __len__(self) -> int:
return len(self._levels)
def __getitem__(self, idx: int) -> PyramidLevel:
return self._levels[idx]
def __iter__(self) -> Iterator[PyramidLevel]:
image_storage = ImageStorage(self._resize_ops())
for level in self._levels:
try:
self._resize(level)
yield level
finally:
image_storage.restore()
def _resize(self, level: PyramidLevel) -> None:
for op in self._resize_ops():
if isinstance(op, ComparisonOperator):
if op.has_target_guide:
resized_guide = level.resize_guide(op.target_guide)
op.set_target_guide(resized_guide, recalc_repr=False)
if op.has_target_image:
resized_image = level.resize_image(
op.target_image, interpolation_mode=self.interpolation_mode
)
op.set_target_image(resized_image)
if op.has_input_guide:
resized_guide = level.resize_guide(op.input_guide)
op.set_input_guide(resized_guide)
def _resize_ops(self) -> Set[Operator]:
resize_ops = set()
for target in self._resize_targets:
if isinstance(target, Operator):
resize_ops.add(target)
for op in target.operators(recurse=True):
if not isinstance(op, OperatorContainer):
resize_ops.add(op)
return resize_ops
def _properties(self) -> Dict[str, Any]:
dct = super()._properties()
if self.interpolation_mode != "bilinear":
dct["interpolation_mode"] = self.interpolation_mode
return dct
def _named_children(self) -> Iterator[Tuple[str, Any]]:
yield from super()._named_children()
for idx, level in enumerate(self._levels):
yield str(idx), level
class OctaveImagePyramid(ImagePyramid):
r"""Image pyramid that comprises levels spaced by a factor of two.
Args:
max_edge_size: Maximum edge size.
num_steps: Number of steps for each level.
.. note::
If ``num_steps`` is specified as sequence of ``int``s, you should also
specify ``num_levels`` to match the lengths
num_levels: Optional number of levels. If ``None``, the number is determined by
the number of steps of factor two between ``max_edge_size`` and
``min_edge_size``.
min_edge_size: Minimum edge size for the automatic calculation of
``num_levels``.
image_pyramid_kwargs: Additional options. See
:class:`~pystiche.pyramid.ImagePyramid` for details.
"""
def __init__(
self,
max_edge_size: int,
num_steps: Union[int, Sequence[int]],
num_levels: Optional[int] = None,
min_edge_size: int = 64,
**image_pyramid_kwargs: Any,
) -> None:
if num_levels is None:
num_levels = int(np.floor(np.log2(max_edge_size / min_edge_size))) + 1
edge_sizes = [
round(max_edge_size / (2.0 ** ((num_levels - 1) - level)))
for level in range(num_levels)
]
super().__init__(edge_sizes, num_steps, **image_pyramid_kwargs) | pystiche/pyramid/pyramid.py | from typing import (
Any,
Collection,
Dict,
Iterator,
Optional,
Sequence,
Set,
Tuple,
Union,
)
import numpy as np
from pystiche import ComplexObject
from pystiche.loss import MultiOperatorLoss
from pystiche.misc import zip_equal
from pystiche.ops import ComparisonOperator, Operator, OperatorContainer
from .level import PyramidLevel
from .storage import ImageStorage
__all__ = ["ImagePyramid", "OctaveImagePyramid"]
class ImagePyramid(ComplexObject):
r"""Image pyramid for a coarse-to-fine optimization on different levels. If
iterated on yields :class:`~pystiche.pyramid.PyramidLevel` s and handles the
resizing of all set images and guides of ``resize_targets``.
Args:
edge_sizes: Edge sizes for each level.
num_steps: Number of steps for each level. If sequence of ``int`` its length
has to match the length of ``edge_sizes``.
edge: Corresponding edge to the edge size for each level. Can be ``"short"`` or
``"long"``. If sequence of ``str`` its length has to match the length of
``edge_sizes``. Defaults to ``"short"``.
interpolation_mode: Interpolation mode used for the resizing of the images.
Defaults to ``"bilinear"``.
.. note::
For the resizing of guides ``"nearest"`` is used regardless of the
``interpolation_mode``.
resize_targets: Targets for resizing of set images and guides during iteration.
"""
def __init__(
self,
edge_sizes: Sequence[int],
num_steps: Union[Sequence[int], int],
edge: Union[Sequence[str], str] = "short",
interpolation_mode: str = "bilinear",
resize_targets: Collection[Union[Operator, MultiOperatorLoss]] = (),
):
self._levels = self.build_levels(edge_sizes, num_steps, edge)
self.interpolation_mode = interpolation_mode
self._resize_targets = set(resize_targets)
@staticmethod
def build_levels(
edge_sizes: Sequence[int],
num_steps: Union[Sequence[int], int],
edge: Union[Sequence[str], str],
) -> Tuple[PyramidLevel, ...]:
num_levels = len(edge_sizes)
if isinstance(num_steps, int):
num_steps = [num_steps] * num_levels
if isinstance(edge, str):
edge = [edge] * num_levels
return tuple(
[
PyramidLevel(edge_size, num_steps_, edge_)
for edge_size, num_steps_, edge_ in zip_equal(
edge_sizes, num_steps, edge
)
]
)
# TODO: can this be removed?
def add_resize_target(self, op: Operator) -> None:
self._resize_targets.add(op)
def __len__(self) -> int:
return len(self._levels)
def __getitem__(self, idx: int) -> PyramidLevel:
return self._levels[idx]
def __iter__(self) -> Iterator[PyramidLevel]:
image_storage = ImageStorage(self._resize_ops())
for level in self._levels:
try:
self._resize(level)
yield level
finally:
image_storage.restore()
def _resize(self, level: PyramidLevel) -> None:
for op in self._resize_ops():
if isinstance(op, ComparisonOperator):
if op.has_target_guide:
resized_guide = level.resize_guide(op.target_guide)
op.set_target_guide(resized_guide, recalc_repr=False)
if op.has_target_image:
resized_image = level.resize_image(
op.target_image, interpolation_mode=self.interpolation_mode
)
op.set_target_image(resized_image)
if op.has_input_guide:
resized_guide = level.resize_guide(op.input_guide)
op.set_input_guide(resized_guide)
def _resize_ops(self) -> Set[Operator]:
resize_ops = set()
for target in self._resize_targets:
if isinstance(target, Operator):
resize_ops.add(target)
for op in target.operators(recurse=True):
if not isinstance(op, OperatorContainer):
resize_ops.add(op)
return resize_ops
def _properties(self) -> Dict[str, Any]:
dct = super()._properties()
if self.interpolation_mode != "bilinear":
dct["interpolation_mode"] = self.interpolation_mode
return dct
def _named_children(self) -> Iterator[Tuple[str, Any]]:
yield from super()._named_children()
for idx, level in enumerate(self._levels):
yield str(idx), level
class OctaveImagePyramid(ImagePyramid):
r"""Image pyramid that comprises levels spaced by a factor of two.
Args:
max_edge_size: Maximum edge size.
num_steps: Number of steps for each level.
.. note::
If ``num_steps`` is specified as sequence of ``int``s, you should also
specify ``num_levels`` to match the lengths
num_levels: Optional number of levels. If ``None``, the number is determined by
the number of steps of factor two between ``max_edge_size`` and
``min_edge_size``.
min_edge_size: Minimum edge size for the automatic calculation of
``num_levels``.
image_pyramid_kwargs: Additional options. See
:class:`~pystiche.pyramid.ImagePyramid` for details.
"""
def __init__(
self,
max_edge_size: int,
num_steps: Union[int, Sequence[int]],
num_levels: Optional[int] = None,
min_edge_size: int = 64,
**image_pyramid_kwargs: Any,
) -> None:
if num_levels is None:
num_levels = int(np.floor(np.log2(max_edge_size / min_edge_size))) + 1
edge_sizes = [
round(max_edge_size / (2.0 ** ((num_levels - 1) - level)))
for level in range(num_levels)
]
super().__init__(edge_sizes, num_steps, **image_pyramid_kwargs) | 0.890488 | 0.521654 |
from __future__ import division
from enum import Enum
import pytest
from mock import call, MagicMock, Mock
from pytest import raises, approx
import numpy as np
import torch
from torch.nn import Linear
from torch.nn.functional import mse_loss
from torch.optim import SGD
from ignite.engine import Engine, Events, State, create_supervised_trainer, create_supervised_evaluator
from ignite.metrics import MeanSquaredError
def process_func(engine, batch):
return 1
class DummyEngine(Engine):
def __init__(self):
super(DummyEngine, self).__init__(process_func)
def run(self, num_times):
self.state = State()
for _ in range(num_times):
self.fire_event(Events.STARTED)
self.fire_event(Events.COMPLETED)
return self.state
def test_terminate():
engine = DummyEngine()
assert not engine.should_terminate
engine.terminate()
assert engine.should_terminate
def test_invalid_process_raises_with_invalid_signature():
with pytest.raises(ValueError):
Engine(None)
with pytest.raises(ValueError):
Engine(lambda: None)
with pytest.raises(ValueError):
Engine(lambda batch: None)
with pytest.raises(ValueError):
Engine(lambda engine, batch, extra_arg: None)
def test_add_event_handler_raises_with_invalid_event():
engine = DummyEngine()
with pytest.raises(ValueError):
engine.add_event_handler("incorrect", lambda engine: None)
def test_add_event_handler_raises_with_invalid_signature():
engine = Engine(MagicMock())
def handler(engine):
pass
engine.add_event_handler(Events.STARTED, handler)
with pytest.raises(ValueError):
engine.add_event_handler(Events.STARTED, handler, 1)
def handler_with_args(engine, a):
pass
engine.add_event_handler(Events.STARTED, handler_with_args, 1)
with pytest.raises(ValueError):
engine.add_event_handler(Events.STARTED, handler_with_args)
def handler_with_kwargs(engine, b=42):
pass
engine.add_event_handler(Events.STARTED, handler_with_kwargs, b=2)
with pytest.raises(ValueError):
engine.add_event_handler(Events.STARTED, handler_with_kwargs, c=3)
with pytest.raises(ValueError):
engine.add_event_handler(Events.STARTED, handler_with_kwargs, 1, b=2)
def handler_with_args_and_kwargs(engine, a, b=42):
pass
engine.add_event_handler(Events.STARTED, handler_with_args_and_kwargs, 1, b=2)
with pytest.raises(ValueError):
engine.add_event_handler(Events.STARTED, handler_with_args_and_kwargs, 1, 2, b=2)
with pytest.raises(ValueError):
engine.add_event_handler(Events.STARTED, handler_with_args_and_kwargs, 1, b=2, c=3)
def test_add_event_handler():
engine = DummyEngine()
class Counter(object):
def __init__(self, count=0):
self.count = count
started_counter = Counter()
def handle_iteration_started(engine, counter):
counter.count += 1
engine.add_event_handler(Events.STARTED, handle_iteration_started, started_counter)
completed_counter = Counter()
def handle_iteration_completed(engine, counter):
counter.count += 1
engine.add_event_handler(Events.COMPLETED, handle_iteration_completed, completed_counter)
engine.run(15)
assert started_counter.count == 15
assert completed_counter.count == 15
def test_adding_multiple_event_handlers():
engine = DummyEngine()
handlers = [MagicMock(), MagicMock()]
for handler in handlers:
engine.add_event_handler(Events.STARTED, handler)
engine.run(1)
for handler in handlers:
handler.assert_called_once_with(engine)
def test_has_event_handler():
engine = DummyEngine()
handlers = [MagicMock(), MagicMock()]
m = MagicMock()
for handler in handlers:
engine.add_event_handler(Events.STARTED, handler)
engine.add_event_handler(Events.COMPLETED, m)
for handler in handlers:
assert engine.has_event_handler(handler, Events.STARTED)
assert engine.has_event_handler(handler)
assert not engine.has_event_handler(handler, Events.COMPLETED)
assert not engine.has_event_handler(handler, Events.EPOCH_STARTED)
assert not engine.has_event_handler(m, Events.STARTED)
assert engine.has_event_handler(m, Events.COMPLETED)
assert engine.has_event_handler(m)
assert not engine.has_event_handler(m, Events.EPOCH_STARTED)
def test_args_and_kwargs_are_passed_to_event():
engine = DummyEngine()
kwargs = {'a': 'a', 'b': 'b'}
args = (1, 2, 3)
handlers = []
for event in [Events.STARTED, Events.COMPLETED]:
handler = MagicMock()
engine.add_event_handler(event, handler, *args, **kwargs)
handlers.append(handler)
engine.run(1)
called_handlers = [handle for handle in handlers if handle.called]
assert len(called_handlers) == 2
for handler in called_handlers:
handler_args, handler_kwargs = handler.call_args
assert handler_args[0] == engine
assert handler_args[1::] == args
assert handler_kwargs == kwargs
def test_custom_events():
class Custom_Events(Enum):
TEST_EVENT = "test_event"
# Dummy engine
engine = Engine(lambda engine, batch: 0)
engine.register_events(*Custom_Events)
# Handle is never called
handle = MagicMock()
engine.add_event_handler(Custom_Events.TEST_EVENT, handle)
engine.run(range(1))
assert not handle.called
# Advanced engine
def process_func(engine, batch):
engine.fire_event(Custom_Events.TEST_EVENT)
engine = Engine(process_func)
engine.register_events(*Custom_Events)
# Handle should be called
handle = MagicMock()
engine.add_event_handler(Custom_Events.TEST_EVENT, handle)
engine.run(range(1))
assert handle.called
def test_on_decorator_raises_with_invalid_event():
engine = DummyEngine()
with pytest.raises(ValueError):
@engine.on("incorrect")
def f(engine):
pass
def test_on_decorator():
engine = DummyEngine()
class Counter(object):
def __init__(self, count=0):
self.count = count
started_counter = Counter()
@engine.on(Events.STARTED, started_counter)
def handle_iteration_started(engine, started_counter):
started_counter.count += 1
completed_counter = Counter()
@engine.on(Events.COMPLETED, completed_counter)
def handle_iteration_completed(engine, completed_counter):
completed_counter.count += 1
engine.run(15)
assert started_counter.count == 15
assert completed_counter.count == 15
def test_returns_state():
engine = Engine(MagicMock(return_value=1))
state = engine.run([])
assert isinstance(state, State)
def test_state_attributes():
dataloader = [1, 2, 3]
engine = Engine(MagicMock(return_value=1))
state = engine.run(dataloader, max_epochs=3)
assert state.iteration == 9
assert state.output == 1
assert state.batch == 3
assert state.dataloader == dataloader
assert state.epoch == 3
assert state.max_epochs == 3
assert state.metrics == {}
def test_default_exception_handler():
update_function = MagicMock(side_effect=ValueError())
engine = Engine(update_function)
with raises(ValueError):
engine.run([1])
def test_custom_exception_handler():
value_error = ValueError()
update_function = MagicMock(side_effect=value_error)
engine = Engine(update_function)
class ExceptionCounter(object):
def __init__(self):
self.exceptions = []
def __call__(self, engine, e):
self.exceptions.append(e)
counter = ExceptionCounter()
engine.add_event_handler(Events.EXCEPTION_RAISED, counter)
engine.run([1])
# only one call from _run_once_over_data, since the exception is swallowed
assert len(counter.exceptions) == 1 and counter.exceptions[0] == value_error
def test_current_epoch_counter_increases_every_epoch():
engine = Engine(MagicMock(return_value=1))
max_epochs = 5
class EpochCounter(object):
def __init__(self):
self.current_epoch_count = 1
def __call__(self, engine):
assert engine.state.epoch == self.current_epoch_count
self.current_epoch_count += 1
engine.add_event_handler(Events.EPOCH_STARTED, EpochCounter())
state = engine.run([1], max_epochs=max_epochs)
assert state.epoch == max_epochs
def test_current_iteration_counter_increases_every_iteration():
batches = [1, 2, 3]
engine = Engine(MagicMock(return_value=1))
max_epochs = 5
class IterationCounter(object):
def __init__(self):
self.current_iteration_count = 1
def __call__(self, engine):
assert engine.state.iteration == self.current_iteration_count
self.current_iteration_count += 1
engine.add_event_handler(Events.ITERATION_STARTED, IterationCounter())
state = engine.run(batches, max_epochs=max_epochs)
assert state.iteration == max_epochs * len(batches)
def test_stopping_criterion_is_max_epochs():
engine = Engine(MagicMock(return_value=1))
max_epochs = 5
state = engine.run([1], max_epochs=max_epochs)
assert state.epoch == max_epochs
def test_terminate_at_end_of_epoch_stops_run():
max_epochs = 5
last_epoch_to_run = 3
engine = Engine(MagicMock(return_value=1))
def end_of_epoch_handler(engine):
if engine.state.epoch == last_epoch_to_run:
engine.terminate()
engine.add_event_handler(Events.EPOCH_COMPLETED, end_of_epoch_handler)
assert not engine.should_terminate
state = engine.run([1], max_epochs=max_epochs)
assert state.epoch == last_epoch_to_run
assert engine.should_terminate
def test_terminate_at_start_of_epoch_stops_run_after_completing_iteration():
max_epochs = 5
epoch_to_terminate_on = 3
batches_per_epoch = [1, 2, 3]
engine = Engine(MagicMock(return_value=1))
def start_of_epoch_handler(engine):
if engine.state.epoch == epoch_to_terminate_on:
engine.terminate()
engine.add_event_handler(Events.EPOCH_STARTED, start_of_epoch_handler)
assert not engine.should_terminate
state = engine.run(batches_per_epoch, max_epochs=max_epochs)
# epoch is not completed so counter is not incremented
assert state.epoch == epoch_to_terminate_on
assert engine.should_terminate
# completes first iteration
assert state.iteration == ((epoch_to_terminate_on - 1) * len(batches_per_epoch)) + 1
def test_terminate_stops_run_mid_epoch():
num_iterations_per_epoch = 10
iteration_to_stop = num_iterations_per_epoch + 3
engine = Engine(MagicMock(return_value=1))
def start_of_iteration_handler(engine):
if engine.state.iteration == iteration_to_stop:
engine.terminate()
engine.add_event_handler(Events.ITERATION_STARTED, start_of_iteration_handler)
state = engine.run(data=[None] * num_iterations_per_epoch, max_epochs=3)
# completes the iteration but doesn't increment counter (this happens just before a new iteration starts)
assert (state.iteration == iteration_to_stop)
assert state.epoch == np.ceil(iteration_to_stop / num_iterations_per_epoch) # it starts from 0
def test_terminate_epoch_stops_mid_epoch():
num_iterations_per_epoch = 10
iteration_to_stop = num_iterations_per_epoch + 3
engine = Engine(MagicMock(return_value=1))
def start_of_iteration_handler(engine):
if engine.state.iteration == iteration_to_stop:
engine.terminate_epoch()
max_epochs = 3
engine.add_event_handler(Events.ITERATION_STARTED, start_of_iteration_handler)
state = engine.run(data=[None] * num_iterations_per_epoch, max_epochs=max_epochs)
# completes the iteration but doesn't increment counter (this happens just before a new iteration starts)
assert state.iteration == num_iterations_per_epoch * (max_epochs - 1) + \
iteration_to_stop % num_iterations_per_epoch
def _create_mock_data_loader(epochs, batches_per_epoch):
batches = [MagicMock()] * batches_per_epoch
data_loader_manager = MagicMock()
batch_iterators = [iter(batches) for _ in range(epochs)]
data_loader_manager.__iter__.side_effect = batch_iterators
return data_loader_manager
def test_iteration_events_are_fired():
max_epochs = 5
num_batches = 3
data = _create_mock_data_loader(max_epochs, num_batches)
engine = Engine(MagicMock(return_value=1))
mock_manager = Mock()
iteration_started = Mock()
engine.add_event_handler(Events.ITERATION_STARTED, iteration_started)
iteration_complete = Mock()
engine.add_event_handler(Events.ITERATION_COMPLETED, iteration_complete)
mock_manager.attach_mock(iteration_started, 'iteration_started')
mock_manager.attach_mock(iteration_complete, 'iteration_complete')
engine.run(data, max_epochs=max_epochs)
assert iteration_started.call_count == num_batches * max_epochs
assert iteration_complete.call_count == num_batches * max_epochs
expected_calls = []
for i in range(max_epochs * num_batches):
expected_calls.append(call.iteration_started(engine))
expected_calls.append(call.iteration_complete(engine))
assert mock_manager.mock_calls == expected_calls
def test_create_supervised_trainer():
model = Linear(1, 1)
model.weight.data.zero_()
model.bias.data.zero_()
optimizer = SGD(model.parameters(), 0.1)
trainer = create_supervised_trainer(model, optimizer, mse_loss)
x = torch.FloatTensor([[1.0], [2.0]])
y = torch.FloatTensor([[3.0], [5.0]])
data = [(x, y)]
assert model.weight.data[0, 0].item() == approx(0.0)
assert model.bias.item() == approx(0.0)
state = trainer.run(data)
assert state.output == approx(17.0)
assert model.weight.data[0, 0].item() == approx(1.3)
assert model.bias.item() == approx(0.8)
def test_create_supervised_trainer_with_cpu():
model = Linear(1, 1)
model.weight.data.zero_()
model.bias.data.zero_()
optimizer = SGD(model.parameters(), 0.1)
trainer = create_supervised_trainer(model, optimizer, mse_loss, device='cpu')
x = torch.FloatTensor([[1.0], [2.0]])
y = torch.FloatTensor([[3.0], [5.0]])
data = [(x, y)]
assert model.weight.data[0, 0].item() == approx(0.0)
assert model.bias.item() == approx(0.0)
state = trainer.run(data)
assert state.output == approx(17.0)
assert model.weight.data[0, 0].item() == approx(1.3)
assert model.bias.item() == approx(0.8)
def test_create_supervised_trainer_traced_with_cpu():
model = Linear(1, 1)
model.weight.data.zero_()
model.bias.data.zero_()
class DummyContext(object):
def __enter__(self):
return None
def __exit__(self, exc_type, exc_value, traceback):
return False
example_input = torch.randn(1, 1)
traced_model = torch.jit.trace(model, example_input)
optimizer = SGD(traced_model.parameters(), 0.1)
ctx = DummyContext() if 'dev' in torch.__version__ else pytest.raises(RuntimeError)
with ctx:
trainer = create_supervised_trainer(traced_model, optimizer, mse_loss, device='cpu')
x = torch.FloatTensor([[1.0], [2.0]])
y = torch.FloatTensor([[3.0], [5.0]])
data = [(x, y)]
assert traced_model.weight.data[0, 0].item() == approx(0.0)
assert traced_model.bias.item() == approx(0.0)
state = trainer.run(data)
assert state.output == approx(17.0)
assert traced_model.weight.data[0, 0].item() == approx(1.3)
assert traced_model.bias.item() == approx(0.8)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="Skip if no GPU")
def test_create_supervised_trainer_on_cuda():
model = Linear(1, 1)
model.weight.data.zero_()
model.bias.data.zero_()
optimizer = SGD(model.parameters(), 0.1)
trainer = create_supervised_trainer(model, optimizer, mse_loss, device='cuda')
x = torch.FloatTensor([[1.0], [2.0]])
y = torch.FloatTensor([[3.0], [5.0]])
data = [(x, y)]
assert model.weight.data[0, 0].item() == approx(0.0)
assert model.bias.item() == approx(0.0)
state = trainer.run(data)
assert state.output == approx(17.0)
assert model.weight.data[0, 0].item() == approx(1.3)
assert model.bias.item() == approx(0.8)
def test_create_supervised():
model = Linear(1, 1)
model.weight.data.zero_()
model.bias.data.zero_()
evaluator = create_supervised_evaluator(model)
x = torch.FloatTensor([[1.0], [2.0]])
y = torch.FloatTensor([[3.0], [5.0]])
data = [(x, y)]
state = evaluator.run(data)
y_pred, y = state.output
assert y_pred[0, 0].item() == approx(0.0)
assert y_pred[1, 0].item() == approx(0.0)
assert y[0, 0].item() == approx(3.0)
assert y[1, 0].item() == approx(5.0)
assert model.weight.data[0, 0].item() == approx(0.0)
assert model.bias.item() == approx(0.0)
def test_create_supervised_on_cpu():
model = Linear(1, 1)
model.weight.data.zero_()
model.bias.data.zero_()
evaluator = create_supervised_evaluator(model, device='cpu')
x = torch.FloatTensor([[1.0], [2.0]])
y = torch.FloatTensor([[3.0], [5.0]])
data = [(x, y)]
state = evaluator.run(data)
y_pred, y = state.output
assert y_pred[0, 0].item() == approx(0.0)
assert y_pred[1, 0].item() == approx(0.0)
assert y[0, 0].item() == approx(3.0)
assert y[1, 0].item() == approx(5.0)
assert model.weight.data[0, 0].item() == approx(0.0)
assert model.bias.item() == approx(0.0)
def test_create_supervised_evaluator_traced_on_cpu():
model = Linear(1, 1)
model.weight.data.zero_()
model.bias.data.zero_()
class DummyContext(object):
def __enter__(self):
return None
def __exit__(self, exc_type, exc_value, traceback):
return False
ctx = DummyContext() if 'dev' in torch.__version__ else pytest.raises(RuntimeError)
example_input = torch.randn(1, 1)
traced_model = torch.jit.trace(model, example_input)
with ctx:
evaluator = create_supervised_evaluator(traced_model, device='cpu')
x = torch.FloatTensor([[1.0], [2.0]])
y = torch.FloatTensor([[3.0], [5.0]])
data = [(x, y)]
state = evaluator.run(data)
y_pred, y = state.output
assert y_pred[0, 0].item() == approx(0.0)
assert y_pred[1, 0].item() == approx(0.0)
assert y[0, 0].item() == approx(3.0)
assert y[1, 0].item() == approx(5.0)
assert traced_model.weight.data[0, 0].item() == approx(0.0)
assert traced_model.bias.item() == approx(0.0)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="Skip if no GPU")
def test_create_supervised_on_cuda():
model = Linear(1, 1)
model.weight.data.zero_()
model.bias.data.zero_()
evaluator = create_supervised_evaluator(model, device='cuda')
x = torch.FloatTensor([[1.0], [2.0]])
y = torch.FloatTensor([[3.0], [5.0]])
data = [(x, y)]
state = evaluator.run(data)
y_pred, y = state.output
assert y_pred[0, 0].item() == approx(0.0)
assert y_pred[1, 0].item() == approx(0.0)
assert y[0, 0].item() == approx(3.0)
assert y[1, 0].item() == approx(5.0)
assert model.weight.data[0, 0].item() == approx(0.0)
assert model.bias.item() == approx(0.0)
def test_create_supervised_with_metrics():
model = Linear(1, 1)
model.weight.data.zero_()
model.bias.data.zero_()
evaluator = create_supervised_evaluator(model, metrics={'mse': MeanSquaredError()})
x = torch.FloatTensor([[1.0], [2.0]])
y = torch.FloatTensor([[3.0], [4.0]])
data = [(x, y)]
state = evaluator.run(data)
assert state.metrics['mse'] == 12.5 | tests/ignite/engine/test_engine.py | from __future__ import division
from enum import Enum
import pytest
from mock import call, MagicMock, Mock
from pytest import raises, approx
import numpy as np
import torch
from torch.nn import Linear
from torch.nn.functional import mse_loss
from torch.optim import SGD
from ignite.engine import Engine, Events, State, create_supervised_trainer, create_supervised_evaluator
from ignite.metrics import MeanSquaredError
def process_func(engine, batch):
return 1
class DummyEngine(Engine):
def __init__(self):
super(DummyEngine, self).__init__(process_func)
def run(self, num_times):
self.state = State()
for _ in range(num_times):
self.fire_event(Events.STARTED)
self.fire_event(Events.COMPLETED)
return self.state
def test_terminate():
engine = DummyEngine()
assert not engine.should_terminate
engine.terminate()
assert engine.should_terminate
def test_invalid_process_raises_with_invalid_signature():
with pytest.raises(ValueError):
Engine(None)
with pytest.raises(ValueError):
Engine(lambda: None)
with pytest.raises(ValueError):
Engine(lambda batch: None)
with pytest.raises(ValueError):
Engine(lambda engine, batch, extra_arg: None)
def test_add_event_handler_raises_with_invalid_event():
engine = DummyEngine()
with pytest.raises(ValueError):
engine.add_event_handler("incorrect", lambda engine: None)
def test_add_event_handler_raises_with_invalid_signature():
engine = Engine(MagicMock())
def handler(engine):
pass
engine.add_event_handler(Events.STARTED, handler)
with pytest.raises(ValueError):
engine.add_event_handler(Events.STARTED, handler, 1)
def handler_with_args(engine, a):
pass
engine.add_event_handler(Events.STARTED, handler_with_args, 1)
with pytest.raises(ValueError):
engine.add_event_handler(Events.STARTED, handler_with_args)
def handler_with_kwargs(engine, b=42):
pass
engine.add_event_handler(Events.STARTED, handler_with_kwargs, b=2)
with pytest.raises(ValueError):
engine.add_event_handler(Events.STARTED, handler_with_kwargs, c=3)
with pytest.raises(ValueError):
engine.add_event_handler(Events.STARTED, handler_with_kwargs, 1, b=2)
def handler_with_args_and_kwargs(engine, a, b=42):
pass
engine.add_event_handler(Events.STARTED, handler_with_args_and_kwargs, 1, b=2)
with pytest.raises(ValueError):
engine.add_event_handler(Events.STARTED, handler_with_args_and_kwargs, 1, 2, b=2)
with pytest.raises(ValueError):
engine.add_event_handler(Events.STARTED, handler_with_args_and_kwargs, 1, b=2, c=3)
def test_add_event_handler():
engine = DummyEngine()
class Counter(object):
def __init__(self, count=0):
self.count = count
started_counter = Counter()
def handle_iteration_started(engine, counter):
counter.count += 1
engine.add_event_handler(Events.STARTED, handle_iteration_started, started_counter)
completed_counter = Counter()
def handle_iteration_completed(engine, counter):
counter.count += 1
engine.add_event_handler(Events.COMPLETED, handle_iteration_completed, completed_counter)
engine.run(15)
assert started_counter.count == 15
assert completed_counter.count == 15
def test_adding_multiple_event_handlers():
engine = DummyEngine()
handlers = [MagicMock(), MagicMock()]
for handler in handlers:
engine.add_event_handler(Events.STARTED, handler)
engine.run(1)
for handler in handlers:
handler.assert_called_once_with(engine)
def test_has_event_handler():
engine = DummyEngine()
handlers = [MagicMock(), MagicMock()]
m = MagicMock()
for handler in handlers:
engine.add_event_handler(Events.STARTED, handler)
engine.add_event_handler(Events.COMPLETED, m)
for handler in handlers:
assert engine.has_event_handler(handler, Events.STARTED)
assert engine.has_event_handler(handler)
assert not engine.has_event_handler(handler, Events.COMPLETED)
assert not engine.has_event_handler(handler, Events.EPOCH_STARTED)
assert not engine.has_event_handler(m, Events.STARTED)
assert engine.has_event_handler(m, Events.COMPLETED)
assert engine.has_event_handler(m)
assert not engine.has_event_handler(m, Events.EPOCH_STARTED)
def test_args_and_kwargs_are_passed_to_event():
engine = DummyEngine()
kwargs = {'a': 'a', 'b': 'b'}
args = (1, 2, 3)
handlers = []
for event in [Events.STARTED, Events.COMPLETED]:
handler = MagicMock()
engine.add_event_handler(event, handler, *args, **kwargs)
handlers.append(handler)
engine.run(1)
called_handlers = [handle for handle in handlers if handle.called]
assert len(called_handlers) == 2
for handler in called_handlers:
handler_args, handler_kwargs = handler.call_args
assert handler_args[0] == engine
assert handler_args[1::] == args
assert handler_kwargs == kwargs
def test_custom_events():
class Custom_Events(Enum):
TEST_EVENT = "test_event"
# Dummy engine
engine = Engine(lambda engine, batch: 0)
engine.register_events(*Custom_Events)
# Handle is never called
handle = MagicMock()
engine.add_event_handler(Custom_Events.TEST_EVENT, handle)
engine.run(range(1))
assert not handle.called
# Advanced engine
def process_func(engine, batch):
engine.fire_event(Custom_Events.TEST_EVENT)
engine = Engine(process_func)
engine.register_events(*Custom_Events)
# Handle should be called
handle = MagicMock()
engine.add_event_handler(Custom_Events.TEST_EVENT, handle)
engine.run(range(1))
assert handle.called
def test_on_decorator_raises_with_invalid_event():
engine = DummyEngine()
with pytest.raises(ValueError):
@engine.on("incorrect")
def f(engine):
pass
def test_on_decorator():
engine = DummyEngine()
class Counter(object):
def __init__(self, count=0):
self.count = count
started_counter = Counter()
@engine.on(Events.STARTED, started_counter)
def handle_iteration_started(engine, started_counter):
started_counter.count += 1
completed_counter = Counter()
@engine.on(Events.COMPLETED, completed_counter)
def handle_iteration_completed(engine, completed_counter):
completed_counter.count += 1
engine.run(15)
assert started_counter.count == 15
assert completed_counter.count == 15
def test_returns_state():
engine = Engine(MagicMock(return_value=1))
state = engine.run([])
assert isinstance(state, State)
def test_state_attributes():
dataloader = [1, 2, 3]
engine = Engine(MagicMock(return_value=1))
state = engine.run(dataloader, max_epochs=3)
assert state.iteration == 9
assert state.output == 1
assert state.batch == 3
assert state.dataloader == dataloader
assert state.epoch == 3
assert state.max_epochs == 3
assert state.metrics == {}
def test_default_exception_handler():
update_function = MagicMock(side_effect=ValueError())
engine = Engine(update_function)
with raises(ValueError):
engine.run([1])
def test_custom_exception_handler():
value_error = ValueError()
update_function = MagicMock(side_effect=value_error)
engine = Engine(update_function)
class ExceptionCounter(object):
def __init__(self):
self.exceptions = []
def __call__(self, engine, e):
self.exceptions.append(e)
counter = ExceptionCounter()
engine.add_event_handler(Events.EXCEPTION_RAISED, counter)
engine.run([1])
# only one call from _run_once_over_data, since the exception is swallowed
assert len(counter.exceptions) == 1 and counter.exceptions[0] == value_error
def test_current_epoch_counter_increases_every_epoch():
engine = Engine(MagicMock(return_value=1))
max_epochs = 5
class EpochCounter(object):
def __init__(self):
self.current_epoch_count = 1
def __call__(self, engine):
assert engine.state.epoch == self.current_epoch_count
self.current_epoch_count += 1
engine.add_event_handler(Events.EPOCH_STARTED, EpochCounter())
state = engine.run([1], max_epochs=max_epochs)
assert state.epoch == max_epochs
def test_current_iteration_counter_increases_every_iteration():
batches = [1, 2, 3]
engine = Engine(MagicMock(return_value=1))
max_epochs = 5
class IterationCounter(object):
def __init__(self):
self.current_iteration_count = 1
def __call__(self, engine):
assert engine.state.iteration == self.current_iteration_count
self.current_iteration_count += 1
engine.add_event_handler(Events.ITERATION_STARTED, IterationCounter())
state = engine.run(batches, max_epochs=max_epochs)
assert state.iteration == max_epochs * len(batches)
def test_stopping_criterion_is_max_epochs():
engine = Engine(MagicMock(return_value=1))
max_epochs = 5
state = engine.run([1], max_epochs=max_epochs)
assert state.epoch == max_epochs
def test_terminate_at_end_of_epoch_stops_run():
max_epochs = 5
last_epoch_to_run = 3
engine = Engine(MagicMock(return_value=1))
def end_of_epoch_handler(engine):
if engine.state.epoch == last_epoch_to_run:
engine.terminate()
engine.add_event_handler(Events.EPOCH_COMPLETED, end_of_epoch_handler)
assert not engine.should_terminate
state = engine.run([1], max_epochs=max_epochs)
assert state.epoch == last_epoch_to_run
assert engine.should_terminate
def test_terminate_at_start_of_epoch_stops_run_after_completing_iteration():
max_epochs = 5
epoch_to_terminate_on = 3
batches_per_epoch = [1, 2, 3]
engine = Engine(MagicMock(return_value=1))
def start_of_epoch_handler(engine):
if engine.state.epoch == epoch_to_terminate_on:
engine.terminate()
engine.add_event_handler(Events.EPOCH_STARTED, start_of_epoch_handler)
assert not engine.should_terminate
state = engine.run(batches_per_epoch, max_epochs=max_epochs)
# epoch is not completed so counter is not incremented
assert state.epoch == epoch_to_terminate_on
assert engine.should_terminate
# completes first iteration
assert state.iteration == ((epoch_to_terminate_on - 1) * len(batches_per_epoch)) + 1
def test_terminate_stops_run_mid_epoch():
num_iterations_per_epoch = 10
iteration_to_stop = num_iterations_per_epoch + 3
engine = Engine(MagicMock(return_value=1))
def start_of_iteration_handler(engine):
if engine.state.iteration == iteration_to_stop:
engine.terminate()
engine.add_event_handler(Events.ITERATION_STARTED, start_of_iteration_handler)
state = engine.run(data=[None] * num_iterations_per_epoch, max_epochs=3)
# completes the iteration but doesn't increment counter (this happens just before a new iteration starts)
assert (state.iteration == iteration_to_stop)
assert state.epoch == np.ceil(iteration_to_stop / num_iterations_per_epoch) # it starts from 0
def test_terminate_epoch_stops_mid_epoch():
num_iterations_per_epoch = 10
iteration_to_stop = num_iterations_per_epoch + 3
engine = Engine(MagicMock(return_value=1))
def start_of_iteration_handler(engine):
if engine.state.iteration == iteration_to_stop:
engine.terminate_epoch()
max_epochs = 3
engine.add_event_handler(Events.ITERATION_STARTED, start_of_iteration_handler)
state = engine.run(data=[None] * num_iterations_per_epoch, max_epochs=max_epochs)
# completes the iteration but doesn't increment counter (this happens just before a new iteration starts)
assert state.iteration == num_iterations_per_epoch * (max_epochs - 1) + \
iteration_to_stop % num_iterations_per_epoch
def _create_mock_data_loader(epochs, batches_per_epoch):
batches = [MagicMock()] * batches_per_epoch
data_loader_manager = MagicMock()
batch_iterators = [iter(batches) for _ in range(epochs)]
data_loader_manager.__iter__.side_effect = batch_iterators
return data_loader_manager
def test_iteration_events_are_fired():
max_epochs = 5
num_batches = 3
data = _create_mock_data_loader(max_epochs, num_batches)
engine = Engine(MagicMock(return_value=1))
mock_manager = Mock()
iteration_started = Mock()
engine.add_event_handler(Events.ITERATION_STARTED, iteration_started)
iteration_complete = Mock()
engine.add_event_handler(Events.ITERATION_COMPLETED, iteration_complete)
mock_manager.attach_mock(iteration_started, 'iteration_started')
mock_manager.attach_mock(iteration_complete, 'iteration_complete')
engine.run(data, max_epochs=max_epochs)
assert iteration_started.call_count == num_batches * max_epochs
assert iteration_complete.call_count == num_batches * max_epochs
expected_calls = []
for i in range(max_epochs * num_batches):
expected_calls.append(call.iteration_started(engine))
expected_calls.append(call.iteration_complete(engine))
assert mock_manager.mock_calls == expected_calls
def test_create_supervised_trainer():
model = Linear(1, 1)
model.weight.data.zero_()
model.bias.data.zero_()
optimizer = SGD(model.parameters(), 0.1)
trainer = create_supervised_trainer(model, optimizer, mse_loss)
x = torch.FloatTensor([[1.0], [2.0]])
y = torch.FloatTensor([[3.0], [5.0]])
data = [(x, y)]
assert model.weight.data[0, 0].item() == approx(0.0)
assert model.bias.item() == approx(0.0)
state = trainer.run(data)
assert state.output == approx(17.0)
assert model.weight.data[0, 0].item() == approx(1.3)
assert model.bias.item() == approx(0.8)
def test_create_supervised_trainer_with_cpu():
model = Linear(1, 1)
model.weight.data.zero_()
model.bias.data.zero_()
optimizer = SGD(model.parameters(), 0.1)
trainer = create_supervised_trainer(model, optimizer, mse_loss, device='cpu')
x = torch.FloatTensor([[1.0], [2.0]])
y = torch.FloatTensor([[3.0], [5.0]])
data = [(x, y)]
assert model.weight.data[0, 0].item() == approx(0.0)
assert model.bias.item() == approx(0.0)
state = trainer.run(data)
assert state.output == approx(17.0)
assert model.weight.data[0, 0].item() == approx(1.3)
assert model.bias.item() == approx(0.8)
def test_create_supervised_trainer_traced_with_cpu():
model = Linear(1, 1)
model.weight.data.zero_()
model.bias.data.zero_()
class DummyContext(object):
def __enter__(self):
return None
def __exit__(self, exc_type, exc_value, traceback):
return False
example_input = torch.randn(1, 1)
traced_model = torch.jit.trace(model, example_input)
optimizer = SGD(traced_model.parameters(), 0.1)
ctx = DummyContext() if 'dev' in torch.__version__ else pytest.raises(RuntimeError)
with ctx:
trainer = create_supervised_trainer(traced_model, optimizer, mse_loss, device='cpu')
x = torch.FloatTensor([[1.0], [2.0]])
y = torch.FloatTensor([[3.0], [5.0]])
data = [(x, y)]
assert traced_model.weight.data[0, 0].item() == approx(0.0)
assert traced_model.bias.item() == approx(0.0)
state = trainer.run(data)
assert state.output == approx(17.0)
assert traced_model.weight.data[0, 0].item() == approx(1.3)
assert traced_model.bias.item() == approx(0.8)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="Skip if no GPU")
def test_create_supervised_trainer_on_cuda():
model = Linear(1, 1)
model.weight.data.zero_()
model.bias.data.zero_()
optimizer = SGD(model.parameters(), 0.1)
trainer = create_supervised_trainer(model, optimizer, mse_loss, device='cuda')
x = torch.FloatTensor([[1.0], [2.0]])
y = torch.FloatTensor([[3.0], [5.0]])
data = [(x, y)]
assert model.weight.data[0, 0].item() == approx(0.0)
assert model.bias.item() == approx(0.0)
state = trainer.run(data)
assert state.output == approx(17.0)
assert model.weight.data[0, 0].item() == approx(1.3)
assert model.bias.item() == approx(0.8)
def test_create_supervised():
model = Linear(1, 1)
model.weight.data.zero_()
model.bias.data.zero_()
evaluator = create_supervised_evaluator(model)
x = torch.FloatTensor([[1.0], [2.0]])
y = torch.FloatTensor([[3.0], [5.0]])
data = [(x, y)]
state = evaluator.run(data)
y_pred, y = state.output
assert y_pred[0, 0].item() == approx(0.0)
assert y_pred[1, 0].item() == approx(0.0)
assert y[0, 0].item() == approx(3.0)
assert y[1, 0].item() == approx(5.0)
assert model.weight.data[0, 0].item() == approx(0.0)
assert model.bias.item() == approx(0.0)
def test_create_supervised_on_cpu():
model = Linear(1, 1)
model.weight.data.zero_()
model.bias.data.zero_()
evaluator = create_supervised_evaluator(model, device='cpu')
x = torch.FloatTensor([[1.0], [2.0]])
y = torch.FloatTensor([[3.0], [5.0]])
data = [(x, y)]
state = evaluator.run(data)
y_pred, y = state.output
assert y_pred[0, 0].item() == approx(0.0)
assert y_pred[1, 0].item() == approx(0.0)
assert y[0, 0].item() == approx(3.0)
assert y[1, 0].item() == approx(5.0)
assert model.weight.data[0, 0].item() == approx(0.0)
assert model.bias.item() == approx(0.0)
def test_create_supervised_evaluator_traced_on_cpu():
model = Linear(1, 1)
model.weight.data.zero_()
model.bias.data.zero_()
class DummyContext(object):
def __enter__(self):
return None
def __exit__(self, exc_type, exc_value, traceback):
return False
ctx = DummyContext() if 'dev' in torch.__version__ else pytest.raises(RuntimeError)
example_input = torch.randn(1, 1)
traced_model = torch.jit.trace(model, example_input)
with ctx:
evaluator = create_supervised_evaluator(traced_model, device='cpu')
x = torch.FloatTensor([[1.0], [2.0]])
y = torch.FloatTensor([[3.0], [5.0]])
data = [(x, y)]
state = evaluator.run(data)
y_pred, y = state.output
assert y_pred[0, 0].item() == approx(0.0)
assert y_pred[1, 0].item() == approx(0.0)
assert y[0, 0].item() == approx(3.0)
assert y[1, 0].item() == approx(5.0)
assert traced_model.weight.data[0, 0].item() == approx(0.0)
assert traced_model.bias.item() == approx(0.0)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="Skip if no GPU")
def test_create_supervised_on_cuda():
model = Linear(1, 1)
model.weight.data.zero_()
model.bias.data.zero_()
evaluator = create_supervised_evaluator(model, device='cuda')
x = torch.FloatTensor([[1.0], [2.0]])
y = torch.FloatTensor([[3.0], [5.0]])
data = [(x, y)]
state = evaluator.run(data)
y_pred, y = state.output
assert y_pred[0, 0].item() == approx(0.0)
assert y_pred[1, 0].item() == approx(0.0)
assert y[0, 0].item() == approx(3.0)
assert y[1, 0].item() == approx(5.0)
assert model.weight.data[0, 0].item() == approx(0.0)
assert model.bias.item() == approx(0.0)
def test_create_supervised_with_metrics():
model = Linear(1, 1)
model.weight.data.zero_()
model.bias.data.zero_()
evaluator = create_supervised_evaluator(model, metrics={'mse': MeanSquaredError()})
x = torch.FloatTensor([[1.0], [2.0]])
y = torch.FloatTensor([[3.0], [4.0]])
data = [(x, y)]
state = evaluator.run(data)
assert state.metrics['mse'] == 12.5 | 0.862844 | 0.372448 |