max_stars_repo_path stringlengths 3 269 | max_stars_repo_name stringlengths 4 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.05M | score float64 0.23 5.13 | int_score int64 0 5 |
|---|---|---|---|---|---|---|
pynse/pynse.py | nitinkumar4321/pynse | 1 | 12767251 | <filename>pynse/pynse.py
import datetime as dt
import time
import enum
import logging
import urllib.parse
import requests
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
import io
import zipfile
import os
import shutil
import pickle
logger = logging.getLogger(__name__)
class IndexSymbol(enum.Enum):
All = 'ALL'
FnO = 'FNO'
Nifty50 = 'NIFTY 50'
NiftyNext50 = 'NIFTY NEXT 50'
Nifty100 = 'NIFTY 100'
Nifty200 = 'NIFTY 200'
Nifty500 = 'NIFTY 500'
NiftyMidcap50 = 'NIFTY MIDCAP 50'
NiftyMidcap100 = 'NIFTY MIDCAP 100'
NiftySmlcap100 = 'NIFTY SMLCAP 100'
NiftyMidcap150 = 'NIFTY MIDCAP 150'
NiftySmlcap50 = 'NIFTY SMLCAP 50'
NiftySmlcap250 = 'NIFTY SMLCAP 250'
NiftyMidsml400 = 'NIFTY MIDSML 400'
NiftyBank = 'NIFTY BANK'
NiftyAuto = 'NIFTY AUTO'
NiftyFinService = 'NIFTY FIN SERVICE'
NiftyFmcg = 'NIFTY FMCG'
NiftyIt = 'NIFTY IT'
NiftyMedia = 'NIFTY MEDIA'
NiftyMetal = 'NIFTY METAL'
NiftyPharma = 'NIFTY PHARMA'
NiftyPsuBank = 'NIFTY PSU BANK'
NiftyPvtBank = 'NIFTY PVT BANK'
NiftyRealty = 'NIFTY REALTY'
Nifty50Value20 = 'NIFTY50 VALUE 20'
NiftyAlpha50 = 'NIFTY ALPHA 50'
Nifty50EqlWgt = 'NIFTY50 EQL WGT'
Nifty100EqlWgt = 'NIFTY100 EQL WGT'
Nifty100Lowvol30 = 'NIFTY100 LOWVOL30'
Nifty200Qualty30 = 'NIFTY200 QUALTY30'
NiftyCommodities = 'NIFTY COMMODITIES'
NiftyConsumption = 'NIFTY CONSUMPTION'
NiftyEnergy = 'NIFTY ENERGY'
NiftyInfra = 'NIFTY INFRA'
NiftyMnc = 'NIFTY MNC'
NiftyPse = 'NIFTY PSE'
NiftyServSector = 'NIFTY SERV SECTOR'
class OutputType(enum.Enum):
pandas = 'pd'
dict = 'json'
class Format(enum.Enum):
pkl = 'pkl'
csv = 'csv'
class Segment(enum.Enum):
EQ = 'EQ'
FUT = 'FUT'
OPT = 'OPT'
class OptionType(enum.Enum):
CE = 'Call'
PE = 'Put'
class MostActive(enum.Enum):
AllFnO = 'contracts&limit=10'
EQ = ''
Options = 'options'
Futures = 'futures'
Calls = 'calls'
Puts = 'puts'
OI = 'oi'
class Nse:
"""
pynse is a library to extract realtime and historical data from NSE website
Examples
--------
>>> from pynse import *
>>> nse = Nse()
>>> nse.market_status()
"""
def __init__(self, path:str='data'):
self.expiry_list = list()
self.strike_list = list()
self.max_retries = 5
self.timeout = 10
self.__urls, self.__wrls = dict(), list()
self.data_root = {'data_root': path}
self.data_root.update({d: f'{self.data_root["data_root"]}/{d}/' for d in
['bhavcopy_eq', 'bhavcopy_fno', 'option_chain', 'symbol_list', 'pre_open', 'hist',
'fii_dii', 'config', 'eq_stock_watch', 'daily_delivery', 'insider_trading',
'corp_info', 'screen_shots']})
self.__symbol_files = {i.name: f"{self.data_root['symbol_list']}{i.name}.pkl" for i in IndexSymbol}
self.__zero_files = {i.name: f"{f'{os.path.split(__file__)[0]}/symbol_list/'}{i.name}.pkl" for i in IndexSymbol}
self.__startup()
self.__headers = self.__desc(new=False)
self.symbols = {i.name: self.__read_object(self.__symbol_files[i.name], Format.pkl) for i in IndexSymbol}
def __get_resp(self, url, retries=0, timeout=0):
retries = self.max_retries if retries == 0 else retries
timeout = self.timeout if timeout == 0 else timeout
self.__headers.update({'Referer': np.random.choice(self.__wrls)})
for nrt in range(retries):
try:
time.sleep(5)
# response = requests.get(url, headers=self.__headers, timeout=timeout)
# Fix for new NSE session issue
session = requests.Session()
response = session.get("http://nseindia.com", headers=self.__headers)
response = session.get(url, headers=self.__headers, timeout=timeout)
except Exception as e:
logger.error(e)
if nrt + 1 == retries:
try:
if requests.get(url='https://www.google.com/', headers=self.__headers,
timeout=timeout).status_code == 200:
logging.error('Try slowing down\n'
'or try after sometime')
except:
logging.error('cannot connect to internet')
raise ConnectionError()
self.__desc()
logger.debug('retrying')
time.sleep(10)
else:
return response
def __desc(self, new=True):
from fake_headers import Headers
hfile = f'{self.data_root["config"]}hf'
if new or not os.path.exists(hfile):
h = Headers(headers=True).generate()
with open(hfile, 'wb') as f:
pickle.dump(h, f)
else:
with open(hfile, 'rb') as f:
h = pickle.load(f)
return h
def __startup(self):
for _, path in self.data_root.items():
if path != '':
if not os.path.exists(path):
os.mkdir(path)
if not os.path.exists(self.__symbol_files['All']):
logger.debug('First run.\nCreating folders and symbol files')
for i in IndexSymbol:
if not os.path.exists(self.__symbol_files[i.name]):
try:
shutil.copyfile(self.__zero_files[i.name], self.__symbol_files[i.name])
except Exception as e:
logger.error(e)
self.__urls, self.__wrls = self.__read_object(f'{os.path.split(__file__)[0]}/symbol_list/config', Format.pkl)
@staticmethod
def __read_object(filename, format):
if format == Format.pkl:
with open(filename, 'rb')as f:
obj = pickle.load(f)
return obj
elif format == Format.csv:
with open(filename, 'r')as f:
obj = f.read()
return obj
else:
raise FileNotFoundError(f'{filename} not found')
@staticmethod
def __save_object(obj, filename, format):
if format == Format.pkl:
with open(filename, 'wb')as f:
pickle.dump(obj, f)
elif format == Format.csv:
with open(filename, 'w')as f:
f.write(obj)
logger.debug(f'saved {filename}')
@staticmethod
def __validate_symbol(symbol, _list):
symbol = symbol if isinstance(symbol, IndexSymbol) else symbol.upper()
if isinstance(symbol, IndexSymbol):
symbol = urllib.parse.quote(symbol.value)
return symbol
elif symbol in _list:
symbol = urllib.parse.quote(symbol.upper())
return symbol
else:
symbol = None
raise ValueError('not a vaild symbol')
def market_status(self) -> dict:
"""
get market status
Examples
--------
>>> nse.market_status()
"""
config = self.__urls
logger.info("downloading market status")
url = config['host'] + config['path']['marketStatus']
return self.__get_resp(url=url).json()
def info(self, symbol: str = 'SBIN') -> dict:
'''
Get symbol information from nse
Examples
--------
>>> nse.info('SBIN')
'''
config = self.__urls
symbol = self.__validate_symbol(symbol, self.symbols[IndexSymbol.All.name])
if symbol is not None:
logger.info(f"downloading symbol info for {symbol}")
url = config['host'] + config['path']['info'].format(symbol=symbol)
return self.__get_resp(url=url).json()
def get_quote(self,
symbol: str = 'HDFC',
segment: Segment = Segment.EQ,
expiry: dt.date = None,
optionType: OptionType = OptionType.CE,
strike: str = '-') -> dict:
"""
Get realtime quote for EQ, FUT and OPT
if no expiry date is provided for derivatives, returns date for nearest expiry
Examples
--------
for cash
>>> nse.get_quote('RELIANCE')
for futures
>>> nse.get_quote('TCS', segment=Segment.FUT, expiry=dt.date( 2020, 6, 30 ))
for options
>>> nse.get_quote('HDFC', segment=Segment.OPT, optionType=OptionType.PE)
"""
config = self.__urls
segment = segment.value
optionType = optionType.value
if symbol is not None:
logger.info(f"downloading quote for {symbol} {segment}")
quote = {}
if segment == 'EQ':
symbol = self.__validate_symbol(symbol,
self.symbols[IndexSymbol.All.name] + [idx.value for idx in IndexSymbol])
url = config['host'] + config['path']['quote_eq'].format(symbol=symbol)
url1 = config['host'] + config['path']['trade_info'].format(symbol=symbol)
data = self.__get_resp(url).json()
data.update(self.__get_resp(url1).json())
quote = data['priceInfo']
quote['timestamp'] = dt.datetime.strptime(data['metadata']['lastUpdateTime'], '%d-%b-%Y %H:%M:%S')
quote.update(series=data['metadata']['series'])
quote.update(symbol=data['metadata']['symbol'])
quote.update(data['securityWiseDP'])
quote['low'] = quote['intraDayHighLow']['min']
quote['high'] = quote['intraDayHighLow']['max']
elif segment == 'FUT':
symbol = self.__validate_symbol(symbol,
self.symbols[IndexSymbol.FnO.name] + ['NIFTY', 'BANKNIFTY'])
url = config['host'] + config['path']['quote_derivative'].format(symbol=symbol)
data = self.__get_resp(url).json()
quote['timestamp'] = dt.datetime.strptime(data['fut_timestamp'], '%d-%b-%Y %H:%M:%S')
data = [
i for i in data['stocks']
if segment.lower() in i['metadata']['instrumentType'].lower()
]
expiry_list = list(
dict.fromkeys([dt.datetime.strptime(i['metadata']['expiryDate'], '%d-%b-%Y').date() for i in data]))
if expiry is None:
expiry = expiry_list[0]
data = [i for i in data if
dt.datetime.strptime(i['metadata']['expiryDate'], '%d-%b-%Y').date() == expiry]
quote.update(data[0]['marketDeptOrderBook']['tradeInfo'])
quote.update(data[0]['metadata'])
quote['expiryDate'] = dt.datetime.strptime(quote['expiryDate'], '%d-%b-%Y').date()
elif segment == 'OPT':
url = config['host'] + config['path']['quote_derivative'].format(symbol=symbol)
data = self.__get_resp(url).json()
quote['timestamp'] = dt.datetime.strptime(data['opt_timestamp'], '%d-%b-%Y %H:%M:%S')
data = [
i for i in data['stocks']
if segment.lower() in i['metadata']['instrumentType'].lower()
and i['metadata']['optionType'] == optionType
]
self.strike_list = list(dict.fromkeys(
[i['metadata']['strikePrice'] for i in data]))
strike = strike if strike in self.strike_list else self.strike_list[0]
self.expiry_list = list(
dict.fromkeys([dt.datetime.strptime(i['metadata']['expiryDate'], '%d-%b-%Y').date() for i in data]))
if expiry is None:
expiry = self.expiry_list[0]
data = [i for i in data if
dt.datetime.strptime(i['metadata']['expiryDate'], '%d-%b-%Y').date() == expiry and
i['metadata']['strikePrice'] == strike]
quote.update(data[0]['marketDeptOrderBook']['tradeInfo'])
quote.update(data[0]['marketDeptOrderBook']['otherInfo'])
quote.update(data[0]['metadata'])
quote['expiryDate'] = dt.datetime.strptime(quote['expiryDate'], '%d-%b-%Y').date()
return quote
def bhavcopy(self, req_date: dt.date = None,
series: str = 'eq') -> pd.DataFrame:
"""
download bhavcopy from nse
or
read bhavcopy if already downloaded
Examples
--------
>>> nse.bhavcopy()
>>> nse.bhavcopy(dt.date(2020,6,17))
"""
series = series.upper()
req_date = self.__trading_days()[-1].date() if req_date is None else req_date
filename = f'{self.data_root["bhavcopy_eq"]}bhav_{req_date}.pkl'
bhavcopy = None
if os.path.exists(filename):
bhavcopy = pd.read_pickle(filename)
logger.debug(f'read {filename} from disk')
else:
config = self.__urls
url = config['path']['bhavcopy'].format(date=req_date.strftime("%d%m%Y"))
csv = self.__get_resp(url).content.decode('utf8').replace(" ", "")
bhavcopy = pd.read_csv(io.StringIO(csv))
bhavcopy["DATE1"] = bhavcopy["DATE1"].apply(lambda x: dt.datetime.strptime(x, '%d-%b-%Y').date())
bhavcopy.to_pickle(filename)
if bhavcopy is not None:
if series != 'ALL':
bhavcopy = bhavcopy.loc[bhavcopy['SERIES'] == series]
bhavcopy.set_index(['SYMBOL', 'SERIES'], inplace=True)
return bhavcopy
def bhavcopy_fno(self, req_date: dt.date = None) -> pd.DataFrame:
"""
download bhavcopy from nse
or
read bhavcopy if already downloaded
Examples
--------
>>> nse.bhavcopy_fno()
>>> nse.bhavcopy_fno(dt.date(2020,6,17))
"""
req_date = self.__trading_days()[-1].date() if req_date is None else req_date
filename = f'{self.data_root["bhavcopy_fno"]}bhav_{req_date}.pkl'
bhavcopy = None
if os.path.exists(filename):
bhavcopy = pd.read_pickle(filename)
logger.debug(f'read {filename} from disk')
else:
config = self.__urls
url = config['path']['bhavcopy_derivatives'].format(date=req_date.strftime("%d%b%Y").upper(),
month=req_date.strftime("%b").upper(),
year=req_date.strftime("%Y"))
logger.debug("downloading bhavcopy for {}".format(req_date))
stream = self.__get_resp(
url).content
filebytes = io.BytesIO(stream)
zf = zipfile.ZipFile(filebytes)
bhavcopy = pd.read_csv(zf.open(zf.namelist()[0]))
bhavcopy.set_index('SYMBOL', inplace=True)
bhavcopy.dropna(axis=1, inplace=True)
bhavcopy.EXPIRY_DT = bhavcopy.EXPIRY_DT.apply(lambda x: dt.datetime.strptime(x, '%d-%b-%Y'))
bhavcopy.to_pickle(filename)
return bhavcopy
def pre_open(self) -> pd.DataFrame:
"""
get pre open data from nse
Examples
--------
>>> nse.pre_open()
"""
filename = f"{self.data_root['pre_open']}{dt.date.today()}.pkl"
if os.path.exists(filename):
pre_open_data = pd.read_pickle(filename)
logging.debug('pre_open data read from file')
else:
logger.debug("downloading preopen data")
config = self.__urls
url = config['host'] + config['path']['preOpen']
data = self.__get_resp(url).json()
timestamp = dt.datetime.strptime(data['timestamp'], "%d-%b-%Y %H:%M:%S").date()
pre_open_data = pd.json_normalize(data['data'])
pre_open_data = pre_open_data.set_index('metadata.symbol')
pre_open_data["detail.preOpenMarket.lastUpdateTime"] = pre_open_data[
"detail.preOpenMarket.lastUpdateTime"].apply(
lambda x: dt.datetime.strptime(x, '%d-%b-%Y %H:%M:%S'))
filename = f"{self.data_root['pre_open']}{timestamp}.pkl"
pre_open_data.to_pickle(filename)
return pre_open_data
def __option_chain_download(self, symbol):
symbol = self.__validate_symbol(symbol, self.symbols[IndexSymbol.FnO.name] + ['NIFTY', 'BANKNIFTY', 'NIFTYIT'])
logger.debug('download option chain')
config = self.__urls
url = config['host'] + (config['path']['option_chain_index'] if 'NIFTY' in symbol else config['path'][
'option_cahin_equities']).format(symbol=symbol)
data = self.__get_resp(url).json()
return data
def option_chain(self, symbol: str = 'NIFTY', req_date: dt.date = None) -> dict:
"""
downloads the option chain
or
reads if already downloaded
if no req_date is specified latest available option chain from nse website
:returns dictonaly containing
timestamp as str
option chain as pd.Dataframe
expiry_list as list
Examples
--------
>>> nse.option_chain('INFY')
>>> nse.option_chain('INFY',expiry=dt.date(2020,6,30))
"""
dir = f"{self.data_root['option_chain']}{symbol}/"
if not os.path.exists(dir):
os.mkdir(dir)
download_req = True
filename = f"{dir}{dt.date.today()}_eod.pkl"
if os.path.exists(filename):
download_req = False
elif req_date is None:
q = self.get_quote(np.random.choice(self.symbols['FnO']))
logger.debug('got timestamp')
timestamp = q['timestamp'] if q is not None else None
if timestamp.date() == dt.date.today() and timestamp.time() <= dt.time(15, 30):
filename = f"{dir}{dt.date.today()}_{dt.datetime.now().strftime('%H%M%S')}.pkl"
download_req = True
elif timestamp.date() == dt.date.today():
filename = f"{dir}{dt.date.today()}_eod.pkl"
download_req = False if os.path.exists(filename) else True
else:
prev_trading_day = self.__trading_days()[-1].date()
filename = f"{dir}{prev_trading_day}_eod.pkl"
download_req = False if os.path.exists(filename) else True
else:
if req_date == dt.date.today():
q = self.get_quote()
timestamp = dt.datetime.strptime(self.get_quote()['timestamp'],
"%d-%b-%Y %H:%M:%S") if q is not None else None
if timestamp.date() == dt.date.today() and timestamp.time() <= dt.time(15, 30):
filename = f"{dir}{req_date}_{dt.datetime.now().strftime('%H%M%S')}.pkl"
download_req = True
else:
filename = filename = f"{dir}{req_date}_eod.pkl"
download_req = False if os.path.exists(filename) else True
else:
prev_trading_day = self.__trading_days()[-1]
if req_date >= prev_trading_day:
filename = filename = f"{dir}{prev_trading_day}_eod.pkl"
download_req = False if os.path.exists(filename) else True
else:
filename = filename = f"{dir}{req_date}_eod.pkl"
download_req = False
if download_req:
data = self.__option_chain_download(symbol)
self.__save_object(data, filename, Format.pkl)
data = self.__read_object(filename, Format.pkl)
expiry_list = data['records']['expiryDates']
option_chain = pd.json_normalize(data['records']['data'])
timestamp = data['records']['timestamp']
return {'timestamp': timestamp, 'data': option_chain, 'expiry_list': expiry_list}
def fii_dii(self) -> pd.DataFrame:
"""
get FII and DII data from nse
Examples
--------
>>> nse.fii_dii()
"""
filename = f'{self.data_root["fii_dii"]}fii_dii.csv'
if not os.path.exists(filename):
mode = 'w'
timestamp = dt.date.today() - dt.timedelta(days=2)
else:
mode = 'a'
csv_file = pd.read_csv(filename, header=[0, 1], index_col=[0])
timestamp = dt.datetime.strptime(csv_file.tail(1).index[0], '%d-%b-%Y').date()
if timestamp == dt.date.today() or timestamp == dt.date.today() - dt.timedelta(
days=1) and dt.datetime.now().time() < dt.time(15, 30):
logger.debug('read fii/dii data from disk')
return csv_file.tail(1)
else:
config = self.__urls
url = config['host'] + config['path']['fii_dii']
resp = self.__get_resp(url).json()
resp[0].pop('date')
date = resp[1].pop('date')
fii = [d for d in resp if d['category'] == 'FII/FPI *'][0]
dii = [d for d in resp if d['category'] == 'DII **'][0]
fii_dii = pd.concat(
[pd.json_normalize(fii),
pd.json_normalize(dii)],
axis=1,
keys=[fii['category'], dii['category']])
fii_dii.index = [date]
if dt.datetime.strptime(date, '%d-%b-%Y').date() != timestamp:
fii_dii.to_csv(filename, mode=mode, header=True if mode == 'w' else False)
return fii_dii.tail(1)
def __get_hist(self, symbol='SBIN', from_date=None, to_date=None):
config = self.__urls
max_date_range = 480
if from_date == None:
from_date = dt.date.today() - dt.timedelta(days=30)
if to_date == None:
to_date = dt.date.today()
hist = pd.DataFrame()
while True:
if (to_date - from_date).days > max_date_range:
marker = from_date + dt.timedelta(max_date_range)
url = config['host'] + config['path']['hist'].format(symbol=symbol,
from_date=from_date.strftime('%d-%m-%Y'),
to_date=marker.strftime('%d-%m-%Y'))
from_date = from_date + dt.timedelta(days=(max_date_range + 1))
csv = self.__get_resp(url).content.decode('utf8').replace(" ", "")
is_complete = False
else:
url = config['host'] + config['path']['hist'].format(symbol=symbol,
from_date=from_date.strftime('%d-%m-%Y'),
to_date=to_date.strftime('%d-%m-%Y'))
from_date = from_date + dt.timedelta(max_date_range + 1)
csv = self.__get_resp(url).content.decode('utf8').replace(" ", "")
is_complete = True
hist = pd.concat([hist, pd.read_csv(io.StringIO(csv))[::-1]])
if is_complete:
break
time.sleep(1)
hist['Date'] = pd.to_datetime(hist['Date'])
hist.set_index('Date', inplace=True)
hist.drop(['series', 'PREV.CLOSE', 'ltp', 'vwap', '52WH', '52WL', 'VALUE', 'Nooftrades'], axis=1, inplace=True)
try:
hist.columns = ['Open', 'High', 'Low', 'Close', 'Volume']
except Exception as e:
print(hist.columns, e)
time.sleep(5)
for column in hist.columns[:4]:
hist[column] = hist[column].astype(str).str.replace(',', '').replace('-', '0').astype(float)
hist['Volume'] = hist['Volume'].astype(int)
return hist
def __get_hist_index(self, symbol='NIFTY 50', from_date=None,
to_date=None):
if from_date == None:
from_date = dt.date.today() - dt.timedelta(days=30)
if to_date == None:
to_date = dt.date.today()
config = self.__urls
base_url = config['path']['indices_hist_base']
urls = []
max_range_len = 100
while True:
if (to_date - from_date).days > max_range_len:
s = from_date
e = s + dt.timedelta(max_range_len)
url = f"{base_url}{symbol}&fromDate={s.strftime('%d-%m-%Y')}&toDate={e.strftime('%d-%m-%Y')}"
urls.append(url)
from_date = from_date + dt.timedelta(max_range_len + 1)
else:
url = f"{base_url}{symbol}&fromDate={from_date.strftime('%d-%m-%Y')}&toDate={to_date.strftime('%d-%m-%Y')}"
urls.append(url)
break
hist = pd.DataFrame(columns=[
'Date', 'Open', 'High', 'Low', 'Close', 'SharesTraded',
'Turnover(Cr)'
])
for url in urls:
page = self.__get_resp(url).content.decode('utf-8')
raw_table = BeautifulSoup(page, 'lxml').find_all('table')[0]
rows = raw_table.find_all('tr')
for row_no, row in enumerate(rows):
if row_no > 2:
_row = [
cell.get_text().replace(" ", "").replace(",", "")
for cell in row.find_all('td')
]
if len(_row) > 4:
hist.loc[len(hist)] = _row
time.sleep(1)
hist.Date = hist.Date.apply(lambda d: dt.datetime.strptime(d, '%d-%b-%Y'))
hist.set_index("Date", inplace=True)
for col in hist.columns:
hist[col] = hist[col].astype(str).replace(',', '').replace('-', '0').astype(float)
return hist
def get_hist(self, symbol: str = 'SBIN', from_date: dt.date = None, to_date: dt.date = None) -> pd.DataFrame:
"""
get historical data from nse
symbol index or symbol
Examples
--------
>>> nse.get_hist('SBIN')
>>> nse.get_hist('NIFTY 50', from_date=dt.date(2020,1,1),to_date=dt.date(2020,6,26))
"""
symbol = self.__validate_symbol(symbol,
self.symbols[IndexSymbol.All.name] + [idx.value for idx in IndexSymbol])
if "NIFTY" in symbol:
return self.__get_hist_index(symbol, from_date, to_date)
else:
return self.__get_hist(symbol, from_date, to_date)
def get_indices(self, index: IndexSymbol = None) -> pd.DataFrame:
"""
get realtime index value
Examples
--------
>>> nse.get_indices(IndexSymbol.NiftyInfra)
>>> nse.get_indices(IndexSymbol.Nifty50))
"""
if index is not None:
self.__validate_symbol(index, [idx for idx in IndexSymbol])
config = self.__urls
url = config['host'] + config['path']['indices']
data = self.__get_resp(url).json()['data']
data = pd.json_normalize(data).set_index('indexSymbol')
if index is not None:
data = data[data.index == index.value]
data.drop(['chart365dPath', 'chartTodayPath', 'chart30dPath'], inplace=True, axis=1)
return data
def __gainers_losers(self, index, advance=False):
index = self.__validate_symbol(index.value, [idx.value for idx in IndexSymbol if idx.value != 'ALL'])
index = 'SECURITIES%20IN%20F%26O' if index == 'FNO' else index
config = self.__urls
url = config['host'] + config['path']['gainer_loser'].format(index=index)
data = self.__get_resp(url).json()
if advance:
return data["advance"]
table = pd.DataFrame(data['data'])
table.drop([
'chart30dPath', 'chart365dPath', 'chartTodayPath', 'meta',
'identifier'
],
axis=1,
inplace=True)
table.set_index('symbol', inplace=True)
return table
def __symbol_list(self, index: IndexSymbol):
"""
:param index: index name or fno
:return: list ig symbols for selected group
"""
if not isinstance(index, IndexSymbol):
raise TypeError('index is not of type "Index"')
config = self.__urls
if index == IndexSymbol.All:
data = list(self.bhavcopy().reset_index().SYMBOL)
elif index == IndexSymbol.FnO:
url = config['host'] + config['path']['fnoSymbols']
data = self.__get_resp(url).json()
data.extend(['NIFTY', 'BANKNIFTY'])
else:
url = config['host'] + config['path']['symbol_list'].format(
index=self.__validate_symbol(index, IndexSymbol))
data = self.__get_resp(url).json()['data']
data = [i['meta']['symbol'] for i in data if i['identifier'] != index.value]
data.sort()
with open(self.data_root['symbol_list'] + index.name + '.pkl', 'wb')as f:
pickle.dump(data, f)
logger.info(f'symbol list saved for {index}')
return data
def update_symbol_list(self):
"""
Update list of symbols
no need to run frequently
required when constituent of an index is changed
or
list of securities in fno are updates
:return: None
Examples:
```
nse.update_symbol_list()
```
"""
for i in [a for a in IndexSymbol]:
self.__symbol_list(i)
time.sleep(1)
def __trading_days(self):
filename = f'{self.data_root["data_root"]}/trading_days.csv'
if os.path.exists(filename):
trading_days = pd.read_csv(filename, header=None)
trading_days.columns = ['Date']
trading_days['Date'] = trading_days['Date'].apply(lambda x: dt.datetime.strptime(x, '%Y-%m-%d'))
previous_trading_day = list(trading_days.tail(1)['Date'])[0].date()
else:
previous_trading_day = dt.date.today() - dt.timedelta(days=100)
trading_days = pd.DataFrame()
if previous_trading_day == dt.date.today() or previous_trading_day == dt.date.today() - dt.timedelta(
days=1) and dt.datetime.now().time() <= dt.time(18, 45):
pass
else:
_trading_days = self.get_hist(symbol='SBIN', from_date=previous_trading_day - dt.timedelta(7),
to_date=dt.date.today()).reset_index()[['Date']]
trading_days = pd.concat([trading_days, _trading_days]).drop_duplicates()
trading_days.to_csv(filename, mode='w', index=False, header=False)
trading_days = pd.read_csv(filename, header=None, index_col=0)
trading_days.index = trading_days.index.map(lambda x: dt.datetime.strptime(x, "%Y-%m-%d"))
return trading_days.index
def top_gainers(self, index: IndexSymbol = IndexSymbol.FnO, length: int = 10) -> pd.DataFrame:
"""
get top gainers in given index
Examples
--------
>>> nse.top_gainers(IndexSymbol.FnO,length=10)
"""
gainers = self.__gainers_losers(index).sort_values(by=['pChange'],
axis=0,
ascending=False).head(length)
gainers = gainers[gainers.pChange > 0.]
return gainers
def top_losers(self, index: IndexSymbol = IndexSymbol.FnO, length: int = 10) -> pd.DataFrame:
"""
get lop losers in given index
Examples
--------
>>> nse.top_gainers(IndexSymbol.FnO,length=10)
"""
losers = self.__gainers_losers(index).sort_values(by=['pChange'],
axis=0,
ascending=True).head(length)
losers = losers[losers.pChange < 0.]
return losers
def eq_stock_watch(self) -> pd.DataFrame:
"""
download Equity Stock Watch from nse
or
read eq_stock_watch if already downloaded
Examples
--------
>>> nse.eq_stock_watch()
"""
req_date = self.__trading_days()[-1].date()
filename = f'{self.data_root["eq_stock_watch"]}eq_stock_watch_{req_date}.pkl'
eq_stock_watch = None
if os.path.exists(filename):
eq_stock_watch = pd.read_pickle(filename)
logger.debug(f'read {filename} from disk')
else:
config = self.__urls
url = config['host'] + config['path']['equity_stock_watch']
csv = self.__get_resp(url).content.decode('utf8').replace(" ", "")
eq_stock_watch = pd.read_csv(io.StringIO(csv))
eq_stock_watch.columns = list(map((lambda x: x.replace('\n',' ').strip()), eq_stock_watch.columns))
logger.debug("downloading eq_stock_watch for {}".format(req_date))
eq_stock_watch.set_index('SYMBOL', inplace=True)
eq_stock_watch.dropna(axis=1, inplace=True)
eq_stock_watch.to_pickle(filename)
return eq_stock_watch
def daily_delivery(self, req_date: dt.date = None) -> pd.DataFrame:
"""
download Daily delivery from nse
or
read daily_delivery if already downloaded
Examples
--------
>>> nse.daily_delivery()
>>> nse.daily_delivery(dt.date(2020,7,20))
"""
req_date = self.__trading_days()[-1].date() if req_date is None else req_date
filename = f'{self.data_root["daily_delivery"]}daily_delivery_{req_date}.pkl'
daily_delivery = None
if os.path.exists(filename):
daily_delivery = pd.read_pickle(filename)
logger.debug(f'read {filename} from disk')
else:
config = self.__urls
url = config['path']['daily_delivery'].format(date=req_date.strftime("%d%m%Y").upper())
csv = self.__get_resp(url).content.decode('utf8').replace(" ", "")
daily_delivery = pd.read_csv(io.StringIO(csv), skiprows=3, index_col=False)
daily_delivery.columns = list(map((lambda x: x.strip()), daily_delivery.columns))
daily_delivery.rename(columns={'NameofSecurity':'SYMBOL'}, inplace=True)
logger.debug("downloading daily_delivery for {}".format(req_date))
daily_delivery.set_index('SYMBOL', inplace=True)
daily_delivery.dropna(axis=1, inplace=True)
daily_delivery.to_pickle(filename)
return daily_delivery
def insider_trading(self, from_date=None, to_date=None) -> pd.DataFrame:
"""
download Insider trading from nse
or
read insider_trading if already downloaded
Examples
--------
>>> nse.insider_trading()
>>> nse.insider_trading(to_date=dt.date(2020, 8, 3)
"""
config = self.__urls
if from_date == None:
from_date = dt.date.today() - dt.timedelta(days=100)
if to_date == None:
to_date = dt.date.today()
filename = f'{self.data_root["insider_trading"]}insider_trading_{from_date}_to_{to_date}.pkl'
insider_trading = None
if os.path.exists(filename):
insider_trading = pd.read_pickle(filename)
logger.debug(f'read {filename} from disk')
else:
insider_trading = pd.DataFrame()
url = config['host'] + config['path']['insider_trading'].format(from_date=from_date.strftime('%d-%m-%Y'),
to_date=to_date.strftime('%d-%m-%Y'))
data = self.__get_resp(url).json()
insider_trading = pd.DataFrame(data['data'])
insider_trading.drop(['xbrl', 'tkdAcqm', 'anex', 'derivativeType', 'remarks'], axis=1, inplace=True)
insider_trading.to_pickle(filename)
return insider_trading
def corp_info(self, symbol: str = 'SBIN', month=None, use_pickle=True):
"""
download Corporation Info from nse
or
read corp_info if already downloaded
Examples
--------
>>> nse.corp_info()
>>> nse.corp_info(symbol='SBIN', month=dt.date.today().strftime('%B'))
>>> nse.corp_info(symbol='SBIN', use_pickle=False) #Use on prod
"""
config = self.__urls
corp_info = {}
if month == None:
month = dt.date.today().strftime('%B')
if symbol is not None:
filename = f'{self.data_root["corp_info"]}corp_info_{symbol}_{month}.pkl'
if use_pickle and os.path.exists(filename):
with open(filename, 'rb') as pk:
corp_info = pickle.load(pk)
logger.debug(f'read {filename} from disk')
else:
logger.info(f"downloading corp data for {symbol}")
symbol = self.__validate_symbol(symbol,
self.symbols[IndexSymbol.All.name] + [idx.value for idx in IndexSymbol])
url = config['host'] + config['path']['corp_info'].format(symbol=symbol)
data = self.__get_resp(url).json()
corp_info['share_holding_patterns'] = pd.DataFrame(data['corporate']['shareholdingPatterns']['data'])
corp_info['financial_results'] = pd.DataFrame(data['corporate']['financialResults'])
corp_info['pledge_details'] = pd.DataFrame(data['corporate']['pledgedetails'])
corp_info['sast_Regulations_29'] = pd.DataFrame(data['corporate']['sastRegulations_29'])
if use_pickle:
with open(filename, 'wb') as pk:
pickle.dump(corp_info, pk, protocol=pickle.HIGHEST_PROTOCOL)
return corp_info
| 2.5 | 2 |
experiments/vneTest.py | sri-sensors/prosthnet | 0 | 12767252 | import vne
from vne.constants import nfeat, nsensors
from vne.model import simpleModel, init_weights_simple
from vne.persist import save_model, load_model
import numpy as np
import torch
import os
def encode_save(sig=np.random.random([1, nfeat, nsensors]), name='simpleModel_ini', dir_path="../src/vne/models"):
"""
This function will create a model, test it, then save a persistent version (a file)
Parameters
__________
sig:
a numpy array with shape (nsamples, nfeatures, nsensors). in general a single neural signal may contain multiple channels.
the multi-channel nature of the neural activations is a feature of the vne.
typically shaped with size (1,1,S) where S is number os sensors
the vne will map all the different channels to a single scalar encoded signal.
name:
string with the filename to save the model under
dir:
dir_path, the local directory to save the model
Returns
--------
model:
A copy of the encoder model generated by the function
"""
model = simpleModel().eval()
model.apply(init_weights_simple)
sig = torch.tensor(sig.astype(np.float32)).to('cpu')
enc = model(sig)
print("signal={}".format(sig))
print("encoded={}".format(enc))
# save the model
model.apply(vne.init_weights_simple)
save_model(encoder=model, name=name, dir_path=dir_path)
return model
def encode_load(sig=np.random.random([1, nfeat, nsensors]), name="simpleModel_ini", dir_path="../src/vne/models"):
"""
This function will load a saved model, test it, then save a persistent version (a file)
Parameters
----------
sig:
a numpy array with shape (nsamples, nfeatures, nsensors). in general a single neural signal may contain multiple channels.
the multi-channel nature of the neural activations is a feature of the vne.
typically shaped with size (1,1,S) where S is number os sensors
the vne will map all the different channels to a single scalar encoded signal.
name:
the filename of the saved model
dir_path:
the directory path to the folder containing the file with the saved model
"""
# load the saved model
model = load_model(name, dir_path)
# do some stuff
# save the model
model.apply(vne.init_weights_simple)
return model
# Function to Convert to ONNX
def Convert_ONNX(model=None, name="simpleModel_ini", dir_path="../src/vne/models"):
if model is None:
model = encode_load()
# set the model to inference mode (making sure)
model.eval()
name = os.path.join(dir_path, name)
# Let's create a dummy input tensor
dummy_input = torch.randn(1, nfeat, nsensors, requires_grad=True)
# Export the model
torch.onnx.export(model, # model being run
dummy_input, # model input (or a tuple for multiple inputs)
name + ".onnx", # where to save the model
export_params=True, # store the trained parameter weights inside the model file
opset_version=9, # the ONNX version to export the model to
do_constant_folding=True, # whether to execute constant folding for optimization
input_names=['sensorData'], # the model's input names
output_names=['modelOutput'], # the model's output names
dynamic_axes={'modelInput': {0: 'batch_size'}, # variable length axes
'modelOutput': {0: 'batch_size'}})
print(" ")
print('Model has been converted to ONNX')
if __name__ == '__main__':
# load persistent model from file
model_name = 'simpleModel_ini-Trivial19'
model = encode_save(name=model_name)
print("saved model")
# use the model
sig = np.random.random([1, nfeat, nsensors])
sig = torch.tensor(sig.astype(np.float32)).to('cpu')
enc = model(sig)
print("signal={}".format(sig))
print("encoded={}".format(enc))
print("ran model")
Convert_ONNX(model, name=model_name)
| 3.125 | 3 |
finetune_vs_scratch/experiments.py | finiteautomata/finetune_vs_scratch | 12 | 12767253 | <reponame>finiteautomata/finetune_vs_scratch
import os
import torch
import tempfile
from pysentimiento.metrics import compute_metrics
from transformers import Trainer, TrainingArguments, DataCollatorWithPadding
class MultiLabelTrainer(Trainer):
"""
Multilabel and class weighted trainer
"""
def __init__(self, class_weight, *args, **kwargs):
super().__init__(*args, **kwargs)
self.class_weight = class_weight
def compute_loss(self, model, inputs, return_outputs=False):
labels = inputs.pop("labels")
outputs = model(**inputs)
logits = outputs.logits
loss_fct = torch.nn.CrossEntropyLoss(weight=self.class_weight)
num_labels = self.model.config.num_labels
loss = loss_fct(logits, labels)
return (loss, outputs) if return_outputs else loss
def run_experiment(model, tokenizer, train_dataset, dev_dataset, test_dataset, id2label,
epochs=5, batch_size=32, accumulation_steps=1, format_dataset=None, eval_batch_size=16, use_dynamic_padding=True, class_weight=None, group_by_length=True,
**kwargs):
"""
Run experiments experiments
"""
padding = False if use_dynamic_padding else 'max_length'
def tokenize(batch):
return tokenizer(batch['text'], padding=padding, truncation=True)
device = "cuda" if torch.cuda.is_available() else "cpu"
train_dataset = train_dataset.map(tokenize, batched=True, batch_size=batch_size)
dev_dataset = dev_dataset.map(tokenize, batched=True, batch_size=eval_batch_size)
test_dataset = test_dataset.map(tokenize, batched=True, batch_size=eval_batch_size)
data_collator = None
if use_dynamic_padding:
data_collator = DataCollatorWithPadding(tokenizer, padding="longest")
else:
if not format_dataset:
raise ValueError("Must provide format_dataset if not using dynamic padding")
train_dataset = format_dataset(train_dataset)
dev_dataset = format_dataset(dev_dataset)
test_dataset = format_dataset(test_dataset)
output_path = tempfile.mkdtemp()
training_args = TrainingArguments(
output_dir=output_path,
num_train_epochs=epochs,
per_device_train_batch_size=batch_size,
per_device_eval_batch_size=eval_batch_size,
gradient_accumulation_steps=accumulation_steps,
warmup_ratio=0.1,
evaluation_strategy="epoch",
save_strategy="epoch",
do_eval=False,
weight_decay=0.01,
logging_dir='./logs',
load_best_model_at_end=True,
metric_for_best_model="macro_f1",
group_by_length=group_by_length,
**kwargs,
)
if class_weight is not None:
class_weight = class_weight.to(device)
trainer = MultiLabelTrainer(
class_weight=class_weight,
model=model,
args=training_args,
compute_metrics=lambda x: compute_metrics(x, id2label=id2label),
train_dataset=train_dataset,
eval_dataset=dev_dataset,
data_collator=data_collator,
)
else:
trainer = Trainer(
model=model,
args=training_args,
compute_metrics=lambda x: compute_metrics(x, id2label=id2label),
train_dataset=train_dataset,
eval_dataset=dev_dataset,
data_collator=data_collator,
)
trainer.train()
test_results = trainer.evaluate(test_dataset)
os.system(f"rm -Rf {output_path}")
return test_results
| 2.3125 | 2 |
inference.py | jmendozais/SDSSDepth | 0 | 12767254 | import os
import argparse
import configargparse
import time
import glob
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision.transforms import functional as VF
from torch.nn import functional as F
import cv2
import model
import data
from eval.kitti_depth_eval_utils import *
from eval.depth_eval_utils import *
from data import create_dataset
import opts
class DirDataset(Dataset):
def __init__(self, dir, height, width, crop=None):
'''
crop: (top, left, height, width)
'''
self.filenames = glob.glob(os.path.join(args.input_dir, "*.jpg"))
self.height = height
self.width = width
self.crop = crop
def __getitem__(self, idx):
img = Image.open(self.filenames[idx])
if img.size[0] != self.width or img.size[1] != self.height:
img = img.resize((self.width, self.height), resample=Image.LANCZOS)
else:
print("No resize required")
if self.crop is not None:
img = img.crop(
(self.crop[1], self.crop[0], self.crop[1] + self.crop[3], self.crop[0] + self.crop[2]))
img = VF.to_tensor(img)
return {'path': self.filenames[idx], 'img': img}
def __len__(self):
return len(self.filenames)
if __name__ == '__main__':
args = opts.parse_args()
args.seq_len = 1
args.workers = 0
checkpoint = torch.load(args.checkpoint)
os.makedirs(args.output_dir, exist_ok=True)
model = checkpoint['model']
model.to(args.device)
model.eval()
dataset = DirDataset(args.input_dir, args.height, args.width)
dataloader = DataLoader(dataset, batch_size=12,
shuffle=False, num_workers=args.workers)
for i, batch in enumerate(dataloader):
with torch.no_grad():
fnames, imgs = batch['path'], batch['img']
imgs = imgs.to(args.device)
imgs_normalized = VF.normalize(
imgs, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
depths, _, _ = model.depth_net(imgs_normalized)
depths = depths[0].cpu().numpy()
depths = np.squeeze(depths, 1)
assert len(depths), len(fnames)
vmin = np.min(1 / depths)
vmax = np.percentile(1 / depths, 95)
disps = 1 / depths
disps_rgb = convert_util.gray_to_rgb_np(
disps, cmap='magma', lb=vmin, ub=vmax)
for j in range(len(fnames)):
filename = fnames[j].split('/')[-1]
outname_noext = os.path.join(args.output_dir, filename[:-4])
if args.output_type == 'png':
cv2.imwrite(
outname_noext + '_pred.png',
255 * disps_rgb[j])
else:
np.savez(outname_noext + '.npz', disps_rgb[j])
| 2.21875 | 2 |
defcon/_labeling.py | kmdouglass/DEFCoN | 9 | 12767255 | <gh_stars>1-10
# © All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE,
# Switzerland, Laboratory of Experimental Biophysics, 2018
# See the LICENSE.txt file for more details.
import os
import h5py
import numpy as np
import pandas as pd
import tifffile
from scipy.stats import multivariate_normal
#%% generate_map function
def generate_map(locs, x_max=64, y_max=64, sigma=1):
"""Generates a density map from an array of fluorophore positions
Parameters
----
locs : numpy array of double
N-by-2 ndarray containing the horizontal and vertical positions of the
fluorophores in the frame, in pixels (but with subpixel precision)
x_max : int
Number of horizontal pixels of the density map (default 64)
y_max : int
Number of vertical pixels of the density map (default 64)
Returns
----
genMap : numpy array of double
x_max-by-y_max array containing the values for each pixel of the
density map
"""
# meshgrid
x, y = np.meshgrid(range(x_max), range(y_max))
x = x.reshape(-1,1)
y = y.reshape(-1,1)
grid = np.hstack((x,y))
# create a map
genMap = np.zeros((grid.shape[0],1))
for k in range(locs.shape[0]):
# Sum the mvn at each position for each pixel
mvn = multivariate_normal.pdf(grid + 0.5, locs[k,:], cov=sigma)
genMap += mvn.reshape(-1,1)
genMap = genMap.reshape((x_max, y_max))
return genMap
#%% generate_stack function
def gen_map_stack(frame_gt,
n_frames,
x_max, y_max,
threshold = 250,
sigma=1,
output_file=None,
dataset='data'):
"""Generates a HDF5 file with the density maps given in inputFile
Parameters
----------
frame_gt : str or pandas.DataFrame
CSV file or pandas.DataFrame containing the ground truth positions,
with the first column being the frame, and the second and third
columns the fluorophore positions, in pixels (with sub-pixel
precision)
outputFile : str
Name of the output HDF5 file containing the density maps. It
contains a unique dataset named 'data', of shape
(nFrames, x_max, y_max)
nFrames : int
The total number of frames in the stack
x_max : int
Number of horizontal pixels of the density map (default 64)
y_max : int
Number of vertical pixels of the density map (default 64)
threshold : float (0<x<1)
Minimal brightness to register on the image, in photons
"""
if isinstance(frame_gt, str):
ground_truth = pd.read_csv(frame_gt)
elif isinstance(frame_gt, pd.DataFrame):
ground_truth = frame_gt
else:
class GroundTruthFormatError(Exception):
pass
raise GroundTruthFormatError
('The ground truth must be either a csv file or a pandas.DataFrame')
# Dont take into account the fluorophores with weak signals.
print('Removing low-brightness molecules')
# TODO Add unit test for this.
try:
ground_truth = ground_truth[ground_truth['brightness'] > threshold]
print('Done.')
except KeyError:
print('No column named "brightness" detected. No thresholding on '
'fluorophore brightness will be performed.')
# Group by frame
idx = ground_truth.groupby('frame')
# Parse all the frames
density_stack = np.zeros((n_frames, x_max, y_max))
for index, f in idx:
locs = f[['x', 'y']].values
genMap = generate_map(locs, x_max, y_max, sigma=sigma)
# The frames are in 1-indexing (ImageJ)
numFrame = int(f.iloc[0]['frame'])
density_stack[numFrame-1,:,:] = genMap
if numFrame % 500 == 0:
print('Frame {0}/{1}...' .format(numFrame, n_frames))
print('Map generation complete.')
# Export to HDF5
if output_file is not None:
h5File = h5py.File(output_file, 'a')
h5File.create_dataset(dataset, data=density_stack)
h5File.close()
return density_stack
#%% Generate a tiff stack from the density HDF5 file
def h5_to_tiff(inputFile, dataset, outputFile=None):
"""Generate a tiff stack from a HDF5 dataset
"""
inputName = os.path.splitext(inputFile)[0]
if outputFile is None:
outputFile = inputName + '.tif'
file = h5py.File(inputFile, 'r')
dMap = file[dataset]
dMap = np.array(dMap)
dMap *=10000
dMap = dMap.astype('uint16')
tifffile.imsave(outputFile, dMap)
file.close()
def array_to_tiff(arr, outputTiff):
"""Transform a density map array into a tiff image, to be visualized."""
arr = np.array(arr)
arr *=10000
arr = arr.astype('uint16')
arr[arr > 60000] = 0
tifffile.imsave(outputTiff, arr)
#%% frame ground truth (gt) from state logger
# Deprecated
def get_frame_gt(position_logger, state_logger, output_file=None):
"""Given the position logger and the state logger of a SASS simulation,
builds a ['frame', 'time_on', 'x', 'y', 'id'] pandas DataFrame
giving for each frame the positions and on time of fluorophores that are
in a visible state
"""
print('Extracting the ground truth positions per frame from the state logger...')
def df_frame_time(on_frame, off_frame, on_time, off_time):
# A column with all the frames during which the fluo is on
out_row = pd.DataFrame(np.arange(on_frame, off_frame+1), columns=['frame'])
# A column with the time the fluo is on for each frame
if out_row.shape[0] == 1:
time_on = off_time - on_time
else:
time_on = np.ones(out_row.shape)
time_on[0] = on_frame+1 - on_time
time_on[-1] = off_time - off_frame
out_row['time_on'] = time_on
out_row['time_on'].astype(float)
return out_row
# Load the state logger
logger = pd.read_csv(state_logger)
# Load the positions
positions = pd.read_csv(position_logger)
positions['id'] = positions['id'].astype('int64')
# Some global variables
on_state = 0
nFrames = np.ceil(logger.time_elapsed.max())
# Add a column with the frame number
logger['frame'] = np.floor(logger['time_elapsed'])
logger.frame = logger.frame.astype(int)
# Sort by time elapsed and group by fluorophore
id_index = logger.groupby(['id'])
# Create the output empty data frame
frameGT = pd.DataFrame(columns = ['frame', 'time_on', 'x', 'y',
'z', 'id'])
# Parse for each frame
for fluoID, m in id_index:
# Check whether molecule starts in the ON state
if m.iloc[0]['initial_state'] == on_state:
on_frame = 0
on_time = 0.0
for index, row in m.iterrows():
if row['next_state'] == on_state:
on_frame = row['frame']
on_time = row['time_elapsed']
if row['initial_state'] == on_state:
off_frame = row['frame']
off_time = row['time_elapsed']
#print(positions['id']==fluoID)
out_df = df_frame_time(on_frame, off_frame, on_time, off_time)
out_df['x'] = positions.loc[positions['id']==fluoID].x.values[0]
out_df['y'] = positions.loc[positions['id']==fluoID].y.values[0]
out_df['z'] = positions.loc[positions['id']==fluoID].z.values[0]
out_df['id'] = fluoID
# Append to the output dataframe
frameGT = frameGT.append(out_df)
# Check if some molecules are on in the end
if m.iloc[-1]['next_state'] == on_state:
off_frame = nFrames-1
off_time = float(nFrames)
out_df = df_frame_time(on_frame, off_frame, on_time, off_time)
out_df['x'] = positions.loc[positions['id']==fluoID].x.values[0]
out_df['y'] = positions.loc[positions['id']==fluoID].y.values[0]
out_df['z'] = positions.loc[positions['id']==fluoID].z.values[0]
out_df['id'] = fluoID
# Append to the output dataframe
frameGT = frameGT.append(out_df)
# Timer
if fluoID % 1000 == 0:
print('Fluorophore %d / %d...' % (fluoID, positions.shape[0]))
# Convert the frame column to integers
frameGT['frame'] = frameGT['frame'].astype(int)
# If a fluo is activated twice during the same frame, the time_on must be
# added: for a same frame-ID pair, add the times, and take the min
# of the positions (they should be the same anyway)
aggFunc = {'time_on': 'sum', 'x': 'min', 'y' : 'min', 'z' : 'min'}
# Perform the aggregation on every frame-ID pair
frameGT = frameGT.groupby(['frame', 'id']).agg(aggFunc)
# Store the frame and ID as columns and not as index
frameGT = frameGT.reset_index()
frameGT['brightness'] = frameGT['time_on']*2500.0
if output_file is not None:
# Save the dataframe to a csv file
csv_file = output_file
frameGT.to_csv(csv_file, index=False)
print("File saved at '{0}'" .format(csv_file))
return frameGT
| 2.359375 | 2 |
GlobalSim_cluster.py | cosmo-epfl/glosim2 | 12 | 12767256 | from subprocess import Popen
from time import time,ctime
from libmatch.utils import s2hms,print_logo
import cPickle as pck
from GlobalSimilarity import get_globalKernel
import numpy as np
from Pool.mpi_pool import MPIPool
import sys,os,argparse
import quippy as qp
def func(command):
p = Popen(command, shell=True)
return p.wait()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="""Computes the Global average/rematch kernel. Needs MPI to run,
mpiexec -n 4 python """)
parser.add_argument("filename", nargs=1, help="Name of the LibAtom formatted xyz input file")
# parser.add_argument("-pe", "--path-to-executable", type=str, default="/home/musil/git/glosim2/",
# help="Path to the executable that runs, i.e. GlobalSimilarity_cluster.py")
parser.add_argument("-n", type=int, default=8, help="Number of radial functions for the descriptor")
parser.add_argument("-l", type=int, default=6, help="Maximum number of angular functions for the descriptor")
parser.add_argument("-c", type=float, default=3.5, help="Radial cutoff")
parser.add_argument("-cotw", type=float, default=0.5, help="Cutoff transition width")
parser.add_argument("-g", type=float, default=0.5, help="Atom Gaussian sigma")
parser.add_argument("-cw", type=float, default=1.0, help="Center atom weight")
# parser.add_argument("-k","--kernel", type=str, default="average",
# help="Global kernel mode (e.g. --kernel average / rematch ")
parser.add_argument("-gm","--gamma", type=str, default='2',
help="Regularization for entropy-smoothed best-match kernel")
parser.add_argument("-z", "--zeta", type=str, default='2', help="Power for the environmental matrix")
parser.add_argument("--prefix", type=str, default='', help="Prefix for output files (defaults to input file name)")
parser.add_argument("--first", type=int, default='0', help="Index of first frame to be read in")
parser.add_argument("--last", type=int, default='0', help="Index of last frame to be read in")
parser.add_argument("--outformat", type=str, default='text', help="Choose how to dump the alchemySoaps, e.g. pickle (default) or text (same as from glosim --verbose)")
parser.add_argument("-nt","--nthreads", type=int, default=4, help="Number of threads (1,2,4,6,9,12,16,25,36,48,64,81,100).")
parser.add_argument("-np","--nprocess", type=int, default=4, help="Number of processes to run in parallel.")
parser.add_argument("-cl","--chunklen", type=str, default='', help="Lenght of chunks to divide the global kernel matrix in. (comma separated)")
parser.add_argument("--nocenters", type=str, default="",help="Comma-separated list of atom Z to be ignored as environment centers (e.g. --nocenter 1,2,4)")
parser.add_argument("-ngk","--normalize-global-kernel", action='store_true', help="Normalize global kernel")
args = parser.parse_args()
###### Reads parameters input ######
filename = args.filename[0]
prefix = args.prefix
centerweight = args.cw
gaussian_width = args.g
cutoff = args.c
cutoff_transition_width = args.cotw
nmax = args.n
lmax = args.l
# global_kernel_type = args.kernel
# zeta = args.zeta
# gamma = args.gamma
try:
zetas = [int(zeta) for zeta in args.zeta.split(',')]
gammas = [float(gamma) for gamma in args.gamma.split(',')]
except:
raise ValueError('zeta and gamma must be coma separated int or float respectively')
global_kernel_type = {'average':zetas,'rematch':gammas}
nthreads = args.nthreads
nprocess = args.nprocess
normalize_global_kernel = args.normalize_global_kernel
save_env_kernels = True
first = args.first if args.first>0 else None
last = args.last if args.last>0 else None
# assumes GlobalSimilarity_cluster.py is still in the same folder
# as GlobalSim_cluster.py
path_to_executable = os.path.dirname(os.path.realpath(__file__))
if args.outformat in ['text','pickle']:
outformat = args.outformat
else:
raise Exception('outformat is not recognised')
# reads the nocenters list and transforms it into a list
if args.nocenters == "":
nocenters = []
else:
nocenters = map(int, args.nocenters.split(','))
nocenters = sorted(list(set(nocenters)))
###### Start the app ######
pool = MPIPool()
if not pool.is_master():
# Wait for instructions from the master process.
pool.wait()
sys.exit(0)
print_logo()
print "Start dirty parallelisation for cluster " \
"with a pool of {} mpi processes: {}".format(pool.size,ctime())
print "Computing the global {} kernel of {} " \
"from index {} to {} (None -> default, i.e. begining/end)".format(global_kernel_type, filename,first,last)
# run commands in parallel
st = time()
frames = qp.AtomsList(filename,start=first,stop=last)
Nframe = len(frames)
if args.chunklen:
aa = args.chunklen.split(',')
if len(aa) > 1:
xchunklen, ychunklen = int(aa[0]), int(aa[1])
elif len(aa) == 1:
xchunklen, ychunklen = int(aa[0]), int(aa[0])
else:
raise Exception('chunk lenght format not recognised')
else:
print 'Default chunk lenght'
xchunklen, ychunklen = Nframe // 5, Nframe // 5
xNchunk = Nframe // xchunklen
yNchunk = Nframe // ychunklen
xslices = [(it*xchunklen,(it+1)*xchunklen) for it in range(xNchunk)]
yslices = [(it*ychunklen,(it+1)*ychunklen) for it in range(yNchunk)]
xslices.append(((xNchunk)*xchunklen,Nframe))
yslices.append(((yNchunk)*ychunklen,Nframe))
soap_params = "-n" + str(nmax) + "-l" + str(lmax) + "-c" + str(cutoff) + \
"-g" + str(gaussian_width) + "-cw" + str(centerweight) + \
"-cotw" + str(cutoff_transition_width)
if prefix:
abspath = os.path.abspath(prefix)
else:
abspath = os.path.abspath(filename)
path,name = os.path.split(abspath)
if name.endswith('.xyz'):
name = name[:-4]
path += '/'
outpath = path
suffix = 0
while os.path.exists(path+name+soap_params+'_tmp{}'.format(suffix)):
suffix += 1
tmp_path = path+name+ soap_params +'_tmp{}/'.format(suffix)
print 'TMP output is in ' + tmp_path
os.makedirs(tmp_path)
fn_env_kernels = [tmp_path+name+'-{xf},{xl}-{yf},{yl}'.format(xf=xsl[0],xl=xsl[1],yf=ysl[0],yl=ysl[1])
+soap_params + '-env_kernels.pck'
for xsl in xslices for ysl in yslices if ysl[0] >= xsl[0]]
command_str = ['export OMP_NUM_THREADS={nthreads}; '
'python {path2exec} {filename} ' ,
'-n {nmax} -l {lmax} -c {cutoff} -g {gaussian_width} -cw {centerweight} ' ,
'-cotw {cutoff_transition_width} -z {zeta} -gm {gamma} ' ,
'-nt 1 -np {nprocess} -nc 1 --xlim {xf},{xl} --ylim {yf},{yl} ' ,
'--prefix {prefix}{name}-{xf},{xl}-{yf},{yl} -sek ' ,
]
if len(nocenters) > 0:
command_str.append(' --nocenters {nocenters} '.format(nocenters=args.nocenters))
command_str.append(' 2>&1 | tee {prefix}log-{xf},{xl}-{yf},{yl} >/dev/null ')
command_str = ' '.join(command_str)
path2GlobSim = path_to_executable+'GlobalSimilarity_cluster.py'
commands = [command_str.format(path2exec=path2GlobSim,filename=filename,
nmax=nmax,lmax=lmax,cutoff=cutoff,
gaussian_width=gaussian_width,centerweight=centerweight,
cutoff_transition_width=cutoff_transition_width,
zeta=zeta,gamma=gamma,
nthreads=nthreads,nprocess=1,
xf=xsl[0], xl=xsl[1], yf=ysl[0], yl=ysl[1],
prefix=tmp_path,name=name)
for xsl in xslices for ysl in yslices if ysl[0] >= xsl[0]
]
pool.map(func,commands)
pool.close()
env_kernels = {}
for fn in fn_env_kernels:
with open(fn,'rb') as f:
aa = pck.load(f)
env_kernels.update(**aa)
fn = outpath + name + soap_params + '-env_kernels.pck'
print 'Saving env kernels in ' + fn
with open(fn, 'wb') as f:
pck.dump(env_kernels, f, protocol=pck.HIGHEST_PROTOCOL)
if not normalize_global_kernel:
norm = "-nonorm"
else:
norm = ''
for kernel_name,params in global_kernel_type.iteritems():
for param in params:
if kernel_name == 'average':
gkt = '-average-zeta{:.0f}'.format(param)
globalKernel = get_globalKernel(env_kernels, kernel_type=kernel_name, zeta=param, nthreads=1)
fn = outpath + name + soap_params + gkt + norm + '.k'
print 'Saving global kernel in ' + fn
np.savetxt(fn, globalKernel)
elif kernel_name == 'rematch':
gkt = '-rematch-gamma{:.2f}'.format(param)
globalKernel = get_globalKernel(env_kernels, kernel_type=kernel_name, gamma=param, nthreads=8)
fn = outpath + name + soap_params + gkt + norm + '.k'
print 'Saving global kernel in ' + fn
np.savetxt(fn, globalKernel)
else:
raise ValueError
print 'Finished in: {}'.format(s2hms(time()-st))
print 'Closing app: {}'.format(ctime()) | 2.265625 | 2 |
AES/test2.py | Pumpkin-NN/Cryptography | 0 | 12767257 | data_matrix = [
[2, 3, 1, 1],
[1, 2, 3, 1],
[1, 1, 2, 3],
[3, 1, 1, 2]
]
def fill_zeros(data_val):
return bin(int(data_val, 16))[2:].zfill(8)
input_hex = [0xd4, 0xbf, 0x5d, 0x30]
input_bin = []
for i, bin_num in enumerate(input_hex):
bin_num = bin(input_hex[i])[2:].zfill(8)
print(bin_num)
bin_num = int(bin_num, 2)
input_bin.append(bin_num)
print(input_bin)
for col in data_matrix:
print("+++++++++++++++++++++++\nThe {} round\n\n".format(col))
result_row_1 = []
for i, row in enumerate(col):
if row == 2:
print("2")
a = input_bin[i]
a = bin(input_bin[i])[2:].zfill(8)
print("AAAAAAAAAAAAAAAAA\n")
print("a = {}".format(a))
print(type(a))
print("\nAAAAAAAAAAAAAAAA")
if int(a[0]) == 1:
a = input_bin[i] << 1
a = bin(a)[3:].zfill(8)
print("I am a leftshifted a: {}".format(a))
a = int(a, 2)
xor_row_1 = a ^ 0x1b
xor_row_1 = bin(xor_row_1)[2:].zfill(8)
print("I am == 1: {}".format(xor_row_1))
else:
a = input_bin[i] << 1
a = bin(a)[3:].zfill(8)
a = int(a, 2)
xor_row_1 = a
xor_row_1 = bin(xor_row_1)[2:].zfill(8)
print("I am == 0: {}".format(xor_row_1))
xor_row_1 = a
elif row == 3:
print("3")
b = input_bin[i]
b = bin(input_bin[i])[2:].zfill(8)
print("BBBBBBBBBBBBBBBBBB\n")
print("b = {}".format(b))
print(type(b))
print("\nBBBBBBBBBBBBBBBBBBB")
if int(b[0]) == 1:
b = input_bin[i] << 1
b = bin(b)[3:].zfill(8)
print("I am a leftshifted b: {}".format(b))
b = int(b, 2)
xor_row_2 = b ^ 0x1b ^ input_bin[i]
xor_row_2 = bin(xor_row_2)[2:].zfill(8)
print("I am == 1: {}".format(xor_row_2))
else:
b = input_bin[i] << 1
b = bin(b)[2:].zfill(8)
print("I am a leftshifted b: {}".format(b))
b = int(b, 2)
xor_row_2 = b ^ input_bin[i]
xor_row_2 = bin(xor_row_2)[2:].zfill(8)
print("I am == 0: {}".format(xor_row_2))
print(xor_row_2)
else:
print("1")
print("\n\n\n\n\n\n")
| 3.25 | 3 |
ait/core/bin/ait_table_decode.py | robschneider16/AIT-Core | 1 | 12767258 | <filename>ait/core/bin/ait_table_decode.py
#!/usr/bin/env python
# Advanced Multi-Mission Operations System (AMMOS) Instrument Toolkit (AIT)
# Bespoke Link to Instruments and Small Satellites (BLISS)
#
# Copyright 2016, by the California Institute of Technology. ALL RIGHTS
# RESERVED. United States Government Sponsorship acknowledged. Any
# commercial use must be negotiated with the Office of Technology Transfer
# at the California Institute of Technology.
#
# This software may be subject to U.S. export control laws. By accepting
# this software, the user agrees to comply with all applicable U.S. export
# laws and regulations. User has the responsibility to obtain export licenses,
# or other export authority as may be required before exporting such
# information to foreign countries or providing access to foreign persons.
'''
usage: ait-table-decode --fswtabdict config/table.yaml --tabletype targets --binfile /Users/ays/targets.bin
Decodes the given FSW binary table to text.
Examples:
$ ait-table-decode --fswtabdict config/table.yaml --tabletype targets --binfile /Users/ays/targets.bin
'''
import os
import sys
import argparse
from ait.core import gds, log, table
def main():
log.begin()
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
# Add optional command line arguments
parser.add_argument('--binfile', default=None, required=True)
parser.add_argument('--fswtabdict', default=None, required=True)
parser.add_argument('--tabletype', default=None, required=True)
parser.add_argument('--verbose', action='store_true', default=False)
parser.add_argument('--version', default=0, type=int)
# Get command line arguments
args = vars(parser.parse_args())
binfile = args['binfile']
dictpath = args['fswtabdict']
tabletype = args['tabletype']
verbose = args['verbose']
version = args['version']
# Grab default table dictionary
if dictpath is not None:
dictCache = table.FSWTabDictCache(filename=dictpath)
try:
filename = dictCache.filename
except IOError, e:
msg = 'Could not load default table dictionary "%s": %s'
log.error(msg, filename, str(e))
fswtabdict = table.getDefaultFSWTabDict()
# Check if cmddict exists
if fswtabdict is not None:
# Write out the table file using the command dictionary
table.writeToText(fswtabdict, tabletype, binfile, verbose, version)
log.end()
if __name__ == '__main__':
main()
| 2.390625 | 2 |
searchable-options/searchable_options_test.py | phpc0de/idea-android | 0 | 12767259 | import filecmp
import glob
import os
import platform
import re
import shutil
import unittest
import zipfile
import update_searchable_options
class SearchableOptionTests(unittest.TestCase):
"""Tests searchable options to be up-to-date.
This test purpose is to generate these files, so whenever a
configurable or an action description changes we can use this
test to keep the files up-to-date.
"""
def test_searchable_options(self):
work_dir = os.getenv("TEST_TMPDIR")
expected_dir = os.path.join(work_dir, "expected")
plugin_list = update_searchable_options.generate_searchable_options(work_dir, expected_dir)
# Create actual tree
plugin_path = {
"Windows": "android-studio/plugins",
"Linux": "android-studio/plugins",
"Darwin": "Android Studio*.app/Contents/plugins",
}
actual_dir = os.path.join(work_dir, "actual")
[plugins_dir] = glob.glob(os.path.join(work_dir, plugin_path[platform.system()]))
for plugin in os.listdir(plugins_dir):
if plugin in plugin_list:
lib_dir = os.path.join(plugins_dir, plugin, "lib")
for jar in os.listdir(lib_dir):
if jar.endswith(".jar"):
with zipfile.ZipFile(os.path.join(lib_dir, jar)) as jar_file:
has_searchable_options = False
has_search_entry = False
for name in jar_file.namelist():
if re.match(r"search/.*searchableOptions\.xml", name):
jar_file.extract(name, path=os.path.join(actual_dir, plugin, jar))
has_searchable_options = True
if name == "search/":
has_search_entry = True
if has_searchable_options and not has_search_entry:
self.fail("Jar %s contains searchable options xmls, but it does " % jar +
"not have a search/ directory entry. IntelliJ requires the directory entry to find the .xmls")
eq = self.same_folders(filecmp.dircmp(expected_dir, actual_dir))
if not eq:
print("Searchable options comparison failed.")
print("The expected output is in outputs.zip, please update tools/adt/idea/searchable-options with it.")
print("Alternatively, if you are on Linux you can run: bazel run //tools/adt/idea/searchable-options:update_searchable_options")
undeclared_outputs = os.getenv("TEST_UNDECLARED_OUTPUTS_DIR")
for name in os.listdir(expected_dir):
shutil.copytree(os.path.join(expected_dir, name), os.path.join(undeclared_outputs, name))
self.fail("Searchable options differ")
def same_folders(self, diff):
if diff.diff_files:
return False
for sub_diff in diff.subdirs.values():
if not self.same_folders(sub_diff):
return False
return True
if __name__ == "__main__":
unittest.main()
| 2.640625 | 3 |
src/conll_to_text.py | talktovishal/biasCDA | 0 | 12767260 | <filename>src/conll_to_text.py
import argparse
from utils.conll import load_sentences, load_sentences_from_string
from utils.data import get_sentence_text
from tqdm import tqdm
import os
"""
Program to convert a conll file to a text file
"""
def getTextFromConllu(conlluLines):
print(f"getTextFromConllu::conllu = {type(conlluLines)} ; {type(conlluLines[0])}\n", flush=True)
conllu = load_sentences_from_string('\n'.join(conlluLines)+'\n')
print(f"getTextFromConllu::conllu = {type(conllu)}; {type(conllu[0])}\n", flush=True)
return get_sentence_text(conllu[0])
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--in_files', required=True, nargs='+', help='Input conllu files')
parser.add_argument('--out_dir', required=True, help='Output directory')
parser.add_argument('--part', type=int)
opt = parser.parse_args()
for i in range(len(opt.in_files)):
file = opt.in_files[i]
out_file = os.path.join(opt.out_dir, file.split("/")[-1][:file.rfind('.')] + "_text")
out = open(out_file, "w")
print("Processing file " + str(i + 1) + " out of " + str(len(opt.in_files)) + " files")
part = 1
with open(file, "r") as f:
not_empty = True
while not_empty and (not opt.part or part <= opt.part):
conll, not_empty = load_sentences(10000, f)
out_text = ""
for sent in tqdm(conll, total=len(conll)):
try:
print(f"conll_to_text::sent() = {type(sent)}")
out_text += sent.id + "\n"
out_text += get_sentence_text(sent) + "\n"
except TypeError:
for x in sent:
print(x.id, x.form, x.lemma, x.upos, x.head, x.deprel)
exit()
del conll
out.write(out_text)
del out_text
part += 1
out.close()
print("Done")
| 3.515625 | 4 |
encoder3.py | dhylands/upy-examples | 78 | 12767261 | <filename>encoder3.py
import pyb
import stm
# This script sets up a timer to do quadrature decoding
#
# THis script assumes that you have a jumper from X1 to X3 and X2 to X4
out_idx = 0
out_seq = [0, 1, 3, 2]
pin_a2 = pyb.Pin('X3', pyb.Pin.OUT_PP)
pin_b2 = pyb.Pin('X4', pyb.Pin.OUT_PP)
def set_out():
print("Writing X4 {:d} X3 {:d}".format((out_seq[out_idx] & 0x02) != 0, (out_seq[out_idx] & 0x01) != 0))
pin_a2.value((out_seq[out_idx] & 0x01) != 0)
pin_b2.value((out_seq[out_idx] & 0x02) != 0)
def incr():
global out_idx
out_idx = (out_idx + 1) % 4
set_out()
def decr():
global out_idx
out_idx = (out_idx - 1) % 4
set_out()
set_out()
pin_a = pyb.Pin('X1', pyb.Pin.AF_PP, pull=pyb.Pin.PULL_NONE, af=pyb.Pin.AF1_TIM2)
pin_b = pyb.Pin('X2', pyb.Pin.AF_PP, pull=pyb.Pin.PULL_NONE, af=pyb.Pin.AF1_TIM2)
enc_timer = pyb.Timer(2, prescaler=1, period=100000)
enc_channel = enc_timer.channel(1, pyb.Timer.ENC_AB)
for i in range(12):
print("Counter =", enc_timer.counter());
incr()
for i in range(24):
print("Counter =", enc_timer.counter());
decr()
for i in range(12):
print("Counter =", enc_timer.counter());
incr()
print("Counter =", enc_timer.counter());
| 2.78125 | 3 |
examplecode/n_pointed_start.py | lacitrus/LC101_ThinkPython | 0 | 12767262 | <filename>examplecode/n_pointed_start.py<gh_stars>0
# creat n-pointed star
import turtle
def draw_star(turtle, n):
for i in range(n):
turtle.forward(100)
turtle.right(180-180/n)
def main():
tess = turtle.Turtle()
draw_star(tess, 9)
if __name__ == "__main__":
main()
| 3.5625 | 4 |
databroker/tests/test_v2/test_multi_descriptor.py | ericdill/DataBroker | 15 | 12767263 | <filename>databroker/tests/test_v2/test_multi_descriptor.py
from pytest import fixture
import pytest
import event_model
import numpy as np
import time
from databroker.in_memory import BlueskyInMemoryCatalog
data_shape = (1000, 1000)
@fixture(params=[(('primary', 'baseline'), True), (('primary', 'primary'), True),
(('primary', 'baseline'), False), (('primary', 'primary'), False)])
def multi_descriptor_doc_stream(request):
streams, with_dims = request.param
def doc_gen(stream_names):
# Compose run start
run_bundle = event_model.compose_run() # type: event_model.ComposeRunBundle
start_doc = run_bundle.start_doc
yield "start", start_doc
for stream_name in stream_names:
data = np.random.random(data_shape)
# Compose descriptor
source = "NCEM"
frame_data_keys = {
"raw": {
"source": source,
"dtype": "array",
"shape": data.shape,
"dims": ("x", "y"),
}
}
if not with_dims:
del frame_data_keys['raw']['dims']
frame_stream_bundle = run_bundle.compose_descriptor(
data_keys=frame_data_keys, name=stream_name,
)
yield "descriptor", frame_stream_bundle.descriptor_doc
yield "event", frame_stream_bundle.compose_event(
data={"raw": data}, timestamps={"raw": time.time()}
)
yield "stop", run_bundle.compose_stop()
return doc_gen(streams)
def test_multi_descriptors(multi_descriptor_doc_stream):
docs = list(multi_descriptor_doc_stream)
catalog = BlueskyInMemoryCatalog()
start = docs[0][1]
stop = docs[-1][1]
def doc_gen():
yield from docs
catalog.upsert(start, stop, doc_gen, [], {})
assert catalog[-1]["primary"].to_dask()["raw"].compute().shape == (
stop["num_events"]["primary"],
*data_shape,
)
| 2.078125 | 2 |
optimus/lr_method/armijo.py | IanTayler/tao-exercises | 3 | 12767264 | """Armijo rule."""
import numpy as np
from optimus.types import LRMethod, Function
class Armijo(LRMethod):
"""Armijo method for finding Learning Rate.
This method successively reduces the learning rate until it finds the
resulting change to be as good as a linear approximation of the function.
"""
def __init__(
self,
initial_lr: float,
tolerance: float,
decrease_factor: float,
max_iters: int = 10,
):
self.initial_lr = initial_lr
self.tolerance = tolerance
self.decrease_factor = decrease_factor
self.max_iters = max_iters
def __call__(
self,
parameters: np.ndarray,
function_value: float,
gradient: np.ndarray,
direction: np.ndarray,
step: int,
objective_function: Function,
) -> float:
lr = self.initial_lr
def new_value(lr):
return function_value - objective_function(parameters - lr * direction)
def desired_value(lr):
return self.tolerance * lr * np.dot(gradient, direction)
while new_value(lr) < desired_value(lr):
lr *= self.decrease_factor
return lr
| 3.46875 | 3 |
esileapclient/v1/offer.py | betaredex/python-esileapclient | 0 | 12767265 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import json
import logging
from osc_lib import exceptions
from esileapclient.common import base
LOG = logging.getLogger(__name__)
class Offer(base.Resource):
detailed_fields = {
'availabilities': "Availabilities",
'end_time': "End Time",
'lessee': "Lessee",
'lessee_id': "Lessee ID",
'name': "Name",
'parent_lease_uuid': "Parent Lease UUID",
'project': "Project",
'project_id': "Project ID",
'properties': "Properties",
'resource': "Resource",
'resource_type': "Resource Type",
'resource_uuid': "Resource UUID",
'start_time': "Start Time",
'status': "Status",
'uuid': "UUID",
}
fields = {
'uuid': "UUID",
'resource': "Resource",
'lessee': "Lessee",
'start_time': "Start Time",
'end_time': "End Time",
'status': "Status",
'availabilities': "Availabilities",
}
_creation_attributes = ['resource_type', 'resource_uuid',
'start_time', 'end_time', 'status',
'project_id', 'properties', 'name',
'lessee_id']
def __repr__(self):
return "<Offer %s>" % self._info
class OfferManager(base.Manager):
resource_class = Offer
_resource_name = 'offers'
def create(self, os_esileap_api_version=None, **kwargs):
"""Create an offer based on a kwargs dictionary of attributes.
:returns: a :class: `Offer` object
"""
offer = self._create(os_esileap_api_version=os_esileap_api_version,
**kwargs)
return offer
def list(self, filters, os_esileap_api_version=None):
"""Retrieve a list of offers.
:returns: A list of offers.
"""
resource_id = ''
url_variables = OfferManager._url_variables(filters)
url = self._path(resource_id) + url_variables
offers = self._list(url,
os_esileap_api_version=os_esileap_api_version)
if type(offers) is list:
return offers
def get(self, offer_uuid):
"""Get an offer with the specified identifier.
:param offer_uuid: The uuid of an offer.
:returns: a :class:`Offer` object.
"""
offer = self._get(offer_uuid)
return offer
def delete(self, offer_uuid):
"""Delete an offer with the specified identifier.
:param offer_uuid: The uuid of an offer.
:returns: a :class:`Offer` object.
"""
self._delete(resource_id=offer_uuid)
def claim(self, offer_uuid, **kwargs):
"""Claim an offer with the specified identifier.
:param offer_uuid: The uuid of an offer.
:returns: a :class:`Offer` object.
"""
url = self._path(offer_uuid) + "/claim"
resp, body = self.api.json_request('POST', url, body=kwargs)
if resp.status_code == 201:
return self.resource_class(self, body)
else:
raise exceptions.CommandError(json.loads(resp.text)['faultstring'])
| 1.71875 | 2 |
modules/speaker/software/tcp_speaker.py | riera90/Pancho | 0 | 12767266 | #!/usr/bin/python3
from pygame import mixer
import re, os, signal
import paho.mqtt.client as mqtt
import config
class Player():
def __init__(self, path=""):
self.__path = path
self.__mixer = mixer
self.__mixer.init()
self.__vlc_pid = None
self.__vlc_url = None
def setPath(self, path):
self.__path = path
def play(self):
self.__mixer.music.load(self.__path)
self.__mixer.music.play()
def stop(self):
self.__mixer.music.stop()
def pause(self):
self.__mixer.music.pause()
def resume(self):
self.__mixer.music.unpause()
def playWeb(self, url):
if (self.__vlc_pid == None):
self.__vlc_url = url
self.__vlc_pid = os.fork()
if self.__vlc_pid == 0:
os.system("cvlc --intf dummy " + self.__vlc_url)
os._exit(0)
else:
self.stopWeb()
self.playWeb(url)
def stopWeb(self):
os.system("killall vlc -9")
self.__vlc_pid = None
player = Player("music.flac")
mqtt_client = mqtt.Client(config.HOSTNAME)
mqtt_client.username_pw_set(config.MQTT_USERNAME, config.MQTT_PASSWORD)
mqtt_client.connect(config.MQTT_BROKER, config.MQTT_BROKER_PORT)
mqtt_client.subscribe(config.MQTT_TOPIC, config.MQTT_QOS)
# Define event callbacks
def on_connect(client, userdata, flags, rc):
print("rc: " + str(rc))
def on_message(client, obj, msg):
print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
request = msg.payload.decode("utf-8")
play_web = re.match(r'play web (.*)', request, re.I)
if play_web:
player.playWeb(play_web.group(1))
play = re.match(r'play (.*)', request, re.I)
if play:
player.setPath(play.group(1))
player.play()
elif (request == "play"):
player.play()
elif (request == "pause"):
player.pause()
elif (request == "resume"):
player.resume()
elif (request == "stop"):
player.stop()
elif (request == "stop web"):
player.stopWeb()
def on_publish(client, obj, mid):
print("mid: " + str(mid))
def on_subscribe(client, obj, mid, granted_qos):
print("Subscribed: " + str(mid) + " " + str(granted_qos))
def on_log(client, obj, level, string):
print(string)
# Assign event callbacks
mqtt_client.on_message = on_message
mqtt_client.on_connect = on_connect
mqtt_client.on_publish = on_publish
mqtt_client.on_subscribe = on_subscribe
def main():
while True:
try:
mqtt_client.loop()
except Exception as e:
print(e)
if __name__ == "__main__":
main()
| 2.59375 | 3 |
assignments/test_binary_search.py | yamaszone/software-testing | 13 | 12767267 | import unittest
import binary_search
class test_binary_search(unittest.TestCase):
def test_binary_search_returns_true_when_search_key_found(self):
self.assertTrue(binary_search.binary_search([3, 1, 2], 2))
def test_binary_search_returns_false_when_search_key_not_found(self):
self.assertFalse(binary_search.binary_search([3, 1, 2], 0))
| 3.515625 | 4 |
tests/test_halos/test_uldm.py | DarthLazar/pyHalo | 0 | 12767268 | from astropy.cosmology.funcs import z_at_value
import numpy as np
from pyHalo.single_realization import SingleHalo
import numpy.testing as npt
import numpy as np
from pyHalo.Halos.HaloModels.ULDM import ULDMFieldHalo, ULDMSubhalo
from pyHalo.Halos.lens_cosmo import LensCosmo
from pyHalo.Cosmology.cosmology import Cosmology
from lenstronomy.LensModel.Profiles.cnfw import CNFW
from lenstronomy.LensModel.Profiles.nfw import NFW
from lenstronomy.LensModel.Profiles.uldm import Uldm
import pytest
class TestULDMHalo(object):
def setup(self):
mass = 1e9
x = 0.5
y = 1.
r3d = np.sqrt(1 + 0.5 ** 2 + 70**2)
self.r3d = r3d
self.z = 0.25
sub_flag = True
mdef = 'ULDM'
self.H0 = 70
self.omega_baryon = 0.03
self.omega_DM = 0.25
self.sigma8 = 0.82
curvature = 'flat'
self.ns = 0.9608
cosmo_params = {'H0': self.H0, 'Om0': self.omega_baryon + self.omega_DM, 'Ob0': self.omega_baryon,
'sigma8': self.sigma8, 'ns': self.ns, 'curvature': curvature}
self._dm, self._bar = self.omega_DM, self.omega_baryon
cosmo = Cosmology(cosmo_kwargs=cosmo_params)
self.lens_cosmo = LensCosmo(self.z, 2., cosmo)
profile_args = {'RocheNorm': 1.2, 'RocheNu': 2/3,
'evaluate_mc_at_zlens': False,
'log_mc': None, 'c_scale': 60.,
'c_power': -0.17, 'c_scatter': False,
'mc_model': 'diemer19', 'LOS_truncation_factor': 40,
'c_scatter_dex': 0.1, 'mc_mdef': '200c',
'log10_m_uldm':-22, 'uldm_plaw':1/3}
self.subhalo = ULDMSubhalo(mass, x, y, r3d, mdef, self.z,
sub_flag, self.lens_cosmo,
profile_args, unique_tag=np.random.rand())
self.fieldhalo = ULDMFieldHalo(mass, x, y, r3d, mdef, self.z,
sub_flag, self.lens_cosmo,
profile_args, unique_tag=np.random.rand())
def test_lenstronomy_ID(self):
ID = self.fieldhalo.lenstronomy_ID
npt.assert_string_equal(ID[0], 'CNFW')
npt.assert_string_equal(ID[1], 'ULDM')
ID = self.subhalo.lenstronomy_ID
npt.assert_string_equal(ID[0], 'CNFW')
npt.assert_string_equal(ID[1], 'ULDM')
def test_redshift_eval(self):
z_subhalo = self.subhalo.z_eval
z_field = self.fieldhalo.z_eval
npt.assert_equal(z_field, self.z)
# because the concentration is evaluated at infall, and z_infall > z
npt.assert_equal(True, z_subhalo > z_field)
def test_profile_load(self):
# test cored composite profile
profile_args = {'log10_m_uldm': -22, 'uldm_plaw': 1/3, 'scale_nfw':False}
single_halo = SingleHalo(1e8, 0.5, 0.5, 'ULDM', 0.5, 0.5, 1.5, None, True, profile_args, None)
lens_model_list, redshift_array, kwargs_lens, numerical_interp = single_halo.\
lensing_quantities(add_mass_sheet_correction=False)
npt.assert_string_equal(lens_model_list[1], 'ULDM')
npt.assert_string_equal(lens_model_list[0], 'CNFW')
npt.assert_equal(True, len(kwargs_lens)==2)
npt.assert_equal(True, len(redshift_array)==2)
def test_profile_normalization(self):
"""
Test that the mass enclosed within r200 of the composite profile is correct
and check that the ULDM core density is correct.
"""
profile_args = {'log10_m_uldm': -21, 'uldm_plaw': 1/3, 'scale_nfw':True}
mass = 1e10
zl = 0.5
zs = 1.5
single_halo = SingleHalo(mass, 0.5, 0.5, 'ULDM', zl, zl, zs, None, True, profile_args, None)
_, _, kwargs_lens, _ = single_halo.lensing_quantities(add_mass_sheet_correction=False)
Rs_angle, _ = single_halo.halos[0].lens_cosmo.nfw_physical2angle(mass, single_halo.halos[0].c, zl)
sigma_crit = single_halo.halos[0].lens_cosmo.sigmacrit
r200 = single_halo.halos[0].c * Rs_angle
cnfw_kwargs, uldm_kwargs = kwargs_lens
M_nfw = CNFW().mass_3d_lens(r200, cnfw_kwargs['Rs'], cnfw_kwargs['alpha_Rs']*sigma_crit, cnfw_kwargs['r_core'])
M_uldm = Uldm().mass_3d_lens(r200, uldm_kwargs['kappa_0']*sigma_crit, uldm_kwargs['theta_c'])
npt.assert_almost_equal((M_uldm+M_nfw)/mass,1,decimal=2) # less than 1% error
_,theta_c,kappa_0 = single_halo.halos[0].profile_args
rho0 = Uldm().density_lens(0,uldm_kwargs['kappa_0'],
uldm_kwargs['theta_c'])
rhos = CNFW().density_lens(0,cnfw_kwargs['Rs'],
cnfw_kwargs['alpha_Rs'],
cnfw_kwargs['r_core'])
rho_goal = Uldm().density_lens(0,kappa_0,theta_c)
npt.assert_array_less(np.array([1-(rho0+rhos)/rho_goal]),np.array([0.02])) # less than 2% error
if __name__ == '__main__':
pytest.main()
| 1.9375 | 2 |
ARCIT/forms.py | s0hailAnsari/ARCIT | 0 | 12767269 | from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import get_user_model
class UserForm(UserCreationForm):
class Meta:
model = get_user_model()
fields = ('username', '<PASSWORD>', '<PASSWORD>', )
| 2.1875 | 2 |
setup.py | zhouzaihang/jupyterlab_micropython_kernel | 7 | 12767270 | <reponame>zhouzaihang/jupyterlab_micropython_kernel<gh_stars>1-10
from pathlib import Path
from setuptools import setup
# Get the long description from the README file
project = Path(__file__).parent
with (project / 'README.md').open(encoding='utf-8') as f:
long_description = f.read()
setup(name="jupyterlab_micropython_kernel",
version="0.0.7",
description=long_description,
author='ZhouZaihang, <NAME>, <NAME>',
author_email='<EMAIL>',
keywords='jupyterlab micropython',
url='https://github.com/zhouzaihang/jupyterlab_micropython_kernel',
license='MIT',
packages=['jupyterlab_micropython_kernel'],
install_requires=['pyserial>=3.4', 'websocket-client>=0.44', 'ipykernel', 'nbconvert', 'nbformat']
) | 1.78125 | 2 |
ladderdev/RatingSystemTester.py | fistaco/Smogon-Usage-Stats | 26 | 12767271 | <filename>ladderdev/RatingSystemTester.py
#!/usr/bin/python
# -*- coding: latin-1 -*-
import sys
import gzip
import json
import math
import cPickle as pickle
def incorrectSyntax():
sys.stderr.write('Incorrect syntax.\n')
sys.stderr.write('Correct usage:\n')
sys.stderr.write('\tpython RatingSystemTester.py SYSTEMS [-n] [-w prefix] FILES...\n')
sys.stderr.write('OPTIONS:\n')
sys.stderr.write('\t-w prefix\tWrite "win" files listing actual vs. expected outcomes.\n')
sys.stderr.write('\t\t\tA file is generated for each system with a name starting\n')
sys.stderr.write('\t\t\twith the specified prefix.\n')
sys.stderr.write('\t-n\t\tIf match ended in a forfeit, do not update ratings.\n')
sys.stderr.write('Example:\n')
sys.stderr.write('\tpython RatingSystemTester.py Elo,Glicko2 -w ratingTests/lc-201401 ratingTests/lc-201401.csv\n')
sys.exit(1)
daysPerRatingPeriod=1
systems = sys.argv[1].split(',')
try:
ratingSystems={}
for system in systems:
ratingSystems[system] = __import__(system)
except:
incorrectSyntax()
ratings={}
winfiles={}
noforfeits=False
idx=2
while sys.argv[idx].startswith('-'):
if (sys.argv[idx] == '-w'):
base=sys.argv[idx+1]+'-'
for system in systems:
winfiles[system]=open(base+system+'.csv','w')
idx+=2
elif (sys.argv[idx] == '-n'):
noforfeits=True
idx+=1
else:
incorrectSyntax()
date=''
bprpfile=open(base+'brpr.csv','w')
i=0
while idx<len(sys.argv):
for line in open(sys.argv[idx]).readlines():
battle=line.split(',')
if len(battle)<8:
continue
if battle[6] != 'normal' and noforfeits:
continue
if battle[0] != date:
i+=1
if (i == daysPerRatingPeriod):
for player in ratings.keys():
bprpfile.write(str(ratings[player]['battlesInRatingPeriod'])+'\n')
ratings[player]['battlesInRatingPeriod']=0
for system in systems:
ratings[player][system]=ratingSystems[system].newRatingPeriod(ratings[player][system])
i=0
date=battle[0]
for p in [1,3]:
if battle[p] not in ratings.keys():
newScore={'nBattles':0.0,'nWins':0.0,'battlesInRatingPeriod':0.0}
for system in systems:
newScore[system]=ratingSystems[system].newPlayer()
ratings[battle[p]]=newScore
ratings[battle[p]]['nBattles']+=1
ratings[battle[p]]['battlesInRatingPeriod']+=1
ratings[battle[1]]['nWins']+=2.0-float(battle[5])
ratings[battle[3]]['nWins']+=float(battle[5])-1.0
for system in systems:
ratings[battle[1]][system],ratings[battle[3]][system],E=ratingSystems[system].update(ratings[battle[1]][system],ratings[battle[3]][system],battle[5])
if system in winfiles.keys():
winfile=winfiles[system]
if int(battle[5]) == 1:
score=1.0
elif int(battle[5]) == 2:
score=0.0
else: #if outcome == 0
score=0.5
winfile.write(str(E)+','+str(score)+'\n')
idx+=1
try:
for winfile in winfiles.values():
winfile.close()
bprpfile.close()
except:
sys.err.write("I dunno what's going on.\n")
for player in ratings.keys():
ratings[player]['battlesInRatingPeriod']=0
for system in systems:
ratings[player][system]=ratingSystems[system].newRatingPeriod(ratings[player][system])
printme='Username,nBattles,nWins'
for system in systems:
printme+=','+ratingSystems[system].headers()
print printme
for player in ratings.keys():
printme=player+','+str(ratings[player]['nBattles'])+','+str(ratings[player]['nWins'])
for system in systems:
printme+=','+ratingSystems[system].printRating(ratings[player][system])
print printme
| 2.515625 | 3 |
tests/junk/recall/train_keras.py | imandr/gradnet | 0 | 12767272 | from generator import Generator
import numpy as np, random
np.set_printoptions(precision=4, suppress=True, linewidth=132)
from tensorflow import keras
from tensorflow.keras.layers import LSTM, Dense, Input
from tensorflow.keras import Model
from tensorflow.keras.optimizers import Adagrad
def create_net(nwords, batch_size, hidden=100):
inp = Input((None, nwords), batch_size=batch_size)
r1 = LSTM(hidden, return_sequences=True, stateful=True)(inp)
#r2 = LSTM(hidden, return_sequences=True)(r1)
probs = Dense(nwords, activation="softmax")(r1)
model = Model(inp, probs)
model.compile(optimizer=Adagrad(learning_rate=0.01), loss="categorical_crossentropy")
return model
def generate_from_model(model, g, length, batch_size):
#print("------- generate ----------")
model.reset_states()
nwords = g.NWords
rows = []
row = [random.randint(0, nwords-1) for _ in range(batch_size)] # [w]
rows.append(row)
for t in range(length-1):
x = np.array([g.vectorize(xi) for xi in row])
y = model.predict(x[:,None,:])[:,0,:] # y: [mb, w], t=0
pvec = y**3
pvec = pvec/np.sum(pvec, axis=-1, keepdims=True) # -> [mb, w]
row = [np.random.choice(nwords, p=p) for p in pvec]
rows.append(row)
rows = np.array(rows) # [t,mb]
return rows.transpose((1,0))
def generate_batch(g, length, batch_size):
#print("generate_batch(%s, %s)..." % (length, batch_size))
sequences = np.array([g.generate(length+1, as_vectors=True) for _ in range(batch_size)])
#print("sequences:", sequences.shape)
x = sequences[:,:-1,:]
y_ = sequences[:,1:,:]
return x, y_
def train(model, g, length, batch_size):
valid_ma = 0.0
steps = 0
for iteration in range(100000):
#print
x, y_ = generate_batch(g, length, batch_size)
loss = model.train_on_batch(x, y_)
if iteration and iteration % 50 == 0:
generated = generate_from_model(model, g, length, batch_size)[0]
#print(type(generated), generated.shape, generated)
valid_length = g.validate(generated)
valid_ma += 0.1*(valid_length-valid_ma)
if iteration % 100 == 0:
print(generated[:valid_length], "*", generated[valid_length:], " valid length:", valid_length)
print("Batches:", iteration, " steps:", iteration*length*batch_size, " loss/step:", loss/x.shape[1],
" moving average:", valid_ma)
if __name__ == '__main__':
nwords = 10
length = 50
distance = 5
r = 2
batch_size = 5
g = Generator(nwords, distance, r)
model = create_net(nwords, batch_size)
train(model, g, length, batch_size)
| 2.859375 | 3 |
eternal/7win.py | pjturcot/eternal | 0 | 12767273 | import json
import re
import matplotlib.pyplot as plt
import pandas as pd
import scipy.stats
import eternal.card
import eternal.ewc
import eternal.plot
CARDS_DATA = eternal.card.ALL.data
def imode(src):
"""Return a copy of a series where all case-insensitive versions have been replaced with the most common case sensitive variant."""
dest = src.copy()
for lower, subset in src.groupby(src.str.lower()):
dest[subset.index] = subset.mode().values[0]
return dest
if __name__ == '__main__':
# The structure of this CSV is FarmingEternal's 7-win run breakdown (Google Sheet) exported as CSV
df_7win_decks = pd.read_csv('7win_decks_set12.csv')[['s', 'Factions', 'Contributor', 'Image', 'EWC', 'EWC-P', 'W',
'L', 'Ep. #']]
df_7win_decks['Deck'] = None
for id, row in df_7win_decks.iterrows():
deck = eternal.ewc.parse_deckbuilder_url(row['EWC-P'])
deck.main_data.name = id
deck.main_data['DeckId'] = id
deck.main_data['PowerCount'] = [card.power_count() for card in deck.main_cards]
deck.main_data['MarketAccess'] = [card.has_market_access() for card in deck.main_cards]
df_7win_decks.at[id, 'Deck'] = deck
df_7win_decks['Contributor'] = imode(df_7win_decks['Contributor'])
df_7win_decks['MainFaction'] = df_7win_decks.Deck.apply(lambda x: ''.join(x.faction()[0]))
df_7win_decks['SplashFaction'] = df_7win_decks.Deck.apply(lambda x: ''.join(x.faction()[1]))
all_cards = pd.concat(df_7win_decks.Deck.apply(lambda x: x.main_data).tolist())
all_cards['DeckMainFaction'] = all_cards.DeckId.map(df_7win_decks['MainFaction'])
all_cards['DeckSplashFaction'] = all_cards.DeckId.map(df_7win_decks['SplashFaction'])
all_cards['IsSplash'] = all_cards.apply(lambda x: bool(set(x['DeckSplashFaction']).intersection(x['Influence'])), axis=1)
all_cards['Faction'] = all_cards['Influence'].apply(eternal.card.influence_to_faction)
all_cards['Contributor'] = all_cards.DeckId.map(df_7win_decks['Contributor'])
for faction in 'FTJPS':
all_cards[faction] = all_cards['Faction'].str.contains(faction)
# Playable deck counts
card_factions = set(map(eternal.card.influence_to_faction, all_cards[all_cards['Type'] != 'Power']['Influence'].unique()))
playable_deck_count_by_faction = {}
for faction in card_factions:
if faction == 'None':
faction = ''
is_deck_playable = lambda x: set(x['MainFaction']).union(set(x['SplashFaction'])).issuperset(faction)
deck_count = df_7win_decks.apply(is_deck_playable, axis=1).sum()
playable_deck_count_by_faction[faction] = deck_count
playable_deck_count_by_faction['None'] = len(df_7win_decks)
# ********** TOP CARDS (LISTS) **************
# Figure out card count statistics
card_counts = all_cards.groupby('Name')['Faction'].apply(lambda x: pd.Series({'Faction': x[0], 'Count': x.size})).unstack(1)
card_counts['PossibleDecks'] = card_counts['Faction'].map(playable_deck_count_by_faction)
card_counts['CountPerDeck'] = card_counts['Count'] / card_counts['PossibleDecks']
card_counts = card_counts.merge(CARDS_DATA, left_index=True, right_on='Name', how='left')
card_counts['MarketAccess'] = card_counts.index.map(dict(([(x.id, x.has_market_access()) for x in eternal.card.ALL.cards])))
# Frequency normalized (pick, boosting, faction, rarity)
CURRENT_SET = 12
DRAFT_FORMAT = '12.1'
with open(f'boosting_data/{DRAFT_FORMAT}.json') as fin:
DRAFT_PACK_BOOSTING = json.load(fin)['boosting']
freq_faction_lookup = {}
for faction in card_counts['Faction'].unique():
freq_faction_lookup[faction] = (df_7win_decks['MainFaction'] + df_7win_decks['SplashFaction']).str.contains(faction).sum() / len(df_7win_decks)
freq_faction_lookup['None'] = 1.0
freq_faction = card_counts['Faction'].map(freq_faction_lookup)
# Determine base offer rates by card
currentset_rarity_counts = CARDS_DATA[CARDS_DATA['SetNumber'] == CURRENT_SET]['Rarity'].value_counts()
currentset_rarity_counts.drop('Promo', inplace=True, errors='ignore')
draft_pack_cards = CARDS_DATA.loc[DRAFT_PACK_BOOSTING.keys()].copy()
draft_pack_cards['Boosting'] = draft_pack_cards.index.map(DRAFT_PACK_BOOSTING)
draft_pack_rarity_counts = draft_pack_cards.groupby('Rarity')['Boosting'].sum()
draft_pack_rarity_counts.drop('Promo', inplace=True, errors='ignore')
draft_pack_cards['BoostedFreq'] = draft_pack_cards['Boosting'] / draft_pack_cards['Rarity'].map(draft_pack_rarity_counts)
currentset_index = card_counts['SetNumber'] == CURRENT_SET
draft_pack_index = ~currentset_index & ~(card_counts['Name'].str.endswith('Sigil'))
freq_rarity_per_pack = card_counts['Rarity'].map({'Common': 8.0, 'Uncommon': 3.0, 'Rare': 0.905, 'Legendary': 0.095})
base_offer_rate = pd.Series(index=card_counts.index, dtype='float64')
base_offer_rate[currentset_index] = 1.0 / (card_counts[currentset_index])['Rarity'].map(currentset_rarity_counts)
base_offer_rate[draft_pack_index] = draft_pack_cards['BoostedFreq'].loc[base_offer_rate[draft_pack_index].index]
offer_rate = 2 * freq_rarity_per_pack * base_offer_rate # 2 packs for each pool
card_counts['OfferRate'] = offer_rate
card_counts['CountPerOffer'] = card_counts['Count'] / (card_counts['OfferRate'])
card_counts['CountPerOfferDeck'] = (card_counts['Count'] / (card_counts['OfferRate'] * card_counts['PossibleDecks'])).astype('float')
# Analyze the top commons
CARD_COUNT_DISPLAY_COLS = ['Name', 'Rarity', 'Faction', 'PossibleDecks', 'OfferRate', 'Count', 'CountPerDeck', 'CountPerOffer', 'CountPerOfferDeck']
N = 20
RARITY = ['Common', 'Uncommon', 'Rare', 'Legendary']
# Analyze the top cards by count
top_common_cards = card_counts[card_counts['Rarity'].isin(RARITY)].sort_values('Count', ascending=False)
print("******Top {N} {Rarity} cards (by count)*****".format(N=N, Rarity='+'.join(RARITY)))
print("NOTE: OfferRates is the number of cards you would expect in a given 4-pack draft")
print("NOTE: CountPerOfferDeck also corrects for possible Decks so faction frequency is accounted for")
print(top_common_cards[CARD_COUNT_DISPLAY_COLS].head(N))
print("\n")
# Analyze the top cards by playable deck faction
top_common_cards = card_counts[card_counts['Rarity'].isin(RARITY)].sort_values('CountPerDeck', ascending=False)
print("******Top {N} {Rarity} cards (by count per deck)*****".format(N=N, Rarity='+'.join(RARITY)))
print("NOTE: OfferRates is the number of cards you would expect in a given 4-pack draft")
print("NOTE: CounterPerOffer also corrects for possible Decks so faction frequency is accounted for")
print(top_common_cards[CARD_COUNT_DISPLAY_COLS].head(N))
print("\n")
# Analyze the top cards picked cards
top_picked_cards = card_counts[card_counts['Rarity'].isin(RARITY)].sort_values('CountPerOffer', ascending=False)
print("******Top {N} {Rarity} cards (by count per offer*)*****".format(N=N, Rarity='+'.join(RARITY)))
print("NOTE: OfferRates is the number of cards you would expect in a given 4-pack draft")
print("NOTE: CountPerOfferDeck also corrects for possible Decks so faction frequency is accounted for")
print(top_picked_cards[CARD_COUNT_DISPLAY_COLS].head(N))
print("\n")
# Analyze the least picked rare cards
least_picked_cards = card_counts[card_counts['Rarity'].isin(RARITY)].sort_values('CountPerOffer', ascending=True)
print("******Bottom {N} {Rarity} cards (by count per offer*)*****".format(N=N, Rarity='+'.join(RARITY)))
print("NOTE: OfferRates is the number of cards you would expect in a given 4-pack draft")
print("NOTE: CountPerOfferDeck also corrects for possible Decks so faction frequency is accounted for")
print(least_picked_cards[CARD_COUNT_DISPLAY_COLS].head(N))
print("\n")
# Analyze the top splashed cards
N = 20
splash_cards = all_cards[all_cards['IsSplash']].copy()
n_splash_decks = len(splash_cards['DeckId'].unique())
top_splashed_cards = splash_cards[splash_cards.Type != 'Power']['Name'].value_counts()
print("******Top {N} splashed for cards****".format(N=N))
print("(out of {n_splash_decks} decks that splashed)".format(n_splash_decks=n_splash_decks))
print(top_splashed_cards.head(N))
print("\n")
# Analyz all the market cards in play
market_cards = card_counts[card_counts['MarketAccess']].sort_values('Count', ascending=False)
print("*******ALL MARKET ACCESS CARDS********")
print("NOTE: OfferRates is the number of cards you would expect in a given 4-pack draft")
print("NOTE: CountPerOfferDeck also corrects for possible Decks so faction frequency is accounted for")
print(market_cards[CARD_COUNT_DISPLAY_COLS])
print("\n")
# Top combat tricks
N = 20
print("******Top {N} Fast spells (by count)*****".format(N=N))
print(all_cards[all_cards['Type'] == 'Fast Spell']['Name'].value_counts().head(N))
print("\n")
top_fastspell_cards = card_counts[card_counts['Type'] == 'Fast Spell'].sort_values('CountPerDeck', ascending=False)
print("******Top {N} Fast spells (by count per deck)*****".format(N=N))
print(top_fastspell_cards[CARD_COUNT_DISPLAY_COLS].head(N))
print("\n")
# Top stealth units
N = 20
print("******Top {N} Stealth Units (by count)*****".format(N=N))
print(all_cards[(all_cards['Type'] == 'Unit') & (all_cards['CardText'].str.contains('<b>Stealth</b>'))]['Name'].value_counts().head(N))
print("\n")
top_stealth_cards = card_counts[(card_counts['Type'] == 'Unit') & (card_counts['CardText'].str.contains('<b>Stealth</b>'))].sort_values('CountPerDeck',
ascending=False)
print("******Top {N} Stealh Units (by count per deck)*****".format(N=N))
print(top_stealth_cards[CARD_COUNT_DISPLAY_COLS].head(N))
print("\n")
# List out all "out of faction" cards
out_of_faction_cards = pd.DataFrame(
[x for i, x in all_cards.iterrows() if (not set(x.Faction).issubset(x.DeckMainFaction + x.DeckSplashFaction)) and (x.Faction is not 'None')])
print("Out of faction most played cards")
if not out_of_faction_cards.empty:
print(out_of_faction_cards['Name'].value_counts())
print("Out of faction card Contributors")
print(df_7win_decks.loc[out_of_faction_cards['DeckId']]['Contributor'].value_counts())
else:
print("No out of faction cards played!!!")
# ********** UNIT ANALYSIS **************
# Look at the unit-counts by player
df_7win_decks['UnitCount'] = df_7win_decks.Deck.apply(lambda x: x.types())['Unit']
units_by_player = df_7win_decks.groupby('Contributor')['UnitCount'].describe()
units_by_player[units_by_player['count'] >= 3].sort_values('mean')[['count', 'mean', 'min', 'max']]
# Look at the unit-counts by player
df_7win_decks['UnitCount'] = df_7win_decks.Deck.apply(lambda x: x.types())['Unit']
units_by_faction = df_7win_decks.groupby('MainFaction')['UnitCount'].describe()
print("**** Average unit count by deck main-faction (minimum 3 decks)")
print(units_by_faction[units_by_faction['count'] >= 3].sort_values('mean')[['count', 'mean', 'min', 'max']])
# ********** DECK POWER ANALYSIS **************
# Contributor Deck Power (Type==Power)
df_7win_decks['NumPower'] = df_7win_decks.Deck.apply(lambda x: x.types())['Power']
power_by_player = df_7win_decks.groupby('Contributor')['NumPower'].describe()[['count', 'mean', 'min', 'max']]
print("**** Power played by player (card type = Power) *****")
print(power_by_player[power_by_player['count'] >= 3].sort_values('mean')[['count', 'mean', 'min', 'max']])
# Contributor Deck Power (Effective Power)
df_7win_decks['EffectivePower'] = df_7win_decks.index.map(all_cards.groupby('DeckId')['PowerCount'].sum())
powercount_by_player = df_7win_decks.groupby('Contributor')['EffectivePower'].describe()[['count', 'mean', 'min', 'max']]
print("**** Power played by player (effective power*) *****")
print("NOTE: <=2 cost or less spells counted as power e.g. Seek Power/Etchings/BluePrints etc.")
print(powercount_by_player[powercount_by_player['count'] >= 3].sort_values('mean'))
# Contributor Deck Power (Type==Power vs. Effective Power)
power_by_player_merged = pd.merge(power_by_player, powercount_by_player, left_index=True, right_index=True,
suffixes=('_type', '_effective'))
print(power_by_player_merged[power_by_player_merged['count_type'] >= 3].sort_values('mean_effective'))
# MainFaction Deck Power (Type==Power vs. Effective Power)
powercount_by_deck_main_faction = df_7win_decks.groupby('MainFaction')['EffectivePower'].describe()[['count', 'mean', 'min', 'max']]
print("**** Power played by deck main factions (effective power*) *****")
print("NOTE: <=2 cost or less spells counted as power e.g. Seek Power/Etchings/BluePrints etc.")
print(powercount_by_deck_main_faction[powercount_by_deck_main_faction['count'] >= 3].sort_values('mean'))
# Contrbutor power vs. Effective power
power_by_player_subset = power_by_player_merged[power_by_player_merged['count_type'] >= 3]
plt.figure()
plt.scatter(power_by_player_subset['mean_type'].values, power_by_player_subset['mean_effective'].values, label=power_by_player_subset.index)
for name in power_by_player_subset.index:
plt.annotate(name, (power_by_player_subset.loc[name]['mean_type'], power_by_player_subset.loc[name]['mean_effective']))
plt.grid('on')
plt.xlabel('Power (type) cards')
plt.ylabel('Effective power')
plt.show()
# Plot amount of power
MIN_DECK = 10
deck_count_by_faction = df_7win_decks['MainFaction'].value_counts()
deck_power_by_faction = df_7win_decks.groupby('MainFaction')['EffectivePower'].value_counts().sort_index()
normalized_deck_power_by_faction = pd.DataFrame()
for faction, count in deck_count_by_faction.items():
if count >= MIN_DECK:
normalized_deck_power_by_faction[faction] = deck_power_by_faction.loc[faction] / (float(count)) * 100.0
first_color = eternal.plot.get_faction_colors([x[0] for x in normalized_deck_power_by_faction.columns])
second_color = eternal.plot.get_faction_colors([x[1] for x in normalized_deck_power_by_faction.columns])
ax = normalized_deck_power_by_faction.plot(grid='on', color=first_color, linewidth=6, alpha=0.5)
normalized_deck_power_by_faction.plot(grid='on', color=second_color, linewidth=1, ax=ax)
plt.ylabel('Percentage of decks')
plt.title('Effective power by deck main faction')
# ********** CARD-COST ANALYSIS **************
# Mean card cost by deck faction
all_cards[all_cards.Type != 'Power'].groupby('DeckMainFaction')['Cost'].mean()
# all_cards[ all_cards.Type != 'Power' ].boxplot( 'Cost', 'DeckMainFaction' ) # Box plot (not that informative)
# Plot curve by deck faction
MIN_DECK = 10
curve_by_faction = all_cards[all_cards.Type != 'Power'].groupby(['DeckMainFaction', 'Cost'])['Name'].count()
deck_count_by_faction = df_7win_decks['MainFaction'].value_counts()
normalized_curve_by_faction = pd.DataFrame()
for faction, count in deck_count_by_faction.items():
if count >= MIN_DECK:
normalized_curve_by_faction[faction] = curve_by_faction.loc[faction] / (float(count))
first_color = eternal.plot.get_faction_colors([x[0] for x in normalized_curve_by_faction.columns])
second_color = eternal.plot.get_faction_colors([x[1] for x in normalized_curve_by_faction.columns])
ax = normalized_curve_by_faction.plot(grid='on', color=first_color, linewidth=6, alpha=0.5)
normalized_curve_by_faction.plot(grid='on', color=second_color, linewidth=1, ax=ax)
plt.ylabel('Number of cards')
plt.title('Average curve by deck main faction')
print("**** Average card cost by deck main faction ****")
print("(for all main-faction pairs with at least {MIN_DECK} decks)".format(MIN_DECK=MIN_DECK))
print(all_cards[all_cards.Type != 'Power'].groupby('DeckMainFaction')['Cost'].mean()[normalized_curve_by_faction.columns].sort_values())
# Augment 7win list with average unit Attack / Health
df_unit_stats = df_7win_decks.Deck.apply(lambda x: x.unit_stats())
df_7win_decks['Attack'] = df_unit_stats.Attack
df_7win_decks['Health'] = df_unit_stats.Health
# Plot the unit-health by faction
units = all_cards[all_cards.Type == 'Unit'].copy()
units['Faction'] = units.Influence.apply(eternal.card.influence_to_faction)
units_health_by_faction = units.pivot_table(index='Faction', columns=['Health'], values='Name', aggfunc='count')
sorted_units_faction_by_health = units_health_by_faction.loc[units_health_by_faction.sum(axis=1).sort_values(ascending=False).index].transpose()
colors = eternal.plot.get_faction_colors(sorted_units_faction_by_health.columns)
sorted_units_faction_by_health.plot(kind='bar', stacked=True, grid=True, color=colors, legend=True)
##******** BEST AND WORST DECKS **************
all_cards['CountPerOffer'] = all_cards.index.map(card_counts['CountPerOffer'])
all_cards['CountPerOfferDeck'] = all_cards.index.map(card_counts['CountPerOfferDeck'])
best_decks = df_7win_decks.loc[all_cards.groupby('DeckId')['CountPerOfferDeck'].mean().nlargest(10).index]
worst_decks = df_7win_decks.loc[all_cards.groupby('DeckId')['CountPerOfferDeck'].mean().nsmallest(10).index]
def plot_contributor_faction_usage():
contributor_faction_counts = all_cards[all_cards.Type != 'Power'].groupby('Contributor')[['F', 'T', 'J', 'P', 'S']].sum()
contributor_faction_percent = contributor_faction_counts.div(contributor_faction_counts.sum(axis=1), axis=0)
contributor_faction_percent['count'] = contributor_faction_percent.index.map(df_7win_decks['Contributor'].value_counts())
contributor_faction_percent['deviation'] = (contributor_faction_percent[['F', 'T', 'J', 'P', 'S']] - 0.2).abs().sum(axis=1)
divergence = lambda x: scipy.stats.entropy(x.values, [0.2, 0.2, 0.2, 0.2, 0.2])
contributor_faction_percent['divergence'] = contributor_faction_percent[['F', 'T', 'J', 'P', 'S']].apply(divergence, axis=1)
contributor_faction_percent['top_faction_percent'] = (contributor_faction_percent[['F', 'T', 'J', 'P', 'S']]).max(axis=1)
contributor_faction_percent['top_faction'] = (contributor_faction_percent[['F', 'T', 'J', 'P', 'S']]).idxmax(axis=1)
subset = contributor_faction_percent[contributor_faction_percent['count'] >= 7]
plt.figure()
plt.plot(subset['divergence'], subset['top_faction_percent'], 'ob')
for name, data in subset.iterrows():
top_faction = data['top_faction']
color = eternal.plot.get_faction_colors(top_faction)
plt.annotate(f'{name} ({top_faction})', (data['divergence'], data['top_faction_percent']), color=color[0])
plt.grid('on')
plt.xlabel('Divergence (0 = generalize, 1.0 = specialist)')
plt.ylabel('Maximum faction (%)')
plt.title('Generalist vs. specialist')
def plot_inscribe_faction_usage(FACTION):
faction_cards = all_cards[(all_cards.Type != 'Power') & (all_cards.Influence.str.contains(FACTION))].copy()
faction_cards['IsInscribe'] = faction_cards.CardText.str.contains('<b>Inscribe</b>')
faction_cards_by_deck = faction_cards.groupby('DeckId')['IsInscribe']
faction_deck_stats = pd.DataFrame({'total': faction_cards_by_deck.count(), 'inscribe': faction_cards_by_deck.sum()})
faction_deck_stats['percent'] = faction_deck_stats['inscribe'] / faction_deck_stats['total'] * 100.0
plt.figure()
ax = plt.subplot(2, 1, 1)
faction_deck_stats.boxplot(column=['percent'], by=['total'], ax=ax)
plt.ylabel('Percent (%) Inscribe')
plt.xlabel(f'Number of {FACTION} cards')
plt.title(None)
ax = plt.subplot(2, 1, 2)
faction_deck_stats['total'].value_counts().sort_index().plot(kind='bar', ax=ax)
plt.grid('on')
plt.ylabel('Number of decks')
plt.xlabel(f'Number of {FACTION} cards')
# Plot the unit-health by faction
def plot_unit_health_by_faction():
plt.figure()
for i, COST in enumerate([3, 5]):
ax = plt.subplot(2, 1, i + 1)
stealth_units = all_cards[(all_cards.Type == 'Unit') & (all_cards.CardText.str.contains('<b>Stealth</b>')) & (all_cards.Cost == COST)].copy()
stealth_units['Faction'] = stealth_units.Influence.apply(eternal.card.influence_to_faction)
stealth_units_health_by_faction = stealth_units.pivot_table(index='Faction', columns=['Health'], values='Name', aggfunc='count')
sorted_stealth_units_faction_by_health = stealth_units_health_by_faction.loc[
stealth_units_health_by_faction.sum(axis=1).sort_values(ascending=False).index].transpose()
colors = eternal.plot.get_faction_colors(sorted_stealth_units_faction_by_health.columns)
sorted_stealth_units_faction_by_health.plot(kind='bar', stacked=True, grid=True, color=colors, legend=True, ax=ax)
plt.ylabel('Count of units')
plt.title('Health of {COST}-cost *Stealth* units'.format(COST=COST))
# Plot the main popularity over time
def plot_faction_popularity(faction_type='MainFaction', n_deck_window=100):
"""
Args:
faction_type: 'MainFaction', 'SplashFaction', or 'MainFaction + SplashFaction'
:return:
"""
plt.figure()
if faction_type == 'MainFaction':
deck_factions = df_7win_decks['MainFaction'].str
elif faction_type == 'SplashFaction':
deck_factions = df_7win_decks['SplashFaction'].str
elif faction_type == 'MainFaction + SplashFaction':
deck_factions = (df_7win_decks['SplashFaction'] + df_7win_decks['SplashFaction']).str
for faction in eternal.card.FACTIONS:
color = eternal.plot.get_faction_colors(faction)
plt.plot(deck_factions.contains(faction).rolling(n_deck_window).mean() * 100.0, color=color[0], label=faction)
average_n_factions = deck_factions.len().mean()
plt.legend()
plt.title(f'Rolling {n_deck_window}-deck average of {faction_type} popularity')
plt.grid('on')
plt.ylabel('Percentage of decks')
xlim = plt.xlim()
plt.plot(plt.xlim(), [average_n_factions / 5.0 * 100] * 2, '--', color=(0.5, 0.5, 0.5))
plt.xlim(xlim)
plt.ylim(0.0, plt.ylim()[1])
# Plot the faction popularity over time (multi-faction)
def plot_multifaction_popularity():
MIN_DECK = 10
N_DECK_WINDOW = 100
deck_count_by_faction = df_7win_decks['MainFaction'].value_counts()
deck_popularity_by_faction = pd.DataFrame()
for faction, count in deck_count_by_faction.items():
if count >= MIN_DECK:
deck_popularity_by_faction[faction] = (df_7win_decks['MainFaction'] == faction).rolling(N_DECK_WINDOW).mean() * 100.0
plt.figure()
faction_order = deck_popularity_by_faction.iloc[-1].sort_values(ascending=False).index
ax = plt.subplot(2, 1, 1)
df_popularity = deck_popularity_by_faction[faction_order[:5]]
first_color = eternal.plot.get_faction_colors([x[0] for x in df_popularity.columns])
second_color = eternal.plot.get_faction_colors([x[1] for x in df_popularity.columns])
df_popularity.plot(grid='on', color=first_color, linewidth=6, alpha=0.5, ax=ax)
df_popularity.plot(grid='on', color=second_color, linewidth=1, ax=ax)
plt.ylabel('Percentage of decks')
plt.title('Deck popularity (top 1-5 popular factions today)')
ax.get_legend().remove()
ylim = plt.ylim()
ax = plt.subplot(2, 1, 2)
df_popularity = deck_popularity_by_faction[faction_order[5:]]
first_color = eternal.plot.get_faction_colors([x[0] for x in df_popularity.columns])
second_color = eternal.plot.get_faction_colors([x[1] for x in df_popularity.columns])
df_popularity.plot(grid='on', color=first_color, linewidth=6, alpha=0.5, ax=ax)
df_popularity.plot(grid='on', color=second_color, linewidth=1, ax=ax)
plt.ylabel('Percentage of decks')
plt.title('Deck popularity (top 6-10 popular factions today)')
ax.get_legend().remove()
plt.ylim(ylim)
def power_sink_summary():
""""Analyze decks using Sketches or Rune"""
cards_sketches = CARDS_DATA[CARDS_DATA['Name'].str.endswith('Sketch')]
cards_runes = CARDS_DATA[CARDS_DATA['Name'].str.startswith('Rune of')]
cards_both = pd.concat([cards_runes, cards_sketches])
power_sink_summary = []
for id, sketch in cards_both.iterrows():
n_decks = all_cards[all_cards.index.isin([id])].DeckId.unique().size
power_sink_summary.append([sketch.Name, n_decks])
power_sink_summary.append(['Any Rune', all_cards[all_cards.index.isin(cards_runes.index)].DeckId.unique().size])
power_sink_summary.append(['Any Sketch', all_cards[all_cards.index.isin(cards_sketches.index)].DeckId.unique().size])
power_sink_summary.append(['Any Rune or Sketch', all_cards[all_cards.index.isin(cards_both.index)].DeckId.unique().size])
df_power_sink_summary = pd.DataFrame(power_sink_summary, columns=['Scenario', 'NumDecks'])
df_power_sink_summary['PercentageDecks'] = df_power_sink_summary['NumDecks'] / len(df_7win_decks) * 100.0
print("**** Percentage of decks containing power sinks (Sketches and/or Runes)****")
print(df_power_sink_summary)
def display_cards_in_contention(*args,
stats=['Name', 'PossibleDecks', 'OfferRate', 'Count', 'CountPerDeck', 'CountPerOffer', 'CountPerOfferDeck']):
"""
Args:
*args: One (or more) strings to use to search the names of cards to display (case insenstive)
stats: (optional) List of columns to display
"""
re_string = '|'.join(args)
print(card_counts[card_counts['Name'].str.contains(re_string, flags=re.IGNORECASE)][stats])
display_cards_in_contention('open', 'protector')
# Dump outputs
output_order = ['Faction', 'Count', 'PossibleDecks', 'CountPerDeck', 'SetNumber', 'EternalID', 'OfferRate', 'CountPerOffer', 'CountPerOfferDeck', 'Rarity',
'Type', 'Name', 'CardText', 'Cost', 'Influence', 'Attack', 'Health', 'ImageUrl', 'DetailsUrl', 'DeckBuildable', 'UnitType', 'MarketAccess']
card_counts[output_order].to_csv('card_counts.csv')
# Additional analysis
# plot_unit_health_by_faction()
plot_faction_popularity('MainFaction', 100)
plot_faction_popularity('SplashFaction', 100)
plot_contributor_faction_usage()
| 2.59375 | 3 |
InvenTree/part/migrations/0011_part_revision.py | ArakniD/InvenTree | 656 | 12767274 | # Generated by Django 2.2.2 on 2019-06-20 11:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('part', '0010_auto_20190620_2135'),
]
operations = [
migrations.AddField(
model_name='part',
name='revision',
field=models.CharField(blank=True, help_text='Part revision or version number', max_length=100),
),
]
| 1.453125 | 1 |
2016_IceCTF/a_strong_feeling_for_bruteforcing.py | kenoph/WriteUps | 2 | 12767275 | <gh_stars>1-10
#!/usr/bin/env python3
import subprocess
def run(txt):
return subprocess.run('./a_strong_feeling', input=txt, stdout=subprocess.PIPE).stdout
if __name__ == '__main__':
key = b''
for n in range(500):
res = dict()
for l in range(1, 128):
curr = key + bytes([l])
out = run(curr)
if out not in res:
res[out] = curr
else:
del res[out]
key = list(res.values())[0]
if key[-1] == 0x7F:
key = key[:-1]
break
print(key)
| 2.890625 | 3 |
annotate.py | mvasilkov/Makeup-Running | 1 | 12767276 | <gh_stars>1-10
#!/usr/bin/env python3
import html
import pathlib
import sys
import webbrowser
from makeup_running.parser import Makefile, LineType
def print_line(f, line_number, line_t) -> str:
line_type, line = line_t
class_name = 'target' if line_type == LineType.TARGET else 'recipe' if line_type == LineType.RECIPE else ''
target = f.target_from_line_number.get(line_number, None)
target_name = target.name if target is not None else ''
line_header = html.escape(f'{LineType(line_type).name} {target_name}')
return ''.join([
f'<tr title="{line_header}">',
f'<td class="LineType {class_name}">{line_header}</td>',
f'<td class="Makefile"><code>{html.escape(line)}</code></td>',
'</tr>',
])
def print_file(f) -> str:
tab = ['<table>']
for line_number, line in enumerate(f.lines):
tab.append(print_line(f, line_number, line))
tab.append('</table>')
return ''.join(tab)
def run(filename: str):
template = open('debug_files/base.html', encoding='utf-8').read()
f = Makefile(filename) if filename else Makefile()
template = template.replace('{{ contents }}', print_file(f))
with open('debug.html', 'w', encoding='utf-8', newline='\n') as outfile:
outfile.write(template)
webbrowser.open_new_tab(pathlib.Path('debug.html').resolve().as_uri())
if __name__ == '__main__':
argc = len(sys.argv)
if argc > 2:
sys.exit('Usage: annotate.py [Makefile]')
if argc == 2:
a = sys.argv[1]
else:
a = None
run(a)
| 2.84375 | 3 |
scripts/generate_inputs.py | marcullo/image-renderer | 0 | 12767277 | #!/usr/bin/env python3
import argparse
class Rectangle:
def __init__(self, x, y, w, h):
self.x = x
self.y = y
self.w = w
self.h = h
def __repr__(self):
return f'DRAW_RECTANGLE {self.x},{self.y},{self.w},{self.h}'
@staticmethod
def spawn(start, delta_x, delta_y, end_x, end_y):
print(f'SET_WIDTH {end_x}')
print(f'SET_HEIGHT {end_y}')
for x in range(start.x, end_x, delta_x):
for y in range(start.y, end_y, delta_y):
r = Rectangle(x, y, start.w, start.h)
print(str(r))
print(f'RENDER output.bmp')
class Triangle:
def __init__(self, x1, y1, x2, y2, x3, y3):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
self.x3 = x3
self.y3 = y3
def __repr__(self):
return f'DRAW_RECTANGLE {self.x1},{self.y1},{self.x2},{self.y2},{self.x3},{self.y3}'
def _parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('pattern', type=str, choices=['squared'], help='shape pattern')
parser.add_argument('--width', type=int, default=500, help='image width')
parser.add_argument('--height', type=int, default=500, help='image height')
parser.add_argument('--size', type=int, default=25, help='object size')
return parser.parse_args()
def generate_inputs(pattern, width, height, size):
if pattern == 'squared':
Rectangle.spawn(Rectangle(int(size / 2), int(size / 2), size, size), 2 * size, 2 * size, width, height)
if __name__ == '__main__':
args = _parse_args()
generate_inputs(args.pattern, args.width, args.height, args.size)
| 3.34375 | 3 |
final/one_time/reddit.py | Fabhi/sentiment-analysis | 1 | 12767278 | import json
from emotion import ProcessEmotions
f = open("reddit.json",encoding = 'utf-8')
loaded = json.load(f)
data = loaded["data"]["children"]
text = map(lambda x: x["data"]["title"], data)
res = map(ProcessEmotions, text)
for item in res:
if item:
for i in item:
if i["valid"]:
print(i["emotion"], i["valid"])
else:
print(i["emotion"], i["text"])
else:
print("No item") | 3.40625 | 3 |
songs/la-gran-jaime/pop.py | mathigatti/EP | 1 | 12767279 | <filename>songs/la-gran-jaime/pop.py<gh_stars>1-10
Root.default = -3
Scale.default = 'minor'
Clock.bpm=100
acordes = [(2,4,6),(-1,1,3),(0,2,4)]
escalera = P[5,4,3,2]
p1 >> space([0,0,4,2,0,0,5,2],dur=1,amp=[0,1,1,1])
d1 >> play("X ",amp=1)
pt >> play('#', dur=16,sus=4, rate=-1/2, amp=var([1,0],[16,inf],start=now))
p1 >> space([4,4,2,0,3,3,2,1],dur=1,amp=[0,1,1,1])
p1 >> space([0,0,4,2,0,0,5,2],dur=1,amp=[0,1,1,1])
b1 >> ambi([0,-2,4,3],dur=4,sus=3,oct=3,chop=3,amp=3)
v1 >> loop("verso",P[0:8],formant=0,amp=2,room=0.0,mix=0.0,glide=0,chop=0)
p1 >> space([4,4,2,0,3,3,2,1],dur=1,amp=[0,1,1,1])
v1 >> loop("verso",P[8:16],formant=0,amp=2,room=0.0,mix=0.0,glide=0,chop=0)
d3 >> play("-")
p1 >> space([0,0,4,2,0,0,5,2],dur=1,amp=[0,1,1,1])
v1 >> loop("verso",P[0:8],formant=2,amp=2,room=0.0,mix=0.0,glide=0,chop=0)
p1 >> space([4,4,2,0,3,3,2,1],dur=1,amp=[0,1,1,1])
v1 >> loop("verso",P[8:16],formant=2,amp=2,room=0.0,mix=0.0,glide=0,chop=0)
pt >> play('#', dur=16,sus=4, rate=-1/2, amp=var([1,0],[16,inf],start=now))
b1 >> ambi([0],dur=4,sus=2,oct=3,chop=3)
p1 >> space([(0,2,4)]*4,dur=2,amp=1)
p2 >> prophet([(0,2,4)]*4,dur=2,amp=0.5)
d1 >> play("X ",amp=1)
d3 >> play("-",dur=PSum(6,4))
b1 >> bass([2,-1,0,-2],dur=4,chop=2,sus=3,amp=0.7,oct=5)
n = 5
p2 >> prophet([(2,4,6)]*n+[(-1,1,3)]*n+[(0,2,4)]*n+[5,4,3,2],dur=list(PSum(n,4)[:n*3])+[1]*4,amp=[1,1,1,1]*3 + [1,1,1,1])
v1 >> loop("estribillo1_pablito_rack",P[0:8],formant=[0],amp=1)
v1 >> loop("estribillo1_pablito_rack",P[8:16],formant=[0],amp=1)
v1 >> loop("estribillo2_mathi_rack",P[0:8],formant=[0],amp=0.7)
v1 >> loop("estribillo2_mathi_rack",P[8:16],formant=[0],amp=0.7)
v1 >> loop("estribillo3_pablito_rack",P[0:8],formant=[0],amp=1)
v1 >> loop("estribillo3_pablito_rack",P[8:16],formant=[0],amp=1)
v1 >> loop("estribillo4_pablito_rack",P[0:8],formant=[0],amp=1)
v1 >> loop("estribillo4_pablito_rack",P[8:16],formant=[0],amp=1)
b1 >> bass([2],dur=4,chop=3,sus=2)
p1 >> space([(2,4,6)]*4,dur=2,amp=1)
p2 >> prophet([(2,4,6)]*4,dur=2,amp=1)
v1 >> loop('estribillo4_pablito_rack',P[0:8], formant=0,amp=1)
v2 >> loop('estribillo4_mathi_rack', P[8:16],formant=0, amp=0.5)
Group(v1,v2).solo()
| 2.234375 | 2 |
homeassistant/components/sql/sensor.py | davyike/core | 3 | 12767280 | """Sensor from an SQL Query."""
from __future__ import annotations
from datetime import date
import decimal
import logging
import sqlalchemy
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import scoped_session, sessionmaker
import voluptuous as vol
from homeassistant.components.recorder import CONF_DB_URL, DEFAULT_DB_FILE, DEFAULT_URL
from homeassistant.components.sensor import (
PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA,
SensorEntity,
)
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import CONF_NAME, CONF_UNIT_OF_MEASUREMENT, CONF_VALUE_TEMPLATE
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.device_registry import DeviceEntryType
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.template import Template
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from .const import CONF_COLUMN_NAME, CONF_QUERIES, CONF_QUERY, DB_URL_RE, DOMAIN
_LOGGER = logging.getLogger(__name__)
def redact_credentials(data: str) -> str:
"""Redact credentials from string data."""
return DB_URL_RE.sub("//****:****@", data)
_QUERY_SCHEME = vol.Schema(
{
vol.Required(CONF_COLUMN_NAME): cv.string,
vol.Required(CONF_NAME): cv.string,
vol.Required(CONF_QUERY): cv.string,
vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string,
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
}
)
PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend(
{vol.Required(CONF_QUERIES): [_QUERY_SCHEME], vol.Optional(CONF_DB_URL): cv.string}
)
async def async_setup_platform(
hass: HomeAssistant,
config: ConfigType,
async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the SQL sensor platform."""
_LOGGER.warning(
# SQL config flow added in 2022.4 and should be removed in 2022.6
"Configuration of the SQL sensor platform in YAML is deprecated and "
"will be removed in Home Assistant 2022.6; Your existing configuration "
"has been imported into the UI automatically and can be safely removed "
"from your configuration.yaml file"
)
default_db_url = DEFAULT_URL.format(
hass_config_path=hass.config.path(DEFAULT_DB_FILE)
)
for query in config[CONF_QUERIES]:
new_config = {
CONF_DB_URL: config.get(CONF_DB_URL, default_db_url),
CONF_NAME: query.get(CONF_NAME),
CONF_QUERY: query.get(CONF_QUERY),
CONF_UNIT_OF_MEASUREMENT: query.get(CONF_UNIT_OF_MEASUREMENT),
CONF_VALUE_TEMPLATE: query.get(CONF_VALUE_TEMPLATE),
CONF_COLUMN_NAME: query.get(CONF_COLUMN_NAME),
}
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data=new_config,
)
)
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up the SQL sensor entry."""
db_url: str = entry.options[CONF_DB_URL]
name: str = entry.options[CONF_NAME]
query_str: str = entry.options[CONF_QUERY]
unit: str | None = entry.options.get(CONF_UNIT_OF_MEASUREMENT)
template: str | None = entry.options.get(CONF_VALUE_TEMPLATE)
column_name: str = entry.options[CONF_COLUMN_NAME]
value_template: Template | None = None
if template is not None:
try:
value_template = Template(template)
value_template.ensure_valid()
except TemplateError:
value_template = None
if value_template is not None:
value_template.hass = hass
try:
engine = sqlalchemy.create_engine(db_url)
sessmaker = scoped_session(sessionmaker(bind=engine))
except SQLAlchemyError as err:
_LOGGER.error("Can not open database %s", {redact_credentials(str(err))})
return
# MSSQL uses TOP and not LIMIT
if not ("LIMIT" in query_str.upper() or "SELECT TOP" in query_str.upper()):
query_str = (
query_str.replace("SELECT", "SELECT TOP 1")
if "mssql" in db_url
else query_str.replace(";", " LIMIT 1;")
)
async_add_entities(
[
SQLSensor(
name,
sessmaker,
query_str,
column_name,
unit,
value_template,
entry.entry_id,
)
],
True,
)
class SQLSensor(SensorEntity):
"""Representation of an SQL sensor."""
_attr_icon = "mdi:database-search"
def __init__(
self,
name: str,
sessmaker: scoped_session,
query: str,
column: str,
unit: str | None,
value_template: Template | None,
entry_id: str,
) -> None:
"""Initialize the SQL sensor."""
self._attr_name = name
self._query = query
self._attr_native_unit_of_measurement = unit
self._template = value_template
self._column_name = column
self.sessionmaker = sessmaker
self._attr_extra_state_attributes = {}
self._attr_unique_id = entry_id
self._attr_device_info = DeviceInfo(
entry_type=DeviceEntryType.SERVICE,
identifiers={(DOMAIN, entry_id)},
manufacturer="SQL",
name=name,
)
def update(self) -> None:
"""Retrieve sensor data from the query."""
data = None
self._attr_extra_state_attributes = {}
sess: scoped_session = self.sessionmaker()
try:
result = sess.execute(self._query)
except SQLAlchemyError as err:
_LOGGER.error(
"Error executing query %s: %s",
self._query,
redact_credentials(str(err)),
)
return
_LOGGER.debug("Result %s, ResultMapping %s", result, result.mappings())
for res in result.mappings():
_LOGGER.debug("result = %s", res.items())
data = res[self._column_name]
for key, value in res.items():
if isinstance(value, decimal.Decimal):
value = float(value)
if isinstance(value, date):
value = value.isoformat()
self._attr_extra_state_attributes[key] = value
if data is not None and self._template is not None:
self._attr_native_value = (
self._template.async_render_with_possible_json_value(data, None)
)
else:
self._attr_native_value = data
if data is None:
_LOGGER.warning("%s returned no results", self._query)
sess.close()
| 2.078125 | 2 |
packages/w3af/w3af/core/data/kb/kb_url_extensions.py | ZooAtmosphereGroup/HelloPackages | 0 | 12767281 | <gh_stars>0
"""
kb_url_extensions.py
Copyright 2019 <NAME>
This file is part of w3af, http://w3af.org/ .
w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
w3af is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with w3af; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
import w3af.core.data.kb.knowledge_base as kb
def get_url_extensions_from_kb():
"""
:return: A set with all the URL filename extensions that have been found
during the scan. This is useful to reduce the number of HTTP
requests which are sent during URL brute-forcing.
For example, when a site only has aspx, js, css and png extensions
a plugin might get that information using get_url_extensions_from_kb()
and decide that it won't perform URL brute-forcing for php extensions.
"""
all_extensions = set()
all_urls = kb.kb.get_all_known_urls()
for url in all_urls:
all_extensions.add(url.get_extension())
return all_extensions
| 1.773438 | 2 |
sodium/yolo/__init__.py | Keerthi001/PySodium | 3 | 12767282 | from .yolo import YoloOpenCV
| 1.023438 | 1 |
api/resources/video.py | melonmanchan/gachimuch.io-api | 0 | 12767283 | <gh_stars>0
__author__ = 'matti'
from common.database import db
import datetime
from flask import jsonify
from flask_restful import Resource
from models.video import VideoModel
class Video(Resource):
def get(self, videoid):
video = VideoModel.query.get_or_404(videoid)
video.views += 1
db.session.add(video)
db.session.commit()
resp = {'video': video.tojson()}
return jsonify(resp)
def post(self):
video = VideoModel('title', 'desc', '12312445', 'http://asd123.com', datetime.datetime.now(),
datetime.datetime.now())
db.session.add(video)
db.session.commit()
return 200
| 2.65625 | 3 |
Generate_Synthetic_Data/render_fcns.py | saeedmhz/Sarc-Graph | 1 | 12767284 | import numpy as np
import matplotlib.pyplot as plt
import os
import cv2
from scipy.ndimage import gaussian_filter, median_filter
from matplotlib.animation import FuncAnimation
from perlin_noise import PerlinNoise
##########################################################################################
# FUNCTIONS FOR RENDERING I.E. GO FROM GEOMETRY TO FINAL IMAGES
##########################################################################################
# function: z_disk_props
# function: sarc_list_in_slice_fcn
# function: return_x_y_z_mat
# function: point_in_cyl
# function: binary_box
# function: slice_to_matrix
# function: matrix_gaussian_blur_fcn
# function: matrix_median_blur_fcn
# function: random_val
# function: cloud_image
# function: matrix_to_image
# function: add_perlin_noise
# function: save_img_stil
# function: still_to_avi
# function: ground_truth_movie
##########################################################################################
##########################################################################################
def z_disk_props( sarc_list, is_normal_radius, is_normal_height, avg_radius, avg_height, parameter_radius, parameter_height):
"""Create z disk properties, z disks are modeled as cylinders with radius R and height H. Once cylinder per sarcomere (s1)."""
radius_list = []
height_list = []
for kk in range(0,len(sarc_list)):
if is_normal_radius:
rad = avg_radius + np.random.normal(0,parameter_radius)
else:
rad = avg_radius + (np.random.random(1)[0] - .5) * parameter_radius * 2.0
if is_normal_height:
hei = avg_height + np.random.normal(0,parameter_height)
else:
hei = avg_height + (np.random.random(1)[0] - .5) * parameter_height * 2.0
radius_list.append(rad)
height_list.append(hei)
return radius_list, height_list
##########################################################################################
def sarc_list_in_slice_fcn(sarc_list, radius_list, height_list, z_lower, z_upper):
"""Check to see if sarcomere is within a slice in the z dimension."""
sarc_list_in_slice = []
radius_list_in_slice = []
height_list_in_slice = []
num_sarc = len(sarc_list)
for kk in range(0,num_sarc):
z = 0.5*( sarc_list[kk][0][2] + sarc_list[kk][1][2] )
if z > z_lower and z < z_upper:
sarc_list_in_slice.append(sarc_list[kk])
radius_list_in_slice.append(radius_list[kk])
height_list_in_slice.append(height_list[kk])
return sarc_list_in_slice, radius_list_in_slice, height_list_in_slice
##########################################################################################
def return_x_y_z_mat(matrix, x_lower, x_upper, y_lower, y_upper, z_lower, z_upper):
"""Helper function that returns the X, Y, and Z coordinates of a matrix."""
matrix_X = np.zeros(matrix.shape)
matrix_Y = np.zeros(matrix.shape)
matrix_Z = np.zeros(matrix.shape)
num_x = matrix.shape[0]
num_y = matrix.shape[1]
num_z = matrix.shape[2]
for ii in range(0,num_x):
for jj in range(0,num_y):
for kk in range(0,num_z):
matrix_X[ii,jj,kk] = ii / num_x * (x_upper - x_lower) + x_lower
matrix_Y[ii,jj,kk] = jj / num_y * (y_upper - y_lower) + y_lower
matrix_Z[ii,jj,kk] = kk / num_z * (z_upper - z_lower) + z_lower
return matrix_X, matrix_Y, matrix_Z
##########################################################################################
def point_in_cyl(pt_x,pt_y,pt_z,cyl_p1,cyl_p2,cyl_rad):
"""Helper function that returns 1 if a point is inside a cylinder, 0 otherwise."""
q = np.asarray([pt_x,pt_y,pt_z])
p1 = np.asarray([cyl_p1[0],cyl_p1[1],cyl_p1[2]])
p2 = np.asarray([cyl_p2[0],cyl_p2[1],cyl_p2[2]])
check_1 = np.dot(q-p1,p2-p1)
check_2 = np.dot(q-p2,p2-p1)
if check_1 >=0 and check_2 <= 0:
rad = np.linalg.norm(np.cross( q-p1, p2-p1 )) / np.linalg.norm(p2-p1)
if rad <= cyl_rad:
return 1
else:
return 0
else:
return 0
##########################################################################################
def binary_box(matrix_X,matrix_Y,matrix_Z,cyl_p1,cyl_p2,cyl_rad):
"""Helper function that returns a binary matrix if the point is inside the cylinder."""
num_x = matrix_X.shape[0]
num_y = matrix_Y.shape[1]
num_z = matrix_Z.shape[2]
bin_box = np.zeros((num_x,num_y,num_z))
for ii in range(0,num_x):
for jj in range(0,num_y):
for kk in range(0,num_z):
x = matrix_X[ii,jj,kk]
y = matrix_Y[ii,jj,kk]
z = matrix_Z[ii,jj,kk]
bin_box[ii,jj,kk] = point_in_cyl(x,y,z,cyl_p1,cyl_p2,cyl_rad)
return bin_box
##########################################################################################
def slice_to_matrix(sarc_list,dim_x,dim_y,dim_z,x_lower,x_upper,y_lower,y_upper,z_lower,z_upper, mean_rad, mean_hei, bound_x, bound_y, bound_z, val):
"""Create a 3D matrix where each sarcomere is represented as voxels."""
matrix = np.zeros((dim_x,dim_y,dim_z))
matrix_X, matrix_Y, matrix_Z = return_x_y_z_mat(matrix, x_lower, x_upper, y_lower, y_upper, z_lower, z_upper)
# for each, only add s1 (adding s2 would be redundant)
num_sarc = len(sarc_list)
for kk in range(0,num_sarc):
s1 = sarc_list[kk][0]
s1 = np.asarray([s1[0],s1[1],s1[2]])
s2 = sarc_list[kk][1]
s2 = np.asarray([s2[0],s2[1],s2[2]])
vec = (s2 - s1) / np.linalg.norm(s2-s1)
rad = mean_rad[kk]
hei = mean_hei[kk]
p1 = s1 + vec * hei/2.0
p2 = s1 - vec * hei/2.0
cent_x = int((s1[0] - x_lower)/(x_upper-x_lower) * dim_x)
cent_y = int((s1[1] - y_lower)/(y_upper-y_lower) * dim_y)
cent_z = int((s1[2] - z_lower)/(z_upper-z_lower) * dim_z)
lower_x = np.max([cent_x - bound_x, 0])
upper_x = np.min([cent_x + bound_x, dim_x-1])
lower_y = np.max([cent_y - bound_y, 0])
upper_y = np.min([cent_y + bound_y, dim_y-1])
lower_z = np.max([cent_z - bound_z, 0])
upper_z = np.min([cent_z + bound_z, dim_z-1])
mm_x = matrix_X[lower_x:upper_x,lower_y:upper_y,lower_z:upper_z]
mm_y = matrix_Y[lower_x:upper_x,lower_y:upper_y,lower_z:upper_z]
mm_z = matrix_Z[lower_x:upper_x,lower_y:upper_y,lower_z:upper_z]
bin_box = binary_box(mm_x,mm_y,mm_z,p1,p2,rad)
matrix[lower_x:upper_x,lower_y:upper_y,lower_z:upper_z] += bin_box*val
if kk == num_sarc - 1:
s1 = sarc_list[kk][0]
s1 = np.asarray([s1[0],s1[1],s1[2]])
s2 = sarc_list[kk][1]
s2 = np.asarray([s2[0],s2[1],s2[2]])
vec = (s2 - s1) / np.linalg.norm(s2-s1)
rad = mean_rad[kk]
hei = mean_hei[kk]
p1 = s2 + vec * hei/2.0
p2 = s2 - vec * hei/2.0
cent_x = int((s1[0] - x_lower)/(x_upper-x_lower) * dim_x)
cent_y = int((s1[1] - y_lower)/(y_upper-y_lower) * dim_y)
cent_z = int((s1[2] - z_lower)/(z_upper-z_lower) * dim_z)
lower_x = np.max([cent_x - bound_x, 0])
upper_x = np.min([cent_x + bound_x, dim_x-1])
lower_y = np.max([cent_y - bound_y, 0])
upper_y = np.min([cent_y + bound_y, dim_y-1])
lower_z = np.max([cent_z - bound_z, 0])
upper_z = np.min([cent_z + bound_z, dim_z-1])
mm_x = matrix_X[lower_x:upper_x,lower_y:upper_y,lower_z:upper_z]
mm_y = matrix_Y[lower_x:upper_x,lower_y:upper_y,lower_z:upper_z]
mm_z = matrix_Z[lower_x:upper_x,lower_y:upper_y,lower_z:upper_z]
bin_box = binary_box(mm_x,mm_y,mm_z,p1,p2,rad)
matrix[lower_x:upper_x,lower_y:upper_y,lower_z:upper_z] += bin_box*val
return matrix
##########################################################################################
def matrix_gaussian_blur_fcn(matrix,sig):
"""Function to apply gaussian blur to the matrix that represents sarcomeres as voxels."""
matrix_blur = gaussian_filter(matrix, sigma=sig)
return matrix_blur
##########################################################################################
def matrix_median_blur_fcn(matrix,size):
"""Function to apply median blur to the matrix that represents sarcomeres as voxels."""
matrix_blur = median_filter(matrix_blur, size=size)
return matrix_blur
##########################################################################################
def random_val(matrix,mean,std):
"""Function to apply normally distributed random noise to the matrix that represents sarcomeres as voxels."""
mat = np.random.normal(mean,std,matrix.shape)
matrix += mat
return matrix
##########################################################################################
def cloud_image(a,b,x0,y0,matrix,val):
for ii in range(0,matrix.shape[0]):
for jj in range(0,matrix.shape[1]):
for kk in range(0,matrix.shape[2]):
if ((ii-x0)/a)**2.0 + ((jj - y0)/b)**2.0 < 1:
matrix[ii,jj,kk] += val*10
return matrix
##########################################################################################
def matrix_to_image(matrix,slice_lower,slice_upper):
"""Convert the 3D matrix into a projected 2D image matrix."""
matrix = matrix[:,:,slice_lower:slice_upper]
image = np.sum(matrix,axis=2)
return image
##########################################################################################
def add_perlin_noise(image,octaves,mag_ratio):
"""Add Perlin noise to the image."""
noise = PerlinNoise(octaves,seed=777)
pix0 = image.shape[0]; pix1 = image.shape[1]
pic = [[noise([i/pix0, j/pix1]) for j in range(pix0)] for i in range(pix1)]
# make perlin noise from range 0-1
pic = (pic - np.min(pic)) / (np.max(pic) - np.min(pic))
max_image = np.max(image)
image_with_noise = image + pic * max_image * mag_ratio
return image_with_noise
##########################################################################################
def save_img_stills(image_list,folder_name):
"""Save image stills with correct matplotlib settings."""
folder_name_render = folder_name + '/render'
if not os.path.exists(folder_name_render):
os.makedirs(folder_name_render)
num_images = len(image_list)
for step in range(0,num_images):
image = image_list[step]
plt.figure()
plt.imshow(image)
plt.axis('off')
ax = plt.gca()
ax.set_xticks([]); ax.set_yticks([])
if step < 10:
plt.savefig(folder_name_render + '/frame_00%i.png'%(step),bbox_inches = 'tight',transparent=True,pad_inches = 0)
elif step < 100:
plt.savefig(folder_name_render + '/frame_0%i.png'%(step),bbox_inches = 'tight',transparent=True,pad_inches = 0)
else:
plt.savefig(folder_name_render + '/frame_%i.png'%(step),bbox_inches = 'tight',transparent=True,pad_inches = 0)
plt.close()
return
##########################################################################################
def still_to_avi(folder_name,num_frames,is_GT):
"""Convert still images to an avi."""
folder_name_render = folder_name + '/render'
if is_GT == True:
video_name = folder_name + '/ground_truth_movie/GT_' + folder_name + '.avi'
else:
video_name = folder_name + '/' + folder_name + '.avi'
img_list = []
for kk in range(0,num_frames):
if kk < 10:
fname = 'frame_00%i.png'%(kk)
elif kk < 100:
fname = 'frame_0%i.png'%(kk)
else:
fname = 'frame_%i.png'%(kk)
img_list.append(fname)
images = [img for img in img_list]
if is_GT == True:
frame = cv2.imread(os.path.join(folder_name + '/ground_truth_movie', images[0]))
else:
frame = cv2.imread(os.path.join(folder_name + '/render', images[0]))
height, width, layers = frame.shape
video = cv2.VideoWriter(video_name, 0, 30, (width,height))
for image in images:
if is_GT == True:
video.write(cv2.imread(os.path.join(folder_name + '/ground_truth_movie', image)))
else:
video.write(cv2.imread(os.path.join(folder_name + '/render', image)))
cv2.destroyAllWindows()
video.release()
return
##########################################################################################
def ground_truth_movie(folder_name,num_frames,img_list,sarc_array_normalized, x_pos_array, y_pos_array,x_lower,x_upper,y_lower,y_upper,dim_x,dim_y):
"""Make the ground truth movie from the geometry."""
folder_name_GT = folder_name + '/ground_truth_movie'
if not os.path.exists(folder_name_GT):
os.makedirs(folder_name_GT)
all_normalized = sarc_array_normalized
color_matrix = np.zeros(all_normalized.shape)
for kk in range(0,all_normalized.shape[0]):
for jj in range(0,all_normalized.shape[1]):
of = all_normalized[kk,jj]
if of < -.2:
color_matrix[kk,jj] = 0
elif of > .2:
color_matrix[kk,jj] = 1
else:
color_matrix[kk,jj] = of*2.5 + .5
for t in range(0,num_frames):
img = img_list[t]
plt.figure()
plt.imshow(img)
for kk in range(0,all_normalized.shape[0]):
col = (1 - color_matrix[kk,t], 0, color_matrix[kk,t])
yy = (y_pos_array[kk,t] - y_lower)/(y_upper-y_lower)*dim_y
xx = (x_pos_array[kk,t] - x_lower)/(x_upper-x_lower)*dim_x
plt.plot(yy,xx,'.',c=col)
ax = plt.gca()
ax.set_xticks([]); ax.set_yticks([])
plt.axis('off')
if t < 10:
plt.savefig(folder_name_GT + '/frame_00%i.png'%(t),bbox_inches = 'tight',transparent=True,pad_inches = 0)
elif t < 100:
plt.savefig(folder_name_GT + '/frame_0%i.png'%(t),bbox_inches = 'tight',transparent=True,pad_inches = 0)
else:
plt.savefig(folder_name_GT + '/frame_%i.png'%(t),bbox_inches = 'tight',transparent=True,pad_inches = 0)
plt.close()
return
| 2.484375 | 2 |
ex019.py | ranierelm/Python_exercise | 0 | 12767285 | import random
a1 = input('Primeiro aluno: ')
a2 = input('Segundo aluno: ')
a3 = input('Terceiro aluno: ')
a4 = input('Quarto aluno: ')
sorteio = [a1,a2,a3,a4]
random.shuffle(sorteio)
#Shuffle (embaralha lista)
#Choice (Escolhe 1 da lista)
print(f'Ordem de apresentação: {sorteio}')
| 3.609375 | 4 |
spresso/utils/crypto.py | lujung/python-spresso | 0 | 12767286 | """This module provides the necessary cryptographic primitives for the system.
It is based on the `cryptography <https://cryptography.io/en/latest/>`_
package."""
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
def encrypt_aes_gcm(key, iv, plaintext, associated_data=b""):
"""
Method for encrypting AES-GCM
:param key: byte
:param plaintext: byte
:param associated_data: byte
:param iv: byte
:return: byte, byte
"""
#: Construct an AES-GCM Cipher object with the given key and a
#: randomly generated IV.
encryptor = Cipher(
algorithms.AES(key),
modes.GCM(iv),
backend=default_backend()
).encryptor()
#: Associated_data will be authenticated but not encrypted,
#: it must also be passed in on decryption.
encryptor.authenticate_additional_data(associated_data)
#: Encrypt the plaintext and get the associated cipher text.
#: GCM does not require padding.
cipher_text = encryptor.update(plaintext) + encryptor.finalize()
return cipher_text, encryptor.tag
def decrypt_aes_gcm(key, iv, auth_tag, cipher_text, associated_data=b""):
"""Method to decrypt AES in GCM mode.
Constructs a :class:`Cipher <cryptography.hazmat.primitives.ciphers.Cipher>`
object from key, iv and authentication tag. The associated data is passed in
during decryption.
Args:
key (bytes): The symmetric key used during decryption.
iv (bytes): The initialisation vector used during decryption.
auth_tag (bytes): The authentication tag used during decryption.
cipher_text (bytes): Cipher text to decrypt.
associated_data (bytes): Additional authentication data that was passed
in during encryption.
Returns:
bytes: The decrypted cipher text as bytes.
Raises:
InvalidTag: The authentication tag in combination with the given
parameters is invalid.
"""
decryptor = Cipher(
algorithms.AES(key),
modes.GCM(iv, auth_tag),
backend=default_backend()
).decryptor()
decryptor.authenticate_additional_data(associated_data)
plaintext = decryptor.update(cipher_text) + decryptor.finalize()
return plaintext
def create_signature(private_key, data):
"""
Create PKCS#1 signature using SHA256.
:param private_key: byte
:param data: byte
:return: byte
"""
private_key = serialization.load_pem_private_key(
private_key,
password=None,
backend=default_backend()
)
signer = private_key.signer(
padding.PKCS1v15(),
hashes.SHA256()
)
signer.update(data)
signed_data = signer.finalize()
return signed_data
def verify_signature(public_key, signature, data):
"""
Verify PKCS#1 signature using SHA256.
Raises an InvalidSignature Exception on failure.
:param public_key: byte
:param signature: byte
:param data: byte
:return:
"""
public_key = serialization.load_pem_public_key(
public_key,
backend=default_backend()
)
verifier = public_key.verifier(
signature,
padding.PKCS1v15(),
hashes.SHA256()
)
verifier.update(data)
verifier.verify()
| 3.203125 | 3 |
core/testIMain.py | xrami/Door-Interactive | 0 | 12767287 | #!/usr/bin/env python3
# Test Interactive
import datetime
from core import config,raiDB,SMSInteractive
input = True
doorType = 'glass'
print(datetime.datetime.now())
databaseInteractive.interactive(input,doorType)
#SMSInteractive.interactive(input)
| 2.15625 | 2 |
pandemik/Polymod.py | autonomio/pandemik | 4 | 12767288 | _url = 'https://raw.githubusercontent.com/mikkokotila/version-controlled-data/master/data/polymod_social_contact_data.csv'
class Polymod:
def __init__(self, data=None):
import pandas as _pd
self.data = _pd.read_csv(_url)
def country_data(self, country_code='fi'):
# get the country columns to drop it before return
cols = []
for col in self.data.columns:
if 'country_' in col:
cols.append(col)
return p.data[p.data['country_' + country_code] == 1].drop(cols, 1)
def _build_population(self,
population_size,
age_distribution=[15, 65, 20]):
'''Returns a population expressed as a 1d array where
each record is a member of the population.'''
import numpy as np
self.population = np.random.choice([1, 2, 3], size=population_size, p=np.array(age_distribution) / 100)
def _build_contacts(self, data, probabilities=False):
'''Returns participant level daily contact record
in absolute values or probabilities.'''
temp = data.copy(deep=True)
temp = temp.groupby('participant_id').sum()
cols = ['contact_home',
'contact_work',
'contact_school',
'contact_transport',
'contact_leisure',
'contact_other']
temp = temp[cols]
if probabilities:
temp['contact_total'] = temp.sum(axis=1)
for col in cols:
temp[col] = temp[col] / temp['contact_total']
return temp.dropna()
def _build_age_groups(self, country_code):
country_data = self.country_data(country_code)
country_data['0-14'] = country_data.participant_age.between(0, 14).astype(int)
country_data['15-64'] = country_data.participant_age.between(15, 64).astype(int)
country_data['65-100'] = country_data.participant_age.between(64, 100).astype(int)
self.age_young = country_data[country_data.participant_age.between(0, 14)]
self.age_adult = country_data[country_data.participant_age.between(15, 64)]
self.age_elderly = country_data[country_data.participant_age.between(64, 100)]
def raw_daily_contacts(self, country_code='fi', probabilities=False):
self._build_age_groups(country_code)
if probabilities:
young = self._build_contacts(self.age_young, True).values
adult = self._build_contacts(self.age_adult, True).values
elderly = self._build_contacts(self.age_elderly, True).values
else:
young = self._build_contacts(self.age_young).values
adult = self._build_contacts(self.age_adult).values
elderly = self._build_contacts(self.age_elderly).values
return young, adult, elderly
def total_daily_contacts(self,
population_size=1000,
country_code='fi',
multiplier=1,
age_distribution=[15, 65, 20],
restrictions=[0,0,0,0,0,0]):
import random
import numpy as np
restrictions = np.array(restrictions)
self._build_age_groups(country_code)
self._build_population(population_size=population_size, age_distribution=age_distribution)
out = []
young = (self.population == 1).sum() * multiplier
adult = (self.population == 2).sum() * multiplier
elderly = (self.population == 3).sum() * multiplier
young_picks = self._build_contacts(self.age_young).values * (1 - restrictions)
adult_picks = self._build_contacts(self.age_adult).values * (1 - restrictions)
elderly_picks = self._build_contacts(self.age_elderly).values * (1 - restrictions)
out = random.choices(young_picks.tolist(), k=young)
out += random.choices(adult_picks.tolist(), k=adult)
out += random.choices(elderly_picks.tolist(), k=elderly)
return [int(i) for i in np.array(out).sum(0)]
p = Polymod()
| 3.453125 | 3 |
watering-plants-ii/watering-plants-ii.py | jurayev/data-structures-algorithms-solutions | 0 | 12767289 | <gh_stars>0
class Solution:
def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:
"""
[2,2,4,3,3] A = 5, B = 5 cans = 1
1
2
[1,2,4,4,5] A = 6, B = 2 cans = 3
0,3 1,1 (c-(sum%c))
"""
n = len(plants)
i, j = 0, n-1
cap_a, cap_b = capacityA, capacityB
cans_used = 0 # 1
while i < j:
cans_used += cap_a < plants[i]
cans_used += cap_b < plants[j]
cap_a = cap_a if cap_a >= plants[i] else capacityA
cap_b = cap_b if cap_b >= plants[j] else capacityB
cap_a -= plants[i]
cap_b -= plants[j]
i += 1
j -= 1
if i == j:
max_water = max(cap_a, cap_b)
cans_used += max_water < plants[i]
return cans_used | 3.234375 | 3 |
db/fixUnFormatedData.py | yankj12/interview | 0 | 12767290 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
转换以下字段的格式
birth yyyy/MM
graduateMonth yyyy/MM
firstJobBeginMonth yyyy/MM
firstPhoneCallTime yyyy-MM-dd HH:mm:ss
firstInterviewTime yyyy-MM-dd HH:mm:ss
secondInterviewTime yyyy-MM-dd HH:mm:ss
'''
__author__ = 'yankj12'
from pymongo import MongoClient
#from bson.objectid import ObjectId
from myutil.Properties import Properties
from myutil.DateTransUtil import DateTransUtil
import urllib
import re
# 读取properties的配置文件
dictProperties = Properties("db.properties").getProperties()
# print dictProperties
print '加载配置文件结束'
user = dictProperties['user']
pwd = <PASSWORD>['password']
server = dictProperties['ip']
port = dictProperties['port']
db_name = dictProperties['dbUserDefined']
user = urllib.quote_plus(user)
pwd = urllib.quote_plus(pwd)
uri = 'mongodb://' + user + ':' + pwd + '@' + server + ':' + port + '/'+ db_name
client = MongoClient(uri)
db = client.manage
# 因为要处理所有的数据,所以要遍历所有的数据
interview_set = db.Interview
'''
格式化字段 yyyy/MM
'''
def format_year_month(interview_set, field):
for i in interview_set.find({field: {'$exists': True}}):
# print(i)
if i[field] and i[field] != '':
o_id = i['_id']
format_str = DateTransUtil.trans_year_month_format(i[field])
interview_set.update({'_id': o_id}, {"$set": {field: format_str}})
'''
格式化字段 yyyy - MM - dd HH:mm:ss
'''
def format_date_time(interview_set, field):
for i in interview_set.find({field: {'$exists': True}}):
# print(i)
if i[field] and i[field] != '':
o_id = i['_id']
format_str = DateTransUtil.trans_date_time_format(i[field])
interview_set.update({'_id': o_id}, {"$set": {field: format_str}})
# 格式化 birth yyyy/MM
format_year_month(interview_set, 'birth')
# 格式化 graduateMonth yyyy/MM
format_year_month(interview_set, 'graduateMonth')
# 格式化 firstJobBeginMonth yyyy/MM
format_year_month(interview_set, 'firstJobBeginMonth')
format_date_time(interview_set, 'firstPhoneCallTime')
format_date_time(interview_set, 'firstInterviewTime')
format_date_time(interview_set, 'secondInterviewTime')
print '数据修正结束'
| 2.890625 | 3 |
app/app/urls.py | rikkt0r/django-organiser | 0 | 12767291 | <gh_stars>0
# https://docs.djangoproject.com/en/1.8/topics/http/urls/
from django.conf.urls import include, url
from django.contrib import admin
handler404 = 'app.views.error404'
handler500 = 'app.views.error500'
urlpatterns = [
url(r'^$', 'tasks.views.index', name='index'),
url(r'^admin/', include(admin.site.urls)),
url(r'^about/', include('about.urls', namespace='about')),
url(r'^users/', include('users.urls', namespace='users')),
url(r'^tasks/', include('tasks.urls', namespace='tasks')),
url(r'^user/(?P<username>\w+)/$', 'tasks.views.tasks_user', name='tasks_user')
]
| 1.976563 | 2 |
CIM14/CPSM/StateVariables/StateVariables/TopologicalIsland.py | MaximeBaudette/PyCIM | 58 | 12767292 | <gh_stars>10-100
# Copyright (C) 2010-2011 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from CIM14.CPSM.StateVariables.Element import Element
class TopologicalIsland(Element):
"""An electrically connected subset of the network. Topological islands can change as the current network state changes (i.e. switch or Terminal.connected status changes).
"""
def __init__(self, AngleRef_TopologicalNode=None, TopologicalNodes=None, *args, **kw_args):
"""Initialises a new 'TopologicalIsland' instance.
@param AngleRef_TopologicalNode: The angle reference for the island. Normally there is one TopologicalNode that is selected as the angle reference for each island. Other reference schemes exist, so the association is optional.
@param TopologicalNodes: A topological node belongs to a topological island
"""
self._AngleRef_TopologicalNode = None
self.AngleRef_TopologicalNode = AngleRef_TopologicalNode
self._TopologicalNodes = []
self.TopologicalNodes = [] if TopologicalNodes is None else TopologicalNodes
super(TopologicalIsland, self).__init__(*args, **kw_args)
_attrs = []
_attr_types = {}
_defaults = {}
_enums = {}
_refs = ["AngleRef_TopologicalNode", "TopologicalNodes"]
_many_refs = ["TopologicalNodes"]
def getAngleRef_TopologicalNode(self):
"""The angle reference for the island. Normally there is one TopologicalNode that is selected as the angle reference for each island. Other reference schemes exist, so the association is optional.
"""
return self._AngleRef_TopologicalNode
def setAngleRef_TopologicalNode(self, value):
if self._AngleRef_TopologicalNode is not None:
self._AngleRef_TopologicalNode._AngleRef_TopologicalIsland = None
self._AngleRef_TopologicalNode = value
if self._AngleRef_TopologicalNode is not None:
self._AngleRef_TopologicalNode.AngleRef_TopologicalIsland = None
self._AngleRef_TopologicalNode._AngleRef_TopologicalIsland = self
AngleRef_TopologicalNode = property(getAngleRef_TopologicalNode, setAngleRef_TopologicalNode)
def getTopologicalNodes(self):
"""A topological node belongs to a topological island
"""
return self._TopologicalNodes
def setTopologicalNodes(self, value):
for x in self._TopologicalNodes:
x.TopologicalIsland = None
for y in value:
y._TopologicalIsland = self
self._TopologicalNodes = value
TopologicalNodes = property(getTopologicalNodes, setTopologicalNodes)
def addTopologicalNodes(self, *TopologicalNodes):
for obj in TopologicalNodes:
obj.TopologicalIsland = self
def removeTopologicalNodes(self, *TopologicalNodes):
for obj in TopologicalNodes:
obj.TopologicalIsland = None
| 1.757813 | 2 |
code/huxt_inputs.py | University-of-Reading-Space-Science/GeoModelUncertainty | 0 | 12767293 | <reponame>University-of-Reading-Space-Science/GeoModelUncertainty<gh_stars>0
import httplib2
import urllib
import huxt as H
import os
from pyhdf.SD import SD, SDC
import numpy as np
import astropy.units as u
from scipy.io import netcdf
def get_MAS_boundary_conditions(cr=np.NaN, observatory='', runtype='', runnumber='', verbose=True):
"""
A function to grab the Vr and Br boundary conditions from MHDweb. An order
of preference for observatories is given in the function. Checks first if
the data already exists in the HUXt boundary condition folder
Parameters
----------
cr : INT
Carrington rotation number
observatory : STRING
Name of preferred observatory (e.g., 'hmi','mdi','solis',
'gong','mwo','wso','kpo'). Empty if no preference and automatically selected
runtype : STRING
Name of preferred MAS run type (e.g., 'mas','mast','masp').
Empty if no preference and automatically selected
runnumber : STRING
Name of preferred MAS run number (e.g., '0101','0201').
Empty if no preference and automatically selected
Returns
-------
flag : INT
1 = successful download. 0 = files exist, -1 = no file found.
"""
assert(np.isnan(cr) == False)
# The order of preference for different MAS run results
overwrite = False
if not observatory:
observatories_order = ['hmi', 'mdi', 'solis', 'gong', 'mwo', 'wso', 'kpo']
else:
observatories_order = [str(observatory)]
overwrite = True # If the user wants a specific observatory, overwrite what's already downloaded
if not runtype:
runtype_order = ['masp', 'mas', 'mast']
else:
runtype_order = [str(runtype)]
overwrite = True
if not runnumber:
runnumber_order = ['0201', '0101']
else:
runnumber_order = [str(runnumber)]
overwrite = True
# Get the HUXt boundary condition directory
dirs = H._setup_dirs_()
_boundary_dir_ = dirs['boundary_conditions']
# Example URL: http://www.predsci.com/data/runs/cr2010-medium/mdi_mas_mas_std_0101/helio/br_r0.hdf
heliomas_url_front = 'http://www.predsci.com/data/runs/cr'
heliomas_url_end = '_r0.hdf'
vrfilename = 'HelioMAS_CR'+str(int(cr)) + '_vr'+heliomas_url_end
brfilename = 'HelioMAS_CR'+str(int(cr)) + '_br'+heliomas_url_end
if (os.path.exists(os.path.join(_boundary_dir_, brfilename)) == False or
os.path.exists(os.path.join(_boundary_dir_, vrfilename)) == False or
overwrite == True): # Check if the files already exist
# Search MHDweb for a HelioMAS run, in order of preference
h = httplib2.Http()
foundfile = False
for masob in observatories_order:
for masrun in runtype_order:
for masnum in runnumber_order:
urlbase = (heliomas_url_front + str(int(cr)) + '-medium/' + masob + '_' +
masrun + '_mas_std_' + masnum + '/helio/')
url = urlbase + 'br' + heliomas_url_end
# See if this br file exists
resp = h.request(url, 'HEAD')
if int(resp[0]['status']) < 400:
foundfile = True
# Exit all the loops - clumsy, but works
if foundfile:
break
if foundfile:
break
if foundfile:
break
if foundfile == False:
if verbose:
print('No data available for given CR and observatory preferences')
return -1
# Download teh vr and br files
if verbose:
print('Downloading from: ', urlbase)
urllib.request.urlretrieve(urlbase + 'br' + heliomas_url_end,
os.path.join(_boundary_dir_, brfilename))
urllib.request.urlretrieve(urlbase+'vr'+heliomas_url_end,
os.path.join(_boundary_dir_, vrfilename))
return 1
else:
if verbose:
print('Files already exist for CR' + str(int(cr)))
return 0
def read_MAS_vr_br(cr):
"""
A function to read in the MAS coundary conditions for a given CR
Parameters
----------
cr : INT
Carrington rotation number
Returns
-------
MAS_vr : NP ARRAY (NDIM = 2)
Solar wind speed at 30rS, in km/s
MAS_vr_Xa : NP ARRAY (NDIM = 1)
Carrington longitude of Vr map, in rad
MAS_vr_Xm : NP ARRAY (NDIM = 1)
Latitude of Vr as angle down from N pole, in rad
MAS_br : NP ARRAY (NDIM = 2)
Radial magnetic field at 30rS, in model units
MAS_br_Xa : NP ARRAY (NDIM = 1)
Carrington longitude of Br map, in rad
MAS_br_Xm : NP ARRAY (NDIM = 1)
Latitude of Br as angle down from N pole, in rad
"""
# Get the boundary condition directory
dirs = H._setup_dirs_()
_boundary_dir_ = dirs['boundary_conditions']
# Create the filenames
heliomas_url_end = '_r0.hdf'
vrfilename = 'HelioMAS_CR'+str(int(cr)) + '_vr' + heliomas_url_end
brfilename = 'HelioMAS_CR'+str(int(cr)) + '_br' + heliomas_url_end
filepath = os.path.join(_boundary_dir_, vrfilename)
assert os.path.exists(filepath)
file = SD(filepath, SDC.READ)
sds_obj = file.select('fakeDim0') # select sds
MAS_vr_Xa = sds_obj.get() # get sds data
sds_obj = file.select('fakeDim1') # select sds
MAS_vr_Xm = sds_obj.get() # get sds data
sds_obj = file.select('Data-Set-2') # select sds
MAS_vr = sds_obj.get() # get sds data
# Convert from model to physicsal units
MAS_vr = MAS_vr*481.0 * u.km/u.s
MAS_vr_Xa = MAS_vr_Xa * u.rad
MAS_vr_Xm = MAS_vr_Xm * u.rad
filepath = os.path.join(_boundary_dir_, brfilename)
assert os.path.exists(filepath)
file = SD(filepath, SDC.READ)
sds_obj = file.select('fakeDim0') # select sds
MAS_br_Xa = sds_obj.get() # get sds data
sds_obj = file.select('fakeDim1') # select sds
MAS_br_Xm = sds_obj.get() # get sds data
sds_obj = file.select('Data-Set-2') # select sds
MAS_br = sds_obj.get() # get sds data
MAS_br_Xa = MAS_br_Xa * u.rad
MAS_br_Xm = MAS_br_Xm * u.rad
return MAS_vr, MAS_vr_Xa, MAS_vr_Xm, MAS_br, MAS_br_Xa, MAS_br_Xm
def get_MAS_long_profile(cr, lat=0.0*u.deg, verbose=True):
"""
a function to download, read and process MAS output to provide HUXt boundary
conditions at a given latitude
Parameters
----------
cr : INT
Carrington rotation number
lat : FLOAT
Latitude at which to extract the longitudinal profile, measure up from equator
Returns
-------
vr_in : NP ARRAY (NDIM = 1)
Solar wind speed as a function of Carrington longitude at solar equator.
Interpolated to HUXt longitudinal resolution. In km/s
br_in : NP ARRAY(NDIM = 1)
Radial magnetic field as a function of Carrington longitude at solar equator.
Interpolated to HUXt longitudinal resolution. Dimensionless
"""
assert(np.isnan(cr) == False and cr > 0)
assert(lat >= -90.0*u.deg)
assert(lat <= 90.0*u.deg)
# Convert angle from equator to angle down from N pole
ang_from_N_pole = np.pi/2 - (lat.to(u.rad)).value
# Check the data exist, if not, download them
flag = get_MAS_boundary_conditions(cr, verbose=verbose)
assert(flag > -1)
# Read the HelioMAS data
MAS_vr, MAS_vr_Xa, MAS_vr_Xm, MAS_br, MAS_br_Xa, MAS_br_Xm = read_MAS_vr_br(cr)
# Extract the value at the given latitude
vr = np.ones(len(MAS_vr_Xa))
for i in range(0, len(MAS_vr_Xa)):
vr[i] = np.interp(ang_from_N_pole, MAS_vr_Xm.value, MAS_vr[i][:].value)
br = np.ones(len(MAS_br_Xa))
for i in range(0, len(MAS_br_Xa)):
br[i] = np.interp(ang_from_N_pole, MAS_br_Xm.value, MAS_br[i][:])
# Now interpolate on to the HUXt longitudinal grid
longs, dlon, nlon = H.longitude_grid(lon_start=0.0 * u.rad, lon_stop=2*np.pi * u.rad)
vr_in = np.interp(longs.value, MAS_vr_Xa.value, vr)*u.km/u.s
br_in = np.interp(longs.value, MAS_br_Xa.value, br)
return vr_in
def get_MAS_maps(cr):
"""
a function to download, read and process MAS output to provide HUXt boundary
conditions as lat-long maps, along with angle from equator for the maps
maps returned in native resolution, not HUXt resolution
Parameters
----------
cr : INT
Carrington rotation number
Returns
-------
vr_map : NP ARRAY
Solar wind speed as a Carrington longitude-latitude map. In km/s
vr_lats :
The latitudes for the Vr map, in radians from trhe equator
vr_longs :
The Carrington longitudes for the Vr map, in radians
br_map : NP ARRAY
Br as a Carrington longitude-latitude map. Dimensionless
br_lats :
The latitudes for the Br map, in radians from trhe equator
br_longs :
The Carrington longitudes for the Br map, in radians
"""
assert(np.isnan(cr) == False and cr > 0)
# Check the data exist, if not, download them
flag = get_MAS_boundary_conditions(cr)
assert(flag > -1)
# Read the HelioMAS data
MAS_vr, MAS_vr_Xa, MAS_vr_Xm, MAS_br, MAS_br_Xa, MAS_br_Xm = read_MAS_vr_br(cr)
vr_map = MAS_vr
br_map = MAS_br
# Convert the lat angles from N-pole to equator centred
vr_lats = (np.pi/2)*u.rad - MAS_vr_Xm
br_lats = (np.pi/2)*u.rad - MAS_br_Xm
# Flip lats, so they're increasing in value
vr_lats = np.flipud(vr_lats)
br_lats = np.flipud(br_lats)
vr_map = np.fliplr(vr_map)
br_map = np.fliplr(br_map)
vr_longs = MAS_vr_Xa
br_longs = MAS_br_Xa
return vr_map, vr_lats, vr_longs
@u.quantity_input(v_outer=u.km / u.s)
@u.quantity_input(r_outer=u.solRad)
@u.quantity_input(lon_outer=u.rad)
@u.quantity_input(r_inner=u.solRad)
def map_v_inwards(v_outer, r_outer, lon_outer, r_inner):
"""
Function to map v from r_outer (in rs) to r_inner (in rs) accounting for
residual acceleration, but neglecting stream interactions.
:param v_outer: Solar wind speed at outer radial distance. Units of km/s.
:param r_outer: Radial distance at outer radial distance. Units of km.
:param lon_outer: Carrington longitude at outer distance. Units of rad
:param r_inner: Radial distance at inner radial distance. Units of km.
:return v_inner: Solar wind speed mapped from r_outer to r_inner. Units of km/s.
:return lon_inner: Carrington longitude at r_inner. Units of rad.
"""
# Get the acceleration parameters
constants = H.huxt_constants()
alpha = constants['alpha'] # Scale parameter for residual SW acceleration
rH = constants['r_accel'].to(u.kilometer).value # Spatial scale parameter for residual SW acceleration
Tsyn = constants['synodic_period'].to(u.s).value
r_outer = r_outer.to(u.km).value
r_inner = r_inner.to(u.km).value
r_30 = 30*u.solRad
r_30 = r_30.to(u.km).value
# Compute the 30 rS speed
v30 = v_outer.value * (1 + alpha * (1 - np.exp((r_30 - r_outer) / rH)))
# Compute the speed at the new inner boundary height (using Vacc term, equation 5 in the paper)
v0 = v30 * (1 + alpha * (1 - np.exp((r_30 - r_inner) / rH)))
# Compute the transit time from the new to old inner boundary heights (i.e., integrate equations 3 and 4 wrt to r)
A = v0 + alpha * v0
term1 = rH * np.log(A * np.exp(r_outer / rH) - alpha * v0 * np.exp(r_inner / rH)) / A
term2 = rH * np.log(A * np.exp(r_inner / rH) - alpha * v0 * np.exp(r_inner / rH)) / A
T_integral = term1 - term2
# Work out the longitudinal shift
phi_new = H._zerototwopi_(lon_outer.value + (T_integral / Tsyn) * 2 * np.pi)
return v0*u.km/u.s, phi_new*u.rad
@u.quantity_input(v_outer=u.km / u.s)
@u.quantity_input(r_outer=u.solRad)
@u.quantity_input(r_inner=u.solRad)
def map_v_boundary_inwards(v_outer, r_outer, r_inner):
"""
Function to map a longitudinal V series from r_outer (in rs) to r_inner (in rs)
accounting for residual acceleration, but neglecting stream interactions.
Series return on HUXt longitudinal grid, not input grid
:param v_outer: Solar wind speed at outer radial boundary. Units of km/s.
:param r_outer: Radial distance at outer radial boundary. Units of km.
:param r_inner: Radial distance at inner radial boundary. Units of km.
:return v_inner: Solar wind speed mapped from r_outer to r_inner. Units of km/s.
"""
if r_outer < r_inner:
raise ValueError("Warning: r_outer < r_inner. Mapping will not work.")
# Compute the longitude grid from the length of the vouter input variable
lon, dlon, nlon = H.longitude_grid()
# Map each point in to a new speed and longitude
v0, phis_new = map_v_inwards(v_outer, r_outer, lon, r_inner)
# Interpolate the mapped speeds back onto the regular Carr long grid,
# making boundaries periodic
v_inner = np.interp(lon, phis_new, v0, period=2*np.pi)
return v_inner
@u.quantity_input(v_map=u.km / u.s)
@u.quantity_input(v_map_lat=u.rad)
@u.quantity_input(v_map_long=u.rad)
@u.quantity_input(r_outer=u.solRad)
@u.quantity_input(r_inner=u.solRad)
def map_vmap_inwards(v_map, v_map_lat, v_map_long, r_outer, r_inner):
"""
Function to map a V Carrington map from r_outer (in rs) to r_inner (in rs),
accounting for acceleration, but ignoring stream interaction
Map returned on input coord system, not HUXT resolution
:param v_map: Solar wind speed Carrington map at outer radial boundary. Units of km/s.
:param v_map_lat: Latitude (from equator) of v_map positions. Units of radians
:param v_map_long: Carrington longitude of v_map positions. Units of radians
:param r_outer: Radial distance at outer radial boundary. Units of km.
:param r_inner: Radial distance at inner radial boundary. Units of km.
:return v_map_inner: Solar wind speed map at r_inner. Units of km/s.
"""
if r_outer < r_inner:
raise ValueError("Warning: r_outer < r_inner. Mapping will not work.")
# Check the dimensions
assert(len(v_map_lat) == len(v_map[1, :]))
assert(len(v_map_long) == len(v_map[:, 1]))
v_map_inner = np.ones((len(v_map_long), len(v_map_lat)))
for ilat in range(0, len(v_map_lat)):
# Map each point in to a new speed and longitude
v0, phis_new = map_v_inwards(v_map[:, ilat], r_outer, v_map_long, r_inner)
# Interpolate the mapped speeds back onto the regular Carr long grid,
# making boundaries periodic * u.km/u.s
v_map_inner[:, ilat] = np.interp(v_map_long.value, phis_new.value, v0.value, period=2*np.pi)
return v_map_inner * u.km / u.s
def get_PFSS_maps(filepath):
"""
a function to load, read and process PFSSpy output to provide HUXt boundary
conditions as lat-long maps, along with angle from equator for the maps
maps returned in native resolution, not HUXt resolution
Parameters
----------
filepath : STR
The filepath for the PFSSpy .nc file
Returns
-------
vr_map : NP ARRAY
Solar wind speed as a Carrington longitude-latitude map. In km/s
vr_lats :
The latitudes for the Vr map, in radians from trhe equator
vr_longs :
The Carrington longitudes for the Vr map, in radians
br_map : NP ARRAY
Br as a Carrington longitude-latitude map. Dimensionless
br_lats :
The latitudes for the Br map, in radians from trhe equator
br_longs :
The Carrington longitudes for the Br map, in radians
"""
assert os.path.exists(filepath)
nc = netcdf.netcdf_file(filepath, 'r')
cotheta = nc.variables['cos(th)'].data
vr_lats = np.arcsin(cotheta[:, 0])*u.rad
br_lats = vr_lats
phi = nc.variables['ph'].data
vr_longs = phi[0, :] * u.rad
br_longs = vr_longs
br_map = np.rot90(nc.variables['br'].data)
vr_map = np.rot90(nc.variables['vr'].data) * u.km / u.s
return vr_map, vr_lats, vr_longs, br_map, br_lats, br_longs
| 2.609375 | 3 |
examples/simple_models/mobilenet/model/src/func_main.py | Hydrospheredata/hydro-serving-runtime | 7 | 12767294 | <reponame>Hydrospheredata/hydro-serving-runtime<gh_stars>1-10
import numpy as np
import tensorflow as tf
from keras.applications import mobilenet_v2
mobile_net = mobilenet_v2.MobileNetV2(
alpha=0.35,
weights="/model/files/mobilenet_v2_weights_tf_dim_ordering_tf_kernels_0.35_224"
)
graph = tf.get_default_graph()
def predict(input):
images = mobilenet_v2.preprocess_input(input)
with graph.as_default():
probas = mobile_net.predict(images)
classes = probas.argmax(axis=1)
return {
"classes": classes.astype("int64"),
"probabilities": probas.astype("double")
}
| 2.375 | 2 |
cohesity_management_sdk/controllers/remote_restore_controller.py | nick6655/management-sdk-python | 18 | 12767295 | <filename>cohesity_management_sdk/controllers/remote_restore_controller.py
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
import logging
from cohesity_management_sdk.api_helper import APIHelper
from cohesity_management_sdk.configuration import Configuration
from cohesity_management_sdk.controllers.base_controller import BaseController
from cohesity_management_sdk.http.auth.auth_manager import AuthManager
from cohesity_management_sdk.models.remote_vault_restore_task_status import RemoteVaultRestoreTaskStatus
from cohesity_management_sdk.models.universal_id import UniversalId
from cohesity_management_sdk.models.remote_vault_search_job_results import RemoteVaultSearchJobResults
from cohesity_management_sdk.models.remote_vault_search_job_information import RemoteVaultSearchJobInformation
from cohesity_management_sdk.models.created_remote_vault_search_job_uid import CreatedRemoteVaultSearchJobUid
from cohesity_management_sdk.models.vault_bandwidth_limits import VaultBandwidthLimits
from cohesity_management_sdk.exceptions.request_error_error_exception import RequestErrorErrorException
class RemoteRestoreController(BaseController):
"""A Controller to access Endpoints in the cohesity_management_sdk API."""
def __init__(self, config=None, client=None, call_back=None):
super(RemoteRestoreController, self).__init__(client, call_back)
self.logger = logging.getLogger(__name__)
self.config = config
def upload_vault_encryption_keys(self, id, body=None):
"""Does a PUT request to /public/remoteVaults/encryptionKeys/{id}.
This request contains multiple files stored as multipart mime data.
Each file has a key used to encrypt data between a remote Cluster and
the
remote Vault.
Content of the file should be same as the file downloaded from the
remote
Cluster.
Args:
id (long|int): Specifies a unique id of the Vault.
body (list of VaultEncryptionKey, optional): Request to upload
encryption keys of a remote Vault.
Returns:
void: Response from the API. No Content
Raises:
APIException: When an error occurs while fetching the data from
the remote API. This exception includes the HTTP Response
code, an error message, and the HTTP body that was received in
the request.
"""
try:
self.logger.info('upload_vault_encryption_keys called.')
# Validate required parameters
self.logger.info(
'Validating required parameters for upload_vault_encryption_keys.'
)
self.validate_parameters(id=id)
# Prepare query URL
self.logger.info(
'Preparing query URL for upload_vault_encryption_keys.')
_url_path = '/public/remoteVaults/encryptionKeys/{id}'
_url_path = APIHelper.append_url_with_template_parameters(
_url_path, {'id': id})
_query_builder = self.config.get_base_uri()
_query_builder += _url_path
_query_url = APIHelper.clean_url(_query_builder)
# Prepare headers
self.logger.info(
'Preparing headers for upload_vault_encryption_keys.')
_headers = {'content-type': 'application/json; charset=utf-8'}
# Prepare and execute request
self.logger.info(
'Preparing and executing request for upload_vault_encryption_keys.'
)
_request = self.http_client.put(
_query_url,
headers=_headers,
parameters=APIHelper.json_serialize(body))
AuthManager.apply(_request, self.config)
_context = self.execute_request(
_request, name='upload_vault_encryption_keys')
# Endpoint and global error handling using HTTP status codes.
self.logger.info(
'Validating response for upload_vault_encryption_keys.')
if _context.response.status_code == 0:
raise RequestErrorErrorException('Error', _context)
self.validate_response(_context)
except Exception as e:
self.logger.error(e, exc_info=True)
raise
def list_remote_vault_restore_tasks(self):
"""Does a GET request to /public/remoteVaults/restoreTasks.
A remote Vault restore task can restore archived data from a Vault
(External Target) to this local Cluster.
This is part of the CloudRetrieve functionality for finding and
restoring
archived data from remote Vaults to an alternative (non-original)
Cluster.
Returns:
list of RemoteVaultRestoreTaskStatus: Response from the API.
Success
Raises:
APIException: When an error occurs while fetching the data from
the remote API. This exception includes the HTTP Response
code, an error message, and the HTTP body that was received in
the request.
"""
try:
self.logger.info('list_remote_vault_restore_tasks called.')
# Prepare query URL
self.logger.info(
'Preparing query URL for list_remote_vault_restore_tasks.')
_url_path = '/public/remoteVaults/restoreTasks'
_query_builder = self.config.get_base_uri()
_query_builder += _url_path
_query_url = APIHelper.clean_url(_query_builder)
# Prepare headers
self.logger.info(
'Preparing headers for list_remote_vault_restore_tasks.')
_headers = {'accept': 'application/json'}
# Prepare and execute request
self.logger.info(
'Preparing and executing request for list_remote_vault_restore_tasks.'
)
_request = self.http_client.get(_query_url, headers=_headers)
AuthManager.apply(_request, self.config)
_context = self.execute_request(
_request, name='list_remote_vault_restore_tasks')
# Endpoint and global error handling using HTTP status codes.
self.logger.info(
'Validating response for list_remote_vault_restore_tasks.')
if _context.response.status_code == 0:
raise RequestErrorErrorException('Error', _context)
self.validate_response(_context)
# Return appropriate type
return APIHelper.json_deserialize(
_context.response.raw_body,
RemoteVaultRestoreTaskStatus.from_dictionary)
except Exception as e:
self.logger.error(e, exc_info=True)
raise
def create_remote_vault_restore_task(self, body):
"""Does a POST request to /public/remoteVaults/restoreTasks.
Returns the id of the remote Vault restore Task that was created.
After a Vault is searched by a search Job, this operation can be
called to create a task that restores the indexes and/or the
Snapshots
of a Protection Job, which were archived on a remote Vault (External
Target).
This is part of the CloudRetrieve functionality for finding and
restoring
archived data from remote Vaults to an alternative (non-original)
Cluster.
Args:
body (CreateRemoteVaultRestoreTaskParameters): Request to create a
remote Vault restore task.
Returns:
UniversalId: Response from the API. Success
Raises:
APIException: When an error occurs while fetching the data from
the remote API. This exception includes the HTTP Response
code, an error message, and the HTTP body that was received in
the request.
"""
try:
self.logger.info('create_remote_vault_restore_task called.')
# Validate required parameters
self.logger.info(
'Validating required parameters for create_remote_vault_restore_task.'
)
self.validate_parameters(body=body)
# Prepare query URL
self.logger.info(
'Preparing query URL for create_remote_vault_restore_task.')
_url_path = '/public/remoteVaults/restoreTasks'
_query_builder = self.config.get_base_uri()
_query_builder += _url_path
_query_url = APIHelper.clean_url(_query_builder)
# Prepare headers
self.logger.info(
'Preparing headers for create_remote_vault_restore_task.')
_headers = {
'accept': 'application/json',
'content-type': 'application/json; charset=utf-8'
}
# Prepare and execute request
self.logger.info(
'Preparing and executing request for create_remote_vault_restore_task.'
)
_request = self.http_client.post(
_query_url,
headers=_headers,
parameters=APIHelper.json_serialize(body))
AuthManager.apply(_request, self.config)
_context = self.execute_request(
_request, name='create_remote_vault_restore_task')
# Endpoint and global error handling using HTTP status codes.
self.logger.info(
'Validating response for create_remote_vault_restore_task.')
if _context.response.status_code == 0:
raise RequestErrorErrorException('Error', _context)
self.validate_response(_context)
# Return appropriate type
return APIHelper.json_deserialize(_context.response.raw_body,
UniversalId.from_dictionary)
except Exception as e:
self.logger.error(e, exc_info=True)
raise
def get_remote_vault_search_job_results(self,
search_job_id,
cluster_id,
cluster_incarnation_id,
page_count=None,
cluster_name=None,
cookie=None):
"""Does a GET request to /public/remoteVaults/searchJobResults.
Specify a unique id of the search Job using a combination of the
searchJobId, clusterId, and clusterIncarnationId parameters,
which are all required.
The results can be optionally filtered by the remote Cluster name.
This is part of the CloudRetrieve functionality for finding and
restoring
archived data from a remote Vault.
Args:
search_job_id (long|int): Specifies the id of the remote Vault
search Job assigned by the Cohesity Cluster. Used in
combination with the clusterId and clusterIncarnationId to
uniquely identify the search Job.
cluster_id (long|int): Specifies the Cohesity Cluster id where the
search Job was created. Used in combination with the
searchJobId and clusterIncarnationId to uniquely identify the
search Job.
cluster_incarnation_id (long|int): Specifies the incarnation id of
the Cohesity Cluster where the search Job was created. Used in
combination with the searchJobId and clusterId to uniquely
identify the search Job.
page_count (int, optional): Specifies the number of Protection
Jobs to return in the response to support pagination.
cluster_name (string, optional): Optionally filter the result by
the remote Cohesity Cluster name.
cookie (string, optional): Specifies the opaque string cookie
returned by the previous response, to get next set of results.
Used in combination with pageCount to support pagination.
Returns:
RemoteVaultSearchJobResults: Response from the API. Success
Raises:
APIException: When an error occurs while fetching the data from
the remote API. This exception includes the HTTP Response
code, an error message, and the HTTP body that was received in
the request.
"""
try:
self.logger.info('get_remote_vault_search_job_results called.')
# Validate required parameters
self.logger.info(
'Validating required parameters for get_remote_vault_search_job_results.'
)
self.validate_parameters(
search_job_id=search_job_id,
cluster_id=cluster_id,
cluster_incarnation_id=cluster_incarnation_id)
# Prepare query URL
self.logger.info(
'Preparing query URL for get_remote_vault_search_job_results.')
_url_path = '/public/remoteVaults/searchJobResults'
_query_builder = self.config.get_base_uri()
_query_builder += _url_path
_query_parameters = {
'searchJobId': search_job_id,
'clusterId': cluster_id,
'clusterIncarnationId': cluster_incarnation_id,
'pageCount': page_count,
'clusterName': cluster_name,
'cookie': cookie
}
_query_builder = APIHelper.append_url_with_query_parameters(
_query_builder, _query_parameters,
Configuration.array_serialization)
_query_url = APIHelper.clean_url(_query_builder)
# Prepare headers
self.logger.info(
'Preparing headers for get_remote_vault_search_job_results.')
_headers = {'accept': 'application/json'}
# Prepare and execute request
self.logger.info(
'Preparing and executing request for get_remote_vault_search_job_results.'
)
_request = self.http_client.get(_query_url, headers=_headers)
AuthManager.apply(_request, self.config)
_context = self.execute_request(
_request, name='get_remote_vault_search_job_results')
# Endpoint and global error handling using HTTP status codes.
self.logger.info(
'Validating response for get_remote_vault_search_job_results.')
if _context.response.status_code == 0:
raise RequestErrorErrorException('Error', _context)
self.validate_response(_context)
# Return appropriate type
return APIHelper.json_deserialize(
_context.response.raw_body,
RemoteVaultSearchJobResults.from_dictionary)
except Exception as e:
self.logger.error(e, exc_info=True)
raise
def delete_stop_remote_vault_search_job(self, body):
"""Does a DELETE request to /public/remoteVaults/searchJobs.
This is part of the CloudRetrieve functionality for finding and
restoring
archived data from remote Vaults to an alternative (non-original)
Cluster.
Args:
body (StopRemoteVaultSearchJobParameters): Request to stop a
Remote Vault Search Job.
Returns:
void: Response from the API. No Content
Raises:
APIException: When an error occurs while fetching the data from
the remote API. This exception includes the HTTP Response
code, an error message, and the HTTP body that was received in
the request.
"""
try:
self.logger.info('delete_stop_remote_vault_search_job called.')
# Validate required parameters
self.logger.info(
'Validating required parameters for delete_stop_remote_vault_search_job.'
)
self.validate_parameters(body=body)
# Prepare query URL
self.logger.info(
'Preparing query URL for delete_stop_remote_vault_search_job.')
_url_path = '/public/remoteVaults/searchJobs'
_query_builder = self.config.get_base_uri()
_query_builder += _url_path
_query_url = APIHelper.clean_url(_query_builder)
# Prepare headers
self.logger.info(
'Preparing headers for delete_stop_remote_vault_search_job.')
_headers = {'content-type': 'application/json; charset=utf-8'}
# Prepare and execute request
self.logger.info(
'Preparing and executing request for delete_stop_remote_vault_search_job.'
)
_request = self.http_client.delete(
_query_url,
headers=_headers,
parameters=APIHelper.json_serialize(body))
AuthManager.apply(_request, self.config)
_context = self.execute_request(
_request, name='delete_stop_remote_vault_search_job')
# Endpoint and global error handling using HTTP status codes.
self.logger.info(
'Validating response for delete_stop_remote_vault_search_job.')
if _context.response.status_code == 0:
raise RequestErrorErrorException('Error', _context)
self.validate_response(_context)
except Exception as e:
self.logger.error(e, exc_info=True)
raise
def list_remote_vault_search_jobs(self):
"""Does a GET request to /public/remoteVaults/searchJobs.
List all the searches of remote Vaults (External Targets) that
have run or are running on this Cohesity Cluster.
A search finds Protection Jobs that have archived to a
Vault (External Target).
This is part of the CloudRetrieve functionality for finding and
restoring
archived data from remote Vaults to an alternative (non-original)
Cluster.
NOTE: A Vault is equivalent to an External Target in the Cohesity
Dashboard.
A search Job is equivalent to a search task in the Cohesity
Dashboard.
Returns:
list of RemoteVaultSearchJobInformation: Response from the API.
Success
Raises:
APIException: When an error occurs while fetching the data from
the remote API. This exception includes the HTTP Response
code, an error message, and the HTTP body that was received in
the request.
"""
try:
self.logger.info('list_remote_vault_search_jobs called.')
# Prepare query URL
self.logger.info(
'Preparing query URL for list_remote_vault_search_jobs.')
_url_path = '/public/remoteVaults/searchJobs'
_query_builder = self.config.get_base_uri()
_query_builder += _url_path
_query_url = APIHelper.clean_url(_query_builder)
# Prepare headers
self.logger.info(
'Preparing headers for list_remote_vault_search_jobs.')
_headers = {'accept': 'application/json'}
# Prepare and execute request
self.logger.info(
'Preparing and executing request for list_remote_vault_search_jobs.'
)
_request = self.http_client.get(_query_url, headers=_headers)
AuthManager.apply(_request, self.config)
_context = self.execute_request(
_request, name='list_remote_vault_search_jobs')
# Endpoint and global error handling using HTTP status codes.
self.logger.info(
'Validating response for list_remote_vault_search_jobs.')
if _context.response.status_code == 0:
raise RequestErrorErrorException('Error', _context)
self.validate_response(_context)
# Return appropriate type
return APIHelper.json_deserialize(
_context.response.raw_body,
RemoteVaultSearchJobInformation.from_dictionary)
except Exception as e:
self.logger.error(e, exc_info=True)
raise
def create_remote_vault_search_job(self, body):
"""Does a POST request to /public/remoteVaults/searchJobs.
A search Job finds Protection Jobs that archived data to a
Vault (External Target) which also match the specified search
criteria.
The results can be optionally filtered by specifying a Cluster match
string,
a Protection Job match string, a start time and an end time.
This is part of the CloudRetrieve functionality for finding and
restoring
archived data from remote Vaults to an alternative (non-original)
Cluster.
NOTE: A Vault is equivalent to an External Target in the Cohesity
Dashboard.
A search Job is equivalent to a search task in the Cohesity
Dashboard.
Args:
body (CreateRemoteVaultSearchJobParameters): Request to create a
search of a remote Vault.
Returns:
CreatedRemoteVaultSearchJobUid: Response from the API. Success
Raises:
APIException: When an error occurs while fetching the data from
the remote API. This exception includes the HTTP Response
code, an error message, and the HTTP body that was received in
the request.
"""
try:
self.logger.info('create_remote_vault_search_job called.')
# Validate required parameters
self.logger.info(
'Validating required parameters for create_remote_vault_search_job.'
)
self.validate_parameters(body=body)
# Prepare query URL
self.logger.info(
'Preparing query URL for create_remote_vault_search_job.')
_url_path = '/public/remoteVaults/searchJobs'
_query_builder = self.config.get_base_uri()
_query_builder += _url_path
_query_url = APIHelper.clean_url(_query_builder)
# Prepare headers
self.logger.info(
'Preparing headers for create_remote_vault_search_job.')
_headers = {
'accept': 'application/json',
'content-type': 'application/json; charset=utf-8'
}
# Prepare and execute request
self.logger.info(
'Preparing and executing request for create_remote_vault_search_job.'
)
_request = self.http_client.post(
_query_url,
headers=_headers,
parameters=APIHelper.json_serialize(body))
AuthManager.apply(_request, self.config)
_context = self.execute_request(
_request, name='create_remote_vault_search_job')
# Endpoint and global error handling using HTTP status codes.
self.logger.info(
'Validating response for create_remote_vault_search_job.')
if _context.response.status_code == 0:
raise RequestErrorErrorException('Error', _context)
self.validate_response(_context)
# Return appropriate type
return APIHelper.json_deserialize(
_context.response.raw_body,
CreatedRemoteVaultSearchJobUid.from_dictionary)
except Exception as e:
self.logger.error(e, exc_info=True)
raise
def list_remote_vault_search_job_by_id(self, id):
"""Does a GET request to /public/remoteVaults/searchJobs/{id}.
Specify an id for a completed or running search Job.
A search Job finds data that has been archived to a Vault (External
Target).
The returned results do not include Job Run (Snapshot) information.
It is part of the CloudRetrieve functionality for finding and
restoring
archived data from remote Vaults to an alternative (non-original)
Cluster.
Args:
id (long|int): Specifies the id of the remote Vault search Job to
return.
Returns:
RemoteVaultSearchJobInformation: Response from the API. Success
Raises:
APIException: When an error occurs while fetching the data from
the remote API. This exception includes the HTTP Response
code, an error message, and the HTTP body that was received in
the request.
"""
try:
self.logger.info('list_remote_vault_search_job_by_id called.')
# Validate required parameters
self.logger.info(
'Validating required parameters for list_remote_vault_search_job_by_id.'
)
self.validate_parameters(id=id)
# Prepare query URL
self.logger.info(
'Preparing query URL for list_remote_vault_search_job_by_id.')
_url_path = '/public/remoteVaults/searchJobs/{id}'
_url_path = APIHelper.append_url_with_template_parameters(
_url_path, {'id': id})
_query_builder = self.config.get_base_uri()
_query_builder += _url_path
_query_url = APIHelper.clean_url(_query_builder)
# Prepare headers
self.logger.info(
'Preparing headers for list_remote_vault_search_job_by_id.')
_headers = {'accept': 'application/json'}
# Prepare and execute request
self.logger.info(
'Preparing and executing request for list_remote_vault_search_job_by_id.'
)
_request = self.http_client.get(_query_url, headers=_headers)
AuthManager.apply(_request, self.config)
_context = self.execute_request(
_request, name='list_remote_vault_search_job_by_id')
# Endpoint and global error handling using HTTP status codes.
self.logger.info(
'Validating response for list_remote_vault_search_job_by_id.')
if _context.response.status_code == 0:
raise RequestErrorErrorException('Error', _context)
self.validate_response(_context)
# Return appropriate type
return APIHelper.json_deserialize(
_context.response.raw_body,
RemoteVaultSearchJobInformation.from_dictionary)
except Exception as e:
self.logger.error(e, exc_info=True)
raise
def list_cloud_domain_migration(self):
"""Does a GET request to /public/remoteVaults/cloudDomainMigration.
Returns the Cloud domain migration info.
Returns:
VaultBandwidthLimits: Response from the API. Success
Raises:
APIException: When an error occurs while fetching the data from
the remote API. This exception includes the HTTP Response
code, an error message, and the HTTP body that was received in
the request.
"""
try:
self.logger.info('list_cloud_domain_migration called.')
# Prepare query URL
self.logger.info(
'Preparing query URL for list_cloud_domain_migration.')
_url_path = '/public/remoteVaults/cloudDomainMigration'
_query_builder = self.config.get_base_uri()
_query_builder += _url_path
_query_url = APIHelper.clean_url(_query_builder)
# Prepare headers
self.logger.info('Preparing headers for list_cloud_domain_migration.')
_headers = {'accept': 'application/json'}
# Prepare and execute request
self.logger.info(
'Preparing and executing request for list_cloud_domain_migration.')
_request = self.http_client.get(_query_url, headers=_headers)
AuthManager.apply(_request, self.config)
_context = self.execute_request(_request,
name='list_cloud_domain_migration')
# Endpoint and global error handling using HTTP status codes.
self.logger.info(
'Validating response for list_cloud_domain_migration.')
if _context.response.status_code == 0:
raise RequestErrorErrorException('Error', _context)
self.validate_response(_context)
# Return appropriate type
return APIHelper.json_deserialize(_context.response.raw_body,
VaultBandwidthLimits.from_dictionary)
except Exception as e:
self.logger.error(e, exc_info=True)
raise
def schedule_cloud_domain_migration(self):
"""Does a POST request to /public/remoteVaults/cloudDomainMigration.
Returns the updated bandwidth limits.
Returns:
VaultBandwidthLimits: Response from the API. Success
Raises:
APIException: When an error occurs while fetching the data from
the remote API. This exception includes the HTTP Response
code, an error message, and the HTTP body that was received in
the request.
"""
try:
self.logger.info('schedule_cloud_domain_migration called.')
# Prepare query URL
self.logger.info('Preparing query URL for schedule_cloud_domain_migration.')
_url_path = '/public/remoteVaults/cloudDomainMigration'
_query_builder = self.config.get_base_uri()
_query_builder += _url_path
_query_url = APIHelper.clean_url(_query_builder)
# Prepare headers
self.logger.info('Preparing headers for schedule_cloud_domain_migration.')
_headers = {
'accept': 'application/json',
'content-type': 'application/json; charset=utf-8'
}
# Prepare and execute request
self.logger.info(
'Preparing and executing request for schedule_cloud_domain_migration.')
_request = self.http_client.post(
_query_url,
headers=_headers)
AuthManager.apply(_request, self.config)
_context = self.execute_request(_request, name='schedule_cloud_domain_migration')
# Endpoint and global error handling using HTTP status codes.
self.logger.info('Validating response for schedule_cloud_domain_migration.')
if _context.response.status_code == 0:
raise RequestErrorErrorException('Error', _context)
self.validate_response(_context)
# Return appropriate type
return APIHelper.json_deserialize(_context.response.raw_body,
VaultBandwidthLimits.from_dictionary)
except Exception as e:
self.logger.error(e, exc_info=True)
raise
| 2.171875 | 2 |
tests/test_common/test_crypto.py | so1n/rap | 3 | 12767296 | <gh_stars>1-10
import pytest
from rap.common.crypto import Crypto
class TestCrypto:
def test_init_error(self) -> None:
with pytest.raises(ValueError):
Crypto("keyskeyskeyskey")
def test_crypto_str(self) -> None:
crypto: "Crypto" = Crypto("keyskeyskeyskeys")
raw_str: str = "test_rap_crypto_text"
encrypt_byte: bytes = crypto.encrypt(raw_str)
decrypt_str: str = crypto.decrypt(encrypt_byte)
assert raw_str == decrypt_str
def test_crypto_obj(self) -> None:
crypto: "Crypto" = Crypto("keyskeyskeyskeys")
raw_obj: dict = {"key": "test"}
encrypt_byte: bytes = crypto.encrypt_object(raw_obj)
decrypt_obj: dict = crypto.decrypt_object(encrypt_byte)
assert raw_obj == decrypt_obj
| 2.4375 | 2 |
day1_1.py | SeyelentEco/AdventOfCode2018 | 0 | 12767297 | def main():
totalNum = 0
totalValues = {}
filename = 'day1_1_input.txt'
found = False
while not found:
userInput = open(filename, 'r')
print ("Starting from the top")
for i in userInput:
print (i)
if i[0] == '-':
totalNum -= int(i[1:])
else:
totalNum += int(i[1:])
print (totalNum)
if totalNum in totalValues:
found = True
break
else:
totalValues[totalNum] = 1
userInput.close()
print(totalNum)
main()
| 3.40625 | 3 |
Tools/Misc.py | MuZiGuYue/VideoSuperResolution | 1 | 12767298 | """
Copyright: Wenyi Tang 2017-2019
Author: <NAME>
Email: <EMAIL>
Created Date: Jan 7th, 2019
Misc utility tools
- make TFRecords files
"""
# Copyright (c): <NAME> 2017-2019.
# Author: <NAME>
# Email: <EMAIL>
# Update Date: 2019/4/3 下午5:03
import tensorflow as tf
def make_tensor_label_records(tensors, labels, writer):
assert isinstance(tensors, (list, tuple))
assert isinstance(labels, (list, tuple))
assert len(tensors) == len(labels)
example = tf.train.Example(features=tf.train.Features())
for _t, _l in zip(tensors, labels):
assert isinstance(_t, bytes)
assert isinstance(_l, str)
bl = tf.train.BytesList(value=[_t])
ff = example.features.feature.get_or_create(_l)
ff.MergeFrom(tf.train.Feature(bytes_list=bl))
writer.write(example.SerializeToString())
| 2.609375 | 3 |
utils/dihedralAngle.py | jameswind/neuralCT | 28 | 12767299 | <reponame>jameswind/neuralCT
import numpy as np
import torch
# Adopted from https://stackoverflow.com/questions/20305272/dihedral-torsion-angle-from-four-points-in-cartesian-coordinates-in-python
def dihedralAngle(p0,p1,p2,p3):
b0 = -1.0*(p1-p0)
b1 = p2-p1
b2 = p3-p2
b0xb1 = torch.cross(b0,b1,dim=1)
b1xb2 = torch.cross(b2,b1,dim=1)
b0xb1_x_b1xb2 = torch.cross(b0xb1,b1xb2,dim=1)
y = torch.bmm(b0xb1_x_b1xb2.reshape(-1,1,3),b1.reshape(-1,3,1)).reshape(-1,1)*(1.0/torch.norm(b1,p=2,dim=1)).reshape(-1,1)
x = torch.bmm(b0xb1.reshape(-1,1,3),b1xb2.reshape(-1,3,1)).reshape(-1,1)
return torch.atan2(y,x)*180/np.pi
def alanineDipeptidePhiPsi(data):
p0 = data[:,1]
p1 = data[:,3]
p2 = data[:,4]
p3 = data[:,6]
Phi = dihedralAngle(p0,p1,p2,p3)
p0 = data[:,3]
p1 = data[:,4]
p2 = data[:,6]
p3 = data[:,8]
Psi = dihedralAngle(p0,p1,p2,p3)
return Phi,Psi
| 2.625 | 3 |
EOC/prototype/model/__init__.py | double-fire-0/SystemNoise | 8 | 12767300 | <filename>EOC/prototype/model/__init__.py
from .mobilenet_v2 import mobilenet_v2 # noqa: F401
from .regnet import ( # noqa: F401
regnetx_200m, regnetx_400m, regnetx_600m, regnetx_800m,
regnetx_1600m, regnetx_3200m, regnetx_4000m, regnetx_6400m,
regnety_200m, regnety_400m, regnety_600m, regnety_800m,
regnety_1600m, regnety_3200m, regnety_4000m, regnety_6400m,
)
from .efficientnet import ( # noqa: F401
efficientnet_b0, efficientnet_b1, efficientnet_b2, efficientnet_b3,
efficientnet_b4, efficientnet_b5, efficientnet_b6, efficientnet_b7,
efficientnet_b0_nodrop, efficientnet_b1_nodrop, efficientnet_b2_nodrop, efficientnet_b3_nodrop,
efficientnet_b4_nodrop, efficientnet_b5_nodrop, efficientnet_b6_nodrop, efficientnet_b7_nodrop
)
from .shufflenet_v2 import ( # noqa: F401
shufflenet_v2_x0_5, shufflenet_v2_x1_0, shufflenet_v2_x1_5, shufflenet_v2_x2_0, shufflenet_v2_scale
)
from .densenet import densenet121, densenet169, densenet201, densenet161 # noqa: F401
# from .toponet import toponet_conv, toponet_sepconv, toponet_mb
from .resnet_official import ( # noqa: F401
resnet18_official, resnet34_official, resnet50_official, resnet101_official, resnet152_official,
resnext50_32x4d, resnext101_32x8d, wide_resnet50_2, wide_resnet101_2
)
from .mobilenet_v3 import mobilenet_v3 # noqa: F401
from .vision_transformer import ( # noqa: F401
vit_b32_224, vit_b16_224,
deit_tiny_b16_224, deit_small_b16_224, deit_base_b16_224
)
# add from .vit
from .vit.swin_transformer import ( # noqa: F401
swin_tiny, swin_small, swin_base_224, swin_base_384, swin_large_224, swin_large_384
)
from .vit.mlp_mixer import ( # noqa: F401
mixer_b16_224, mixer_L16_224
)
from .vit.vit_base import ( # noqa: F401
new_deit_small_patch16_224
)
from .repvgg import ( # noqa: F401
repvgg_A0, repvgg_A1, repvgg_A2, repvgg_B0,
repvgg_B1, repvgg_B1g2, repvgg_B1g4,
repvgg_B2, repvgg_B2g2, repvgg_B2g4,
repvgg_B3, repvgg_B3g2, repvgg_B3g4
)
from .alexnet import alexnet
def get_model_robust_dcit():
return {
'alexnet': alexnet(),
"deit_base_b16_224": deit_base_b16_224(drop_path=0.0, dropout=0.0, attention_dropout=0.0, qkv_bias=True),
"deit_small_b16_224": deit_small_b16_224(drop_path=0.0, dropout=0.0, attention_dropout=0.0, qkv_bias=True),
"deit_tiny_b16_224": deit_tiny_b16_224(drop_path=0.0, dropout=0.0, attention_dropout=0.0, qkv_bias=True),
"densenet121": densenet121(),
"densenet169": densenet169(),
"densenet201": densenet201(),
"mixer_b16_224": mixer_b16_224(drop_path=0.0, drop_path_rate=0.0),
"mixer_L16_224": mixer_L16_224(drop_path=0.0, drop_path_rate=0.0),
"mobilenet_v2_x0_5": mobilenet_v2(scale=0.5),
"mobilenet_v2_x0_75": mobilenet_v2(scale=0.75),
"mobilenet_v2_x1_0": mobilenet_v2(scale=1.0),
"mobilenet_v2_x1_4": mobilenet_v2(scale=1.4),
"mobilenet_v3_large_x0_5": mobilenet_v3(scale=0.5, dropout=0.0, mode='large'),
"mobilenet_v3_large_x0_35": mobilenet_v3(scale=0.35, dropout=0.0, mode='large'),
"mobilenet_v3_large_x0_75": mobilenet_v3(scale=0.75, dropout=0.0, mode='large'),
"mobilenet_v3_large_x1_0": mobilenet_v3(scale=1.0, dropout=0.0, mode='large'),
"mobilenet_v3_large_x1_4": mobilenet_v3(scale=1.4, dropout=0.0, mode='large'),
"regnetx_400m": regnetx_400m(),
"regnetx_800m": regnetx_800m(),
"regnetx_1600m": regnetx_1600m(),
"regnetx_3200m": regnetx_3200m(),
"regnetx_6400m": regnetx_6400m(),
"repvgg_A0": repvgg_A0(),
"repvgg_B3": repvgg_B3(),
"resnet18": resnet18_official(),
"resnet34": resnet34_official(),
"resnet50": resnet50_official(),
"resnet101": resnet101_official(),
"resnet152": resnet152_official(),
"resnext50_32x4d": resnext50_32x4d(),
"resnext101_32x8d": resnext101_32x8d(),
"shufflenet_v2_x0_5": shufflenet_v2_x0_5(),
"shufflenet_v2_x1_0": shufflenet_v2_x1_0(),
"shufflenet_v2_x1_5": shufflenet_v2_x1_5(),
"shufflenet_v2_x2_0": shufflenet_v2_x2_0(),
"vit_b16_224": vit_b16_224(drop_path=0.0, dropout=0.0, attention_dropout=0.0, qkv_bias=True,
representation_size=768),
"vit_b32_224": vit_b32_224(drop_path=0.0, dropout=0.0, attention_dropout=0.0, qkv_bias=True,
representation_size=768),
"wide_resnet50_2": wide_resnet50_2(),
"wide_resnet101_2": wide_resnet101_2(),
'resnet50_augmix': resnet50_official(),
'resnet50_mococv2': resnet50_official(),
'resnet50_adamw': resnet50_official(),
'regnetx_3200m_augmix': regnetx_3200m(),
'regnetx_3200m_adamw': regnetx_3200m(),
'repvgg_A0_deploy': repvgg_A0(),
'repvgg_B3_deploy': repvgg_B3(),
'shufflenet_v2_x2_0_augmentation': shufflenet_v2_x2_0(),
'shufflenetv2_2.0_augmix': shufflenet_v2_x2_0(),
'shufflenet_v2_x2_0_ema': shufflenet_v2_x2_0(),
'shufflenet_v2_x2_0_label_smooth': shufflenet_v2_x2_0(),
'shufflenetv2_2.0_adamw': shufflenet_v2_x2_0(),
"efficientnet_b0": efficientnet_b0(),
'efficientnet_b0_nodrop': efficientnet_b0_nodrop(),
'efficientnet_b1_nodrop_240': efficientnet_b1_nodrop(),
'efficientnet_b2_nodrop_260': efficientnet_b2_nodrop(),
'efficientnet_b3_nodrop_300': efficientnet_b3_nodrop(),
'efficientnet_b4_nodrop_380': efficientnet_b4_nodrop(),
'mobilenet_v3_large_x1_4_augmentation': mobilenet_v3(scale=1.4, dropout=0.0, mode='large'),
'mobilenet_v3_large_x1_4_augmix': mobilenet_v3(scale=1.4, dropout=0.0, mode='large'),
'mobilenet_v3_large_x1_4_ema': mobilenet_v3(scale=1.4, dropout=0.0, mode='large'),
'mobilenet_v3_large_x1_4_label_smooth': mobilenet_v3(scale=1.4, dropout=0.0, mode='large'),
'mobilenet_v3_large_x1_4_adv_train': mobilenet_v3(scale=1.4, dropout=0.0, mode='large'),
'mobilenet_v3_large_x1_4_adamw': mobilenet_v3(scale=1.4, dropout=0.0, mode='large'),
'mobilenet_v3_large_x1_4_dropout': mobilenet_v3(scale=1.4, dropout=0.2, mode='large'),
'21k_resnet50': resnet50_official(),
'21k_vit_base_patch16_224': vit_b16_224(drop_path=0.0, dropout=0.0, attention_dropout=0.0, qkv_bias=True,
representation_size=768),
'vit_base_patch16_224_withdrop': vit_b16_224(drop_path=0.1, qkv_bias=True,
representation_size=768),
'mixer_B16_224_augmentation':mixer_b16_224(drop_path=0.0, drop_path_rate=0.0),
'mixer_b16_224_augmix': mixer_b16_224(drop_path=0.0, drop_path_rate=0.0),
'mixer_B16_224_ema': mixer_b16_224(drop_path=0.0, drop_path_rate=0.0),
'mixer_B16_224_label_smooth.pth.tar': mixer_b16_224(drop_path=0.0, drop_path_rate=0.0),
'mixer_B16_224_adv_train': mixer_b16_224(drop_path=0.0, drop_path_rate=0.0),
'mixer_b16_224_withdrop': mixer_b16_224(drop_path=0.1, drop_path_rate=0.1),
}
def model_entry(config):
if config['type'] not in globals():
if config['type'].startswith('spring_'):
try:
from spring.models import SPRING_MODELS_REGISTRY
except ImportError:
print('Please install Spring2 first!')
model_name = config['type'][len('spring_'):]
config['type'] = model_name
return SPRING_MODELS_REGISTRY.build(config)
return globals()[config['type']](**config['kwargs'])
get_model = model_entry
| 1.515625 | 2 |
tests/unit/contrib/system/conftest.py | gitter-badger/sitri | 0 | 12767301 | import pytest
from sitri.contrib.system import SystemConfigProvider, SystemCredentialProvider
@pytest.fixture(scope="module")
def system_config() -> SystemConfigProvider:
return SystemConfigProvider(prefix="test")
@pytest.fixture(scope="module")
def system_credential() -> SystemCredentialProvider:
return SystemCredentialProvider(prefix="test")
| 1.898438 | 2 |
scripts/classical/fisher_relationship.py | doubleblind666/inferring-undiscovered-species-extinctions | 2 | 12767302 | <filename>scripts/classical/fisher_relationship.py<gh_stars>1-10
# get the relationship between the omega and the total number of species infered
import sys
sys.path.insert(0,'../../undetected_extinctions') # so I can import the undetected extinctions package
import csv
import numpy as np
from scipy.stats import uniform
import pickle
from rpy2.robjects.packages import importr # so I can import R package BiasedUrn for the Fisher variant
import rpy2.robjects.numpy2ri
from undetected_extinctions import frst_last_changed_E, get_SE, find_U0_bnd
# user parameters
# ---
percentile = 95
# no samples; omega values to explore; file name to plot to
nreps = 10000
omegaV = np.linspace(.15, .95, 17)
U_T = 0 # assume that at the final timestep there are no undetected species remaining
rpy2.robjects.numpy2ri.activate()
biasedurn = importr('BiasedUrn')
# where databases are etc.
# ---
fname_frstlast = '../../data/processed/first_last_detns_final.csv'
fname_results = '../../results/classical/fisher_relationship/fisher_relationship.csv' # where we append our data to
# get record of first and last observations, and other info
# ---
# read in data
csv_f = csv.reader(open(fname_frstlast))
header = next(csv_f)
# each row of frst_last_full corresponds to a particular species
frst_last = [ ( int(row[1]), int(row[2]) ) for row in csv_f ]
# modify record, so that we only take intervals where the number of detected extinct species E changes
years_mod, frst_last_mod = frst_last_changed_E(frst_last)
# calculate the S and E for the timeseries
_, S, E = get_SE(frst_last_mod, years_mod)
# get important information about the record
d = S[1:] - S[:-1] + E[1:] - E[:-1] # discoveries at each timestep
psi = S[:-1] - (E[1:]-E[:-1]) # survivors at each timestep
extns = E[1:] - E[:-1] # extinctions at each timestep
T_idx = len(S) # number of timesteps
tV = list( reversed(range(1,T_idx)) ) # list of timesteps to work backwards through
# for each omega in the list, estimate N, and append to results file
# ---
for omega in omegaV:
print(omega)
# sampling to obtain estimates of total no. of species N
# ---
NV = list()
for nrep in range(nreps):
# work our way backwards through the time series, randomly sampling confidence leve
if nrep % 10 == 0:
print('omega = ', str(omega), '; nrep = ', str(nrep) )
U = [0]*T_idx # a place to store this replicate
U[-1] = U_T
impossibleFlag = False
for t in tV: # work our way backwards
alpha = uniform.rvs()
S0 = S[t-1]; S1 = S[t]; U1 = U[t]; d0 = d[t-1]
U[t-1], impossibleFlag = find_U0_bnd(alpha, S0, S1, U1, d0, impossibleFlag, omega, biasedurn)
# calculate summary info and store
N = S[0] + E[0] + U[0] # assumes X(0) = 0
NV.append(N)
# calculate summary statistics for this value of omega
# ---
N_mean = np.mean(NV)
N_lo = np.percentile(NV, (100-percentile)/2)
N_hi = np.percentile(NV, 100 - (100-percentile)/2)
# append to file
# ---
f = open(fname_results, 'a') # NOTE 'a', appending, so it can be done piecemeal
# header order is: omega,N_mean,N_lo,N_hi,nreps
f.write( ','.join( list(map(str, [omega, N_mean, N_lo, N_hi, nreps] )) ) )
f.write('\n')
f.close()
| 3.0625 | 3 |
whisk/whisk.py | BookletAI/whisk | 8 | 12767303 | """Main module."""
import whisk
from whisk.cli.log_tree import PARENT_TREE_NODE_PREFIX, CHILD_TREE_NODE_PREFIX
from cookiecutter.main import cookiecutter
from os.path import realpath
# https://docs.python.org/3/library/pathlib.html
# Object-oriented filesystem paths
from pathlib import Path
import logging
logger = logging.getLogger(__name__)
def root_module_dir():
"""
Returns a Path object with the root whisk module directory.
"""
filepath = realpath(__file__)
return Path(filepath).parents[0]
def cookiecutter_template_dir():
return str(root_module_dir() / 'template/')
def to_slug(str):
"""
Converts a string to a slug:
* Makes all letters lowercase
* Replaces spaces with underscores
"""
return str.lower().replace(' ', '_')
def create(dir, force=False,
module_name=None,
dependency=f"whisk=={whisk.__version__}",
install_requires=f"whisk=={whisk.__version__}"):
"""
Creates a whisk project.
Parameters
----------
dir : str
Path of the directory to create the project. The directory name is
converted to a slug via :func:`project_name_to_slug`.
module_name : str, optional
Name of the module used when importing the project. This is converted to a
slug via :func:`project_name_to_slug`. Default is the ``project_name``.
force : bool, optional
Recreates the project directory if it exists. Default is `False`.
dependency : str, optional
The whisk dependency entry in the project's requirements.txt file.
Default locks to the current version. The version lock is restrictive
as earlier and later versions of whisk could expect a different
template structure and break functionality.
install_requires : str, optional
The whisk ``install_requires`` entry in the project's ``setup.py``
file. Default locks to the current version. The version lock is
restrictive as earlier and later versions of whisk could expect a
different template structure and break functionality.
"""
path = Path(dir).absolute()
logger.debug(f"Creating project in {path}.")
project_name = path.stem
output_dir = path.parent
project_name_slug = to_slug(project_name)
if module_name:
module_name_slug = to_slug(module_name)
else:
module_name_slug = project_name_slug
# `whisk_dependency` is more flexible (for example, specifying a local
# install) than `whisk_install_requires` and is used in testing to require
# the local version of whisk.
extra_content = {
"repo_name": project_name_slug,
"project_name": module_name_slug,
"whisk_dependency": dependency,
"whisk_install_requires": install_requires
}
logger.debug(f"Creating whisk project with extra_content={extra_content}")
logger.info(PARENT_TREE_NODE_PREFIX +
"Creating project directory structure...")
res = cookiecutter(cookiecutter_template_dir(),
no_input=True,
overwrite_if_exists=force,
output_dir=output_dir,
extra_context=extra_content)
logger.info(CHILD_TREE_NODE_PREFIX+"Project created in %s", res)
logger.info(CHILD_TREE_NODE_PREFIX+"DONE.")
return res
| 2.734375 | 3 |
machine_learning/anomaly/demo1.py | caserwin/daily-learning-python | 1 | 12767304 | # -*- coding: utf-8 -*-
# @Time : 2019/1/8 下午8:20
# @Author : yidxue
from __future__ import division
import numpy
import datetime
import pandas as pd
def get_all_file_path(path):
"""
循环遍历,得到一个文件夹第一层下的文件路径
"""
import os
file_name_list = os.listdir(path)
return [path + os.sep + file_name for file_name in file_name_list]
def read_file(path_ls):
"""
读数据
"""
map = {}
for file_path in path_ls:
with open(file_path, mode="r") as in_file:
for i, line in enumerate(in_file):
if not (line.strip == "" or line.startswith('clusterid')):
data = line.strip().split(",")
cluster = data[0]
timestamp = data[1]
rtts = float(data[7])
if cluster in map.keys():
map[cluster][timestamp] = rtts
else:
cluster_map = {timestamp: rtts}
map[cluster] = cluster_map
return map
def write_file(file_path, context_ls, method='a'):
"""
写数据到一个文件
:param file_path:
:param method: 'a'表示默认为追加方式, 'wb'表示覆盖或者创建文件写入
:param context:
"""
with open(file_path, method) as fo:
for text in context_ls:
fo.write(text + "\n")
# 关闭打开的文件
fo.close()
def calculate_std(dps, moving_average):
variance = 0
flag_list = moving_average.isnull()
count = 0
for index in range(len(dps)):
if flag_list[index]:
count += 1
continue
variance += (dps[index] - moving_average[index]) ** 2
variance /= (len(dps) - count)
return numpy.sqrt(variance)
day = '2018-12-24'
# 1. 读数据
path = '/Users/cisco/Downloads/abnormal_value_2018lastweek/abnormal_value_{day}.csv'
path_ls = get_all_file_path(path.format(day=day))
# 2. 读数据
data_dict = read_file(path_ls)
# 3. 每个cluster时间戳进行排序
DESC = False
# 列表推导生成字典,这个字典的value的是排序后的另一个字典
data_sort = {
cluster: sorted(data_dict[cluster].items(), key=lambda d: datetime.datetime.strptime(d[0], '%Y-%m-%d %H:%M:%S'),
reverse=DESC)
for cluster in data_dict.keys()}
cluster = {}
for key in data_sort.keys():
cluster[key] = pd.Series({item[0]: item[1] for item in data_sort[key]})
# 4. 异常检测
for key in cluster.keys():
dps = pd.Series(cluster[key])
ewma_line = dps.ewm(span=4).mean()
ewma_std = calculate_std(dps, ewma_line)
result = []
for index in ewma_line.index:
if not (ewma_line[index] - ewma_std <= dps[index] <= ewma_line[index] + ewma_std):
result.append(key + "," + index + "," + str(dps[index]) + ",1")
else:
result.append(key + "," + index + "," + str(dps[index]) + ",0")
# 存数据
write_file('/Users/cisco/Desktop/{day}.csv'.format(day=day), result)
| 2.3125 | 2 |
happy_birthday_drchrono/drchronoAPI/api.py | TimothyBest/Happy_Birthday_drchrono | 0 | 12767305 | <filename>happy_birthday_drchrono/drchronoAPI/api.py
import requests, urllib
# TODO: make generic API get function
def get_patients(user, parameters={}):
social = user.social_auth.get(user=user)
access_token = social.extra_data['access_token']
headers = {'Authorization': 'Bearer {0}'.format(access_token)}
patients = []
patients_url = 'https://drchrono.com/api/patients?' + urllib.urlencode(parameters)
while patients_url:
data = requests.get(patients_url, headers=headers).json()
patients.extend(data['results'])
patients_url = data['next'] # A JSON null on the last page
return patients
def get_doctors(user, parameters={}):
social = user.social_auth.get(user=user)
access_token = social.extra_data['access_token']
headers = {'Authorization': 'Bearer {0}'.format(access_token)}
doctors = []
doctors_url = 'https://drchrono.com/api/doctors?' + urllib.urlencode(parameters)
while doctors_url:
data = requests.get(doctors_url, headers=headers).json()
doctors.extend(data['results'])
doctors_url = data['next'] # A JSON null on the last page
return doctors
| 2.84375 | 3 |
bot/app/digest/digest.py | dziban303/SpaceLaunchNow-Server | 0 | 12767306 | <reponame>dziban303/SpaceLaunchNow-Server
import logging
import bot.app.digest.daily as daily_check
import bot.app.digest.weekly as weekly_check
from bot.utils.config import keys
# import the logging library
# Get an instance of a logger
from spacelaunchnow import config
logger = logging.getLogger('bot.digest')
AUTH_TOKEN_HERE = keys['AUTH_TOKEN_HERE']
APP_ID = keys['APP_ID']
DAEMON_SLEEP = 6000
class DigestServer:
def __init__(self, debug=None, version=None):
if debug is None:
self.DEBUG = config.DEBUG
else:
self.DEBUG = debug
self.time_to_next_launch = None
self.next_launch = None
def run(self, daily=False, weekly=False):
if daily:
daily_check.check_launch_daily(self.DEBUG)
elif weekly:
weekly_check.check_launch_weekly(self.DEBUG)
else:
logger.error("Both daily and weekly false...ignoring request.")
| 2.421875 | 2 |
httoop/parser.py | spaceone/httoop | 13 | 12767307 | # -*- coding: utf-8 -*-
u"""Implements a state machine for the parsing process.
"""
# TODO: translation API
from __future__ import absolute_import
from httoop.exceptions import Invalid, InvalidBody, InvalidHeader, InvalidLine, InvalidURI
from httoop.header import Headers
from httoop.messages import Message
from httoop.status import BAD_REQUEST, NOT_IMPLEMENTED
from httoop.util import Unicode, _, integer
CR = b'\r'
LF = b'\n'
CRLF = CR + LF
NOT_RECEIVED_YET = True
class StateMachine(object):
u"""A protocol state machine which supports pipelining and
parses HTTP messages by turning them into appropriate objects."""
Message = Message # subclass provides the type
def __init__(self):
self.buffer = bytearray()
self.message = None
def _reset_state(self):
self.message = self.Message()
self.trailers = None
self.line_end = CRLF
self.message_length = None
self.chunked = False
self.state = dict(
startline=False,
protocol=False,
headers=False,
body=False,
trailer=False,
)
def on_message_started(self):
self._reset_state()
def on_startline_complete(self):
self.state['protocol'] = True
self.on_protocol_complete()
def on_method_complete(self):
pass
def on_uri_complete(self):
pass
def on_protocol_complete(self):
pass
def on_headers_complete(self):
self.set_body_content_encoding()
self.set_body_content_type()
def on_body_complete(self):
self.message.body.seek(0)
self.message.body.decompress()
self.message.body.seek(0)
self.set_content_length()
def on_message_complete(self):
message = self.message
self.message = None
return message
def parse(self, data):
u"""Appends the given data to the internal buffer
and parses it as HTTP Request-Messages.
:param data:
data to parse
:type data: bytes
"""
self.buffer.extend(data)
try:
return tuple(x for x in self._parse() if x is not None)
except (InvalidHeader, InvalidLine, InvalidURI, InvalidBody) as exc:
raise BAD_REQUEST(Unicode(exc))
def _parse(self):
while self.buffer:
if self.message is None:
yield self.on_message_started()
state = self.state
if not state['startline']:
if self.parse_startline():
return
state['startline'] = True
yield self.on_startline_complete()
if not state['headers']:
if self.parse_headers():
return
state['headers'] = True
yield self.on_headers_complete()
if not state['body']:
if self.parse_body():
return
state['body'] = True
yield self.on_body_complete()
yield self.on_message_complete()
def parse_startline(self):
if CRLF not in self.buffer:
if LF not in self.buffer:
return NOT_RECEIVED_YET
self.line_end = LF
requestline, self.buffer = self.buffer.split(self.line_end, 1)
# parse request line
try:
self.message.parse(bytes(requestline))
except (InvalidLine, InvalidURI) as exc:
raise BAD_REQUEST(Unicode(exc))
def parse_headers(self):
# empty headers?
if self.buffer.startswith(self.line_end):
self.buffer = self.buffer[len(self.line_end):]
return False
header_end = self.line_end + self.line_end
if header_end not in self.buffer:
self._parse_single_headers()
# headers incomplete
return NOT_RECEIVED_YET
headers, self.buffer = self.buffer.split(header_end, 1)
self._parse_header(headers)
def _parse_single_headers(self):
if self.buffer.endswith(self.line_end):
headers, _, rest = self.buffer[:-len(self.line_end)].rpartition(self.line_end)
rest += self.buffer[-len(self.line_end):]
else:
headers, _, rest = self.buffer.rpartition(self.line_end)
if headers and _ and rest[:1] not in (b'', b'\t', b' '):
self.buffer = rest
self._parse_header(headers)
def _parse_header(self, headers):
# parse headers
if headers:
try:
self.message.headers.parse(bytes(headers))
except InvalidHeader as exc:
raise BAD_REQUEST(Unicode(exc))
def parse_body(self):
if self.message_length is None and not self.chunked:
self.determine_message_length()
if self.chunked:
return self.parse_chunked_body()
elif self.message_length:
return self.parse_body_with_message_length()
else:
return False # no message body
def determine_message_length(self):
# RFC 2616 Section 4.4
# get message length
# TODO: check if both is set
message = self.message
if 'Transfer-Encoding' in message.headers and message.protocol >= (1, 1):
# chunked transfer in HTTP/1.1
te = message.headers['Transfer-Encoding'].lower()
self.chunked = 'chunked' == te
if not self.chunked:
raise NOT_IMPLEMENTED(u'Unknown HTTP/1.1 Transfer-Encoding: %r' % te)
else:
# Content-Length header defines the length of the message body
try:
self.message_length = integer(message.headers.get("Content-Length", "0"))
if self.message_length < 0:
self.message_length = None
raise ValueError()
except ValueError:
raise BAD_REQUEST(_(u'Invalid Content-Length header.'))
def parse_body_with_message_length(self):
body, self.buffer = self.buffer[:self.message_length], self.buffer[self.message_length:]
self.message.body.parse(bytes(body))
blen = len(body)
unfinished = blen < self.message_length
self.message_length -= blen
if unfinished:
# the body is not yet received completely
return NOT_RECEIVED_YET
def parse_chunked_body(self):
if self.state['trailer']:
return self.parse_trailers()
if self.line_end not in self.buffer:
# chunk size info not received yet
return NOT_RECEIVED_YET
chunk_size, rest_chunk = self.__parse_chunk_size()
if len(rest_chunk) < (len(self.line_end) + chunk_size):
# chunk not received completely
return NOT_RECEIVED_YET
body_part, rest_chunk = rest_chunk[:chunk_size], rest_chunk[chunk_size:]
self.message.body.parse(bytes(body_part))
self.buffer = rest_chunk
if chunk_size == 0:
self.state['trailer'] = True
return self.parse_trailers()
if not rest_chunk.startswith(self.line_end):
raise InvalidBody(_(u'Invalid chunk terminator: %r'), rest_chunk[:2].decode('ISO8859-1'))
self.buffer = self.buffer[len(self.line_end):]
# next chunk
return self.parse_chunked_body()
def __parse_chunk_size(self):
line, rest_chunk = self.buffer.split(self.line_end, 1)
_chunk_size = line.split(b";", 1)[0].strip()
try:
chunk_size = integer(bytes(_chunk_size), 16)
if chunk_size < 0:
raise ValueError()
except (ValueError, OverflowError):
exc = InvalidHeader(_(u'Invalid chunk size: %r'), _chunk_size.decode('ISO8859-1'))
raise BAD_REQUEST(Unicode(exc))
else:
return chunk_size, rest_chunk
def parse_trailers(self):
# TODO: the code is exactly the same as parse_headers but
# we have to make sure no invalid header fields are send (only values told in Trailer header allowed)
if self.buffer.startswith(self.line_end):
self.buffer = self.buffer[len(self.line_end):]
return False # no trailers
trailer_end = self.line_end + self.line_end
if trailer_end not in self.buffer:
# not received yet
return NOT_RECEIVED_YET
trailers, self.buffer = self.buffer.split(trailer_end, 1)
self.trailers = Headers()
try:
self.trailers.parse(bytes(trailers))
except InvalidHeader as exc:
exc = InvalidHeader(_(u'Invalid trailers: %r'), Unicode(exc))
raise BAD_REQUEST(Unicode(exc))
self.merge_trailer_into_header()
return False
def merge_trailer_into_header(self):
message = self.message
for name in message.headers.values('Trailer'):
value = self.trailers.pop(name, None)
if value is not None:
message.headers.append(name, value)
if self.trailers:
msg_trailers = u'" ,"'.join(self.trailers.keys())
raise BAD_REQUEST(u'untold trailers: "%s"' % msg_trailers)
del self.trailers
def set_body_content_encoding(self):
if 'Content-Encoding' in self.message.headers:
try:
self.message.body.content_encoding = self.message.headers.element('Content-Encoding')
self.message.body.content_encoding.codec # pylint: disable=W0104
except Invalid as exc:
raise NOT_IMPLEMENTED(Unicode(exc))
def set_body_content_type(self):
if 'Content-Type' in self.message.headers:
self.message.body.mimetype = self.message.headers.element('Content-Type')
def set_content_length(self):
if 'Content-Length' not in self.message.headers:
self.message.headers['Content-Length'] = str(len(self.message.body)).encode('ASCII')
if self.chunked:
self.message.headers.pop('Transfer-Encoding') # FIXME: there could be other transfer codings as well, only pop out chunked!
| 2.65625 | 3 |
src/picobox/_stack.py | ikalnytskyi/picobox | 35 | 12767308 | <reponame>ikalnytskyi/picobox<gh_stars>10-100
"""Picobox API to work with a box at the top of the stack."""
import contextlib
import functools
import threading
import typing as t
from ._box import Box, ChainBox
def _copy_signature(method, instance=None):
# This is a workaround to overcome 'sphinx.ext.autodoc' inability to
# retrieve a docstring of a bound method. Here's the trick - we create
# a partial function, and autodoc can deal with partially applied
# functions.
if instance:
method = functools.partial(method, instance)
# The reason behind empty arguments is to reuse a signature of wrapped
# function while preserving "__doc__", "__name__" and other accompanied
# attributes. They are very helpful for troubleshooting as well as
# necessary for Sphinx API reference.
return functools.wraps(method, (), ())
def _create_stack_proxy(stack, empty_stack_error):
"""Create an object that proxies all calls to the top of the stack."""
class _StackProxy:
def __getattribute__(self, name):
try:
return getattr(stack[-1], name)
except IndexError:
raise RuntimeError(empty_stack_error)
return _StackProxy()
@contextlib.contextmanager
def _create_push_context_manager(box, pop_callback):
"""Create a context manager that calls something on exit."""
try:
yield box
finally:
# Ensure the poped box is the same that was submitted by this exact
# context manager. It may happen if someone messed up with order of
# push() and pop() calls. Normally, push() should be used a context
# manager to avoid this issue.
assert pop_callback() is box
class Stack:
"""Stack is a dependency injection (DI) container for containers (boxes).
While :class:`Box` is a great way to manage dependencies, it has no means
to override them. This might be handy most of all in tests, where you
usually need to provide a special set of dependencies configured for
test purposes. This is where :class:`Stack` comes in. It provides the very
same interface Box does, but proxies all calls to a box on the top.
This basically means you can define injection points once, but change
dependencies on the fly by changing DI containers (boxes) on the stack.
Here's a minimal example of how a stack can be used::
import picobox
stack = picobox.Stack()
@stack.pass_('magic')
def do(magic):
return magic + 1
foobox = picobox.Box()
foobox.put('magic', 42)
barbox = picobox.Box()
barbox.put('magic', 13)
with stack.push(foobox):
with stack.push(barbox):
assert do() == 14
assert do() == 43
.. note::
Usually you want to have only one stack instance to wire things up.
That's why picobox comes with pre-created stack instance. You can
work with that instance using :func:`push`, :func:`pop`, :func:`put`,
:func:`get` and :func:`pass_` functions.
:param name: (optional) A name of the stack.
.. versionadded:: 2.2
"""
def __init__(self, name: t.Text = None):
self._name = name
self._stack = []
self._lock = threading.Lock()
# A proxy object that proxies all calls to a box instance on the top
# of the stack. We need such an object to provide a set of functions
# that mimic Box interface but deal with a box on the top instead.
# While it's not completely necessary for `put()` and `get()`, it's
# crucial for `pass_()` due to its laziness and thus late evaluation.
self._topbox = _create_stack_proxy(
self._stack, "No boxes found on the stack, please `.push()` a box first."
)
def __repr__(self):
name = self._name
if not self._name:
name = "0x%x" % id(self)
return "<Stack (%s)>" % name
def push(self, box: Box, *, chain: bool = False):
"""Push a :class:`Box` instance to the top of the stack.
Returns a context manager, that will automatically pop the box from the
top of the stack on exit. Can also be used as a regular function, in
which case it's up to callers to perform a corresponding call to
:meth:`.pop`, when they are done with the box.
:param box: A :class:`Box` instance to push to the top of the stack.
:param chain: (optional) Look up missed keys one level down the stack.
To look up through multiple levels, each level must be created with
this option set to ``True``.
"""
# list.append() is a thread-safe operation in CPython, yet the safety
# is not guranteed by the language itself. So the lock is used here to
# ensure the code works properly even when running on alternative
# implementations.
with self._lock:
if chain and self._stack:
box = ChainBox(box, self._stack[-1])
self._stack.append(box)
return _create_push_context_manager(self._stack[-1], self._stack.pop)
def pop(self) -> Box:
"""Pop the box from the top of the stack.
Should be called once for every corresponding call to :meth:`.push` in
order to remove the box from the top of the stack, when a caller is
done with it.
.. note::
Normally :meth:`.push` should be used a context manager, in which
case the box on the top is removed automatically on exit from
the block (i.e. no need to call :meth:`.pop` manually).
:return: a removed box
:raises IndexError: If the stack is empty and there's nothing to pop.
"""
# list.append() is a thread-safe operation in CPython, yet the safety
# is not guranteed by the language itself. So the lock is used here to
# ensure the code works properly even when running on alternative
# implementations.
with self._lock:
return self._stack.pop()
@_copy_signature(Box.put)
def put(self, *args, **kwargs):
"""The same as :meth:`Box.put` but for a box at the top."""
return self._topbox.put(*args, **kwargs)
@_copy_signature(Box.get)
def get(self, *args, **kwargs):
"""The same as :meth:`Box.get` but for a box at the top."""
return self._topbox.get(*args, **kwargs)
@_copy_signature(Box.pass_)
def pass_(self, *args, **kwargs):
"""The same as :meth:`Box.pass_` but for a box at the top."""
# Box.pass_(topbox, *args, **kwargs) does not work in Python 2 because
# Box.pass_ is an unbound method, and unbound methods require a class
# instance as its first argument. Therefore, we need a workaround to
# extract a function without "method" wrapping, so we can pass anything
# as the first argument.
return vars(Box)["pass_"](self._topbox, *args, **kwargs)
_instance = Stack("shared")
@_copy_signature(Stack.push, _instance)
def push(*args, **kwargs):
"""The same as :meth:`Stack.push` but for a shared stack instance.
.. versionadded:: 1.1 ``chain`` parameter
"""
return _instance.push(*args, **kwargs)
@_copy_signature(Stack.pop, _instance)
def pop(*args, **kwargs):
"""The same as :meth:`Stack.pop` but for a shared stack instance.
.. versionadded:: 2.0
"""
return _instance.pop(*args, **kwargs)
@_copy_signature(Stack.put, _instance)
def put(*args, **kwargs):
"""The same as :meth:`Stack.put` but for a shared stack instance."""
return _instance.put(*args, **kwargs)
@_copy_signature(Stack.get, _instance)
def get(*args, **kwargs):
"""The same as :meth:`Stack.get` but for a shared stack instance."""
return _instance.get(*args, **kwargs)
@_copy_signature(Stack.pass_, _instance)
def pass_(*args, **kwargs):
"""The same as :meth:`Stack.pass_` but for a shared stack instance."""
return _instance.pass_(*args, **kwargs)
| 1.960938 | 2 |
mtgjson5/classes/mtgjson_deck_header.py | 0az/mtgjson | 512 | 12767309 | <gh_stars>100-1000
"""
MTGJSON Singular Deck Header Object
"""
from typing import Any, Dict
from ..classes.mtgjson_deck import MtgjsonDeckObject
from ..utils import to_camel_case
class MtgjsonDeckHeaderObject:
"""
MTGJSON Singular Deck Header Object
"""
code: str
file_name: str
name: str
release_date: str
type: str
def __init__(self, output_deck: MtgjsonDeckObject) -> None:
"""
Initialize the header given a deck
"""
self.code = output_deck.code
self.file_name = output_deck.file_name
self.name = output_deck.name
self.release_date = output_deck.release_date
self.type = output_deck.type
def to_json(self) -> Dict[str, Any]:
"""
Support json.dump()
:return: JSON serialized object
"""
return {
to_camel_case(key): value
for key, value in self.__dict__.items()
if "__" not in key and not callable(value)
}
| 2.34375 | 2 |
aikit/datasets/__init__.py | gfournier/aikit | 23 | 12767310 | # -*- coding: utf-8 -*-
"""
Created on Fri May 4 13:33:07 2018
@author: <NAME>
"""
from .datasets import (
DatasetEnum,
load_dataset,
load_titanic,
load_imdb,
load_electricity,
load_housing,
load_quora,
load_abalone,
load_pokemon,
load_wikinews,
)
__all__ = [
"DatasetEnum",
"load_dataset",
"load_titanic",
"load_imdb",
"load_electricity",
"load_housing",
"load_quora",
"load_abalone",
"load_pokemon",
"load_wikinews",
]
| 1.5 | 2 |
server/api/bin/api_start.py | mminamina/311-data | 0 | 12767311 | <reponame>mminamina/311-data
import sys
from os.path import join, dirname
sys.path.append(join(dirname(__file__), '../src'))
def update():
from datetime import datetime
import time
import db
import pb
time.sleep(5)
last_updated = db.info.last_updated()
time_since_update = datetime.utcnow() - last_updated
if time_since_update.days >= 1:
db.requests.update()
if pb.enabled:
pb.populate()
if __name__ == '__main__':
import app
from multiprocessing import Process
from settings import Server
if Server.UPDATE_ON_START:
Process(target=update).start()
app.start()
| 2.296875 | 2 |
tests/preferences_test.py | CraftyChimera/nittfest-site | 0 | 12767312 | """
Tests for preferences route
"""
import json
from fastapi.testclient import TestClient
from config.settings import settings
jwt_test = settings.test_jwt
header = {"Authorization": f"Bearer {jwt_test}"}
ROUTE = "/preferences/"
body = json.dumps(
{
"email": "string",
"preferences": ["EVENTS", "AMBIENCE", "MARKETING"],
}
)
def post_preferences_first_fill(client: TestClient):
"""
post prefs for first time and check prefs
"""
post_response = client.post(url=ROUTE, data=body, headers=header)
assert post_response.status_code == 200
assert post_response.json() == {"status": True}
def post_preferences_another_fill(client: TestClient):
"""
post prefs for another time and check prefs
"""
post_response = client.post(url=ROUTE, data=body, headers=header)
assert post_response.status_code == 403
assert post_response.json() == {"detail": "Preferences Already Filled"}
def check_preferences_already_filled(client: TestClient):
"""
check prefs
"""
get_response = client.get(url=ROUTE, headers=header)
assert get_response.status_code == 200
assert get_response.json() == {"status": True}
| 2.5625 | 3 |
settings.py | Eforcers/python-gae-template | 1 | 12767313 | #-*- coding: utf-8 -*-
# vim: set fileencoding=utf-8
"""
settings.py
Configuration for Flask app
Important: Place your keys in the secret_keys.py module,
which should be kept out of version control.
"""
import logging
import os
import urllib
from secret_keys import CSRF_SECRET_KEY, SESSION_KEY
class Config(object):
"""
Default configuration
"""
#Production is the
ENV_PRODUCTION = 'PRODUCTION'
#Staging is used for testing replicating the same production environment
ENV_STAGING = 'STAGING'
#Done sessions cant be modified
ENV_LOCAL = 'LOCAL'
ENVIRONMENT_CHOICES = [
ENV_PRODUCTION,
ENV_STAGING,
ENV_LOCAL,
]
DEBUG = False
TESTING = False
STAGING = False
PRODUCTION = False
CSRF_ENABLED = True
# Set secret keys for CSRF protection
SECRET_KEY = CSRF_SECRET_KEY
CSRF_SESSION_KEY = SESSION_KEY
OAUTH2_SCOPE = ""
EMAIL_REGEXP = "^[a-zA-Z0-9'._-]+@[a-zA-Z0-9._-]+.[a-zA-Z]{2,6}$"
class ProductionConfig(Config):
"""
Overrides the default configuration
"""
DEBUG = False
TESTING = False
STAGING = False
PRODUCTION = True
CSRF_ENABLED = True
class TestingConfig(Config):
"""
Configuration used for development and testing
"""
DEBUG = False
TESTING = True
PRODUCTION = False
CSRF_ENABLED = False
class DevelopmentConfig(TestingConfig):
"""
Configuration used for local development
"""
DEFAULT_SERVER_NAME = 'localhost:8080'
CUSTOM_SERVER_NAME = 'localhost:8080'
def get_setting(key):
"""
Get the value for a setting with the given key, since cache is shared
between staging and production is necessary to include that in the key too
:param key: string that represents the setting key
:return: the value of the setting
"""
try:
from main import flask_app
return flask_app.config[key]
except:
environment = get_environment()
#Load settings from the corresponding class
if environment == Config.ENV_PRODUCTION:
obj = ProductionConfig()
else:
obj = TestingConfig()
return getattr(obj, key)
def get_environment():
"""
Returns the environment based on the OS variable, server name and app id
:return: The current environment that the app is running on
"""
# Auto-set settings object based on App Engine dev environ
if 'SERVER_SOFTWARE' in os.environ:
if os.environ['SERVER_SOFTWARE'].startswith('Dev'):
return Config.ENV_LOCAL
elif os.environ['SERVER_SOFTWARE'].startswith('Google App Engine/'):
#For considering an environment staging we assume the version id
# contains -staging and the URL
current_version_id = str(os.environ['CURRENT_VERSION_ID']) if (
'CURRENT_VERSION_ID') in os.environ else ''
if '-staging' in current_version_id:
return Config.ENV_STAGING
#If not local or staging then is production TODO: really?
return Config.ENV_PRODUCTION
return Config.ENV_LOCAL
def get_raw_server_name():
"""
The raw server name is GAE generated by default, it's meant for a
specific version of an app. The version ID is taken from OS variable and
the ID from the identity API
:return: URL in the form version.appid.appspot.com
"""
from google.appengine.api import app_identity
return '%s.%s.appspot.com' % (os.environ[
'CURRENT_VERSION_ID'].split('.')[0], app_identity.get_application_id())
def get_url():
"""Returns the URL of the page currently being served.
Returns:
The full URL of the page currently being served.
"""
if os.environ['SERVER_PORT'] == '80':
scheme = 'http://'
else:
scheme = 'https://'
host = os.environ['SERVER_NAME']
script_name = urllib.quote(os.environ.get('SCRIPT_NAME', ''))
path_info = urllib.quote(os.environ.get('PATH_INFO', ''))
qs = os.environ.get('QUERY_STRING', '')
if qs:
qs = '?' + qs
return scheme + host + script_name + path_info + qs
| 2.40625 | 2 |
sdk/consumption/azure-mgmt-consumption/tests/test_budgets.py | adewaleo/azure-sdk-for-python | 1 | 12767314 | # coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import datetime
import unittest
import azure.mgmt.consumption
import azure.mgmt.consumption.models
from devtools_testutils import AzureMgmtTestCase, ResourceGroupPreparer
class MgmtConsumptionTest(AzureMgmtTestCase):
def setUp(self):
super(MgmtConsumptionTest, self).setUp()
self.consumption_client = self.create_mgmt_client(
azure.mgmt.consumption.ConsumptionManagementClient
)
@ResourceGroupPreparer()
def test_budgets(self, resource_group):
SUBSCRIPTION_ID = getattr(self.settings, 'SUBSCRIPTION_ID', "123")
SCOPE = '/subscriptions/{}/resourceGroups/{}'.format(SUBSCRIPTION_ID, resource_group.name)
BUDGET_NAME = self.get_resource_name('budget')
# create
BODY = {
"category": "Cost",
"amount": '100',
"timeGrain": "Monthly",
"timePeriod": {
"startDate": "2020-10-01T00:00:00Z",
"endDate": "2021-10-31T00:00:00Z"
}
}
self.consumption_client.budgets.create_or_update(SCOPE, BUDGET_NAME, BODY)
# get
self.consumption_client.budgets.get(SCOPE, BUDGET_NAME)
# delete
self.consumption_client.budgets.delete(SCOPE, BUDGET_NAME)
# ------------------------------------------------------------------------------
if __name__ == '__main__':
unittest.main()
| 2.078125 | 2 |
play_chess.py | jstrassburg/cs6230-chess-player | 0 | 12767315 | import argparse
from chess_player.ChessGame import ChessGame
from chess_player.Player import SearchPlayer, RandomPlayer
from chess_player.Scorer import SimplifiedEvaluationFunction
from random import randint
from time import perf_counter
class Program:
@staticmethod
def main():
program = Program()
program.run()
def __init__(self):
self._args = None
self._parser = argparse.ArgumentParser(description="Play some chess")
self._scorer = SimplifiedEvaluationFunction()
self._stronger = None
def run(self):
self.add_arguments_and_parse()
print(f"Playing chess with a search depth of {self._args.search_depth} and {self._args.max_children} "
f"children for {self._args.max_turns} turns.")
with open(self._args.outfile, 'a') as outfile:
for i in range(self._args.iterations):
print(f"Playing game iteration {i}...")
start_time = perf_counter()
termination, winner_won, played_turns = self.play_chess()
run_time = perf_counter() - start_time
print(f"This game took: {run_time:0.2f} seconds...\n\n")
outfile.write(f"{self._args.search_depth},{self._args.max_children},{self._args.max_turns},"
f"{run_time:0.2f},{termination},{self._stronger},{winner_won},{played_turns}\n")
def play_chess(self) -> (str, str, int):
search_depth = self._args.search_depth
max_children = self._args.max_children
# flip a coin to see who gets the better player (search vs. random)
if randint(0, 1) == 0:
print(f"The white player should be stronger.")
white_player = SearchPlayer(
search_depth=search_depth, max_children=max_children, scorer=self._scorer)
black_player = RandomPlayer()
self._stronger = 'White stronger'
else:
print(f"The black player should be stronger.")
white_player = RandomPlayer()
black_player = SearchPlayer(
search_depth=search_depth, max_children=max_children, scorer=self._scorer)
self._stronger = 'Black stronger'
game = ChessGame(white_player=white_player, black_player=black_player)
game.play_until(self._args.max_turns)
game.print_game_stats()
termination, winner_won, played_turns = game.get_results()
game.reset()
return termination, winner_won, played_turns
def add_arguments_and_parse(self):
self._parser.add_argument("--search-depth", dest="search_depth", required=False, default=3, type=int,
help="How many levels deep to search for a good move. Default: 3")
self._parser.add_argument("--max-children", dest="max_children", required=False, default=5, type=int,
help="How many random legal moves will be evaluated. Default: 5")
self._parser.add_argument("--max-turns", dest="max_turns", required=False, default=150, type=int,
help="Play until this many turns have been played. Default: 150")
self._parser.add_argument("--iterations", dest="iterations", required=False, default=10, type=int,
help="How many iterations to run with this configuration. Default: 10")
self._parser.add_argument("--outfile", dest="outfile", required=False, default='chess-results.csv', type=str,
help="Where to write the results. Default: chess-results.csv")
self._args = self._parser.parse_args()
if __name__ == "__main__":
Program.main()
| 3.234375 | 3 |
bouser_simargl/message.py | hitsl/bouser_simargl | 0 | 12767316 | # -*- coding: utf-8 -*-
from bouser.utils import as_json
__author__ = 'viruzzz-kun'
class Message(object):
immediate = True # Мгновенное сообщение: будет ставиться в очередь, не пишется в лог
secondary = False # Вторичное сообщение: не пишется в лог
control = False # Управляющее сообщение: для управления клиентами
magic = None # Магическое число для RPC
topic = None # тема сообщения
sender = None # User ID отправителя
recipient = None # User ID получателя
envelope = False # Пачка
def __init__(self):
self.tags = set()
self.hops = []
self.data = None
def make_magic(self):
import os
self.magic = os.urandom(16)
def __json__(self):
return {
'i': bool(self.immediate),
's': bool(self.secondary),
'envelope': bool(self.envelope),
'ctrl': self.control,
'topic': self.topic,
'magic': self.magic,
'sender': self.sender,
'recipient': self.recipient,
'tags': sorted(self.tags),
'data': self.data,
'hops': self.hops,
}
@classmethod
def from_json(cls, j):
result = cls()
result.merge_with_dict(j)
return result
def merge_with_dict(self, j):
self.control = j.get('ctrl', False)
self.magic = j.get('magic', None)
self.topic = j.get('topic', None)
self.sender = j.get('sender')
self.recipient = j.get('recipient')
self.tags = set(j.get('tags', []))
self.data = j.get('data')
self.immediate = j.get('i', True)
self.secondary = j.get('s', False)
self.envelope = j.get('envelope', False)
self.hops = j.get('hops', [])
| 2.203125 | 2 |
api/tests/test_balance_payments.py | jcuna/room-mgt | 0 | 12767317 | <gh_stars>0
from datetime import datetime, timedelta
import pytest
from dateutil.relativedelta import *
from _decimal import Decimal
from flask.testing import FlaskClient
from tests import front_end_date, endpoint
from tests.seeders import seed_tenant, seed_new_agreement, seed_project, seed_room
def test_seeding_data(client: FlaskClient, admin_login: dict):
project_resp = seed_project(client, admin_login)
assert 'id' in project_resp.json
assert project_resp.status_code == 200
room_resp = seed_room(client, admin_login, {'project_id': project_resp.json['id']})
assert 'id' in room_resp.json
assert room_resp.status_code == 200
tenant_resp = seed_tenant(client, admin_login)
assert 'id' in tenant_resp.json
assert tenant_resp.status_code == 200
def test_agreement(client: FlaskClient, admin_login: dict):
from dal.models import Balance, RentalAgreement, Tenant, db, TenantHistory, Payment
from core.crons.balances import balances_cron
tenants = Tenant.query.all()
assert len(tenants) == 1
tenant = tenants.pop()
assert hasattr(tenant, 'id')
tenant_id = tenant.id
# create a new agreement with a balance due today
agreement_resp = seed_new_agreement(client, admin_login, {'tenant_id': tenant_id})
assert 'id' in agreement_resp.json
assert agreement_resp.status_code == 200
balances = Balance.query.all()
assert len(balances) == 1, 'only one balance should exist, the one created on agreement creation'
balance = balances.pop()
assert isinstance(balance.agreement_id, int)
assert balance.balance == Decimal(5900), 'balance should be the sum of deposits and agreement rate'
assert balance.due_date.date() == datetime.utcnow().date()
assert isinstance(balance.agreement, RentalAgreement)
# run balance generator
balances_cron()
balances = Balance.query.all()
assert len(balances) == 1, 'We created an agreement with today as due date so no new balances \
should be created after balance cron runs'
# remove all data related to this agreement to test other scenarios
for b in balances: db.session.delete(b)
db.session.commit()
# should've cascaded through
assert len(RentalAgreement.query.all()) == 0
assert len(TenantHistory.query.all()) == 0
assert len(Payment.query.all()) == 0
assert len(Balance.query.all()) == 0
def test_new_balance(client: FlaskClient, admin_login: dict):
from core.crons.balances import balances_cron
from dal.models import Balance, Tenant, RentalAgreement
tenants = Tenant.query.all()
tenant_id = tenants.pop().id
# create a new agreement with a balance due in the past so it generates a new balance
start_date = datetime.utcnow() - timedelta(days=1)
override = {'tenant_id': tenant_id, 'date': front_end_date(start_date)}
seed_new_agreement(client, admin_login, override)
# run balance generator
balances_cron()
balances = Balance.query.all()
assert len(balances) == 2, 'our latest agreement has a balance due yesterday, \
so we should have generated a new balance for the new period'
last_balance = Balance.query.order_by(Balance.due_date.desc()).limit(1).first()
assert last_balance.balance == Decimal(7400), 'new balance should be the sum of the previous balance \
plus the agreements rate since no payment has been made'
assert last_balance.due_date.date() == (start_date + timedelta(weeks=1)).date(), 'due date is a week \
from yesterday (start_date) because we seeded agreement with weekly payment'
balances_cron()
assert Balance.query.count() == 2, 'We should still only have two balances since the newly created balance \
is not ready to be processed'
assert RentalAgreement.query.count() == 1, 'only one rental agreement thus far'
def test_tenant_balance_generation(client: FlaskClient, admin_login: dict):
from dal.models import Tenant, RentalAgreement, Project, Balance
from core.crons.balances import balances_cron
override = {
'email': '<EMAIL>',
'first_name': 'Sample2',
'last_name': 'Tenant2',
'identification_number': '223-1234567-8',
'phone': '5555555556'
}
# just positive testing for now. A scenario where a tenant with same id number, email or phone # should fail
tenant_resp = seed_tenant(client, admin_login, override)
assert 'id' in tenant_resp.json
assert tenant_resp.status_code == 200
assert Tenant.query.count() == 2
tenant_id = tenant_resp.json['id']
project_id = Project.query.first().id
# seed another room
room_resp = seed_room(client, admin_login, {'name': 'MA-1001', 'project_id': project_id})
# create a new agreement with a balance due in the past so it generates a new balance
start_date = datetime.utcnow() - timedelta(days=4)
override = {
'date': front_end_date(start_date),
'deposit': '3000.00',
'interval': '400',
'rate': '3000.00',
'room_id': room_resp.json['id'],
'tenant_id': tenant_id
}
agreement = seed_new_agreement(client, admin_login, override)
assert agreement.status_code == 200
assert Balance.query.count() == 3, 'We should have thee balances, two from previous and one \
from just inserted one'
assert RentalAgreement.query.count() == 2, 'Should have two rental agreements now'
balances_cron()
new_balance = Balance.query.filter(Balance.agreement_id == agreement.json['id']).order_by(
Balance.due_date.desc()
).limit(1).first()
assert new_balance.balance == Decimal(9000), 'new balance should be the sum of the previous balance \
plus the agreements rate since no payment has been made'
assert new_balance.due_date.date() == (start_date + relativedelta(months=1)).date()
assert Balance.query.count() == 4, 'Only 4 balances should exist right now'
balances_cron()
assert Balance.query.count() == 4, 'Only 4 balances should exist right now since no new agreements or \
date has changed'
def test_no_balance_created_for_canceled_agreement(client: FlaskClient, admin_login: dict):
from dal.models import Balance
from core.crons.balances import balances_cron
override = {
'email': '<EMAIL>',
'first_name': 'Jamal',
'last_name': 'Cristof',
'identification_number': '244-1234567-8',
'phone': '5555555444'
}
tenant_resp = seed_tenant(client, admin_login, override)
start_date = datetime.utcnow() - timedelta(days=4)
tenant_id = tenant_resp.json['id']
# create a new agreement with a balance due today and then cancel agreement
agreement_resp = seed_new_agreement(client, admin_login, {'tenant_id': tenant_id, 'date': front_end_date(start_date)})
assert 'id' in agreement_resp.json
assert agreement_resp.status_code == 200
cancellation = client.put(endpoint('/agreements/{}'.format(agreement_resp.json['id'])), headers=admin_login, json={
'id': agreement_resp.json['id'],
'terminated_on': front_end_date(),
'refund': 0
})
assert cancellation.status_code == 200
assert Balance.query.count() == 5, 'Verify only 5 balances exist, the initial balance'
balances_cron()
assert Balance.query.count() == 5, 'Verify no balances where created for a cancelled agreement'
@pytest.mark.parametrize('_in, out, c', [(4500.00, 2000.00, 4), (3500.00, 3000.00, 5), (1250.99, 5249.01, 6)])
def test_tenant_balance_generation_with_payments(client: FlaskClient, admin_login: dict, _in, out, c):
from dal.models import Tenant, RentalAgreement, Project, Balance
from core.crons.balances import balances_cron
override = {
'email': 'tenant' + str(int(_in)) + '@tenant.com',
'first_name': 'Sample' + str(int(_in)) + '',
'last_name': 'Tenant' + str(int(_in)) + '',
'identification_number': '223-1' + str(int(_in)) + '67-8',
'phone': '555555' + str(int(_in))
}
tenant = seed_tenant(client, admin_login, override)
assert 'id' in tenant.json
assert tenant.status_code == 200
assert Tenant.query.count() == c
# seed another room
room_resp = seed_room(
client,
admin_login,
{'name': 'MA-' + str(int(_in)), 'project_id': Project.query.first().id}
)
# create a new agreement with a balance due in the past so it generates a new balance
start_date = datetime.utcnow() - timedelta(days=2)
override = {
'date': front_end_date(start_date),
'deposit': '2500.00',
'interval': '200', # biweekly
'rate': '2000.00',
'room_id': room_resp.json['id'],
'tenant_id': tenant.json['id']
}
agreement_resp = seed_new_agreement(client, admin_login, override)
agreement = RentalAgreement.query.filter(RentalAgreement.id == agreement_resp.json['id']).first()
assert len(agreement.balances) == 1
assert RentalAgreement.query.count() == c
payment = client.post(
endpoint('/pay-balance'),
json={'balance_id': agreement.balances[0].id, 'payment_type_id': 1, 'amount': _in},
headers=admin_login
)
assert 'id' in payment.json
assert payment.status_code == 200
balances_cron()
balance = Balance.query.filter(Balance.agreement_id == agreement_resp.json['id'])\
.order_by(Balance.due_date.desc()).limit(1).first()
assert float(balance.balance) == out
assert balance.due_date.date() == (start_date + timedelta(days=14)).date()
balances_cron()
agreement = RentalAgreement.query.filter(RentalAgreement.id == agreement_resp.json['id']).first()
assert len(agreement.balances) == 2, 'No new balance should`ve been created for this agreement'
def test_tenant_balance_not_created(client: FlaskClient, admin_login: dict):
from dal.models import Tenant, RentalAgreement, Project, Balance
from core.crons.balances import balances_cron
override = {
'email': '<EMAIL>',
'first_name': 'Sample4',
'last_name': 'Tenant4',
'identification_number': '423-1234567-8',
'phone': '5555555558'
}
tenant_resp = seed_tenant(client, admin_login, override)
assert 'id' in tenant_resp.json
assert tenant_resp.status_code == 200
assert Tenant.query.count() == 7
# seed another room
room_resp = seed_room(
client,
admin_login,
{'name': 'MA-1004', 'project_id': Project.query.first().id}
)
# create a new agreement with a balance due in the past so it generates a new balance
start_date = datetime.utcnow() + timedelta(days=4)
override = {
'date': front_end_date(start_date),
'deposit': '3000.00',
'interval': '200', # biweekly
'rate': '2000.00',
'room_id': room_resp.json['id'],
'tenant_id': tenant_resp.json['id']
}
agreement_resp = seed_new_agreement(client, admin_login, override)
assert Balance.query.count() == 12
agreement = RentalAgreement.query.filter(RentalAgreement.id == agreement_resp.json['id']).first()
assert len(agreement.balances) == 1
assert agreement.balances[0].balance == Decimal(5000)
assert agreement.balances[0].due_date.date() == start_date.date()
balances_cron()
assert Balance.query.count() == 12, 'no new balances should`ve been created because agreement starts in the future'
agreement2 = RentalAgreement.query.filter(RentalAgreement.id == agreement_resp.json['id']).first()
assert len(agreement2.balances) == 1
assert agreement2.balances[0].balance == Decimal(5000)
assert agreement2.balances[0].due_date.date() == start_date.date()
def test_cannot_create_agreement_older_than_5days(client: FlaskClient, admin_login: dict):
from dal.models import Tenant, Project
override = {
'email': '<EMAIL>',
'first_name': 'Sample13',
'last_name': 'Tenant13',
'identification_number': '223-1234517-2',
'phone': '5555555152'
}
# just positive testing for now. A scenario where a tenant with same id number, email or phone # should fail
tenant_resp = seed_tenant(client, admin_login, override)
assert 'id' in tenant_resp.json
assert tenant_resp.status_code == 200
assert Tenant.query.count() == 8
tenant_id = tenant_resp.json['id']
project_id = Project.query.first().id
# seed another room
room_resp = seed_room(client, admin_login, {'name': 'MA-1243', 'project_id': project_id})
# create a new agreement with a balance due in the past so it generates a new balance
start_date = datetime.utcnow() - timedelta(days=7)
override = {
'date': front_end_date(start_date),
'deposit': '3000.00',
'interval': '400',
'rate': '3000.00',
'room_id': room_resp.json['id'],
'tenant_id': tenant_id
}
agreement = seed_new_agreement(client, admin_login, override)
assert agreement.status_code == 400
assert 'Invalid date' in agreement.json['error']
| 2.28125 | 2 |
flask_cloudflare/__init__.py | BillSchumacher/Flask-CloudFlare | 5 | 12767318 | # -*- coding: utf-8 -*-
# Copyright (C) 2019 by <NAME>
#
# Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby
# granted.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
from flask import current_app
from pycflare import CloudFlare as PyCloudFlare
from werkzeug.local import LocalProxy
cloudflare = LocalProxy(lambda: current_app.extensions['cloudflare'])
class CloudFlare(object):
def __init__(self, app=None):
self.app = app
self.cf = None
if app is not None:
self.init_app(app)
def init_app(self, app):
auth_email = app.config.get('CLOUDFLARE_AUTH_EMAIL')
auth_key = app.config.get('CLOUDFLARE_AUTH_KEY')
redis_compat = app.config.get('CLOUDFLARE_ENABLE_REDIS_COMPATIBILITY', False)
if auth_key is None or auth_email is None:
raise RuntimeError("You must provide your CloudFlare AUTH_EMAIL and AUTH_KEY via CLOUDFLARE_AUTH_EMAIL and "
"CLOUDFLARE_AUTH_KEY in the app.config.")
self.cf = PyCloudFlare(auth_email=auth_email, auth_key=auth_key, enable_redis_compatibility=redis_compat)
app.extensions['cloudflare'] = self
def register_account(self, account_id, name):
return self.cf.register_account(account_id, name)
def __getattr__(self, item):
try:
return self.cf.__getattribute__(item)
except AttributeError:
print("CloudFlare: Attribute {value} was not found.".format(value=item))
return None
| 2.171875 | 2 |
fidimag/micro/dmi.py | computationalmodelling/fidimag | 53 | 12767319 | <reponame>computationalmodelling/fidimag
import fidimag.extensions.micro_clib as micro_clib
import numpy as np
from .energy import Energy
from fidimag.common.constant import mu_0
import fidimag.common.helper as helper
# import gc
class DMI(Energy):
"""
Compute the Dzyaloshinskii-Moriya interaction in the micromagnetic
framework. Currently, there are supported the following types of DMI:
bulk :: The energy density associated to this DMI type is:
w = D * M \cdot ( \nabla \times M)
which is found in B20 compunds or materials with
crystallographic class T. Using a finite differences
discretisation, this term turns into an expression similar
to the atomistic DMI with DMI vector D_ij = -D r_ij, where
r_ij is the vector from the i-th mesh site to the j-th
neighbour
interfacial :: The energy density of this DMI is, according to the
convention of Rohart et al [PRB 88, 184422 (2013)]
w = D * ( L_{xz}^{(x)} + L_{yz}^{(y)} )
where L are Lifshitz invariants. This DMI is found in
systems with their interface in contact with a heavy
metal (larger spin orbit coupling). A finite differences
discretisation turns this term into the equivalent
atomistic interfacial DMI term (with a different sign).
Since this DMI type is defined for interfacial systems,
the interaction is only defined with respect to
neighbouring sites in the xy plane and not between
layers in the z direction.
D_2d :: The energy density of this DMI is
w = D * ( L_{xz}^{(y)} + L_{yz}^{(x)} )
where L are Lifshitz invariants. This DMI is for
materials with symmetry class D_{2d}. Structures
known as anti-skyrmions are stabilised with this
DMI type
custom :: Pass n number of DMI constants as the main argument and
specify a dmi_vector array of length 18 * n. This array
has the dmi vector components for every NN in the order
[D1x(-x) D1y(-x) D1z(-x) D1x(+x) D1y(+x) ... D1z(+z),
D2x(-x) D2y(-x) ... D2z(+z),
...
]
The DMI field at the i-th site is specified as:
--- -> -> --- -> ->
2 * D1 \ D1_i X m_i 2 * D2 \ D2_i X m_i
H_DMI = - ------ / ---------- - ------ / ---------- - ...
mu0 Ms --- 2 dx_i mu0 Ms --- 2 dx_i
NN NN
where dx_i is the discretisation in the i-direction, m_i
is the magnetisation in the i-direction.
When using the `custom` option, it is necessary only to
specify the D1_i, D2_i, etc components.
To obtain the discretised DM vectors you can follow
these steps:
- Obtain the DMI field from the DMI Hamiltonian
- Discretise the spatial derivatives of the
magnetisation, for the i-th spin. Here you obtain
the mesh spacings dx_i
- Group terms for every of the 6 nearest neighbours,
i.e. group terms with m(+x), m(-x), etc
- Write the collected terms as in the discrete spin
model: D_i X m_i ; and you directly obtain the
DM vectors
For example, for the interfacial case, where the DMI
Hamiltonian reads
w = D * ( L_{xz}^{(x)} + L_{yz}^{(y)} )
the field is
/ -> -> \
-> - 2 D | ^ dm ^ dm |
H_DMI = ---- | y X -- - x X -- |
mu0 Ms \ dx dy /
After discretising the derivatives, you obtain
-> / -> -> -> ->
H_DMI = - 2 D | -y X m(-x) y X m(+x)
--- | ----------- + -----------
mu0 Ms \ 2 dx 2 dx
-> -> -> -> \
x X m(-y) -x X m(+y) |
+ ---------- + ---------- |
2 dy 2 dy /
where we see that the DM vector is (0, -1, 0) for the
neighbour in the -x-direction, etc.
Thus, we can specify the DMI in this class as:
# Manually set an interfacial DMI
fidimag.micro.DMI([D],
dmi_type='custom',
dmi_vector=[0, -1., 0, # -x neighbour
0, 1., 0, # +x
1., 0, 0, # -y
-1., 0, 0, # +y
0, 0, 0, # -z NO DMI in
0, 0, 0 # +z z-dir
]
)
For further examples, check the micro DMI class code
ARGUMENTS: ----------------------------------------------------------------
D :: DMI vector norm which can be specified as an int, float, (X * n)
or spatially dependent scalar field function. The units are
Joules / ( meter **2 ).
int, float: D will have the same magnitude for every NN of the
spins at every mesh node, given by this magnitude
(n) array or list: D for every DMI constant
OPTIONAL ARGUMENTS: -------------------------------------------------------
dmi_type :: 'bulk' or 'interfacial' or 'D_2d'
name :: Interaction name
"""
def __init__(self, D, name='DMI', dmi_type='bulk', dmi_vector=None):
"""
"""
self.D = D
self.name = name
self.jac = True
self.dmi_type = dmi_type
self.dmi_vector = dmi_vector
# Number of NNs for the calculation of the corresponding DMI
# Interfacial or D_2d are 2D so we use 4 ngbs
types = ['bulk', 'interfacial', 'D_n', 'C_n', 'D_2d', 'custom']
if self.dmi_type not in types:
raise Exception(
("Unsupported DMI type: {}, "
"available options:\n {}").format(self.dmi_type, str(types))
)
# if self.dmi_type == 'D_n' or self.dmi_type == 'C_n':
# if not self.D2:
# raise Exception("For C_n and D_n symmetry, you must also pass a D2 value"
# " as this material class has multiple DMI constants")
def setup(self, mesh, spin, Ms, Ms_inv):
super(DMI, self).setup(mesh, spin, Ms, Ms_inv)
if self.dmi_type == 'bulk':
self.dmi_vector = np.array([-1., 0, 0,
1., 0, 0,
0, -1., 0,
0, 1., 0,
0, 0, -1.,
0, 0, 1.
])
elif self.dmi_type == 'interfacial':
self.dmi_vector = np.array([0, -1., 0, # -x
0, 1., 0, # +x
1., 0, 0, # -y
-1., 0, 0, # +y
0, 0, 0, # -z
0, 0, 0 # +z
])
elif self.dmi_type == 'D_2d':
self.dmi_vector = np.array([1., 0, 0, # -x
-1., 0, 0, # +x
0, -1., 0, # -y
0, 1., 0, # +y
0, 0, 0, # -z
0, 0, 0 # +z
])
# For the following DMIs with two constants check:
# Leonov: Chiral skyrmion states in non-centrosymmetric magnets
# https://arxiv.org/pdf/1406.2177.pdf
# Leonov thesis: http://nbn-resolving.de/urn:nbn:de:bsz:14-qucosa-83823
elif self.dmi_type == 'D_n':
self.dmi_vector = np.array([-1, 0, 0, # D1 components
1, 0, 0,
0, -1, 0,
0, 1, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0, # D2 components
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 1,
0, 0, -1,
])
elif self.dmi_type == 'C_n':
self.dmi_vector = np.array([0, -1., 0, # -x
0, 1., 0, # +x
1., 0, 0, # -y
-1., 0, 0, # +y
0, 0, 0, # -z
0, 0, 0, # +z
-1, 0, 0, # D2 components
1, 0, 0,
0, -1, 0,
0, 1, 0,
0, 0, 0,
0, 0, 0,
])
elif self.dmi_type == 'custom':
self.dmi_vector = np.array(self.dmi_vector)
# Example:
# self.DMI_vector = [ 0, 0, D1, # DMI 1
# 0, 0, -D1,
# 0, 0, 0,
# 0, 0, 0,
# 0, 0, 0,
# 0, 0, 0,
# 0, 0, 0, # DMI 2
# 0, 0, 0,
# 0, D2, 0,
# 0, -D2, 0,
# 0, 0, 0,
# 0, 0, 0,
# ]
n_Ds = len(self.dmi_vector) // 18
if len(self.dmi_vector) % 18 != 0:
raise Exception('The DMI vector length must be a mult of 18: '
' N of DMIs times 3 * number of ngbs = 18')
if n_Ds > 1:
self.Ds = helper.init_vector(self.D, self.mesh, dim=n_Ds)
else:
self.Ds = helper.init_scalar(self.D, self.mesh)
self.n_dmis = n_Ds
if self.dmi_type == 'C_n' or self.dmi_type == 'D_n':
self.Ds = helper.init_vector(self.D, self.mesh, dim=2)
self.n_dmis = 2
elif self.dmi_type != 'custom':
self.Ds = helper.init_scalar(self.D, self.mesh)
self.n_dmis = 1
def compute_field(self, t=0, spin=None):
if spin is not None:
m = spin
else:
m = self.spin
micro_clib.compute_dmi_field(m,
self.field,
self.energy,
self.Ms_inv,
self.Ds,
self.n_dmis,
self.dmi_vector,
self.dx,
self.dy,
self.dz,
self.n,
self.neighbours
)
return self.field
| 2.59375 | 3 |
vcfremapper/samples.py | jeremymcrae/vcfremapper | 0 | 12767320 |
from collections import OrderedDict
class Sample(object):
''' hold sample data for a variant (e.g. genotype call, allele depths)
'''
# set up a class variable that will be shared by all Sample instances, ie,
# all individuals for a given variant. That way they have a common set of
# keys for the variant.
fields = OrderedDict()
@classmethod
def set_format(cls_obj, fields):
cls_obj.fields = OrderedDict()
for key in fields.split(':'):
if key == '':
continue
cls_obj.fields[key] = None
def __init__(self, sample):
self.data = {}
if sample == '.':
sample = '.:' * len(self.fields)
sample = sample[:-1]
sample = sample.split(':')
if len(sample) != len(self.fields):
raise ValueError('sample data should match expected fields')
for key, value in zip(self.fields, sample):
self[key] = value
def __str__(self):
return ':'.join(map(str, (self[x] for x in self.fields)))
def keys(self):
return list(self.fields)
def __getitem__(self, key):
if key not in self.fields:
raise KeyError
# if a key isn't present in one sample (because the key was only used
# for a subset of samples), then use missing value for other samples
if key not in self.data:
return '.'
return self.data[key]
def __setitem__(self, key, value):
if key == '': # key must not be blank
return
# new keys need be tracked for all samples
if key not in self.fields:
self.fields[key] = None
self.data[key] = value
def __contains__(self, key):
return key in self.fields
def __delitem__(self, key):
self.data[key] = '.'
def __hash__(self):
return hash(tuple(self[x] for x in self.fields))
def __eq__(self, other):
return self.fields == other.fields and hash(self) == hash(other)
class Samples(object):
def __init__(self, fields, samples):
Sample.set_format(fields)
self.samples = [ Sample(x) for x in samples ]
self.idx = -1
def __str__(self):
data = [':'.join(Sample.fields)] + list(map(str, self.samples))
return '\t'.join(data)
def __iter__(self):
return self
def __next__(self):
self.idx += 1
if self.idx >= len(self):
self.idx = -1
raise StopIteration
return self.samples[self.idx]
def __len__(self):
return len(self.samples)
def __getitem__(self, idx):
return self.samples[idx]
| 3.046875 | 3 |
logstash/handler_tcp.py | MWedl/python-logstash | 1 | 12767321 | <gh_stars>1-10
from logging.handlers import DatagramHandler, SocketHandler
from logstash import formatter
# Derive from object to force a new-style class and thus allow super() to work
# on Python 2.6
class TCPLogstashHandler(SocketHandler, object):
"""Python logging handler for Logstash. Sends events over TCP.
:param host: The host of the logstash server.
:param port: The port of the logstash server (default 5959).
:param message_type: The type of the message (default logstash).
:param fqdn; Indicates whether to show fully qualified domain name or not (default False).
:param tags: list of tags for a logger (default is None).
:param limit_stacktrace: limit characters for stacktraces
:param limit_string_fields: limit characters for string fields
:param limit_containers: limit length of containers (dict, list, set)
"""
def __init__(self, host, port=5959, message_type='logstash', tags=None, fqdn=False,
limit_stacktrace=0, limit_string_fields=0, limit_containers=0):
super(TCPLogstashHandler, self).__init__(host, port)
self.formatter = formatter.LogstashFormatter(message_type, tags, fqdn, limit_stacktrace=limit_stacktrace,
limit_string_fields=limit_string_fields,
limit_containers=limit_containers)
def makePickle(self, record):
return self.formatter.format(record) + b'\n'
| 2.6875 | 3 |
lib/python2.7/site-packages/appionlib/apWebScript.py | leschzinerlab/myami-3.2-freeHand | 0 | 12767322 | ### webscripting
#python
import MySQLdb
#appion
from appionlib import appiondata
#leginon
import sinedon
#=====================
def setJobToRun(jobid):
if getJobStatus(jobid) == "R":
return False
return setJobStatus(jobid, "R")
#=====================
def setJobToDone(jobid):
if getJobStatus(jobid) == "D":
return False
return setJobStatus(jobid, "D")
#=====================
def setJobToError(jobid):
if getJobStatus(jobid) == "E":
return False
return setJobStatus(jobid, "E")
#=====================
def setJobStatus(jobid, status):
### clean status
newstat = str(status[0]).upper()
### cluster job data
clustdata = appiondata.ApAppionJobData.direct_query(jobid)
if not clustdata:
print "Did not find jobid=%d"%(jobid)
return False
### do the query
dbconf = sinedon.getConfig('appiondata')
db = MySQLdb.connect(**dbconf)
db.autocommit(True)
cursor = db.cursor()
query = (
"UPDATE \n"
+" `ApAppionJobData` as job \n"
+"SET \n"
+" job.`status` = '"+str(newstat)+"' \n"
+"WHERE \n"
+" job.`DEF_id` = "+str(clustdata.dbid)+" \n"
)
try:
cursor.execute(query)
except:
print "MySQL query failed:\n======\n%s"%(query)
return False
if getJobStatus(jobid) == newstat:
return True
return False
#=====================
def getJobStatus(jobid):
clustdata = appiondata.ApAppionJobData.direct_query(jobid)
if not clustdata:
return None
return clustdata['status']
| 2.40625 | 2 |
scikits/statsmodels/examples/example_kde.py | matthew-brett/statsmodels | 0 | 12767323 | <filename>scikits/statsmodels/examples/example_kde.py
from scipy import stats
import numpy as np
from scikits.statsmodels.sandbox.distributions.mixture_rvs import mixture_rvs
from scikits.statsmodels.nonparametric.kde import (kdensity, kdensityfft)
import matplotlib.pyplot as plt
np.random.seed(12345)
obs_dist = mixture_rvs([.25,.75], size=10000, dist=[stats.norm, stats.norm],
kwargs = (dict(loc=-1,scale=.5),dict(loc=1,scale=.5)))
#obs_dist = mixture_rvs([.25,.75], size=10000, dist=[stats.norm, stats.beta],
# kwargs = (dict(loc=-1,scale=.5),dict(loc=1,scale=1,args=(1,.5))))
f_hat, grid, bw = kdensityfft(obs_dist, kernel="gauss", bw="scott")
# check the plot
plt.hist(obs_dist, bins=50, normed=True, color='red')
plt.plot(grid, f_hat, lw=2, color='black')
plt.show()
# do some timings
# get bw first because they're not streamlined
from scikits.statsmodels.nonparametric import bandwidths
bw = bandwidths.bw_scott(obs_dist)
#timeit kdensity(obs_dist, kernel="gauss", bw=bw, gridsize=2**10)
#timeit kdensityfft(obs_dist, kernel="gauss", bw=bw, gridsize=2**10)
| 2.40625 | 2 |
couchbasekit/__init__.py | ardydedase/couchbasekit | 3 | 12767324 | #! /usr/bin/env python
"""
couchbasekit
~~~~~~~~~~~~
A wrapper around CouchBase Python driver for document validation and more.
:website: http://github.com/kirpit/couchbasekit
:copyright: Copyright 2013, <NAME> <kirpit *at* gmail.com>, see AUTHORS.txt.
:license: MIT, see LICENSE.txt for details.
"""
from couchbasekit.connection import Connection
from couchbasekit.document import Document
from couchbasekit.viewsync import register_view
__version__ = '0.2.3-dev'
__all__ = (
Connection,
Document,
register_view,
) | 1.6875 | 2 |
tests/frontend/user/__init__.py | agdsn/pycroft | 18 | 12767325 | from flask import url_for
from tests import FrontendWithAdminTestBase
from tests.factories import RoomFactory, SubnetFactory, PatchPortFactory
class UserLogTestBase(FrontendWithAdminTestBase):
def get_logs(self, user_id=None, **kw):
"""Request the logs, assert validity, and return the response.
By default, the logs are fetched for the user logging in.
The following assertions are made:
* The response code is 200
* The response content_type contains ``"json"``
* The response's JSON contains an ``"items"`` key
:returns: ``response.json['items']``
"""
if user_id is None:
user_id = self.user_id
log_endpoint = url_for('user.user_show_logs_json',
user_id=user_id,
**kw)
response = self.assert_response_code(log_endpoint, code=200)
assert "json" in response.content_type.lower()
json = response.json
assert json.get('items') is not None
return json['items']
class UserFrontendTestBase(FrontendWithAdminTestBase):
def create_factories(self):
super().create_factories()
self.room = RoomFactory()
self.subnet = SubnetFactory()
self.patch_port = PatchPortFactory(room=self.room, patched=True,
switch_port__switch__host__owner=self.admin)
# 2. A pool of default vlans so an IP can be found
self.patch_port.switch_port.default_vlans.append(self.subnet.vlan)
| 2.40625 | 2 |
exercises/bob/example.py | kishankj/python | 1,177 | 12767326 | <gh_stars>1000+
def response(hey_bob):
hey_bob = hey_bob.strip()
if _is_silence(hey_bob):
return 'Fine. Be that way!'
if _is_shouting(hey_bob):
if _is_question(hey_bob):
return "Calm down, I know what I'm doing!"
else:
return 'Whoa, chill out!'
elif _is_question(hey_bob):
return 'Sure.'
else:
return 'Whatever.'
def _is_silence(hey_bob):
return hey_bob == ''
def _is_shouting(hey_bob):
return hey_bob.isupper()
def _is_question(hey_bob):
return hey_bob.endswith('?')
| 3.09375 | 3 |
test/test_source_base.py | macbre/Mike | 6 | 12767327 | """
Set of unit test for SourceBase class
"""
import pytest
from mycroft_holmes.errors import MycroftSourceError
from mycroft_holmes.sources.base import SourceBase
from mycroft_holmes.sources import ConstSource
def test_get_sources_names():
sources = SourceBase.get_sources_names()
print(sources)
assert 'common/const' in sources
def test_new_from_name():
source = SourceBase.new_from_name('common/const')
print(source)
assert isinstance(source, ConstSource), 'ConstSource should be returned by SourceBase.new_from_name'
assert source.get_value() == 1
def test_new_from_name_missing():
with pytest.raises(MycroftSourceError):
SourceBase.new_from_name('foo/missing-source')
def test_get_description():
source = ConstSource()
print(source.get_description())
assert source.get_name() == 'common/const'
assert source.get_short_description() == \
'Returns a constant value (can be used to tweak a score of a feature).'
assert source.get_description() == """
Returns a constant value (can be used to tweak a score of a feature).
#### `metrics` config
```yaml
metrics:
- name: common/const
weight: 100
```
""".strip()
| 2.453125 | 2 |
18.py | ikramulkayes/Python_season2 | 0 | 12767328 | <filename>18.py
word = input("Enter a number: ")
word = int(word)
count =10
while True:
temp = word % 10
word = word//10
if temp % 2==0:
print(temp,end="")
if word == 0:
break | 3.921875 | 4 |
pythonProject1/venv/Lib/site-packages/customtkinter/customtkinter_progressbar.py | mjtomlinson/CNE330_Python_1_Final_Project | 0 | 12767329 | import tkinter
from .customtkinter_frame import CTkFrame
from .appearance_mode_tracker import AppearanceModeTracker
from .customtkinter_color_manager import CTkColorManager
class CTkProgressBar(tkinter.Frame):
def __init__(self,
bg_color=None,
border_color=CTkColorManager.PROGRESS_BG,
fg_color=CTkColorManager.PROGRESS_BG,
progress_color=CTkColorManager.MAIN,
width=160,
height=10,
border_width=0,
*args, **kwargs):
super().__init__(*args, **kwargs)
AppearanceModeTracker.add(self.change_appearance_mode)
if bg_color is None:
if isinstance(self.master, CTkFrame):
self.bg_color = self.master.fg_color
else:
self.bg_color = self.master.cget("bg")
else:
self.bg_color = bg_color
self.border_color = border_color
self.fg_color = fg_color
self.progress_color = progress_color
self.appearance_mode = AppearanceModeTracker.get_mode() # 0: "Light" 1: "Dark"
self.width = width
self.height = height
self.border_width = border_width
self.value = 0.5
self.configure(width=self.width, height=self.height)
self.canvas = tkinter.Canvas(master=self,
highlightthicknes=0,
width=self.width,
height=self.height)
self.canvas.place(x=0, y=0)
self.border_parts = []
self.fg_parts = []
self.progress_parts = []
self.draw()
def draw(self):
self.canvas.delete("all")
self.border_parts = []
self.fg_parts = []
self.progress_parts = []
# frame_border
self.border_parts.append(self.canvas.create_oval(0, 0,
self.height, self.height))
self.border_parts.append(self.canvas.create_rectangle(self.height/2, 0,
self.width-(self.height/2), self.height))
self.border_parts.append(self.canvas.create_oval(self.width-self.height, 0,
self.width, self.height))
# foreground
self.fg_parts.append(self.canvas.create_oval(self.border_width, self.border_width,
self.height-self.border_width, self.height-self.border_width))
self.fg_parts.append(self.canvas.create_rectangle(self.height/2, self.border_width,
self.width-(self.height/2), self.height-self.border_width))
self.fg_parts.append(self.canvas.create_oval(self.width-self.height+self.border_width, self.border_width,
self.width-self.border_width, self.height-self.border_width))
if type(self.bg_color) == tuple:
self.canvas.configure(bg=self.bg_color[self.appearance_mode])
else:
self.canvas.configure(bg=self.bg_color)
for part in self.border_parts:
if type(self.border_color) == tuple:
self.canvas.itemconfig(part, fill=self.border_color[self.appearance_mode], width=0)
else:
self.canvas.itemconfig(part, fill=self.border_color, width=0)
for part in self.fg_parts:
if type(self.fg_color) == tuple:
self.canvas.itemconfig(part, fill=self.fg_color[self.appearance_mode], width=0)
else:
self.canvas.itemconfig(part, fill=self.fg_color, width=0)
self.set(self.value)
def set(self, value):
self.value = value
if self.value > 1:
self.value = 1
elif self.value < 0:
self.value = 0
for part in self.progress_parts:
self.canvas.delete(part)
# progress
self.progress_parts.append(self.canvas.create_oval(self.border_width,
self.border_width,
self.height - self.border_width,
self.height - self.border_width))
self.progress_parts.append(self.canvas.create_rectangle(self.height / 2,
self.border_width,
self.height / 2 + (self.width - self.height) * self.value,
self.height - self.border_width))
self.progress_parts.append(self.canvas.create_oval(self.height / 2 + (self.width - self.height) * self.value - (self.height) / 2 + self.border_width,
self.border_width,
self.height / 2 + (self.width - self.height) * self.value + (self.height) / 2 - self.border_width,
self.height - self.border_width))
for part in self.progress_parts:
if type(self.progress_color) == tuple:
self.canvas.itemconfig(part, fill=self.progress_color[self.appearance_mode], width=0)
else:
self.canvas.itemconfig(part, fill=self.progress_color, width=0)
self.canvas.update()
self.canvas.update_idletasks()
def change_appearance_mode(self, mode_string):
if mode_string.lower() == "dark":
self.appearance_mode = 1
elif mode_string.lower() == "light":
self.appearance_mode = 0
if isinstance(self.master, CTkFrame):
self.bg_color = self.master.fg_color
else:
self.bg_color = self.master.cget("bg")
self.draw()
| 2.6875 | 3 |
KancolleConnector.py | zigoni/KancolleConnecotr | 2 | 12767330 | <filename>KancolleConnector.py
import os
import random
from flask import Flask, request, abort, session, render_template
from requests.exceptions import ReadTimeout
from kcc import get_play_url, DmmTokenError, TokenError, AjaxRequestError, LoginError
app = Flask(__name__)
def get_random_string(length=16, allowed_chars='abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'):
return ''.join(random.choice(allowed_chars) for i in range(length))
@app.before_request
def csrf_protect():
if request.method == "POST":
token = session.pop('_csrf_token', None)
if not token or token != request.form.get('_csrf_token'):
abort(403)
def generate_csrf_token():
if '_csrf_token' not in session:
session['_csrf_token'] = get_random_string()
return session['_csrf_token']
app.jinja_env.globals['csrf_token'] = generate_csrf_token
app.secret_key = os.environ.get('KCC_KEY', '<KEY>')
app.debug = bool(os.environ.get('KCC_DEBUG', False))
@app.route(os.environ.get('KCC_PATH', '/connector/'), methods=['GET', 'POST'])
def index():
if request.method == 'GET':
return render_template('form.html', error=False)
else:
login_id = request.form.get('login_id', '')
password = request.form.get('password', '')
if login_id == '' or password == '':
return render_template('form.html', error=True, message='请输入正确的登录ID和密码')
shimakezego = bool(os.environ.get('KCC_SHIMAKAZEGO', False))
if shimakezego:
REQUESTS_PROXIES = {'http': 'http://127.0.0.1:8099', 'https': 'http://127.0.0.1:8099'}
else:
REQUESTS_PROXIES = None
try:
play_url = get_play_url(login_id, password, REQUESTS_PROXIES)
except (DmmTokenError, TokenError, AjaxRequestError, ReadTimeout):
return render_template('form.html', error=True, message='登录DMM网站失败,可能原因为DMM本身出现故障或服务器网络拥堵')
except LoginError:
return render_template('form.html', error=True, message='登录DMM网站失败,可能原因为登录ID或密码输入错误,或者DMM要求您更改密码')
return render_template('play.html', play_url=play_url)
if __name__ == '__main__':
app.run()
| 1.976563 | 2 |
tests/test_vector.py | metagraph-dev/dask-grblas | 3 | 12767331 | <filename>tests/test_vector.py
import inspect
import grblas as gb
import pytest
from grblas import dtypes
from pytest import raises
import dask.array as da
import dask_grblas as dgb
from .utils import compare
@pytest.fixture
def vs():
v = gb.Vector.from_values([0, 1, 2, 4, 5], [0, -20, 30, 40, 50])
dv0 = dgb.Vector.from_vector(v)
dv1 = dgb.concat_vectors(
[
dgb.Vector.from_vector(gb.Vector.from_values([0, 1, 2], [0, -20, 30])),
dgb.Vector.from_vector(gb.Vector.from_values([1, 2], [40, 50])),
]
)
dv2 = dgb.concat_vectors(
[
dgb.concat_vectors(
[
dgb.Vector.from_vector(gb.Vector.from_values([0], [0])),
dgb.Vector.from_vector(gb.Vector.from_values([0, 1], [-20, 30])),
]
),
dgb.Vector.from_vector(gb.Vector.from_values([1, 2], [40, 50])),
]
)
return v, (dv0, dv1, dv2)
@pytest.fixture
def ws():
w = gb.Vector.from_values([0, 1, 3, 4, 5], [1.0, 2.0, 3.0, -4.0, 0.0])
dw0 = dgb.Vector.from_vector(w)
dw1 = dgb.concat_vectors(
[
dgb.Vector.from_vector(gb.Vector.from_values([0, 1], [1.0, 2.0])),
dgb.Vector.from_vector(gb.Vector.from_values([1, 2, 3], [3.0, -4.0, 0.0])),
]
)
return w, (dw0, dw1)
@pytest.fixture
def vms():
val_mask = gb.Vector.from_values(
[0, 1, 2, 3, 4, 5], [True, False, False, True, True, False], size=6
)
dvm0 = dgb.Vector.from_vector(val_mask)
dvm1 = dgb.concat_vectors(
[
dgb.Vector.from_vector(gb.Vector.from_values([0, 1], [True, False])),
dgb.Vector.from_vector(
gb.Vector.from_values([0, 1, 2, 3], [False, True, True, False], size=4)
),
]
)
return val_mask, (dvm0, dvm1)
@pytest.fixture
def sms():
struct_mask = gb.Vector.from_values([0, 3, 4], [False, False, False], size=6)
dsm0 = dgb.Vector.from_vector(struct_mask)
dsm1 = dgb.concat_vectors(
[
dgb.Vector.from_vector(gb.Vector.from_values([0], [False], size=2)),
dgb.Vector.from_vector(gb.Vector.from_values([1, 2], [False, False], size=4)),
]
)
return struct_mask, (dsm0, dsm1)
def test_new():
v = gb.Vector.new(int)
dv = dgb.Vector.new(int)
compare(lambda x: x, v, dv)
compare(lambda x: x.size, v, dv, compute=False)
compare(lambda x: x.shape, v, dv, compute=False)
v = gb.Vector.new(float, 3)
dv = dgb.Vector.new(float, 3)
compare(lambda x: x, v, dv)
compare(lambda x: x.size, v, dv, compute=False)
compare(lambda x: x.shape, v, dv, compute=False)
o = object()
compare(lambda x, y: type(x).new(y), (v, o), (dv, o), errors=True)
def test_from_values():
n = 100
I = da.arange(n, chunks=10)
f = lambda module, arr: module.Vector.from_values(arr, arr, name="arange")
compare(f, (gb, I.compute()), (dgb, I))
I = [0, 1, 3, 4, 5]
V = [1.0, 2.0, 3.0, -4.0, 0.0]
I_da = da.from_array(I, chunks=3)
V_da = da.from_array(V, chunks=2)
f = lambda module, i, v, kwargs: module.Vector.from_values(
i, v, name="test-from-values", **kwargs
)
compare(f, (gb, I, V, {}), (dgb, I_da, V_da, {}))
compare(f, (gb, I, V, {}), (dgb, I_da, V_da, {"chunks": 3}))
def test_to_values(vs, ws):
(v, dvs) = vs
(w, dws) = ws
def f0(v):
return v.to_values()[0]
def f1(v):
return v.to_values()[1]
for dv in dvs:
compare(f0, v, dv)
compare(f1, v, dv)
for dw in dws:
compare(f0, w, dw)
compare(f1, w, dw)
def test_dup(vs):
v, dvs = vs
for dv in dvs:
compare(lambda x: x.dup(), v, dv)
compare(lambda x: x.dup(dtype=dtypes.FP64), v, dv)
o = object()
compare(lambda x, y: x.dup(y), (v, o), (dv, o), errors=True)
compare(lambda x: x.dup(mask=1), v, dv, errors=True)
with raises(TypeError):
dv.dup(mask=v.S)
@pytest.mark.slow
def test_isequal_isclose(vs, ws):
o = object()
for method_name in ["isequal", "isclose"]:
v = vs[0]
w = ws[0]
for dv in vs[1]:
compare(lambda x, y: getattr(x, method_name)(y), (v, v), (dv, dv))
compare(lambda x: getattr(x, method_name)(o), v, dv, errors=True)
for dw in ws[1]:
compare(lambda x, y: getattr(x, method_name)(y), (v, w), (dv, dw))
def test_nvals(vs):
v, dvs = vs
for dv in dvs:
compare(lambda x: x.nvals, v, dv)
v = gb.Vector.new(int)
dv = dgb.Vector.new(int)
compare(lambda x: x.nvals, v, dv)
def test_clear(vs):
def f(x):
x.clear()
return x
v, dvs = vs
compare(f, v, dvs[0])
def test_ewise(vs, ws):
v = vs[0]
w = ws[0]
binfunc = lambda x, y: getattr(x, method_name)(y, op, require_monoid=False).new()
for op in [gb.monoid.plus, gb.binary.plus]:
for method_name in ["ewise_add", "ewise_mult"]:
def f(w, x, y):
w << getattr(x, method_name)(y, op)
return w
# errors = method_name == 'ewise_add' and op is gb.binary.plus
errors = False
compute = not errors
funcs = [
lambda x, y: getattr(x, method_name)(y, op).new(),
lambda x, y: getattr(x, method_name)(y, op).new(dtype=dtypes.FP64),
lambda x, y: getattr(x, method_name)(y, op).new(mask=y.S),
lambda x, y: getattr(x, method_name)(y, op).new(mask=y.V),
lambda x, y: getattr(x, method_name)(y, op).new(mask=~x.S),
lambda x, y: getattr(x, method_name)(y, op).new(mask=~x.V),
]
for dv in vs[1]:
for index, func in enumerate(funcs):
compare(func, (v, v), (dv, dv), errors=errors, compute=compute)
if method_name == "ewise_add":
compare(binfunc, (v, v), (dv, dv))
compare(
f,
(v.dup(), v, v),
(dv.dup(), dv, dv),
errors=errors,
compute=compute,
)
for dw in ws[1]:
for func in funcs:
compare(func, (v, w), (dv, dw), errors=errors, compute=compute)
if method_name == "ewise_add":
compare(binfunc, (v, v), (dv, dv))
compare(
f,
(v.dup(), v, w),
(dv.dup(), dv, dw),
errors=errors,
compute=compute,
)
compare(
f,
(w.dup(), v, w),
(dw.dup(), dv, dw),
errors=errors,
compute=compute,
)
def test_reduce(vs):
v, dvs = vs
def f0(x, y):
x << y.reduce()
return x
def f1(x, y):
x() << y.reduce()
return x
def f2(x, y):
x(accum=gb.binary.plus) << y.reduce()
return x
for dv in dvs:
compare(lambda x: x.reduce().new(), v, dv)
compare(lambda x: x.reduce(gb.monoid.max).new(), v, dv)
compare(lambda x: x.reduce().new(dtype=dtypes.FP64), v, dv)
compare(lambda x: x.reduce(gb.binary.plus).new(), v, dv)
for i, f in enumerate([f0, f1, f2]):
s = gb.Scalar.new(int)
ds = dgb.Scalar.from_value(s.dup())
compare(f, (s, v), (ds, dv))
s = gb.Scalar.from_value(100)
ds = dgb.Scalar.from_value(s.dup())
compare(f, (s, v), (ds, dv))
s = gb.Scalar.new(float)
ds = dgb.Scalar.from_value(s.dup())
compare(f, (s, v), (ds, dv))
s = gb.Scalar.from_value(1.23)
ds = dgb.Scalar.from_value(s.dup())
compare(f, (s, v), (ds, dv))
def test_apply(vs):
v, dvs = vs
def f(x):
y = type(x).new(x.dtype, x.size)
y << x.apply(gb.unary.abs)
return y
def g(x, scalar=1):
y = type(x).new(x.dtype, x.size)
y << x.apply(gb.binary.gt, right=scalar)
return y
def h(x, scalar=2):
y = type(x).new(x.dtype, x.size)
y << x.apply(gb.binary.minus, left=scalar)
return y
def i(x, scalar=1):
y = type(x).new(x.dtype, x.size)
y << x.apply(gb.binary.plus, left=scalar)
return y
def j(x, scalar=1):
y = type(x).new(x.dtype, x.size)
y << x.apply(gb.monoid.plus, left=scalar)
return y
def k(x, scalar=1):
y = type(x).new(x.dtype, x.size)
y << x.apply(gb.monoid.plus, right=scalar)
return y
for dv in dvs:
compare(lambda x: x.apply(gb.unary.abs).new(), v, dv)
compare(lambda x: x.apply(gb.unary.abs).new(dtype=float), v, dv)
compare(lambda x: x.apply(gb.binary.plus).new(), v, dv, errors=True)
compare(f, v.dup(), dv.dup())
compare(lambda x: x.apply(gb.binary.gt, right=1).new(), v, dv)
compare(lambda x: x.apply(gb.binary.gt, right=1).new(dtype=float), v, dv)
compare(g, v.dup(), dv.dup())
s = gb.Scalar.from_value(1)
ds = dgb.Scalar.from_value(s)
compare(
lambda x, s: x.apply(gb.binary.gt, right=s).new(dtype=float),
(v, s),
(dv, ds),
)
compare(g, (v.dup(), s), (dv.dup(), ds))
compare(lambda x: x.apply(gb.binary.minus, left=2).new(), v, dv)
compare(lambda x: x.apply(gb.binary.minus, left=2).new(dtype=float), v, dv)
compare(h, v.dup(), dv.dup())
s = gb.Scalar.from_value(2)
ds = dgb.Scalar.from_value(s)
compare(
lambda x, s: x.apply(gb.binary.minus, left=s).new(dtype=float),
(v, s),
(dv, ds),
)
compare(h, (v.dup(), s), (dv.dup(), ds))
compare(lambda x: x.apply(gb.binary.plus, left=1).new(), v, dv)
compare(lambda x: x.apply(gb.binary.plus, left=1).new(dtype=float), v, dv)
compare(i, v.dup(), dv.dup())
s = gb.Scalar.from_value(1)
ds = dgb.Scalar.from_value(s)
compare(
lambda x, s: x.apply(gb.binary.minus, left=s).new(dtype=float),
(v, s),
(dv, ds),
)
compare(i, (v.dup(), s), (dv.dup(), ds))
compare(lambda x: x.apply(gb.monoid.plus, left=1).new(), v, dv)
compare(lambda x: x.apply(gb.monoid.plus, left=1).new(dtype=float), v, dv)
compare(j, v.dup(), dv.dup())
s = gb.Scalar.from_value(1)
ds = dgb.Scalar.from_value(s)
compare(
lambda x, s: x.apply(gb.binary.minus, left=s).new(dtype=float),
(v, s),
(dv, ds),
)
compare(j, (v.dup(), s), (dv.dup(), ds))
compare(lambda x: x.apply(gb.monoid.plus, right=1).new(), v, dv)
compare(lambda x: x.apply(gb.monoid.plus, right=1).new(dtype=float), v, dv)
compare(k, v.dup(), dv.dup())
s = gb.Scalar.from_value(1)
ds = dgb.Scalar.from_value(s)
compare(
lambda x, s: x.apply(gb.binary.minus, right=s).new(dtype=float),
(v, s),
(dv, ds),
)
compare(k, (v.dup(), s), (dv.dup(), ds))
def test_update(vs, ws):
v, dvs = vs
w, dws = ws
def f0(x, y):
x.update(y)
return x
def f1(x, y):
x << y
return x
def f2(x, y):
x().update(y)
return x
def f3(x, y):
x(y.S) << y
return x
def f4(x, y):
x(y.V) << y
return x
def f5(x, y):
x(accum=gb.binary.plus).update(y)
return x
for f in [f0, f1, f2, f3, f4, f5]:
for dv in dvs:
for dw in dws:
compare(f, (v.dup(), w.dup()), (dv.dup(), dw.dup()))
compare(f, (v.dup(dtype=float), w.dup()), (dv.dup(dtype=float), dw.dup()))
@pytest.mark.slow
def test_extract(vs, ws, vms, sms):
v, dvs = vs
w, dws = ws
vm, dvms = vms
sm, dsms = sms
for index in [
slice(None),
[0, 3, 1, 4, 2, 5],
[0, 5, 5, 1, 2, 0],
slice(None, None, -1),
[0] * 6,
]:
def f1(x, y):
x << y[index]
return x
def f2(x, y):
x() << y[index]
return x
def g1(m, x, y):
x(mask=m) << y[index]
return x
def g2(x, y):
x(accum=gb.binary.plus) << y[index]
return x
def g3(x, y):
x(replace=True) << y[index]
return x
def g4(x, y):
x(replace=False) << y[index]
return x
def h1(x, y):
x(accum=gb.binary.plus, replace=True) << y[index]
return x
def h2(x, y):
x(accum=gb.binary.plus, replace=False) << y[index]
return x
def h3(m, x, y):
x(mask=m, replace=True) << y[index]
return x
def h4(m, x, y):
x(mask=m, replace=False) << y[index]
return x
def h5(m, x, y):
x(mask=m, accum=gb.binary.plus) << y[index]
return x
def i1(m, x, y):
x(mask=m, accum=gb.binary.plus, replace=True) << y[index]
return x
def i2(m, x, y):
x(mask=m, accum=gb.binary.plus, replace=False) << y[index]
return x
for dv in dvs:
compare(lambda x: x[index].new(), v, dv)
compare(lambda x: x[index].new(dtype=float), v, dv)
for dw in dws:
compare(f1, (v.dup(), w), (dv.dup(), dw))
compare(f1, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw))
compare(f2, (v.dup(), w), (dv.dup(), dw))
compare(f2, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw))
compare(g2, (v.dup(), w), (dv.dup(), dw))
compare(g2, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw))
compare(g3, (v.dup(), w), (dv.dup(), dw), errors=True)
compare(g3, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw), errors=True)
compare(g4, (v.dup(), w), (dv.dup(), dw))
compare(g4, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw))
compare(h1, (v.dup(), w), (dv.dup(), dw), errors=True)
compare(h1, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw), errors=True)
compare(h2, (v.dup(), w), (dv.dup(), dw))
compare(h2, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw))
for dvm in dvms:
compare(g1, (vm.V, v.dup(), w), (dvm.V, dv.dup(), dw))
compare(
g1,
(vm.V, v.dup(dtype=float), w),
(dvm.V, dv.dup(dtype=float), dw),
)
compare(lambda m, x: x[index].new(mask=m), (vm.V, w), (dvm.V, dw))
compare(
lambda m, x: x[index].new(mask=m, dtype=float),
(vm.V, w),
(dvm.V, dw),
)
compare(h3, (vm.V, v.dup(), w), (dvm.V, dv.dup(), dw))
compare(
h3,
(vm.V, v.dup(dtype=float), w),
(dvm.V, dv.dup(dtype=float), dw),
)
compare(
lambda m, x: x[index].new(mask=m, replace=True),
(vm.V, w),
(dvm.V, dw),
errors=True,
)
compare(
lambda m, x: x[index].new(mask=m, replace=True, dtype=float),
(vm.V, w),
(dvm.V, dw),
errors=True,
)
compare(h4, (vm.V, v.dup(), w), (dvm.V, dv.dup(), dw))
compare(
h4,
(vm.V, v.dup(dtype=float), w),
(dvm.V, dv.dup(dtype=float), dw),
)
compare(
lambda m, x: x[index].new(mask=m, replace=False),
(vm.V, w),
(dvm.V, dw),
errors=True,
)
compare(
lambda m, x: x[index].new(mask=m, replace=False, dtype=float),
(vm.V, w),
(dvm.V, dw),
errors=True,
)
compare(h5, (vm.V, v.dup(), w), (dvm.V, dv.dup(), dw))
compare(
h5,
(vm.V, v.dup(dtype=float), w),
(dvm.V, dv.dup(dtype=float), dw),
)
compare(
lambda m, x: x[index].new(mask=m, accum=gb.binary.plus),
(vm.V, w),
(dvm.V, dw),
errors=True,
)
compare(
lambda m, x: x[index].new(mask=m, accum=gb.binary.plus, dtype=float),
(vm.V, w),
(dvm.V, dw),
errors=True,
)
compare(i1, (vm.V, v.dup(), w), (dvm.V, dv.dup(), dw))
compare(
i1,
(vm.V, v.dup(dtype=float), w),
(dvm.V, dv.dup(dtype=float), dw),
)
compare(
lambda m, x: x[index].new(mask=m, accum=gb.binary.plus, replace=True),
(vm.V, w),
(dvm.V, dw),
errors=True,
)
compare(
lambda m, x: x[index].new(
mask=m, accum=gb.binary.plus, replace=True, dtype=float
),
(vm.V, w),
(dvm.V, dw),
errors=True,
)
compare(i2, (vm.V, v.dup(), w), (dvm.V, dv.dup(), dw))
compare(
i2,
(vm.V, v.dup(dtype=float), w),
(dvm.V, dv.dup(dtype=float), dw),
)
compare(
lambda m, x: x[index].new(mask=m, accum=gb.binary.plus, replace=False),
(vm.V, w),
(dvm.V, dw),
errors=True,
)
compare(
lambda m, x: x[index].new(
mask=m, accum=gb.binary.plus, replace=False, dtype=float
),
(vm.V, w),
(dvm.V, dw),
errors=True,
)
for dsm in dsms:
compare(g1, (sm.S, v.dup(), w), (dsm.S, dv.dup(), dw))
compare(
g1,
(sm.S, v.dup(dtype=float), w),
(dsm.S, dv.dup(dtype=float), dw),
)
compare(lambda m, x: x[index].new(mask=m), (sm.S, w), (dsm.S, dw))
compare(
lambda m, x: x[index].new(mask=m, dtype=float),
(sm.S, w),
(dsm.S, dw),
)
compare(h3, (sm.S, v.dup(), w), (dsm.S, dv.dup(), dw))
compare(
h3,
(sm.S, v.dup(dtype=float), w),
(dsm.S, dv.dup(dtype=float), dw),
)
compare(
lambda m, x: x[index].new(mask=m, replace=True),
(sm.S, w),
(dsm.S, dw),
errors=True,
)
compare(
lambda m, x: x[index].new(mask=m, replace=True, dtype=float),
(sm.S, w),
(dsm.S, dw),
errors=True,
)
compare(h4, (sm.S, v.dup(), w), (dsm.S, dv.dup(), dw))
compare(
h4,
(sm.S, v.dup(dtype=float), w),
(dsm.S, dv.dup(dtype=float), dw),
)
compare(
lambda m, x: x[index].new(mask=m, replace=False),
(sm.S, w),
(dsm.S, dw),
errors=True,
)
compare(
lambda m, x: x[index].new(mask=m, replace=False, dtype=float),
(sm.S, w),
(dsm.S, dw),
errors=True,
)
compare(h5, (sm.S, v.dup(), w), (dsm.S, dv.dup(), dw))
compare(
h5,
(sm.S, v.dup(dtype=float), w),
(dsm.S, dv.dup(dtype=float), dw),
)
compare(
lambda m, x: x[index].new(mask=m, accum=gb.binary.plus),
(sm.S, w),
(dsm.S, dw),
errors=True,
)
compare(
lambda m, x: x[index].new(mask=m, accum=gb.binary.plus, dtype=float),
(sm.S, w),
(dsm.S, dw),
errors=True,
)
compare(i1, (sm.S, v.dup(), w), (dsm.S, dv.dup(), dw))
compare(
i1,
(sm.S, v.dup(dtype=float), w),
(dsm.S, dv.dup(dtype=float), dw),
)
compare(
lambda m, x: x[index].new(mask=m, accum=gb.binary.plus, replace=True),
(sm.S, w),
(dsm.S, dw),
errors=True,
)
compare(
lambda m, x: x[index].new(
mask=m, accum=gb.binary.plus, replace=True, dtype=float
),
(sm.S, w),
(dsm.S, dw),
errors=True,
)
compare(i2, (sm.S, v.dup(), w), (dsm.S, dv.dup(), dw))
compare(
i2,
(sm.S, v.dup(dtype=float), w),
(dsm.S, dv.dup(dtype=float), dw),
)
compare(
lambda m, x: x[index].new(mask=m, accum=gb.binary.plus, replace=False),
(sm.S, w),
(dsm.S, dw),
errors=True,
)
compare(
lambda m, x: x[index].new(
mask=m, accum=gb.binary.plus, replace=False, dtype=float
),
(sm.S, w),
(dsm.S, dw),
errors=True,
)
@pytest.mark.slow
def test_extract_da(vs, ws, vms, sms):
v, dvs = vs
w, dws = ws
vm, dvms = vms
sm, dsms = sms
index1_da = da.from_array([0, 3, 1, 4, 2, 5], chunks=((2, 2, 2),))
index2_da = da.from_array([0, 5, 5, 1, 2, 0], chunks=((2, 2, 2),))
index3_da = da.from_array([0] * 6, chunks=((2, 2, 2),))
for index in [
index1_da,
index2_da,
index3_da,
]:
ind = index.compute()
def f1(x, y, index):
x << y[index]
return x
def f2(x, y, index):
x() << y[index]
return x
def g1(m, x, y, index):
x(mask=m) << y[index]
return x
def g2(x, y, index):
x(accum=gb.binary.plus) << y[index]
return x
def g3(x, y, index):
x(replace=True) << y[index]
return x
def g4(x, y, index):
x(replace=False) << y[index]
return x
def h1(x, y, index):
x(accum=gb.binary.plus, replace=True) << y[index]
return x
def h2(x, y, index):
x(accum=gb.binary.plus, replace=False) << y[index]
return x
def h3(m, x, y, index):
x(mask=m, replace=True) << y[index]
return x
def h4(m, x, y, index):
x(mask=m, replace=False) << y[index]
return x
def h5(m, x, y, index):
x(mask=m, accum=gb.binary.plus) << y[index]
return x
def i1(m, x, y, index):
x(mask=m, accum=gb.binary.plus, replace=True) << y[index]
return x
def i2(m, x, y, index):
x(mask=m, accum=gb.binary.plus, replace=False) << y[index]
return x
for dv in dvs:
compare(lambda x, index: x[index].new(), (v, ind), (dv, index))
compare(lambda x, index: x[index].new(dtype=float), (v, ind), (dv, index))
for dw in dws:
compare(f1, (v.dup(), w, ind), (dv.dup(), dw, index))
compare(f1, (v.dup(dtype=float), w, ind), (dv.dup(dtype=float), dw, index))
compare(f2, (v.dup(), w, ind), (dv.dup(), dw, index))
compare(f2, (v.dup(dtype=float), w, ind), (dv.dup(dtype=float), dw, index))
compare(g2, (v.dup(), w, ind), (dv.dup(), dw, index))
compare(g2, (v.dup(dtype=float), w, ind), (dv.dup(dtype=float), dw, index))
compare(g3, (v.dup(), w, ind), (dv.dup(), dw, index), errors=True)
compare(
g3, (v.dup(dtype=float), w, ind), (dv.dup(dtype=float), dw, index), errors=True
)
compare(g4, (v.dup(), w, ind), (dv.dup(), dw, index))
compare(g4, (v.dup(dtype=float), w, ind), (dv.dup(dtype=float), dw, index))
compare(h1, (v.dup(), w, ind), (dv.dup(), dw, index), errors=True)
compare(
h1, (v.dup(dtype=float), w, ind), (dv.dup(dtype=float), dw, index), errors=True
)
compare(h2, (v.dup(), w, ind), (dv.dup(), dw, index))
compare(h2, (v.dup(dtype=float), w, ind), (dv.dup(dtype=float), dw, index))
for dvm in dvms:
compare(g1, (vm.V, v.dup(), w, ind), (dvm.V, dv.dup(), dw, index))
compare(
g1,
(vm.V, v.dup(dtype=float), w, ind),
(dvm.V, dv.dup(dtype=float), dw, index),
)
compare(
lambda m, x, index: x[index].new(mask=m), (vm.V, w, ind), (dvm.V, dw, index)
)
compare(
lambda m, x, index: x[index].new(mask=m, dtype=float),
(vm.V, w, ind),
(dvm.V, dw, index),
)
compare(h3, (vm.V, v.dup(), w, ind), (dvm.V, dv.dup(), dw, index))
compare(
h3,
(vm.V, v.dup(dtype=float), w, ind),
(dvm.V, dv.dup(dtype=float), dw, index),
)
compare(
lambda m, x, index: x[index].new(mask=m, replace=True),
(vm.V, w, ind),
(dvm.V, dw, index),
errors=True,
)
compare(
lambda m, x, index: x[index].new(mask=m, replace=True, dtype=float),
(vm.V, w, ind),
(dvm.V, dw, index),
errors=True,
)
compare(h4, (vm.V, v.dup(), w, ind), (dvm.V, dv.dup(), dw, index))
compare(
h4,
(vm.V, v.dup(dtype=float), w, ind),
(dvm.V, dv.dup(dtype=float), dw, index),
)
compare(
lambda m, x, index: x[index].new(mask=m, replace=False),
(vm.V, w, ind),
(dvm.V, dw, index),
errors=True,
)
compare(
lambda m, x, index: x[index].new(mask=m, replace=False, dtype=float),
(vm.V, w, ind),
(dvm.V, dw, index),
errors=True,
)
compare(h5, (vm.V, v.dup(), w, ind), (dvm.V, dv.dup(), dw, index))
compare(
h5,
(vm.V, v.dup(dtype=float), w, ind),
(dvm.V, dv.dup(dtype=float), dw, index),
)
compare(
lambda m, x, index: x[index].new(mask=m, accum=gb.binary.plus),
(vm.V, w, ind),
(dvm.V, dw, index),
errors=True,
)
compare(
lambda m, x, index: x[index].new(mask=m, accum=gb.binary.plus, dtype=float),
(vm.V, w, ind),
(dvm.V, dw, index),
errors=True,
)
compare(i1, (vm.V, v.dup(), w, ind), (dvm.V, dv.dup(), dw, index))
compare(
i1,
(vm.V, v.dup(dtype=float), w, ind),
(dvm.V, dv.dup(dtype=float), dw, index),
)
compare(
lambda m, x, index: x[index].new(
mask=m, accum=gb.binary.plus, replace=True
),
(vm.V, w, ind),
(dvm.V, dw, index),
errors=True,
)
compare(
lambda m, x, index: x[index].new(
mask=m, accum=gb.binary.plus, replace=True, dtype=float
),
(vm.V, w, ind),
(dvm.V, dw, index),
errors=True,
)
compare(i2, (vm.V, v.dup(), w, ind), (dvm.V, dv.dup(), dw, index))
compare(
i2,
(vm.V, v.dup(dtype=float), w, ind),
(dvm.V, dv.dup(dtype=float), dw, index),
)
compare(
lambda m, x, index: x[index].new(
mask=m, accum=gb.binary.plus, replace=False
),
(vm.V, w, ind),
(dvm.V, dw, index),
errors=True,
)
compare(
lambda m, x, index: x[index].new(
mask=m, accum=gb.binary.plus, replace=False, dtype=float
),
(vm.V, w, ind),
(dvm.V, dw, index),
errors=True,
)
for dsm in dsms:
compare(g1, (sm.S, v.dup(), w, ind), (dsm.S, dv.dup(), dw, index))
compare(
g1,
(sm.S, v.dup(dtype=float), w, ind),
(dsm.S, dv.dup(dtype=float), dw, index),
)
compare(
lambda m, x, index: x[index].new(mask=m), (sm.S, w, ind), (dsm.S, dw, index)
)
compare(
lambda m, x, index: x[index].new(mask=m, dtype=float),
(sm.S, w, ind),
(dsm.S, dw, index),
)
compare(h3, (sm.S, v.dup(), w, ind), (dsm.S, dv.dup(), dw, index))
compare(
h3,
(sm.S, v.dup(dtype=float), w, ind),
(dsm.S, dv.dup(dtype=float), dw, index),
)
compare(
lambda m, x, index: x[index].new(mask=m, replace=True),
(sm.S, w, ind),
(dsm.S, dw, index),
errors=True,
)
compare(
lambda m, x, index: x[index].new(mask=m, replace=True, dtype=float),
(sm.S, w, ind),
(dsm.S, dw, index),
errors=True,
)
compare(h4, (sm.S, v.dup(), w, ind), (dsm.S, dv.dup(), dw, index))
compare(
h4,
(sm.S, v.dup(dtype=float), w, ind),
(dsm.S, dv.dup(dtype=float), dw, index),
)
compare(
lambda m, x, index: x[index].new(mask=m, replace=False),
(sm.S, w, ind),
(dsm.S, dw, index),
errors=True,
)
compare(
lambda m, x, index: x[index].new(mask=m, replace=False, dtype=float),
(sm.S, w, ind),
(dsm.S, dw, index),
errors=True,
)
compare(h5, (sm.S, v.dup(), w, ind), (dsm.S, dv.dup(), dw, index))
compare(
h5,
(sm.S, v.dup(dtype=float), w, ind),
(dsm.S, dv.dup(dtype=float), dw, index),
)
compare(
lambda m, x, index: x[index].new(mask=m, accum=gb.binary.plus),
(sm.S, w, ind),
(dsm.S, dw, index),
errors=True,
)
compare(
lambda m, x, index: x[index].new(mask=m, accum=gb.binary.plus, dtype=float),
(sm.S, w, ind),
(dsm.S, dw, index),
errors=True,
)
compare(i1, (sm.S, v.dup(), w, ind), (dsm.S, dv.dup(), dw, index))
compare(
i1,
(sm.S, v.dup(dtype=float), w, ind),
(dsm.S, dv.dup(dtype=float), dw, index),
)
compare(
lambda m, x, index: x[index].new(
mask=m, accum=gb.binary.plus, replace=True
),
(sm.S, w, ind),
(dsm.S, dw, index),
errors=True,
)
compare(
lambda m, x, index: x[index].new(
mask=m, accum=gb.binary.plus, replace=True, dtype=float
),
(sm.S, w, ind),
(dsm.S, dw, index),
errors=True,
)
compare(i2, (sm.S, v.dup(), w, ind), (dsm.S, dv.dup(), dw, index))
compare(
i2,
(sm.S, v.dup(dtype=float), w, ind),
(dsm.S, dv.dup(dtype=float), dw, index),
)
compare(
lambda m, x, index: x[index].new(
mask=m, accum=gb.binary.plus, replace=False
),
(sm.S, w, ind),
(dsm.S, dw, index),
errors=True,
)
compare(
lambda m, x, index: x[index].new(
mask=m, accum=gb.binary.plus, replace=False, dtype=float
),
(sm.S, w, ind),
(dsm.S, dw, index),
errors=True,
)
@pytest.mark.slow
def test_subassign(vs, ws, vms, sms):
test_replace_true = True
v, dvs = vs
gw, dws = ws
vm, dvms = vms
sm, dsms = sms
scalars = (1, 1.0)
gws = (gw,) * len(dws) + scalars
dws = dws + scalars
def inv_if(mask, is_inv=False):
if is_inv:
return ~mask
return mask
index1_da = da.from_array([0, 3, 1, 4, 2, 5], chunks=((2, 2, 2),))
index2_da = da.from_array([0, 5, 5, 1, 2, 0], chunks=((2, 2, 2),))
index3_da = da.from_array([0] * 6, chunks=((2, 2, 2),))
for index in [
index1_da,
index2_da,
index3_da,
[0, 3, 1, 4, 2, 5],
[0, 5, 5, 1, 2, 0],
slice(None),
slice(None, None, -1),
[0] * 6,
]:
def f2(x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x[ind]() << y
return x
def g1(m, x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x[ind](mask=m) << y
return x
def g2(x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x[ind](accum=gb.binary.plus) << y
return x
def g3(x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x[ind](replace=True) << y
return x
def g4(x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x[ind](replace=False) << y
return x
def h1(x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x[ind](accum=gb.binary.plus, replace=True) << y
return x
def h2(x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x[ind](accum=gb.binary.plus, replace=False) << y
return x
def h3(m, x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x[ind](mask=m, replace=test_replace_true) << y
return x
def h4(m, x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x[ind](mask=m, replace=False) << y
return x
def h5(m, x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x[ind](mask=m, accum=gb.binary.plus) << y
return x
def i1(m, x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x[ind](mask=m, accum=gb.binary.plus, replace=test_replace_true) << y
return x
def i2(m, x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x[ind](mask=m, accum=gb.binary.plus, replace=False) << y
return x
for dv in dvs:
for w, dw in zip(gws, dws):
compare(f2, (v.dup(), w), (dv.dup(), dw))
compare(f2, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw))
compare(g2, (v.dup(), w), (dv.dup(), dw))
compare(g2, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw))
compare(g3, (v.dup(), w), (dv.dup(), dw), errors=True)
compare(g3, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw), errors=True)
compare(g4, (v.dup(), w), (dv.dup(), dw))
compare(g4, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw))
compare(h1, (v.dup(), w), (dv.dup(), dw), errors=True)
compare(h1, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw), errors=True)
compare(h2, (v.dup(), w), (dv.dup(), dw))
compare(h2, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw))
for is_inv in [False, True]:
for dvm in dvms:
compare(
g1,
(inv_if(vm.V, is_inv), v.dup(), w),
(inv_if(dvm.V, is_inv), dv.dup(), dw),
)
compare(
g1,
(inv_if(vm.V, is_inv), v.dup(dtype=float), w),
(inv_if(dvm.V, is_inv), dv.dup(dtype=float), dw),
)
compare(
h3,
(inv_if(vm.V, is_inv), v.dup(), w),
(inv_if(dvm.V, is_inv), dv.dup(), dw),
)
compare(
h3,
(inv_if(vm.V, is_inv), v.dup(dtype=float), w),
(inv_if(dvm.V, is_inv), dv.dup(dtype=float), dw),
)
compare(
h4,
(inv_if(vm.V, is_inv), v.dup(), w),
(inv_if(dvm.V, is_inv), dv.dup(), dw),
)
compare(
h4,
(inv_if(vm.V, is_inv), v.dup(dtype=float), w),
(inv_if(dvm.V, is_inv), dv.dup(dtype=float), dw),
)
compare(
h5,
(inv_if(vm.V, is_inv), v.dup(), w),
(inv_if(dvm.V, is_inv), dv.dup(), dw),
)
compare(
h5,
(inv_if(vm.V, is_inv), v.dup(dtype=float), w),
(inv_if(dvm.V, is_inv), dv.dup(dtype=float), dw),
)
compare(
i1,
(inv_if(vm.V, is_inv), v.dup(), w),
(inv_if(dvm.V, is_inv), dv.dup(), dw),
)
compare(
i1,
(inv_if(vm.V, is_inv), v.dup(dtype=float), w),
(inv_if(dvm.V, is_inv), dv.dup(dtype=float), dw),
)
compare(
i2,
(inv_if(vm.V, is_inv), v.dup(), w),
(inv_if(dvm.V, is_inv), dv.dup(), dw),
)
compare(
i2,
(inv_if(vm.V, is_inv), v.dup(dtype=float), w),
(inv_if(dvm.V, is_inv), dv.dup(dtype=float), dw),
)
for dsm in dsms:
compare(
g1,
(inv_if(sm.S, is_inv), v.dup(), w),
(inv_if(dsm.S, is_inv), dv.dup(), dw),
)
compare(
g1,
(inv_if(sm.S, is_inv), v.dup(dtype=float), w),
(inv_if(dsm.S, is_inv), dv.dup(dtype=float), dw),
)
compare(
h3,
(inv_if(sm.S, is_inv), v.dup(), w),
(inv_if(dsm.S, is_inv), dv.dup(), dw),
)
compare(
h3,
(inv_if(sm.S, is_inv), v.dup(dtype=float), w),
(inv_if(dsm.S, is_inv), dv.dup(dtype=float), dw),
)
compare(
h4,
(inv_if(sm.S, is_inv), v.dup(), w),
(inv_if(dsm.S, is_inv), dv.dup(), dw),
)
compare(
h4,
(inv_if(sm.S, is_inv), v.dup(dtype=float), w),
(inv_if(dsm.S, is_inv), dv.dup(dtype=float), dw),
)
compare(
h5,
(inv_if(sm.S, is_inv), v.dup(), w),
(inv_if(dsm.S, is_inv), dv.dup(), dw),
)
compare(
h5,
(inv_if(sm.S, is_inv), v.dup(dtype=float), w),
(inv_if(dsm.S, is_inv), dv.dup(dtype=float), dw),
)
compare(
i1,
(inv_if(sm.S, is_inv), v.dup(), w),
(inv_if(dsm.S, is_inv), dv.dup(), dw),
)
compare(
i1,
(inv_if(sm.S, is_inv), v.dup(dtype=float), w),
(inv_if(dsm.S, is_inv), dv.dup(dtype=float), dw),
)
compare(
i2,
(inv_if(sm.S, is_inv), v.dup(), w),
(inv_if(dsm.S, is_inv), dv.dup(), dw),
)
compare(
i2,
(inv_if(sm.S, is_inv), v.dup(dtype=float), w),
(inv_if(dsm.S, is_inv), dv.dup(dtype=float), dw),
)
@pytest.mark.slow
def test_assign(vs, ws, vms, sms):
test_replace_true = True
v, dvs = vs
gw, dws = ws
vm, dvms = vms
sm, dsms = sms
gb_s = gb.Scalar.from_value(9)
dgb_s = dgb.Scalar.from_value(9)
scalars = (1, 1.0)
gws = (gw,) * len(dws) + scalars + (gb_s,)
dws = dws + scalars + (dgb_s,)
def inv_if(mask, is_inv=False):
if is_inv:
return ~mask
return mask
index1_da = da.from_array([0, 3, 1, 4, 2, 5], chunks=((2, 2, 2),))
index2_da = da.from_array([0, 5, 5, 1, 2, 0], chunks=((2, 2, 2),))
index3_da = da.from_array([0] * 6, chunks=((2, 2, 2),))
for index in [
index1_da,
index2_da,
index3_da,
[0] * 6,
slice(None, None, -1),
slice(None),
[0, 3, 1, 4, 2, 5],
[0, 5, 5, 1, 2, 0],
]:
def f1(x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x[ind] << y
return x
def f2(x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x()[ind] << y
return x
def g1(m, x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x(mask=m)[ind] << y
return x
def g2(x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x(accum=gb.binary.plus)[ind] << y
return x
def g3(x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x(replace=True)[ind] << y
return x
def g4(x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x(replace=False)[ind] << y
return x
def h1(x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x(accum=gb.binary.plus, replace=True)[ind] << y
return x
def h2(x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x(accum=gb.binary.plus, replace=False)[ind] << y
return x
def h3(m, x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x(mask=m, replace=test_replace_true)[ind] << y
return x
def h4(m, x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x(mask=m, replace=False)[ind] << y
return x
def h5(m, x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x(mask=m, accum=gb.binary.plus)[ind] << y
return x
def i1(m, x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x(mask=m, accum=gb.binary.plus, replace=test_replace_true)[ind] << y
return x
def i2(m, x, y):
ind = (
index.compute()
if isinstance(x, gb.base.BaseType) and type(index) is da.core.Array
else index
)
x(mask=m, accum=gb.binary.plus, replace=False)[ind] << y
return x
for dv in dvs:
for w, dw in zip(gws, dws):
compare(f1, (v.dup(), w), (dv.dup(), dw))
compare(f1, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw))
compare(f2, (v.dup(), w), (dv.dup(), dw))
compare(f2, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw))
compare(g2, (v.dup(), w), (dv.dup(), dw))
compare(g2, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw))
compare(g3, (v.dup(), w), (dv.dup(), dw), errors=True)
compare(g3, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw), errors=True)
compare(g4, (v.dup(), w), (dv.dup(), dw))
compare(g4, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw))
compare(h1, (v.dup(), w), (dv.dup(), dw), errors=True)
compare(h1, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw), errors=True)
compare(h2, (v.dup(), w), (dv.dup(), dw))
compare(h2, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw))
for is_inv in [False, True]:
for dvm in dvms:
compare(
g1,
(inv_if(vm.V, is_inv), v.dup(), w),
(inv_if(dvm.V, is_inv), dv.dup(), dw),
)
compare(
g1,
(inv_if(vm.V, is_inv), v.dup(dtype=float), w),
(inv_if(dvm.V, is_inv), dv.dup(dtype=float), dw),
)
compare(
h3,
(inv_if(vm.V, is_inv), v.dup(), w),
(inv_if(dvm.V, is_inv), dv.dup(), dw),
)
compare(
h3,
(inv_if(vm.V, is_inv), v.dup(dtype=float), w),
(inv_if(dvm.V, is_inv), dv.dup(dtype=float), dw),
)
compare(
h4,
(inv_if(vm.V, is_inv), v.dup(), w),
(inv_if(dvm.V, is_inv), dv.dup(), dw),
)
compare(
h4,
(inv_if(vm.V, is_inv), v.dup(dtype=float), w),
(inv_if(dvm.V, is_inv), dv.dup(dtype=float), dw),
)
compare(
h5,
(inv_if(vm.V, is_inv), v.dup(), w),
(inv_if(dvm.V, is_inv), dv.dup(), dw),
)
compare(
h5,
(inv_if(vm.V, is_inv), v.dup(dtype=float), w),
(inv_if(dvm.V, is_inv), dv.dup(dtype=float), dw),
)
compare(
i1,
(inv_if(vm.V, is_inv), v.dup(), w),
(inv_if(dvm.V, is_inv), dv.dup(), dw),
)
compare(
i1,
(inv_if(vm.V, is_inv), v.dup(dtype=float), w),
(inv_if(dvm.V, is_inv), dv.dup(dtype=float), dw),
)
compare(
i2,
(inv_if(vm.V, is_inv), v.dup(), w),
(inv_if(dvm.V, is_inv), dv.dup(), dw),
)
compare(
i2,
(inv_if(vm.V, is_inv), v.dup(dtype=float), w),
(inv_if(dvm.V, is_inv), dv.dup(dtype=float), dw),
)
for dsm in dsms:
compare(
g1,
(inv_if(sm.S, is_inv), v.dup(), w),
(inv_if(dsm.S, is_inv), dv.dup(), dw),
)
compare(
g1,
(inv_if(sm.S, is_inv), v.dup(dtype=float), w),
(inv_if(dsm.S, is_inv), dv.dup(dtype=float), dw),
)
compare(
h3,
(inv_if(sm.S, is_inv), v.dup(), w),
(inv_if(dsm.S, is_inv), dv.dup(), dw),
)
compare(
h3,
(inv_if(sm.S, is_inv), v.dup(dtype=float), w),
(inv_if(dsm.S, is_inv), dv.dup(dtype=float), dw),
)
compare(
h4,
(inv_if(sm.S, is_inv), v.dup(), w),
(inv_if(dsm.S, is_inv), dv.dup(), dw),
)
compare(
h4,
(inv_if(sm.S, is_inv), v.dup(dtype=float), w),
(inv_if(dsm.S, is_inv), dv.dup(dtype=float), dw),
)
compare(
h5,
(inv_if(sm.S, is_inv), v.dup(), w),
(inv_if(dsm.S, is_inv), dv.dup(), dw),
)
compare(
h5,
(inv_if(sm.S, is_inv), v.dup(dtype=float), w),
(inv_if(dsm.S, is_inv), dv.dup(dtype=float), dw),
)
compare(
i1,
(inv_if(sm.S, is_inv), v.dup(), w),
(inv_if(dsm.S, is_inv), dv.dup(), dw),
)
compare(
i1,
(inv_if(sm.S, is_inv), v.dup(dtype=float), w),
(inv_if(dsm.S, is_inv), dv.dup(dtype=float), dw),
)
compare(
i2,
(inv_if(sm.S, is_inv), v.dup(), w),
(inv_if(dsm.S, is_inv), dv.dup(), dw),
)
compare(
i2,
(inv_if(sm.S, is_inv), v.dup(dtype=float), w),
(inv_if(dsm.S, is_inv), dv.dup(dtype=float), dw),
)
def test_reduce_assign(vs, ws, vms, sms):
test_replace_true = True
v, dvs = vs
gw, dws = ws
vm, dvms = vms
sm, dsms = sms
gb_s = gb.Scalar.from_value(9)
dgb_s = dgb.Scalar.from_value(9)
scalars = (1, 1.0)
gws = (gw,) * len(dws) + scalars + (gb_s,)
dws = dws + scalars + (dgb_s,)
def inv_if(mask, is_inv=False):
if is_inv:
return ~mask
return mask
index1_da = da.from_array([0, 3, 1, 4, 2, 5], chunks=((2, 2, 2),))
index2_da = da.from_array([0, 5, 5, 1, 2, 0], chunks=((2, 2, 2),))
index3_da = da.from_array([0] * 6, chunks=((2, 2, 2),))
for index in [
[0, 3, 1, 4, 2, 5],
[0, 5, 5, 1, 2, 0],
[0] * 6,
slice(None),
slice(None, None, -1),
index1_da,
index2_da,
index3_da,
]:
def f1(x, y):
if isinstance(x, gb.base.BaseType):
ind = index.compute() if type(index) is da.core.Array else index
x[ind] << y
else:
ind = index
dgb.expr.reduce_assign(x, ind, y, dup_op="last")
return x
def g1(m, x, y):
if isinstance(x, gb.base.BaseType):
ind = index.compute() if type(index) is da.core.Array else index
x(mask=m)[ind] << y
else:
ind = index
dgb.expr.reduce_assign(x, ind, y, mask=m, dup_op="last")
return x
def g2(x, y):
if isinstance(x, gb.base.BaseType):
ind = index.compute() if type(index) is da.core.Array else index
x(accum=gb.binary.plus)[ind] << y
else:
ind = index
dgb.expr.reduce_assign(x, ind, y, accum=gb.binary.plus, dup_op="last")
return x
def g3(x, y):
if isinstance(x, gb.base.BaseType):
ind = index.compute() if type(index) is da.core.Array else index
x(replace=True)[ind] << y
else:
ind = index
dgb.expr.reduce_assign(x, ind, y, dup_op="last", replace=True)
return x
def g4(x, y):
if isinstance(x, gb.base.BaseType):
ind = index.compute() if type(index) is da.core.Array else index
x(replace=False)[ind] << y
else:
ind = index
dgb.expr.reduce_assign(x, ind, y, dup_op="last", replace=False)
return x
def h1(x, y):
if isinstance(x, gb.base.BaseType):
ind = index.compute() if type(index) is da.core.Array else index
x(accum=gb.binary.plus, replace=True)[ind] << y
else:
ind = index
dgb.expr.reduce_assign(x, ind, y, dup_op="last", accum=gb.binary.plus, replace=True)
return x
def h2(x, y):
if isinstance(x, gb.base.BaseType):
ind = index.compute() if type(index) is da.core.Array else index
x(accum=gb.binary.plus, replace=False)[ind] << y
else:
ind = index
dgb.expr.reduce_assign(
x, ind, y, dup_op="last", accum=gb.binary.plus, replace=False
)
return x
def h3(m, x, y):
if isinstance(x, gb.base.BaseType):
ind = index.compute() if type(index) is da.core.Array else index
x(mask=m, replace=True)[ind] << y
else:
ind = index
dgb.expr.reduce_assign(x, ind, y, mask=m, dup_op="last", replace=True)
return x
def h4(m, x, y):
if isinstance(x, gb.base.BaseType):
ind = index.compute() if type(index) is da.core.Array else index
x(mask=m, replace=False)[ind] << y
else:
ind = index
dgb.expr.reduce_assign(x, ind, y, mask=m, dup_op="last", replace=False)
return x
def h5(m, x, y):
if isinstance(x, gb.base.BaseType):
ind = index.compute() if type(index) is da.core.Array else index
x(mask=m, accum=gb.binary.plus)[ind] << y
else:
ind = index
dgb.expr.reduce_assign(x, ind, y, mask=m, accum=gb.binary.plus, dup_op="last")
return x
def i1(m, x, y):
if isinstance(x, gb.base.BaseType):
ind = index.compute() if type(index) is da.core.Array else index
x(mask=m, accum=gb.binary.plus, replace=True)[ind] << y
else:
ind = index
dgb.expr.reduce_assign(
x, ind, y, mask=m, accum=gb.binary.plus, replace=True, dup_op="last"
)
return x
def i2(m, x, y):
if isinstance(x, gb.base.BaseType):
ind = index.compute() if type(index) is da.core.Array else index
x(mask=m, accum=gb.binary.plus, replace=False)[ind] << y
else:
ind = index
dgb.expr.reduce_assign(
x, ind, y, mask=m, accum=gb.binary.plus, replace=False, dup_op="last"
)
return x
for dv in dvs:
for w, dw in zip(gws, dws):
compare(f1, (v.dup(), w), (dv.dup(), dw))
compare(f1, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw))
compare(g2, (v.dup(), w), (dv.dup(), dw))
compare(g2, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw))
compare(g3, (v.dup(), w), (dv.dup(), dw), errors=True)
compare(g3, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw), errors=True)
compare(g4, (v.dup(), w), (dv.dup(), dw))
compare(g4, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw))
compare(h1, (v.dup(), w), (dv.dup(), dw), errors=True)
compare(h1, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw), errors=True)
compare(h2, (v.dup(), w), (dv.dup(), dw))
compare(h2, (v.dup(dtype=float), w), (dv.dup(dtype=float), dw))
for is_inv in [False, True]:
for dvm in dvms:
compare(
g1,
(inv_if(vm.V, is_inv), v.dup(), w),
(inv_if(dvm.V, is_inv), dv.dup(), dw),
)
compare(
g1,
(inv_if(vm.V, is_inv), v.dup(dtype=float), w),
(inv_if(dvm.V, is_inv), dv.dup(dtype=float), dw),
)
compare(
h3,
(inv_if(vm.V, is_inv), v.dup(), w),
(inv_if(dvm.V, is_inv), dv.dup(), dw),
)
compare(
h3,
(inv_if(vm.V, is_inv), v.dup(dtype=float), w),
(inv_if(dvm.V, is_inv), dv.dup(dtype=float), dw),
)
compare(
h4,
(inv_if(vm.V, is_inv), v.dup(), w),
(inv_if(dvm.V, is_inv), dv.dup(), dw),
)
compare(
h4,
(inv_if(vm.V, is_inv), v.dup(dtype=float), w),
(inv_if(dvm.V, is_inv), dv.dup(dtype=float), dw),
)
compare(
h5,
(inv_if(vm.V, is_inv), v.dup(), w),
(inv_if(dvm.V, is_inv), dv.dup(), dw),
)
compare(
h5,
(inv_if(vm.V, is_inv), v.dup(dtype=float), w),
(inv_if(dvm.V, is_inv), dv.dup(dtype=float), dw),
)
compare(
i1,
(inv_if(vm.V, is_inv), v.dup(), w),
(inv_if(dvm.V, is_inv), dv.dup(), dw),
)
compare(
i1,
(inv_if(vm.V, is_inv), v.dup(dtype=float), w),
(inv_if(dvm.V, is_inv), dv.dup(dtype=float), dw),
)
compare(
i2,
(inv_if(vm.V, is_inv), v.dup(), w),
(inv_if(dvm.V, is_inv), dv.dup(), dw),
)
compare(
i2,
(inv_if(vm.V, is_inv), v.dup(dtype=float), w),
(inv_if(dvm.V, is_inv), dv.dup(dtype=float), dw),
)
for dsm in dsms:
compare(
g1,
(inv_if(sm.S, is_inv), v.dup(), w),
(inv_if(dsm.S, is_inv), dv.dup(), dw),
)
compare(
g1,
(inv_if(sm.S, is_inv), v.dup(dtype=float), w),
(inv_if(dsm.S, is_inv), dv.dup(dtype=float), dw),
)
compare(
h3,
(inv_if(sm.S, is_inv), v.dup(), w),
(inv_if(dsm.S, is_inv), dv.dup(), dw),
)
compare(
h3,
(inv_if(sm.S, is_inv), v.dup(dtype=float), w),
(inv_if(dsm.S, is_inv), dv.dup(dtype=float), dw),
)
compare(
h4,
(inv_if(sm.S, is_inv), v.dup(), w),
(inv_if(dsm.S, is_inv), dv.dup(), dw),
)
compare(
h4,
(inv_if(sm.S, is_inv), v.dup(dtype=float), w),
(inv_if(dsm.S, is_inv), dv.dup(dtype=float), dw),
)
compare(
h5,
(inv_if(sm.S, is_inv), v.dup(), w),
(inv_if(dsm.S, is_inv), dv.dup(), dw),
)
compare(
h5,
(inv_if(sm.S, is_inv), v.dup(dtype=float), w),
(inv_if(dsm.S, is_inv), dv.dup(dtype=float), dw),
)
compare(
i1,
(inv_if(sm.S, is_inv), v.dup(), w),
(inv_if(dsm.S, is_inv), dv.dup(), dw),
)
compare(
i1,
(inv_if(sm.S, is_inv), v.dup(dtype=float), w),
(inv_if(dsm.S, is_inv), dv.dup(dtype=float), dw),
)
compare(
i2,
(inv_if(sm.S, is_inv), v.dup(), w),
(inv_if(dsm.S, is_inv), dv.dup(), dw),
)
compare(
i2,
(inv_if(sm.S, is_inv), v.dup(dtype=float), w),
(inv_if(dsm.S, is_inv), dv.dup(dtype=float), dw),
)
@pytest.mark.xfail
def test_attrs(vs):
v, dvs = vs
dv = dvs[0]
assert set(dir(v)) - set(dir(dv)) == {
"__del__", # TODO
"_assign_element",
"_extract_element",
"_is_scalar",
"_prep_for_assign",
"_prep_for_extract",
"_delete_element",
"gb_obj",
"show",
}
assert set(dir(dv)) - set(dir(v)) == {
"_delayed",
"_meta",
"_optional_dup",
"compute",
"from_vector",
"from_delayed",
"persist",
"visualize",
}
def test_signatures_match_grblas():
def has_signature(x):
try:
inspect.signature(x)
except Exception:
return False
else:
return True
v1 = gb.Vector.from_values(1, 2)
v2 = dgb.Vector.from_values(1, 2)
skip = {
"from_pygraphblas",
"to_pygraphblas",
"__class__",
"__init__",
"from_values",
"inner", # TODO
"outer", # TODO
}
d1 = {
key: inspect.signature(val)
for key, val in inspect.getmembers(v1)
if has_signature(val) and key not in skip
}
d2 = {
key: inspect.signature(val)
for key, val in inspect.getmembers(v2)
if has_signature(val) and key not in skip
}
for key, val in d1.items():
# if not key.startswith("_") or key.startswith("__") and key in d2:
if not key.startswith("_"):
assert val == d2[key], (key, str(val), str(d2[key]))
| 2.21875 | 2 |
closed/Intel/code/bert-99/mxnet/run_mxnet_server.py | wom-ai/inference_results_v1.0 | 0 | 12767332 | """
This is a sample stub of loadgen with multiple processes support.
Each process sets its affinity by a proc list.
Loadgen is a producer, which calls issue_queries(). issue_queries() gets query
from loadgen and puts query id/sample indices into an input queue.
Each Consumer(process)'s run() reads input queue, calls model_predict() to get
inference result, and put result into output queue.
A standalone thread's response_loadgen() reads output queue, and responds
inference result to loadgen.
Server and Offline scenario PerformanceOnly mode are verified.
Each Model needs to implement below
model_predict()
load_query_samples()
unload_query_samples()
For model_predict(), how to return data to loadgen is model specific, the
loadgen CPP API requires a data pointer and length, then it saves the data to
mlperf_log_accuracy.json, which is used to generate accuracy number offline.
"""
import multiprocessing
import threading
import subprocess
import time
import os
import sys
import argparse
import array
import logging
import numpy as np
import mlperf_loadgen as lg
from collections import defaultdict
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("MXNet-BERT")
num_cpus = 28
num_ins = 2
NANO_SEC = 1e9
MILLI_SEC = 1000
in_queue_cnt = 0
out_queue_cnt = 0
bs_step = 8
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--scenario", choices=["Offline", "Server"], default="Offline", help="Scenario")
parser.add_argument("--batching", choices=["Fixed", "Dynamic", "Adaptive"], default="Adaptive", help="Batching method")
parser.add_argument("--batch-size", default=1, type=int, help="batch_size")
parser.add_argument("--num-instance", default=2, type=int, help="number of instance")
parser.add_argument("--num-phy-cpus", default=28, type=int, help="number of physical cpus")
parser.add_argument("--vocab", default='converted_from_tf_to_mxnet/tf.vocab',
type=str, help="vocab file path")
parser.add_argument("--params", default='converted_from_tf_to_mxnet/tf_fp32.params',
type=str, help="FP32 params path")
parser.add_argument("--quantized_model_prefix",
default='converted_from_tf_to_mxnet/quantized_models/model_bert_squad_quantized_customize',
type=str, help="quantized model prefix")
parser.add_argument("--accuracy", action="store_true", help="enable accuracy pass")
parser.add_argument("--quantized", action="store_true", help="use quantized model")
parser.add_argument("--mlperf-conf", default="mlperf.conf", help="mlperf rules config")
parser.add_argument("--user-conf", default="user.conf", help="user rules config")
parser.add_argument("--perf-count", default=None, help="perf count")
parser.add_argument("--profile", action="store_true", help="whether enable profiler")
parser.add_argument("--warmup", action="store_true", help="whether do warmup")
parser.add_argument("--perf_calibrate", action="store_true", help="whether do performance calibration")
args = parser.parse_args()
return args
scenario_map = {
"Offline": lg.TestScenario.Offline,
"Server": lg.TestScenario.Server,
}
def load_query_samples(sample_list):
# This is model specific place holder
pass
def unload_query_samples(sample_list):
# This is model specific place holder
pass
def block_until(counter, num_ins, t=1):
while counter.value < num_ins:
time.sleep(t)
batches = None
def load_perf_prof():
global batches
global throughputs
# load performance profile map for offline scenario
if os.path.exists("prof.py"):
from prof import prof_map
from prof import prof_bs_step
else:
prof_map = {}
prof_bs_step = 1
return
longest_seq = 0
for k, v in sorted(prof_map.items()):
if k > longest_seq:
longest_seq = k
batches = [0.0] * (longest_seq+1)
throughputs = [0.0] * (longest_seq+1)
for k, v in sorted(prof_map.items()):
max_throughput = 0.0
max_bs = 0
for i in range(1, len(v)):
current_bs = i * prof_bs_step
if current_bs/v[i] > max_throughput:
max_throughput = current_bs/v[i]
max_bs = current_bs
batches[k] = max_bs
throughputs[k] = max_throughput
def get_best_bs(seq_len):
global batches
if batches == None:
load_perf_prof()
global throughputs
while batches[seq_len] == 0:
seq_len += 1
best_seq_len = seq_len
best_bs = batches[seq_len]
best_throughput = throughputs[seq_len]
seq_len += 1
while seq_len < 385:
if throughputs[seq_len] > best_throughput:
best_seq_len = seq_len
best_bs = batches[seq_len]
best_throughput = throughputs[seq_len]
seq_len += 1
return best_seq_len, best_bs, best_throughput
class Consumer(multiprocessing.Process):
def __init__(self, task_queue, result_queue, lock, init_counter, calibrate_counter, proc_idx, world_size, args, max_pad_len=384):
multiprocessing.Process.__init__(self)
global num_ins
self.task_queue = task_queue
self.result_queue = result_queue
self.lock = lock
self.init_counter = init_counter
self.calibrate_counter = calibrate_counter
self.proc_idx = proc_idx
self.world_size = world_size
self.args = args
self.affinity = range(round(proc_idx * num_cpus / num_ins),
round((proc_idx + 1) * num_cpus / num_ins))
self.start_core_idx = proc_idx * num_cpus // num_ins
self.end_core_idx = (proc_idx + 1) * num_cpus // num_ins - 1
self.length_list = {}
self.length_time_list = {}
self.max_pad_len = max_pad_len
def warmup(self, model, data_set, context, scenario):
if self.proc_idx == 0:
print ('Start warmup...')
data_size = len(data_set.eval_features)
count = 0
import mxnet as mx
for start in range(0, data_size):
inputs_list = []
token_types_list = []
valid_length_list = []
eval_feature = data_set.eval_features[start]
_, inputs, token_types, valid_length, _, _ = eval_feature
if len(inputs) in self.length_list:
continue
self.length_list[len(inputs)] = True
max_throughput = 0.0
best_bs = 0
if scenario == 'Offline':
# only support warmup of adaptive batching
best_len, best_bs, _ = get_best_bs(len(inputs))
if best_len in self.length_list:
continue
self.length_list[best_len] = True
inputs += [0] * (best_len - len(inputs))
token_types += [0] * (best_len - len(token_types))
for i in range(best_bs):
inputs_list.append(inputs)
token_types_list.append(token_types)
valid_length_list.append(valid_length)
if self.proc_idx == 0:
print ("warmup seqlen {} batchsize {}".format(best_len, best_bs))
else:
inputs_list.append(inputs)
token_types_list.append(token_types)
valid_length_list.append(valid_length)
inputs_nd = mx.nd.array(inputs_list).as_in_context(context)
token_types_nd = mx.nd.array(token_types_list).as_in_context(context)
valid_length_nd = mx.nd.array(valid_length_list).as_in_context(context).astype('float32')
# warm up primitive once
out = model.net(inputs_nd, token_types_nd, valid_length_nd)
out_np = out.asnumpy()
count += 1
if count % 10 == 0 and self.proc_idx == 0:
print ('Warmup {} samples'.format(count))
if self.proc_idx == 0:
print ('Warmup done')
def calibrate(self, model, data_set, context):
if self.proc_idx == 0:
print ('Start calibration...')
data_size = len(data_set.eval_features)
count = 0
global bs_step
import mxnet as mx
for start in range(0, data_size):
inputs_list = []
token_types_list = []
valid_length_list = []
eval_feature = data_set.eval_features[start]
_, inputs, token_types, valid_length, _, _ = eval_feature
cur_len = len(inputs)
if cur_len in self.length_list:
continue
self.length_list[cur_len] = True
if count % self.world_size != self.proc_idx:
count += 1
continue
count += 1
length_time_list = []
length_time_list.append(0)
max_throughput = 0.0
best_bs = 0
max_len = len(inputs)
while True:
for i in range(bs_step):
inputs_list.append(inputs)
token_types_list.append(token_types)
valid_length_list.append(valid_length)
inputs_nd = mx.nd.array(inputs_list).as_in_context(context)
token_types_nd = mx.nd.array(token_types_list).as_in_context(context)
valid_length_nd = mx.nd.array(valid_length_list).as_in_context(context).astype('float32')
# warm up primitive once
out = model.net(inputs_nd, token_types_nd, valid_length_nd)
out_np = out.asnumpy()
# measure time for the batch
t0 = time.time()
for i in range(8):
out = model.net(inputs_nd, token_types_nd, valid_length_nd)
out_np = out.asnumpy()
t1 = time.time()
duration = (t1 - t0)/8.0
throughput = len(inputs_list)/duration
if throughput > max_throughput:
max_throughput = throughput
best_bs = len(inputs_list)
if len(inputs_list) >= 256:
print ("{} - Best efficiency for seq len {} is BS {} with seq/s {:.5}".format(
self.proc_idx, max_len, best_bs, max_throughput))
break
#print ("{} - Best efficiency for seq len {} is BS {} with seq/s {:.5}, current BS {} seq/s {:.5}\r".format(
# self.proc_idx, max_len, best_bs, max_throughput, len(inputs_list), throughput), end='')
length_time_list.append(duration)
self.length_time_list[cur_len] = length_time_list
with open('prof_new.py', 'a') as f:
for k, v in sorted(self.length_time_list.items()):
print (' {} : {},'.format(k, v), file=f)
# keep the processor hot until all instance done calibration
print ('Calibrate almost done, keep instance hot')
self.lock.acquire()
self.calibrate_counter.value += 1
self.lock.release()
while self.calibrate_counter.value < 2 * self.world_size:
out = model.net(inputs_nd, token_types_nd, valid_length_nd)
out_np = out.asnumpy()
print ('Calibrate done')
def run(self):
global batching
#os.sched_setaffinity(self.pid, self.affinity)
cmd = "taskset -p -c %d-%d %d" % (self.start_core_idx, self.end_core_idx, self.pid)
print (cmd)
os.system(cmd)
import mxnet as mx
ctx = mx.cpu()
#from numexpr.utils import set_num_threads
#set_num_threads(28)
os.environ['OMP_NUM_THREADS'] = '{}'.format(self.end_core_idx-self.start_core_idx+1)
model = BERTModel(mx.cpu(), self.args.vocab, self.args.params,
self.args.quantized, self.args.quantized_model_prefix)
data_set = BERTDataSet(self.args.vocab, self.args.perf_count)
self.lock.acquire()
self.calibrate_counter.value += 1
self.lock.release()
block_until(self.calibrate_counter, self.world_size)
if self.args.perf_calibrate:
self.calibrate(model, data_set, ctx)
return
self.lock.acquire()
self.calibrate_counter.value += 1
self.lock.release()
if self.args.warmup:
self.warmup(model, data_set, ctx, self.args.scenario)
self.lock.acquire()
self.init_counter.value += 1
self.lock.release()
#affinity = os.sched_getaffinity(self.pid)
#print('Process', self.pid, 'affinity proc list:', affinity)
cur_step = 0
start_step = 384
end_step = -1
from utils import profile
while True:
next_task = self.task_queue.get() #(self.proc_idx)
if next_task is None:
# None means shutdown
log.info('Exiting {}-pid:{}, cur_step={}'.format(self.name, self.pid, cur_step))
self.task_queue.task_done()
if self.args.profile and self.proc_idx==0:
if end_step == -1:
end_step = cur_step
profile(cur_step, start_step, end_step, profile_name='profile_{}.json'.format(self.pid), early_exit=False)
break
query_id_list = next_task.query_id_list
sample_index_list = next_task.sample_index_list
batch_size = len(sample_index_list)
#print ('pid-{}, query_id_list: {}, sample_index_list: {}'.format(self.pid, query_id_list, sample_index_list))
inputs_list = []
token_types_list = []
valid_length_list = []
for sample_index in sample_index_list:
eval_feature = data_set.eval_features[sample_index]
_, inputs, token_types, valid_length, _, _ = eval_feature
inputs_list.append(inputs)
token_types_list.append(token_types)
valid_length_list.append(valid_length)
if len(inputs_list) > 1:
max_len = max([len(inp) for inp in inputs_list])
new_max_len, bs, best_throughput = get_best_bs(max_len)
if bs == len(inputs_list):
max_len = new_max_len
#for i in range(len(inputs_list)):
# inputs_list[i] += [0] * (max_len - len(inputs_list[i]))
# token_types_list[i] += [0] * (max_len - len(token_types_list[i]))
else:
max_len = self.max_pad_len #len(inputs_list[0]) #self.max_pad_len #len(inputs_list)
for i in range(len(inputs_list)):
inputs_list[i] += [0] * (max_len - len(inputs_list[i]))
token_types_list[i] += [0] * (max_len - len(token_types_list[i]))
inputs = mx.nd.array(inputs_list).as_in_context(ctx)
token_types = mx.nd.array(token_types_list).as_in_context(ctx)
valid_length = mx.nd.array(valid_length_list).as_in_context(ctx).astype('float32')
if self.args.profile and self.proc_idx==0:
profile(cur_step, start_step, end_step, profile_name='profile_{}.json'.format(self.pid), early_exit=False)
cur_step += 1
#t0 = time.time()
out = model.net(inputs, token_types, valid_length)
out_np = out.asnumpy()
#t1 = time.time()
#if self.proc_idx == 0:
# cur_throughput = len(inputs_list)/(t1-t0)
# if best_throughput != 0:
# throughput_diff = (cur_throughput - best_throughput) / best_throughput
# print ('inference seq len = {} BS = {} throughput = {:.5f} ({:.3f}%)'.format(max_len, len(inputs_list), cur_throughput, throughput_diff*100))
# else:
# print ('inference seq len = {} BS = {} throughput = {:.5f})'.format(max_len, len(inputs_list), cur_throughput))
result = Output(query_id_list, out_np)
self.result_queue.put(result)
#print('consumer-{}: output.shape={}, query_id={}'.format(self.pid, out_np.shape, query_id_list[0]))
self.task_queue.task_done()
class Input(object):
def __init__(self, id_list, index_list, sample_length_list):
assert isinstance(id_list, list)
assert isinstance(index_list, list)
assert isinstance(sample_length_list, list)
assert len(id_list) == len(index_list)
self.query_id_list = id_list
self.sample_index_list = index_list
self.sample_length_list = sample_length_list
class Output(object):
def __init__(self, query_id_list, result):
self.query_id_list = query_id_list
self.result = result
class InQueue():
def __init__(self, in_queue, batch_size, data_set):
from preprocessing_utils import max_seq_length
self.in_queue = in_queue
self.batch_size = batch_size
self.query_id_list = []
self.sample_index_list = []
self.sample_length_list = []
self.index = 0
self.data_set = data_set
self.max_seq_len = max_seq_length
def put(self, query_samples):
global in_queue_cnt
##TODO, debug
idx = [q.index for q in query_samples]
query_id = [q.id for q in query_samples]
query_len = len(query_samples)
num_samples = len(query_samples)
def idx_len(e):
idx = e.index
feature = self.data_set.eval_features[idx]
_, inputs, _, _, _, _ = feature
return len(inputs)
if num_samples == 1:
if self.batch_size == 1:
in_queue_cnt += 1
self.in_queue.put(Input([query_samples[0].id],
[query_samples[0].index],
[idx_len(query_samples[0])]))
else:
self.index += 1
if self.index < self.batch_size:
self.query_id_list.append(query_samples[0].id)
self.sample_index_list.append(query_samples[0].index)
self.sample_length_list.append(idx_len(query_samples[0]))
else:
self.query_id_list.append(query_samples[0].id)
self.sample_index_list.append(query_samples[0].index)
self.sample_length_list.append(idx_len(query_samples[0]))
self.in_queue.put(Input(self.query_id_list, self.sample_index_list, self.sample_length_list))
in_queue_cnt += self.batch_size
self.index = 0
self.query_id_list = []
self.sample_index_list = []
self.sample_length_list = []
else:
query_samples.sort(key=idx_len, reverse=True)
def enqueue_batch(cur_batch_size, base_index=0):
global in_queue_cnt
id_list = []
index_list = []
length_list = []
for i in range(cur_batch_size):
id_list.append(query_samples[base_index + i].id)
index_list.append(query_samples[base_index + i].index)
length_list.append(idx_len(query_samples[base_index + i]))
self.in_queue.put(Input(id_list, index_list, length_list))
in_queue_cnt += cur_batch_size
global batching
true_total_len = 0
total_len = 0
for i in range(num_samples):
true_total_len += idx_len(query_samples[i])
if batching == 'Dynamic':
batch_seq_len = self.batch_size * self.max_seq_len
base_index = 0
num_batches = 0
while base_index < num_samples:
base_len = idx_len(query_samples[base_index])
for i in range(base_index, num_samples):
current_len = base_len * (i-base_index+1)
if i+1 < num_samples:
next_len = base_len * (i+1-base_index+1)
if next_len > batch_seq_len:
if next_len - batch_seq_len > batch_seq_len - current_len:
next_index = i+1
else:
next_index = i+2
break
else:
next_index = i+1
break
total_len += base_len * (next_index-base_index)
enqueue_batch(next_index-base_index, base_index)
num_batches += 1
#print('pid-{2}: enqueue bs={0} and input volume {1}...'
# .format(next_index-base_index, current_len, os.getpid()))
base_index = next_index
print('pid-{1}: enqueued {0} batches, pad ratio = {2}%'
.format(num_batches, os.getpid(), (total_len-true_total_len)*100/true_total_len))
elif batching == 'Adaptive':
batch_seq_len = self.batch_size * self.max_seq_len
base_index = 0
num_batches = 0
while base_index < num_samples:
base_len = idx_len(query_samples[base_index])
best_len, best_bs, _ = get_best_bs(base_len)
next_index = base_index + best_bs
if next_index > num_samples:
next_index = num_samples
total_len += base_len * (next_index-base_index)
enqueue_batch(next_index-base_index, base_index)
num_batches += 1
#print('pid-{2}: enqueue bs={0} and input volume {1}...'
# .format(next_index-base_index, current_len, os.getpid()))
base_index = next_index
print('pid-{1}: enqueued {0} batches, pad ratio = {2}%'
.format(num_batches, os.getpid(), (total_len-true_total_len)*100/true_total_len))
else:
num_batch = num_samples // self.batch_size
remaining_batch = num_samples % self.batch_size
## TODO, remove
print('pid-{3}: split the datasets into {0} batches with bs={1} and remaining {2}...'
.format(num_batch, self.batch_size, remaining_batch, os.getpid()))
for b in range(num_batch):
base_index = b * self.batch_size
enqueue_batch(self.batch_size, base_index)
if remaining_batch > 0:
base_index = num_batch * self.batch_size
enqueue_batch(remaining_batch, base_index)
#print ('in_queue_cnt=', in_queue_cnt)
class InQueueServer():
def __init__(self, in_queue, batch_sizes, data_set, expected_total_queries):
from preprocessing_utils import max_seq_length
self.in_queues = in_queue
self.batch_sizes = batch_sizes
self.query_id_lists = defaultdict(list)
self.sample_index_lists = defaultdict(list)
self.indexes = defaultdict(int)
self.sample_length_lists = defaultdict(list)
self.data_set = data_set
self.max_seq_len = max_seq_length
self.num_buckets = len(in_queue)
self.cutoffs = sorted(list(batch_sizes.keys()))
self.expected_total_queries = expected_total_queries
self.batch_sizes = defaultdict(int)
def getQueryBucket(self, query_len):
end = 0
while end < self.num_buckets and query_len > self.cutoffs[end]:
end += 1
return self.cutoffs[end]
def getQuerySampleLength(self, query ):
idx = query.index
return len( self.data_set.eval_features[idx][1] ) # input sequence is the 2nd attribute per ex.
def put(self, query_samples):
global in_queue_cnt
global queries_so_far # Track no. of queries received from loadgen
##TODO, debug
idx = [q.index for q in query_samples]
query_id = [q.id for q in query_samples]
query_len = len(query_samples)
num_samples = len(query_samples)
if num_samples == 1:
# Use length of the query sample to determine the queue it should be put
q_length = self.getQuerySampleLength( query_samples[0] )
bucket = self.getQueryBucket( q_length )
if self.batch_sizes[bucket] == 1:
in_queue_cnt += 1
self.in_queues[bucket].put(Input([query_samples[0].id], [query_samples[0].index], [q_len]))
else:
self.indexes[bucket] += 1
if self.indexes[bucket] < self.batch_sizes[bucket]:
self.query_id_lists[bucket].append(query_samples[0].id)
self.sample_index_lists[bucket].append(query_samples[0].index)
self.sample_length__lists[bucket].append(q_length)
else:
self.query_id_lists[bucket].append(query_samples[0].id)
self.sample_index_lists[bucket].append(query_samples[0].index)
self.sample_length_lists[bucket].append(q_length)
self.in_queues[bucket].put(Input(self.query_id_lists[bucket], self.sample_index_lists[bucket], self.sample_length_lists[bucket]))
in_queue_cnt += self.batch_sizes[bucket]
self.indexes[bucket] = 0
self.query_id_lists[bucket] = []
self.sample_index_lists[bucket] = []
self.sample_length_lists[bucket] = []
if queries_so_far == self.expected_total_queries:
for bucket in self.in_queues:
query_id_list = self.query_id_lists[bucket]
sample_index_list = self.sample_index_lists[bucket]
sample_length_list = self.sample_length_lists[bucket]
for j, q_id in enumerate(query_id_list):
s_idx = sample_index_list[j]
s_len = sample_length_list[j]
self.in_queues[bucket].put(Input([q_id], [s_idx], [s_len]))
in_queue_cnt += 1
def flush_queries():
pass
def process_latencies(latencies_ns):
# It's called by loadgen to show us the recorded latencies
log.info("Average latency (ms) per query:")
log.info(np.mean(latencies_ns)/1000000.0)
log.info("Median latency (ms): ")
log.info(np.percentile(latencies_ns, 50)/1000000.0)
log.info("90 percentile latency (ms): ")
log.info(np.percentile(latencies_ns, 90)/1000000.0)
def response_loadgen(out_queue):
global out_queue_cnt
while True:
next_task = out_queue.get()
if next_task is None:
# None means shutdown
log.info('Exiting response thread')
break
query_id_list = next_task.query_id_list
result = next_task.result
batch_size = len(query_id_list)
result.reshape(batch_size, -1, 2)
out_list = np.split(result, batch_size, axis=0)
#responses = []
for i, o in enumerate(out_list):
response_array = array.array("B", np.array(o).astype(np.float32).tobytes())
bi = response_array.buffer_info()
#responses.append(lg.QuerySampleResponse(query_id_list[i], bi[0], bi[1]))
responses = [lg.QuerySampleResponse(query_id_list[i], bi[0], bi[1])]
out_queue_cnt += 1
#print('Response loadgen ({}), query_id {}, out_queue_cnt {}'.format(os.getpid(), query_id_list[i], out_queue_cnt))
lg.QuerySamplesComplete(responses)
#lg.QuerySamplesComplete(responses)
class BERTModel():
def __init__(self, ctx, mx_vocab, params, quantized, quantized_model_prefix):
import gluonnlp as nlp
from utils import BertForQA
import mxnet as mx
if quantized:
log.info('Loading quantized MXNet model...')
self.net = mx.gluon.SymbolBlock.imports('{}-symbol.json'.format(quantized_model_prefix),
['data0', 'data1', 'data2'],
'{}-0000.params'.format(quantized_model_prefix))
self.net.hybridize(static_alloc=True, static_shape=True)
else:
log.info('Loading MXNet model...')
with open(mx_vocab, 'r') as f:
vocab = nlp.vocab.BERTVocab.from_json(f.read())
bert, vocab = nlp.model.get_model(
name='bert_24_1024_16',
dataset_name=None,
vocab=vocab,
pretrained=False,
ctx=ctx,
use_pooler=False,
use_decoder=False,
use_classifier=False)
self.net = BertForQA(bert=bert)
nlp.utils.load_parameters(self.net, params, ctx=ctx, cast_dtype=True)
self.net.hybridize(static_alloc=True)
class BERTDataSet():
def __init__(self, mx_vocab, perf_count):
import gluonnlp as nlp
from preprocessing_utils import preprocess_dataset, max_seq_length, max_query_length, doc_stride
from gluonnlp.data import SQuAD
eval_features = []
with open(mx_vocab, 'r') as f:
vocab = nlp.vocab.BERTVocab.from_json(f.read())
log.info("Creating tokenizer...")
tokenizer = nlp.data.BERTTokenizer(vocab=vocab, lower=True)
round_to = None
log.info("Reading examples...")
dev_path = os.path.join(os.getcwd(), 'build/data')
dev_data = SQuAD('dev', version='1.1', root=dev_path)
dev_data_transform = preprocess_dataset(tokenizer,
dev_data,
max_seq_length=max_seq_length,
doc_stride=doc_stride,
max_query_length=max_query_length,
input_features=True)
self.eval_features = dev_data_transform
self.count = len(self.eval_features)
self.perf_count = perf_count if perf_count is not None else self.count
class MultiprocessShapeBasedQueue(object):
def __init__(self):
global num_ins
self._jq = multiprocessing.JoinableQueue()
self._instances_queue = [multiprocessing.Queue() for _ in range(num_ins)]
self._manager = multiprocessing.Manager()
self.shape_in_instance = self._manager.dict()
self.finish_status = self._manager.dict()
def get(self, instance_id=0):
return self._jq.get()
# with multiprocessing.Lock():
# if self._instances_queue[instance_id].empty():
# while True:
# item = self._jq.get()
# if item != None:
# sample_length = item.sample_length_list[0]
# batch_size = len(item.sample_index_list)
# key = (batch_size, sample_length)
# if key in self.shape_in_instance.keys():
# if self.shape_in_instance[key] == instance_id:
# return item
# else:
# target_instance = self.shape_in_instance[key]
# if target_instance in self.finish_status.keys():
# # target instance already finished execution - get item
# del shape_in_instance[key]
# return item
# else:
# self._instances_queue[target_instance].put(item)
# # reapeat while loop - get new item and check if it's suitable for instance
# else:
# # mark shape with current instance
# self.shape_in_instance[key] = instance_id
# return item
# else:
# self.finish_status[instance_id] = True
# return item # return None
# else:
# item = self._instances_queue[instance_id].get()
# return item
def put(self, obj, block=True, timeout=None):
return self._jq.put(obj, block, timeout)
##print("end put")
def task_done(self):
#print("task_done")
return self._jq.task_done()
#print("end task_done")
def join(self):
#print("join")
return self._jq.join()
#print("end join")
def main():
global num_ins
global num_cpus
global in_queue_cnt
global out_queue_cnt
global batching
global queries_so_far
global Latencies
queries_so_far = 0
args = get_args()
log.info(args)
scenario = args.scenario
accuracy_mode = args.accuracy
perf_count = args.perf_count
batch_size = args.batch_size
num_ins = args.num_instance
num_cpus = args.num_phy_cpus
batching = args.batching
# Read Loadgen and workload config parameters
settings = lg.TestSettings()
settings.scenario = scenario_map[scenario]
settings.FromConfig(args.mlperf_conf, "bert", scenario)
settings.FromConfig(args.user_conf, "bert", scenario)
settings.mode = lg.TestMode.AccuracyOnly if accuracy_mode else lg.TestMode.PerformanceOnly
# Establish communication queues
lock = multiprocessing.Lock()
init_counter = multiprocessing.Value("i", 0)
calibrate_counter = multiprocessing.Value("i", 0)
out_queue = multiprocessing.Queue()
# Create consumers
consumers = []
if scenario == "Server":
from parse_server_config import configParser
buckets = configParser( "machine_conf.json")
cutoffs = list(buckets.keys())
batch_sizes = {}
in_queue = {j: multiprocessing.JoinableQueue() for j in buckets}
proc_idx = 0
num_cpus = 0
total_ins = 0
for cutoff in list(buckets.keys()):
batch_sizes[ cutoff ] = buckets[ cutoff ]["batch_size"]
num_ins = buckets[ cutoff ]["instances"]
cpus_per_instance = buckets[ cutoff ]["cpus_per_instance"]
num_cpus = num_ins * cpus_per_instance
total_ins += num_ins
for j in range(num_ins):
consumer = Consumer( in_queue[ cutoff ], out_queue, lock, init_counter, calibrate_counter, proc_idx, num_ins, args, cutoff)
consumer.start_core_idx = proc_idx
consumer.end_core_idx = proc_idx + cpus_per_instance - 1
consumers.append(consumer)
proc_idx = consumer.end_core_idx + 1
num_ins = total_ins
else:
total_ins = num_ins
in_queue = MultiprocessShapeBasedQueue()
consumers = [Consumer(in_queue, out_queue, lock, init_counter, calibrate_counter, i, num_ins, args)
for i in range(num_ins)]
for c in consumers:
c.start()
# Dataset object used by constructQSL
data_set = BERTDataSet(args.vocab, args.perf_count)
if scenario=="Server":
issue_queue = InQueueServer(in_queue, batch_sizes, data_set, settings.min_query_count)
else:
issue_queue = InQueue(in_queue, batch_size, data_set)
# Wait until all sub-processors are ready
block_until(init_counter, total_ins, 2)
# Start response thread
response_worker = threading.Thread(
target=response_loadgen, args=(out_queue,))
response_worker.daemon = True
response_worker.start()
def issue_queries(query_samples):
# It's called by loadgen to send query to SUT
issue_queue.put(query_samples)
sut = lg.ConstructSUT(
issue_queries, flush_queries, process_latencies)
qsl = lg.ConstructQSL(
data_set.count, data_set.perf_count, load_query_samples, unload_query_samples)
log_path = "build/logs"
if not os.path.exists(log_path):
os.makedirs(log_path)
log_output_settings = lg.LogOutputSettings()
log_output_settings.outdir = log_path
log_output_settings.copy_summary_to_stdout = True
log_settings = lg.LogSettings()
log_settings.log_output = log_output_settings
lg.StartTestWithLogSettings(sut, qsl, settings, log_settings)
# Wait until outQueue done
while out_queue_cnt < in_queue_cnt:
time.sleep(0.2)
if scenario == "Server":
for i in in_queue:
in_queue[i].join()
for j in range(buckets[ i ]["cpus_per_instance"]):
in_queue[i].put(None)
else:
for i in range(num_ins):
in_queue.put(None)
for c in consumers:
c.join()
out_queue.put(None)
if accuracy_mode:
cmd = "python accuracy-squad.py --log_file={}/mlperf_log_accuracy.json".format(log_path)
subprocess.check_call(cmd, shell=True)
lg.DestroyQSL(qsl)
lg.DestroySUT(sut)
if __name__ == '__main__':
main()
| 2.453125 | 2 |
scripts/eval_bop19.py | MartinSmeyer/bop_toolkit | 0 | 12767333 | # Author: <NAME> (<EMAIL>)
# Center for Machine Perception, Czech Technical University in Prague
"""Evaluation script for the BOP Challenge 2019."""
import os
import time
import argparse
import subprocess
import numpy as np
from bop_toolkit_lib import config
from bop_toolkit_lib import inout
from bop_toolkit_lib import misc
# PARAMETERS (some can be overwritten by the command line arguments below).
################################################################################
p = {
# Errors to calculate.
'errors': [
{
'n_top': -1,
'type': 'vsd',
'vsd_deltas': {
'hb': 15,
'icbin': 15,
'icmi': 15,
'itodd': 5,
'lm': 15,
'lmo': 15,
'ruapc': 15,
'tless': 15,
'tudl': 15,
'tyol': 15,
},
'vsd_taus': list(np.arange(0.05, 0.51, 0.05)),
'correct_th': [[th] for th in np.arange(0.05, 0.51, 0.05)]
},
{
'n_top': -1,
'type': 'mssd',
'correct_th': [[th] for th in np.arange(0.05, 0.51, 0.05)]
},
{
'n_top': -1,
'type': 'mspd',
'correct_th': [[th] for th in np.arange(5, 51, 5)]
},
],
# Minimum visible surface fraction of a valid GT pose.
'visib_gt_min': 0.1,
# See misc.get_symmetry_transformations().
'max_sym_disc_step': 0.01,
# Type of the renderer (used for the VSD pose error function).
'renderer_type': 'python', # Options: 'cpp', 'python'.
# Names of files with results for which to calculate the errors (assumed to be
# stored in folder config.eval_path). See docs/bop_challenge_2019.md for a
# description of the format. Example results can be found at:
# http://ptak.felk.cvut.cz/6DB/public/bop_sample_results/bop_challenge_2019/
'result_filenames': [
'/home_local/sund_ma/src/foreign_packages/bop/bop_results/bop_challenge_2019/hodan-iros15_lm-test.csv',
],
# File with a list of estimation targets to consider. The file is assumed to
# be stored in the dataset folder.
'targets_filename': 'test_targets_bop19.json',
}
################################################################################
# Command line arguments.
# ------------------------------------------------------------------------------
parser = argparse.ArgumentParser()
parser.add_argument('--visib_gt_min', default=p['visib_gt_min'])
parser.add_argument('--max_sym_disc_step', default=p['max_sym_disc_step'])
parser.add_argument('--renderer_type', default=p['renderer_type'])
parser.add_argument('--result_filenames',
default=','.join(p['result_filenames']),
help='Comma-separated names of files with results.')
parser.add_argument('--targets_filename', default=p['targets_filename'])
args = parser.parse_args()
p['visib_gt_min'] = float(args.visib_gt_min)
p['max_sym_disc_step'] = float(args.max_sym_disc_step)
p['renderer_type'] = str(args.renderer_type)
p['result_filenames'] = args.result_filenames.split(',')
p['targets_filename'] = str(args.targets_filename)
# Evaluation.
# ------------------------------------------------------------------------------
for result_filename in p['result_filenames']:
misc.log('===========')
misc.log('EVALUATING: {}'.format(result_filename))
misc.log('===========')
time_start = time.time()
aur = {}
for error in p['errors']:
# Calculate error of the pose estimates.
calc_errors_cmd = [
'python',
os.path.join('scripts', 'eval_calc_errors.py'),
'--n_top={}'.format(error['n_top']),
'--error_type={}'.format(error['type']),
'--result_filenames={}'.format(result_filename),
'--renderer_type={}'.format(p['renderer_type']),
'--targets_filename={}'.format(p['targets_filename']),
'--max_sym_disc_step={}'.format(p['max_sym_disc_step']),
'--skip_missing=1',
]
if error['type'] == 'vsd':
vsd_deltas_str = \
','.join(['{}:{}'.format(k, v) for k, v in error['vsd_deltas'].items()])
calc_errors_cmd += [
'--vsd_deltas={}'.format(vsd_deltas_str),
'--vsd_taus={}'.format(','.join(map(str, error['vsd_taus'])))
]
misc.log('Running: ' + ' '.join(calc_errors_cmd))
if subprocess.call(calc_errors_cmd) != 0:
raise RuntimeError('Calculation of VSD failed.')
# Name of the result and the dataset.
result_name = os.path.splitext(os.path.basename(result_filename))[0]
dataset = str(result_name.split('_')[1].split('-')[0])
# Paths (rel. to config.eval_path) to folders with calculated pose errors.
# For VSD, there is one path for each setting of tau. For the other pose
# error functions, there is only one path.
error_dir_paths = {}
if error['type'] == 'vsd':
for vsd_tau in error['vsd_taus']:
error_sign = misc.get_error_signature(
error['type'], error['n_top'], vsd_delta=error['vsd_deltas'][dataset],
vsd_tau=vsd_tau)
error_dir_paths[error_sign] = os.path.join(result_name, error_sign)
else:
error_sign = misc.get_error_signature(error['type'], error['n_top'])
error_dir_paths[error_sign] = os.path.join(result_name, error_sign)
# Recall scores for all settings of the threshold of correctness (and also
# of the misalignment tolerance tau in the case of VSD).
recalls = []
# Calculate performance scores.
for error_sign, error_dir_path in error_dir_paths.items():
for correct_th in error['correct_th']:
calc_scores_cmd = [
'python',
os.path.join('scripts', 'eval_calc_scores.py'),
'--error_dir_paths={}'.format(error_dir_path),
'--targets_filename={}'.format(p['targets_filename']),
'--visib_gt_min={}'.format(p['visib_gt_min'])
]
calc_scores_cmd += ['--correct_th_{}={}'.format(
error['type'], ','.join(map(str, correct_th)))]
misc.log('Running: ' + ' '.join(calc_scores_cmd))
if subprocess.call(calc_scores_cmd) != 0:
raise RuntimeError('Calculation of scores failed.')
# Path to file with calculated scores.
score_sign = misc.get_score_signature(correct_th, p['visib_gt_min'])
scores_filename = 'scores_{}.json'.format(score_sign)
scores_path = os.path.join(
config.eval_path, result_name, error_sign, scores_filename)
# Load the scores.
misc.log('Loading calculated scores from: {}'.format(scores_path))
scores = inout.load_json(scores_path)
recalls.append(scores['total_recall'])
# Area under precision recall:
aur[error['type']] = np.mean(recalls)
misc.log('Recall scores: {}'.format(' '.join(map(str, recalls))))
time_total = time.time() - time_start
misc.log('Evaluation of {} took {}s.'.format(result_filename, time_total))
# output final scores
err_types = [e['type'] for e in p['errors']]
for err_type in err_types:
misc.log('#### {} #### area under recall surface: {}'.format(err_type,
aur[err_type]))
if set(['vsd', 'mssd', 'mspd']).issubset(err_types):
test_set = os.path.basename(result_filename)
mean_error = np.mean([aur[err_type] for err_type in err_types])
misc.log('Average BOP score on {}: {}'.format(test_set, mean_error))
misc.log('Done.')
| 2.125 | 2 |
python_scripts/datasets_bike_rides.py | aquinquenel/scikit-learn-mooc | 1 | 12767334 | # ---
# jupyter:
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# %% [markdown]
# # The bike rides dataset
#
# In this notebook, we will present the "Bike Ride" dataset. This dataset is
# located in the directory `datasets` in a comma separated values (CSV) format.
#
# We open this dataset using pandas.
# %%
import pandas as pd
cycling = pd.read_csv("../datasets/bike_rides.csv")
cycling.head()
# %% [markdown]
# The first column `timestamp` contains a specific information regarding the
# the time and date of a record while other columns contain numerical value
# of some specific measurements. Let's check the data type of the columns more
# in details.
# %%
cycling.info()
# %% [markdown]
# Indeed, CSV format store data as text. Pandas tries to infer numerical type
# by default. It is the reason why all features but `timestamp` are encoded as
# floating point values. However, we see that the `timestamp` is stored as an
# `object` column. It means that the data in this column are stored as `str`
# rather than a specialized `datetime` data type.
#
# In fact, one needs to set an option such that pandas is directed to infer
# such data type when opening the file. In addition, we will want to use
# `timestamp` as an index. Thus, we can reopen the file with some extra
# arguments to help pandas at reading properly our CSV file.
# %%
cycling = pd.read_csv("../datasets/bike_rides.csv", index_col=0,
parse_dates=True)
cycling.index.name = ""
cycling.head()
# %%
cycling.info()
# %% [markdown]
# By specifying to pandas to parse the date, we obtain a `DatetimeIndex` that
# is really handy when filtering data based on date.
#
# We can now have a look at the data stored in our dataframe. It will help us
# to frame the data science problem that we try to solve.
#
# The records correspond at information derived from GPS recordings of a
# cyclist (`speed`, `acceleration`, `slope`) and some extra information
# acquired from other sensors: `heart-rate` that corresponds to the number of
# beats per minute of the cyclist heart, `cadence` that is the rate at which a
# cyclist is turning the pedals, and `power` that corresponds to the work
# required by the cyclist to go forward.
#
# The power might be slightly an abstract quantity so let's give a more
# intuitive explanation.
#
# Let's take the example of a soup blender that one uses to blend vegetable.
# The engine of this blender develop an instantaneous power of ~300 Watts to
# blend the vegetable. Here, our cyclist is just the engine of the blender (at
# the difference that an average cyclist will develop an instantaneous power
# around ~150 Watts) and blending the vegetable corresponds to move the
# cyclist's bike forward.
#
# Professional cyclists are using power to calibrate their training and track
# the energy spent during a ride. For instance, riding at a higher power
# requires more energy and thus, you need to provide resources to create this
# energy. With human, this resource is food. For our soup blender, this
# resource can be uranium, petrol, natural gas, coal, etc. Our body serves as a
# power plant to transform the resources into energy.
#
# The issue with measuring power is linked to the cost of the sensor: a cycling
# power meter. The cost of such sensor vary from $400 to $1000. Thus, our
# data science problem is quite easy: can we predict instantaneous cyclist
# power from other (cheaper) sensors.
# %%
target_name = "power"
data, target = cycling.drop(columns=target_name), cycling[target_name]
# %% [markdown]
# We can have a first look at the target distribution.
# %%
import matplotlib.pyplot as plt
target.plot.hist(bins=50, edgecolor="black")
plt.xlabel("Power (W)")
# %% [markdown]
# We see a pick at 0 Watts, it corresponds to whenever our cyclist does not
# pedals (descent, stopped). In average, this cyclist delivers a power around
# ~200 Watts. We also see a long tail from ~300 Watts to ~400 Watts. You can
# think that this range of data correspond to effort a cyclist will train to
# reproduce to be able to breakout in the final kilometers of a cycling race.
# However, this is costly for the human body and no one can cruise with this
# power output.
#
# Now, let's have a look at the data.
# %%
data.head()
# %% [markdown]
# We can first have a closer look to the index of the dataframe.
# %%
data.index
# %% [markdown]
# We see that records are acquired every seconds.
# %%
data.index.min(), data.index.max()
# %% [markdown]
# The starting date is the August 18, 2020 and the ending date is
# September 13, 2020. However, it is obvious that our cyclist did not ride
# every seconds between these dates. Indeed, only a couple of date should be
# present in the dataframe, corresponding to the number of cycling rides.
# %%
data.index.normalize().nunique()
# %% [markdown]
# Indeed, we have only four different dates corresponding to four rides. Let's
# extract only the first ride of August 18, 2020.
# %%
date_first_ride = "2020-08-18"
cycling_ride = cycling.loc[date_first_ride]
data_ride, target_ride = data.loc[date_first_ride], target.loc[date_first_ride]
# %%
data_ride.plot()
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
_ = plt.title("Sensor values for different cyclist measurements")
# %% [markdown]
# Since the unit and range of each measurement (feature) is different, it is
# rather difficult to interpret the plot. Also, the high temporal resolution
# make it difficult to make any observation. We could resample the data to get
# a smoother visualization.
# %%
data_ride.resample("60S").mean().plot()
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
_ = plt.title("Sensor values for different cyclist measurements")
# %% [markdown]
# We can check the range of the different features:
# %%
axs = data_ride.hist(figsize=(10, 12), bins=50, edgecolor="black", grid=False)
# add the units to the plots
units = ["beats per minute", "rotations per minute", "meters per second",
"meters per second squared", "%"]
for unit, ax in zip(units, axs.ravel()):
ax.set_xlabel(unit)
plt.subplots_adjust(hspace=0.6)
# %% [markdown]
# From these plots, we can see some interesting information: a cyclist is
# spending some time without pedaling. This samples should be associated with
# a null power. We also see that the slope have large extremum.
#
# Let's make a pair plot on a subset of data samples to see if we can confirm
# some of these intuitions.
# %%
import numpy as np
rng = np.random.RandomState(0)
indices = rng.choice(np.arange(cycling_ride.shape[0]), size=500, replace=False)
# %%
subset = cycling_ride.iloc[indices].copy()
# Quantize the target and keep the midpoint for each interval
subset["power"] = pd.qcut(subset["power"], 6, retbins=False)
subset["power"] = subset["power"].apply(lambda x: x.mid)
# %%
import seaborn as sns
_ = sns.pairplot(data=subset, hue="power", palette="viridis")
# %% [markdown]
# Indeed, we see that low cadence is associated with low power. We can also
# the a link between higher slope / high heart-rate and higher power: a cyclist
# need to develop more energy to go uphill enforcing a stronger physiological
# stimuli on the body. We can confirm this intuition by looking at the
# interaction between the slope and the speed: a lower speed with a higher
# slope is usually associated with higher power.
| 3.921875 | 4 |
nlp/tests/test_marshal.py | mobarski/sandbox | 0 | 12767335 | <filename>nlp/tests/test_marshal.py<gh_stars>0
import marshal
import numpy as np
a = np.array([[1,2],[3,4]],dtype=np.uint8)
m = marshal.dumps(a)
print(len(m))
| 2.28125 | 2 |
src/post/migrations/0003_auto_20161113_1742.py | pandeydivesh15/item_sharing_portal | 1 | 12767336 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-11-13 17:42
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('post', '0002_post_is_share_post'),
]
operations = [
migrations.RemoveField(
model_name='post',
name='is_share_post',
),
migrations.AddField(
model_name='post',
name='reason_share',
field=models.CharField(default='share', max_length=10),
preserve_default=False,
),
]
| 1.570313 | 2 |
gunpowder/nodes/defect_augment.py | trivoldus28/gunpowder | 43 | 12767337 | import logging
import random
import numpy as np
# imports for deformed slice
from skimage.draw import line
from scipy.ndimage.measurements import label
from scipy.ndimage.interpolation import map_coordinates
from scipy.ndimage.morphology import binary_dilation
from gunpowder.batch_request import BatchRequest
from gunpowder.coordinate import Coordinate
from .batch_filter import BatchFilter
logger = logging.getLogger(__name__)
class DefectAugment(BatchFilter):
'''Augment intensity arrays section-wise with artifacts like missing
sections, low-contrast sections, by blending in artifacts drawn from a
separate source, or by deforming a section.
Args:
intensities (:class:`ArrayKey`):
The key of the array of intensities to modify.
prob_missing(``float``):
prob_low_contrast(``float``):
prob_artifact(``float``):
prob_deform(``float``):
Probabilities of having a missing section, low-contrast section, an
artifact (see param ``artifact_source``) or a deformed slice. The
sum should not exceed 1. Values in missing sections will be set to
0.
contrast_scale (``float``, optional):
By how much to scale the intensities for a low-contrast section,
used if ``prob_low_contrast`` > 0.
artifact_source (class:`BatchProvider`, optional):
A gunpowder batch provider that delivers intensities (via
:class:`ArrayKey` ``artifacts``) and an alpha mask (via
:class:`ArrayKey` ``artifacts_mask``), used if ``prob_artifact`` > 0.
artifacts(:class:`ArrayKey`, optional):
The key to query ``artifact_source`` for to get the intensities
of the artifacts.
artifacts_mask(:class:`ArrayKey`, optional):
The key to query ``artifact_source`` for to get the alpha mask
of the artifacts to blend them with ``intensities``.
deformation_strength (``int``, optional):
Strength of the slice deformation in voxels, used if
``prob_deform`` > 0. The deformation models a fold by shifting the
section contents towards a randomly oriented line in the section.
The line itself will be drawn with a value of 0.
axis (``int``, optional):
Along which axis sections are cut.
'''
def __init__(
self,
intensities,
prob_missing=0.05,
prob_low_contrast=0.05,
prob_artifact=0.0,
prob_deform=0.0,
contrast_scale=0.1,
artifact_source=None,
artifacts=None,
artifacts_mask=None,
deformation_strength=20,
axis=0):
self.intensities = intensities
self.prob_missing = prob_missing
self.prob_low_contrast = prob_low_contrast
self.prob_artifact = prob_artifact
self.prob_deform = prob_deform
self.contrast_scale = contrast_scale
self.artifact_source = artifact_source
self.artifacts = artifacts
self.artifacts_mask = artifacts_mask
self.deformation_strength = deformation_strength
self.axis = axis
def setup(self):
if self.artifact_source is not None:
self.artifact_source.setup()
def teardown(self):
if self.artifact_source is not None:
self.artifact_source.teardown()
# send roi request to data-source upstream
def prepare(self, request):
random.seed(request.random_seed)
deps = BatchRequest()
# we prepare the augmentations, by determining which slices
# will be augmented by which method
# If one of the slices is augmented with 'deform',
# we prepare these trafos already
# and request a bigger roi from upstream
prob_missing_threshold = self.prob_missing
prob_low_contrast_threshold = prob_missing_threshold + self.prob_low_contrast
prob_artifact_threshold = prob_low_contrast_threshold + self.prob_artifact
prob_deform_slice = prob_artifact_threshold + self.prob_deform
spec = request[self.intensities].copy()
roi = spec.roi
logger.debug("downstream request ROI is %s" % roi)
raw_voxel_size = self.spec[self.intensities].voxel_size
# store the mapping slice to augmentation type in a dict
self.slice_to_augmentation = {}
# store the transformations for deform slice
self.deform_slice_transformations = {}
for c in range((roi / raw_voxel_size).get_shape()[self.axis]):
r = random.random()
if r < prob_missing_threshold:
logger.debug("Zero-out " + str(c))
self.slice_to_augmentation[c] = 'zero_out'
elif r < prob_low_contrast_threshold:
logger.debug("Lower contrast " + str(c))
self.slice_to_augmentation[c] = 'lower_contrast'
elif r < prob_artifact_threshold:
logger.debug("Add artifact " + str(c))
self.slice_to_augmentation[c] = 'artifact'
elif r < prob_deform_slice:
logger.debug("Add deformed slice " + str(c))
self.slice_to_augmentation[c] = 'deformed_slice'
# get the shape of a single slice
slice_shape = (roi / raw_voxel_size).get_shape()
slice_shape = slice_shape[:self.axis] + slice_shape[self.axis+1:]
self.deform_slice_transformations[c] = self.__prepare_deform_slice(slice_shape)
# prepare transformation and
# request bigger upstream roi for deformed slice
if 'deformed_slice' in self.slice_to_augmentation.values():
# create roi sufficiently large to feed deformation
logger.debug("before growth: %s" % spec.roi)
growth = Coordinate(
tuple(0 if d == self.axis else raw_voxel_size[d] * self.deformation_strength
for d in range(spec.roi.dims()))
)
logger.debug("growing request by %s" % str(growth))
source_roi = roi.grow(growth, growth)
# update request ROI to get all voxels necessary to perfrom
# transformation
spec.roi = source_roi
logger.debug("upstream request roi is %s" % spec.roi)
deps[self.intensities] = spec
def process(self, batch, request):
assert batch.get_total_roi().dims() == 3, "defectaugment works on 3d batches only"
raw = batch.arrays[self.intensities]
raw_voxel_size = self.spec[self.intensities].voxel_size
for c, augmentation_type in self.slice_to_augmentation.items():
section_selector = tuple(
slice(None if d != self.axis else c, None if d != self.axis else c+1)
for d in range(raw.spec.roi.dims())
)
if augmentation_type == 'zero_out':
raw.data[section_selector] = 0
elif augmentation_type == 'low_contrast':
section = raw.data[section_selector]
mean = section.mean()
section -= mean
section *= self.contrast_scale
section += mean
raw.data[section_selector] = section
elif augmentation_type == 'artifact':
section = raw.data[section_selector]
alpha_voxel_size = self.artifact_source.spec[self.artifacts_mask].voxel_size
assert raw_voxel_size == alpha_voxel_size, ("Can only alpha blend RAW with "
"ALPHA_MASK if both have the same "
"voxel size")
artifact_request = BatchRequest()
artifact_request.add(self.artifacts, Coordinate(section.shape) * raw_voxel_size, voxel_size=raw_voxel_size)
artifact_request.add(self.artifacts_mask, Coordinate(section.shape) * alpha_voxel_size, voxel_size=raw_voxel_size)
logger.debug("Requesting artifact batch %s", artifact_request)
artifact_batch = self.artifact_source.request_batch(artifact_request)
artifact_alpha = artifact_batch.arrays[self.artifacts_mask].data
artifact_raw = artifact_batch.arrays[self.artifacts].data
assert artifact_alpha.dtype == np.float32
assert artifact_alpha.min() >= 0.0
assert artifact_alpha.max() <= 1.0
raw.data[section_selector] = section*(1.0 - artifact_alpha) + artifact_raw*artifact_alpha
elif augmentation_type == 'deformed_slice':
section = raw.data[section_selector].squeeze()
# set interpolation to cubic, spec interploatable is true, else to 0
interpolation = 3 if self.spec[self.intensities].interpolatable else 0
# load the deformation fields that were prepared for this slice
flow_x, flow_y, line_mask = self.deform_slice_transformations[c]
# apply the deformation fields
shape = section.shape
section = map_coordinates(
section, (flow_y, flow_x), mode='constant', order=interpolation
).reshape(shape)
# things can get smaller than 0 at the boundary, so we clip
section = np.clip(section, 0., 1.)
# zero-out data below the line mask
section[line_mask] = 0.
raw.data[section_selector] = section
# in case we needed to change the ROI due to a deformation augment,
# restore original ROI and crop the array data
if 'deformed_slice' in self.slice_to_augmentation.values():
old_roi = request[self.intensities].roi
logger.debug("resetting roi to %s" % old_roi)
crop = tuple(
slice(None) if d == self.axis else slice(self.deformation_strength, -self.deformation_strength)
for d in range(raw.spec.roi.dims())
)
raw.data = raw.data[crop]
raw.spec.roi = old_roi
def __prepare_deform_slice(self, slice_shape):
# grow slice shape by 2 x deformation strength
grow_by = 2 * self.deformation_strength
shape = (slice_shape[0] + grow_by, slice_shape[1] + grow_by)
# randomly choose fixed x or fixed y with p = 1/2
fixed_x = random.random() < .5
if fixed_x:
x0, y0 = 0, np.random.randint(1, shape[1] - 2)
x1, y1 = shape[0] - 1, np.random.randint(1, shape[1] - 2)
else:
x0, y0 = np.random.randint(1, shape[0] - 2), 0
x1, y1 = np.random.randint(1, shape[0] - 2), shape[1] - 1
## generate the mask of the line that should be blacked out
line_mask = np.zeros(shape, dtype='bool')
rr, cc = line(x0, y0, x1, y1)
line_mask[rr, cc] = 1
# generate vectorfield pointing towards the line to compress the image
# first we get the unit vector representing the line
line_vector = np.array([x1 - x0, y1 - y0], dtype='float32')
line_vector /= np.linalg.norm(line_vector)
# next, we generate the normal to the line
normal_vector = np.zeros_like(line_vector)
normal_vector[0] = - line_vector[1]
normal_vector[1] = line_vector[0]
# make meshgrid
x, y = np.meshgrid(np.arange(shape[1]), np.arange(shape[0]))
# generate the vector field
flow_x, flow_y = np.zeros(shape), np.zeros(shape)
# find the 2 components where coordinates are bigger / smaller than the line
# to apply normal vector in the correct direction
components, n_components = label(np.logical_not(line_mask).view('uint8'))
assert n_components == 2, "%i" % n_components
neg_val = components[0, 0] if fixed_x else components[-1, -1]
pos_val = components[-1, -1] if fixed_x else components[0, 0]
flow_x[components == pos_val] = self.deformation_strength * normal_vector[1]
flow_y[components == pos_val] = self.deformation_strength * normal_vector[0]
flow_x[components == neg_val] = - self.deformation_strength * normal_vector[1]
flow_y[components == neg_val] = - self.deformation_strength * normal_vector[0]
# generate the flow fields
flow_x, flow_y = (x + flow_x).reshape(-1, 1), (y + flow_y).reshape(-1, 1)
# dilate the line mask
line_mask = binary_dilation(line_mask, iterations=10)
return flow_x, flow_y, line_mask
| 2.09375 | 2 |
municipios/views.py | coletivoEITA/django-municipios | 0 | 12767338 | # -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import render
from django.apps import apps
from municipios.forms import FormMunicipio
def base_url_js(request):
return HttpResponse(u"var __municipios_base_url__ = '%s';" % reverse('municipios-base-url'))
def municipios_ajax(request, uf, app_label, object_name):
model_cls = apps.get_model(app_label, object_name)
municipio_list = model_cls.objects.filter(Q(uf=uf)).order_by('nome')
return render(
request,
"municipios/municipios_options.html",
{"municipio_list": municipio_list},
)
def teste(request):
form = FormMunicipio(request.GET or None)
return render(
request,
'municipios/teste.html',
{'form': form},
)
| 1.960938 | 2 |
myproject/cms/migrations/0002_auto_20180412_1141.py | RazvanCopaceanu/X-Serv-15.8-CmsUsersPut | 0 | 12767339 | <reponame>RazvanCopaceanu/X-Serv-15.8-CmsUsersPut<filename>myproject/cms/migrations/0002_auto_20180412_1141.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cms', '0001_initial'),
]
operations = [
migrations.RenameModel(
old_name='Pages',
new_name='Persona',
),
migrations.RenameField(
model_name='persona',
old_name='pagina',
new_name='descripcion',
),
]
| 1.4375 | 1 |
src/ramachandran.py | h3nnn4n/Ramachandran-Angle-Probability.py | 0 | 12767340 | <filename>src/ramachandran.py
import re
import os.path
import math
import random
import numpy as np
import os
class Ramachandran():
def __init__(self):
self.data = {}
self.parsed_data = {}
self.aa = {}
self.aa['g'] = 'gly'
self.aa['a'] = 'ala'
self.aa['p'] = 'pro'
self.aa['s'] = 'ser'
self.aa['c'] = 'cys'
self.aa['t'] = "thr"
self.aa['v'] = 'val'
self.aa['i'] = 'ile'
self.aa['l'] = 'leu'
self.aa['d'] = 'asp'
self.aa['n'] = 'asn'
self.aa['f'] = 'phe'
self.aa['y'] = 'tyr'
self.aa['h'] = 'his'
self.aa['w'] = 'trp'
self.aa['m'] = 'met'
self.aa['e'] = 'glu'
self.aa['q'] = 'gln'
self.aa['k'] = 'lys'
self.aa['r'] = 'arg'
def load(self, path=""):
if os.path.isfile(path):
with open(path) as f:
for line in f.readlines():
line = line.rstrip('\r\n')
tokens = re.sub("\s+", " ", line).split(' ')
if tokens[0][0] != "#":
name, phi, psi, prob, _ = tokens
phi = round(float((phi)))
psi = round(float((psi)))
prob = float(prob)
if name not in self.data:
a = {}
a[(phi, psi)] = prob
self.data[name] = a
else:
self.data[name][(phi, psi)] = prob
else:
if path == "":
raise Exception("path is empty, please use keyword path to point to the file")
else:
raise Exception("Could not find: %s" % path)
def process(self):
f = None
size = None
dx = None
for k, v in self.data.items():
if f is None:
f = len(v)
else:
if len(v) != f:
raise Exception("Uneven number of information")
if round(math.sqrt(f)) == math.sqrt(f):
size = round(math.sqrt(f))
dx = (360) / size
else:
raise Exception("Unable to determine grid size")
for k, v in self.data.items():
self.parsed_data[k] = np.zeros((size, size))
for a, b in self.data[k].items():
phi, psi = a
x = round((phi + 180) / dx)
y = round((psi + 180) / dx)
self.parsed_data[k][x, y] = self.data[k][a]
self.size = size
self.dx = dx
def index(self, name, phi, psi):
x = round((phi + 180) / self.dx)
y = round((psi + 180) / self.dx)
return self.parsed_data[name][x, y]
def gnuprint(self, name, path=None):
if path is None:
for phi in range(-180, 180, 10):
for psi in range(-180, 180, 10):
print("%4d %4d %.4f" % (phi, psi, self.index(name, phi, psi)))
print()
else:
with open(path, "w") as f:
for phi in range(-180, 180, 10):
for psi in range(-180, 180, 10):
f.write("%4d %4d %.4f\n" % (phi, psi, self.index(name, phi, psi)))
f.write("\n")
def get_random_angle(self, name):
if len(name) != 3:
name = self.convert(name)
r = random.random()
c = 0.0
x, y = 0, 0
while c < r and x < self.size and y < self.size:
x += 1
if x == self.size:
x = 0
y += 1
if y == 36:
y -= 1
c += self.parsed_data[name][x, y]
phi = (x * self.dx) - 180 + random.random() * self.dx
psi = (y * self.dx) - 180 + random.random() * self.dx
return (phi, psi)
def convert(self, name):
return self.aa[name.lower()].lower()
if __name__ == "__main__":
rama = Ramachandran()
p1 = "/home/h3nnn4n/PyRosetta4.Release.python35.linux.release-147/setup/pyrosetta/database/scoring/score_functions/rama/shapovalov/kappa75/all.ramaProb"
p2 = "/usr/local/lib/python3.5/dist-packages/pyrosetta-4.0-py3.5-linux-x86_64.egg/pyrosetta/database/scoring/score_functions/rama/shapovalov/kappa75/all.ramaProb"
p3 = "/usr/local/lib/python3.6/site-packages/pyrosetta-2018.22+release.99b36feae43-py3.6-macosx-10.13-x86_64.egg/pyrosetta/database/scoring/score_functions/rama/shapovalov/kappa75/all.ramaProb"
if os.path.exists(p1):
rama.load(path=p1)
elif os.path.exists(p2):
rama.load(path=p2)
else:
rama.load(path=p3)
rama.process()
print(rama.get_random_angle('T'))
import matplotlib.pyplot as plt
for k, v in rama.parsed_data.items():
plt.imshow(v.transpose(), cmap='viridis', interpolation='nearest', origin="lower")
plt.savefig(k + ".png")
| 2.875 | 3 |
setup.py | wjps/grass-river-extraction-tools | 0 | 12767341 | import sys
import subprocess
from setuptools import find_packages, setup
def gdal_warning(msg=None):
raise Exception(f"Unable to determine gdal version using gdal-config: {msg}")
def libgdal_version():
version = None
try:
proc = subprocess.Popen(['gdal-config', '--version'], stdout=subprocess.PIPE)
version = proc.stdout.read().decode('utf-8').rstrip()
if not version:
gdal_warning("Version not set")
except Exception as e:
gdal_warning(e)
return f"{version}.*"
requires = ["numpy", "Cartopy", "richdem",
"matplotlib", "elevation", "click<7", "scipy",
"pygdal=="+libgdal_version()]
setup(
name='src',
packages=find_packages(),
version='0.1.0',
description='Automated method to extract river profiles using GRASS GIS',
author='<NAME>',
author_email='<EMAIL>',
url="https://grass-gis-to-extract-river-profiles.readthedocs.io",
license='MIT',
scripts=['bin/extract-rivers'],
entry_points={
"console_scripts": [
"visualise = grass_river_extraction_tools.visualise_dem:main"
]
},
install_requires=requires,
python_requires='~=3.6'
)
| 2.1875 | 2 |
wgs_report.py | mgi-qc/cwl_wgs_report | 0 | 12767342 | #wgs report
__author__ = '<NAME>'
#TODO checks for metrics
# write report
# write Ssheet
import csv
import os
import sys
import glob
import datetime
import argparse
import subprocess
from string import Template
parser = argparse.ArgumentParser()
parser.add_argument('-nod', help='Turn off directory creation', action='store_true')
args = parser.parse_args()
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def data_dir_check(dir_list, woid, date):
"""Create and return transfer directory if 'model' found in dir path."""
# return NA if no transfer dir found
transfer_dir = 'NA'
# iterate over data dirs
for directory in dir_list:
# if model found, create transfer dir and return path
if os.path.isdir(directory) and 'model' in directory:
dir_path_items = directory.split('/')
for no, d in enumerate(dir_path_items):
if 'model' in d:
model_directory = '/'.join(dir_path_items[:no + 1]) + '/'
transfer_dir = os.path.join(model_directory, 'data_transfer/{}_{}/'.format(woid, date))
if os.path.isdir(transfer_dir):
print('Transfer Directory already exists: {}'.format(transfer_dir))
return 'NA'
if os.path.isdir(model_directory) and not os.path.isdir(transfer_dir):
try:
os.mkdir(transfer_dir)
except OSError:
# raise OSError("Can't create destination directory {}!".format(transfer_dir))
return 'NA'
print('Data transfer directory created:\n{}'.format(transfer_dir))
return transfer_dir
return transfer_dir
mm_dd_yy = datetime.datetime.now().strftime("%m%d%y")
#Check for metrics file;
if not glob.glob('*.cwl.metrics.*.tsv'):
sys.exit('cwl.metrics file not found')
else:
metrics_files = glob.glob('*.cwl.metrics.*.tsv'.format(mm_dd_yy))
#Check, open, and create template file using Template;
if not os.path.isfile('/gscmnt/gc2783/qc/GMSworkorders/reports/wgs_results_template_file.txt'):
sys.exit('Template file not found.')
with open('/gscmnt/gc2783/qc/GMSworkorders/reports/wgs_results_template_file.txt', 'r', encoding='utf-8') as fh:
template = fh.read()
template_file = Template(template)
metrics_tracked = ['HAPLOID COVERAGE', 'discordant_rate', 'inter-chromosomal_Pairing rate',
'FREEMIX', 'FOP: PF_MISMATCH_RATE', 'SOP: PF_MISMATCH_RATE']
totals_list = ['HAPLOID COVERAGE', 'discordant_rate', 'inter-chromosomal_Pairing rate', 'FREEMIX',
'FOP: PF_MISMATCH_RATE','SOP: PF_MISMATCH_RATE', 'MEAN_INSERT_SIZE', 'STANDARD_DEVIATION',
'PCT_ADAPTER', 'PCT_20X','PCT_30X','PF_ALIGNED_BASES', 'PERCENT_DUPLICATION']
for file in metrics_files:
file_name = file.split('.')[0]
file_date = file.split('.')[-2]
SSheet_outfile = '{}.cwl.results.{}.tsv'.format(file_name, file_date)
report_outfile = '{}.cwl.report.{}.txt'.format(file_name, file_date)
# Ini. dicts
prnt_report = False
template_file_dict = {}
totals_dict = {}
tot_cnt_dict = {}
data_directories = []
print('Confluence link: \nhttps://confluence.ris.wustl.edu/pages/viewpage.action?spaceKey=AD&title=WorkOrder+{}'.format(file_name))
while True:
hap_in = input('Please enter Haploid Coverage value for {}: '.format(file_name))
if is_number(hap_in) and float(hap_in) > 0:
hap_value = float(hap_in)
break
else:
print('Please enter a positive number for Haploid Coverage. ')
while True:
seq_in = input('\nWould you like to add a SEQUENCING_NOTE? y/n: ')
if seq_in is 'y':
seq_notes = []
while True:
note_line = input()
if note_line != 'q':
seq_notes.append(note_line)
else:
break
break
elif seq_in is 'n':
seq_notes = ['']
print('Skipping SEQUENCING_NOTE')
break
else:
print('Please enter y or n')
for total in totals_list:
totals_dict[total] = 0
for metric in metrics_tracked:
template_file_dict[metric] = 0
for total in totals_list:
tot_cnt_dict[total] = 0
# Metrics File Open, Check Metrics, Generate 'results', Get Totals;
with open(file, 'r') as fh, open(SSheet_outfile, 'w') as of:
metrics_dict = csv.DictReader(fh, delimiter='\t')
header = metrics_dict.fieldnames
ofd = csv.DictWriter(of, fieldnames=header, delimiter='\t')
header.extend(['QC_Status','QC_failed_metrics'])
ofd.writeheader()
last_succeeded_build_id = []
#ini totals variables
count = 0
pass_count = 0
fail_count = 0
for line in metrics_dict:
line['QC_failed_metrics'] = ''
failed_metrics = []
template_file_dict['WOID'] = line['WorkOrder']
data_directories.append(line['data_directory'])
#Check metrics...
met_to_check = []
met_not_check = []
for met in metrics_tracked:
if met in line and is_number(line[met]):
met_to_check.append(met)
prnt_report = True
else:
met_not_check.append(met)
if 'HAPLOID COVERAGE' in met_to_check and float(line['HAPLOID COVERAGE']) < float(hap_value):
failed_metrics.append('HAPLOID COVERAGE')
template_file_dict['HAPLOID COVERAGE'] += 1
if 'discordant_rate' in met_to_check and float(line['discordant_rate']) > 5:
failed_metrics.append('discordant_rate')
template_file_dict['discordant_rate'] += 1
if 'inter-chromosomal_Pairing rate' in met_to_check and float(line['inter-chromosomal_Pairing rate']) > 0.05:
failed_metrics.append('inter-chromosomal_Pairing rate')
template_file_dict['inter-chromosomal_Pairing rate'] += 1
if 'FREEMIX' in met_to_check and float(line['FREEMIX']) > 0.05:
failed_metrics.append('FREEMIX')
template_file_dict['FREEMIX'] += 1
if 'FOP: PF_MISMATCH_RATE' in met_to_check and float(line['FOP: PF_MISMATCH_RATE']) > 0.05:
failed_metrics.append('FOP: PF_MISMATCH_RATE')
template_file_dict['FOP: PF_MISMATCH_RATE'] += 1
if 'SOP: PF_MISMATCH_RATE' in met_to_check and float(line['SOP: PF_MISMATCH_RATE']) > 0.05:
failed_metrics.append('SOP: PF_MISMATCH_RATE')
template_file_dict['SOP: PF_MISMATCH_RATE'] += 1
count += 1
if len(met_to_check) != len(metrics_tracked):
line['QC_Status'] = 'NA'
line['QC_failed_metrics'] = ','.join(failed_metrics)
elif len(failed_metrics) > 0:
line['QC_Status'] = 'FAIL'
line['QC_failed_metrics'] = ','.join(failed_metrics)
fail_count += 1
else:
line['QC_Status'] = 'PASS'
line['QC_failed_metrics'] = 'NA'
pass_count += 1
for total in totals_list:
if total in line and is_number(line[total]):
totals_dict[total] += float(line[total])
tot_cnt_dict[total] += 1
last_succeeded_build_id.append(line['last_succeeded_build'])
ofd.writerow(line)
avg_dict = {}
for total in totals_list:
if totals_dict[total] != 0:
avg_dict[total] = totals_dict[total] / tot_cnt_dict[total]
else:
avg_dict[total] = 'NA'
if prnt_report:
for metric in metrics_tracked:
if template_file_dict[metric] is 0 and pass_count + fail_count != count:
template_file_dict[metric] = 'NA'
#set unchecked metrics to NA
#print missing metric
##print report
transfer_data_directory = 'NA'
if not args.nod:
transfer_data_directory = data_dir_check(data_directories, template_file_dict['WOID'], mm_dd_yy)
with open(report_outfile, 'w', encoding='utf-8') as fhr:
fhr.write(template_file.substitute(WOID = template_file_dict['WOID'],
HAP_IN = hap_in,
SEQUENCING_NOTE = '\n'.join(seq_notes),
SAMPLE_NUMBER = count,
PASS_SAMPLES = pass_count,
FAIL = fail_count,
HAP_FAIL_COUNT = template_file_dict['HAPLOID COVERAGE'],
DIS_RT_FAIL_COUNT = template_file_dict['discordant_rate'],
INTER_CHR_FAIL_COUNT = template_file_dict['inter-chromosomal_Pairing rate'],
FREE_FAIL_COUNT = template_file_dict['FREEMIX'],
FOP_FAIL_COUNT = template_file_dict['FOP: PF_MISMATCH_RATE'],
SOP_FAIL_COUNT = template_file_dict['SOP: PF_MISMATCH_RATE'],
HAPLOID_COVERAGE = avg_dict['HAPLOID COVERAGE'],
discordant_rate = avg_dict['discordant_rate'],
inter_chromosomal_Pairing_rate = avg_dict['inter-chromosomal_Pairing rate'],
FREEMIX = avg_dict['FREEMIX'],
FOP_PF_MISMATCH_RATE = avg_dict['FOP: PF_MISMATCH_RATE'],
SOP_PF_MISMATCH_RATE= avg_dict['SOP: PF_MISMATCH_RATE'],
MEAN_INSERT_SIZE = avg_dict['MEAN_INSERT_SIZE'],
STANDARD_DEVIATION = avg_dict['STANDARD_DEVIATION'],
PCT_ADAPTER = avg_dict['PCT_ADAPTER'],
PCT_20X = avg_dict['PCT_20X'],
PCT_30X = avg_dict['PCT_30X'],
PF_ALIGNED_BASES = avg_dict['PF_ALIGNED_BASES'],
PERCENT_DUPLICATION = avg_dict['PERCENT_DUPLICATION'],
TRANSFER_DIR=transfer_data_directory,
RESULTS_SPREADSHEET = SSheet_outfile))
print('Report generated for {}'.format(file_name))
print('-----------------------')
builds = ','.join(last_succeeded_build_id)
with open('{}.Data_transfer_help.{}.txt'.format(template_file_dict['WOID'], file_date), 'w') as df:
df.write('Data Transfer Directory ={td}\ncd to parent data dir\ncd to model_data'
'\nmkdir data_transfer/{w}\nTransfer Commands:\n\ngenome model cwl-pipeline prep-for-transfer --md5sum'
' --directory={td} --builds {b}\n\n'
'genome model cwl-pipeline prep-for-transfer --md5sum'
' --directory={td} model_groups.project.id={w}\n'.format(td=transfer_data_directory, w=template_file_dict['WOID'], b=builds,))
else:
print('No report generated for {}; No required metrics found.'.format(file_name))
print('-----------------------------------------------------')
| 2.484375 | 2 |
src/dizest/res/websrc/apps/kbeenuux6kdk1651928207/api.py | season-framework/dizest | 2 | 12767343 | <filename>src/dizest/res/websrc/apps/kbeenuux6kdk1651928207/api.py
import os
import dizest as dizest_core
import season
import time
import builtins
import urllib
import requests
import traceback
import multiprocessing as mp
host = urllib.parse.urlparse(wiz.flask.request.base_url)
host = f"{host.scheme}://{host.netloc}/dizest/api/kernel/dev"
Dizest = wiz.model("dizest/scheduler")
wpid = wiz.request.segment.get(0)
fid = wiz.request.segment.get(1)
develop = False
if wpid == 'develop':
dizest = Dizest.test(fid)
flow = dizest.flow(fid)
develop = True
else:
db = wiz.model("dizest/db").use("workflow")
workflow = db.get(id=wpid)
dizest = Dizest(wpid, workflow)
flow = dizest.flow(fid)
kernel = dizest.kernel
def dizest_api(wiz):
def run(q, logger, dizest, flow, fnname, cwd, user):
os.chdir(cwd)
env = dict()
env['print'] = logger
env['display'] = logger
env['dizest'] = dizest
try:
code = flow.app().get("api")
local_env = dict()
exec(code, env, local_env)
local_env[fnname]()
except dizest_core.util.response.ResponseException as e:
data = e.get()
q.put(data)
except Exception as e:
stderr = traceback.format_exc()
logger(f"Dizest API Error: {type(e)} \n{stderr}", color=91)
q.put(e)
q.put(None)
inputs = flow.define.inputs()
fids = []
for key in inputs:
for i in range(len(inputs[key])):
fid = inputs[key][i]['flow_id']
if fid not in fids:
fids.append(fid)
for fid in fids:
kernel.sync(fid)
cwd = kernel.workflow.cwd()
wiz.pid = os.getpid()
fnname = wiz.request.segment.get(2)
dizest = flow.instance()
dizest.output = None
dizest.request = wiz.request
segpath = dizest.request.segment.framework.segmentpath
segpath = segpath.split("/")[3:]
segpath = "/".join(segpath)
dizest.request.segment.framework.segmentpath = segpath
logger = flow.logger
q = mp.Queue()
p = mp.Process(target=run, args=[q, logger, dizest, flow, fnname, cwd, wiz.session.get("id")])
p.start()
res = q.get()
p.join()
try:
p.kill()
except:
pass
if type(res) == tuple:
name, code, resp = res
wiz.response.headers.load(resp['headers'])
wiz.response.cookies.load(resp['cookies'])
wiz.response.set_mimetype(resp['mimetype'])
fn = getattr(wiz.response, name)
fn(*resp['args'], **resp['kwargs'])
wiz.response.status(404) | 2 | 2 |
python/pyproj/crs/crs.py | SamTDickinson/sciket-learn-lambda | 0 | 12767344 | <reponame>SamTDickinson/sciket-learn-lambda
"""
This module interfaces with PROJ to produce a pythonic interface
to the coordinate reference system (CRS) information.
"""
# pylint: disable=too-many-lines
import json
import re
import threading
import warnings
from abc import abstractmethod
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from pyproj._crs import (
_CRS,
AreaOfUse,
AuthorityMatchInfo,
Axis,
CoordinateOperation,
CoordinateSystem,
Datum,
Ellipsoid,
PrimeMeridian,
_load_proj_json,
is_proj,
is_wkt,
)
from pyproj.crs._cf1x8 import (
_GEOGRAPHIC_GRID_MAPPING_NAME_MAP,
_GRID_MAPPING_NAME_MAP,
_INVERSE_GEOGRAPHIC_GRID_MAPPING_NAME_MAP,
_INVERSE_GRID_MAPPING_NAME_MAP,
_horizontal_datum_from_params,
_try_list_if_string,
)
from pyproj.crs.coordinate_operation import ToWGS84Transformation
from pyproj.crs.coordinate_system import Cartesian2DCS, Ellipsoidal2DCS, VerticalCS
from pyproj.enums import ProjVersion, WktVersion
from pyproj.exceptions import CRSError
from pyproj.geod import Geod
class CRSLocal(threading.local):
"""
Threading local instance for cython CRS class.
For more details, see:
https://github.com/pyproj4/pyproj/issues/782
"""
def __init__(self):
self.crs = None # Initialises in each thread
super().__init__()
def _prepare_from_dict(projparams: dict, allow_json: bool = True) -> str:
if not isinstance(projparams, dict):
raise CRSError("CRS input is not a dict")
# check if it is a PROJ JSON dict
if "proj" not in projparams and "init" not in projparams and allow_json:
return json.dumps(projparams)
# convert a dict to a proj string.
pjargs = []
for key, value in projparams.items():
# the towgs84 as list
if isinstance(value, (list, tuple)):
value = ",".join([str(val) for val in value])
# issue 183 (+ no_rot)
if value is None or str(value) == "True":
pjargs.append(f"+{key}")
elif str(value) == "False":
pass
else:
pjargs.append(f"+{key}={value}")
return _prepare_from_string(" ".join(pjargs))
def _prepare_from_proj_string(in_crs_string: str) -> str:
in_crs_string = re.sub(r"[\s+]?=[\s+]?", "=", in_crs_string.lstrip())
# make sure the projection starts with +proj or +init
starting_params = ("+init", "+proj", "init", "proj")
if not in_crs_string.startswith(starting_params):
kvpairs: List[str] = []
first_item_inserted = False
for kvpair in in_crs_string.split():
if not first_item_inserted and (kvpair.startswith(starting_params)):
kvpairs.insert(0, kvpair)
first_item_inserted = True
else:
kvpairs.append(kvpair)
in_crs_string = " ".join(kvpairs)
# make sure it is the CRS type
if "type=crs" not in in_crs_string:
if "+" in in_crs_string:
in_crs_string += " +type=crs"
else:
in_crs_string += " type=crs"
# look for EPSG, replace with epsg (EPSG only works
# on case-insensitive filesystems).
in_crs_string = in_crs_string.replace("+init=EPSG", "+init=epsg").strip()
if in_crs_string.startswith(("+init", "init")):
warnings.warn(
"'+init=<authority>:<code>' syntax is deprecated. "
"'<authority>:<code>' is the preferred initialization method. "
"When making the change, be mindful of axis order changes: "
"https://pyproj4.github.io/pyproj/stable/gotchas.html"
"#axis-order-changes-in-proj-6",
FutureWarning,
stacklevel=2,
)
return in_crs_string
def _prepare_from_string(in_crs_string: str) -> str:
if not isinstance(in_crs_string, str):
raise CRSError("CRS input is not a string")
if not in_crs_string:
raise CRSError(f"CRS string is empty or invalid: {in_crs_string!r}")
if "{" in in_crs_string:
# may be json, try to decode it
try:
crs_dict = json.loads(in_crs_string, strict=False)
except ValueError as err:
raise CRSError("CRS appears to be JSON but is not valid") from err
if not crs_dict:
raise CRSError("CRS is empty JSON")
in_crs_string = _prepare_from_dict(crs_dict)
elif is_proj(in_crs_string):
in_crs_string = _prepare_from_proj_string(in_crs_string)
return in_crs_string
def _prepare_from_authority(auth_name: str, auth_code: Union[str, int]):
return f"{auth_name}:{auth_code}"
def _prepare_from_epsg(auth_code: Union[str, int]):
return _prepare_from_authority("epsg", auth_code)
class CRS:
"""
A pythonic Coordinate Reference System manager.
.. versionadded:: 2.0.0
The functionality is based on other fantastic projects:
* `rasterio <https://github.com/mapbox/rasterio/blob/c13f0943b95c0eaa36ff3f620bd91107aa67b381/rasterio/_crs.pyx>`_ # noqa: E501
* `opendatacube <https://github.com/opendatacube/datacube-core/blob/83bae20d2a2469a6417097168fd4ede37fd2abe5/datacube/utils/geometry/_base.py>`_ # noqa: E501
Attributes
----------
srs: str
The string form of the user input used to create the CRS.
"""
def __init__(self, projparams: Any = None, **kwargs) -> None:
"""
Initialize a CRS class instance with:
- PROJ string
- Dictionary of PROJ parameters
- PROJ keyword arguments for parameters
- JSON string with PROJ parameters
- CRS WKT string
- An authority string [i.e. 'epsg:4326']
- An EPSG integer code [i.e. 4326]
- A tuple of ("auth_name": "auth_code") [i.e ('epsg', '4326')]
- An object with a `to_wkt` method.
- A :class:`pyproj.crs.CRS` class
Example usage:
>>> from pyproj import CRS
>>> crs_utm = CRS.from_user_input(26915)
>>> crs_utm
<Projected CRS: EPSG:26915>
Name: NAD83 / UTM zone 15N
Axis Info [cartesian]:
- E[east]: Easting (metre)
- N[north]: Northing (metre)
Area of Use:
- name: North America - 96°W to 90°W and NAD83 by country
- bounds: (-96.0, 25.61, -90.0, 84.0)
Coordinate Operation:
- name: UTM zone 15N
- method: Transverse Mercator
Datum: North American Datum 1983
- Ellipsoid: GRS 1980
- Prime Meridian: Greenwich
<BLANKLINE>
>>> crs_utm.area_of_use.bounds
(-96.0, 25.61, -90.0, 84.0)
>>> crs_utm.ellipsoid
ELLIPSOID["GRS 1980",6378137,298.257222101,
LENGTHUNIT["metre",1],
ID["EPSG",7019]]
>>> crs_utm.ellipsoid.inverse_flattening
298.257222101
>>> crs_utm.ellipsoid.semi_major_metre
6378137.0
>>> crs_utm.ellipsoid.semi_minor_metre
6356752.314140356
>>> crs_utm.prime_meridian
PRIMEM["Greenwich",0,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8901]]
>>> crs_utm.prime_meridian.unit_name
'degree'
>>> crs_utm.prime_meridian.unit_conversion_factor
0.017453292519943295
>>> crs_utm.prime_meridian.longitude
0.0
>>> crs_utm.datum
DATUM["North American Datum 1983",
ELLIPSOID["GRS 1980",6378137,298.257222101,
LENGTHUNIT["metre",1]],
ID["EPSG",6269]]
>>> crs_utm.coordinate_system
CS[Cartesian,2],
AXIS["(E)",east,
ORDER[1],
LENGTHUNIT["metre",1,
ID["EPSG",9001]]],
AXIS["(N)",north,
ORDER[2],
LENGTHUNIT["metre",1,
ID["EPSG",9001]]]
>>> print(crs_utm.coordinate_operation.to_wkt(pretty=True))
CONVERSION["UTM zone 15N",
METHOD["Transverse Mercator",
ID["EPSG",9807]],
PARAMETER["Latitude of natural origin",0,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8801]],
PARAMETER["Longitude of natural origin",-93,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8802]],
PARAMETER["Scale factor at natural origin",0.9996,
SCALEUNIT["unity",1],
ID["EPSG",8805]],
PARAMETER["False easting",500000,
LENGTHUNIT["metre",1],
ID["EPSG",8806]],
PARAMETER["False northing",0,
LENGTHUNIT["metre",1],
ID["EPSG",8807]],
ID["EPSG",16015]]
>>> crs = CRS(proj='utm', zone=10, ellps='WGS84')
>>> print(crs.to_wkt(pretty=True))
PROJCRS["unknown",
BASEGEOGCRS["unknown",
DATUM["Unknown based on WGS84 ellipsoid",
ELLIPSOID["WGS 84",6378137,298.257223563,
LENGTHUNIT["metre",1],
ID["EPSG",7030]]],
PRIMEM["Greenwich",0,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8901]]],
CONVERSION["UTM zone 10N",
METHOD["Transverse Mercator",
ID["EPSG",9807]],
PARAMETER["Latitude of natural origin",0,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8801]],
PARAMETER["Longitude of natural origin",-123,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8802]],
PARAMETER["Scale factor at natural origin",0.9996,
SCALEUNIT["unity",1],
ID["EPSG",8805]],
PARAMETER["False easting",500000,
LENGTHUNIT["metre",1],
ID["EPSG",8806]],
PARAMETER["False northing",0,
LENGTHUNIT["metre",1],
ID["EPSG",8807]],
ID["EPSG",16010]],
CS[Cartesian,2],
AXIS["(E)",east,
ORDER[1],
LENGTHUNIT["metre",1,
ID["EPSG",9001]]],
AXIS["(N)",north,
ORDER[2],
LENGTHUNIT["metre",1,
ID["EPSG",9001]]]]
>>> geod = crs.get_geod()
>>> f"+a={geod.a:.0f} +f={geod.f:.8f}"
'+a=6378137 +f=0.00335281'
>>> crs.is_projected
True
>>> crs.is_geographic
False
"""
projstring = ""
if projparams:
if isinstance(projparams, _CRS):
projstring = projparams.srs
elif isinstance(projparams, str):
projstring = _prepare_from_string(projparams)
elif isinstance(projparams, dict):
projstring = _prepare_from_dict(projparams)
elif isinstance(projparams, int):
projstring = _prepare_from_epsg(projparams)
elif isinstance(projparams, (list, tuple)) and len(projparams) == 2:
projstring = _prepare_from_authority(*projparams)
elif hasattr(projparams, "to_wkt"):
projstring = projparams.to_wkt() # type: ignore
else:
raise CRSError(f"Invalid CRS input: {projparams!r}")
if kwargs:
projkwargs = _prepare_from_dict(kwargs, allow_json=False)
projstring = _prepare_from_string(" ".join((projstring, projkwargs)))
self.srs = projstring
self._local = CRSLocal()
if isinstance(projparams, _CRS):
self._local.crs = projparams
else:
self._local.crs = _CRS(self.srs)
@property
def _crs(self):
"""
Retrieve the Cython based _CRS object for this thread.
"""
if self._local.crs is None:
self._local.crs = _CRS(self.srs)
return self._local.crs
@classmethod
def from_authority(cls, auth_name: str, code: Union[str, int]) -> "CRS":
"""
.. versionadded:: 2.2.0
Make a CRS from an authority name and authority code
Parameters
----------
auth_name: str
The name of the authority.
code : int or str
The code used by the authority.
Returns
-------
CRS
"""
return cls.from_user_input(_prepare_from_authority(auth_name, code))
@classmethod
def from_epsg(cls, code: Union[str, int]) -> "CRS":
"""Make a CRS from an EPSG code
Parameters
----------
code : int or str
An EPSG code.
Returns
-------
CRS
"""
return cls.from_user_input(_prepare_from_epsg(code))
@classmethod
def from_proj4(cls, in_proj_string: str) -> "CRS":
"""
.. versionadded:: 2.2.0
Make a CRS from a PROJ string
Parameters
----------
in_proj_string : str
A PROJ string.
Returns
-------
CRS
"""
if not is_proj(in_proj_string):
raise CRSError(f"Invalid PROJ string: {in_proj_string}")
return cls.from_user_input(_prepare_from_proj_string(in_proj_string))
@classmethod
def from_wkt(cls, in_wkt_string: str) -> "CRS":
"""
.. versionadded:: 2.2.0
Make a CRS from a WKT string
Parameters
----------
in_wkt_string : str
A WKT string.
Returns
-------
CRS
"""
if not is_wkt(in_wkt_string):
raise CRSError(f"Invalid WKT string: {in_wkt_string}")
return cls.from_user_input(_prepare_from_string(in_wkt_string))
@classmethod
def from_string(cls, in_crs_string: str) -> "CRS":
"""
Make a CRS from:
Initialize a CRS class instance with:
- PROJ string
- JSON string with PROJ parameters
- CRS WKT string
- An authority string [i.e. 'epsg:4326']
Parameters
----------
in_crs_string : str
An EPSG, PROJ, or WKT string.
Returns
-------
CRS
"""
return cls.from_user_input(_prepare_from_string(in_crs_string))
def to_string(self) -> str:
"""
.. versionadded:: 2.2.0
Convert the CRS to a string.
It attempts to convert it to the authority string.
Otherwise, it uses the string format of the user
input to create the CRS.
Returns
-------
str
"""
auth_info = self.to_authority(min_confidence=100)
if auth_info:
return ":".join(auth_info)
return self.srs
@classmethod
def from_user_input(cls, value: Any, **kwargs) -> "CRS":
"""
Initialize a CRS class instance with:
- PROJ string
- Dictionary of PROJ parameters
- PROJ keyword arguments for parameters
- JSON string with PROJ parameters
- CRS WKT string
- An authority string [i.e. 'epsg:4326']
- An EPSG integer code [i.e. 4326]
- A tuple of ("auth_name": "auth_code") [i.e ('epsg', '4326')]
- An object with a `to_wkt` method.
- A :class:`pyproj.crs.CRS` class
Parameters
----------
value : obj
A Python int, dict, or str.
Returns
-------
CRS
"""
if isinstance(value, cls):
return value
return cls(value, **kwargs)
def get_geod(self) -> Optional[Geod]:
"""
Returns
-------
pyproj.geod.Geod:
Geod object based on the ellipsoid.
"""
if self.ellipsoid is None:
return None
return Geod(
a=self.ellipsoid.semi_major_metre,
rf=self.ellipsoid.inverse_flattening,
b=self.ellipsoid.semi_minor_metre,
)
@classmethod
def from_dict(cls, proj_dict: dict) -> "CRS":
"""
.. versionadded:: 2.2.0
Make a CRS from a dictionary of PROJ parameters.
Parameters
----------
proj_dict : str
PROJ params in dict format.
Returns
-------
CRS
"""
return cls.from_user_input(_prepare_from_dict(proj_dict))
@classmethod
def from_json(cls, crs_json: str) -> "CRS":
"""
.. versionadded:: 2.4.0
Create CRS from a CRS JSON string.
Parameters
----------
crs_json: str
CRS JSON string.
Returns
-------
CRS
"""
return cls.from_user_input(_load_proj_json(crs_json))
@classmethod
def from_json_dict(cls, crs_dict: dict) -> "CRS":
"""
.. versionadded:: 2.4.0
Create CRS from a JSON dictionary.
Parameters
----------
crs_dict: dict
CRS dictionary.
Returns
-------
CRS
"""
return cls.from_user_input(json.dumps(crs_dict))
def to_dict(self) -> dict:
"""
.. versionadded:: 2.2.0
Converts the CRS to dictionary of PROJ parameters.
.. warning:: You will likely lose important projection
information when converting to a PROJ string from
another format. See: https://proj.org/faq.html#what-is-the-best-format-for-describing-coordinate-reference-systems # noqa: E501
Returns
-------
dict:
PROJ params in dict format.
"""
def parse(val):
if val.lower() == "true":
return True
if val.lower() == "false":
return False
try:
return int(val)
except ValueError:
pass
try:
return float(val)
except ValueError:
pass
return _try_list_if_string(val)
proj_string = self.to_proj4()
if proj_string is None:
return {}
items = map(
lambda kv: len(kv) == 2 and (kv[0], parse(kv[1])) or (kv[0], None),
(part.lstrip("+").split("=", 1) for part in proj_string.strip().split()),
)
return {key: value for key, value in items if value is not False}
def to_cf(
self,
wkt_version: Union[WktVersion, str] = WktVersion.WKT2_2019,
errcheck: bool = False,
) -> dict:
"""
.. versionadded:: 2.2.0
This converts a :obj:`pyproj.crs.CRS` object
to a Climate and Forecast (CF) Grid Mapping Version 1.8 dict.
:ref:`build_crs_cf`
Parameters
----------
wkt_version: str or pyproj.enums.WktVersion
Version of WKT supported by CRS.to_wkt.
Default is :attr:`pyproj.enums.WktVersion.WKT2_2019`.
errcheck: bool, default=False
If True, will warn when parameters are ignored.
Returns
-------
dict:
CF-1.8 version of the projection.
"""
# pylint: disable=too-many-branches
cf_dict: Dict[str, Any] = {"crs_wkt": self.to_wkt(wkt_version)}
# handle bound CRS
if (
self.is_bound
and self.coordinate_operation
and self.coordinate_operation.towgs84
and self.source_crs
):
sub_cf: Dict[str, Any] = self.source_crs.to_cf(
wkt_version=wkt_version,
errcheck=errcheck,
)
sub_cf.pop("crs_wkt")
cf_dict.update(sub_cf)
cf_dict["towgs84"] = self.coordinate_operation.towgs84
return cf_dict
# handle compound CRS
if self.is_compound:
for sub_crs in self.sub_crs_list:
sub_cf = sub_crs.to_cf(wkt_version=wkt_version, errcheck=errcheck)
sub_cf.pop("crs_wkt")
cf_dict.update(sub_cf)
return cf_dict
# handle vertical CRS
if self.is_vertical:
vert_json = self.to_json_dict()
if "geoid_model" in vert_json:
cf_dict["geoid_name"] = vert_json["geoid_model"]["name"]
if self.datum:
cf_dict["geopotential_datum_name"] = self.datum.name
return cf_dict
# write out datum parameters
if self.ellipsoid:
cf_dict.update(
semi_major_axis=self.ellipsoid.semi_major_metre,
semi_minor_axis=self.ellipsoid.semi_minor_metre,
inverse_flattening=self.ellipsoid.inverse_flattening,
)
cf_dict["reference_ellipsoid_name"] = self.ellipsoid.name
if self.prime_meridian:
cf_dict["longitude_of_prime_meridian"] = self.prime_meridian.longitude
cf_dict["prime_meridian_name"] = self.prime_meridian.name
# handle geographic CRS
if self.geodetic_crs:
cf_dict["geographic_crs_name"] = self.geodetic_crs.name
if self.is_geographic:
if self.coordinate_operation:
cf_dict.update(
_INVERSE_GEOGRAPHIC_GRID_MAPPING_NAME_MAP[
self.coordinate_operation.method_name.lower()
](self.coordinate_operation)
)
if self.datum:
cf_dict["horizontal_datum_name"] = self.datum.name
else:
cf_dict["grid_mapping_name"] = "latitude_longitude"
return cf_dict
# handle projected CRS
if self.is_projected and self.datum:
cf_dict["horizontal_datum_name"] = self.datum.name
coordinate_operation = None
if not self.is_bound and self.is_projected:
coordinate_operation = self.coordinate_operation
cf_dict["projected_crs_name"] = self.name
coordinate_operation_name = (
None
if not coordinate_operation
else coordinate_operation.method_name.lower().replace(" ", "_")
)
if coordinate_operation_name not in _INVERSE_GRID_MAPPING_NAME_MAP:
if errcheck:
if coordinate_operation:
warnings.warn(
"Unsupported coordinate operation: "
f"{coordinate_operation.method_name}"
)
else:
warnings.warn("Coordinate operation not found.")
return {"crs_wkt": self.to_wkt(wkt_version)}
cf_dict.update(
_INVERSE_GRID_MAPPING_NAME_MAP[coordinate_operation_name](
coordinate_operation
)
)
return cf_dict
@staticmethod
def from_cf(
in_cf: dict,
ellipsoidal_cs: Any = None,
cartesian_cs: Any = None,
vertical_cs: Any = None,
errcheck=False,
) -> "CRS":
"""
.. versionadded:: 2.2.0
.. versionadded:: 3.0.0 ellipsoidal_cs, cartesian_cs, vertical_cs
.. deprecated:: 3.2.0 errcheck
This converts a Climate and Forecast (CF) Grid Mapping Version 1.8
dict to a :obj:`pyproj.crs.CRS` object.
:ref:`build_crs_cf`
Parameters
----------
in_cf: dict
CF version of the projection.
ellipsoidal_cs: Any, optional
Input to create an Ellipsoidal Coordinate System.
Anything accepted by :meth:`pyproj.crs.CoordinateSystem.from_user_input`
or an Ellipsoidal Coordinate System created from :ref:`coordinate_system`.
cartesian_cs: Any, optional
Input to create a Cartesian Coordinate System.
Anything accepted by :meth:`pyproj.crs.CoordinateSystem.from_user_input`
or :class:`pyproj.crs.coordinate_system.Cartesian2DCS`.
vertical_cs: Any, optional
Input to create a Vertical Coordinate System accepted by
:meth:`pyproj.crs.CoordinateSystem.from_user_input`
or :class:`pyproj.crs.coordinate_system.VerticalCS`
errcheck: bool, default=False
This parameter is for backwards compatibility with the old version.
It currently does nothing when True or False. DEPRECATED.
Returns
-------
CRS
"""
# pylint: disable=too-many-branches
if errcheck:
warnings.warn(
"errcheck is deprecated as it does nothing.",
DeprecationWarning,
stacklevel=2,
)
unknown_names = ("unknown", "undefined")
if "crs_wkt" in in_cf:
return CRS(in_cf["crs_wkt"])
if "spatial_ref" in in_cf: # for previous supported WKT key
return CRS(in_cf["spatial_ref"])
grid_mapping_name = in_cf.get("grid_mapping_name")
if grid_mapping_name is None:
raise CRSError("CF projection parameters missing 'grid_mapping_name'")
# build datum if possible
datum = _horizontal_datum_from_params(in_cf)
# build geographic CRS
try:
geographic_conversion_method: Optional[
Callable
] = _GEOGRAPHIC_GRID_MAPPING_NAME_MAP[grid_mapping_name]
except KeyError:
geographic_conversion_method = None
geographic_crs_name = in_cf.get("geographic_crs_name")
if datum:
geographic_crs: CRS = GeographicCRS(
name=geographic_crs_name or "undefined",
datum=datum,
ellipsoidal_cs=ellipsoidal_cs,
)
elif geographic_crs_name and geographic_crs_name not in unknown_names:
geographic_crs = CRS(geographic_crs_name)
if ellipsoidal_cs is not None:
geographic_crs_json = geographic_crs.to_json_dict()
geographic_crs_json[
"coordinate_system"
] = CoordinateSystem.from_user_input(ellipsoidal_cs).to_json_dict()
geographic_crs = CRS(geographic_crs_json)
else:
geographic_crs = GeographicCRS(ellipsoidal_cs=ellipsoidal_cs)
if grid_mapping_name == "latitude_longitude":
return geographic_crs
if geographic_conversion_method is not None:
return DerivedGeographicCRS(
base_crs=geographic_crs,
conversion=geographic_conversion_method(in_cf),
ellipsoidal_cs=ellipsoidal_cs,
)
# build projected CRS
try:
conversion_method = _GRID_MAPPING_NAME_MAP[grid_mapping_name]
except KeyError:
raise CRSError(
f"Unsupported grid mapping name: {grid_mapping_name}"
) from None
projected_crs = ProjectedCRS(
name=in_cf.get("projected_crs_name", "undefined"),
conversion=conversion_method(in_cf),
geodetic_crs=geographic_crs,
cartesian_cs=cartesian_cs,
)
# build bound CRS if exists
bound_crs = None
if "towgs84" in in_cf:
bound_crs = BoundCRS(
source_crs=projected_crs,
target_crs="WGS 84",
transformation=ToWGS84Transformation(
projected_crs.geodetic_crs, *_try_list_if_string(in_cf["towgs84"])
),
)
if "geopotential_datum_name" not in in_cf:
return bound_crs or projected_crs
# build Vertical CRS
vertical_crs = VerticalCRS(
name="undefined",
datum=in_cf["geopotential_datum_name"],
geoid_model=in_cf.get("geoid_name"),
vertical_cs=vertical_cs,
)
# build compound CRS
return CompoundCRS(
name="undefined", components=[bound_crs or projected_crs, vertical_crs]
)
def cs_to_cf(self) -> List[dict]:
"""
.. versionadded:: 3.0.0
This converts all coordinate systems (cs) in the CRS
to a list of Climate and Forecast (CF) Version 1.8 dicts.
:ref:`build_crs_cf`
Returns
-------
List[dict]:
CF-1.8 version of the coordinate systems.
"""
cf_axis_list = []
def rotated_pole(crs):
try:
return (
crs.coordinate_operation
and crs.coordinate_operation.method_name.lower()
in _INVERSE_GEOGRAPHIC_GRID_MAPPING_NAME_MAP
)
except KeyError:
return False
if self.type_name == "Temporal CRS" and self.datum:
datum_json = self.datum.to_json_dict()
origin = datum_json.get("time_origin", "1875-05-20").strip().rstrip("zZ")
if len(origin) == 4:
origin = f"{origin}-01-01"
axis = self.axis_info[0]
cf_temporal_axis = {
"standard_name": "time",
"long_name": "time",
"calendar": (
datum_json.get("calendar", "proleptic_gregorian")
.lower()
.replace(" ", "_")
),
"axis": "T",
}
unit_name = axis.unit_name.lower().replace("calendar", "").strip()
# no units for TemporalDateTime
if unit_name:
cf_temporal_axis["units"] = f"{unit_name} since {origin}"
cf_axis_list.append(cf_temporal_axis)
if self.coordinate_system:
cf_axis_list.extend(
self.coordinate_system.to_cf(rotated_pole=rotated_pole(self))
)
elif self.is_bound and self.source_crs and self.source_crs.coordinate_system:
cf_axis_list.extend(
self.source_crs.coordinate_system.to_cf(
rotated_pole=rotated_pole(self.source_crs)
)
)
else:
for sub_crs in self.sub_crs_list:
cf_axis_list.extend(sub_crs.cs_to_cf())
return cf_axis_list
def is_exact_same(self, other: Any) -> bool:
"""
Check if the CRS objects are the exact same.
Parameters
----------
other: Any
Check if the other CRS is the exact same to this object.
If the other object is not a CRS, it will try to create one.
On Failure, it will return False.
Returns
-------
bool
"""
try:
other = CRS.from_user_input(other)
except CRSError:
return False
return self._crs.is_exact_same(other._crs)
def equals(self, other: Any, ignore_axis_order: bool = False) -> bool:
"""
.. versionadded:: 2.5.0
Check if the CRS objects are equivalent.
Parameters
----------
other: Any
Check if the other object is equivalent to this object.
If the other object is not a CRS, it will try to create one.
On Failure, it will return False.
ignore_axis_order: bool, default=False
If True, it will compare the CRS class and ignore the axis order.
Returns
-------
bool
"""
try:
other = CRS.from_user_input(other)
except CRSError:
return False
return self._crs.equals(other._crs, ignore_axis_order=ignore_axis_order)
@property
def geodetic_crs(self) -> Optional["CRS"]:
"""
.. versionadded:: 2.2.0
Returns
-------
CRS:
The the geodeticCRS / geographicCRS from the CRS.
"""
return (
None
if self._crs.geodetic_crs is None
else self.__class__(self._crs.geodetic_crs)
)
@property
def source_crs(self) -> Optional["CRS"]:
"""
The the base CRS of a BoundCRS or a DerivedCRS/ProjectedCRS,
or the source CRS of a CoordinateOperation.
Returns
-------
CRS
"""
return (
None
if self._crs.source_crs is None
else self.__class__(self._crs.source_crs)
)
@property
def target_crs(self) -> Optional["CRS"]:
"""
.. versionadded:: 2.2.0
Returns
-------
CRS:
The hub CRS of a BoundCRS or the target CRS of a CoordinateOperation.
"""
return (
None
if self._crs.target_crs is None
else self.__class__(self._crs.target_crs)
)
@property
def sub_crs_list(self) -> List["CRS"]:
"""
If the CRS is a compound CRS, it will return a list of sub CRS objects.
Returns
-------
List[CRS]
"""
return [self.__class__(sub_crs) for sub_crs in self._crs.sub_crs_list]
@property
def utm_zone(self) -> Optional[str]:
"""
.. versionadded:: 2.6.0
Finds the UTM zone in a Projected CRS, Bound CRS, or Compound CRS
Returns
-------
Optional[str]:
The UTM zone number and letter if applicable.
"""
if self.is_bound and self.source_crs:
return self.source_crs.utm_zone
if self.sub_crs_list:
for sub_crs in self.sub_crs_list:
if sub_crs.utm_zone:
return sub_crs.utm_zone
elif (
self.coordinate_operation
and "UTM ZONE" in self.coordinate_operation.name.upper()
):
return self.coordinate_operation.name.upper().split("UTM ZONE ")[-1]
return None
@property
def name(self) -> str:
"""
Returns
-------
str:
The name of the CRS (from :cpp:func:`proj_get_name`).
"""
return self._crs.name
@property
def type_name(self) -> str:
"""
Returns
-------
str:
The name of the type of the CRS object.
"""
return self._crs.type_name
@property
def axis_info(self) -> List[Axis]:
"""
Retrieves all relevant axis information in the CRS.
If it is a Bound CRS, it gets the axis list from the Source CRS.
If it is a Compound CRS, it gets the axis list from the Sub CRS list.
Returns
-------
List[Axis]:
The list of axis information.
"""
return self._crs.axis_info
@property
def area_of_use(self) -> Optional[AreaOfUse]:
"""
Returns
-------
AreaOfUse:
The area of use object with associated attributes.
"""
return self._crs.area_of_use
@property
def ellipsoid(self) -> Optional[Ellipsoid]:
"""
.. versionadded:: 2.2.0
Returns
-------
Ellipsoid:
The ellipsoid object with associated attributes.
"""
return self._crs.ellipsoid
@property
def prime_meridian(self) -> Optional[PrimeMeridian]:
"""
.. versionadded:: 2.2.0
Returns
-------
PrimeMeridian:
The prime meridian object with associated attributes.
"""
return self._crs.prime_meridian
@property
def datum(self) -> Optional[Datum]:
"""
.. versionadded:: 2.2.0
Returns
-------
Datum
"""
return self._crs.datum
@property
def coordinate_system(self) -> Optional[CoordinateSystem]:
"""
.. versionadded:: 2.2.0
Returns
-------
CoordinateSystem
"""
return self._crs.coordinate_system
@property
def coordinate_operation(self) -> Optional[CoordinateOperation]:
"""
.. versionadded:: 2.2.0
Returns
-------
CoordinateOperation
"""
return self._crs.coordinate_operation
@property
def remarks(self) -> str:
"""
.. versionadded:: 2.4.0
Returns
-------
str:
Remarks about object.
"""
return self._crs.remarks
@property
def scope(self) -> str:
"""
.. versionadded:: 2.4.0
Returns
-------
str:
Scope of object.
"""
return self._crs.scope
def to_wkt(
self,
version: Union[WktVersion, str] = WktVersion.WKT2_2019,
pretty: bool = False,
) -> str:
"""
Convert the projection to a WKT string.
Version options:
- WKT2_2015
- WKT2_2015_SIMPLIFIED
- WKT2_2019
- WKT2_2019_SIMPLIFIED
- WKT1_GDAL
- WKT1_ESRI
Parameters
----------
version: pyproj.enums.WktVersion, optional
The version of the WKT output.
Default is :attr:`pyproj.enums.WktVersion.WKT2_2019`.
pretty: bool, default=False
If True, it will set the output to be a multiline string.
Returns
-------
str
"""
return self._crs.to_wkt(version=version, pretty=pretty)
def to_json(self, pretty: bool = False, indentation: int = 2) -> str:
"""
.. versionadded:: 2.4.0
Convert the object to a JSON string.
Parameters
----------
pretty: bool, default=False
If True, it will set the output to be a multiline string.
indentation: int, default=2
If pretty is True, it will set the width of the indentation.
Returns
-------
str
"""
return self._crs.to_json(pretty=pretty, indentation=indentation)
def to_json_dict(self) -> dict:
"""
.. versionadded:: 2.4.0
Convert the object to a JSON dictionary.
Returns
-------
dict
"""
return self._crs.to_json_dict()
def to_proj4(self, version: Union[ProjVersion, int] = ProjVersion.PROJ_5) -> str:
"""
Convert the projection to a PROJ string.
.. warning:: You will likely lose important projection
information when converting to a PROJ string from
another format. See:
https://proj.org/faq.html#what-is-the-best-format-for-describing-coordinate-reference-systems # noqa: E501
Parameters
----------
version: pyproj.enums.ProjVersion
The version of the PROJ string output.
Default is :attr:`pyproj.enums.ProjVersion.PROJ_4`.
Returns
-------
str
"""
return self._crs.to_proj4(version=version)
def to_epsg(self, min_confidence: int = 70) -> Optional[int]:
"""
Return the EPSG code best matching the CRS
or None if it a match is not found.
Example:
>>> from pyproj import CRS
>>> ccs = CRS("epsg:4328")
>>> ccs.to_epsg()
4328
If the CRS is bound, you can attempt to get an epsg code from
the source CRS:
>>> from pyproj import CRS
>>> ccs = CRS("+proj=geocent +datum=WGS84 +towgs84=0,0,0")
>>> ccs.to_epsg()
>>> ccs.source_crs.to_epsg()
4978
>>> ccs == CRS.from_epsg(4978)
False
Parameters
----------
min_confidence: int, default=70
A value between 0-100 where 100 is the most confident.
:ref:`min_confidence`
Returns
-------
Optional[int]:
The best matching EPSG code matching the confidence level.
"""
return self._crs.to_epsg(min_confidence=min_confidence)
def to_authority(self, auth_name: Optional[str] = None, min_confidence: int = 70):
"""
.. versionadded:: 2.2.0
Return the authority name and code best matching the CRS
or None if it a match is not found.
Example:
>>> from pyproj import CRS
>>> ccs = CRS("epsg:4328")
>>> ccs.to_authority()
('EPSG', '4328')
If the CRS is bound, you can get an authority from
the source CRS:
>>> from pyproj import CRS
>>> ccs = CRS("+proj=geocent +datum=WGS84 +towgs84=0,0,0")
>>> ccs.to_authority()
>>> ccs.source_crs.to_authority()
('EPSG', '4978')
>>> ccs == CRS.from_authorty('EPSG', '4978')
False
Parameters
----------
auth_name: str, optional
The name of the authority to filter by.
min_confidence: int, default=70
A value between 0-100 where 100 is the most confident.
:ref:`min_confidence`
Returns
-------
tuple(str, str) or None:
The best matching (<auth_name>, <code>) for the confidence level.
"""
return self._crs.to_authority(
auth_name=auth_name, min_confidence=min_confidence
)
def list_authority(
self, auth_name: Optional[str] = None, min_confidence: int = 70
) -> List[AuthorityMatchInfo]:
"""
.. versionadded:: 3.2.0
Return the authority names and codes best matching the CRS.
Example:
>>> from pyproj import CRS
>>> ccs = CRS("epsg:4328")
>>> ccs.list_authority()
[AuthorityMatchInfo(auth_name='EPSG', code='4326', confidence=100)]
If the CRS is bound, you can get an authority from
the source CRS:
>>> from pyproj import CRS
>>> ccs = CRS("+proj=geocent +datum=WGS84 +towgs84=0,0,0")
>>> ccs.list_authority()
[]
>>> ccs.source_crs.list_authority()
[AuthorityMatchInfo(auth_name='EPSG', code='4978', confidence=70)]
>>> ccs == CRS.from_authorty('EPSG', '4978')
False
Parameters
----------
auth_name: str, optional
The name of the authority to filter by.
min_confidence: int, default=70
A value between 0-100 where 100 is the most confident.
:ref:`min_confidence`
Returns
-------
List[AuthorityMatchInfo]:
List of authority matches for the CRS.
"""
return self._crs.list_authority(
auth_name=auth_name, min_confidence=min_confidence
)
def to_3d(self, name: Optional[str] = None) -> "CRS":
"""
.. versionadded:: 3.1.0
Convert the current CRS to the 3D version if it makes sense.
New vertical axis attributes:
- ellipsoidal height
- oriented upwards
- metre units
Parameters
----------
name: str, optional
CRS name. Defaults to use the name of the original CRS.
Returns
-------
CRS
"""
return self.__class__(self._crs.to_3d(name=name))
@property
def is_geographic(self) -> bool:
"""
This checks if the CRS is geographic.
It will check if it has a geographic CRS
in the sub CRS if it is a compount CRS and will check if
the source CRS is geographic if it is a bound CRS.
Returns
-------
bool:
True if the CRS is in geographic (lon/lat) coordinates.
"""
return self._crs.is_geographic
@property
def is_projected(self) -> bool:
"""
This checks if the CRS is projected.
It will check if it has a projected CRS
in the sub CRS if it is a compount CRS and will check if
the source CRS is projected if it is a bound CRS.
Returns
-------
bool:
True if CRS is projected.
"""
return self._crs.is_projected
@property
def is_vertical(self) -> bool:
"""
.. versionadded:: 2.2.0
This checks if the CRS is vertical.
It will check if it has a vertical CRS
in the sub CRS if it is a compount CRS and will check if
the source CRS is vertical if it is a bound CRS.
Returns
-------
bool:
True if CRS is vertical.
"""
return self._crs.is_vertical
@property
def is_bound(self) -> bool:
"""
Returns
-------
bool:
True if CRS is bound.
"""
return self._crs.is_bound
@property
def is_compound(self) -> bool:
"""
.. versionadded:: 3.1.0
Returns
-------
bool:
True if CRS is compound.
"""
return self._crs.is_compound
@property
def is_engineering(self) -> bool:
"""
.. versionadded:: 2.2.0
Returns
-------
bool:
True if CRS is local/engineering.
"""
return self._crs.is_engineering
@property
def is_geocentric(self) -> bool:
"""
This checks if the CRS is geocentric and
takes into account if the CRS is bound.
Returns
-------
bool:
True if CRS is in geocentric (x/y) coordinates.
"""
return self._crs.is_geocentric
@property
def is_derived(self):
"""
.. versionadded:: 3.2.0
Returns
-------
bool:
True if CRS is a Derived CRS.
"""
return self._crs.is_derived
def __eq__(self, other: Any) -> bool:
return self.equals(other)
def __getstate__(self) -> Dict[str, str]:
return {"srs": self.srs}
def __setstate__(self, state: Dict[str, Any]):
self.__dict__.update(state)
self._local = CRSLocal()
def __hash__(self) -> int:
return hash(self.to_wkt())
def __str__(self) -> str:
return self.srs
def __repr__(self) -> str:
# get axis information
axis_info_list: List[str] = []
for axis in self.axis_info:
axis_info_list.extend(["- ", str(axis), "\n"])
axis_info_str = "".join(axis_info_list)
# get coordinate system & sub CRS info
source_crs_repr = ""
sub_crs_repr = ""
if self.coordinate_system and self.coordinate_system.axis_list:
coordinate_system_name = str(self.coordinate_system)
elif self.is_bound and self.source_crs:
coordinate_system_name = str(self.source_crs.coordinate_system)
source_crs_repr = f"Source CRS: {self.source_crs.name}\n"
else:
coordinate_system_names = []
sub_crs_repr_list = ["Sub CRS:\n"]
for sub_crs in self.sub_crs_list:
coordinate_system_names.append(str(sub_crs.coordinate_system))
sub_crs_repr_list.extend(["- ", sub_crs.name, "\n"])
coordinate_system_name = "|".join(coordinate_system_names)
sub_crs_repr = "".join(sub_crs_repr_list)
# get coordinate operation repr
coordinate_operation = ""
if self.coordinate_operation:
coordinate_operation = "".join(
[
"Coordinate Operation:\n",
"- name: ",
str(self.coordinate_operation),
"\n- method: ",
self.coordinate_operation.method_name,
"\n",
]
)
# get SRS representation
srs_repr = self.to_string()
srs_repr = srs_repr if len(srs_repr) <= 50 else " ".join([srs_repr[:50], "..."])
axis_info_str = axis_info_str or "- undefined\n"
return (
f"<{self.type_name}: {srs_repr}>\n"
f"Name: {self.name}\n"
f"Axis Info [{coordinate_system_name or 'undefined'}]:\n"
f"{axis_info_str}"
"Area of Use:\n"
f"{self.area_of_use or '- undefined'}\n"
f"{coordinate_operation}"
f"Datum: {self.datum}\n"
f"- Ellipsoid: {self.ellipsoid or 'undefined'}\n"
f"- Prime Meridian: {self.prime_meridian or 'undefined'}\n"
f"{source_crs_repr}"
f"{sub_crs_repr}"
)
class CustomConstructorCRS(CRS):
"""
This class is a base class for CRS classes
that use a different constructor than the main CRS class.
.. versionadded:: 3.2.0
See: https://github.com/pyproj4/pyproj/issues/847
"""
@property
@abstractmethod
def _expected_types(self) -> Tuple[str, ...]:
"""
These are the type names of the CRS class
that are expected when using the from_* methods.
"""
raise NotImplementedError
def _check_type(self):
"""
This validates that the type of the CRS is expected
when using the from_* methods.
"""
if self.type_name not in self._expected_types:
raise CRSError(
f"Invalid type {self.type_name}. Expected {self._expected_types}."
)
@classmethod
def from_user_input(cls, value: Any, **kwargs) -> "CRS":
"""
Initialize a CRS class instance with:
- PROJ string
- Dictionary of PROJ parameters
- PROJ keyword arguments for parameters
- JSON string with PROJ parameters
- CRS WKT string
- An authority string [i.e. 'epsg:4326']
- An EPSG integer code [i.e. 4326]
- A tuple of ("auth_name": "auth_code") [i.e ('epsg', '4326')]
- An object with a `to_wkt` method.
- A :class:`pyproj.crs.CRS` class
Parameters
----------
value : obj
A Python int, dict, or str.
Returns
-------
CRS
"""
if isinstance(value, cls):
return value
crs = cls.__new__(cls)
super(CustomConstructorCRS, crs).__init__(value, **kwargs)
crs._check_type()
return crs
@property
def geodetic_crs(self) -> Optional["CRS"]:
"""
.. versionadded:: 2.2.0
Returns
-------
CRS:
The the geodeticCRS / geographicCRS from the CRS.
"""
return None if self._crs.geodetic_crs is None else CRS(self._crs.geodetic_crs)
@property
def source_crs(self) -> Optional["CRS"]:
"""
The the base CRS of a BoundCRS or a DerivedCRS/ProjectedCRS,
or the source CRS of a CoordinateOperation.
Returns
-------
CRS
"""
return None if self._crs.source_crs is None else CRS(self._crs.source_crs)
@property
def target_crs(self) -> Optional["CRS"]:
"""
.. versionadded:: 2.2.0
Returns
-------
CRS:
The hub CRS of a BoundCRS or the target CRS of a CoordinateOperation.
"""
return None if self._crs.target_crs is None else CRS(self._crs.target_crs)
@property
def sub_crs_list(self) -> List["CRS"]:
"""
If the CRS is a compound CRS, it will return a list of sub CRS objects.
Returns
-------
List[CRS]
"""
return [CRS(sub_crs) for sub_crs in self._crs.sub_crs_list]
def to_3d(self, name: Optional[str] = None) -> "CRS":
"""
.. versionadded:: 3.1.0
Convert the current CRS to the 3D version if it makes sense.
New vertical axis attributes:
- ellipsoidal height
- oriented upwards
- metre units
Parameters
----------
name: str, optional
CRS name. Defaults to use the name of the original CRS.
Returns
-------
CRS
"""
return CRS(self._crs.to_3d(name=name))
class GeographicCRS(CustomConstructorCRS):
"""
.. versionadded:: 2.5.0
This class is for building a Geographic CRS
"""
_expected_types = ("Geographic CRS", "Geographic 2D CRS", "Geographic 3D CRS")
def __init__(
self,
name: str = "undefined",
datum: Any = "urn:ogc:def:datum:EPSG::6326",
ellipsoidal_cs: Any = None,
) -> None:
"""
Parameters
----------
name: str, default="undefined"
Name of the CRS.
datum: Any, default="urn:ogc:def:datum:EPSG::6326"
Anything accepted by :meth:`pyproj.crs.Datum.from_user_input` or
a :class:`pyproj.crs.datum.CustomDatum`.
ellipsoidal_cs: Any, optional
Input to create an Ellipsoidal Coordinate System.
Anything accepted by :meth:`pyproj.crs.CoordinateSystem.from_user_input`
or an Ellipsoidal Coordinate System created from :ref:`coordinate_system`.
"""
geographic_crs_json = {
"$schema": "https://proj.org/schemas/v0.2/projjson.schema.json",
"type": "GeographicCRS",
"name": name,
"datum": Datum.from_user_input(datum).to_json_dict(),
"coordinate_system": CoordinateSystem.from_user_input(
ellipsoidal_cs or Ellipsoidal2DCS()
).to_json_dict(),
}
super().__init__(geographic_crs_json)
class DerivedGeographicCRS(CustomConstructorCRS):
"""
.. versionadded:: 2.5.0
This class is for building a Derived Geographic CRS
"""
_expected_types = ("Geographic CRS", "Geographic 2D CRS", "Geographic 3D CRS")
def _check_type(self):
"""
This validates that the type of the CRS is expected
when using the from_* methods.
"""
super()._check_type()
if not self.is_derived:
raise CRSError("CRS is not a Derived Geographic CRS")
def __init__(
self,
base_crs: Any,
conversion: Any,
ellipsoidal_cs: Any = None,
name: str = "undefined",
) -> None:
"""
Parameters
----------
base_crs: Any
Input to create the Geodetic CRS, a :class:`GeographicCRS` or
anything accepted by :meth:`pyproj.crs.CRS.from_user_input`.
conversion: Any
Anything accepted by :meth:`pyproj.crs.CoordinateSystem.from_user_input`
or a conversion from :ref:`coordinate_operation`.
ellipsoidal_cs: Any, optional
Input to create an Ellipsoidal Coordinate System.
Anything accepted by :meth:`pyproj.crs.CoordinateSystem.from_user_input`
or an Ellipsoidal Coordinate System created from :ref:`coordinate_system`.
name: str, default="undefined"
Name of the CRS.
"""
derived_geographic_crs_json = {
"$schema": "https://proj.org/schemas/v0.2/projjson.schema.json",
"type": "DerivedGeographicCRS",
"name": name,
"base_crs": CRS.from_user_input(base_crs).to_json_dict(),
"conversion": CoordinateOperation.from_user_input(
conversion
).to_json_dict(),
"coordinate_system": CoordinateSystem.from_user_input(
ellipsoidal_cs or Ellipsoidal2DCS()
).to_json_dict(),
}
super().__init__(derived_geographic_crs_json)
class GeocentricCRS(CustomConstructorCRS):
"""
.. versionadded:: 3.2.0
This class is for building a Geocentric CRS
"""
_expected_types = ("Geocentric CRS",)
def __init__(
self,
name: str = "undefined",
datum: Any = "urn:ogc:def:datum:EPSG::6326",
) -> None:
"""
Parameters
----------
name: str, default="undefined"
Name of the CRS.
datum: Any, default="urn:ogc:def:datum:EPSG::6326"
Anything accepted by :meth:`pyproj.crs.Datum.from_user_input` or
a :class:`pyproj.crs.datum.CustomDatum`.
"""
geocentric_crs_json = {
"$schema": ("https://proj.org/schemas/v0.2/projjson.schema.json"),
"type": "GeodeticCRS",
"name": name,
"datum": Datum.from_user_input(datum).to_json_dict(),
"coordinate_system": {
"subtype": "Cartesian",
"axis": [
{
"name": "Geocentric X",
"abbreviation": "X",
"direction": "geocentricX",
"unit": "metre",
},
{
"name": "Geocentric Y",
"abbreviation": "Y",
"direction": "geocentricY",
"unit": "metre",
},
{
"name": "Geocentric Z",
"abbreviation": "Z",
"direction": "geocentricZ",
"unit": "metre",
},
],
},
}
super().__init__(geocentric_crs_json)
class ProjectedCRS(CustomConstructorCRS):
"""
.. versionadded:: 2.5.0
This class is for building a Projected CRS.
"""
_expected_types = ("Projected CRS",)
def __init__(
self,
conversion: Any,
name: str = "undefined",
cartesian_cs: Any = None,
geodetic_crs: Any = None,
) -> None:
"""
Parameters
----------
conversion: Any
Anything accepted by :meth:`pyproj.crs.CoordinateSystem.from_user_input`
or a conversion from :ref:`coordinate_operation`.
name: str, optional
The name of the Projected CRS. Default is undefined.
cartesian_cs: Any, optional
Input to create a Cartesian Coordinate System.
Anything accepted by :meth:`pyproj.crs.CoordinateSystem.from_user_input`
or :class:`pyproj.crs.coordinate_system.Cartesian2DCS`.
geodetic_crs: Any, optional
Input to create the Geodetic CRS, a :class:`GeographicCRS` or
anything accepted by :meth:`pyproj.crs.CRS.from_user_input`.
"""
proj_crs_json = {
"$schema": "https://proj.org/schemas/v0.2/projjson.schema.json",
"type": "ProjectedCRS",
"name": name,
"base_crs": CRS.from_user_input(
geodetic_crs or GeographicCRS()
).to_json_dict(),
"conversion": CoordinateOperation.from_user_input(
conversion
).to_json_dict(),
"coordinate_system": CoordinateSystem.from_user_input(
cartesian_cs or Cartesian2DCS()
).to_json_dict(),
}
super().__init__(proj_crs_json)
class VerticalCRS(CustomConstructorCRS):
"""
.. versionadded:: 2.5.0
This class is for building a Vetical CRS.
.. warning:: geoid_model support only exists in PROJ >= 6.3.0
"""
_expected_types = ("Vertical CRS",)
def __init__(
self,
name: str,
datum: Any,
vertical_cs: Any = None,
geoid_model: Optional[str] = None,
) -> None:
"""
Parameters
----------
name: str
The name of the Vertical CRS (e.g. NAVD88 height).
datum: Any
Anything accepted by :meth:`pyproj.crs.Datum.from_user_input`
vertical_cs: Any, optional
Input to create a Vertical Coordinate System accepted by
:meth:`pyproj.crs.CoordinateSystem.from_user_input`
or :class:`pyproj.crs.coordinate_system.VerticalCS`
geoid_model: str, optional
The name of the GEOID Model (e.g. GEOID12B).
"""
vert_crs_json = {
"$schema": "https://proj.org/schemas/v0.2/projjson.schema.json",
"type": "VerticalCRS",
"name": name,
"datum": Datum.from_user_input(datum).to_json_dict(),
"coordinate_system": CoordinateSystem.from_user_input(
vertical_cs or VerticalCS()
).to_json_dict(),
}
if geoid_model is not None:
vert_crs_json["geoid_model"] = {"name": geoid_model}
super().__init__(vert_crs_json)
class CompoundCRS(CustomConstructorCRS):
"""
.. versionadded:: 2.5.0
This class is for building a Compound CRS.
"""
_expected_types = ("Compound CRS",)
def __init__(self, name: str, components: List[Any]) -> None:
"""
Parameters
----------
name: str
The name of the Compound CRS.
components: List[Any], optional
List of CRS to create a Compound Coordinate System.
List of anything accepted by :meth:`pyproj.crs.CRS.from_user_input`
"""
compound_crs_json = {
"$schema": "https://proj.org/schemas/v0.2/projjson.schema.json",
"type": "CompoundCRS",
"name": name,
"components": [
CRS.from_user_input(component).to_json_dict()
for component in components
],
}
super().__init__(compound_crs_json)
class BoundCRS(CustomConstructorCRS):
"""
.. versionadded:: 2.5.0
This class is for building a Bound CRS.
"""
_expected_types = ("Bound CRS",)
def __init__(self, source_crs: Any, target_crs: Any, transformation: Any) -> None:
"""
Parameters
----------
source_crs: Any
Input to create a source CRS.
target_crs: Any
Input to create the target CRS.
transformation: Any
Input to create the transformation.
"""
bound_crs_json = {
"$schema": "https://proj.org/schemas/v0.2/projjson.schema.json",
"type": "BoundCRS",
"source_crs": CRS.from_user_input(source_crs).to_json_dict(),
"target_crs": CRS.from_user_input(target_crs).to_json_dict(),
"transformation": CoordinateOperation.from_user_input(
transformation
).to_json_dict(),
}
super().__init__(bound_crs_json)
| 2.15625 | 2 |
codeforces/1469B-Red and Blue/1469B.py | hubert-wojtowicz/faang | 0 | 12767345 | <gh_stars>0
# https://codeforces.com/problemset/problem/1469/B
# https://codeforces.com/problemset/submission/1469/120399560
#
# Introduce two pointers i and j for red end blue position pointing.
# observations
# 1. whenever i o j is moved all previous elements are components of sum
# 2. defining prefix sum we can see maximal component sum for both red and blue
# 3. order of insertion to prefix sum does not matter - sum has the same value independent of insertion order
# 4. f(a) can be maximal value of 0, MPR, MPB, MPR+MPB, where:
# MPR - max prefix sum value build of Red sequence
# MPB - max prefix sum value build of Blue sequence
# Complexity O(n+m)
from itertools import accumulate
if __name__ == '__main__':
t = int(input())
while t>0:
t-=1
n = input()
MPR=max(accumulate(map(int, input().split(' '))))
m = input()
MPB=max(accumulate(map(int, input().split(' '))))
print(max(0, MPR, MPB, MPR+MPB)) | 3.34375 | 3 |
script/inspect.py | cherrytrick/auto_ui_test | 3 | 12767346 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
import os
import yaml
from utils.times import run_time
from config.conf import cm
@run_time
def inspect_element():
"""审查所有的元素是否正确"""
for i in os.listdir(cm.ELEMENT_PATH):
_path = os.path.join(cm.ELEMENT_PATH, i)
if os.path.isfile(_path):
with open(_path, encoding='utf-8') as f:
data = yaml.safe_load(f)
for k in data.values():
pattern, value = k.split('==')
if pattern not in cm.LOCATE_MODE:
raise AttributeError('【%s】路径中【%s]元素没有指定类型' % (i, k))
if pattern == 'xpath':
assert '//' in value, '【%s】路径中【%s]元素xpath类型与值不配' % (
i, k)
if pattern == 'css':
assert '//' not in value, '【%s】路径中【%s]元素css类型与值不配' % (
i, k)
if pattern in ('id', 'name', 'class'):
assert value, '【%s】路径中【%s]元素类型与值不匹配' % (i, k)
if __name__ == '__main__':
inspect_element()
| 2.46875 | 2 |
icbc-appointment.py | FuFunG/icbc-appointment-bot | 0 | 12767347 | <reponame>FuFunG/icbc-appointment-bot
import requests
import json
import yaml
from datetime import datetime
import gmail
with open('./config.yml', 'r') as file:
conf = yaml.safe_load(file)
lastName = conf['icbc']['drvrLastName']
licenceNumber = conf['icbc']['licenceNumber']
keyword = conf['icbc']['keyword']
expactAfterDate = conf['icbc']['expactAfterDate']
expactBeforeDate = conf['icbc']['expactBeforeDate']
expactAfterTime = conf['icbc']['expactAfterTime']
expactBeforeTime = conf['icbc']['expactBeforeTime']
examClass = str(conf['icbc']['examClass'])
DATE_FORMAT = "%Y-%m-%d"
TIME_FORMAT = "%H:%M"
def getToken():
login_url = "https://onlinebusiness.icbc.com/deas-api/v1/webLogin/webLogin"
headers = {'Content-type': 'application/json'}
payload = {
"drvrLastName": lastName,
"licenceNumber": licenceNumber,
"keyword": keyword
}
response = requests.put(login_url, data=json.dumps(payload), headers=headers)
if response.status_code == 200:
return response.headers["Authorization"]
return ""
def getAppointments(token):
appointment_url = "https://onlinebusiness.icbc.com/deas-api/v1/web/getAvailableAppointments"
headers = {
'Content-type': 'application/json',
'Authorization': token
}
point_grey = {
"aPosID": 9,
"examType": examClass+"-R-1",
"examDate": expactAfterDate,
"ignoreReserveTime": "false",
"prfDaysOfWeek": "[0,1,2,3,4,5,6]",
"prfPartsOfDay": "[0,1]",
"lastName": lastName,
"licenseNumber": licenceNumber
}
response = requests.post(appointment_url, data=json.dumps(point_grey), headers=headers)
if response.status_code == 200:
return response.json()
print('Authorization Error')
return []
def getAppointmentDate(appointment):
return appointment["appointmentDt"]["date"]
def appointmentMatchRequirement(appointment):
appointmentDate = getAppointmentDate(appointment)
thatDate = datetime.strptime(appointmentDate, DATE_FORMAT)
beforeDate = datetime.strptime(expactBeforeDate, DATE_FORMAT)
appointmentTime = appointment["startTm"]
thatTime = datetime.strptime(appointmentTime, TIME_FORMAT)
afterTime = datetime.strptime(expactAfterTime, TIME_FORMAT)
beforeTime = datetime.strptime(expactBeforeTime, TIME_FORMAT)
return thatDate <= beforeDate and afterTime <= thatTime <= beforeTime
if __name__ == "__main__":
token = getToken()
appointments = getAppointments(token)
mail_header = "Available Dates and Times:"
mail_content = ""
prevDate = ""
for appointment in appointments:
if (appointmentMatchRequirement(appointment)):
appointmentDate = getAppointmentDate(appointment)
appointmentTime = appointment["startTm"]
if prevDate != appointmentDate:
mail_content += '\n\n' + appointmentDate + ':'
prevDate = appointmentDate
mail_content += '\n\t' + appointmentTime
if mail_content != "":
sender_address = conf['gmail']['sender_address']
sender_pass = conf['gmail']['sender_pass']
receiver_address = conf['gmail']['receiver_address']
print(gmail.sendEmail(mail_header+mail_content, sender_address, sender_pass, receiver_address))
else:
print('No appointment match the date: '+expactAfterDate+' - ' +
expactBeforeDate+' at '+expactAfterTime+' - '+expactBeforeTime)
| 2.34375 | 2 |
kat_ran/kat.py | tojov/kat_ran_thru_my_keebord | 0 | 12767348 | <reponame>tojov/kat_ran_thru_my_keebord
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 4 23:12:15 2019
@author: abhijithneilabraham
"""
import random
import time
c=int(input('write in number how much you love a cat \n'))
def catran():
a=random.randint(97,122)
print(chr(a),end="")
r=0.05
for i in range(c):
if i%5==0:
r=random.uniform(0.01,0.2)
time.sleep(r)
catran()
print("\n Oops,cat ran"+str(c)+"times through ya keyboard!")
| 3.109375 | 3 |
src/ec2/helpers/query.py | cc1-cloud/cc1 | 11 | 12767349 | <reponame>cc1-cloud/cc1<filename>src/ec2/helpers/query.py
# -*- coding: utf-8 -*-
# @COPYRIGHT_begin
#
# Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @COPYRIGHT_end
"""@package src.ec2.helpers.query
@copyright Copyright (c) 2012 Institute of Nuclear Physics PAS <http://www.ifj.edu.pl/>
@author <NAME> <<EMAIL>>
"""
from datetime import datetime
import urllib
from ec2.base.auth import _sign_parameters_ver2
def query(parameters, aws_key=None, aws_secret=None, endpoint=None,
method=None, secure=False):
parameters.setdefault('SignatureMethod', 'HmacSHA256')
parameters.setdefault('SignatureVersion', '2')
parameters['AWSAccessKeyId'] = aws_key
parameters['Timestamp'] = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
parameters['Version'] = "2012-03-01"
# set Signature
signature = _sign_parameters_ver2(
parameters,
aws_secret,
endpoint=endpoint,
method=method,
)
parameters['Signature'] = signature
# build request
protocol = 'http' if not secure else 'https'
query_parameters = urllib.urlencode(parameters)
if method == 'GET':
request = ("%s://%s/?%s" % (protocol, endpoint, query_parameters),)
elif method == 'POST':
request = ("%s://%s" % (protocol, endpoint), query_parameters)
else:
raise Exception('Unsupported %s method: %s' % (protocol.upper(), method))
response = urllib.urlopen(*request).read()
return request, response
def get_instance_tags(cluster_manager):
instances = cluster_manager.user.vm.get_list()
tags = []
for instance in instances:
tags.append({'resource-id' : 'i-' + str(instance['vm_id']),
'key' : 'Name',
'resource-type' : 'instance',
'value' : instance['name']})
return tags
def get_instance_name_tag(cluster_manager, id):
instance = cluster_manager.user.vm.get_by_id({'vm_id':id})
tags = {'resource-id' : 'i-' + str(instance['vm_id']),
'key' : 'Name',
'resource-type' : 'instance',
'value' : instance['name']}
return tags
def get_volume_name_tag(cluster_manager, id):
volume = cluster_manager.user.storage_image.get_by_id({'vm_id':id})
tags = {'resource-id' : 'i-' + str(volume['storage_image_id']),
'key' : 'Name',
'resource-type' : 'volume',
'value' : volume['name']}
return tags
def get_volume_tags(cluster_manager):
volumes = cluster_manager.user.storage_image.get_list()
tags = []
for volume in volumes:
tags.append({'resource-id' : 'vol-' + str(volume['storage_image_id']),
'key' : 'Name',
'resource-type' : 'volume',
'value' : volume['name']})
return tags
| 2.625 | 3 |
src/pymor/parallel/dummy.py | mahgadalla/pymor | 1 | 12767350 | <gh_stars>1-10
# This file is part of the pyMOR project (http://www.pymor.org).
# Copyright 2013-2017 pyMOR developers and contributors. All rights reserved.
# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
from copy import deepcopy
from pymor.core.interfaces import ImmutableInterface
from pymor.parallel.interfaces import WorkerPoolInterface, RemoteObjectInterface
class DummyPool(WorkerPoolInterface):
def __len__(self):
return 1
def push(self, obj):
if isinstance(obj, ImmutableInterface):
return DummyRemoteObject(obj)
else:
return DummyRemoteObject(deepcopy(obj)) # ensure we make a deep copy of the data
def scatter_array(self, U, copy=True):
if copy:
U = U.copy()
return DummyRemoteObject(U)
def scatter_list(self, l):
l = list(l)
return DummyRemoteObject(l)
def _map_kwargs(self, kwargs):
return {k: (v.obj if isinstance(v, DummyRemoteObject) else v) for k, v in kwargs.items()}
def apply(self, function, *args, **kwargs):
kwargs = self._map_kwargs(kwargs)
return [function(*args, **kwargs)]
def apply_only(self, function, worker, *args, **kwargs):
kwargs = self._map_kwargs(kwargs)
return function(*args, **kwargs)
def map(self, function, *args, **kwargs):
kwargs = self._map_kwargs(kwargs)
result = [function(*a, **kwargs) for a in zip(*args)]
return result
def __bool__(self):
return False
dummy_pool = DummyPool()
class DummyRemoteObject(RemoteObjectInterface):
def __init__(self, obj):
self.obj = obj
def _remove(self):
del self.obj
| 2.21875 | 2 |