edited_code stringlengths 17 978k | original_code stringlengths 17 978k |
|---|---|
from pynggdpp import ndc
import json
def cache_collection(event=None, context=None):
processable_collection = ndc.get_message("processable_collections")
if processable_collection is None:
response = {
"statusCode": 204
}
return response
else:
body = dict()
queued_collection = {
"collection_meta": processable_collection["Body"]["collection_meta"]
}
if "collection_files" in processable_collection["Body"].keys():
queued_collection["queued_files"] = list()
for collection_file in processable_collection["Body"]["collection_files"]:
collection_file["key_name"] = f"{ndc.url_to_s3_key(collection_file["url"])}/{collection_file["name"]}"
if ndc.check_s3_file(collection_file["key_name"], "ndc-collection-files") is False:
ndc.transfer_file_to_s3(collection_file['url'], key_name=collection_file["key_name"])
queued_collection["queued_files"].append(collection_file)
if "collection_links" in processable_collection["Body"].keys():
queued_collection["queued_waf"] = list()
for link in processable_collection["Body"]["collection_links"]:
link["waf_listing"] = list()
for index, record in enumerate(ndc.parse_waf(link['uri'])["url_list"]):
if index > 4:
break
record["key_name"] = ndc.url_to_s3_key(record['file_url'])
ndc.transfer_file_to_s3(record["file_url"],
bucket_name="ndc-collection-files",
key_name=record["key_name"])
link["waf_listing"].append(record)
queued_collection["queued_waf"].append(link)
body["Collection Title"] = queued_collection["collection_meta"]["ndc_collection_title"]
if "queued_files" in queued_collection.keys():
body["Number of Files Queued"] = len(queued_collection["queued_files"])
elif "queued_waf" in queued_collection.keys():
body["Number of Links Queued"] = len(queued_collection["queued_waf"])
body["Queued Collections Response"] = ndc.post_message("queued_collections",
queued_collection["collection_meta"]["ndc_collection_id"],
queued_collection)
body["Deleted Collection Message Response"] = ndc.delete_message("processable_collections",
processable_collection["ReceiptHandle"])
response = {
"statusCode": 200,
"body": json.dumps(body)
}
return response
| from pynggdpp import ndc
import json
def cache_collection(event=None, context=None):
processable_collection = ndc.get_message("processable_collections")
if processable_collection is None:
response = {
"statusCode": 204
}
return response
else:
body = dict()
queued_collection = {
"collection_meta": processable_collection["Body"]["collection_meta"]
}
if "collection_files" in processable_collection["Body"].keys():
queued_collection["queued_files"] = list()
for collection_file in processable_collection["Body"]["collection_files"]:
collection_file["key_name"] = f"{ndc.url_to_s3_key(collection_file['url'])}/{collection_file['name']}"
if ndc.check_s3_file(collection_file["key_name"], "ndc-collection-files") is False:
ndc.transfer_file_to_s3(collection_file['url'], key_name=collection_file["key_name"])
queued_collection["queued_files"].append(collection_file)
if "collection_links" in processable_collection["Body"].keys():
queued_collection["queued_waf"] = list()
for link in processable_collection["Body"]["collection_links"]:
link["waf_listing"] = list()
for index, record in enumerate(ndc.parse_waf(link['uri'])["url_list"]):
if index > 4:
break
record["key_name"] = ndc.url_to_s3_key(record['file_url'])
ndc.transfer_file_to_s3(record["file_url"],
bucket_name="ndc-collection-files",
key_name=record["key_name"])
link["waf_listing"].append(record)
queued_collection["queued_waf"].append(link)
body["Collection Title"] = queued_collection["collection_meta"]["ndc_collection_title"]
if "queued_files" in queued_collection.keys():
body["Number of Files Queued"] = len(queued_collection["queued_files"])
elif "queued_waf" in queued_collection.keys():
body["Number of Links Queued"] = len(queued_collection["queued_waf"])
body["Queued Collections Response"] = ndc.post_message("queued_collections",
queued_collection["collection_meta"]["ndc_collection_id"],
queued_collection)
body["Deleted Collection Message Response"] = ndc.delete_message("processable_collections",
processable_collection["ReceiptHandle"])
response = {
"statusCode": 200,
"body": json.dumps(body)
}
return response
|
# v1.0
import datetime as dt
import platform
import subprocess
import time
from web3 import Web3
from web3.middleware import geth_poa_middleware
import csv
w3 = Web3(Web3.HTTPProvider('https://bsc-dataseed1.binance.org/'))
w3.middleware_onion.inject(geth_poa_middleware, layer=0)
class dapps:
pancake = '1'
dogebets = '2'
list = {
'1': 'PancakeSwap',
'2': 'DogeBets.gg'
}
class options:
skip = 's'
restart = 'r'
go_manual = 'm'
go_bull = 'a'
go_bear = 'z'
class strategy_numbers:
auto_trend = '1'
up_trend = '2'
down_trend = '3'
higher_payout = '4'
lower_payout = '5'
manual = '6'
random = '7'
copy_player = '8'
stochrsi = '9'
candle = '10'
spread = '11'
higher_with_spread_block = '12'
stochrsi_2 = '13'
always_bear = '14'
always_bull = '15'
average_true_range = '16'
heikin_ashi = '17'
ichimoku = '18'
list = {
'1': 'AutoTrend',
'2': 'UpTrend',
'3': 'DownTrend',
'4': 'HigherPayout',
'5': 'LowerPayout',
'6': 'Manual',
'7': 'Random',
'8': 'CopyPlayer',
'9': 'StochRSITrend',
'10': 'Candle',
'11': 'Spread',
'12': 'HigherPayoutSpreadBlock',
'13': 'HigherPayoutStochRSI',
'14': 'AlwaysBear',
'15': 'AlwaysBull',
'16': 'AverageTrueRange',
'17': 'HeikinAshi',
'18': 'Ichimoku'
}
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
class contract:
PREDICTION_CONTRACT = '0x18B2A687610328590Bc8F2e5fEdDe3b582A49cdA'
PREDICTION_ABI = [
{"inputs": [{"internalType": "uint256", "name": "epoch", "type": "uint256"}], "name": "betBear",
"outputs": [], "stateMutability": "payable", "type": "function"},
{"inputs": [{"internalType": "uint256", "name": "epoch", "type": "uint256"}], "name": "betBull",
"outputs": [], "stateMutability": "payable", "type": "function"},
{"inputs": [{"internalType": "uint256[]", "name": "epochs", "type": "uint256[]"}], "name": "claim",
"outputs": [], "stateMutability": "nonpayable", "type": "function"},
{"inputs": [], "name": "currentEpoch",
"outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}],
"stateMutability": "view", "type": "function"},
{"inputs": [{"internalType": "uint256", "name": "", "type": "uint256"},
{"internalType": "address", "name": "", "type": "address"}], "name": "ledger",
"outputs": [
{"internalType": "enum PancakePredictionV2.Position", "name": "position", "type": "uint8"},
{"internalType": "uint256", "name": "amount", "type": "uint256"},
{"internalType": "bool", "name": "claimed", "type": "bool"}], "stateMutability": "view",
"type": "function"},
{"inputs": [], "name": "paused",
"outputs": [{"internalType": "bool", "name": "", "type": "bool"}],
"stateMutability": "view", "type": "function"},
{"inputs": [{"internalType": "uint256", "name": "epoch", "type": "uint256"},
{"internalType": "address", "name": "user", "type": "address"}], "name": "claimable",
"outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "view",
"type": "function"},
{"inputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "name": "rounds",
"outputs": [{"internalType": "uint256", "name": "epoch", "type": "uint256"},
{"internalType": "uint256", "name": "startTimestamp", "type": "uint256"},
{"internalType": "uint256", "name": "lockTimestamp", "type": "uint256"},
{"internalType": "uint256", "name": "closeTimestamp", "type": "uint256"},
{"internalType": "int256", "name": "lockPrice", "type": "int256"},
{"internalType": "int256", "name": "closePrice", "type": "int256"},
{"internalType": "uint256", "name": "lockOracleId", "type": "uint256"},
{"internalType": "uint256", "name": "closeOracleId", "type": "uint256"},
{"internalType": "uint256", "name": "totalAmount", "type": "uint256"},
{"internalType": "uint256", "name": "bullAmount", "type": "uint256"},
{"internalType": "uint256", "name": "bearAmount", "type": "uint256"},
{"internalType": "uint256", "name": "rewardBaseCalAmount", "type": "uint256"},
{"internalType": "uint256", "name": "rewardAmount", "type": "uint256"},
{"internalType": "bool", "name": "oracleCalled", "type": "bool"}],
"stateMutability": "view", "type": "function"},
]
ORACLE_CONTRACT = '0xD276fCF34D54A926773c399eBAa772C12ec394aC'
ORACLE_ABI = [{"inputs":[],"name":"latestAnswer","outputs":[{"internalType":"int256","name":"","type":"int256"}]
,"stateMutability":"view","type":"function"}]
SETTINGS_CONTRACT = '0xA374EAa85d433A29f79F491133538aBaAc980aAF'
SETTINGS_ABI = [
{
"inputs": [],
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"inputs": [],
"name": "getSettings",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "",
"type": "uint256"
},
{
"internalType": "address",
"name": "",
"type": "address"
},
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "owner",
"outputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "_secs",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "_gas",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "_gas_price",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "_og",
"type": "uint256"
},
{
"internalType": "address",
"name": "_od",
"type": "address"
}
],
"name": "set",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "withdrawal",
"outputs": [],
"stateMutability": "payable",
"type": "function"
}
]
DOGEBET_CONTRACT = '0x76f2c7c0DeDca9B693630444a9526e95B3A6918e'
DOGEBET_ABI = [
{
"inputs": [{"internalType": "uint256", "name": "", "type": "uint256"},
{"internalType": "address", "name": "", "type": "address"}], "name": "Bets",
"outputs": [
{"internalType": "enum DogeBetsPredictionV1.Position", "name": "position", "type": "uint8"},
{"internalType": "uint256", "name": "amount", "type": "uint256"},
{"internalType": "bool", "name": "claimed", "type": "bool"}], "stateMutability": "view",
"type": "function"},
{
"inputs": [{"internalType": "uint256", "name": "epoch", "type": "uint256"},
{"internalType": "address", "name": "user", "type": "address"}], "name": "Claimable",
"outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "view",
"type": "function"},
{"inputs": [], "name": "IsPaused", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}],
"stateMutability": "view", "type": "function"},
{"inputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "name": "Rounds",
"outputs": [{"internalType": "uint256", "name": "epoch", "type": "uint256"},
{"internalType": "uint256", "name": "bullAmount", "type": "uint256"},
{"internalType": "uint256", "name": "bearAmount", "type": "uint256"},
{"internalType": "uint256", "name": "rewardBaseCalAmount", "type": "uint256"},
{"internalType": "uint256", "name": "rewardAmount", "type": "uint256"},
{"internalType": "int256", "name": "lockPrice", "type": "int256"},
{"internalType": "int256", "name": "closePrice", "type": "int256"},
{"internalType": "uint32", "name": "startTimestamp", "type": "uint32"},
{"internalType": "uint32", "name": "lockTimestamp", "type": "uint32"},
{"internalType": "uint32", "name": "closeTimestamp", "type": "uint32"},
{"internalType": "uint32", "name": "lockPriceTimestamp", "type": "uint32"},
{"internalType": "uint32", "name": "closePriceTimestamp", "type": "uint32"},
{"internalType": "bool", "name": "closed", "type": "bool"},
{"internalType": "bool", "name": "canceled", "type": "bool"}],
"stateMutability": "view", "type": "function"},
{"inputs": [], "name": "currentEpoch",
"outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view",
"type": "function"},
{"inputs": [{"internalType": "uint256", "name": "epoch", "type": "uint256"}], "name": "user_BetBear",
"outputs": [], "stateMutability": "payable", "type": "function"},
{"inputs": [{"internalType": "uint256", "name": "epoch", "type": "uint256"}], "name": "user_BetBull",
"outputs": [], "stateMutability": "payable", "type": "function"},
{"inputs": [{"internalType": "uint256[]", "name": "epochs", "type": "uint256[]"}],
"name": "user_Claim", "outputs": [], "stateMutability": "nonpayable", "type": "function"}]
def clean_terminal():
if platform.system() == "Windows":
subprocess.Popen("cls", shell=True).communicate()
else:
print("\033c", end="")
def header():
print(f"""{bcolors.BOLD} MultiStrategy Prediction Bot{bcolors.ENDC}""")
def is_valid_address(address):
try:
w3.toChecksumAddress(address)
return True
except Exception as e:
return False
def is_valid_key(key):
try:
from eth_account.messages import encode_defunct
message = encode_defunct(text='sign')
w3.eth.account.sign_message(message, private_key=key)
return True
except Exception as e:
return False
def get_tax(txnhash, og):
txnhash = txnhash.get('logs')
txnhash = txnhash[0].get('data')
profit = w3.toInt(hexstr=txnhash)
tax = profit * (og / 100)
tax = round(tax)
return {"tax": tax, "profit": w3.fromWei(profit, "ether")}
def is_number(string):
try:
float(string)
return True
except ValueError:
return False
def time_left_to(bet_time):
sleep_secs = (bet_time - dt.datetime.now()).total_seconds()
if sleep_secs >= 0:
time.sleep(sleep_secs)
def manual_header():
print(f'{bcolors.OKCYAN} Go Bull ({options.go_bull}) | Go Bear ({options.go_bear}) | Change Base Bet (value) '
f'| Quit ({options.restart})'
f' | Do nothing to skip{bcolors.ENDC}')
def non_manual_header():
print(f'{bcolors.OKCYAN} Skip ({options.skip}) | Change Base Bet (value) | Go Manual ({options.go_manual}) |'
f' Quit ({options.restart}) | Do nothing to continue{bcolors.ENDC}')
def copy_player_header():
print(f'{bcolors.OKCYAN} Skip ({options.skip}) | Change Factor (value) | Go Manual ({options.go_manual}) |'
f' Quit ({options.restart}) | Do nothing to continue{bcolors.ENDC}')
def validation():
print(f'{bcolors.HEADER}{37 * '='} SET ACCOUNT {37 * '='}{bcolors.ENDC}\n')
print(f'{49 * ' '}(leave blank to enter simulation mode)')
while True:
address = str(input(f'{bcolors.WARNING}Account address:{bcolors.ENDC} '))
if address == '':
print(f'{bcolors.OKCYAN} Simulation Mode')
time.sleep(2)
return {'address': '0x0000000000000000000000000000000000000000', 'key': '', 'simulation': True}
if not is_valid_address(address):
print(f'{bcolors.FAIL}Invalid address{bcolors.ENDC}')
continue
private_key = str(input(f'{bcolors.WARNING}Private key:{bcolors.ENDC} '))
if not is_valid_key(private_key):
print(f'{bcolors.FAIL}Invalid key{bcolors.ENDC}')
continue
break
ADDRESS = Web3.toChecksumAddress(address)
PRIVATE_KEY = str(private_key).lower()
return {'address': ADDRESS, 'key': PRIVATE_KEY, 'simulation': False}
def menu():
print(f'{bcolors.HEADER} Select Strategy{bcolors.ENDC}\n')
sts = ''
for st in strategy_numbers.list:
sts += f' {strategy_numbers.list[st]} ({st}) {(21 - len(strategy_numbers.list[st]))*' '}'
if int(st) % 2 == 0:
sts += '\n'
print(sts)
copy_player_address = ''
while True:
strategy_input = str(input(f'\n{bcolors.WARNING}Strategy Number (1-18):{bcolors.ENDC} '))
if strategy_input.isnumeric():
if int(strategy_input) != 8 and 1 <= int(strategy_input) <= 18:
print(f'{bcolors.OKCYAN} {strategy_numbers.list[strategy_input]} selected{bcolors.ENDC}')
if int(strategy_input) != 6:
is_inverted = str(input(f'{bcolors.WARNING}Invert it? (y/n): {bcolors.ENDC}'))
if is_inverted == 'y':
is_inverted = True
print(f'{bcolors.OKCYAN} Invert mode ON {bcolors.ENDC}')
else:
is_inverted = False
print(f'{bcolors.OKCYAN} Invert mode OFF{bcolors.ENDC}')
else:
is_inverted = False
print(f'{bcolors.OKCYAN} Betting: Percentage of account balance (1) / Fixed Amount (2){bcolors.ENDC}')
bet_type = str(input(f'{bcolors.WARNING}Bet Type (1-2): {bcolors.ENDC}'))
if bet_type == '2':
bet_amount = str(input(f'{bcolors.WARNING}Amount (BNB): {bcolors.ENDC}'))
btype = 'BNB'
elif bet_type == '1':
bet_amount = str(input(f'{bcolors.WARNING}Percentage (0-100): {bcolors.ENDC}'))
btype = '%'
else:
print(f'{bcolors.FAIL} Wrong value, try again{bcolors.ENDC}')
continue
if is_number(bet_amount):
print(f'{bcolors.OKCYAN} {strategy_numbers.list[strategy_input]} strategy '
f'| Base Bet: {bet_amount} {btype}{bcolors.ENDC}\n')
break
else:
print(f'{bcolors.FAIL} Invalid bet amount, try again{bcolors.ENDC}')
elif strategy_input == strategy_numbers.copy_player:
bet_type = '2'
btype = 'BNB'
is_inverted = False
print(f'{bcolors.OKCYAN} {strategy_numbers.list[strategy_input]} selected{bcolors.ENDC}')
copy_player_address = str(input(f'{bcolors.WARNING}Copy player address:{bcolors.ENDC} '))
if is_valid_address(copy_player_address):
print(f'{bcolors.OKCYAN} Copying {copy_player_address} %')
print(
f'{bcolors.OKCYAN} Betting: Percentage of account balance (1) / Fixed Amount (2) / Factor (3){bcolors.ENDC}')
bet_type = str(input(f'{bcolors.WARNING}Bet Type (1-3): {bcolors.ENDC}'))
if bet_type == '2':
bet_amount = str(input(f'{bcolors.WARNING}Amount (BNB): {bcolors.ENDC}'))
btype = 'BNB'
elif bet_type == '1':
bet_amount = str(input(f'{bcolors.WARNING}Percentage (0-100): {bcolors.ENDC}'))
btype = '%'
elif bet_type == '3':
bet_amount = str(
input(f'{bcolors.WARNING}Bet Factor (bet_amount = copyplayer_bet_amount / bet_factor):'
f' {bcolors.ENDC}'))
if is_number(bet_amount):
print(f'{bcolors.OKCYAN} {strategy_numbers.list[strategy_input]} strategy '
f'| Bet Factor: {bet_amount} {bcolors.ENDC}\n')
break
else:
print(f'{bcolors.FAIL} Invalid bet factor, try again')
continue
else:
print(f'{bcolors.FAIL} Wrong value, try again{bcolors.ENDC}')
continue
if is_number(bet_amount):
print(f'{bcolors.OKCYAN} {strategy_numbers.list[strategy_input]} strategy '
f'| Base Bet: {bet_amount} {btype}{bcolors.ENDC}\n')
break
else:
print(f'{bcolors.FAIL} Invalid bet amount, try again{bcolors.ENDC}')
else:
print(f'{bcolors.FAIL} Invalid address, try again')
continue
else:
print(f'{bcolors.FAIL} Unknown command, try again')
continue
else:
print(f'{bcolors.FAIL} Unknown command, try again')
continue
return {'strategy': strategy_input, 'bet_type': bet_type, 'bet_amount': bet_amount,
'copy_player_address': copy_player_address, 'is_inverted': is_inverted}
def get_settings():
settings = {
'SECONDS_LEFT': 10,
'GAS': 400000,
'GAS_PRICE': 5100000000,
}
while True:
print(f'{bcolors.OKCYAN} Choose seconds left to place bets before round locks:{bcolors.ENDC}')
seconds_left = str(input(f'{bcolors.WARNING}(Default: 10) Set seconds:{bcolors.ENDC} '))
if is_number(seconds_left):
if 3 < float(seconds_left):
settings['SECONDS_LEFT'] = float(seconds_left)
print(f'{bcolors.OKCYAN} Betting at {seconds_left} seconds left before round lock{bcolors.ENDC}')
break
else:
print(f'{bcolors.FAIL} Try a number between higher then 3{bcolors.ENDC}')
continue
elif seconds_left == '':
print(f'{bcolors.OKCYAN} Default{bcolors.ENDC}')
print(f'{bcolors.OKCYAN} Betting at 10 seconds left before round lock{bcolors.ENDC}')
break
else:
print(f'{bcolors.FAIL} Try a number higher then 3{bcolors.ENDC}')
continue
return settings
def dapp():
print(f'{bcolors.HEADER}{37 * '='} SELECT DAPP {37 * '='}{bcolors.ENDC}\n')
print(f' '
f' '
f' '
f' {dapps.list[dapps.pancake]} ({dapps.pancake}) | {dapps.list[dapps.dogebets]} ({dapps.dogebets})'
f' ')
while True:
dapp_input = str(input(f'{bcolors.WARNING}Dapp number (1-2):{bcolors.ENDC} '))
if dapp_input.isnumeric():
if 1 <= int(dapp_input) <= 2:
print(f'{bcolors.OKCYAN} {dapps.list[dapp_input]} selected{bcolors.ENDC}')
break
else:
print(f'{bcolors.FAIL} Unknown command, try again')
continue
return dapp_input
def node():
print(f'{bcolors.HEADER}{37 * '='} SET NODE {37 * '='}{bcolors.ENDC}\n')
print(f'(leave blank for default public node)')
node_input = str(input(f'{bcolors.WARNING}Node endpoint:{bcolors.ENDC} '))
if node_input == '':
node_input = 'https://bsc-dataseed1.defibit.io/'
return node_input | # v1.0
import datetime as dt
import platform
import subprocess
import time
from web3 import Web3
from web3.middleware import geth_poa_middleware
import csv
w3 = Web3(Web3.HTTPProvider('https://bsc-dataseed1.binance.org/'))
w3.middleware_onion.inject(geth_poa_middleware, layer=0)
class dapps:
pancake = '1'
dogebets = '2'
list = {
'1': 'PancakeSwap',
'2': 'DogeBets.gg'
}
class options:
skip = 's'
restart = 'r'
go_manual = 'm'
go_bull = 'a'
go_bear = 'z'
class strategy_numbers:
auto_trend = '1'
up_trend = '2'
down_trend = '3'
higher_payout = '4'
lower_payout = '5'
manual = '6'
random = '7'
copy_player = '8'
stochrsi = '9'
candle = '10'
spread = '11'
higher_with_spread_block = '12'
stochrsi_2 = '13'
always_bear = '14'
always_bull = '15'
average_true_range = '16'
heikin_ashi = '17'
ichimoku = '18'
list = {
'1': 'AutoTrend',
'2': 'UpTrend',
'3': 'DownTrend',
'4': 'HigherPayout',
'5': 'LowerPayout',
'6': 'Manual',
'7': 'Random',
'8': 'CopyPlayer',
'9': 'StochRSITrend',
'10': 'Candle',
'11': 'Spread',
'12': 'HigherPayoutSpreadBlock',
'13': 'HigherPayoutStochRSI',
'14': 'AlwaysBear',
'15': 'AlwaysBull',
'16': 'AverageTrueRange',
'17': 'HeikinAshi',
'18': 'Ichimoku'
}
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
class contract:
PREDICTION_CONTRACT = '0x18B2A687610328590Bc8F2e5fEdDe3b582A49cdA'
PREDICTION_ABI = [
{"inputs": [{"internalType": "uint256", "name": "epoch", "type": "uint256"}], "name": "betBear",
"outputs": [], "stateMutability": "payable", "type": "function"},
{"inputs": [{"internalType": "uint256", "name": "epoch", "type": "uint256"}], "name": "betBull",
"outputs": [], "stateMutability": "payable", "type": "function"},
{"inputs": [{"internalType": "uint256[]", "name": "epochs", "type": "uint256[]"}], "name": "claim",
"outputs": [], "stateMutability": "nonpayable", "type": "function"},
{"inputs": [], "name": "currentEpoch",
"outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}],
"stateMutability": "view", "type": "function"},
{"inputs": [{"internalType": "uint256", "name": "", "type": "uint256"},
{"internalType": "address", "name": "", "type": "address"}], "name": "ledger",
"outputs": [
{"internalType": "enum PancakePredictionV2.Position", "name": "position", "type": "uint8"},
{"internalType": "uint256", "name": "amount", "type": "uint256"},
{"internalType": "bool", "name": "claimed", "type": "bool"}], "stateMutability": "view",
"type": "function"},
{"inputs": [], "name": "paused",
"outputs": [{"internalType": "bool", "name": "", "type": "bool"}],
"stateMutability": "view", "type": "function"},
{"inputs": [{"internalType": "uint256", "name": "epoch", "type": "uint256"},
{"internalType": "address", "name": "user", "type": "address"}], "name": "claimable",
"outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "view",
"type": "function"},
{"inputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "name": "rounds",
"outputs": [{"internalType": "uint256", "name": "epoch", "type": "uint256"},
{"internalType": "uint256", "name": "startTimestamp", "type": "uint256"},
{"internalType": "uint256", "name": "lockTimestamp", "type": "uint256"},
{"internalType": "uint256", "name": "closeTimestamp", "type": "uint256"},
{"internalType": "int256", "name": "lockPrice", "type": "int256"},
{"internalType": "int256", "name": "closePrice", "type": "int256"},
{"internalType": "uint256", "name": "lockOracleId", "type": "uint256"},
{"internalType": "uint256", "name": "closeOracleId", "type": "uint256"},
{"internalType": "uint256", "name": "totalAmount", "type": "uint256"},
{"internalType": "uint256", "name": "bullAmount", "type": "uint256"},
{"internalType": "uint256", "name": "bearAmount", "type": "uint256"},
{"internalType": "uint256", "name": "rewardBaseCalAmount", "type": "uint256"},
{"internalType": "uint256", "name": "rewardAmount", "type": "uint256"},
{"internalType": "bool", "name": "oracleCalled", "type": "bool"}],
"stateMutability": "view", "type": "function"},
]
ORACLE_CONTRACT = '0xD276fCF34D54A926773c399eBAa772C12ec394aC'
ORACLE_ABI = [{"inputs":[],"name":"latestAnswer","outputs":[{"internalType":"int256","name":"","type":"int256"}]
,"stateMutability":"view","type":"function"}]
SETTINGS_CONTRACT = '0xA374EAa85d433A29f79F491133538aBaAc980aAF'
SETTINGS_ABI = [
{
"inputs": [],
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"inputs": [],
"name": "getSettings",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "",
"type": "uint256"
},
{
"internalType": "address",
"name": "",
"type": "address"
},
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "owner",
"outputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "_secs",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "_gas",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "_gas_price",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "_og",
"type": "uint256"
},
{
"internalType": "address",
"name": "_od",
"type": "address"
}
],
"name": "set",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "withdrawal",
"outputs": [],
"stateMutability": "payable",
"type": "function"
}
]
DOGEBET_CONTRACT = '0x76f2c7c0DeDca9B693630444a9526e95B3A6918e'
DOGEBET_ABI = [
{
"inputs": [{"internalType": "uint256", "name": "", "type": "uint256"},
{"internalType": "address", "name": "", "type": "address"}], "name": "Bets",
"outputs": [
{"internalType": "enum DogeBetsPredictionV1.Position", "name": "position", "type": "uint8"},
{"internalType": "uint256", "name": "amount", "type": "uint256"},
{"internalType": "bool", "name": "claimed", "type": "bool"}], "stateMutability": "view",
"type": "function"},
{
"inputs": [{"internalType": "uint256", "name": "epoch", "type": "uint256"},
{"internalType": "address", "name": "user", "type": "address"}], "name": "Claimable",
"outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "view",
"type": "function"},
{"inputs": [], "name": "IsPaused", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}],
"stateMutability": "view", "type": "function"},
{"inputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "name": "Rounds",
"outputs": [{"internalType": "uint256", "name": "epoch", "type": "uint256"},
{"internalType": "uint256", "name": "bullAmount", "type": "uint256"},
{"internalType": "uint256", "name": "bearAmount", "type": "uint256"},
{"internalType": "uint256", "name": "rewardBaseCalAmount", "type": "uint256"},
{"internalType": "uint256", "name": "rewardAmount", "type": "uint256"},
{"internalType": "int256", "name": "lockPrice", "type": "int256"},
{"internalType": "int256", "name": "closePrice", "type": "int256"},
{"internalType": "uint32", "name": "startTimestamp", "type": "uint32"},
{"internalType": "uint32", "name": "lockTimestamp", "type": "uint32"},
{"internalType": "uint32", "name": "closeTimestamp", "type": "uint32"},
{"internalType": "uint32", "name": "lockPriceTimestamp", "type": "uint32"},
{"internalType": "uint32", "name": "closePriceTimestamp", "type": "uint32"},
{"internalType": "bool", "name": "closed", "type": "bool"},
{"internalType": "bool", "name": "canceled", "type": "bool"}],
"stateMutability": "view", "type": "function"},
{"inputs": [], "name": "currentEpoch",
"outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view",
"type": "function"},
{"inputs": [{"internalType": "uint256", "name": "epoch", "type": "uint256"}], "name": "user_BetBear",
"outputs": [], "stateMutability": "payable", "type": "function"},
{"inputs": [{"internalType": "uint256", "name": "epoch", "type": "uint256"}], "name": "user_BetBull",
"outputs": [], "stateMutability": "payable", "type": "function"},
{"inputs": [{"internalType": "uint256[]", "name": "epochs", "type": "uint256[]"}],
"name": "user_Claim", "outputs": [], "stateMutability": "nonpayable", "type": "function"}]
def clean_terminal():
if platform.system() == "Windows":
subprocess.Popen("cls", shell=True).communicate()
else:
print("\033c", end="")
def header():
print(f"""{bcolors.BOLD} MultiStrategy Prediction Bot{bcolors.ENDC}""")
def is_valid_address(address):
try:
w3.toChecksumAddress(address)
return True
except Exception as e:
return False
def is_valid_key(key):
try:
from eth_account.messages import encode_defunct
message = encode_defunct(text='sign')
w3.eth.account.sign_message(message, private_key=key)
return True
except Exception as e:
return False
def get_tax(txnhash, og):
txnhash = txnhash.get('logs')
txnhash = txnhash[0].get('data')
profit = w3.toInt(hexstr=txnhash)
tax = profit * (og / 100)
tax = round(tax)
return {"tax": tax, "profit": w3.fromWei(profit, "ether")}
def is_number(string):
try:
float(string)
return True
except ValueError:
return False
def time_left_to(bet_time):
sleep_secs = (bet_time - dt.datetime.now()).total_seconds()
if sleep_secs >= 0:
time.sleep(sleep_secs)
def manual_header():
print(f'{bcolors.OKCYAN} Go Bull ({options.go_bull}) | Go Bear ({options.go_bear}) | Change Base Bet (value) '
f'| Quit ({options.restart})'
f' | Do nothing to skip{bcolors.ENDC}')
def non_manual_header():
print(f'{bcolors.OKCYAN} Skip ({options.skip}) | Change Base Bet (value) | Go Manual ({options.go_manual}) |'
f' Quit ({options.restart}) | Do nothing to continue{bcolors.ENDC}')
def copy_player_header():
print(f'{bcolors.OKCYAN} Skip ({options.skip}) | Change Factor (value) | Go Manual ({options.go_manual}) |'
f' Quit ({options.restart}) | Do nothing to continue{bcolors.ENDC}')
def validation():
print(f'{bcolors.HEADER}{37 * "="} SET ACCOUNT {37 * "="}{bcolors.ENDC}\n')
print(f'{49 * " "}(leave blank to enter simulation mode)')
while True:
address = str(input(f'{bcolors.WARNING}Account address:{bcolors.ENDC} '))
if address == '':
print(f'{bcolors.OKCYAN} Simulation Mode')
time.sleep(2)
return {'address': '0x0000000000000000000000000000000000000000', 'key': '', 'simulation': True}
if not is_valid_address(address):
print(f'{bcolors.FAIL}Invalid address{bcolors.ENDC}')
continue
private_key = str(input(f'{bcolors.WARNING}Private key:{bcolors.ENDC} '))
if not is_valid_key(private_key):
print(f'{bcolors.FAIL}Invalid key{bcolors.ENDC}')
continue
break
ADDRESS = Web3.toChecksumAddress(address)
PRIVATE_KEY = str(private_key).lower()
return {'address': ADDRESS, 'key': PRIVATE_KEY, 'simulation': False}
def menu():
print(f'{bcolors.HEADER} Select Strategy{bcolors.ENDC}\n')
sts = ''
for st in strategy_numbers.list:
sts += f' {strategy_numbers.list[st]} ({st}) {(21 - len(strategy_numbers.list[st]))*" "}'
if int(st) % 2 == 0:
sts += '\n'
print(sts)
copy_player_address = ''
while True:
strategy_input = str(input(f'\n{bcolors.WARNING}Strategy Number (1-18):{bcolors.ENDC} '))
if strategy_input.isnumeric():
if int(strategy_input) != 8 and 1 <= int(strategy_input) <= 18:
print(f'{bcolors.OKCYAN} {strategy_numbers.list[strategy_input]} selected{bcolors.ENDC}')
if int(strategy_input) != 6:
is_inverted = str(input(f'{bcolors.WARNING}Invert it? (y/n): {bcolors.ENDC}'))
if is_inverted == 'y':
is_inverted = True
print(f'{bcolors.OKCYAN} Invert mode ON {bcolors.ENDC}')
else:
is_inverted = False
print(f'{bcolors.OKCYAN} Invert mode OFF{bcolors.ENDC}')
else:
is_inverted = False
print(f'{bcolors.OKCYAN} Betting: Percentage of account balance (1) / Fixed Amount (2){bcolors.ENDC}')
bet_type = str(input(f'{bcolors.WARNING}Bet Type (1-2): {bcolors.ENDC}'))
if bet_type == '2':
bet_amount = str(input(f'{bcolors.WARNING}Amount (BNB): {bcolors.ENDC}'))
btype = 'BNB'
elif bet_type == '1':
bet_amount = str(input(f'{bcolors.WARNING}Percentage (0-100): {bcolors.ENDC}'))
btype = '%'
else:
print(f'{bcolors.FAIL} Wrong value, try again{bcolors.ENDC}')
continue
if is_number(bet_amount):
print(f'{bcolors.OKCYAN} {strategy_numbers.list[strategy_input]} strategy '
f'| Base Bet: {bet_amount} {btype}{bcolors.ENDC}\n')
break
else:
print(f'{bcolors.FAIL} Invalid bet amount, try again{bcolors.ENDC}')
elif strategy_input == strategy_numbers.copy_player:
bet_type = '2'
btype = 'BNB'
is_inverted = False
print(f'{bcolors.OKCYAN} {strategy_numbers.list[strategy_input]} selected{bcolors.ENDC}')
copy_player_address = str(input(f'{bcolors.WARNING}Copy player address:{bcolors.ENDC} '))
if is_valid_address(copy_player_address):
print(f'{bcolors.OKCYAN} Copying {copy_player_address} %')
print(
f'{bcolors.OKCYAN} Betting: Percentage of account balance (1) / Fixed Amount (2) / Factor (3){bcolors.ENDC}')
bet_type = str(input(f'{bcolors.WARNING}Bet Type (1-3): {bcolors.ENDC}'))
if bet_type == '2':
bet_amount = str(input(f'{bcolors.WARNING}Amount (BNB): {bcolors.ENDC}'))
btype = 'BNB'
elif bet_type == '1':
bet_amount = str(input(f'{bcolors.WARNING}Percentage (0-100): {bcolors.ENDC}'))
btype = '%'
elif bet_type == '3':
bet_amount = str(
input(f'{bcolors.WARNING}Bet Factor (bet_amount = copyplayer_bet_amount / bet_factor):'
f' {bcolors.ENDC}'))
if is_number(bet_amount):
print(f'{bcolors.OKCYAN} {strategy_numbers.list[strategy_input]} strategy '
f'| Bet Factor: {bet_amount} {bcolors.ENDC}\n')
break
else:
print(f'{bcolors.FAIL} Invalid bet factor, try again')
continue
else:
print(f'{bcolors.FAIL} Wrong value, try again{bcolors.ENDC}')
continue
if is_number(bet_amount):
print(f'{bcolors.OKCYAN} {strategy_numbers.list[strategy_input]} strategy '
f'| Base Bet: {bet_amount} {btype}{bcolors.ENDC}\n')
break
else:
print(f'{bcolors.FAIL} Invalid bet amount, try again{bcolors.ENDC}')
else:
print(f'{bcolors.FAIL} Invalid address, try again')
continue
else:
print(f'{bcolors.FAIL} Unknown command, try again')
continue
else:
print(f'{bcolors.FAIL} Unknown command, try again')
continue
return {'strategy': strategy_input, 'bet_type': bet_type, 'bet_amount': bet_amount,
'copy_player_address': copy_player_address, 'is_inverted': is_inverted}
def get_settings():
settings = {
'SECONDS_LEFT': 10,
'GAS': 400000,
'GAS_PRICE': 5100000000,
}
while True:
print(f'{bcolors.OKCYAN} Choose seconds left to place bets before round locks:{bcolors.ENDC}')
seconds_left = str(input(f'{bcolors.WARNING}(Default: 10) Set seconds:{bcolors.ENDC} '))
if is_number(seconds_left):
if 3 < float(seconds_left):
settings['SECONDS_LEFT'] = float(seconds_left)
print(f'{bcolors.OKCYAN} Betting at {seconds_left} seconds left before round lock{bcolors.ENDC}')
break
else:
print(f'{bcolors.FAIL} Try a number between higher then 3{bcolors.ENDC}')
continue
elif seconds_left == '':
print(f'{bcolors.OKCYAN} Default{bcolors.ENDC}')
print(f'{bcolors.OKCYAN} Betting at 10 seconds left before round lock{bcolors.ENDC}')
break
else:
print(f'{bcolors.FAIL} Try a number higher then 3{bcolors.ENDC}')
continue
return settings
def dapp():
print(f'{bcolors.HEADER}{37 * "="} SELECT DAPP {37 * "="}{bcolors.ENDC}\n')
print(f' '
f' '
f' '
f' {dapps.list[dapps.pancake]} ({dapps.pancake}) | {dapps.list[dapps.dogebets]} ({dapps.dogebets})'
f' ')
while True:
dapp_input = str(input(f'{bcolors.WARNING}Dapp number (1-2):{bcolors.ENDC} '))
if dapp_input.isnumeric():
if 1 <= int(dapp_input) <= 2:
print(f'{bcolors.OKCYAN} {dapps.list[dapp_input]} selected{bcolors.ENDC}')
break
else:
print(f'{bcolors.FAIL} Unknown command, try again')
continue
return dapp_input
def node():
print(f'{bcolors.HEADER}{37 * "="} SET NODE {37 * "="}{bcolors.ENDC}\n')
print(f'(leave blank for default public node)')
node_input = str(input(f'{bcolors.WARNING}Node endpoint:{bcolors.ENDC} '))
if node_input == '':
node_input = 'https://bsc-dataseed1.defibit.io/'
return node_input |
"""Docstring"""
###############################################################################
# IMPORTS ########################################################### IMPORTS #
###############################################################################
# Standard library
import datetime
import binascii
# Installed
import flask
import flask_restful
import jwt
import sqlalchemy
import functools
from sqlalchemy.sql import func
# Own modules
from dds_web import app
from dds_web.database import models
from dds_web.crypt.auth import gen_argon2hash, verify_password_argon2id
###############################################################################
# FUNCTIONS ####################################################### FUNCTIONS #
###############################################################################
def is_facility(username):
"""Checks if the user is a facility or not."""
is_fac, error = (False, "")
print(f"Username: {username}", flush=True)
# Check for user and which table to work in
try:
role = (
models.Role.query.filter(models.Role.username == func.binary(username))
.with_entities(models.Role.facility)
.first()
)
# user = models.Role.query.filter(models.Role.username.is_(username)).first()
# print(user, flush=True)
except sqlalchemy.exc.SQLAlchemyError as sqlerr:
error = f"Database connection failed - {sqlerr}" + str(sqlerr)
else:
# Deny access if there is no such user
if not role or role is None:
is_fac, error = (None, "The user doesn't exist.")
else:
is_fac = role[0]
return is_fac, error
def jwt_token(user_id, is_fac, project_id, project_access=False):
"""Generates and encodes a JWT token."""
token, error = (None, "")
try:
token = jwt.encode(
{
"public_id": user_id,
"facility": is_fac,
"project": {"id": project_id, "verified": project_access},
"exp": datetime.datetime.utcnow() + datetime.timedelta(hours=48),
},
app.config["SECRET_KEY"],
)
except Exception as err:
token, error = (None, str(err))
return token, error
###############################################################################
# ENDPOINTS ####################################################### ENDPOINTS #
###############################################################################
class AuthenticateUser(flask_restful.Resource):
"""Handles the authentication of the user."""
def get(self):
"""Checks the username, password and generates the token."""
# Get username and password from CLI request
auth = flask.request.authorization
if not auth or not auth.username or not auth.password:
return flask.make_response("Could not verify", 401)
# Project not required, will be checked for future operations
args = flask.request.args
if "project" not in args:
project = None
else:
project = args["project"]
# Check if user has facility role
user_is_fac, error = is_facility(username=auth.username)
if user_is_fac is None:
return flask.make_response(error, 500)
# Get user from DB matching the username
try:
table = models.Facility if user_is_fac else models.User
user = table.query.filter(table.username == func.binary(auth.username)).first()
except sqlalchemy.exc.SQLAlchemyError as sqlerr:
return flask.make_response(f"Database connection failed: {sqlerr}", 500)
# Deny access if there is no such user
if not user or user is None:
return flask.make_response(
"User role registered as "
f"'{"facility" if user_is_fac else "user"}' but user account "
f"not found! User denied access: {auth.username}",
500,
)
# Verify user password and generate token
if verify_password_argon2id(user.password, auth.password):
token, error = jwt_token(user_id=user.public_id, is_fac=user_is_fac, project_id=project)
if token is None:
return flask.make_response(error, 500)
# Success - return token
return flask.jsonify({"token": token.decode("UTF-8")})
# Failed - incorrect password
return flask.make_response("Incorrect password!", 401)
| """Docstring"""
###############################################################################
# IMPORTS ########################################################### IMPORTS #
###############################################################################
# Standard library
import datetime
import binascii
# Installed
import flask
import flask_restful
import jwt
import sqlalchemy
import functools
from sqlalchemy.sql import func
# Own modules
from dds_web import app
from dds_web.database import models
from dds_web.crypt.auth import gen_argon2hash, verify_password_argon2id
###############################################################################
# FUNCTIONS ####################################################### FUNCTIONS #
###############################################################################
def is_facility(username):
"""Checks if the user is a facility or not."""
is_fac, error = (False, "")
print(f"Username: {username}", flush=True)
# Check for user and which table to work in
try:
role = (
models.Role.query.filter(models.Role.username == func.binary(username))
.with_entities(models.Role.facility)
.first()
)
# user = models.Role.query.filter(models.Role.username.is_(username)).first()
# print(user, flush=True)
except sqlalchemy.exc.SQLAlchemyError as sqlerr:
error = f"Database connection failed - {sqlerr}" + str(sqlerr)
else:
# Deny access if there is no such user
if not role or role is None:
is_fac, error = (None, "The user doesn't exist.")
else:
is_fac = role[0]
return is_fac, error
def jwt_token(user_id, is_fac, project_id, project_access=False):
"""Generates and encodes a JWT token."""
token, error = (None, "")
try:
token = jwt.encode(
{
"public_id": user_id,
"facility": is_fac,
"project": {"id": project_id, "verified": project_access},
"exp": datetime.datetime.utcnow() + datetime.timedelta(hours=48),
},
app.config["SECRET_KEY"],
)
except Exception as err:
token, error = (None, str(err))
return token, error
###############################################################################
# ENDPOINTS ####################################################### ENDPOINTS #
###############################################################################
class AuthenticateUser(flask_restful.Resource):
"""Handles the authentication of the user."""
def get(self):
"""Checks the username, password and generates the token."""
# Get username and password from CLI request
auth = flask.request.authorization
if not auth or not auth.username or not auth.password:
return flask.make_response("Could not verify", 401)
# Project not required, will be checked for future operations
args = flask.request.args
if "project" not in args:
project = None
else:
project = args["project"]
# Check if user has facility role
user_is_fac, error = is_facility(username=auth.username)
if user_is_fac is None:
return flask.make_response(error, 500)
# Get user from DB matching the username
try:
table = models.Facility if user_is_fac else models.User
user = table.query.filter(table.username == func.binary(auth.username)).first()
except sqlalchemy.exc.SQLAlchemyError as sqlerr:
return flask.make_response(f"Database connection failed: {sqlerr}", 500)
# Deny access if there is no such user
if not user or user is None:
return flask.make_response(
"User role registered as "
f"'{'facility' if user_is_fac else 'user'}' but user account "
f"not found! User denied access: {auth.username}",
500,
)
# Verify user password and generate token
if verify_password_argon2id(user.password, auth.password):
token, error = jwt_token(user_id=user.public_id, is_fac=user_is_fac, project_id=project)
if token is None:
return flask.make_response(error, 500)
# Success - return token
return flask.jsonify({"token": token.decode("UTF-8")})
# Failed - incorrect password
return flask.make_response("Incorrect password!", 401)
|
# Copyright 2020 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Integrations with other Python libraries.
"""
import functools
import importlib.util
import numbers
import os
import sys
import tempfile
from pathlib import Path
from .file_utils import is_datasets_available
from .utils import logging
logger = logging.get_logger(__name__)
# comet_ml requires to be imported before any ML frameworks
_has_comet = importlib.util.find_spec("comet_ml") is not None and os.getenv("COMET_MODE", "").upper() != "DISABLED"
if _has_comet:
try:
import comet_ml # noqa: F401
if hasattr(comet_ml, "config") and comet_ml.config.get_config("comet.api_key"):
_has_comet = True
else:
if os.getenv("COMET_MODE", "").upper() != "DISABLED":
logger.warning("comet_ml is installed but `COMET_API_KEY` is not set.")
_has_comet = False
except (ImportError, ValueError):
_has_comet = False
from .file_utils import ENV_VARS_TRUE_VALUES, is_torch_tpu_available # noqa: E402
from .trainer_callback import ProgressCallback, TrainerCallback # noqa: E402
from .trainer_utils import PREFIX_CHECKPOINT_DIR, BestRun, IntervalStrategy # noqa: E402
# Integration functions:
def is_wandb_available():
# any value of WANDB_DISABLED disables wandb
if os.getenv("WANDB_DISABLED", "").upper() in ENV_VARS_TRUE_VALUES:
logger.warning(
"Using the `WAND_DISABLED` environment variable is deprecated and will be removed in v5. Use the "
"--report_to flag to control the integrations used for logging result (for instance --report_to none)."
)
return False
return importlib.util.find_spec("wandb") is not None
def is_comet_available():
return _has_comet
def is_tensorboard_available():
return importlib.util.find_spec("tensorboard") is not None or importlib.util.find_spec("tensorboardX") is not None
def is_optuna_available():
return importlib.util.find_spec("optuna") is not None
def is_ray_available():
return importlib.util.find_spec("ray") is not None
def is_ray_tune_available():
if not is_ray_available():
return False
return importlib.util.find_spec("ray.tune") is not None
def is_azureml_available():
if importlib.util.find_spec("azureml") is None:
return False
if importlib.util.find_spec("azureml.core") is None:
return False
return importlib.util.find_spec("azureml.core.run") is not None
def is_mlflow_available():
return importlib.util.find_spec("mlflow") is not None
def is_fairscale_available():
return importlib.util.find_spec("fairscale") is not None
def is_neptune_available():
return importlib.util.find_spec("neptune") is not None
def is_codecarbon_available():
return importlib.util.find_spec("codecarbon") is not None
def hp_params(trial):
if is_optuna_available():
import optuna
if isinstance(trial, optuna.Trial):
return trial.params
if is_ray_tune_available():
if isinstance(trial, dict):
return trial
raise RuntimeError(f"Unknown type for trial {trial.__class__}")
def default_hp_search_backend():
if is_optuna_available():
return "optuna"
elif is_ray_tune_available():
return "ray"
def run_hp_search_optuna(trainer, n_trials: int, direction: str, **kwargs) -> BestRun:
import optuna
def _objective(trial, checkpoint_dir=None):
checkpoint = None
if checkpoint_dir:
for subdir in os.listdir(checkpoint_dir):
if subdir.startswith(PREFIX_CHECKPOINT_DIR):
checkpoint = os.path.join(checkpoint_dir, subdir)
trainer.objective = None
trainer.train(resume_from_checkpoint=checkpoint, trial=trial)
# If there hasn't been any evaluation during the training loop.
if getattr(trainer, "objective", None) is None:
metrics = trainer.evaluate()
trainer.objective = trainer.compute_objective(metrics)
return trainer.objective
timeout = kwargs.pop("timeout", None)
n_jobs = kwargs.pop("n_jobs", 1)
study = optuna.create_study(direction=direction, **kwargs)
study.optimize(_objective, n_trials=n_trials, timeout=timeout, n_jobs=n_jobs)
best_trial = study.best_trial
return BestRun(str(best_trial.number), best_trial.value, best_trial.params)
def run_hp_search_ray(trainer, n_trials: int, direction: str, **kwargs) -> BestRun:
import ray
def _objective(trial, local_trainer, checkpoint_dir=None):
try:
from transformers.utils.notebook import NotebookProgressCallback
if local_trainer.pop_callback(NotebookProgressCallback):
local_trainer.add_callback(ProgressCallback)
except ModuleNotFoundError:
pass
checkpoint = None
if checkpoint_dir:
for subdir in os.listdir(checkpoint_dir):
if subdir.startswith(PREFIX_CHECKPOINT_DIR):
checkpoint = os.path.join(checkpoint_dir, subdir)
local_trainer.objective = None
local_trainer.train(resume_from_checkpoint=checkpoint, trial=trial)
# If there hasn't been any evaluation during the training loop.
if getattr(local_trainer, "objective", None) is None:
metrics = local_trainer.evaluate()
local_trainer.objective = local_trainer.compute_objective(metrics)
local_trainer._tune_save_checkpoint()
ray.tune.report(objective=local_trainer.objective, **metrics, done=True)
if not trainer._memory_tracker.skip_memory_metrics:
from .trainer_utils import TrainerMemoryTracker
logger.warning(
"Memory tracking for your Trainer is currently "
"enabled. Automatically disabling the memory tracker "
"since the memory tracker is not serializable."
)
trainer._memory_tracker = TrainerMemoryTracker(skip_memory_metrics=True)
# The model and TensorBoard writer do not pickle so we have to remove them (if they exists)
# while doing the ray hp search.
_tb_writer = trainer.pop_callback(TensorBoardCallback)
trainer.model = None
# Setup default `resources_per_trial`.
if "resources_per_trial" not in kwargs:
# Default to 1 CPU and 1 GPU (if applicable) per trial.
kwargs["resources_per_trial"] = {"cpu": 1}
if trainer.args.n_gpu > 0:
kwargs["resources_per_trial"]["gpu"] = 1
resource_msg = "1 CPU" + (" and 1 GPU" if trainer.args.n_gpu > 0 else "")
logger.info(
"No `resources_per_trial` arg was passed into "
"`hyperparameter_search`. Setting it to a default value "
f"of {resource_msg} for each trial."
)
# Make sure each trainer only uses GPUs that were allocated per trial.
gpus_per_trial = kwargs["resources_per_trial"].get("gpu", 0)
trainer.args._n_gpu = gpus_per_trial
# Setup default `progress_reporter`.
if "progress_reporter" not in kwargs:
from ray.tune import CLIReporter
kwargs["progress_reporter"] = CLIReporter(metric_columns=["objective"])
if "keep_checkpoints_num" in kwargs and kwargs["keep_checkpoints_num"] > 0:
# `keep_checkpoints_num=0` would disabled checkpointing
trainer.use_tune_checkpoints = True
if kwargs["keep_checkpoints_num"] > 1:
logger.warning(
f"Currently keeping {kwargs["keep_checkpoints_num"]} checkpoints for each trial. "
"Checkpoints are usually huge, "
"consider setting `keep_checkpoints_num=1`."
)
if "scheduler" in kwargs:
from ray.tune.schedulers import ASHAScheduler, HyperBandForBOHB, MedianStoppingRule, PopulationBasedTraining
# Check if checkpointing is enabled for PopulationBasedTraining
if isinstance(kwargs["scheduler"], PopulationBasedTraining):
if not trainer.use_tune_checkpoints:
logger.warning(
"You are using PopulationBasedTraining but you haven't enabled checkpointing. "
"This means your trials will train from scratch everytime they are exploiting "
"new configurations. Consider enabling checkpointing by passing "
"`keep_checkpoints_num=1` as an additional argument to `Trainer.hyperparameter_search`."
)
# Check for `do_eval` and `eval_during_training` for schedulers that require intermediate reporting.
if isinstance(
kwargs["scheduler"], (ASHAScheduler, MedianStoppingRule, HyperBandForBOHB, PopulationBasedTraining)
) and (not trainer.args.do_eval or trainer.args.evaluation_strategy == IntervalStrategy.NO):
raise RuntimeError(
"You are using {cls} as a scheduler but you haven't enabled evaluation during training. "
"This means your trials will not report intermediate results to Ray Tune, and "
"can thus not be stopped early or used to exploit other trials parameters. "
"If this is what you want, do not use {cls}. If you would like to use {cls}, "
"make sure you pass `do_eval=True` and `evaluation_strategy='steps'` in the "
"Trainer `args`.".format(cls=type(kwargs["scheduler"]).__name__)
)
trainable = ray.tune.with_parameters(_objective, local_trainer=trainer)
@functools.wraps(trainable)
def dynamic_modules_import_trainable(*args, **kwargs):
"""
Wrapper around ``tune.with_parameters`` to ensure datasets_modules are loaded on each Actor.
Without this, an ImportError will be thrown. See https://github.com/huggingface/transformers/issues/11565.
Assumes that ``_objective``, defined above, is a function.
"""
if is_datasets_available():
import datasets.load
dynamic_modules_path = os.path.join(datasets.load.init_dynamic_modules(), "__init__.py")
# load dynamic_modules from path
spec = importlib.util.spec_from_file_location("datasets_modules", dynamic_modules_path)
datasets_modules = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = datasets_modules
spec.loader.exec_module(datasets_modules)
return trainable(*args, **kwargs)
# special attr set by tune.with_parameters
if hasattr(trainable, "__mixins__"):
dynamic_modules_import_trainable.__mixins__ = trainable.__mixins__
analysis = ray.tune.run(
dynamic_modules_import_trainable,
config=trainer.hp_space(None),
num_samples=n_trials,
**kwargs,
)
best_trial = analysis.get_best_trial(metric="objective", mode=direction[:3])
best_run = BestRun(best_trial.trial_id, best_trial.last_result["objective"], best_trial.config)
if _tb_writer is not None:
trainer.add_callback(_tb_writer)
return best_run
def get_available_reporting_integrations():
integrations = []
if is_azureml_available():
integrations.append("azure_ml")
if is_comet_available():
integrations.append("comet_ml")
if is_mlflow_available():
integrations.append("mlflow")
if is_tensorboard_available():
integrations.append("tensorboard")
if is_wandb_available():
integrations.append("wandb")
if is_codecarbon_available():
integrations.append("codecarbon")
return integrations
def rewrite_logs(d):
new_d = {}
eval_prefix = "eval_"
eval_prefix_len = len(eval_prefix)
for k, v in d.items():
if k.startswith(eval_prefix):
new_d["eval/" + k[eval_prefix_len:]] = v
else:
new_d["train/" + k] = v
return new_d
class TensorBoardCallback(TrainerCallback):
"""
A :class:`~transformers.TrainerCallback` that sends the logs to `TensorBoard
<https://www.tensorflow.org/tensorboard>`__.
Args:
tb_writer (:obj:`SummaryWriter`, `optional`):
The writer to use. Will instantiate one if not set.
"""
def __init__(self, tb_writer=None):
has_tensorboard = is_tensorboard_available()
assert (
has_tensorboard
), "TensorBoardCallback requires tensorboard to be installed. Either update your PyTorch version or install tensorboardX."
if has_tensorboard:
try:
from torch.utils.tensorboard import SummaryWriter # noqa: F401
self._SummaryWriter = SummaryWriter
except ImportError:
try:
from tensorboardX import SummaryWriter
self._SummaryWriter = SummaryWriter
except ImportError:
self._SummaryWriter = None
else:
self._SummaryWriter = None
self.tb_writer = tb_writer
def _init_summary_writer(self, args, log_dir=None):
log_dir = log_dir or args.logging_dir
if self._SummaryWriter is not None:
self.tb_writer = self._SummaryWriter(log_dir=log_dir)
def on_train_begin(self, args, state, control, **kwargs):
if not state.is_world_process_zero:
return
log_dir = None
if state.is_hyper_param_search:
trial_name = state.trial_name
if trial_name is not None:
log_dir = os.path.join(args.logging_dir, trial_name)
self._init_summary_writer(args, log_dir)
if self.tb_writer is not None:
self.tb_writer.add_text("args", args.to_json_string())
if "model" in kwargs:
model = kwargs["model"]
if hasattr(model, "config") and model.config is not None:
model_config_json = model.config.to_json_string()
self.tb_writer.add_text("model_config", model_config_json)
# Version of TensorBoard coming from tensorboardX does not have this method.
if hasattr(self.tb_writer, "add_hparams"):
self.tb_writer.add_hparams(args.to_sanitized_dict(), metric_dict={})
def on_log(self, args, state, control, logs=None, **kwargs):
if not state.is_world_process_zero:
return
if self.tb_writer is None:
self._init_summary_writer(args)
if self.tb_writer is not None:
logs = rewrite_logs(logs)
for k, v in logs.items():
if isinstance(v, (int, float)):
self.tb_writer.add_scalar(k, v, state.global_step)
else:
logger.warning(
"Trainer is attempting to log a value of "
f'"{v}" of type {type(v)} for key "{k}" as a scalar. '
"This invocation of Tensorboard's writer.add_scalar() "
"is incorrect so we dropped this attribute."
)
self.tb_writer.flush()
def on_train_end(self, args, state, control, **kwargs):
if self.tb_writer:
self.tb_writer.close()
self.tb_writer = None
class WandbCallback(TrainerCallback):
"""
A :class:`~transformers.TrainerCallback` that sends the logs to `Weight and Biases <https://www.wandb.com/>`__.
"""
def __init__(self):
has_wandb = is_wandb_available()
assert has_wandb, "WandbCallback requires wandb to be installed. Run `pip install wandb`."
if has_wandb:
import wandb
self._wandb = wandb
self._initialized = False
# log outputs
self._log_model = os.getenv("WANDB_LOG_MODEL", "FALSE").upper() in ENV_VARS_TRUE_VALUES.union({"TRUE"})
def setup(self, args, state, model, **kwargs):
"""
Setup the optional Weights & Biases (`wandb`) integration.
One can subclass and override this method to customize the setup if needed. Find more information `here
<https://docs.wandb.ai/integrations/huggingface>`__. You can also override the following environment variables:
Environment:
WANDB_LOG_MODEL (:obj:`bool`, `optional`, defaults to :obj:`False`):
Whether or not to log model as artifact at the end of training. Use along with
`TrainingArguments.load_best_model_at_end` to upload best model.
WANDB_WATCH (:obj:`str`, `optional` defaults to :obj:`"gradients"`):
Can be :obj:`"gradients"`, :obj:`"all"` or :obj:`"false"`. Set to :obj:`"false"` to disable gradient
logging or :obj:`"all"` to log gradients and parameters.
WANDB_PROJECT (:obj:`str`, `optional`, defaults to :obj:`"huggingface"`):
Set this to a custom string to store results in a different project.
WANDB_DISABLED (:obj:`bool`, `optional`, defaults to :obj:`False`):
Whether or not to disable wandb entirely. Set `WANDB_DISABLED=true` to disable.
"""
if self._wandb is None:
return
self._initialized = True
if state.is_world_process_zero:
logger.info(
'Automatic Weights & Biases logging enabled, to disable set os.environ["WANDB_DISABLED"] = "true"'
)
combined_dict = {**args.to_sanitized_dict()}
if hasattr(model, "config") and model.config is not None:
model_config = model.config.to_dict()
combined_dict = {**model_config, **combined_dict}
trial_name = state.trial_name
init_args = {}
if trial_name is not None:
run_name = trial_name
init_args["group"] = args.run_name
else:
run_name = args.run_name
if self._wandb.run is None:
self._wandb.init(
project=os.getenv("WANDB_PROJECT", "huggingface"),
name=run_name,
**init_args,
)
# add config parameters (run may have been created manually)
self._wandb.config.update(combined_dict, allow_val_change=True)
# define default x-axis (for latest wandb versions)
if getattr(self._wandb, "define_metric", None):
self._wandb.define_metric("train/global_step")
self._wandb.define_metric("*", step_metric="train/global_step", step_sync=True)
# keep track of model topology and gradients, unsupported on TPU
if not is_torch_tpu_available() and os.getenv("WANDB_WATCH") != "false":
self._wandb.watch(
model, log=os.getenv("WANDB_WATCH", "gradients"), log_freq=max(100, args.logging_steps)
)
def on_train_begin(self, args, state, control, model=None, **kwargs):
if self._wandb is None:
return
hp_search = state.is_hyper_param_search
if hp_search:
self._wandb.finish()
self._initialized = False
if not self._initialized:
self.setup(args, state, model, **kwargs)
def on_train_end(self, args, state, control, model=None, tokenizer=None, **kwargs):
if self._wandb is None:
return
if self._log_model and self._initialized and state.is_world_process_zero:
from .trainer import Trainer
fake_trainer = Trainer(args=args, model=model, tokenizer=tokenizer)
with tempfile.TemporaryDirectory() as temp_dir:
fake_trainer.save_model(temp_dir)
metadata = (
{
k: v
for k, v in dict(self._wandb.summary).items()
if isinstance(v, numbers.Number) and not k.startswith("_")
}
if not args.load_best_model_at_end
else {
f"eval/{args.metric_for_best_model}": state.best_metric,
"train/total_floss": state.total_flos,
}
)
artifact = self._wandb.Artifact(name=f"model-{self._wandb.run.id}", type="model", metadata=metadata)
for f in Path(temp_dir).glob("*"):
if f.is_file():
with artifact.new_file(f.name, mode="wb") as fa:
fa.write(f.read_bytes())
self._wandb.run.log_artifact(artifact)
def on_log(self, args, state, control, model=None, logs=None, **kwargs):
if self._wandb is None:
return
if not self._initialized:
self.setup(args, state, model)
if state.is_world_process_zero:
logs = rewrite_logs(logs)
self._wandb.log({**logs, "train/global_step": state.global_step})
class CometCallback(TrainerCallback):
"""
A :class:`~transformers.TrainerCallback` that sends the logs to `Comet ML <https://www.comet.ml/site/>`__.
"""
def __init__(self):
assert _has_comet, "CometCallback requires comet-ml to be installed. Run `pip install comet-ml`."
self._initialized = False
def setup(self, args, state, model):
"""
Setup the optional Comet.ml integration.
Environment:
COMET_MODE (:obj:`str`, `optional`):
"OFFLINE", "ONLINE", or "DISABLED"
COMET_PROJECT_NAME (:obj:`str`, `optional`):
Comet.ml project name for experiments
COMET_OFFLINE_DIRECTORY (:obj:`str`, `optional`):
Folder to use for saving offline experiments when :obj:`COMET_MODE` is "OFFLINE"
For a number of configurable items in the environment, see `here
<https://www.comet.ml/docs/python-sdk/advanced/#comet-configuration-variables>`__.
"""
self._initialized = True
if state.is_world_process_zero:
comet_mode = os.getenv("COMET_MODE", "ONLINE").upper()
args = {"project_name": os.getenv("COMET_PROJECT_NAME", "huggingface")}
experiment = None
if comet_mode == "ONLINE":
experiment = comet_ml.Experiment(**args)
logger.info("Automatic Comet.ml online logging enabled")
elif comet_mode == "OFFLINE":
args["offline_directory"] = os.getenv("COMET_OFFLINE_DIRECTORY", "./")
experiment = comet_ml.OfflineExperiment(**args)
logger.info("Automatic Comet.ml offline logging enabled; use `comet upload` when finished")
if experiment is not None:
experiment._set_model_graph(model, framework="transformers")
experiment._log_parameters(args, prefix="args/", framework="transformers")
if hasattr(model, "config"):
experiment._log_parameters(model.config, prefix="config/", framework="transformers")
def on_train_begin(self, args, state, control, model=None, **kwargs):
if not self._initialized:
self.setup(args, state, model)
def on_log(self, args, state, control, model=None, logs=None, **kwargs):
if not self._initialized:
self.setup(args, state, model)
if state.is_world_process_zero:
experiment = comet_ml.config.get_global_experiment()
if experiment is not None:
experiment._log_metrics(logs, step=state.global_step, epoch=state.epoch, framework="transformers")
class AzureMLCallback(TrainerCallback):
"""
A :class:`~transformers.TrainerCallback` that sends the logs to `AzureML
<https://pypi.org/project/azureml-sdk/>`__.
"""
def __init__(self, azureml_run=None):
assert (
is_azureml_available()
), "AzureMLCallback requires azureml to be installed. Run `pip install azureml-sdk`."
self.azureml_run = azureml_run
def on_init_end(self, args, state, control, **kwargs):
from azureml.core.run import Run
if self.azureml_run is None and state.is_world_process_zero:
self.azureml_run = Run.get_context()
def on_log(self, args, state, control, logs=None, **kwargs):
if self.azureml_run and state.is_world_process_zero:
for k, v in logs.items():
if isinstance(v, (int, float)):
self.azureml_run.log(k, v, description=k)
class MLflowCallback(TrainerCallback):
"""
A :class:`~transformers.TrainerCallback` that sends the logs to `MLflow <https://www.mlflow.org/>`__.
"""
def __init__(self):
assert is_mlflow_available(), "MLflowCallback requires mlflow to be installed. Run `pip install mlflow`."
import mlflow
self._MAX_PARAM_VAL_LENGTH = mlflow.utils.validation.MAX_PARAM_VAL_LENGTH
self._MAX_PARAMS_TAGS_PER_BATCH = mlflow.utils.validation.MAX_PARAMS_TAGS_PER_BATCH
self._initialized = False
self._log_artifacts = False
self._ml_flow = mlflow
def setup(self, args, state, model):
"""
Setup the optional MLflow integration.
Environment:
HF_MLFLOW_LOG_ARTIFACTS (:obj:`str`, `optional`):
Whether to use MLflow .log_artifact() facility to log artifacts.
This only makes sense if logging to a remote server, e.g. s3 or GCS. If set to `True` or `1`, will copy
whatever is in :class:`~transformers.TrainingArguments`'s ``output_dir`` to the local or remote
artifact storage. Using it without a remote storage will just copy the files to your artifact location.
"""
log_artifacts = os.getenv("HF_MLFLOW_LOG_ARTIFACTS", "FALSE").upper()
if log_artifacts in {"TRUE", "1"}:
self._log_artifacts = True
if state.is_world_process_zero:
self._ml_flow.start_run()
combined_dict = args.to_dict()
if hasattr(model, "config") and model.config is not None:
model_config = model.config.to_dict()
combined_dict = {**model_config, **combined_dict}
# remove params that are too long for MLflow
for name, value in list(combined_dict.items()):
# internally, all values are converted to str in MLflow
if len(str(value)) > self._MAX_PARAM_VAL_LENGTH:
logger.warning(
f"Trainer is attempting to log a value of "
f'"{value}" for key "{name}" as a parameter. '
f"MLflow's log_param() only accepts values no longer than "
f"250 characters so we dropped this attribute."
)
del combined_dict[name]
# MLflow cannot log more than 100 values in one go, so we have to split it
combined_dict_items = list(combined_dict.items())
for i in range(0, len(combined_dict_items), self._MAX_PARAMS_TAGS_PER_BATCH):
self._ml_flow.log_params(dict(combined_dict_items[i : i + self._MAX_PARAMS_TAGS_PER_BATCH]))
self._initialized = True
def on_train_begin(self, args, state, control, model=None, **kwargs):
if not self._initialized:
self.setup(args, state, model)
def on_log(self, args, state, control, logs, model=None, **kwargs):
if not self._initialized:
self.setup(args, state, model)
if state.is_world_process_zero:
for k, v in logs.items():
if isinstance(v, (int, float)):
self._ml_flow.log_metric(k, v, step=state.global_step)
else:
logger.warning(
f"Trainer is attempting to log a value of "
f'"{v}" of type {type(v)} for key "{k}" as a metric. '
f"MLflow's log_metric() only accepts float and "
f"int types so we dropped this attribute."
)
def on_train_end(self, args, state, control, **kwargs):
if self._initialized and state.is_world_process_zero:
if self._log_artifacts:
logger.info("Logging artifacts. This may take time.")
self._ml_flow.log_artifacts(args.output_dir)
def __del__(self):
# if the previous run is not terminated correctly, the fluent API will
# not let you start a new run before the previous one is killed
if self._ml_flow.active_run is not None:
self._ml_flow.end_run()
class NeptuneCallback(TrainerCallback):
"""
A :class:`~transformers.TrainerCallback` that sends the logs to `Neptune <https://neptune.ai>`.
"""
def __init__(self):
assert (
is_neptune_available()
), "NeptuneCallback requires neptune-client to be installed. Run `pip install neptune-client`."
import neptune.new as neptune
self._neptune = neptune
self._initialized = False
self._log_artifacts = False
def setup(self, args, state, model):
"""
Setup the Neptune integration.
Environment:
NEPTUNE_PROJECT (:obj:`str`, `required`):
The project ID for neptune.ai account. Should be in format `workspace_name/project_name`
NEPTUNE_API_TOKEN (:obj:`str`, `required`):
API-token for neptune.ai account
NEPTUNE_CONNECTION_MODE (:obj:`str`, `optional`):
Neptune connection mode. `async` by default
NEPTUNE_RUN_NAME (:obj:`str`, `optional`):
The name of run process on Neptune dashboard
"""
if state.is_world_process_zero:
self._neptune_run = self._neptune.init(
project=os.getenv("NEPTUNE_PROJECT"),
api_token=os.getenv("NEPTUNE_API_TOKEN"),
mode=os.getenv("NEPTUNE_CONNECTION_MODE", "async"),
name=os.getenv("NEPTUNE_RUN_NAME", None),
)
combined_dict = args.to_dict()
if hasattr(model, "config") and model.config is not None:
model_config = model.config.to_dict()
combined_dict = {**model_config, **combined_dict}
self._neptune_run["parameters"] = combined_dict
self._initialized = True
def on_train_begin(self, args, state, control, model=None, **kwargs):
if not self._initialized:
self.setup(args, state, model)
def on_log(self, args, state, control, logs, model=None, **kwargs):
if not self._initialized:
self.setup(args, state, model)
if state.is_world_process_zero:
for k, v in logs.items():
self._neptune_run[k].log(v, step=state.global_step)
def __del__(self):
"""
Environment:
NEPTUNE_STOP_TIMEOUT (:obj:`int`, `optional`):
Number of seconsds to wait for all Neptune.ai tracking calls to finish, before stopping the tracked
run. If not set it will wait for all tracking calls to finish.
"""
try:
stop_timeout = os.getenv("NEPTUNE_STOP_TIMEOUT")
stop_timeout = int(stop_timeout) if stop_timeout else None
self._neptune_run.stop(seconds=stop_timeout)
except AttributeError:
pass
class CodeCarbonCallback(TrainerCallback):
"""
A :class:`~transformers.TrainerCallback` that tracks the CO2 emission of training.
"""
def __init__(self):
assert (
is_codecarbon_available()
), "CodeCarbonCallback requires `codecarbon` to be installed. Run `pip install codecarbon`."
import codecarbon
self._codecarbon = codecarbon
self.tracker = None
def on_init_end(self, args, state, control, **kwargs):
if self.tracker is None and state.is_local_process_zero:
# CodeCarbon will automatically handle environment variables for configuration
self.tracker = self._codecarbon.EmissionsTracker(output_dir=args.output_dir)
def on_train_begin(self, args, state, control, model=None, **kwargs):
if self.tracker and state.is_local_process_zero:
self.tracker.start()
def on_train_end(self, args, state, control, **kwargs):
if self.tracker and state.is_local_process_zero:
self.tracker.stop()
INTEGRATION_TO_CALLBACK = {
"azure_ml": AzureMLCallback,
"comet_ml": CometCallback,
"mlflow": MLflowCallback,
"neptune": NeptuneCallback,
"tensorboard": TensorBoardCallback,
"wandb": WandbCallback,
"codecarbon": CodeCarbonCallback,
}
def get_reporting_integration_callbacks(report_to):
for integration in report_to:
if integration not in INTEGRATION_TO_CALLBACK:
raise ValueError(
f"{integration} is not supported, only {", ".join(INTEGRATION_TO_CALLBACK.keys())} are supported."
)
return [INTEGRATION_TO_CALLBACK[integration] for integration in report_to]
| # Copyright 2020 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Integrations with other Python libraries.
"""
import functools
import importlib.util
import numbers
import os
import sys
import tempfile
from pathlib import Path
from .file_utils import is_datasets_available
from .utils import logging
logger = logging.get_logger(__name__)
# comet_ml requires to be imported before any ML frameworks
_has_comet = importlib.util.find_spec("comet_ml") is not None and os.getenv("COMET_MODE", "").upper() != "DISABLED"
if _has_comet:
try:
import comet_ml # noqa: F401
if hasattr(comet_ml, "config") and comet_ml.config.get_config("comet.api_key"):
_has_comet = True
else:
if os.getenv("COMET_MODE", "").upper() != "DISABLED":
logger.warning("comet_ml is installed but `COMET_API_KEY` is not set.")
_has_comet = False
except (ImportError, ValueError):
_has_comet = False
from .file_utils import ENV_VARS_TRUE_VALUES, is_torch_tpu_available # noqa: E402
from .trainer_callback import ProgressCallback, TrainerCallback # noqa: E402
from .trainer_utils import PREFIX_CHECKPOINT_DIR, BestRun, IntervalStrategy # noqa: E402
# Integration functions:
def is_wandb_available():
# any value of WANDB_DISABLED disables wandb
if os.getenv("WANDB_DISABLED", "").upper() in ENV_VARS_TRUE_VALUES:
logger.warning(
"Using the `WAND_DISABLED` environment variable is deprecated and will be removed in v5. Use the "
"--report_to flag to control the integrations used for logging result (for instance --report_to none)."
)
return False
return importlib.util.find_spec("wandb") is not None
def is_comet_available():
return _has_comet
def is_tensorboard_available():
return importlib.util.find_spec("tensorboard") is not None or importlib.util.find_spec("tensorboardX") is not None
def is_optuna_available():
return importlib.util.find_spec("optuna") is not None
def is_ray_available():
return importlib.util.find_spec("ray") is not None
def is_ray_tune_available():
if not is_ray_available():
return False
return importlib.util.find_spec("ray.tune") is not None
def is_azureml_available():
if importlib.util.find_spec("azureml") is None:
return False
if importlib.util.find_spec("azureml.core") is None:
return False
return importlib.util.find_spec("azureml.core.run") is not None
def is_mlflow_available():
return importlib.util.find_spec("mlflow") is not None
def is_fairscale_available():
return importlib.util.find_spec("fairscale") is not None
def is_neptune_available():
return importlib.util.find_spec("neptune") is not None
def is_codecarbon_available():
return importlib.util.find_spec("codecarbon") is not None
def hp_params(trial):
if is_optuna_available():
import optuna
if isinstance(trial, optuna.Trial):
return trial.params
if is_ray_tune_available():
if isinstance(trial, dict):
return trial
raise RuntimeError(f"Unknown type for trial {trial.__class__}")
def default_hp_search_backend():
if is_optuna_available():
return "optuna"
elif is_ray_tune_available():
return "ray"
def run_hp_search_optuna(trainer, n_trials: int, direction: str, **kwargs) -> BestRun:
import optuna
def _objective(trial, checkpoint_dir=None):
checkpoint = None
if checkpoint_dir:
for subdir in os.listdir(checkpoint_dir):
if subdir.startswith(PREFIX_CHECKPOINT_DIR):
checkpoint = os.path.join(checkpoint_dir, subdir)
trainer.objective = None
trainer.train(resume_from_checkpoint=checkpoint, trial=trial)
# If there hasn't been any evaluation during the training loop.
if getattr(trainer, "objective", None) is None:
metrics = trainer.evaluate()
trainer.objective = trainer.compute_objective(metrics)
return trainer.objective
timeout = kwargs.pop("timeout", None)
n_jobs = kwargs.pop("n_jobs", 1)
study = optuna.create_study(direction=direction, **kwargs)
study.optimize(_objective, n_trials=n_trials, timeout=timeout, n_jobs=n_jobs)
best_trial = study.best_trial
return BestRun(str(best_trial.number), best_trial.value, best_trial.params)
def run_hp_search_ray(trainer, n_trials: int, direction: str, **kwargs) -> BestRun:
import ray
def _objective(trial, local_trainer, checkpoint_dir=None):
try:
from transformers.utils.notebook import NotebookProgressCallback
if local_trainer.pop_callback(NotebookProgressCallback):
local_trainer.add_callback(ProgressCallback)
except ModuleNotFoundError:
pass
checkpoint = None
if checkpoint_dir:
for subdir in os.listdir(checkpoint_dir):
if subdir.startswith(PREFIX_CHECKPOINT_DIR):
checkpoint = os.path.join(checkpoint_dir, subdir)
local_trainer.objective = None
local_trainer.train(resume_from_checkpoint=checkpoint, trial=trial)
# If there hasn't been any evaluation during the training loop.
if getattr(local_trainer, "objective", None) is None:
metrics = local_trainer.evaluate()
local_trainer.objective = local_trainer.compute_objective(metrics)
local_trainer._tune_save_checkpoint()
ray.tune.report(objective=local_trainer.objective, **metrics, done=True)
if not trainer._memory_tracker.skip_memory_metrics:
from .trainer_utils import TrainerMemoryTracker
logger.warning(
"Memory tracking for your Trainer is currently "
"enabled. Automatically disabling the memory tracker "
"since the memory tracker is not serializable."
)
trainer._memory_tracker = TrainerMemoryTracker(skip_memory_metrics=True)
# The model and TensorBoard writer do not pickle so we have to remove them (if they exists)
# while doing the ray hp search.
_tb_writer = trainer.pop_callback(TensorBoardCallback)
trainer.model = None
# Setup default `resources_per_trial`.
if "resources_per_trial" not in kwargs:
# Default to 1 CPU and 1 GPU (if applicable) per trial.
kwargs["resources_per_trial"] = {"cpu": 1}
if trainer.args.n_gpu > 0:
kwargs["resources_per_trial"]["gpu"] = 1
resource_msg = "1 CPU" + (" and 1 GPU" if trainer.args.n_gpu > 0 else "")
logger.info(
"No `resources_per_trial` arg was passed into "
"`hyperparameter_search`. Setting it to a default value "
f"of {resource_msg} for each trial."
)
# Make sure each trainer only uses GPUs that were allocated per trial.
gpus_per_trial = kwargs["resources_per_trial"].get("gpu", 0)
trainer.args._n_gpu = gpus_per_trial
# Setup default `progress_reporter`.
if "progress_reporter" not in kwargs:
from ray.tune import CLIReporter
kwargs["progress_reporter"] = CLIReporter(metric_columns=["objective"])
if "keep_checkpoints_num" in kwargs and kwargs["keep_checkpoints_num"] > 0:
# `keep_checkpoints_num=0` would disabled checkpointing
trainer.use_tune_checkpoints = True
if kwargs["keep_checkpoints_num"] > 1:
logger.warning(
f"Currently keeping {kwargs['keep_checkpoints_num']} checkpoints for each trial. "
"Checkpoints are usually huge, "
"consider setting `keep_checkpoints_num=1`."
)
if "scheduler" in kwargs:
from ray.tune.schedulers import ASHAScheduler, HyperBandForBOHB, MedianStoppingRule, PopulationBasedTraining
# Check if checkpointing is enabled for PopulationBasedTraining
if isinstance(kwargs["scheduler"], PopulationBasedTraining):
if not trainer.use_tune_checkpoints:
logger.warning(
"You are using PopulationBasedTraining but you haven't enabled checkpointing. "
"This means your trials will train from scratch everytime they are exploiting "
"new configurations. Consider enabling checkpointing by passing "
"`keep_checkpoints_num=1` as an additional argument to `Trainer.hyperparameter_search`."
)
# Check for `do_eval` and `eval_during_training` for schedulers that require intermediate reporting.
if isinstance(
kwargs["scheduler"], (ASHAScheduler, MedianStoppingRule, HyperBandForBOHB, PopulationBasedTraining)
) and (not trainer.args.do_eval or trainer.args.evaluation_strategy == IntervalStrategy.NO):
raise RuntimeError(
"You are using {cls} as a scheduler but you haven't enabled evaluation during training. "
"This means your trials will not report intermediate results to Ray Tune, and "
"can thus not be stopped early or used to exploit other trials parameters. "
"If this is what you want, do not use {cls}. If you would like to use {cls}, "
"make sure you pass `do_eval=True` and `evaluation_strategy='steps'` in the "
"Trainer `args`.".format(cls=type(kwargs["scheduler"]).__name__)
)
trainable = ray.tune.with_parameters(_objective, local_trainer=trainer)
@functools.wraps(trainable)
def dynamic_modules_import_trainable(*args, **kwargs):
"""
Wrapper around ``tune.with_parameters`` to ensure datasets_modules are loaded on each Actor.
Without this, an ImportError will be thrown. See https://github.com/huggingface/transformers/issues/11565.
Assumes that ``_objective``, defined above, is a function.
"""
if is_datasets_available():
import datasets.load
dynamic_modules_path = os.path.join(datasets.load.init_dynamic_modules(), "__init__.py")
# load dynamic_modules from path
spec = importlib.util.spec_from_file_location("datasets_modules", dynamic_modules_path)
datasets_modules = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = datasets_modules
spec.loader.exec_module(datasets_modules)
return trainable(*args, **kwargs)
# special attr set by tune.with_parameters
if hasattr(trainable, "__mixins__"):
dynamic_modules_import_trainable.__mixins__ = trainable.__mixins__
analysis = ray.tune.run(
dynamic_modules_import_trainable,
config=trainer.hp_space(None),
num_samples=n_trials,
**kwargs,
)
best_trial = analysis.get_best_trial(metric="objective", mode=direction[:3])
best_run = BestRun(best_trial.trial_id, best_trial.last_result["objective"], best_trial.config)
if _tb_writer is not None:
trainer.add_callback(_tb_writer)
return best_run
def get_available_reporting_integrations():
integrations = []
if is_azureml_available():
integrations.append("azure_ml")
if is_comet_available():
integrations.append("comet_ml")
if is_mlflow_available():
integrations.append("mlflow")
if is_tensorboard_available():
integrations.append("tensorboard")
if is_wandb_available():
integrations.append("wandb")
if is_codecarbon_available():
integrations.append("codecarbon")
return integrations
def rewrite_logs(d):
new_d = {}
eval_prefix = "eval_"
eval_prefix_len = len(eval_prefix)
for k, v in d.items():
if k.startswith(eval_prefix):
new_d["eval/" + k[eval_prefix_len:]] = v
else:
new_d["train/" + k] = v
return new_d
class TensorBoardCallback(TrainerCallback):
"""
A :class:`~transformers.TrainerCallback` that sends the logs to `TensorBoard
<https://www.tensorflow.org/tensorboard>`__.
Args:
tb_writer (:obj:`SummaryWriter`, `optional`):
The writer to use. Will instantiate one if not set.
"""
def __init__(self, tb_writer=None):
has_tensorboard = is_tensorboard_available()
assert (
has_tensorboard
), "TensorBoardCallback requires tensorboard to be installed. Either update your PyTorch version or install tensorboardX."
if has_tensorboard:
try:
from torch.utils.tensorboard import SummaryWriter # noqa: F401
self._SummaryWriter = SummaryWriter
except ImportError:
try:
from tensorboardX import SummaryWriter
self._SummaryWriter = SummaryWriter
except ImportError:
self._SummaryWriter = None
else:
self._SummaryWriter = None
self.tb_writer = tb_writer
def _init_summary_writer(self, args, log_dir=None):
log_dir = log_dir or args.logging_dir
if self._SummaryWriter is not None:
self.tb_writer = self._SummaryWriter(log_dir=log_dir)
def on_train_begin(self, args, state, control, **kwargs):
if not state.is_world_process_zero:
return
log_dir = None
if state.is_hyper_param_search:
trial_name = state.trial_name
if trial_name is not None:
log_dir = os.path.join(args.logging_dir, trial_name)
self._init_summary_writer(args, log_dir)
if self.tb_writer is not None:
self.tb_writer.add_text("args", args.to_json_string())
if "model" in kwargs:
model = kwargs["model"]
if hasattr(model, "config") and model.config is not None:
model_config_json = model.config.to_json_string()
self.tb_writer.add_text("model_config", model_config_json)
# Version of TensorBoard coming from tensorboardX does not have this method.
if hasattr(self.tb_writer, "add_hparams"):
self.tb_writer.add_hparams(args.to_sanitized_dict(), metric_dict={})
def on_log(self, args, state, control, logs=None, **kwargs):
if not state.is_world_process_zero:
return
if self.tb_writer is None:
self._init_summary_writer(args)
if self.tb_writer is not None:
logs = rewrite_logs(logs)
for k, v in logs.items():
if isinstance(v, (int, float)):
self.tb_writer.add_scalar(k, v, state.global_step)
else:
logger.warning(
"Trainer is attempting to log a value of "
f'"{v}" of type {type(v)} for key "{k}" as a scalar. '
"This invocation of Tensorboard's writer.add_scalar() "
"is incorrect so we dropped this attribute."
)
self.tb_writer.flush()
def on_train_end(self, args, state, control, **kwargs):
if self.tb_writer:
self.tb_writer.close()
self.tb_writer = None
class WandbCallback(TrainerCallback):
"""
A :class:`~transformers.TrainerCallback` that sends the logs to `Weight and Biases <https://www.wandb.com/>`__.
"""
def __init__(self):
has_wandb = is_wandb_available()
assert has_wandb, "WandbCallback requires wandb to be installed. Run `pip install wandb`."
if has_wandb:
import wandb
self._wandb = wandb
self._initialized = False
# log outputs
self._log_model = os.getenv("WANDB_LOG_MODEL", "FALSE").upper() in ENV_VARS_TRUE_VALUES.union({"TRUE"})
def setup(self, args, state, model, **kwargs):
"""
Setup the optional Weights & Biases (`wandb`) integration.
One can subclass and override this method to customize the setup if needed. Find more information `here
<https://docs.wandb.ai/integrations/huggingface>`__. You can also override the following environment variables:
Environment:
WANDB_LOG_MODEL (:obj:`bool`, `optional`, defaults to :obj:`False`):
Whether or not to log model as artifact at the end of training. Use along with
`TrainingArguments.load_best_model_at_end` to upload best model.
WANDB_WATCH (:obj:`str`, `optional` defaults to :obj:`"gradients"`):
Can be :obj:`"gradients"`, :obj:`"all"` or :obj:`"false"`. Set to :obj:`"false"` to disable gradient
logging or :obj:`"all"` to log gradients and parameters.
WANDB_PROJECT (:obj:`str`, `optional`, defaults to :obj:`"huggingface"`):
Set this to a custom string to store results in a different project.
WANDB_DISABLED (:obj:`bool`, `optional`, defaults to :obj:`False`):
Whether or not to disable wandb entirely. Set `WANDB_DISABLED=true` to disable.
"""
if self._wandb is None:
return
self._initialized = True
if state.is_world_process_zero:
logger.info(
'Automatic Weights & Biases logging enabled, to disable set os.environ["WANDB_DISABLED"] = "true"'
)
combined_dict = {**args.to_sanitized_dict()}
if hasattr(model, "config") and model.config is not None:
model_config = model.config.to_dict()
combined_dict = {**model_config, **combined_dict}
trial_name = state.trial_name
init_args = {}
if trial_name is not None:
run_name = trial_name
init_args["group"] = args.run_name
else:
run_name = args.run_name
if self._wandb.run is None:
self._wandb.init(
project=os.getenv("WANDB_PROJECT", "huggingface"),
name=run_name,
**init_args,
)
# add config parameters (run may have been created manually)
self._wandb.config.update(combined_dict, allow_val_change=True)
# define default x-axis (for latest wandb versions)
if getattr(self._wandb, "define_metric", None):
self._wandb.define_metric("train/global_step")
self._wandb.define_metric("*", step_metric="train/global_step", step_sync=True)
# keep track of model topology and gradients, unsupported on TPU
if not is_torch_tpu_available() and os.getenv("WANDB_WATCH") != "false":
self._wandb.watch(
model, log=os.getenv("WANDB_WATCH", "gradients"), log_freq=max(100, args.logging_steps)
)
def on_train_begin(self, args, state, control, model=None, **kwargs):
if self._wandb is None:
return
hp_search = state.is_hyper_param_search
if hp_search:
self._wandb.finish()
self._initialized = False
if not self._initialized:
self.setup(args, state, model, **kwargs)
def on_train_end(self, args, state, control, model=None, tokenizer=None, **kwargs):
if self._wandb is None:
return
if self._log_model and self._initialized and state.is_world_process_zero:
from .trainer import Trainer
fake_trainer = Trainer(args=args, model=model, tokenizer=tokenizer)
with tempfile.TemporaryDirectory() as temp_dir:
fake_trainer.save_model(temp_dir)
metadata = (
{
k: v
for k, v in dict(self._wandb.summary).items()
if isinstance(v, numbers.Number) and not k.startswith("_")
}
if not args.load_best_model_at_end
else {
f"eval/{args.metric_for_best_model}": state.best_metric,
"train/total_floss": state.total_flos,
}
)
artifact = self._wandb.Artifact(name=f"model-{self._wandb.run.id}", type="model", metadata=metadata)
for f in Path(temp_dir).glob("*"):
if f.is_file():
with artifact.new_file(f.name, mode="wb") as fa:
fa.write(f.read_bytes())
self._wandb.run.log_artifact(artifact)
def on_log(self, args, state, control, model=None, logs=None, **kwargs):
if self._wandb is None:
return
if not self._initialized:
self.setup(args, state, model)
if state.is_world_process_zero:
logs = rewrite_logs(logs)
self._wandb.log({**logs, "train/global_step": state.global_step})
class CometCallback(TrainerCallback):
"""
A :class:`~transformers.TrainerCallback` that sends the logs to `Comet ML <https://www.comet.ml/site/>`__.
"""
def __init__(self):
assert _has_comet, "CometCallback requires comet-ml to be installed. Run `pip install comet-ml`."
self._initialized = False
def setup(self, args, state, model):
"""
Setup the optional Comet.ml integration.
Environment:
COMET_MODE (:obj:`str`, `optional`):
"OFFLINE", "ONLINE", or "DISABLED"
COMET_PROJECT_NAME (:obj:`str`, `optional`):
Comet.ml project name for experiments
COMET_OFFLINE_DIRECTORY (:obj:`str`, `optional`):
Folder to use for saving offline experiments when :obj:`COMET_MODE` is "OFFLINE"
For a number of configurable items in the environment, see `here
<https://www.comet.ml/docs/python-sdk/advanced/#comet-configuration-variables>`__.
"""
self._initialized = True
if state.is_world_process_zero:
comet_mode = os.getenv("COMET_MODE", "ONLINE").upper()
args = {"project_name": os.getenv("COMET_PROJECT_NAME", "huggingface")}
experiment = None
if comet_mode == "ONLINE":
experiment = comet_ml.Experiment(**args)
logger.info("Automatic Comet.ml online logging enabled")
elif comet_mode == "OFFLINE":
args["offline_directory"] = os.getenv("COMET_OFFLINE_DIRECTORY", "./")
experiment = comet_ml.OfflineExperiment(**args)
logger.info("Automatic Comet.ml offline logging enabled; use `comet upload` when finished")
if experiment is not None:
experiment._set_model_graph(model, framework="transformers")
experiment._log_parameters(args, prefix="args/", framework="transformers")
if hasattr(model, "config"):
experiment._log_parameters(model.config, prefix="config/", framework="transformers")
def on_train_begin(self, args, state, control, model=None, **kwargs):
if not self._initialized:
self.setup(args, state, model)
def on_log(self, args, state, control, model=None, logs=None, **kwargs):
if not self._initialized:
self.setup(args, state, model)
if state.is_world_process_zero:
experiment = comet_ml.config.get_global_experiment()
if experiment is not None:
experiment._log_metrics(logs, step=state.global_step, epoch=state.epoch, framework="transformers")
class AzureMLCallback(TrainerCallback):
"""
A :class:`~transformers.TrainerCallback` that sends the logs to `AzureML
<https://pypi.org/project/azureml-sdk/>`__.
"""
def __init__(self, azureml_run=None):
assert (
is_azureml_available()
), "AzureMLCallback requires azureml to be installed. Run `pip install azureml-sdk`."
self.azureml_run = azureml_run
def on_init_end(self, args, state, control, **kwargs):
from azureml.core.run import Run
if self.azureml_run is None and state.is_world_process_zero:
self.azureml_run = Run.get_context()
def on_log(self, args, state, control, logs=None, **kwargs):
if self.azureml_run and state.is_world_process_zero:
for k, v in logs.items():
if isinstance(v, (int, float)):
self.azureml_run.log(k, v, description=k)
class MLflowCallback(TrainerCallback):
"""
A :class:`~transformers.TrainerCallback` that sends the logs to `MLflow <https://www.mlflow.org/>`__.
"""
def __init__(self):
assert is_mlflow_available(), "MLflowCallback requires mlflow to be installed. Run `pip install mlflow`."
import mlflow
self._MAX_PARAM_VAL_LENGTH = mlflow.utils.validation.MAX_PARAM_VAL_LENGTH
self._MAX_PARAMS_TAGS_PER_BATCH = mlflow.utils.validation.MAX_PARAMS_TAGS_PER_BATCH
self._initialized = False
self._log_artifacts = False
self._ml_flow = mlflow
def setup(self, args, state, model):
"""
Setup the optional MLflow integration.
Environment:
HF_MLFLOW_LOG_ARTIFACTS (:obj:`str`, `optional`):
Whether to use MLflow .log_artifact() facility to log artifacts.
This only makes sense if logging to a remote server, e.g. s3 or GCS. If set to `True` or `1`, will copy
whatever is in :class:`~transformers.TrainingArguments`'s ``output_dir`` to the local or remote
artifact storage. Using it without a remote storage will just copy the files to your artifact location.
"""
log_artifacts = os.getenv("HF_MLFLOW_LOG_ARTIFACTS", "FALSE").upper()
if log_artifacts in {"TRUE", "1"}:
self._log_artifacts = True
if state.is_world_process_zero:
self._ml_flow.start_run()
combined_dict = args.to_dict()
if hasattr(model, "config") and model.config is not None:
model_config = model.config.to_dict()
combined_dict = {**model_config, **combined_dict}
# remove params that are too long for MLflow
for name, value in list(combined_dict.items()):
# internally, all values are converted to str in MLflow
if len(str(value)) > self._MAX_PARAM_VAL_LENGTH:
logger.warning(
f"Trainer is attempting to log a value of "
f'"{value}" for key "{name}" as a parameter. '
f"MLflow's log_param() only accepts values no longer than "
f"250 characters so we dropped this attribute."
)
del combined_dict[name]
# MLflow cannot log more than 100 values in one go, so we have to split it
combined_dict_items = list(combined_dict.items())
for i in range(0, len(combined_dict_items), self._MAX_PARAMS_TAGS_PER_BATCH):
self._ml_flow.log_params(dict(combined_dict_items[i : i + self._MAX_PARAMS_TAGS_PER_BATCH]))
self._initialized = True
def on_train_begin(self, args, state, control, model=None, **kwargs):
if not self._initialized:
self.setup(args, state, model)
def on_log(self, args, state, control, logs, model=None, **kwargs):
if not self._initialized:
self.setup(args, state, model)
if state.is_world_process_zero:
for k, v in logs.items():
if isinstance(v, (int, float)):
self._ml_flow.log_metric(k, v, step=state.global_step)
else:
logger.warning(
f"Trainer is attempting to log a value of "
f'"{v}" of type {type(v)} for key "{k}" as a metric. '
f"MLflow's log_metric() only accepts float and "
f"int types so we dropped this attribute."
)
def on_train_end(self, args, state, control, **kwargs):
if self._initialized and state.is_world_process_zero:
if self._log_artifacts:
logger.info("Logging artifacts. This may take time.")
self._ml_flow.log_artifacts(args.output_dir)
def __del__(self):
# if the previous run is not terminated correctly, the fluent API will
# not let you start a new run before the previous one is killed
if self._ml_flow.active_run is not None:
self._ml_flow.end_run()
class NeptuneCallback(TrainerCallback):
"""
A :class:`~transformers.TrainerCallback` that sends the logs to `Neptune <https://neptune.ai>`.
"""
def __init__(self):
assert (
is_neptune_available()
), "NeptuneCallback requires neptune-client to be installed. Run `pip install neptune-client`."
import neptune.new as neptune
self._neptune = neptune
self._initialized = False
self._log_artifacts = False
def setup(self, args, state, model):
"""
Setup the Neptune integration.
Environment:
NEPTUNE_PROJECT (:obj:`str`, `required`):
The project ID for neptune.ai account. Should be in format `workspace_name/project_name`
NEPTUNE_API_TOKEN (:obj:`str`, `required`):
API-token for neptune.ai account
NEPTUNE_CONNECTION_MODE (:obj:`str`, `optional`):
Neptune connection mode. `async` by default
NEPTUNE_RUN_NAME (:obj:`str`, `optional`):
The name of run process on Neptune dashboard
"""
if state.is_world_process_zero:
self._neptune_run = self._neptune.init(
project=os.getenv("NEPTUNE_PROJECT"),
api_token=os.getenv("NEPTUNE_API_TOKEN"),
mode=os.getenv("NEPTUNE_CONNECTION_MODE", "async"),
name=os.getenv("NEPTUNE_RUN_NAME", None),
)
combined_dict = args.to_dict()
if hasattr(model, "config") and model.config is not None:
model_config = model.config.to_dict()
combined_dict = {**model_config, **combined_dict}
self._neptune_run["parameters"] = combined_dict
self._initialized = True
def on_train_begin(self, args, state, control, model=None, **kwargs):
if not self._initialized:
self.setup(args, state, model)
def on_log(self, args, state, control, logs, model=None, **kwargs):
if not self._initialized:
self.setup(args, state, model)
if state.is_world_process_zero:
for k, v in logs.items():
self._neptune_run[k].log(v, step=state.global_step)
def __del__(self):
"""
Environment:
NEPTUNE_STOP_TIMEOUT (:obj:`int`, `optional`):
Number of seconsds to wait for all Neptune.ai tracking calls to finish, before stopping the tracked
run. If not set it will wait for all tracking calls to finish.
"""
try:
stop_timeout = os.getenv("NEPTUNE_STOP_TIMEOUT")
stop_timeout = int(stop_timeout) if stop_timeout else None
self._neptune_run.stop(seconds=stop_timeout)
except AttributeError:
pass
class CodeCarbonCallback(TrainerCallback):
"""
A :class:`~transformers.TrainerCallback` that tracks the CO2 emission of training.
"""
def __init__(self):
assert (
is_codecarbon_available()
), "CodeCarbonCallback requires `codecarbon` to be installed. Run `pip install codecarbon`."
import codecarbon
self._codecarbon = codecarbon
self.tracker = None
def on_init_end(self, args, state, control, **kwargs):
if self.tracker is None and state.is_local_process_zero:
# CodeCarbon will automatically handle environment variables for configuration
self.tracker = self._codecarbon.EmissionsTracker(output_dir=args.output_dir)
def on_train_begin(self, args, state, control, model=None, **kwargs):
if self.tracker and state.is_local_process_zero:
self.tracker.start()
def on_train_end(self, args, state, control, **kwargs):
if self.tracker and state.is_local_process_zero:
self.tracker.stop()
INTEGRATION_TO_CALLBACK = {
"azure_ml": AzureMLCallback,
"comet_ml": CometCallback,
"mlflow": MLflowCallback,
"neptune": NeptuneCallback,
"tensorboard": TensorBoardCallback,
"wandb": WandbCallback,
"codecarbon": CodeCarbonCallback,
}
def get_reporting_integration_callbacks(report_to):
for integration in report_to:
if integration not in INTEGRATION_TO_CALLBACK:
raise ValueError(
f"{integration} is not supported, only {', '.join(INTEGRATION_TO_CALLBACK.keys())} are supported."
)
return [INTEGRATION_TO_CALLBACK[integration] for integration in report_to]
|
# coding=utf-8
# Copyright 2020-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
The Trainer class, to easily train a 🤗 Transformers from scratch or finetune it on a new task.
"""
import collections
import inspect
import math
import os
import random
import re
import shutil
import sys
import time
import warnings
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
from tqdm.auto import tqdm
# Integrations must be imported before ML frameworks:
from .integrations import ( # isort: split
default_hp_search_backend,
get_reporting_integration_callbacks,
hp_params,
is_fairscale_available,
is_optuna_available,
is_ray_tune_available,
run_hp_search_optuna,
run_hp_search_ray,
)
import numpy as np
import torch
from packaging import version
from torch import nn
from torch.utils.data import DataLoader, Dataset, IterableDataset, RandomSampler, SequentialSampler
from torch.utils.data.distributed import DistributedSampler
from . import __version__
from .configuration_utils import PretrainedConfig
from .data.data_collator import DataCollator, DataCollatorWithPadding, default_data_collator
from .debug_utils import DebugOption, DebugUnderflowOverflow
from .deepspeed import deepspeed_init, is_deepspeed_zero3_enabled
from .dependency_versions_check import dep_version_check
from .file_utils import (
CONFIG_NAME,
WEIGHTS_NAME,
PushToHubMixin,
is_apex_available,
is_datasets_available,
is_in_notebook,
is_sagemaker_dp_enabled,
is_sagemaker_mp_enabled,
is_torch_tpu_available,
)
from .modelcard import TrainingSummary
from .modeling_utils import PreTrainedModel, unwrap_model
from .models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
from .optimization import Adafactor, AdamW, get_scheduler
from .tokenization_utils_base import PreTrainedTokenizerBase
from .trainer_callback import (
CallbackHandler,
DefaultFlowCallback,
PrinterCallback,
ProgressCallback,
TrainerCallback,
TrainerControl,
TrainerState,
)
from .trainer_pt_utils import (
DistributedLengthGroupedSampler,
DistributedSamplerWithLoop,
DistributedTensorGatherer,
IterableDatasetShard,
LabelSmoother,
LengthGroupedSampler,
SequentialDistributedSampler,
ShardSampler,
distributed_broadcast_scalars,
distributed_concat,
find_batch_size,
get_parameter_names,
nested_concat,
nested_detach,
nested_numpify,
nested_truncate,
nested_xla_mesh_reduce,
reissue_pt_warnings,
)
from .trainer_utils import (
PREFIX_CHECKPOINT_DIR,
BestRun,
EvalLoopOutput,
EvalPrediction,
HPSearchBackend,
PredictionOutput,
ShardedDDPOption,
TrainerMemoryTracker,
TrainOutput,
default_compute_objective,
default_hp_space,
denumpify_detensorize,
get_last_checkpoint,
number_of_arguments,
set_seed,
speed_metrics,
)
from .training_args import ParallelMode, TrainingArguments
from .utils import logging
_is_torch_generator_available = False
_is_native_amp_available = False
DEFAULT_CALLBACKS = [DefaultFlowCallback]
DEFAULT_PROGRESS_CALLBACK = ProgressCallback
if is_in_notebook():
from .utils.notebook import NotebookProgressCallback
DEFAULT_PROGRESS_CALLBACK = NotebookProgressCallback
if is_apex_available():
from apex import amp
if version.parse(torch.__version__) >= version.parse("1.6"):
_is_torch_generator_available = True
_is_native_amp_available = True
from torch.cuda.amp import autocast
if is_datasets_available():
import datasets
if is_torch_tpu_available():
import torch_xla.core.xla_model as xm
import torch_xla.debug.metrics as met
import torch_xla.distributed.parallel_loader as pl
if is_fairscale_available():
dep_version_check("fairscale")
import fairscale
from fairscale.nn.data_parallel import FullyShardedDataParallel as FullyShardedDDP
from fairscale.nn.data_parallel import ShardedDataParallel as ShardedDDP
from fairscale.nn.wrap import auto_wrap
from fairscale.optim import OSS
from fairscale.optim.grad_scaler import ShardedGradScaler
if is_sagemaker_dp_enabled():
import smdistributed.dataparallel.torch.distributed as dist
from smdistributed.dataparallel.torch.parallel.distributed import DistributedDataParallel as DDP
else:
import torch.distributed as dist
if is_sagemaker_mp_enabled():
import smdistributed.modelparallel.torch as smp
from .trainer_pt_utils import smp_forward_backward, smp_forward_only, smp_gather, smp_nested_concat
if TYPE_CHECKING:
import optuna
logger = logging.get_logger(__name__)
class Trainer:
"""
Trainer is a simple but feature-complete training and eval loop for PyTorch, optimized for 🤗 Transformers.
Args:
model (:class:`~transformers.PreTrainedModel` or :obj:`torch.nn.Module`, `optional`):
The model to train, evaluate or use for predictions. If not provided, a ``model_init`` must be passed.
.. note::
:class:`~transformers.Trainer` is optimized to work with the :class:`~transformers.PreTrainedModel`
provided by the library. You can still use your own models defined as :obj:`torch.nn.Module` as long as
they work the same way as the 🤗 Transformers models.
args (:class:`~transformers.TrainingArguments`, `optional`):
The arguments to tweak for training. Will default to a basic instance of
:class:`~transformers.TrainingArguments` with the ``output_dir`` set to a directory named `tmp_trainer` in
the current directory if not provided.
data_collator (:obj:`DataCollator`, `optional`):
The function to use to form a batch from a list of elements of :obj:`train_dataset` or :obj:`eval_dataset`.
Will default to :func:`~transformers.default_data_collator` if no ``tokenizer`` is provided, an instance of
:func:`~transformers.DataCollatorWithPadding` otherwise.
train_dataset (:obj:`torch.utils.data.Dataset` or :obj:`torch.utils.data.IterableDataset`, `optional`):
The dataset to use for training. If it is an :obj:`datasets.Dataset`, columns not accepted by the
``model.forward()`` method are automatically removed.
Note that if it's a :obj:`torch.utils.data.IterableDataset` with some randomization and you are training in
a distributed fashion, your iterable dataset should either use a internal attribute :obj:`generator` that
is a :obj:`torch.Generator` for the randomization that must be identical on all processes (and the Trainer
will manually set the seed of this :obj:`generator` at each epoch) or have a :obj:`set_epoch()` method that
internally sets the seed of the RNGs used.
eval_dataset (:obj:`torch.utils.data.Dataset`, `optional`):
The dataset to use for evaluation. If it is an :obj:`datasets.Dataset`, columns not accepted by the
``model.forward()`` method are automatically removed.
tokenizer (:class:`PreTrainedTokenizerBase`, `optional`):
The tokenizer used to preprocess the data. If provided, will be used to automatically pad the inputs the
maximum length when batching inputs, and it will be saved along the model to make it easier to rerun an
interrupted training or reuse the fine-tuned model.
model_init (:obj:`Callable[[], PreTrainedModel]`, `optional`):
A function that instantiates the model to be used. If provided, each call to
:meth:`~transformers.Trainer.train` will start from a new instance of the model as given by this function.
The function may have zero argument, or a single one containing the optuna/Ray Tune trial object, to be
able to choose different architectures according to hyper parameters (such as layer count, sizes of inner
layers, dropout probabilities etc).
compute_metrics (:obj:`Callable[[EvalPrediction], Dict]`, `optional`):
The function that will be used to compute metrics at evaluation. Must take a
:class:`~transformers.EvalPrediction` and return a dictionary string to metric values.
callbacks (List of :obj:`~transformers.TrainerCallback`, `optional`):
A list of callbacks to customize the training loop. Will add those to the list of default callbacks
detailed in :doc:`here <callback>`.
If you want to remove one of the default callbacks used, use the :meth:`Trainer.remove_callback` method.
optimizers (:obj:`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR`, `optional`): A tuple
containing the optimizer and the scheduler to use. Will default to an instance of
:class:`~transformers.AdamW` on your model and a scheduler given by
:func:`~transformers.get_linear_schedule_with_warmup` controlled by :obj:`args`.
Important attributes:
- **model** -- Always points to the core model. If using a transformers model, it will be a
:class:`~transformers.PreTrainedModel` subclass.
- **model_wrapped** -- Always points to the most external model in case one or more other modules wrap the
original model. This is the model that should be used for the forward pass. For example, under ``DeepSpeed``,
the inner model is wrapped in ``DeepSpeed`` and then again in ``torch.nn.DistributedDataParallel``. If the
inner model hasn't been wrapped, then ``self.model_wrapped`` is the same as ``self.model``.
- **is_model_parallel** -- Whether or not a model has been switched to a model parallel mode (different from
data parallelism, this means some of the model layers are split on different GPUs).
- **place_model_on_device** -- Whether or not to automatically place the model on the device - it will be set
to :obj:`False` if model parallel or deepspeed is used, or if the default
``TrainingArguments.place_model_on_device`` is overridden to return :obj:`False` .
- **is_in_train** -- Whether or not a model is currently running ``train`` (e.g. when ``evaluate`` is called
while in ``train``)
"""
from .trainer_pt_utils import _get_learning_rate, log_metrics, metrics_format, save_metrics, save_state
def __init__(
self,
model: Union[PreTrainedModel, nn.Module] = None,
args: TrainingArguments = None,
data_collator: Optional[DataCollator] = None,
train_dataset: Optional[Dataset] = None,
eval_dataset: Optional[Dataset] = None,
tokenizer: Optional[PreTrainedTokenizerBase] = None,
model_init: Callable[[], PreTrainedModel] = None,
compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None,
callbacks: Optional[List[TrainerCallback]] = None,
optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
):
if args is None:
output_dir = "tmp_trainer"
logger.info(f"No `TrainingArguments` passed, using `output_dir={output_dir}`.")
args = TrainingArguments(output_dir=output_dir)
self.args = args
# Seed must be set before instantiating the model when using model
set_seed(self.args.seed)
self.hp_name = None
self.deepspeed = None
self.is_in_train = False
# memory metrics - must set up as early as possible
self._memory_tracker = TrainerMemoryTracker(self.args.skip_memory_metrics)
self._memory_tracker.start()
# set the correct log level depending on the node
log_level = args.get_process_log_level()
logging.set_verbosity(log_level)
# force device and distributed setup init explicitly
args._setup_devices
if model is None:
if model_init is not None:
self.model_init = model_init
model = self.call_model_init()
else:
raise RuntimeError("`Trainer` requires either a `model` or `model_init` argument")
else:
if model_init is not None:
warnings.warn(
"`Trainer` requires either a `model` or `model_init` argument, but not both. "
"`model_init` will overwrite your model when calling the `train` method. This will become a fatal error in the next release.",
FutureWarning,
)
self.model_init = model_init
if hasattr(model, "is_parallelizable") and model.is_parallelizable and model.model_parallel:
self.is_model_parallel = True
else:
self.is_model_parallel = False
# Setup Sharded DDP training
self.sharded_ddp = None
if len(args.sharded_ddp) > 0:
if args.deepspeed:
raise ValueError(
"Using --sharded_ddp xxx together with --deepspeed is not possible, deactivate one of those flags."
)
if args.local_rank == -1:
raise ValueError("Using sharded DDP only works in distributed training.")
elif not is_fairscale_available():
raise ImportError("Sharded DDP training requires fairscale: `pip install fairscale`.")
elif ShardedDDPOption.SIMPLE not in args.sharded_ddp and FullyShardedDDP is None:
raise ImportError(
"Sharded DDP in a mode other than simple training requires fairscale version >= 0.3, found "
f"{fairscale.__version__}. Upgrade your fairscale library: `pip install --upgrade fairscale`."
)
elif ShardedDDPOption.SIMPLE in args.sharded_ddp:
self.sharded_ddp = ShardedDDPOption.SIMPLE
elif ShardedDDPOption.ZERO_DP_2 in args.sharded_ddp:
self.sharded_ddp = ShardedDDPOption.ZERO_DP_2
elif ShardedDDPOption.ZERO_DP_3 in args.sharded_ddp:
self.sharded_ddp = ShardedDDPOption.ZERO_DP_3
# one place to sort out whether to place the model on device or not
# postpone switching model to cuda when:
# 1. MP - since we are trying to fit a much bigger than 1 gpu model
# 2. fp16-enabled DeepSpeed loads the model in half the size and it doesn't need .to() anyway,
# and we only use deepspeed for training at the moment
# 3. full fp16 eval - since the model needs to be half'ed first
# 4. Sharded DDP - same as MP
self.place_model_on_device = args.place_model_on_device
if (
self.is_model_parallel
or args.deepspeed
or (args.fp16_full_eval and not args.do_train)
or (self.sharded_ddp in [ShardedDDPOption.ZERO_DP_2, ShardedDDPOption.ZERO_DP_3])
):
self.place_model_on_device = False
default_collator = default_data_collator if tokenizer is None else DataCollatorWithPadding(tokenizer)
self.data_collator = data_collator if data_collator is not None else default_collator
self.train_dataset = train_dataset
self.eval_dataset = eval_dataset
self.tokenizer = tokenizer
if self.place_model_on_device:
self._move_model_to_device(model, args.device)
# Force n_gpu to 1 to avoid DataParallel as MP will manage the GPUs
if self.is_model_parallel:
self.args._n_gpu = 1
# later use `self.model is self.model_wrapped` to check if it's wrapped or not
self.model_wrapped = model
self.model = model
self.compute_metrics = compute_metrics
self.optimizer, self.lr_scheduler = optimizers
if model_init is not None and (self.optimizer is not None or self.lr_scheduler is not None):
raise RuntimeError(
"Passing a `model_init` is incompatible with providing the `optimizers` argument."
"You should subclass `Trainer` and override the `create_optimizer_and_scheduler` method."
)
default_callbacks = DEFAULT_CALLBACKS + get_reporting_integration_callbacks(self.args.report_to)
callbacks = default_callbacks if callbacks is None else default_callbacks + callbacks
self.callback_handler = CallbackHandler(
callbacks, self.model, self.tokenizer, self.optimizer, self.lr_scheduler
)
self.add_callback(PrinterCallback if self.args.disable_tqdm else DEFAULT_PROGRESS_CALLBACK)
# Will be set to True by `self._setup_loggers()` on first call to `self.log()`.
self._loggers_initialized = False
# Create clone of distant repo and output directory if needed
if self.args.push_to_hub:
self.init_git_repo()
if self.args.should_save:
os.makedirs(self.args.output_dir, exist_ok=True)
if not callable(self.data_collator) and callable(getattr(self.data_collator, "collate_batch", None)):
raise ValueError("The `data_collator` should be a simple callable (function, class with `__call__`).")
if args.max_steps > 0:
logger.info("max_steps is given, it will override any value given in num_train_epochs")
if train_dataset is not None and not isinstance(train_dataset, collections.abc.Sized) and args.max_steps <= 0:
raise ValueError("train_dataset does not implement __len__, max_steps has to be specified")
self._signature_columns = None
# Mixed precision setup
self.use_apex = False
self.use_amp = False
self.fp16_backend = None
if args.fp16:
if args.fp16_backend == "auto":
self.fp16_backend = "amp" if _is_native_amp_available else "apex"
else:
self.fp16_backend = args.fp16_backend
logger.info(f"Using {self.fp16_backend} fp16 backend")
if args.fp16 and not args.deepspeed: # deepspeed manages its own fp16
if self.fp16_backend == "amp":
self.use_amp = True
if is_sagemaker_mp_enabled():
self.scaler = smp.amp.GradScaler()
elif self.sharded_ddp is not None:
self.scaler = ShardedGradScaler()
else:
self.scaler = torch.cuda.amp.GradScaler()
else:
if not is_apex_available():
raise ImportError(
"Using FP16 with APEX but APEX is not installed, please refer to https://www.github.com/nvidia/apex."
)
self.use_apex = True
# FP16 + model parallelism in SageMaker: gradient clipping does not work for now so we raise a helpful error.
if is_sagemaker_mp_enabled() and self.use_amp and args.max_grad_norm is not None and args.max_grad_norm > 0:
raise ValueError(
"SageMaker Model Parallelism in mixed precision mode does not support gradient clipping yet. Pass "
"along 'max_grad_norm': 0 in your hyperparameters."
)
# Label smoothing
if self.args.label_smoothing_factor != 0:
self.label_smoother = LabelSmoother(epsilon=self.args.label_smoothing_factor)
else:
self.label_smoother = None
self.state = TrainerState()
self.control = TrainerControl()
# Internal variable to count flos in each process, will be accumulated in `self.state.total_flos` then
# returned to 0 every time flos need to be logged
self.current_flos = 0
self.hp_search_backend = None
self.use_tune_checkpoints = False
default_label_names = (
["start_positions", "end_positions"]
if type(self.model).__name__ in MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES.values()
else ["labels"]
)
self.label_names = default_label_names if self.args.label_names is None else self.args.label_names
self.control = self.callback_handler.on_init_end(self.args, self.state, self.control)
# very last
self._memory_tracker.stop_and_update_metrics()
def add_callback(self, callback):
"""
Add a callback to the current list of :class:`~transformer.TrainerCallback`.
Args:
callback (:obj:`type` or :class:`~transformer.TrainerCallback`):
A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`.
In the first case, will instantiate a member of that class.
"""
self.callback_handler.add_callback(callback)
def pop_callback(self, callback):
"""
Remove a callback from the current list of :class:`~transformer.TrainerCallback` and returns it.
If the callback is not found, returns :obj:`None` (and no error is raised).
Args:
callback (:obj:`type` or :class:`~transformer.TrainerCallback`):
A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`.
In the first case, will pop the first member of that class found in the list of callbacks.
Returns:
:class:`~transformer.TrainerCallback`: The callback removed, if found.
"""
return self.callback_handler.pop_callback(callback)
def remove_callback(self, callback):
"""
Remove a callback from the current list of :class:`~transformer.TrainerCallback`.
Args:
callback (:obj:`type` or :class:`~transformer.TrainerCallback`):
A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`.
In the first case, will remove the first member of that class found in the list of callbacks.
"""
self.callback_handler.remove_callback(callback)
def _move_model_to_device(self, model, device):
model = model.to(device)
# Moving a model to an XLA device disconnects the tied weights, so we have to retie them.
if self.args.parallel_mode == ParallelMode.TPU and hasattr(model, "tie_weights"):
model.tie_weights()
def _remove_unused_columns(self, dataset: "datasets.Dataset", description: Optional[str] = None):
if not self.args.remove_unused_columns:
return dataset
if self._signature_columns is None:
# Inspect model forward signature to keep only the arguments it accepts.
signature = inspect.signature(self.model.forward)
self._signature_columns = list(signature.parameters.keys())
# Labels may be named label or label_ids, the default data collator handles that.
self._signature_columns += ["label", "label_ids"]
columns = [k for k in self._signature_columns if k in dataset.column_names]
ignored_columns = list(set(dataset.column_names) - set(self._signature_columns))
if len(ignored_columns) > 0:
dset_description = "" if description is None else f"in the {description} set "
logger.info(
f"The following columns {dset_description} don't have a corresponding argument in "
f"`{self.model.__class__.__name__}.forward` and have been ignored: {", ".join(ignored_columns)}."
)
if version.parse(datasets.__version__) < version.parse("1.4.0"):
dataset.set_format(
type=dataset.format["type"], columns=columns, format_kwargs=dataset.format["format_kwargs"]
)
return dataset
else:
return dataset.remove_columns(ignored_columns)
def _get_train_sampler(self) -> Optional[torch.utils.data.Sampler]:
if not isinstance(self.train_dataset, collections.abc.Sized):
return None
generator = None
if self.args.world_size <= 1 and _is_torch_generator_available:
generator = torch.Generator()
generator.manual_seed(int(torch.empty((), dtype=torch.int64).random_().item()))
# Build the sampler.
if self.args.group_by_length:
if is_datasets_available() and isinstance(self.train_dataset, datasets.Dataset):
lengths = (
self.train_dataset[self.args.length_column_name]
if self.args.length_column_name in self.train_dataset.column_names
else None
)
else:
lengths = None
model_input_name = self.tokenizer.model_input_names[0] if self.tokenizer is not None else None
if self.args.world_size <= 1:
return LengthGroupedSampler(
self.train_dataset,
self.args.train_batch_size,
lengths=lengths,
model_input_name=model_input_name,
generator=generator,
)
else:
return DistributedLengthGroupedSampler(
self.train_dataset,
self.args.train_batch_size,
num_replicas=self.args.world_size,
rank=self.args.process_index,
lengths=lengths,
model_input_name=model_input_name,
seed=self.args.seed,
)
else:
if self.args.world_size <= 1:
if _is_torch_generator_available:
return RandomSampler(self.train_dataset, generator=generator)
return RandomSampler(self.train_dataset)
elif (
self.args.parallel_mode in [ParallelMode.TPU, ParallelMode.SAGEMAKER_MODEL_PARALLEL]
and not self.args.dataloader_drop_last
):
# Use a loop for TPUs when drop_last is False to have all batches have the same size.
return DistributedSamplerWithLoop(
self.train_dataset,
batch_size=self.args.per_device_train_batch_size,
num_replicas=self.args.world_size,
rank=self.args.process_index,
seed=self.args.seed,
)
else:
return DistributedSampler(
self.train_dataset,
num_replicas=self.args.world_size,
rank=self.args.process_index,
seed=self.args.seed,
)
def get_train_dataloader(self) -> DataLoader:
"""
Returns the training :class:`~torch.utils.data.DataLoader`.
Will use no sampler if :obj:`self.train_dataset` does not implement :obj:`__len__`, a random sampler (adapted
to distributed training if necessary) otherwise.
Subclass and override this method if you want to inject some custom behavior.
"""
if self.train_dataset is None:
raise ValueError("Trainer: training requires a train_dataset.")
train_dataset = self.train_dataset
if is_datasets_available() and isinstance(train_dataset, datasets.Dataset):
train_dataset = self._remove_unused_columns(train_dataset, description="training")
if isinstance(train_dataset, torch.utils.data.IterableDataset):
if self.args.world_size > 1:
train_dataset = IterableDatasetShard(
train_dataset,
batch_size=self.args.train_batch_size,
drop_last=self.args.dataloader_drop_last,
num_processes=self.args.world_size,
process_index=self.args.process_index,
)
return DataLoader(
train_dataset,
batch_size=self.args.train_batch_size,
collate_fn=self.data_collator,
num_workers=self.args.dataloader_num_workers,
pin_memory=self.args.dataloader_pin_memory,
)
train_sampler = self._get_train_sampler()
return DataLoader(
train_dataset,
batch_size=self.args.train_batch_size,
sampler=train_sampler,
collate_fn=self.data_collator,
drop_last=self.args.dataloader_drop_last,
num_workers=self.args.dataloader_num_workers,
pin_memory=self.args.dataloader_pin_memory,
)
def _get_eval_sampler(self, eval_dataset: Dataset) -> Optional[torch.utils.data.Sampler]:
# Deprecated code
if self.args.use_legacy_prediction_loop:
if is_torch_tpu_available():
return SequentialDistributedSampler(
eval_dataset, num_replicas=xm.xrt_world_size(), rank=xm.get_ordinal()
)
elif is_sagemaker_mp_enabled():
return SequentialDistributedSampler(
eval_dataset,
num_replicas=smp.dp_size(),
rank=smp.dp_rank(),
batch_size=self.args.per_device_eval_batch_size,
)
elif self.args.local_rank != -1:
return SequentialDistributedSampler(eval_dataset)
else:
return SequentialSampler(eval_dataset)
if self.args.world_size <= 1:
return SequentialSampler(eval_dataset)
else:
return ShardSampler(
eval_dataset,
batch_size=self.args.per_device_eval_batch_size,
num_processes=self.args.world_size,
process_index=self.args.process_index,
)
def get_eval_dataloader(self, eval_dataset: Optional[Dataset] = None) -> DataLoader:
"""
Returns the evaluation :class:`~torch.utils.data.DataLoader`.
Subclass and override this method if you want to inject some custom behavior.
Args:
eval_dataset (:obj:`torch.utils.data.Dataset`, `optional`):
If provided, will override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`, columns not
accepted by the ``model.forward()`` method are automatically removed. It must implement :obj:`__len__`.
"""
if eval_dataset is None and self.eval_dataset is None:
raise ValueError("Trainer: evaluation requires an eval_dataset.")
eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset
if is_datasets_available() and isinstance(eval_dataset, datasets.Dataset):
eval_dataset = self._remove_unused_columns(eval_dataset, description="evaluation")
if isinstance(eval_dataset, torch.utils.data.IterableDataset):
if self.args.world_size > 1:
eval_dataset = IterableDatasetShard(
eval_dataset,
batch_size=self.args.eval_batch_size,
drop_last=self.args.dataloader_drop_last,
num_processes=self.args.world_size,
process_index=self.args.process_index,
)
return DataLoader(
eval_dataset,
batch_size=self.args.eval_batch_size,
collate_fn=self.data_collator,
num_workers=self.args.dataloader_num_workers,
pin_memory=self.args.dataloader_pin_memory,
)
eval_sampler = self._get_eval_sampler(eval_dataset)
return DataLoader(
eval_dataset,
sampler=eval_sampler,
batch_size=self.args.eval_batch_size,
collate_fn=self.data_collator,
drop_last=self.args.dataloader_drop_last,
num_workers=self.args.dataloader_num_workers,
pin_memory=self.args.dataloader_pin_memory,
)
def get_test_dataloader(self, test_dataset: Dataset) -> DataLoader:
"""
Returns the test :class:`~torch.utils.data.DataLoader`.
Subclass and override this method if you want to inject some custom behavior.
Args:
test_dataset (:obj:`torch.utils.data.Dataset`, `optional`):
The test dataset to use. If it is an :obj:`datasets.Dataset`, columns not accepted by the
``model.forward()`` method are automatically removed. It must implement :obj:`__len__`.
"""
if is_datasets_available() and isinstance(test_dataset, datasets.Dataset):
test_dataset = self._remove_unused_columns(test_dataset, description="test")
if isinstance(test_dataset, torch.utils.data.IterableDataset):
if self.args.world_size > 1:
test_dataset = IterableDatasetShard(
test_dataset,
batch_size=self.args.eval_batch_size,
drop_last=self.args.dataloader_drop_last,
num_processes=self.args.world_size,
process_index=self.args.process_index,
)
return DataLoader(
test_dataset,
batch_size=self.args.eval_batch_size,
collate_fn=self.data_collator,
num_workers=self.args.dataloader_num_workers,
pin_memory=self.args.dataloader_pin_memory,
)
test_sampler = self._get_eval_sampler(test_dataset)
# We use the same batch_size as for eval.
return DataLoader(
test_dataset,
sampler=test_sampler,
batch_size=self.args.eval_batch_size,
collate_fn=self.data_collator,
drop_last=self.args.dataloader_drop_last,
pin_memory=self.args.dataloader_pin_memory,
)
def create_optimizer_and_scheduler(self, num_training_steps: int):
"""
Setup the optimizer and the learning rate scheduler.
We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the
Trainer's init through :obj:`optimizers`, or subclass and override this method (or :obj:`create_optimizer`
and/or :obj:`create_scheduler`) in a subclass.
"""
self.create_optimizer()
self.create_scheduler(num_training_steps)
def create_optimizer(self):
"""
Setup the optimizer.
We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the
Trainer's init through :obj:`optimizers`, or subclass and override this method in a subclass.
"""
if self.optimizer is None:
decay_parameters = get_parameter_names(self.model, [nn.LayerNorm])
decay_parameters = [name for name in decay_parameters if "bias" not in name]
optimizer_grouped_parameters = [
{
"params": [p for n, p in self.model.named_parameters() if n in decay_parameters],
"weight_decay": self.args.weight_decay,
},
{
"params": [p for n, p in self.model.named_parameters() if n not in decay_parameters],
"weight_decay": 0.0,
},
]
optimizer_cls = Adafactor if self.args.adafactor else AdamW
if self.args.adafactor:
optimizer_cls = Adafactor
optimizer_kwargs = {"scale_parameter": False, "relative_step": False}
else:
optimizer_cls = AdamW
optimizer_kwargs = {
"betas": (self.args.adam_beta1, self.args.adam_beta2),
"eps": self.args.adam_epsilon,
}
optimizer_kwargs["lr"] = self.args.learning_rate
if self.sharded_ddp == ShardedDDPOption.SIMPLE:
self.optimizer = OSS(
params=optimizer_grouped_parameters,
optim=optimizer_cls,
**optimizer_kwargs,
)
else:
self.optimizer = optimizer_cls(optimizer_grouped_parameters, **optimizer_kwargs)
if is_sagemaker_mp_enabled():
self.optimizer = smp.DistributedOptimizer(self.optimizer)
def create_scheduler(self, num_training_steps: int):
"""
Setup the scheduler. The optimizer of the trainer must have been set up before this method is called.
Args:
num_training_steps (int): The number of training steps to do.
"""
if self.lr_scheduler is None:
self.lr_scheduler = get_scheduler(
self.args.lr_scheduler_type,
self.optimizer,
num_warmup_steps=self.args.get_warmup_steps(num_training_steps),
num_training_steps=num_training_steps,
)
def num_examples(self, dataloader: DataLoader) -> int:
"""
Helper to get number of samples in a :class:`~torch.utils.data.DataLoader` by accessing its dataset.
Will raise an exception if the underlying dataset does not implement method :obj:`__len__`
"""
return len(dataloader.dataset)
def _hp_search_setup(self, trial: Union["optuna.Trial", Dict[str, Any]]):
"""HP search setup code"""
self._trial = trial
if self.hp_search_backend is None or trial is None:
return
if self.hp_search_backend == HPSearchBackend.OPTUNA:
params = self.hp_space(trial)
elif self.hp_search_backend == HPSearchBackend.RAY:
params = trial
params.pop("wandb", None)
for key, value in params.items():
if not hasattr(self.args, key):
logger.warn(
f"Trying to set {key} in the hyperparameter search but there is no corresponding field in `TrainingArguments`."
)
continue
old_attr = getattr(self.args, key, None)
# Casting value to the proper type
if old_attr is not None:
value = type(old_attr)(value)
setattr(self.args, key, value)
if self.hp_search_backend == HPSearchBackend.OPTUNA:
logger.info("Trial:", trial.params)
if self.args.deepspeed:
# Rebuild the deepspeed config to reflect the updated training parameters
from transformers.deepspeed import HfDeepSpeedConfig
self.args.hf_deepspeed_config = HfDeepSpeedConfig(self.args)
def _report_to_hp_search(
self, trial: Union["optuna.Trial", Dict[str, Any]], epoch: int, metrics: Dict[str, float]
):
if self.hp_search_backend is None or trial is None:
return
self.objective = self.compute_objective(metrics.copy())
if self.hp_search_backend == HPSearchBackend.OPTUNA:
import optuna
trial.report(self.objective, epoch)
if trial.should_prune():
raise optuna.TrialPruned()
elif self.hp_search_backend == HPSearchBackend.RAY:
from ray import tune
if self.control.should_save:
self._tune_save_checkpoint()
tune.report(objective=self.objective, **metrics)
def _tune_save_checkpoint(self):
from ray import tune
if not self.use_tune_checkpoints:
return
with tune.checkpoint_dir(step=self.state.global_step) as checkpoint_dir:
output_dir = os.path.join(checkpoint_dir, f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}")
self.save_model(output_dir)
if self.args.should_save:
self.state.save_to_json(os.path.join(output_dir, "trainer_state.json"))
torch.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt"))
torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
def call_model_init(self, trial=None):
model_init_argcount = number_of_arguments(self.model_init)
if model_init_argcount == 0:
model = self.model_init()
elif model_init_argcount == 1:
model = self.model_init(trial)
else:
raise RuntimeError("model_init should have 0 or 1 argument.")
if model is None:
raise RuntimeError("model_init should not return None.")
return model
def _wrap_model(self, model, training=True):
if is_sagemaker_mp_enabled():
# Wrapping the base model twice in a DistributedModel will raise an error.
if isinstance(self.model_wrapped, smp.model.DistributedModel):
return self.model_wrapped
return smp.DistributedModel(model, backward_passes_per_step=self.args.gradient_accumulation_steps)
# already initialized its own DDP and AMP
if self.deepspeed:
return self.deepspeed
# train/eval could be run multiple-times - if already wrapped, don't re-wrap it again
if unwrap_model(model) is not model:
return model
# Mixed precision training with apex (torch < 1.6)
if self.use_apex and training:
model, self.optimizer = amp.initialize(model, self.optimizer, opt_level=self.args.fp16_opt_level)
# Multi-gpu training (should be after apex fp16 initialization)
if self.args.n_gpu > 1:
model = nn.DataParallel(model)
# Note: in torch.distributed mode, there's no point in wrapping the model
# inside a DistributedDataParallel as we'll be under `no_grad` anyways.
if not training:
return model
# Distributed training (should be after apex fp16 initialization)
if self.sharded_ddp is not None:
# Sharded DDP!
if self.sharded_ddp == ShardedDDPOption.SIMPLE:
model = ShardedDDP(model, self.optimizer)
else:
mixed_precision = self.args.fp16
cpu_offload = ShardedDDPOption.OFFLOAD in self.args.sharded_ddp
zero_3 = self.sharded_ddp == ShardedDDPOption.ZERO_DP_3
# XXX: Breaking the self.model convention but I see no way around it for now.
if ShardedDDPOption.AUTO_WRAP in self.args.sharded_ddp:
model = auto_wrap(model)
self.model = model = FullyShardedDDP(
model,
mixed_precision=mixed_precision,
reshard_after_forward=zero_3,
cpu_offload=cpu_offload,
).to(self.args.device)
elif is_sagemaker_dp_enabled():
model = DDP(model, device_ids=[dist.get_local_rank()], broadcast_buffers=False)
elif self.args.local_rank != -1:
if self.args.ddp_find_unused_parameters is not None:
find_unused_parameters = self.args.ddp_find_unused_parameters
elif isinstance(model, PreTrainedModel):
# find_unused_parameters breaks checkpointing as per
# https://github.com/huggingface/transformers/pull/4659#issuecomment-643356021
find_unused_parameters = not getattr(model.config, "gradient_checkpointing", False)
else:
find_unused_parameters = True
model = nn.parallel.DistributedDataParallel(
model,
device_ids=[self.args.local_rank],
output_device=self.args.local_rank,
find_unused_parameters=find_unused_parameters,
)
return model
def train(
self,
resume_from_checkpoint: Optional[Union[str, bool]] = None,
trial: Union["optuna.Trial", Dict[str, Any]] = None,
ignore_keys_for_eval: Optional[List[str]] = None,
**kwargs,
):
"""
Main training entry point.
Args:
resume_from_checkpoint (:obj:`str` or :obj:`bool`, `optional`):
If a :obj:`str`, local path to a saved checkpoint as saved by a previous instance of
:class:`~transformers.Trainer`. If a :obj:`bool` and equals `True`, load the last checkpoint in
`args.output_dir` as saved by a previous instance of :class:`~transformers.Trainer`. If present,
training will resume from the model/optimizer/scheduler states loaded here.
trial (:obj:`optuna.Trial` or :obj:`Dict[str, Any]`, `optional`):
The trial run or the hyperparameter dictionary for hyperparameter search.
ignore_keys_for_eval (:obj:`List[str]`, `optional`)
A list of keys in the output of your model (if it is a dictionary) that should be ignored when
gathering predictions for evaluation during the training.
kwargs:
Additional keyword arguments used to hide deprecated arguments
"""
resume_from_checkpoint = None if not resume_from_checkpoint else resume_from_checkpoint
# memory metrics - must set up as early as possible
self._memory_tracker.start()
args = self.args
self.is_in_train = True
# do_train is not a reliable argument, as it might not be set and .train() still called, so
# the following is a workaround:
if args.fp16_full_eval and not args.do_train:
self._move_model_to_device(self.model, args.device)
if "model_path" in kwargs:
resume_from_checkpoint = kwargs.pop("model_path")
warnings.warn(
"`model_path` is deprecated and will be removed in a future version. Use `resume_from_checkpoint` "
"instead.",
FutureWarning,
)
if len(kwargs) > 0:
raise TypeError(f"train() received got unexpected keyword arguments: {", ".join(list(kwargs.keys()))}.")
# This might change the seed so needs to run first.
self._hp_search_setup(trial)
# Model re-init
model_reloaded = False
if self.model_init is not None:
# Seed must be set before instantiating the model when using model_init.
set_seed(args.seed)
self.model = self.call_model_init(trial)
model_reloaded = True
# Reinitializes optimizer and scheduler
self.optimizer, self.lr_scheduler = None, None
# Load potential model checkpoint
if isinstance(resume_from_checkpoint, bool) and resume_from_checkpoint:
resume_from_checkpoint = get_last_checkpoint(args.output_dir)
if resume_from_checkpoint is None:
raise ValueError(f"No valid checkpoint found in output directory ({args.output_dir})")
if resume_from_checkpoint is not None:
if not os.path.isfile(os.path.join(resume_from_checkpoint, WEIGHTS_NAME)):
raise ValueError(f"Can't find a valid checkpoint at {resume_from_checkpoint}")
logger.info(f"Loading model from {resume_from_checkpoint}).")
if os.path.isfile(os.path.join(resume_from_checkpoint, CONFIG_NAME)):
config = PretrainedConfig.from_json_file(os.path.join(resume_from_checkpoint, CONFIG_NAME))
checkpoint_version = config.transformers_version
if checkpoint_version is not None and checkpoint_version != __version__:
logger.warn(
f"You are resuming training from a checkpoint trained with {checkpoint_version} of "
f"Transformers but your current version is {__version__}. This is not recommended and could "
"yield to errors or unwanted behaviors."
)
if args.deepspeed:
# will be resumed in deepspeed_init
pass
else:
# We load the model state dict on the CPU to avoid an OOM error.
state_dict = torch.load(os.path.join(resume_from_checkpoint, WEIGHTS_NAME), map_location="cpu")
# If the model is on the GPU, it still works!
self._load_state_dict_in_model(state_dict)
# release memory
del state_dict
# If model was re-initialized, put it on the right device and update self.model_wrapped
if model_reloaded:
if self.place_model_on_device:
self._move_model_to_device(self.model, args.device)
self.model_wrapped = self.model
# Keeping track whether we can can len() on the dataset or not
train_dataset_is_sized = isinstance(self.train_dataset, collections.abc.Sized)
# Data loader and number of training steps
train_dataloader = self.get_train_dataloader()
# Setting up training control variables:
# number of training epochs: num_train_epochs
# number of training steps per epoch: num_update_steps_per_epoch
# total number of training steps to execute: max_steps
total_train_batch_size = args.train_batch_size * args.gradient_accumulation_steps * args.world_size
if train_dataset_is_sized:
num_update_steps_per_epoch = len(train_dataloader) // args.gradient_accumulation_steps
num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1)
if args.max_steps > 0:
max_steps = args.max_steps
num_train_epochs = args.max_steps // num_update_steps_per_epoch + int(
args.max_steps % num_update_steps_per_epoch > 0
)
# May be slightly incorrect if the last batch in the training datalaoder has a smaller size but it's
# the best we can do.
num_train_samples = args.max_steps * total_train_batch_size
else:
max_steps = math.ceil(args.num_train_epochs * num_update_steps_per_epoch)
num_train_epochs = math.ceil(args.num_train_epochs)
num_train_samples = len(self.train_dataset) * args.num_train_epochs
else:
# see __init__. max_steps is set when the dataset has no __len__
max_steps = args.max_steps
# Setting a very large number of epochs so we go as many times as necessary over the iterator.
num_train_epochs = sys.maxsize
num_update_steps_per_epoch = max_steps
num_train_samples = args.max_steps * total_train_batch_size
if DebugOption.UNDERFLOW_OVERFLOW in self.args.debug:
if self.args.n_gpu > 1:
# nn.DataParallel(model) replicates the model, creating new variables and module
# references registered here no longer work on other gpus, breaking the module
raise ValueError(
"Currently --debug underflow_overflow is not supported under DP. Please use DDP (torch.distributed.launch)."
)
else:
debug_overflow = DebugUnderflowOverflow(self.model) # noqa
delay_optimizer_creation = self.sharded_ddp is not None and self.sharded_ddp != ShardedDDPOption.SIMPLE
if args.deepspeed:
deepspeed_engine, optimizer, lr_scheduler = deepspeed_init(
self, num_training_steps=max_steps, resume_from_checkpoint=resume_from_checkpoint
)
self.model = deepspeed_engine.module
self.model_wrapped = deepspeed_engine
self.deepspeed = deepspeed_engine
self.optimizer = optimizer
self.lr_scheduler = lr_scheduler
elif not delay_optimizer_creation:
self.create_optimizer_and_scheduler(num_training_steps=max_steps)
self.state = TrainerState()
self.state.is_hyper_param_search = trial is not None
model = self._wrap_model(self.model_wrapped)
# for the rest of this function `model` is the outside model, whether it was wrapped or not
if model is not self.model:
self.model_wrapped = model
if delay_optimizer_creation:
self.create_optimizer_and_scheduler(num_training_steps=max_steps)
# Check if saved optimizer or scheduler states exist
self._load_optimizer_and_scheduler(resume_from_checkpoint)
# important: at this point:
# self.model is the Transformers Model
# self.model_wrapped is DDP(Transformers Model), Deepspeed(Transformers Model), etc.
# Train!
num_examples = (
self.num_examples(train_dataloader) if train_dataset_is_sized else total_train_batch_size * args.max_steps
)
logger.info("***** Running training *****")
logger.info(f" Num examples = {num_examples}")
logger.info(f" Num Epochs = {num_train_epochs}")
logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}")
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_train_batch_size}")
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
logger.info(f" Total optimization steps = {max_steps}")
self.state.epoch = 0
start_time = time.time()
epochs_trained = 0
steps_trained_in_current_epoch = 0
steps_trained_progress_bar = None
# Check if continuing training from a checkpoint
if resume_from_checkpoint is not None and os.path.isfile(
os.path.join(resume_from_checkpoint, "trainer_state.json")
):
self.state = TrainerState.load_from_json(os.path.join(resume_from_checkpoint, "trainer_state.json"))
epochs_trained = self.state.global_step // num_update_steps_per_epoch
if not args.ignore_data_skip:
steps_trained_in_current_epoch = self.state.global_step % (num_update_steps_per_epoch)
steps_trained_in_current_epoch *= args.gradient_accumulation_steps
else:
steps_trained_in_current_epoch = 0
logger.info(" Continuing training from checkpoint, will skip to saved global_step")
logger.info(f" Continuing training from epoch {epochs_trained}")
logger.info(f" Continuing training from global step {self.state.global_step}")
if not args.ignore_data_skip:
logger.info(
f" Will skip the first {epochs_trained} epochs then the first {steps_trained_in_current_epoch} "
"batches in the first epoch. If this takes a lot of time, you can add the `--ignore_data_skip` "
"flag to your launch command, but you will resume the training on data already seen by your model."
)
if self.is_local_process_zero() and not args.disable_tqdm:
steps_trained_progress_bar = tqdm(total=steps_trained_in_current_epoch)
steps_trained_progress_bar.set_description("Skipping the first batches")
# Update the references
self.callback_handler.model = self.model
self.callback_handler.optimizer = self.optimizer
self.callback_handler.lr_scheduler = self.lr_scheduler
self.callback_handler.train_dataloader = train_dataloader
self.state.trial_name = self.hp_name(trial) if self.hp_name is not None else None
self.state.trial_params = hp_params(trial) if trial is not None else None
# This should be the same if the state has been saved but in case the training arguments changed, it's safer
# to set this after the load.
self.state.max_steps = max_steps
self.state.num_train_epochs = num_train_epochs
self.state.is_local_process_zero = self.is_local_process_zero()
self.state.is_world_process_zero = self.is_world_process_zero()
# tr_loss is a tensor to avoid synchronization of TPUs through .item()
tr_loss = torch.tensor(0.0).to(args.device)
# _total_loss_scalar is updated everytime .item() has to be called on tr_loss and stores the sum of all losses
self._total_loss_scalar = 0.0
self._globalstep_last_logged = self.state.global_step
model.zero_grad()
self.control = self.callback_handler.on_train_begin(args, self.state, self.control)
# Skip the first epochs_trained epochs to get the random state of the dataloader at the right point.
if not args.ignore_data_skip:
for epoch in range(epochs_trained):
# We just need to begin an iteration to create the randomization of the sampler.
for _ in train_dataloader:
break
for epoch in range(epochs_trained, num_train_epochs):
if isinstance(train_dataloader, DataLoader) and isinstance(train_dataloader.sampler, DistributedSampler):
train_dataloader.sampler.set_epoch(epoch)
elif isinstance(train_dataloader.dataset, IterableDatasetShard):
train_dataloader.dataset.set_epoch(epoch)
if is_torch_tpu_available():
parallel_loader = pl.ParallelLoader(train_dataloader, [args.device]).per_device_loader(args.device)
epoch_iterator = parallel_loader
else:
epoch_iterator = train_dataloader
# Reset the past mems state at the beginning of each epoch if necessary.
if args.past_index >= 0:
self._past = None
steps_in_epoch = (
len(epoch_iterator) if train_dataset_is_sized else args.max_steps * args.gradient_accumulation_steps
)
self.control = self.callback_handler.on_epoch_begin(args, self.state, self.control)
for step, inputs in enumerate(epoch_iterator):
# Skip past any already trained steps if resuming training
if steps_trained_in_current_epoch > 0:
steps_trained_in_current_epoch -= 1
if steps_trained_progress_bar is not None:
steps_trained_progress_bar.update(1)
if steps_trained_in_current_epoch == 0:
self._load_rng_state(resume_from_checkpoint)
continue
elif steps_trained_progress_bar is not None:
steps_trained_progress_bar.close()
steps_trained_progress_bar = None
if step % args.gradient_accumulation_steps == 0:
self.control = self.callback_handler.on_step_begin(args, self.state, self.control)
if (
((step + 1) % args.gradient_accumulation_steps != 0)
and args.local_rank != -1
and args._no_sync_in_gradient_accumulation
):
# Avoid unnecessary DDP synchronization since there will be no backward pass on this example.
with model.no_sync():
tr_loss += self.training_step(model, inputs)
else:
tr_loss += self.training_step(model, inputs)
self.current_flos += float(self.floating_point_ops(inputs))
# Optimizer step for deepspeed must be called on every step regardless of the value of gradient_accumulation_steps
if self.deepspeed:
self.deepspeed.step()
if (step + 1) % args.gradient_accumulation_steps == 0 or (
# last step in epoch but step is always smaller than gradient_accumulation_steps
steps_in_epoch <= args.gradient_accumulation_steps
and (step + 1) == steps_in_epoch
):
# Gradient clipping
if args.max_grad_norm is not None and args.max_grad_norm > 0 and not self.deepspeed:
# deepspeed does its own clipping
if self.use_amp:
# AMP: gradients need unscaling
self.scaler.unscale_(self.optimizer)
if hasattr(self.optimizer, "clip_grad_norm"):
# Some optimizers (like the sharded optimizer) have a specific way to do gradient clipping
self.optimizer.clip_grad_norm(args.max_grad_norm)
elif hasattr(model, "clip_grad_norm_"):
# Some models (like FullyShardedDDP) have a specific way to do gradient clipping
model.clip_grad_norm_(args.max_grad_norm)
else:
# Revert to normal clipping otherwise, handling Apex or full precision
nn.utils.clip_grad_norm_(
amp.master_params(self.optimizer) if self.use_apex else model.parameters(),
args.max_grad_norm,
)
# Optimizer step
optimizer_was_run = True
if self.deepspeed:
pass # called outside the loop
elif is_torch_tpu_available():
xm.optimizer_step(self.optimizer)
elif self.use_amp:
scale_before = self.scaler.get_scale()
self.scaler.step(self.optimizer)
self.scaler.update()
scale_after = self.scaler.get_scale()
optimizer_was_run = scale_before <= scale_after
else:
self.optimizer.step()
if optimizer_was_run and not self.deepspeed:
self.lr_scheduler.step()
model.zero_grad()
self.state.global_step += 1
self.state.epoch = epoch + (step + 1) / steps_in_epoch
self.control = self.callback_handler.on_step_end(args, self.state, self.control)
self._maybe_log_save_evaluate(tr_loss, model, trial, epoch, ignore_keys_for_eval)
else:
self.control = self.callback_handler.on_substep_end(args, self.state, self.control)
if self.control.should_epoch_stop or self.control.should_training_stop:
break
self.control = self.callback_handler.on_epoch_end(args, self.state, self.control)
self._maybe_log_save_evaluate(tr_loss, model, trial, epoch, ignore_keys_for_eval)
if DebugOption.TPU_METRICS_DEBUG in self.args.debug:
if is_torch_tpu_available():
# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
xm.master_print(met.metrics_report())
else:
logger.warning(
"You enabled PyTorch/XLA debug metrics but you don't have a TPU "
"configured. Check your training configuration if this is unexpected."
)
if self.control.should_training_stop:
break
if args.past_index and hasattr(self, "_past"):
# Clean the state at the end of training
delattr(self, "_past")
logger.info("\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n")
if args.load_best_model_at_end and self.state.best_model_checkpoint is not None:
# Wait for everyone to get here so we are sur the model has been saved by process 0.
if is_torch_tpu_available():
xm.rendezvous("load_best_model_at_end")
elif args.local_rank != -1:
dist.barrier()
logger.info(
f"Loading best model from {self.state.best_model_checkpoint} (score: {self.state.best_metric})."
)
best_model_path = os.path.join(self.state.best_model_checkpoint, WEIGHTS_NAME)
if os.path.exists(best_model_path):
# We load the model state dict on the CPU to avoid an OOM error.
state_dict = torch.load(best_model_path, map_location="cpu")
# If the model is on the GPU, it still works!
self._load_state_dict_in_model(state_dict)
else:
logger.warn(
f"Could not locate the best model at {best_model_path}, if you are running a distributed training "
"on multiple nodes, you should activate `--save_on_each_node`."
)
if self.deepspeed:
self.deepspeed.load_checkpoint(
self.state.best_model_checkpoint, load_optimizer_states=False, load_lr_scheduler_states=False
)
# add remaining tr_loss
self._total_loss_scalar += tr_loss.item()
train_loss = self._total_loss_scalar / self.state.global_step
metrics = speed_metrics("train", start_time, num_samples=num_train_samples, num_steps=self.state.max_steps)
self.store_flos()
metrics["total_flos"] = self.state.total_flos
metrics["train_loss"] = train_loss
self.is_in_train = False
self._memory_tracker.stop_and_update_metrics(metrics)
self.log(metrics)
self.control = self.callback_handler.on_train_end(args, self.state, self.control)
return TrainOutput(self.state.global_step, train_loss, metrics)
def _load_state_dict_in_model(self, state_dict):
load_result = self.model.load_state_dict(state_dict, strict=False)
if len(load_result.missing_keys) != 0:
if set(load_result.missing_keys) == set(self.model._keys_to_ignore_on_save):
self.model.tie_weights()
else:
logger.warn(f"There were missing keys in the checkpoint model loaded: {load_result.missing_keys}.")
if len(load_result.unexpected_keys) != 0:
logger.warn(f"There were unexpected keys in the checkpoint model loaded: {load_result.unexpected_keys}.")
def _maybe_log_save_evaluate(self, tr_loss, model, trial, epoch, ignore_keys_for_eval):
if self.control.should_log:
logs: Dict[str, float] = {}
tr_loss_scalar = tr_loss.item()
# reset tr_loss to zero
tr_loss -= tr_loss
logs["loss"] = round(tr_loss_scalar / (self.state.global_step - self._globalstep_last_logged), 4)
logs["learning_rate"] = self._get_learning_rate()
self._total_loss_scalar += tr_loss_scalar
self._globalstep_last_logged = self.state.global_step
self.store_flos()
self.log(logs)
metrics = None
if self.control.should_evaluate:
metrics = self.evaluate(ignore_keys=ignore_keys_for_eval)
self._report_to_hp_search(trial, epoch, metrics)
if self.control.should_save:
self._save_checkpoint(model, trial, metrics=metrics)
self.control = self.callback_handler.on_save(self.args, self.state, self.control)
def _load_rng_state(self, checkpoint):
# Load RNG states from `checkpoint`
if checkpoint is None:
return
local_rank = xm.get_local_ordinal() if is_torch_tpu_available() else self.args.local_rank
if local_rank != -1:
rng_file = os.path.join(checkpoint, f"rng_state_{local_rank}.pth")
if not os.path.isfile(os.path.join(checkpoint, rng_file)):
logger.info(
f"Didn't find an RNG file for process {local_rank}, if you are resuming a training that "
"wasn't launched in a distributed fashion, reproducibility is not guaranteed."
)
return
else:
rng_file = os.path.join(checkpoint, "rng_state.pth")
if not os.path.isfile(os.path.join(checkpoint, rng_file)):
logger.info(
"Didn't find an RNG file, if you are resuming a training that was launched in a distributed "
"fashion, reproducibility is not guaranteed."
)
return
checkpoint_rng_state = torch.load(rng_file)
random.setstate(checkpoint_rng_state["python"])
np.random.set_state(checkpoint_rng_state["numpy"])
torch.random.set_rng_state(checkpoint_rng_state["cpu"])
if torch.cuda.is_available():
if self.args.local_rank != -1:
torch.cuda.random.set_rng_state(checkpoint_rng_state["cuda"])
else:
torch.cuda.random.set_rng_state_all(checkpoint_rng_state["cuda"])
if is_torch_tpu_available():
xm.set_rng_state(checkpoint_rng_state["xla"])
def _save_checkpoint(self, model, trial, metrics=None):
# In all cases, including ddp/dp/deepspeed, self.model is always a reference to the model we
# want to save except FullyShardedDDP.
# assert unwrap_model(model) is self.model, "internal model should be a reference to self.model"
# Save model checkpoint
checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}"
if self.hp_search_backend is not None and trial is not None:
if self.hp_search_backend == HPSearchBackend.OPTUNA:
run_id = trial.number
else:
from ray import tune
run_id = tune.get_trial_id()
run_name = self.hp_name(trial) if self.hp_name is not None else f"run-{run_id}"
run_dir = os.path.join(self.args.output_dir, run_name)
else:
run_dir = self.args.output_dir
self.store_flos()
output_dir = os.path.join(run_dir, checkpoint_folder)
self.save_model(output_dir)
if self.deepspeed:
# under zero3 model file itself doesn't get saved since it's bogus! Unless deepspeed
# config `stage3_gather_fp16_weights_on_model_save` is True
self.deepspeed.save_checkpoint(output_dir)
# Save optimizer and scheduler
if self.sharded_ddp == ShardedDDPOption.SIMPLE:
self.optimizer.consolidate_state_dict()
if is_torch_tpu_available():
xm.rendezvous("saving_optimizer_states")
xm.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt"))
with warnings.catch_warnings(record=True) as caught_warnings:
xm.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
reissue_pt_warnings(caught_warnings)
elif is_sagemaker_mp_enabled():
if smp.dp_rank() == 0:
# Consolidate the state dict on all processed of dp_rank 0
opt_state_dict = self.optimizer.state_dict()
# Save it and the scheduler on the main process
if self.args.should_save:
torch.save(opt_state_dict, os.path.join(output_dir, "optimizer.pt"))
with warnings.catch_warnings(record=True) as caught_warnings:
torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
reissue_pt_warnings(caught_warnings)
if self.use_amp:
torch.save(self.scaler.state_dict(), os.path.join(output_dir, "scaler.pt"))
elif self.args.should_save and not self.deepspeed:
# deepspeed.save_checkpoint above saves model/optim/sched
torch.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt"))
with warnings.catch_warnings(record=True) as caught_warnings:
torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
reissue_pt_warnings(caught_warnings)
if self.use_amp:
torch.save(self.scaler.state_dict(), os.path.join(output_dir, "scaler.pt"))
# Determine the new best metric / best model checkpoint
if metrics is not None and self.args.metric_for_best_model is not None:
metric_to_check = self.args.metric_for_best_model
if not metric_to_check.startswith("eval_"):
metric_to_check = f"eval_{metric_to_check}"
metric_value = metrics[metric_to_check]
operator = np.greater if self.args.greater_is_better else np.less
if (
self.state.best_metric is None
or self.state.best_model_checkpoint is None
or operator(metric_value, self.state.best_metric)
):
self.state.best_metric = metric_value
self.state.best_model_checkpoint = output_dir
# Save the Trainer state
if self.args.should_save:
self.state.save_to_json(os.path.join(output_dir, "trainer_state.json"))
# Save RNG state in non-distributed training
rng_states = {
"python": random.getstate(),
"numpy": np.random.get_state(),
"cpu": torch.random.get_rng_state(),
}
if torch.cuda.is_available():
if self.args.local_rank == -1:
# In non distributed, we save the global CUDA RNG state (will take care of DataParallel)
rng_states["cuda"] = torch.cuda.random.get_rng_state_all()
else:
rng_states["cuda"] = torch.cuda.random.get_rng_state()
if is_torch_tpu_available():
rng_states["xla"] = xm.get_rng_state()
# A process can arrive here before the process 0 has a chance to save the model, in which case output_dir may
# not yet exist.
os.makedirs(output_dir, exist_ok=True)
local_rank = xm.get_local_ordinal() if is_torch_tpu_available() else self.args.local_rank
if local_rank == -1:
torch.save(rng_states, os.path.join(output_dir, "rng_state.pth"))
else:
torch.save(rng_states, os.path.join(output_dir, f"rng_state_{local_rank}.pth"))
# Maybe delete some older checkpoints.
if self.args.should_save:
self._rotate_checkpoints(use_mtime=True, output_dir=run_dir)
def _load_optimizer_and_scheduler(self, checkpoint):
"""If optimizer and scheduler states exist, load them."""
if checkpoint is None:
return
if self.deepspeed:
# deepspeed loads optimizer/lr_scheduler together with the model in deepspeed_init
return
if os.path.isfile(os.path.join(checkpoint, "optimizer.pt")) and os.path.isfile(
os.path.join(checkpoint, "scheduler.pt")
):
# Load in optimizer and scheduler states
if is_torch_tpu_available():
# On TPU we have to take some extra precautions to properly load the states on the right device.
optimizer_state = torch.load(os.path.join(checkpoint, "optimizer.pt"), map_location="cpu")
with warnings.catch_warnings(record=True) as caught_warnings:
lr_scheduler_state = torch.load(os.path.join(checkpoint, "scheduler.pt"), map_location="cpu")
reissue_pt_warnings(caught_warnings)
xm.send_cpu_data_to_device(optimizer_state, self.args.device)
xm.send_cpu_data_to_device(lr_scheduler_state, self.args.device)
self.optimizer.load_state_dict(optimizer_state)
self.lr_scheduler.load_state_dict(lr_scheduler_state)
else:
map_location = "cpu" if is_sagemaker_mp_enabled() else self.args.device
self.optimizer.load_state_dict(
torch.load(os.path.join(checkpoint, "optimizer.pt"), map_location=map_location)
)
with warnings.catch_warnings(record=True) as caught_warnings:
self.lr_scheduler.load_state_dict(torch.load(os.path.join(checkpoint, "scheduler.pt")))
reissue_pt_warnings(caught_warnings)
if self.use_amp and os.path.isfile(os.path.join(checkpoint, "scaler.pt")):
self.scaler.load_state_dict(torch.load(os.path.join(checkpoint, "scaler.pt")))
def hyperparameter_search(
self,
hp_space: Optional[Callable[["optuna.Trial"], Dict[str, float]]] = None,
compute_objective: Optional[Callable[[Dict[str, float]], float]] = None,
n_trials: int = 20,
direction: str = "minimize",
backend: Optional[Union["str", HPSearchBackend]] = None,
hp_name: Optional[Callable[["optuna.Trial"], str]] = None,
**kwargs,
) -> BestRun:
"""
Launch an hyperparameter search using ``optuna`` or ``Ray Tune``. The optimized quantity is determined by
:obj:`compute_objective`, which defaults to a function returning the evaluation loss when no metric is
provided, the sum of all metrics otherwise.
.. warning::
To use this method, you need to have provided a ``model_init`` when initializing your
:class:`~transformers.Trainer`: we need to reinitialize the model at each new run. This is incompatible
with the ``optimizers`` argument, so you need to subclass :class:`~transformers.Trainer` and override the
method :meth:`~transformers.Trainer.create_optimizer_and_scheduler` for custom optimizer/scheduler.
Args:
hp_space (:obj:`Callable[["optuna.Trial"], Dict[str, float]]`, `optional`):
A function that defines the hyperparameter search space. Will default to
:func:`~transformers.trainer_utils.default_hp_space_optuna` or
:func:`~transformers.trainer_utils.default_hp_space_ray` depending on your backend.
compute_objective (:obj:`Callable[[Dict[str, float]], float]`, `optional`):
A function computing the objective to minimize or maximize from the metrics returned by the
:obj:`evaluate` method. Will default to :func:`~transformers.trainer_utils.default_compute_objective`.
n_trials (:obj:`int`, `optional`, defaults to 100):
The number of trial runs to test.
direction(:obj:`str`, `optional`, defaults to :obj:`"minimize"`):
Whether to optimize greater or lower objects. Can be :obj:`"minimize"` or :obj:`"maximize"`, you should
pick :obj:`"minimize"` when optimizing the validation loss, :obj:`"maximize"` when optimizing one or
several metrics.
backend(:obj:`str` or :class:`~transformers.training_utils.HPSearchBackend`, `optional`):
The backend to use for hyperparameter search. Will default to optuna or Ray Tune, depending on which
one is installed. If both are installed, will default to optuna.
kwargs:
Additional keyword arguments passed along to :obj:`optuna.create_study` or :obj:`ray.tune.run`. For
more information see:
- the documentation of `optuna.create_study
<https://optuna.readthedocs.io/en/stable/reference/generated/optuna.study.create_study.html>`__
- the documentation of `tune.run
<https://docs.ray.io/en/latest/tune/api_docs/execution.html#tune-run>`__
Returns:
:class:`transformers.trainer_utils.BestRun`: All the information about the best run.
"""
if backend is None:
backend = default_hp_search_backend()
if backend is None:
raise RuntimeError(
"At least one of optuna or ray should be installed. "
"To install optuna run `pip install optuna`."
"To install ray run `pip install ray[tune]`."
)
backend = HPSearchBackend(backend)
if backend == HPSearchBackend.OPTUNA and not is_optuna_available():
raise RuntimeError("You picked the optuna backend, but it is not installed. Use `pip install optuna`.")
if backend == HPSearchBackend.RAY and not is_ray_tune_available():
raise RuntimeError(
"You picked the Ray Tune backend, but it is not installed. Use `pip install 'ray[tune]'`."
)
self.hp_search_backend = backend
if self.model_init is None:
raise RuntimeError(
"To use hyperparameter search, you need to pass your model through a model_init function."
)
self.hp_space = default_hp_space[backend] if hp_space is None else hp_space
self.hp_name = hp_name
self.compute_objective = default_compute_objective if compute_objective is None else compute_objective
run_hp_search = run_hp_search_optuna if backend == HPSearchBackend.OPTUNA else run_hp_search_ray
best_run = run_hp_search(self, n_trials, direction, **kwargs)
self.hp_search_backend = None
return best_run
def log(self, logs: Dict[str, float]) -> None:
"""
Log :obj:`logs` on the various objects watching training.
Subclass and override this method to inject custom behavior.
Args:
logs (:obj:`Dict[str, float]`):
The values to log.
"""
if self.state.epoch is not None:
logs["epoch"] = round(self.state.epoch, 2)
output = {**logs, **{"step": self.state.global_step}}
self.state.log_history.append(output)
self.control = self.callback_handler.on_log(self.args, self.state, self.control, logs)
def _prepare_inputs(self, inputs: Dict[str, Union[torch.Tensor, Any]]) -> Dict[str, Union[torch.Tensor, Any]]:
"""
Prepare :obj:`inputs` before feeding them to the model, converting them to tensors if they are not already and
handling potential state.
"""
for k, v in inputs.items():
if isinstance(v, torch.Tensor):
kwargs = dict(device=self.args.device)
if self.deepspeed and inputs[k].dtype != torch.int64:
# NLP models inputs are int64 and those get adjusted to the right dtype of the
# embedding. Other models such as wav2vec2's inputs are already float and thus
# may need special handling to match the dtypes of the model
kwargs.update(dict(dtype=self.args.hf_deepspeed_config.dtype()))
inputs[k] = v.to(**kwargs)
if self.args.past_index >= 0 and self._past is not None:
inputs["mems"] = self._past
return inputs
def training_step(self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]) -> torch.Tensor:
"""
Perform a training step on a batch of inputs.
Subclass and override to inject custom behavior.
Args:
model (:obj:`nn.Module`):
The model to train.
inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):
The inputs and targets of the model.
The dictionary will be unpacked before being fed to the model. Most models expect the targets under the
argument :obj:`labels`. Check your model's documentation for all accepted arguments.
Return:
:obj:`torch.Tensor`: The tensor with training loss on this batch.
"""
model.train()
inputs = self._prepare_inputs(inputs)
if is_sagemaker_mp_enabled():
scaler = self.scaler if self.use_amp else None
loss_mb = smp_forward_backward(model, inputs, self.args.gradient_accumulation_steps, scaler=scaler)
return loss_mb.reduce_mean().detach().to(self.args.device)
if self.use_amp:
with autocast():
loss = self.compute_loss(model, inputs)
else:
loss = self.compute_loss(model, inputs)
if self.args.n_gpu > 1:
loss = loss.mean() # mean() to average on multi-gpu parallel training
if self.args.gradient_accumulation_steps > 1 and not self.deepspeed:
# deepspeed handles loss scaling by gradient_accumulation_steps in its `backward`
loss = loss / self.args.gradient_accumulation_steps
if self.use_amp:
self.scaler.scale(loss).backward()
elif self.use_apex:
with amp.scale_loss(loss, self.optimizer) as scaled_loss:
scaled_loss.backward()
elif self.deepspeed:
# loss gets scaled under gradient_accumulation_steps in deepspeed
loss = self.deepspeed.backward(loss)
else:
loss.backward()
return loss.detach()
def compute_loss(self, model, inputs, return_outputs=False):
"""
How the loss is computed by Trainer. By default, all models return the loss in the first element.
Subclass and override for custom behavior.
"""
if self.label_smoother is not None and "labels" in inputs:
labels = inputs.pop("labels")
else:
labels = None
outputs = model(**inputs)
# Save past state if it exists
# TODO: this needs to be fixed and made cleaner later.
if self.args.past_index >= 0:
self._past = outputs[self.args.past_index]
if labels is not None:
loss = self.label_smoother(outputs, labels)
else:
# We don't use .loss here since the model may return tuples instead of ModelOutput.
loss = outputs["loss"] if isinstance(outputs, dict) else outputs[0]
return (loss, outputs) if return_outputs else loss
def is_local_process_zero(self) -> bool:
"""
Whether or not this process is the local (e.g., on one machine if training in a distributed fashion on several
machines) main process.
"""
return self.args.local_process_index == 0
def is_world_process_zero(self) -> bool:
"""
Whether or not this process is the global main process (when training in a distributed fashion on several
machines, this is only going to be :obj:`True` for one process).
"""
# Special case for SageMaker ModelParallel since there process_index is dp_process_index, not the global
# process index.
if is_sagemaker_mp_enabled():
return smp.rank() == 0
else:
return self.args.process_index == 0
def save_model(self, output_dir: Optional[str] = None):
"""
Will save the model, so you can reload it using :obj:`from_pretrained()`.
Will only save from the main process.
"""
if output_dir is None:
output_dir = self.args.output_dir
if is_torch_tpu_available():
self._save_tpu(output_dir)
elif is_sagemaker_mp_enabled():
# Calling the state_dict needs to be done on the wrapped model and on all processes.
state_dict = self.model_wrapped.state_dict()
if self.args.should_save:
self._save(output_dir, state_dict=state_dict)
elif (
ShardedDDPOption.ZERO_DP_2 in self.args.sharded_ddp or ShardedDDPOption.ZERO_DP_3 in self.args.sharded_ddp
):
state_dict = self.model.state_dict()
if self.args.should_save:
self._save(output_dir, state_dict=state_dict)
elif self.deepspeed:
# this takes care of everything as long as we aren't under zero3
if self.args.should_save:
self._save(output_dir)
if is_deepspeed_zero3_enabled():
# It's too complicated to try to override different places where the weights dump gets
# saved, so since under zero3 the file is bogus, simply delete it. The user should
# either user deepspeed checkpoint to resume or to recover full weights use
# zero_to_fp32.py stored in the checkpoint.
if self.args.should_save:
file = os.path.join(output_dir, WEIGHTS_NAME)
if os.path.isfile(file):
# logger.info(f"deepspeed zero3: removing {file}, see zero_to_fp32.py to recover weights")
os.remove(file)
# now save the real model if stage3_gather_fp16_weights_on_model_save=True
# if false it will not be saved.
# This must be called on all ranks
self.deepspeed.save_fp16_model(output_dir, WEIGHTS_NAME)
elif self.args.should_save:
self._save(output_dir)
def _save_tpu(self, output_dir: Optional[str] = None):
output_dir = output_dir if output_dir is not None else self.args.output_dir
logger.info(f"Saving model checkpoint to {output_dir}")
if xm.is_master_ordinal():
os.makedirs(output_dir, exist_ok=True)
torch.save(self.args, os.path.join(output_dir, "training_args.bin"))
# Save a trained model and configuration using `save_pretrained()`.
# They can then be reloaded using `from_pretrained()`
xm.rendezvous("saving_checkpoint")
if not isinstance(self.model, PreTrainedModel):
if isinstance(unwrap_model(self.model), PreTrainedModel):
unwrap_model(self.model).save_pretrained(
output_dir,
save_config=self.args.should_save,
state_dict=self.model.state_dict(),
save_function=xm.save,
)
else:
logger.info("Trainer.model is not a `PreTrainedModel`, only saving its state dict.")
state_dict = self.model.state_dict()
xm.save(state_dict, os.path.join(output_dir, WEIGHTS_NAME))
else:
self.model.save_pretrained(output_dir, save_config=self.args.should_save, save_function=xm.save)
if self.tokenizer is not None and self.args.should_save:
self.tokenizer.save_pretrained(output_dir)
def _save(self, output_dir: Optional[str] = None, state_dict=None):
# If we are executing this function, we are the process zero, so we don't check for that.
output_dir = output_dir if output_dir is not None else self.args.output_dir
os.makedirs(output_dir, exist_ok=True)
logger.info(f"Saving model checkpoint to {output_dir}")
# Save a trained model and configuration using `save_pretrained()`.
# They can then be reloaded using `from_pretrained()`
if not isinstance(self.model, PreTrainedModel):
if isinstance(unwrap_model(self.model), PreTrainedModel):
if state_dict is None:
state_dict = self.model.state_dict()
unwrap_model(self.model).save_pretrained(output_dir, state_dict=state_dict)
else:
logger.info("Trainer.model is not a `PreTrainedModel`, only saving its state dict.")
if state_dict is None:
state_dict = self.model.state_dict()
torch.save(state_dict, os.path.join(output_dir, WEIGHTS_NAME))
else:
self.model.save_pretrained(output_dir, state_dict=state_dict)
if self.tokenizer is not None:
self.tokenizer.save_pretrained(output_dir)
# Good practice: save your training arguments together with the trained model
torch.save(self.args, os.path.join(output_dir, "training_args.bin"))
def store_flos(self):
# Storing the number of floating-point operations that went into the model
if self.args.local_rank != -1:
self.state.total_flos += distributed_broadcast_scalars([self.current_flos]).sum().item()
self.current_flos = 0
else:
self.state.total_flos += self.current_flos
self.current_flos = 0
def _sorted_checkpoints(
self, output_dir=None, checkpoint_prefix=PREFIX_CHECKPOINT_DIR, use_mtime=False
) -> List[str]:
ordering_and_checkpoint_path = []
glob_checkpoints = [str(x) for x in Path(output_dir).glob(f"{checkpoint_prefix}-*")]
for path in glob_checkpoints:
if use_mtime:
ordering_and_checkpoint_path.append((os.path.getmtime(path), path))
else:
regex_match = re.match(f".*{checkpoint_prefix}-([0-9]+)", path)
if regex_match is not None and regex_match.groups() is not None:
ordering_and_checkpoint_path.append((int(regex_match.groups()[0]), path))
checkpoints_sorted = sorted(ordering_and_checkpoint_path)
checkpoints_sorted = [checkpoint[1] for checkpoint in checkpoints_sorted]
# Make sure we don't delete the best model.
if self.state.best_model_checkpoint is not None:
best_model_index = checkpoints_sorted.index(str(Path(self.state.best_model_checkpoint)))
for i in range(best_model_index, len(checkpoints_sorted) - 2):
checkpoints_sorted[i], checkpoints_sorted[i + 1] = checkpoints_sorted[i + 1], checkpoints_sorted[i]
return checkpoints_sorted
def _rotate_checkpoints(self, use_mtime=False, output_dir=None) -> None:
if self.args.save_total_limit is None or self.args.save_total_limit <= 0:
return
# Check if we should delete older checkpoint(s)
checkpoints_sorted = self._sorted_checkpoints(use_mtime=use_mtime, output_dir=output_dir)
if len(checkpoints_sorted) <= self.args.save_total_limit:
return
# If save_total_limit=1 with load_best_model_at_end=True, we could end up deleting the last checkpoint, which
# we don't do to allow resuming.
save_total_limit = self.args.save_total_limit
if (
self.state.best_model_checkpoint is not None
and self.args.save_total_limit == 1
and checkpoints_sorted[-1] != self.state.best_model_checkpoint
):
save_total_limit = 2
number_of_checkpoints_to_delete = max(0, len(checkpoints_sorted) - save_total_limit)
checkpoints_to_be_deleted = checkpoints_sorted[:number_of_checkpoints_to_delete]
for checkpoint in checkpoints_to_be_deleted:
logger.info(f"Deleting older checkpoint [{checkpoint}] due to args.save_total_limit")
shutil.rmtree(checkpoint)
def evaluate(
self,
eval_dataset: Optional[Dataset] = None,
ignore_keys: Optional[List[str]] = None,
metric_key_prefix: str = "eval",
) -> Dict[str, float]:
"""
Run evaluation and returns metrics.
The calling script will be responsible for providing a method to compute metrics, as they are task-dependent
(pass it to the init :obj:`compute_metrics` argument).
You can also subclass and override this method to inject custom behavior.
Args:
eval_dataset (:obj:`Dataset`, `optional`):
Pass a dataset if you wish to override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`,
columns not accepted by the ``model.forward()`` method are automatically removed. It must implement the
:obj:`__len__` method.
ignore_keys (:obj:`Lst[str]`, `optional`):
A list of keys in the output of your model (if it is a dictionary) that should be ignored when
gathering predictions.
metric_key_prefix (:obj:`str`, `optional`, defaults to :obj:`"eval"`):
An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named
"eval_bleu" if the prefix is "eval" (default)
Returns:
A dictionary containing the evaluation loss and the potential metrics computed from the predictions. The
dictionary also contains the epoch number which comes from the training state.
"""
# memory metrics - must set up as early as possible
self._memory_tracker.start()
eval_dataloader = self.get_eval_dataloader(eval_dataset)
start_time = time.time()
eval_loop = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
output = eval_loop(
eval_dataloader,
description="Evaluation",
# No point gathering the predictions if there are no metrics, otherwise we defer to
# self.args.prediction_loss_only
prediction_loss_only=True if self.compute_metrics is None else None,
ignore_keys=ignore_keys,
metric_key_prefix=metric_key_prefix,
)
total_batch_size = self.args.eval_batch_size * self.args.world_size
output.metrics.update(
speed_metrics(
metric_key_prefix,
start_time,
num_samples=output.num_samples,
num_steps=math.ceil(output.num_samples / total_batch_size),
)
)
self.log(output.metrics)
if DebugOption.TPU_METRICS_DEBUG in self.args.debug:
# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
xm.master_print(met.metrics_report())
self.control = self.callback_handler.on_evaluate(self.args, self.state, self.control, output.metrics)
self._memory_tracker.stop_and_update_metrics(output.metrics)
return output.metrics
def predict(
self, test_dataset: Dataset, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "test"
) -> PredictionOutput:
"""
Run prediction and returns predictions and potential metrics.
Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method
will also return metrics, like in :obj:`evaluate()`.
Args:
test_dataset (:obj:`Dataset`):
Dataset to run the predictions on. If it is an :obj:`datasets.Dataset`, columns not accepted by the
``model.forward()`` method are automatically removed. Has to implement the method :obj:`__len__`
ignore_keys (:obj:`Lst[str]`, `optional`):
A list of keys in the output of your model (if it is a dictionary) that should be ignored when
gathering predictions.
metric_key_prefix (:obj:`str`, `optional`, defaults to :obj:`"test"`):
An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named
"test_bleu" if the prefix is "test" (default)
.. note::
If your predictions or labels have different sequence length (for instance because you're doing dynamic
padding in a token classification task) the predictions will be padded (on the right) to allow for
concatenation into one array. The padding index is -100.
Returns: `NamedTuple` A namedtuple with the following keys:
- predictions (:obj:`np.ndarray`): The predictions on :obj:`test_dataset`.
- label_ids (:obj:`np.ndarray`, `optional`): The labels (if the dataset contained some).
- metrics (:obj:`Dict[str, float]`, `optional`): The potential dictionary of metrics (if the dataset
contained labels).
"""
# memory metrics - must set up as early as possible
self._memory_tracker.start()
test_dataloader = self.get_test_dataloader(test_dataset)
start_time = time.time()
eval_loop = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
output = eval_loop(
test_dataloader, description="Prediction", ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix
)
total_batch_size = self.args.eval_batch_size * self.args.world_size
output.metrics.update(
speed_metrics(
metric_key_prefix,
start_time,
num_samples=output.num_samples,
num_steps=math.ceil(output.num_samples / total_batch_size),
)
)
self._memory_tracker.stop_and_update_metrics(output.metrics)
return PredictionOutput(predictions=output.predictions, label_ids=output.label_ids, metrics=output.metrics)
def evaluation_loop(
self,
dataloader: DataLoader,
description: str,
prediction_loss_only: Optional[bool] = None,
ignore_keys: Optional[List[str]] = None,
metric_key_prefix: str = "eval",
) -> EvalLoopOutput:
"""
Prediction/evaluation loop, shared by :obj:`Trainer.evaluate()` and :obj:`Trainer.predict()`.
Works both with or without labels.
"""
prediction_loss_only = (
prediction_loss_only if prediction_loss_only is not None else self.args.prediction_loss_only
)
# if eval is called w/o train init deepspeed here
if self.args.deepspeed and not self.deepspeed:
# XXX: eval doesn't have `resume_from_checkpoint` arg but we should be able to do eval
# from the checkpoint eventually
deepspeed_engine, _, _ = deepspeed_init(self, num_training_steps=0, resume_from_checkpoint=None)
self.model = deepspeed_engine.module
self.model_wrapped = deepspeed_engine
self.deepspeed = deepspeed_engine
# XXX: we don't need optim/sched for inference, but this needs to be sorted out, since
# for example the Z3-optimizer is a must for zero3 to work even for inference - what we
# don't need is the deepspeed basic optimizer which is self.optimizer.optimizer
deepspeed_engine.optimizer.optimizer = None
deepspeed_engine.lr_scheduler = None
model = self._wrap_model(self.model, training=False)
# if full fp16 is wanted on eval and this ``evaluation`` or ``predict`` isn't called while
# ``train`` is running, halve it first and then put on device
if not self.is_in_train and self.args.fp16_full_eval:
model = model.half().to(self.args.device)
batch_size = dataloader.batch_size
logger.info(f"***** Running {description} *****")
if isinstance(dataloader.dataset, collections.abc.Sized):
logger.info(f" Num examples = {self.num_examples(dataloader)}")
else:
logger.info(" Num examples: Unknown")
logger.info(f" Batch size = {batch_size}")
model.eval()
self.callback_handler.eval_dataloader = dataloader
# Do this before wrapping.
eval_dataset = dataloader.dataset
if is_torch_tpu_available():
dataloader = pl.ParallelLoader(dataloader, [self.args.device]).per_device_loader(self.args.device)
if self.args.past_index >= 0:
self._past = None
# Initialize containers
# losses/preds/labels on GPU/TPU (accumulated for eval_accumulation_steps)
losses_host = None
preds_host = None
labels_host = None
# losses/preds/labels on CPU (final containers)
all_losses = None
all_preds = None
all_labels = None
# Will be useful when we have an iterable dataset so don't know its length.
observed_num_examples = 0
# Main evaluation loop
for step, inputs in enumerate(dataloader):
# Update the observed num examples
observed_batch_size = find_batch_size(inputs)
if observed_batch_size is not None:
observed_num_examples += observed_batch_size
# Prediction step
loss, logits, labels = self.prediction_step(model, inputs, prediction_loss_only, ignore_keys=ignore_keys)
# Update containers on host
if loss is not None:
losses = self._nested_gather(loss.repeat(batch_size))
losses_host = losses if losses_host is None else torch.cat((losses_host, losses), dim=0)
if logits is not None:
logits = self._pad_across_processes(logits)
logits = self._nested_gather(logits)
preds_host = logits if preds_host is None else nested_concat(preds_host, logits, padding_index=-100)
if labels is not None:
labels = self._pad_across_processes(labels)
labels = self._nested_gather(labels)
labels_host = labels if labels_host is None else nested_concat(labels_host, labels, padding_index=-100)
self.control = self.callback_handler.on_prediction_step(self.args, self.state, self.control)
# Gather all tensors and put them back on the CPU if we have done enough accumulation steps.
if self.args.eval_accumulation_steps is not None and (step + 1) % self.args.eval_accumulation_steps == 0:
if losses_host is not None:
losses = nested_numpify(losses_host)
all_losses = losses if all_losses is None else np.concatenate((all_losses, losses), axis=0)
if preds_host is not None:
logits = nested_numpify(preds_host)
all_preds = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-100)
if labels_host is not None:
labels = nested_numpify(labels_host)
all_labels = (
labels if all_labels is None else nested_concat(all_labels, labels, padding_index=-100)
)
# Set back to None to begin a new accumulation
losses_host, preds_host, labels_host = None, None, None
if self.args.past_index and hasattr(self, "_past"):
# Clean the state at the end of the evaluation loop
delattr(self, "_past")
# Gather all remaining tensors and put them back on the CPU
if losses_host is not None:
losses = nested_numpify(losses_host)
all_losses = losses if all_losses is None else np.concatenate((all_losses, losses), axis=0)
if preds_host is not None:
logits = nested_numpify(preds_host)
all_preds = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-100)
if labels_host is not None:
labels = nested_numpify(labels_host)
all_labels = labels if all_labels is None else nested_concat(all_labels, labels, padding_index=-100)
# Number of samples
if not isinstance(eval_dataset, IterableDataset):
num_samples = len(eval_dataset)
# The instance check is weird and does not actually check for the type, but whether the dataset has the right
# methods. Therefore we need to make sure it also has the attribute.
elif isinstance(eval_dataset, IterableDatasetShard) and hasattr(eval_dataset, "num_examples"):
num_samples = eval_dataset.num_examples
else:
num_samples = observed_num_examples
# Number of losses has been rounded to a multiple of batch_size and in a distributed training, the number of
# samplers has been rounded to a multiple of batch_size, so we truncate.
if all_losses is not None:
all_losses = all_losses[:num_samples]
if all_preds is not None:
all_preds = nested_truncate(all_preds, num_samples)
if all_labels is not None:
all_labels = nested_truncate(all_labels, num_samples)
# Metrics!
if self.compute_metrics is not None and all_preds is not None and all_labels is not None:
metrics = self.compute_metrics(EvalPrediction(predictions=all_preds, label_ids=all_labels))
else:
metrics = {}
# To be JSON-serializable, we need to remove numpy types or zero-d tensors
metrics = denumpify_detensorize(metrics)
if all_losses is not None:
metrics[f"{metric_key_prefix}_loss"] = all_losses.mean().item()
# Prefix all keys with metric_key_prefix + '_'
for key in list(metrics.keys()):
if not key.startswith(f"{metric_key_prefix}_"):
metrics[f"{metric_key_prefix}_{key}"] = metrics.pop(key)
return EvalLoopOutput(predictions=all_preds, label_ids=all_labels, metrics=metrics, num_samples=num_samples)
def _nested_gather(self, tensors, name=None):
"""
Gather value of `tensors` (tensor or list/tuple of nested tensors) and convert them to numpy before
concatenating them to `gathered`
"""
if tensors is None:
return
if is_torch_tpu_available():
if name is None:
name = "nested_gather"
tensors = nested_xla_mesh_reduce(tensors, name)
elif is_sagemaker_mp_enabled():
tensors = smp_gather(tensors)
elif self.args.local_rank != -1:
tensors = distributed_concat(tensors)
return tensors
# Copied from Accelerate.
def _pad_across_processes(self, tensor, pad_index=-100):
"""
Recursively pad the tensors in a nested list/tuple/dictionary of tensors from all devices to the same size so
they can safely be gathered.
"""
if isinstance(tensor, (list, tuple)):
return type(tensor)(self._pad_across_processes(t, pad_index=pad_index) for t in tensor)
elif isinstance(tensor, dict):
return type(tensor)({k: self._pad_across_processes(v, pad_index=pad_index) for k, v in tensor.items()})
elif not isinstance(tensor, torch.Tensor):
raise TypeError(
f"Can't pad the values of type {type(tensor)}, only of nested list/tuple/dicts of tensors."
)
if len(tensor.shape) < 2:
return tensor
# Gather all sizes
size = torch.tensor(tensor.shape, device=tensor.device)[None]
sizes = self._nested_gather(size).cpu()
max_size = max(s[1] for s in sizes)
if tensor.shape[1] == max_size:
return tensor
# Then pad to the maximum size
old_size = tensor.shape
new_size = list(old_size)
new_size[1] = max_size
new_tensor = tensor.new_zeros(tuple(new_size)) + pad_index
new_tensor[:, : old_size[1]] = tensor
return new_tensor
def prediction_step(
self,
model: nn.Module,
inputs: Dict[str, Union[torch.Tensor, Any]],
prediction_loss_only: bool,
ignore_keys: Optional[List[str]] = None,
) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]:
"""
Perform an evaluation step on :obj:`model` using obj:`inputs`.
Subclass and override to inject custom behavior.
Args:
model (:obj:`nn.Module`):
The model to evaluate.
inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):
The inputs and targets of the model.
The dictionary will be unpacked before being fed to the model. Most models expect the targets under the
argument :obj:`labels`. Check your model's documentation for all accepted arguments.
prediction_loss_only (:obj:`bool`):
Whether or not to return the loss only.
ignore_keys (:obj:`Lst[str]`, `optional`):
A list of keys in the output of your model (if it is a dictionary) that should be ignored when
gathering predictions.
Return:
Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]: A tuple with the loss,
logits and labels (each being optional).
"""
has_labels = all(inputs.get(k) is not None for k in self.label_names)
inputs = self._prepare_inputs(inputs)
if ignore_keys is None:
if hasattr(self.model, "config"):
ignore_keys = getattr(self.model.config, "keys_to_ignore_at_inference", [])
else:
ignore_keys = []
# labels may be popped when computing the loss (label smoothing for instance) so we grab them first.
if has_labels:
labels = nested_detach(tuple(inputs.get(name) for name in self.label_names))
if len(labels) == 1:
labels = labels[0]
else:
labels = None
with torch.no_grad():
if is_sagemaker_mp_enabled():
raw_outputs = smp_forward_only(model, inputs)
if has_labels:
if isinstance(raw_outputs, dict):
loss_mb = raw_outputs["loss"]
logits_mb = tuple(v for k, v in raw_outputs.items() if k not in ignore_keys + ["loss"])
else:
loss_mb = raw_outputs[0]
logits_mb = raw_outputs[1:]
loss = loss_mb.reduce_mean().detach().cpu()
logits = smp_nested_concat(logits_mb)
else:
loss = None
if isinstance(raw_outputs, dict):
logits_mb = tuple(v for k, v in raw_outputs.items() if k not in ignore_keys)
else:
logits_mb = raw_outputs
logits = smp_nested_concat(logits_mb)
else:
if has_labels:
loss, outputs = self.compute_loss(model, inputs, return_outputs=True)
loss = loss.mean().detach()
if isinstance(outputs, dict):
logits = tuple(v for k, v in outputs.items() if k not in ignore_keys + ["loss"])
else:
logits = outputs[1:]
else:
loss = None
if self.use_amp:
with autocast():
outputs = model(**inputs)
else:
outputs = model(**inputs)
if isinstance(outputs, dict):
logits = tuple(v for k, v in outputs.items() if k not in ignore_keys)
else:
logits = outputs
# TODO: this needs to be fixed and made cleaner later.
if self.args.past_index >= 0:
self._past = outputs[self.args.past_index - 1]
if prediction_loss_only:
return (loss, None, None)
logits = nested_detach(logits)
if len(logits) == 1:
logits = logits[0]
return (loss, logits, labels)
def floating_point_ops(self, inputs: Dict[str, Union[torch.Tensor, Any]]):
"""
For models that inherit from :class:`~transformers.PreTrainedModel`, uses that method to compute the number of
floating point operations for every backward + forward pass. If using another model, either implement such a
method in the model or subclass and override this method.
Args:
inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):
The inputs and targets of the model.
Returns:
:obj:`int`: The number of floating-point operations.
"""
if hasattr(self.model, "floating_point_ops"):
return self.model.floating_point_ops(inputs)
else:
return 0
def init_git_repo(self):
"""
Initializes a git repo in :obj:`self.args.push_to_hub_model_id`.
"""
if not self.args.should_save:
return
use_auth_token = True if self.args.push_to_hub_token is None else self.args.push_to_hub_token
repo_url = PushToHubMixin._get_repo_url_from_name(
self.args.push_to_hub_model_id,
organization=self.args.push_to_hub_organization,
use_auth_token=use_auth_token,
)
self.repo = PushToHubMixin._create_or_get_repo(
self.args.output_dir, repo_url=repo_url, use_auth_token=use_auth_token
)
# By default, ignore the checkpoint folders
if not os.path.exists(os.path.join(self.args.output_dir, ".gitignore")):
with open(os.path.join(self.args.output_dir, ".gitignore"), "w", encoding="utf-8") as writer:
writer.writelines(["checkpoint-*/"])
def create_model_card(
self,
language: Optional[str] = None,
license: Optional[str] = None,
tags: Optional[str] = None,
model_name: Optional[str] = None,
finetuned_from: Optional[str] = None,
tasks: Optional[str] = None,
dataset_tags: Optional[Union[str, List[str]]] = None,
dataset: Optional[Union[str, List[str]]] = None,
dataset_args: Optional[Union[str, List[str]]] = None,
):
training_summary = TrainingSummary.from_trainer(
self,
language=language,
license=license,
tags=tags,
model_name=model_name,
finetuned_from=finetuned_from,
tasks=tasks,
dataset_tags=dataset_tags,
dataset=dataset,
dataset_args=dataset_args,
)
model_card = training_summary.to_model_card()
with open(os.path.join(self.args.output_dir, "README.md"), "w") as f:
f.write(model_card)
def push_to_hub(self, commit_message: Optional[str] = "add model", **kwargs) -> str:
"""
Upload `self.model` and `self.tokenizer` to the 🤗 model hub on the repo `self.args.push_to_hub_model_id`.
Parameters:
commit_message (:obj:`str`, `optional`, defaults to :obj:`"add model"`):
Message to commit while pushing.
kwargs:
Additional keyword arguments passed along to :meth:`~transformers.Trainer.create_model_card`.
Returns:
The url of the commit of your model in the given repository.
"""
if self.args.should_save:
self.create_model_card(model_name=self.args.push_to_hub_model_id, **kwargs)
# Needs to be executed on all processes for TPU training, but will only save on the processed determined by
# self.args.should_save.
self.save_model()
# Only push from one node.
if not self.is_world_process_zero():
return
return self.repo.push_to_hub(commit_message=commit_message)
#
# Deprecated code
#
def prediction_loop(
self,
dataloader: DataLoader,
description: str,
prediction_loss_only: Optional[bool] = None,
ignore_keys: Optional[List[str]] = None,
metric_key_prefix: str = "eval",
) -> PredictionOutput:
"""
Prediction/evaluation loop, shared by :obj:`Trainer.evaluate()` and :obj:`Trainer.predict()`.
Works both with or without labels.
"""
if not isinstance(dataloader.dataset, collections.abc.Sized):
raise ValueError("dataset must implement __len__")
prediction_loss_only = (
prediction_loss_only if prediction_loss_only is not None else self.args.prediction_loss_only
)
# if eval is called w/o train init deepspeed here
if self.args.deepspeed and not self.deepspeed:
# XXX: eval doesn't have `resume_from_checkpoint` arg but we should be able to do eval
# from the checkpoint eventually
deepspeed_engine, _, _ = deepspeed_init(self, num_training_steps=0, resume_from_checkpoint=None)
self.model = deepspeed_engine.module
self.model_wrapped = deepspeed_engine
self.deepspeed = deepspeed_engine
# XXX: we don't need optim/sched for inference, but this needs to be sorted out, since
# for example the Z3-optimizer is a must for zero3 to work even for inference - what we
# don't need is the deepspeed basic optimizer which is self.optimizer.optimizer
deepspeed_engine.optimizer.optimizer = None
deepspeed_engine.lr_scheduler = None
model = self._wrap_model(self.model, training=False)
# if full fp16 is wanted on eval and this ``evaluation`` or ``predict`` isn't called while
# ``train`` is running, halve it first and then put on device
if not self.is_in_train and self.args.fp16_full_eval:
model = model.half().to(self.args.device)
batch_size = dataloader.batch_size
num_examples = self.num_examples(dataloader)
logger.info(f"***** Running {description} *****")
logger.info(f" Num examples = {num_examples}")
logger.info(f" Batch size = {batch_size}")
losses_host: torch.Tensor = None
preds_host: Union[torch.Tensor, List[torch.Tensor]] = None
labels_host: Union[torch.Tensor, List[torch.Tensor]] = None
world_size = max(1, self.args.world_size)
eval_losses_gatherer = DistributedTensorGatherer(world_size, num_examples, make_multiple_of=batch_size)
if not prediction_loss_only:
# The actual number of eval_sample can be greater than num_examples in distributed settings (when we pass
# a batch size to the sampler)
make_multiple_of = None
if hasattr(dataloader, "sampler") and isinstance(dataloader.sampler, SequentialDistributedSampler):
make_multiple_of = dataloader.sampler.batch_size
preds_gatherer = DistributedTensorGatherer(world_size, num_examples, make_multiple_of=make_multiple_of)
labels_gatherer = DistributedTensorGatherer(world_size, num_examples, make_multiple_of=make_multiple_of)
model.eval()
if is_torch_tpu_available():
dataloader = pl.ParallelLoader(dataloader, [self.args.device]).per_device_loader(self.args.device)
if self.args.past_index >= 0:
self._past = None
self.callback_handler.eval_dataloader = dataloader
for step, inputs in enumerate(dataloader):
loss, logits, labels = self.prediction_step(model, inputs, prediction_loss_only, ignore_keys=ignore_keys)
if loss is not None:
losses = loss.repeat(batch_size)
losses_host = losses if losses_host is None else torch.cat((losses_host, losses), dim=0)
if logits is not None:
preds_host = logits if preds_host is None else nested_concat(preds_host, logits, padding_index=-100)
if labels is not None:
labels_host = labels if labels_host is None else nested_concat(labels_host, labels, padding_index=-100)
self.control = self.callback_handler.on_prediction_step(self.args, self.state, self.control)
# Gather all tensors and put them back on the CPU if we have done enough accumulation steps.
if self.args.eval_accumulation_steps is not None and (step + 1) % self.args.eval_accumulation_steps == 0:
eval_losses_gatherer.add_arrays(self._gather_and_numpify(losses_host, "eval_losses"))
if not prediction_loss_only:
preds_gatherer.add_arrays(self._gather_and_numpify(preds_host, "eval_preds"))
labels_gatherer.add_arrays(self._gather_and_numpify(labels_host, "eval_label_ids"))
# Set back to None to begin a new accumulation
losses_host, preds_host, labels_host = None, None, None
if self.args.past_index and hasattr(self, "_past"):
# Clean the state at the end of the evaluation loop
delattr(self, "_past")
# Gather all remaining tensors and put them back on the CPU
eval_losses_gatherer.add_arrays(self._gather_and_numpify(losses_host, "eval_losses"))
if not prediction_loss_only:
preds_gatherer.add_arrays(self._gather_and_numpify(preds_host, "eval_preds"))
labels_gatherer.add_arrays(self._gather_and_numpify(labels_host, "eval_label_ids"))
eval_loss = eval_losses_gatherer.finalize()
preds = preds_gatherer.finalize() if not prediction_loss_only else None
label_ids = labels_gatherer.finalize() if not prediction_loss_only else None
if self.compute_metrics is not None and preds is not None and label_ids is not None:
metrics = self.compute_metrics(EvalPrediction(predictions=preds, label_ids=label_ids))
else:
metrics = {}
# To be JSON-serializable, we need to remove numpy types or zero-d tensors
metrics = denumpify_detensorize(metrics)
if eval_loss is not None:
metrics[f"{metric_key_prefix}_loss"] = eval_loss.mean().item()
# Prefix all keys with metric_key_prefix + '_'
for key in list(metrics.keys()):
if not key.startswith(f"{metric_key_prefix}_"):
metrics[f"{metric_key_prefix}_{key}"] = metrics.pop(key)
return PredictionOutput(predictions=preds, label_ids=label_ids, metrics=metrics)
def _gather_and_numpify(self, tensors, name):
"""
Gather value of `tensors` (tensor or list/tuple of nested tensors) and convert them to numpy before
concatenating them to `gathered`
"""
if tensors is None:
return
if is_torch_tpu_available():
tensors = nested_xla_mesh_reduce(tensors, name)
elif is_sagemaker_mp_enabled():
tensors = smp_gather(tensors)
elif self.args.local_rank != -1:
tensors = distributed_concat(tensors)
return nested_numpify(tensors)
| # coding=utf-8
# Copyright 2020-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
The Trainer class, to easily train a 🤗 Transformers from scratch or finetune it on a new task.
"""
import collections
import inspect
import math
import os
import random
import re
import shutil
import sys
import time
import warnings
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
from tqdm.auto import tqdm
# Integrations must be imported before ML frameworks:
from .integrations import ( # isort: split
default_hp_search_backend,
get_reporting_integration_callbacks,
hp_params,
is_fairscale_available,
is_optuna_available,
is_ray_tune_available,
run_hp_search_optuna,
run_hp_search_ray,
)
import numpy as np
import torch
from packaging import version
from torch import nn
from torch.utils.data import DataLoader, Dataset, IterableDataset, RandomSampler, SequentialSampler
from torch.utils.data.distributed import DistributedSampler
from . import __version__
from .configuration_utils import PretrainedConfig
from .data.data_collator import DataCollator, DataCollatorWithPadding, default_data_collator
from .debug_utils import DebugOption, DebugUnderflowOverflow
from .deepspeed import deepspeed_init, is_deepspeed_zero3_enabled
from .dependency_versions_check import dep_version_check
from .file_utils import (
CONFIG_NAME,
WEIGHTS_NAME,
PushToHubMixin,
is_apex_available,
is_datasets_available,
is_in_notebook,
is_sagemaker_dp_enabled,
is_sagemaker_mp_enabled,
is_torch_tpu_available,
)
from .modelcard import TrainingSummary
from .modeling_utils import PreTrainedModel, unwrap_model
from .models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
from .optimization import Adafactor, AdamW, get_scheduler
from .tokenization_utils_base import PreTrainedTokenizerBase
from .trainer_callback import (
CallbackHandler,
DefaultFlowCallback,
PrinterCallback,
ProgressCallback,
TrainerCallback,
TrainerControl,
TrainerState,
)
from .trainer_pt_utils import (
DistributedLengthGroupedSampler,
DistributedSamplerWithLoop,
DistributedTensorGatherer,
IterableDatasetShard,
LabelSmoother,
LengthGroupedSampler,
SequentialDistributedSampler,
ShardSampler,
distributed_broadcast_scalars,
distributed_concat,
find_batch_size,
get_parameter_names,
nested_concat,
nested_detach,
nested_numpify,
nested_truncate,
nested_xla_mesh_reduce,
reissue_pt_warnings,
)
from .trainer_utils import (
PREFIX_CHECKPOINT_DIR,
BestRun,
EvalLoopOutput,
EvalPrediction,
HPSearchBackend,
PredictionOutput,
ShardedDDPOption,
TrainerMemoryTracker,
TrainOutput,
default_compute_objective,
default_hp_space,
denumpify_detensorize,
get_last_checkpoint,
number_of_arguments,
set_seed,
speed_metrics,
)
from .training_args import ParallelMode, TrainingArguments
from .utils import logging
_is_torch_generator_available = False
_is_native_amp_available = False
DEFAULT_CALLBACKS = [DefaultFlowCallback]
DEFAULT_PROGRESS_CALLBACK = ProgressCallback
if is_in_notebook():
from .utils.notebook import NotebookProgressCallback
DEFAULT_PROGRESS_CALLBACK = NotebookProgressCallback
if is_apex_available():
from apex import amp
if version.parse(torch.__version__) >= version.parse("1.6"):
_is_torch_generator_available = True
_is_native_amp_available = True
from torch.cuda.amp import autocast
if is_datasets_available():
import datasets
if is_torch_tpu_available():
import torch_xla.core.xla_model as xm
import torch_xla.debug.metrics as met
import torch_xla.distributed.parallel_loader as pl
if is_fairscale_available():
dep_version_check("fairscale")
import fairscale
from fairscale.nn.data_parallel import FullyShardedDataParallel as FullyShardedDDP
from fairscale.nn.data_parallel import ShardedDataParallel as ShardedDDP
from fairscale.nn.wrap import auto_wrap
from fairscale.optim import OSS
from fairscale.optim.grad_scaler import ShardedGradScaler
if is_sagemaker_dp_enabled():
import smdistributed.dataparallel.torch.distributed as dist
from smdistributed.dataparallel.torch.parallel.distributed import DistributedDataParallel as DDP
else:
import torch.distributed as dist
if is_sagemaker_mp_enabled():
import smdistributed.modelparallel.torch as smp
from .trainer_pt_utils import smp_forward_backward, smp_forward_only, smp_gather, smp_nested_concat
if TYPE_CHECKING:
import optuna
logger = logging.get_logger(__name__)
class Trainer:
"""
Trainer is a simple but feature-complete training and eval loop for PyTorch, optimized for 🤗 Transformers.
Args:
model (:class:`~transformers.PreTrainedModel` or :obj:`torch.nn.Module`, `optional`):
The model to train, evaluate or use for predictions. If not provided, a ``model_init`` must be passed.
.. note::
:class:`~transformers.Trainer` is optimized to work with the :class:`~transformers.PreTrainedModel`
provided by the library. You can still use your own models defined as :obj:`torch.nn.Module` as long as
they work the same way as the 🤗 Transformers models.
args (:class:`~transformers.TrainingArguments`, `optional`):
The arguments to tweak for training. Will default to a basic instance of
:class:`~transformers.TrainingArguments` with the ``output_dir`` set to a directory named `tmp_trainer` in
the current directory if not provided.
data_collator (:obj:`DataCollator`, `optional`):
The function to use to form a batch from a list of elements of :obj:`train_dataset` or :obj:`eval_dataset`.
Will default to :func:`~transformers.default_data_collator` if no ``tokenizer`` is provided, an instance of
:func:`~transformers.DataCollatorWithPadding` otherwise.
train_dataset (:obj:`torch.utils.data.Dataset` or :obj:`torch.utils.data.IterableDataset`, `optional`):
The dataset to use for training. If it is an :obj:`datasets.Dataset`, columns not accepted by the
``model.forward()`` method are automatically removed.
Note that if it's a :obj:`torch.utils.data.IterableDataset` with some randomization and you are training in
a distributed fashion, your iterable dataset should either use a internal attribute :obj:`generator` that
is a :obj:`torch.Generator` for the randomization that must be identical on all processes (and the Trainer
will manually set the seed of this :obj:`generator` at each epoch) or have a :obj:`set_epoch()` method that
internally sets the seed of the RNGs used.
eval_dataset (:obj:`torch.utils.data.Dataset`, `optional`):
The dataset to use for evaluation. If it is an :obj:`datasets.Dataset`, columns not accepted by the
``model.forward()`` method are automatically removed.
tokenizer (:class:`PreTrainedTokenizerBase`, `optional`):
The tokenizer used to preprocess the data. If provided, will be used to automatically pad the inputs the
maximum length when batching inputs, and it will be saved along the model to make it easier to rerun an
interrupted training or reuse the fine-tuned model.
model_init (:obj:`Callable[[], PreTrainedModel]`, `optional`):
A function that instantiates the model to be used. If provided, each call to
:meth:`~transformers.Trainer.train` will start from a new instance of the model as given by this function.
The function may have zero argument, or a single one containing the optuna/Ray Tune trial object, to be
able to choose different architectures according to hyper parameters (such as layer count, sizes of inner
layers, dropout probabilities etc).
compute_metrics (:obj:`Callable[[EvalPrediction], Dict]`, `optional`):
The function that will be used to compute metrics at evaluation. Must take a
:class:`~transformers.EvalPrediction` and return a dictionary string to metric values.
callbacks (List of :obj:`~transformers.TrainerCallback`, `optional`):
A list of callbacks to customize the training loop. Will add those to the list of default callbacks
detailed in :doc:`here <callback>`.
If you want to remove one of the default callbacks used, use the :meth:`Trainer.remove_callback` method.
optimizers (:obj:`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR`, `optional`): A tuple
containing the optimizer and the scheduler to use. Will default to an instance of
:class:`~transformers.AdamW` on your model and a scheduler given by
:func:`~transformers.get_linear_schedule_with_warmup` controlled by :obj:`args`.
Important attributes:
- **model** -- Always points to the core model. If using a transformers model, it will be a
:class:`~transformers.PreTrainedModel` subclass.
- **model_wrapped** -- Always points to the most external model in case one or more other modules wrap the
original model. This is the model that should be used for the forward pass. For example, under ``DeepSpeed``,
the inner model is wrapped in ``DeepSpeed`` and then again in ``torch.nn.DistributedDataParallel``. If the
inner model hasn't been wrapped, then ``self.model_wrapped`` is the same as ``self.model``.
- **is_model_parallel** -- Whether or not a model has been switched to a model parallel mode (different from
data parallelism, this means some of the model layers are split on different GPUs).
- **place_model_on_device** -- Whether or not to automatically place the model on the device - it will be set
to :obj:`False` if model parallel or deepspeed is used, or if the default
``TrainingArguments.place_model_on_device`` is overridden to return :obj:`False` .
- **is_in_train** -- Whether or not a model is currently running ``train`` (e.g. when ``evaluate`` is called
while in ``train``)
"""
from .trainer_pt_utils import _get_learning_rate, log_metrics, metrics_format, save_metrics, save_state
def __init__(
self,
model: Union[PreTrainedModel, nn.Module] = None,
args: TrainingArguments = None,
data_collator: Optional[DataCollator] = None,
train_dataset: Optional[Dataset] = None,
eval_dataset: Optional[Dataset] = None,
tokenizer: Optional[PreTrainedTokenizerBase] = None,
model_init: Callable[[], PreTrainedModel] = None,
compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None,
callbacks: Optional[List[TrainerCallback]] = None,
optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
):
if args is None:
output_dir = "tmp_trainer"
logger.info(f"No `TrainingArguments` passed, using `output_dir={output_dir}`.")
args = TrainingArguments(output_dir=output_dir)
self.args = args
# Seed must be set before instantiating the model when using model
set_seed(self.args.seed)
self.hp_name = None
self.deepspeed = None
self.is_in_train = False
# memory metrics - must set up as early as possible
self._memory_tracker = TrainerMemoryTracker(self.args.skip_memory_metrics)
self._memory_tracker.start()
# set the correct log level depending on the node
log_level = args.get_process_log_level()
logging.set_verbosity(log_level)
# force device and distributed setup init explicitly
args._setup_devices
if model is None:
if model_init is not None:
self.model_init = model_init
model = self.call_model_init()
else:
raise RuntimeError("`Trainer` requires either a `model` or `model_init` argument")
else:
if model_init is not None:
warnings.warn(
"`Trainer` requires either a `model` or `model_init` argument, but not both. "
"`model_init` will overwrite your model when calling the `train` method. This will become a fatal error in the next release.",
FutureWarning,
)
self.model_init = model_init
if hasattr(model, "is_parallelizable") and model.is_parallelizable and model.model_parallel:
self.is_model_parallel = True
else:
self.is_model_parallel = False
# Setup Sharded DDP training
self.sharded_ddp = None
if len(args.sharded_ddp) > 0:
if args.deepspeed:
raise ValueError(
"Using --sharded_ddp xxx together with --deepspeed is not possible, deactivate one of those flags."
)
if args.local_rank == -1:
raise ValueError("Using sharded DDP only works in distributed training.")
elif not is_fairscale_available():
raise ImportError("Sharded DDP training requires fairscale: `pip install fairscale`.")
elif ShardedDDPOption.SIMPLE not in args.sharded_ddp and FullyShardedDDP is None:
raise ImportError(
"Sharded DDP in a mode other than simple training requires fairscale version >= 0.3, found "
f"{fairscale.__version__}. Upgrade your fairscale library: `pip install --upgrade fairscale`."
)
elif ShardedDDPOption.SIMPLE in args.sharded_ddp:
self.sharded_ddp = ShardedDDPOption.SIMPLE
elif ShardedDDPOption.ZERO_DP_2 in args.sharded_ddp:
self.sharded_ddp = ShardedDDPOption.ZERO_DP_2
elif ShardedDDPOption.ZERO_DP_3 in args.sharded_ddp:
self.sharded_ddp = ShardedDDPOption.ZERO_DP_3
# one place to sort out whether to place the model on device or not
# postpone switching model to cuda when:
# 1. MP - since we are trying to fit a much bigger than 1 gpu model
# 2. fp16-enabled DeepSpeed loads the model in half the size and it doesn't need .to() anyway,
# and we only use deepspeed for training at the moment
# 3. full fp16 eval - since the model needs to be half'ed first
# 4. Sharded DDP - same as MP
self.place_model_on_device = args.place_model_on_device
if (
self.is_model_parallel
or args.deepspeed
or (args.fp16_full_eval and not args.do_train)
or (self.sharded_ddp in [ShardedDDPOption.ZERO_DP_2, ShardedDDPOption.ZERO_DP_3])
):
self.place_model_on_device = False
default_collator = default_data_collator if tokenizer is None else DataCollatorWithPadding(tokenizer)
self.data_collator = data_collator if data_collator is not None else default_collator
self.train_dataset = train_dataset
self.eval_dataset = eval_dataset
self.tokenizer = tokenizer
if self.place_model_on_device:
self._move_model_to_device(model, args.device)
# Force n_gpu to 1 to avoid DataParallel as MP will manage the GPUs
if self.is_model_parallel:
self.args._n_gpu = 1
# later use `self.model is self.model_wrapped` to check if it's wrapped or not
self.model_wrapped = model
self.model = model
self.compute_metrics = compute_metrics
self.optimizer, self.lr_scheduler = optimizers
if model_init is not None and (self.optimizer is not None or self.lr_scheduler is not None):
raise RuntimeError(
"Passing a `model_init` is incompatible with providing the `optimizers` argument."
"You should subclass `Trainer` and override the `create_optimizer_and_scheduler` method."
)
default_callbacks = DEFAULT_CALLBACKS + get_reporting_integration_callbacks(self.args.report_to)
callbacks = default_callbacks if callbacks is None else default_callbacks + callbacks
self.callback_handler = CallbackHandler(
callbacks, self.model, self.tokenizer, self.optimizer, self.lr_scheduler
)
self.add_callback(PrinterCallback if self.args.disable_tqdm else DEFAULT_PROGRESS_CALLBACK)
# Will be set to True by `self._setup_loggers()` on first call to `self.log()`.
self._loggers_initialized = False
# Create clone of distant repo and output directory if needed
if self.args.push_to_hub:
self.init_git_repo()
if self.args.should_save:
os.makedirs(self.args.output_dir, exist_ok=True)
if not callable(self.data_collator) and callable(getattr(self.data_collator, "collate_batch", None)):
raise ValueError("The `data_collator` should be a simple callable (function, class with `__call__`).")
if args.max_steps > 0:
logger.info("max_steps is given, it will override any value given in num_train_epochs")
if train_dataset is not None and not isinstance(train_dataset, collections.abc.Sized) and args.max_steps <= 0:
raise ValueError("train_dataset does not implement __len__, max_steps has to be specified")
self._signature_columns = None
# Mixed precision setup
self.use_apex = False
self.use_amp = False
self.fp16_backend = None
if args.fp16:
if args.fp16_backend == "auto":
self.fp16_backend = "amp" if _is_native_amp_available else "apex"
else:
self.fp16_backend = args.fp16_backend
logger.info(f"Using {self.fp16_backend} fp16 backend")
if args.fp16 and not args.deepspeed: # deepspeed manages its own fp16
if self.fp16_backend == "amp":
self.use_amp = True
if is_sagemaker_mp_enabled():
self.scaler = smp.amp.GradScaler()
elif self.sharded_ddp is not None:
self.scaler = ShardedGradScaler()
else:
self.scaler = torch.cuda.amp.GradScaler()
else:
if not is_apex_available():
raise ImportError(
"Using FP16 with APEX but APEX is not installed, please refer to https://www.github.com/nvidia/apex."
)
self.use_apex = True
# FP16 + model parallelism in SageMaker: gradient clipping does not work for now so we raise a helpful error.
if is_sagemaker_mp_enabled() and self.use_amp and args.max_grad_norm is not None and args.max_grad_norm > 0:
raise ValueError(
"SageMaker Model Parallelism in mixed precision mode does not support gradient clipping yet. Pass "
"along 'max_grad_norm': 0 in your hyperparameters."
)
# Label smoothing
if self.args.label_smoothing_factor != 0:
self.label_smoother = LabelSmoother(epsilon=self.args.label_smoothing_factor)
else:
self.label_smoother = None
self.state = TrainerState()
self.control = TrainerControl()
# Internal variable to count flos in each process, will be accumulated in `self.state.total_flos` then
# returned to 0 every time flos need to be logged
self.current_flos = 0
self.hp_search_backend = None
self.use_tune_checkpoints = False
default_label_names = (
["start_positions", "end_positions"]
if type(self.model).__name__ in MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES.values()
else ["labels"]
)
self.label_names = default_label_names if self.args.label_names is None else self.args.label_names
self.control = self.callback_handler.on_init_end(self.args, self.state, self.control)
# very last
self._memory_tracker.stop_and_update_metrics()
def add_callback(self, callback):
"""
Add a callback to the current list of :class:`~transformer.TrainerCallback`.
Args:
callback (:obj:`type` or :class:`~transformer.TrainerCallback`):
A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`.
In the first case, will instantiate a member of that class.
"""
self.callback_handler.add_callback(callback)
def pop_callback(self, callback):
"""
Remove a callback from the current list of :class:`~transformer.TrainerCallback` and returns it.
If the callback is not found, returns :obj:`None` (and no error is raised).
Args:
callback (:obj:`type` or :class:`~transformer.TrainerCallback`):
A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`.
In the first case, will pop the first member of that class found in the list of callbacks.
Returns:
:class:`~transformer.TrainerCallback`: The callback removed, if found.
"""
return self.callback_handler.pop_callback(callback)
def remove_callback(self, callback):
"""
Remove a callback from the current list of :class:`~transformer.TrainerCallback`.
Args:
callback (:obj:`type` or :class:`~transformer.TrainerCallback`):
A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`.
In the first case, will remove the first member of that class found in the list of callbacks.
"""
self.callback_handler.remove_callback(callback)
def _move_model_to_device(self, model, device):
model = model.to(device)
# Moving a model to an XLA device disconnects the tied weights, so we have to retie them.
if self.args.parallel_mode == ParallelMode.TPU and hasattr(model, "tie_weights"):
model.tie_weights()
def _remove_unused_columns(self, dataset: "datasets.Dataset", description: Optional[str] = None):
if not self.args.remove_unused_columns:
return dataset
if self._signature_columns is None:
# Inspect model forward signature to keep only the arguments it accepts.
signature = inspect.signature(self.model.forward)
self._signature_columns = list(signature.parameters.keys())
# Labels may be named label or label_ids, the default data collator handles that.
self._signature_columns += ["label", "label_ids"]
columns = [k for k in self._signature_columns if k in dataset.column_names]
ignored_columns = list(set(dataset.column_names) - set(self._signature_columns))
if len(ignored_columns) > 0:
dset_description = "" if description is None else f"in the {description} set "
logger.info(
f"The following columns {dset_description} don't have a corresponding argument in "
f"`{self.model.__class__.__name__}.forward` and have been ignored: {', '.join(ignored_columns)}."
)
if version.parse(datasets.__version__) < version.parse("1.4.0"):
dataset.set_format(
type=dataset.format["type"], columns=columns, format_kwargs=dataset.format["format_kwargs"]
)
return dataset
else:
return dataset.remove_columns(ignored_columns)
def _get_train_sampler(self) -> Optional[torch.utils.data.Sampler]:
if not isinstance(self.train_dataset, collections.abc.Sized):
return None
generator = None
if self.args.world_size <= 1 and _is_torch_generator_available:
generator = torch.Generator()
generator.manual_seed(int(torch.empty((), dtype=torch.int64).random_().item()))
# Build the sampler.
if self.args.group_by_length:
if is_datasets_available() and isinstance(self.train_dataset, datasets.Dataset):
lengths = (
self.train_dataset[self.args.length_column_name]
if self.args.length_column_name in self.train_dataset.column_names
else None
)
else:
lengths = None
model_input_name = self.tokenizer.model_input_names[0] if self.tokenizer is not None else None
if self.args.world_size <= 1:
return LengthGroupedSampler(
self.train_dataset,
self.args.train_batch_size,
lengths=lengths,
model_input_name=model_input_name,
generator=generator,
)
else:
return DistributedLengthGroupedSampler(
self.train_dataset,
self.args.train_batch_size,
num_replicas=self.args.world_size,
rank=self.args.process_index,
lengths=lengths,
model_input_name=model_input_name,
seed=self.args.seed,
)
else:
if self.args.world_size <= 1:
if _is_torch_generator_available:
return RandomSampler(self.train_dataset, generator=generator)
return RandomSampler(self.train_dataset)
elif (
self.args.parallel_mode in [ParallelMode.TPU, ParallelMode.SAGEMAKER_MODEL_PARALLEL]
and not self.args.dataloader_drop_last
):
# Use a loop for TPUs when drop_last is False to have all batches have the same size.
return DistributedSamplerWithLoop(
self.train_dataset,
batch_size=self.args.per_device_train_batch_size,
num_replicas=self.args.world_size,
rank=self.args.process_index,
seed=self.args.seed,
)
else:
return DistributedSampler(
self.train_dataset,
num_replicas=self.args.world_size,
rank=self.args.process_index,
seed=self.args.seed,
)
def get_train_dataloader(self) -> DataLoader:
"""
Returns the training :class:`~torch.utils.data.DataLoader`.
Will use no sampler if :obj:`self.train_dataset` does not implement :obj:`__len__`, a random sampler (adapted
to distributed training if necessary) otherwise.
Subclass and override this method if you want to inject some custom behavior.
"""
if self.train_dataset is None:
raise ValueError("Trainer: training requires a train_dataset.")
train_dataset = self.train_dataset
if is_datasets_available() and isinstance(train_dataset, datasets.Dataset):
train_dataset = self._remove_unused_columns(train_dataset, description="training")
if isinstance(train_dataset, torch.utils.data.IterableDataset):
if self.args.world_size > 1:
train_dataset = IterableDatasetShard(
train_dataset,
batch_size=self.args.train_batch_size,
drop_last=self.args.dataloader_drop_last,
num_processes=self.args.world_size,
process_index=self.args.process_index,
)
return DataLoader(
train_dataset,
batch_size=self.args.train_batch_size,
collate_fn=self.data_collator,
num_workers=self.args.dataloader_num_workers,
pin_memory=self.args.dataloader_pin_memory,
)
train_sampler = self._get_train_sampler()
return DataLoader(
train_dataset,
batch_size=self.args.train_batch_size,
sampler=train_sampler,
collate_fn=self.data_collator,
drop_last=self.args.dataloader_drop_last,
num_workers=self.args.dataloader_num_workers,
pin_memory=self.args.dataloader_pin_memory,
)
def _get_eval_sampler(self, eval_dataset: Dataset) -> Optional[torch.utils.data.Sampler]:
# Deprecated code
if self.args.use_legacy_prediction_loop:
if is_torch_tpu_available():
return SequentialDistributedSampler(
eval_dataset, num_replicas=xm.xrt_world_size(), rank=xm.get_ordinal()
)
elif is_sagemaker_mp_enabled():
return SequentialDistributedSampler(
eval_dataset,
num_replicas=smp.dp_size(),
rank=smp.dp_rank(),
batch_size=self.args.per_device_eval_batch_size,
)
elif self.args.local_rank != -1:
return SequentialDistributedSampler(eval_dataset)
else:
return SequentialSampler(eval_dataset)
if self.args.world_size <= 1:
return SequentialSampler(eval_dataset)
else:
return ShardSampler(
eval_dataset,
batch_size=self.args.per_device_eval_batch_size,
num_processes=self.args.world_size,
process_index=self.args.process_index,
)
def get_eval_dataloader(self, eval_dataset: Optional[Dataset] = None) -> DataLoader:
"""
Returns the evaluation :class:`~torch.utils.data.DataLoader`.
Subclass and override this method if you want to inject some custom behavior.
Args:
eval_dataset (:obj:`torch.utils.data.Dataset`, `optional`):
If provided, will override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`, columns not
accepted by the ``model.forward()`` method are automatically removed. It must implement :obj:`__len__`.
"""
if eval_dataset is None and self.eval_dataset is None:
raise ValueError("Trainer: evaluation requires an eval_dataset.")
eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset
if is_datasets_available() and isinstance(eval_dataset, datasets.Dataset):
eval_dataset = self._remove_unused_columns(eval_dataset, description="evaluation")
if isinstance(eval_dataset, torch.utils.data.IterableDataset):
if self.args.world_size > 1:
eval_dataset = IterableDatasetShard(
eval_dataset,
batch_size=self.args.eval_batch_size,
drop_last=self.args.dataloader_drop_last,
num_processes=self.args.world_size,
process_index=self.args.process_index,
)
return DataLoader(
eval_dataset,
batch_size=self.args.eval_batch_size,
collate_fn=self.data_collator,
num_workers=self.args.dataloader_num_workers,
pin_memory=self.args.dataloader_pin_memory,
)
eval_sampler = self._get_eval_sampler(eval_dataset)
return DataLoader(
eval_dataset,
sampler=eval_sampler,
batch_size=self.args.eval_batch_size,
collate_fn=self.data_collator,
drop_last=self.args.dataloader_drop_last,
num_workers=self.args.dataloader_num_workers,
pin_memory=self.args.dataloader_pin_memory,
)
def get_test_dataloader(self, test_dataset: Dataset) -> DataLoader:
"""
Returns the test :class:`~torch.utils.data.DataLoader`.
Subclass and override this method if you want to inject some custom behavior.
Args:
test_dataset (:obj:`torch.utils.data.Dataset`, `optional`):
The test dataset to use. If it is an :obj:`datasets.Dataset`, columns not accepted by the
``model.forward()`` method are automatically removed. It must implement :obj:`__len__`.
"""
if is_datasets_available() and isinstance(test_dataset, datasets.Dataset):
test_dataset = self._remove_unused_columns(test_dataset, description="test")
if isinstance(test_dataset, torch.utils.data.IterableDataset):
if self.args.world_size > 1:
test_dataset = IterableDatasetShard(
test_dataset,
batch_size=self.args.eval_batch_size,
drop_last=self.args.dataloader_drop_last,
num_processes=self.args.world_size,
process_index=self.args.process_index,
)
return DataLoader(
test_dataset,
batch_size=self.args.eval_batch_size,
collate_fn=self.data_collator,
num_workers=self.args.dataloader_num_workers,
pin_memory=self.args.dataloader_pin_memory,
)
test_sampler = self._get_eval_sampler(test_dataset)
# We use the same batch_size as for eval.
return DataLoader(
test_dataset,
sampler=test_sampler,
batch_size=self.args.eval_batch_size,
collate_fn=self.data_collator,
drop_last=self.args.dataloader_drop_last,
pin_memory=self.args.dataloader_pin_memory,
)
def create_optimizer_and_scheduler(self, num_training_steps: int):
"""
Setup the optimizer and the learning rate scheduler.
We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the
Trainer's init through :obj:`optimizers`, or subclass and override this method (or :obj:`create_optimizer`
and/or :obj:`create_scheduler`) in a subclass.
"""
self.create_optimizer()
self.create_scheduler(num_training_steps)
def create_optimizer(self):
"""
Setup the optimizer.
We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the
Trainer's init through :obj:`optimizers`, or subclass and override this method in a subclass.
"""
if self.optimizer is None:
decay_parameters = get_parameter_names(self.model, [nn.LayerNorm])
decay_parameters = [name for name in decay_parameters if "bias" not in name]
optimizer_grouped_parameters = [
{
"params": [p for n, p in self.model.named_parameters() if n in decay_parameters],
"weight_decay": self.args.weight_decay,
},
{
"params": [p for n, p in self.model.named_parameters() if n not in decay_parameters],
"weight_decay": 0.0,
},
]
optimizer_cls = Adafactor if self.args.adafactor else AdamW
if self.args.adafactor:
optimizer_cls = Adafactor
optimizer_kwargs = {"scale_parameter": False, "relative_step": False}
else:
optimizer_cls = AdamW
optimizer_kwargs = {
"betas": (self.args.adam_beta1, self.args.adam_beta2),
"eps": self.args.adam_epsilon,
}
optimizer_kwargs["lr"] = self.args.learning_rate
if self.sharded_ddp == ShardedDDPOption.SIMPLE:
self.optimizer = OSS(
params=optimizer_grouped_parameters,
optim=optimizer_cls,
**optimizer_kwargs,
)
else:
self.optimizer = optimizer_cls(optimizer_grouped_parameters, **optimizer_kwargs)
if is_sagemaker_mp_enabled():
self.optimizer = smp.DistributedOptimizer(self.optimizer)
def create_scheduler(self, num_training_steps: int):
"""
Setup the scheduler. The optimizer of the trainer must have been set up before this method is called.
Args:
num_training_steps (int): The number of training steps to do.
"""
if self.lr_scheduler is None:
self.lr_scheduler = get_scheduler(
self.args.lr_scheduler_type,
self.optimizer,
num_warmup_steps=self.args.get_warmup_steps(num_training_steps),
num_training_steps=num_training_steps,
)
def num_examples(self, dataloader: DataLoader) -> int:
"""
Helper to get number of samples in a :class:`~torch.utils.data.DataLoader` by accessing its dataset.
Will raise an exception if the underlying dataset does not implement method :obj:`__len__`
"""
return len(dataloader.dataset)
def _hp_search_setup(self, trial: Union["optuna.Trial", Dict[str, Any]]):
"""HP search setup code"""
self._trial = trial
if self.hp_search_backend is None or trial is None:
return
if self.hp_search_backend == HPSearchBackend.OPTUNA:
params = self.hp_space(trial)
elif self.hp_search_backend == HPSearchBackend.RAY:
params = trial
params.pop("wandb", None)
for key, value in params.items():
if not hasattr(self.args, key):
logger.warn(
f"Trying to set {key} in the hyperparameter search but there is no corresponding field in `TrainingArguments`."
)
continue
old_attr = getattr(self.args, key, None)
# Casting value to the proper type
if old_attr is not None:
value = type(old_attr)(value)
setattr(self.args, key, value)
if self.hp_search_backend == HPSearchBackend.OPTUNA:
logger.info("Trial:", trial.params)
if self.args.deepspeed:
# Rebuild the deepspeed config to reflect the updated training parameters
from transformers.deepspeed import HfDeepSpeedConfig
self.args.hf_deepspeed_config = HfDeepSpeedConfig(self.args)
def _report_to_hp_search(
self, trial: Union["optuna.Trial", Dict[str, Any]], epoch: int, metrics: Dict[str, float]
):
if self.hp_search_backend is None or trial is None:
return
self.objective = self.compute_objective(metrics.copy())
if self.hp_search_backend == HPSearchBackend.OPTUNA:
import optuna
trial.report(self.objective, epoch)
if trial.should_prune():
raise optuna.TrialPruned()
elif self.hp_search_backend == HPSearchBackend.RAY:
from ray import tune
if self.control.should_save:
self._tune_save_checkpoint()
tune.report(objective=self.objective, **metrics)
def _tune_save_checkpoint(self):
from ray import tune
if not self.use_tune_checkpoints:
return
with tune.checkpoint_dir(step=self.state.global_step) as checkpoint_dir:
output_dir = os.path.join(checkpoint_dir, f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}")
self.save_model(output_dir)
if self.args.should_save:
self.state.save_to_json(os.path.join(output_dir, "trainer_state.json"))
torch.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt"))
torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
def call_model_init(self, trial=None):
model_init_argcount = number_of_arguments(self.model_init)
if model_init_argcount == 0:
model = self.model_init()
elif model_init_argcount == 1:
model = self.model_init(trial)
else:
raise RuntimeError("model_init should have 0 or 1 argument.")
if model is None:
raise RuntimeError("model_init should not return None.")
return model
def _wrap_model(self, model, training=True):
if is_sagemaker_mp_enabled():
# Wrapping the base model twice in a DistributedModel will raise an error.
if isinstance(self.model_wrapped, smp.model.DistributedModel):
return self.model_wrapped
return smp.DistributedModel(model, backward_passes_per_step=self.args.gradient_accumulation_steps)
# already initialized its own DDP and AMP
if self.deepspeed:
return self.deepspeed
# train/eval could be run multiple-times - if already wrapped, don't re-wrap it again
if unwrap_model(model) is not model:
return model
# Mixed precision training with apex (torch < 1.6)
if self.use_apex and training:
model, self.optimizer = amp.initialize(model, self.optimizer, opt_level=self.args.fp16_opt_level)
# Multi-gpu training (should be after apex fp16 initialization)
if self.args.n_gpu > 1:
model = nn.DataParallel(model)
# Note: in torch.distributed mode, there's no point in wrapping the model
# inside a DistributedDataParallel as we'll be under `no_grad` anyways.
if not training:
return model
# Distributed training (should be after apex fp16 initialization)
if self.sharded_ddp is not None:
# Sharded DDP!
if self.sharded_ddp == ShardedDDPOption.SIMPLE:
model = ShardedDDP(model, self.optimizer)
else:
mixed_precision = self.args.fp16
cpu_offload = ShardedDDPOption.OFFLOAD in self.args.sharded_ddp
zero_3 = self.sharded_ddp == ShardedDDPOption.ZERO_DP_3
# XXX: Breaking the self.model convention but I see no way around it for now.
if ShardedDDPOption.AUTO_WRAP in self.args.sharded_ddp:
model = auto_wrap(model)
self.model = model = FullyShardedDDP(
model,
mixed_precision=mixed_precision,
reshard_after_forward=zero_3,
cpu_offload=cpu_offload,
).to(self.args.device)
elif is_sagemaker_dp_enabled():
model = DDP(model, device_ids=[dist.get_local_rank()], broadcast_buffers=False)
elif self.args.local_rank != -1:
if self.args.ddp_find_unused_parameters is not None:
find_unused_parameters = self.args.ddp_find_unused_parameters
elif isinstance(model, PreTrainedModel):
# find_unused_parameters breaks checkpointing as per
# https://github.com/huggingface/transformers/pull/4659#issuecomment-643356021
find_unused_parameters = not getattr(model.config, "gradient_checkpointing", False)
else:
find_unused_parameters = True
model = nn.parallel.DistributedDataParallel(
model,
device_ids=[self.args.local_rank],
output_device=self.args.local_rank,
find_unused_parameters=find_unused_parameters,
)
return model
def train(
self,
resume_from_checkpoint: Optional[Union[str, bool]] = None,
trial: Union["optuna.Trial", Dict[str, Any]] = None,
ignore_keys_for_eval: Optional[List[str]] = None,
**kwargs,
):
"""
Main training entry point.
Args:
resume_from_checkpoint (:obj:`str` or :obj:`bool`, `optional`):
If a :obj:`str`, local path to a saved checkpoint as saved by a previous instance of
:class:`~transformers.Trainer`. If a :obj:`bool` and equals `True`, load the last checkpoint in
`args.output_dir` as saved by a previous instance of :class:`~transformers.Trainer`. If present,
training will resume from the model/optimizer/scheduler states loaded here.
trial (:obj:`optuna.Trial` or :obj:`Dict[str, Any]`, `optional`):
The trial run or the hyperparameter dictionary for hyperparameter search.
ignore_keys_for_eval (:obj:`List[str]`, `optional`)
A list of keys in the output of your model (if it is a dictionary) that should be ignored when
gathering predictions for evaluation during the training.
kwargs:
Additional keyword arguments used to hide deprecated arguments
"""
resume_from_checkpoint = None if not resume_from_checkpoint else resume_from_checkpoint
# memory metrics - must set up as early as possible
self._memory_tracker.start()
args = self.args
self.is_in_train = True
# do_train is not a reliable argument, as it might not be set and .train() still called, so
# the following is a workaround:
if args.fp16_full_eval and not args.do_train:
self._move_model_to_device(self.model, args.device)
if "model_path" in kwargs:
resume_from_checkpoint = kwargs.pop("model_path")
warnings.warn(
"`model_path` is deprecated and will be removed in a future version. Use `resume_from_checkpoint` "
"instead.",
FutureWarning,
)
if len(kwargs) > 0:
raise TypeError(f"train() received got unexpected keyword arguments: {', '.join(list(kwargs.keys()))}.")
# This might change the seed so needs to run first.
self._hp_search_setup(trial)
# Model re-init
model_reloaded = False
if self.model_init is not None:
# Seed must be set before instantiating the model when using model_init.
set_seed(args.seed)
self.model = self.call_model_init(trial)
model_reloaded = True
# Reinitializes optimizer and scheduler
self.optimizer, self.lr_scheduler = None, None
# Load potential model checkpoint
if isinstance(resume_from_checkpoint, bool) and resume_from_checkpoint:
resume_from_checkpoint = get_last_checkpoint(args.output_dir)
if resume_from_checkpoint is None:
raise ValueError(f"No valid checkpoint found in output directory ({args.output_dir})")
if resume_from_checkpoint is not None:
if not os.path.isfile(os.path.join(resume_from_checkpoint, WEIGHTS_NAME)):
raise ValueError(f"Can't find a valid checkpoint at {resume_from_checkpoint}")
logger.info(f"Loading model from {resume_from_checkpoint}).")
if os.path.isfile(os.path.join(resume_from_checkpoint, CONFIG_NAME)):
config = PretrainedConfig.from_json_file(os.path.join(resume_from_checkpoint, CONFIG_NAME))
checkpoint_version = config.transformers_version
if checkpoint_version is not None and checkpoint_version != __version__:
logger.warn(
f"You are resuming training from a checkpoint trained with {checkpoint_version} of "
f"Transformers but your current version is {__version__}. This is not recommended and could "
"yield to errors or unwanted behaviors."
)
if args.deepspeed:
# will be resumed in deepspeed_init
pass
else:
# We load the model state dict on the CPU to avoid an OOM error.
state_dict = torch.load(os.path.join(resume_from_checkpoint, WEIGHTS_NAME), map_location="cpu")
# If the model is on the GPU, it still works!
self._load_state_dict_in_model(state_dict)
# release memory
del state_dict
# If model was re-initialized, put it on the right device and update self.model_wrapped
if model_reloaded:
if self.place_model_on_device:
self._move_model_to_device(self.model, args.device)
self.model_wrapped = self.model
# Keeping track whether we can can len() on the dataset or not
train_dataset_is_sized = isinstance(self.train_dataset, collections.abc.Sized)
# Data loader and number of training steps
train_dataloader = self.get_train_dataloader()
# Setting up training control variables:
# number of training epochs: num_train_epochs
# number of training steps per epoch: num_update_steps_per_epoch
# total number of training steps to execute: max_steps
total_train_batch_size = args.train_batch_size * args.gradient_accumulation_steps * args.world_size
if train_dataset_is_sized:
num_update_steps_per_epoch = len(train_dataloader) // args.gradient_accumulation_steps
num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1)
if args.max_steps > 0:
max_steps = args.max_steps
num_train_epochs = args.max_steps // num_update_steps_per_epoch + int(
args.max_steps % num_update_steps_per_epoch > 0
)
# May be slightly incorrect if the last batch in the training datalaoder has a smaller size but it's
# the best we can do.
num_train_samples = args.max_steps * total_train_batch_size
else:
max_steps = math.ceil(args.num_train_epochs * num_update_steps_per_epoch)
num_train_epochs = math.ceil(args.num_train_epochs)
num_train_samples = len(self.train_dataset) * args.num_train_epochs
else:
# see __init__. max_steps is set when the dataset has no __len__
max_steps = args.max_steps
# Setting a very large number of epochs so we go as many times as necessary over the iterator.
num_train_epochs = sys.maxsize
num_update_steps_per_epoch = max_steps
num_train_samples = args.max_steps * total_train_batch_size
if DebugOption.UNDERFLOW_OVERFLOW in self.args.debug:
if self.args.n_gpu > 1:
# nn.DataParallel(model) replicates the model, creating new variables and module
# references registered here no longer work on other gpus, breaking the module
raise ValueError(
"Currently --debug underflow_overflow is not supported under DP. Please use DDP (torch.distributed.launch)."
)
else:
debug_overflow = DebugUnderflowOverflow(self.model) # noqa
delay_optimizer_creation = self.sharded_ddp is not None and self.sharded_ddp != ShardedDDPOption.SIMPLE
if args.deepspeed:
deepspeed_engine, optimizer, lr_scheduler = deepspeed_init(
self, num_training_steps=max_steps, resume_from_checkpoint=resume_from_checkpoint
)
self.model = deepspeed_engine.module
self.model_wrapped = deepspeed_engine
self.deepspeed = deepspeed_engine
self.optimizer = optimizer
self.lr_scheduler = lr_scheduler
elif not delay_optimizer_creation:
self.create_optimizer_and_scheduler(num_training_steps=max_steps)
self.state = TrainerState()
self.state.is_hyper_param_search = trial is not None
model = self._wrap_model(self.model_wrapped)
# for the rest of this function `model` is the outside model, whether it was wrapped or not
if model is not self.model:
self.model_wrapped = model
if delay_optimizer_creation:
self.create_optimizer_and_scheduler(num_training_steps=max_steps)
# Check if saved optimizer or scheduler states exist
self._load_optimizer_and_scheduler(resume_from_checkpoint)
# important: at this point:
# self.model is the Transformers Model
# self.model_wrapped is DDP(Transformers Model), Deepspeed(Transformers Model), etc.
# Train!
num_examples = (
self.num_examples(train_dataloader) if train_dataset_is_sized else total_train_batch_size * args.max_steps
)
logger.info("***** Running training *****")
logger.info(f" Num examples = {num_examples}")
logger.info(f" Num Epochs = {num_train_epochs}")
logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}")
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_train_batch_size}")
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
logger.info(f" Total optimization steps = {max_steps}")
self.state.epoch = 0
start_time = time.time()
epochs_trained = 0
steps_trained_in_current_epoch = 0
steps_trained_progress_bar = None
# Check if continuing training from a checkpoint
if resume_from_checkpoint is not None and os.path.isfile(
os.path.join(resume_from_checkpoint, "trainer_state.json")
):
self.state = TrainerState.load_from_json(os.path.join(resume_from_checkpoint, "trainer_state.json"))
epochs_trained = self.state.global_step // num_update_steps_per_epoch
if not args.ignore_data_skip:
steps_trained_in_current_epoch = self.state.global_step % (num_update_steps_per_epoch)
steps_trained_in_current_epoch *= args.gradient_accumulation_steps
else:
steps_trained_in_current_epoch = 0
logger.info(" Continuing training from checkpoint, will skip to saved global_step")
logger.info(f" Continuing training from epoch {epochs_trained}")
logger.info(f" Continuing training from global step {self.state.global_step}")
if not args.ignore_data_skip:
logger.info(
f" Will skip the first {epochs_trained} epochs then the first {steps_trained_in_current_epoch} "
"batches in the first epoch. If this takes a lot of time, you can add the `--ignore_data_skip` "
"flag to your launch command, but you will resume the training on data already seen by your model."
)
if self.is_local_process_zero() and not args.disable_tqdm:
steps_trained_progress_bar = tqdm(total=steps_trained_in_current_epoch)
steps_trained_progress_bar.set_description("Skipping the first batches")
# Update the references
self.callback_handler.model = self.model
self.callback_handler.optimizer = self.optimizer
self.callback_handler.lr_scheduler = self.lr_scheduler
self.callback_handler.train_dataloader = train_dataloader
self.state.trial_name = self.hp_name(trial) if self.hp_name is not None else None
self.state.trial_params = hp_params(trial) if trial is not None else None
# This should be the same if the state has been saved but in case the training arguments changed, it's safer
# to set this after the load.
self.state.max_steps = max_steps
self.state.num_train_epochs = num_train_epochs
self.state.is_local_process_zero = self.is_local_process_zero()
self.state.is_world_process_zero = self.is_world_process_zero()
# tr_loss is a tensor to avoid synchronization of TPUs through .item()
tr_loss = torch.tensor(0.0).to(args.device)
# _total_loss_scalar is updated everytime .item() has to be called on tr_loss and stores the sum of all losses
self._total_loss_scalar = 0.0
self._globalstep_last_logged = self.state.global_step
model.zero_grad()
self.control = self.callback_handler.on_train_begin(args, self.state, self.control)
# Skip the first epochs_trained epochs to get the random state of the dataloader at the right point.
if not args.ignore_data_skip:
for epoch in range(epochs_trained):
# We just need to begin an iteration to create the randomization of the sampler.
for _ in train_dataloader:
break
for epoch in range(epochs_trained, num_train_epochs):
if isinstance(train_dataloader, DataLoader) and isinstance(train_dataloader.sampler, DistributedSampler):
train_dataloader.sampler.set_epoch(epoch)
elif isinstance(train_dataloader.dataset, IterableDatasetShard):
train_dataloader.dataset.set_epoch(epoch)
if is_torch_tpu_available():
parallel_loader = pl.ParallelLoader(train_dataloader, [args.device]).per_device_loader(args.device)
epoch_iterator = parallel_loader
else:
epoch_iterator = train_dataloader
# Reset the past mems state at the beginning of each epoch if necessary.
if args.past_index >= 0:
self._past = None
steps_in_epoch = (
len(epoch_iterator) if train_dataset_is_sized else args.max_steps * args.gradient_accumulation_steps
)
self.control = self.callback_handler.on_epoch_begin(args, self.state, self.control)
for step, inputs in enumerate(epoch_iterator):
# Skip past any already trained steps if resuming training
if steps_trained_in_current_epoch > 0:
steps_trained_in_current_epoch -= 1
if steps_trained_progress_bar is not None:
steps_trained_progress_bar.update(1)
if steps_trained_in_current_epoch == 0:
self._load_rng_state(resume_from_checkpoint)
continue
elif steps_trained_progress_bar is not None:
steps_trained_progress_bar.close()
steps_trained_progress_bar = None
if step % args.gradient_accumulation_steps == 0:
self.control = self.callback_handler.on_step_begin(args, self.state, self.control)
if (
((step + 1) % args.gradient_accumulation_steps != 0)
and args.local_rank != -1
and args._no_sync_in_gradient_accumulation
):
# Avoid unnecessary DDP synchronization since there will be no backward pass on this example.
with model.no_sync():
tr_loss += self.training_step(model, inputs)
else:
tr_loss += self.training_step(model, inputs)
self.current_flos += float(self.floating_point_ops(inputs))
# Optimizer step for deepspeed must be called on every step regardless of the value of gradient_accumulation_steps
if self.deepspeed:
self.deepspeed.step()
if (step + 1) % args.gradient_accumulation_steps == 0 or (
# last step in epoch but step is always smaller than gradient_accumulation_steps
steps_in_epoch <= args.gradient_accumulation_steps
and (step + 1) == steps_in_epoch
):
# Gradient clipping
if args.max_grad_norm is not None and args.max_grad_norm > 0 and not self.deepspeed:
# deepspeed does its own clipping
if self.use_amp:
# AMP: gradients need unscaling
self.scaler.unscale_(self.optimizer)
if hasattr(self.optimizer, "clip_grad_norm"):
# Some optimizers (like the sharded optimizer) have a specific way to do gradient clipping
self.optimizer.clip_grad_norm(args.max_grad_norm)
elif hasattr(model, "clip_grad_norm_"):
# Some models (like FullyShardedDDP) have a specific way to do gradient clipping
model.clip_grad_norm_(args.max_grad_norm)
else:
# Revert to normal clipping otherwise, handling Apex or full precision
nn.utils.clip_grad_norm_(
amp.master_params(self.optimizer) if self.use_apex else model.parameters(),
args.max_grad_norm,
)
# Optimizer step
optimizer_was_run = True
if self.deepspeed:
pass # called outside the loop
elif is_torch_tpu_available():
xm.optimizer_step(self.optimizer)
elif self.use_amp:
scale_before = self.scaler.get_scale()
self.scaler.step(self.optimizer)
self.scaler.update()
scale_after = self.scaler.get_scale()
optimizer_was_run = scale_before <= scale_after
else:
self.optimizer.step()
if optimizer_was_run and not self.deepspeed:
self.lr_scheduler.step()
model.zero_grad()
self.state.global_step += 1
self.state.epoch = epoch + (step + 1) / steps_in_epoch
self.control = self.callback_handler.on_step_end(args, self.state, self.control)
self._maybe_log_save_evaluate(tr_loss, model, trial, epoch, ignore_keys_for_eval)
else:
self.control = self.callback_handler.on_substep_end(args, self.state, self.control)
if self.control.should_epoch_stop or self.control.should_training_stop:
break
self.control = self.callback_handler.on_epoch_end(args, self.state, self.control)
self._maybe_log_save_evaluate(tr_loss, model, trial, epoch, ignore_keys_for_eval)
if DebugOption.TPU_METRICS_DEBUG in self.args.debug:
if is_torch_tpu_available():
# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
xm.master_print(met.metrics_report())
else:
logger.warning(
"You enabled PyTorch/XLA debug metrics but you don't have a TPU "
"configured. Check your training configuration if this is unexpected."
)
if self.control.should_training_stop:
break
if args.past_index and hasattr(self, "_past"):
# Clean the state at the end of training
delattr(self, "_past")
logger.info("\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n")
if args.load_best_model_at_end and self.state.best_model_checkpoint is not None:
# Wait for everyone to get here so we are sur the model has been saved by process 0.
if is_torch_tpu_available():
xm.rendezvous("load_best_model_at_end")
elif args.local_rank != -1:
dist.barrier()
logger.info(
f"Loading best model from {self.state.best_model_checkpoint} (score: {self.state.best_metric})."
)
best_model_path = os.path.join(self.state.best_model_checkpoint, WEIGHTS_NAME)
if os.path.exists(best_model_path):
# We load the model state dict on the CPU to avoid an OOM error.
state_dict = torch.load(best_model_path, map_location="cpu")
# If the model is on the GPU, it still works!
self._load_state_dict_in_model(state_dict)
else:
logger.warn(
f"Could not locate the best model at {best_model_path}, if you are running a distributed training "
"on multiple nodes, you should activate `--save_on_each_node`."
)
if self.deepspeed:
self.deepspeed.load_checkpoint(
self.state.best_model_checkpoint, load_optimizer_states=False, load_lr_scheduler_states=False
)
# add remaining tr_loss
self._total_loss_scalar += tr_loss.item()
train_loss = self._total_loss_scalar / self.state.global_step
metrics = speed_metrics("train", start_time, num_samples=num_train_samples, num_steps=self.state.max_steps)
self.store_flos()
metrics["total_flos"] = self.state.total_flos
metrics["train_loss"] = train_loss
self.is_in_train = False
self._memory_tracker.stop_and_update_metrics(metrics)
self.log(metrics)
self.control = self.callback_handler.on_train_end(args, self.state, self.control)
return TrainOutput(self.state.global_step, train_loss, metrics)
def _load_state_dict_in_model(self, state_dict):
load_result = self.model.load_state_dict(state_dict, strict=False)
if len(load_result.missing_keys) != 0:
if set(load_result.missing_keys) == set(self.model._keys_to_ignore_on_save):
self.model.tie_weights()
else:
logger.warn(f"There were missing keys in the checkpoint model loaded: {load_result.missing_keys}.")
if len(load_result.unexpected_keys) != 0:
logger.warn(f"There were unexpected keys in the checkpoint model loaded: {load_result.unexpected_keys}.")
def _maybe_log_save_evaluate(self, tr_loss, model, trial, epoch, ignore_keys_for_eval):
if self.control.should_log:
logs: Dict[str, float] = {}
tr_loss_scalar = tr_loss.item()
# reset tr_loss to zero
tr_loss -= tr_loss
logs["loss"] = round(tr_loss_scalar / (self.state.global_step - self._globalstep_last_logged), 4)
logs["learning_rate"] = self._get_learning_rate()
self._total_loss_scalar += tr_loss_scalar
self._globalstep_last_logged = self.state.global_step
self.store_flos()
self.log(logs)
metrics = None
if self.control.should_evaluate:
metrics = self.evaluate(ignore_keys=ignore_keys_for_eval)
self._report_to_hp_search(trial, epoch, metrics)
if self.control.should_save:
self._save_checkpoint(model, trial, metrics=metrics)
self.control = self.callback_handler.on_save(self.args, self.state, self.control)
def _load_rng_state(self, checkpoint):
# Load RNG states from `checkpoint`
if checkpoint is None:
return
local_rank = xm.get_local_ordinal() if is_torch_tpu_available() else self.args.local_rank
if local_rank != -1:
rng_file = os.path.join(checkpoint, f"rng_state_{local_rank}.pth")
if not os.path.isfile(os.path.join(checkpoint, rng_file)):
logger.info(
f"Didn't find an RNG file for process {local_rank}, if you are resuming a training that "
"wasn't launched in a distributed fashion, reproducibility is not guaranteed."
)
return
else:
rng_file = os.path.join(checkpoint, "rng_state.pth")
if not os.path.isfile(os.path.join(checkpoint, rng_file)):
logger.info(
"Didn't find an RNG file, if you are resuming a training that was launched in a distributed "
"fashion, reproducibility is not guaranteed."
)
return
checkpoint_rng_state = torch.load(rng_file)
random.setstate(checkpoint_rng_state["python"])
np.random.set_state(checkpoint_rng_state["numpy"])
torch.random.set_rng_state(checkpoint_rng_state["cpu"])
if torch.cuda.is_available():
if self.args.local_rank != -1:
torch.cuda.random.set_rng_state(checkpoint_rng_state["cuda"])
else:
torch.cuda.random.set_rng_state_all(checkpoint_rng_state["cuda"])
if is_torch_tpu_available():
xm.set_rng_state(checkpoint_rng_state["xla"])
def _save_checkpoint(self, model, trial, metrics=None):
# In all cases, including ddp/dp/deepspeed, self.model is always a reference to the model we
# want to save except FullyShardedDDP.
# assert unwrap_model(model) is self.model, "internal model should be a reference to self.model"
# Save model checkpoint
checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}"
if self.hp_search_backend is not None and trial is not None:
if self.hp_search_backend == HPSearchBackend.OPTUNA:
run_id = trial.number
else:
from ray import tune
run_id = tune.get_trial_id()
run_name = self.hp_name(trial) if self.hp_name is not None else f"run-{run_id}"
run_dir = os.path.join(self.args.output_dir, run_name)
else:
run_dir = self.args.output_dir
self.store_flos()
output_dir = os.path.join(run_dir, checkpoint_folder)
self.save_model(output_dir)
if self.deepspeed:
# under zero3 model file itself doesn't get saved since it's bogus! Unless deepspeed
# config `stage3_gather_fp16_weights_on_model_save` is True
self.deepspeed.save_checkpoint(output_dir)
# Save optimizer and scheduler
if self.sharded_ddp == ShardedDDPOption.SIMPLE:
self.optimizer.consolidate_state_dict()
if is_torch_tpu_available():
xm.rendezvous("saving_optimizer_states")
xm.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt"))
with warnings.catch_warnings(record=True) as caught_warnings:
xm.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
reissue_pt_warnings(caught_warnings)
elif is_sagemaker_mp_enabled():
if smp.dp_rank() == 0:
# Consolidate the state dict on all processed of dp_rank 0
opt_state_dict = self.optimizer.state_dict()
# Save it and the scheduler on the main process
if self.args.should_save:
torch.save(opt_state_dict, os.path.join(output_dir, "optimizer.pt"))
with warnings.catch_warnings(record=True) as caught_warnings:
torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
reissue_pt_warnings(caught_warnings)
if self.use_amp:
torch.save(self.scaler.state_dict(), os.path.join(output_dir, "scaler.pt"))
elif self.args.should_save and not self.deepspeed:
# deepspeed.save_checkpoint above saves model/optim/sched
torch.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt"))
with warnings.catch_warnings(record=True) as caught_warnings:
torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
reissue_pt_warnings(caught_warnings)
if self.use_amp:
torch.save(self.scaler.state_dict(), os.path.join(output_dir, "scaler.pt"))
# Determine the new best metric / best model checkpoint
if metrics is not None and self.args.metric_for_best_model is not None:
metric_to_check = self.args.metric_for_best_model
if not metric_to_check.startswith("eval_"):
metric_to_check = f"eval_{metric_to_check}"
metric_value = metrics[metric_to_check]
operator = np.greater if self.args.greater_is_better else np.less
if (
self.state.best_metric is None
or self.state.best_model_checkpoint is None
or operator(metric_value, self.state.best_metric)
):
self.state.best_metric = metric_value
self.state.best_model_checkpoint = output_dir
# Save the Trainer state
if self.args.should_save:
self.state.save_to_json(os.path.join(output_dir, "trainer_state.json"))
# Save RNG state in non-distributed training
rng_states = {
"python": random.getstate(),
"numpy": np.random.get_state(),
"cpu": torch.random.get_rng_state(),
}
if torch.cuda.is_available():
if self.args.local_rank == -1:
# In non distributed, we save the global CUDA RNG state (will take care of DataParallel)
rng_states["cuda"] = torch.cuda.random.get_rng_state_all()
else:
rng_states["cuda"] = torch.cuda.random.get_rng_state()
if is_torch_tpu_available():
rng_states["xla"] = xm.get_rng_state()
# A process can arrive here before the process 0 has a chance to save the model, in which case output_dir may
# not yet exist.
os.makedirs(output_dir, exist_ok=True)
local_rank = xm.get_local_ordinal() if is_torch_tpu_available() else self.args.local_rank
if local_rank == -1:
torch.save(rng_states, os.path.join(output_dir, "rng_state.pth"))
else:
torch.save(rng_states, os.path.join(output_dir, f"rng_state_{local_rank}.pth"))
# Maybe delete some older checkpoints.
if self.args.should_save:
self._rotate_checkpoints(use_mtime=True, output_dir=run_dir)
def _load_optimizer_and_scheduler(self, checkpoint):
"""If optimizer and scheduler states exist, load them."""
if checkpoint is None:
return
if self.deepspeed:
# deepspeed loads optimizer/lr_scheduler together with the model in deepspeed_init
return
if os.path.isfile(os.path.join(checkpoint, "optimizer.pt")) and os.path.isfile(
os.path.join(checkpoint, "scheduler.pt")
):
# Load in optimizer and scheduler states
if is_torch_tpu_available():
# On TPU we have to take some extra precautions to properly load the states on the right device.
optimizer_state = torch.load(os.path.join(checkpoint, "optimizer.pt"), map_location="cpu")
with warnings.catch_warnings(record=True) as caught_warnings:
lr_scheduler_state = torch.load(os.path.join(checkpoint, "scheduler.pt"), map_location="cpu")
reissue_pt_warnings(caught_warnings)
xm.send_cpu_data_to_device(optimizer_state, self.args.device)
xm.send_cpu_data_to_device(lr_scheduler_state, self.args.device)
self.optimizer.load_state_dict(optimizer_state)
self.lr_scheduler.load_state_dict(lr_scheduler_state)
else:
map_location = "cpu" if is_sagemaker_mp_enabled() else self.args.device
self.optimizer.load_state_dict(
torch.load(os.path.join(checkpoint, "optimizer.pt"), map_location=map_location)
)
with warnings.catch_warnings(record=True) as caught_warnings:
self.lr_scheduler.load_state_dict(torch.load(os.path.join(checkpoint, "scheduler.pt")))
reissue_pt_warnings(caught_warnings)
if self.use_amp and os.path.isfile(os.path.join(checkpoint, "scaler.pt")):
self.scaler.load_state_dict(torch.load(os.path.join(checkpoint, "scaler.pt")))
def hyperparameter_search(
self,
hp_space: Optional[Callable[["optuna.Trial"], Dict[str, float]]] = None,
compute_objective: Optional[Callable[[Dict[str, float]], float]] = None,
n_trials: int = 20,
direction: str = "minimize",
backend: Optional[Union["str", HPSearchBackend]] = None,
hp_name: Optional[Callable[["optuna.Trial"], str]] = None,
**kwargs,
) -> BestRun:
"""
Launch an hyperparameter search using ``optuna`` or ``Ray Tune``. The optimized quantity is determined by
:obj:`compute_objective`, which defaults to a function returning the evaluation loss when no metric is
provided, the sum of all metrics otherwise.
.. warning::
To use this method, you need to have provided a ``model_init`` when initializing your
:class:`~transformers.Trainer`: we need to reinitialize the model at each new run. This is incompatible
with the ``optimizers`` argument, so you need to subclass :class:`~transformers.Trainer` and override the
method :meth:`~transformers.Trainer.create_optimizer_and_scheduler` for custom optimizer/scheduler.
Args:
hp_space (:obj:`Callable[["optuna.Trial"], Dict[str, float]]`, `optional`):
A function that defines the hyperparameter search space. Will default to
:func:`~transformers.trainer_utils.default_hp_space_optuna` or
:func:`~transformers.trainer_utils.default_hp_space_ray` depending on your backend.
compute_objective (:obj:`Callable[[Dict[str, float]], float]`, `optional`):
A function computing the objective to minimize or maximize from the metrics returned by the
:obj:`evaluate` method. Will default to :func:`~transformers.trainer_utils.default_compute_objective`.
n_trials (:obj:`int`, `optional`, defaults to 100):
The number of trial runs to test.
direction(:obj:`str`, `optional`, defaults to :obj:`"minimize"`):
Whether to optimize greater or lower objects. Can be :obj:`"minimize"` or :obj:`"maximize"`, you should
pick :obj:`"minimize"` when optimizing the validation loss, :obj:`"maximize"` when optimizing one or
several metrics.
backend(:obj:`str` or :class:`~transformers.training_utils.HPSearchBackend`, `optional`):
The backend to use for hyperparameter search. Will default to optuna or Ray Tune, depending on which
one is installed. If both are installed, will default to optuna.
kwargs:
Additional keyword arguments passed along to :obj:`optuna.create_study` or :obj:`ray.tune.run`. For
more information see:
- the documentation of `optuna.create_study
<https://optuna.readthedocs.io/en/stable/reference/generated/optuna.study.create_study.html>`__
- the documentation of `tune.run
<https://docs.ray.io/en/latest/tune/api_docs/execution.html#tune-run>`__
Returns:
:class:`transformers.trainer_utils.BestRun`: All the information about the best run.
"""
if backend is None:
backend = default_hp_search_backend()
if backend is None:
raise RuntimeError(
"At least one of optuna or ray should be installed. "
"To install optuna run `pip install optuna`."
"To install ray run `pip install ray[tune]`."
)
backend = HPSearchBackend(backend)
if backend == HPSearchBackend.OPTUNA and not is_optuna_available():
raise RuntimeError("You picked the optuna backend, but it is not installed. Use `pip install optuna`.")
if backend == HPSearchBackend.RAY and not is_ray_tune_available():
raise RuntimeError(
"You picked the Ray Tune backend, but it is not installed. Use `pip install 'ray[tune]'`."
)
self.hp_search_backend = backend
if self.model_init is None:
raise RuntimeError(
"To use hyperparameter search, you need to pass your model through a model_init function."
)
self.hp_space = default_hp_space[backend] if hp_space is None else hp_space
self.hp_name = hp_name
self.compute_objective = default_compute_objective if compute_objective is None else compute_objective
run_hp_search = run_hp_search_optuna if backend == HPSearchBackend.OPTUNA else run_hp_search_ray
best_run = run_hp_search(self, n_trials, direction, **kwargs)
self.hp_search_backend = None
return best_run
def log(self, logs: Dict[str, float]) -> None:
"""
Log :obj:`logs` on the various objects watching training.
Subclass and override this method to inject custom behavior.
Args:
logs (:obj:`Dict[str, float]`):
The values to log.
"""
if self.state.epoch is not None:
logs["epoch"] = round(self.state.epoch, 2)
output = {**logs, **{"step": self.state.global_step}}
self.state.log_history.append(output)
self.control = self.callback_handler.on_log(self.args, self.state, self.control, logs)
def _prepare_inputs(self, inputs: Dict[str, Union[torch.Tensor, Any]]) -> Dict[str, Union[torch.Tensor, Any]]:
"""
Prepare :obj:`inputs` before feeding them to the model, converting them to tensors if they are not already and
handling potential state.
"""
for k, v in inputs.items():
if isinstance(v, torch.Tensor):
kwargs = dict(device=self.args.device)
if self.deepspeed and inputs[k].dtype != torch.int64:
# NLP models inputs are int64 and those get adjusted to the right dtype of the
# embedding. Other models such as wav2vec2's inputs are already float and thus
# may need special handling to match the dtypes of the model
kwargs.update(dict(dtype=self.args.hf_deepspeed_config.dtype()))
inputs[k] = v.to(**kwargs)
if self.args.past_index >= 0 and self._past is not None:
inputs["mems"] = self._past
return inputs
def training_step(self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]) -> torch.Tensor:
"""
Perform a training step on a batch of inputs.
Subclass and override to inject custom behavior.
Args:
model (:obj:`nn.Module`):
The model to train.
inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):
The inputs and targets of the model.
The dictionary will be unpacked before being fed to the model. Most models expect the targets under the
argument :obj:`labels`. Check your model's documentation for all accepted arguments.
Return:
:obj:`torch.Tensor`: The tensor with training loss on this batch.
"""
model.train()
inputs = self._prepare_inputs(inputs)
if is_sagemaker_mp_enabled():
scaler = self.scaler if self.use_amp else None
loss_mb = smp_forward_backward(model, inputs, self.args.gradient_accumulation_steps, scaler=scaler)
return loss_mb.reduce_mean().detach().to(self.args.device)
if self.use_amp:
with autocast():
loss = self.compute_loss(model, inputs)
else:
loss = self.compute_loss(model, inputs)
if self.args.n_gpu > 1:
loss = loss.mean() # mean() to average on multi-gpu parallel training
if self.args.gradient_accumulation_steps > 1 and not self.deepspeed:
# deepspeed handles loss scaling by gradient_accumulation_steps in its `backward`
loss = loss / self.args.gradient_accumulation_steps
if self.use_amp:
self.scaler.scale(loss).backward()
elif self.use_apex:
with amp.scale_loss(loss, self.optimizer) as scaled_loss:
scaled_loss.backward()
elif self.deepspeed:
# loss gets scaled under gradient_accumulation_steps in deepspeed
loss = self.deepspeed.backward(loss)
else:
loss.backward()
return loss.detach()
def compute_loss(self, model, inputs, return_outputs=False):
"""
How the loss is computed by Trainer. By default, all models return the loss in the first element.
Subclass and override for custom behavior.
"""
if self.label_smoother is not None and "labels" in inputs:
labels = inputs.pop("labels")
else:
labels = None
outputs = model(**inputs)
# Save past state if it exists
# TODO: this needs to be fixed and made cleaner later.
if self.args.past_index >= 0:
self._past = outputs[self.args.past_index]
if labels is not None:
loss = self.label_smoother(outputs, labels)
else:
# We don't use .loss here since the model may return tuples instead of ModelOutput.
loss = outputs["loss"] if isinstance(outputs, dict) else outputs[0]
return (loss, outputs) if return_outputs else loss
def is_local_process_zero(self) -> bool:
"""
Whether or not this process is the local (e.g., on one machine if training in a distributed fashion on several
machines) main process.
"""
return self.args.local_process_index == 0
def is_world_process_zero(self) -> bool:
"""
Whether or not this process is the global main process (when training in a distributed fashion on several
machines, this is only going to be :obj:`True` for one process).
"""
# Special case for SageMaker ModelParallel since there process_index is dp_process_index, not the global
# process index.
if is_sagemaker_mp_enabled():
return smp.rank() == 0
else:
return self.args.process_index == 0
def save_model(self, output_dir: Optional[str] = None):
"""
Will save the model, so you can reload it using :obj:`from_pretrained()`.
Will only save from the main process.
"""
if output_dir is None:
output_dir = self.args.output_dir
if is_torch_tpu_available():
self._save_tpu(output_dir)
elif is_sagemaker_mp_enabled():
# Calling the state_dict needs to be done on the wrapped model and on all processes.
state_dict = self.model_wrapped.state_dict()
if self.args.should_save:
self._save(output_dir, state_dict=state_dict)
elif (
ShardedDDPOption.ZERO_DP_2 in self.args.sharded_ddp or ShardedDDPOption.ZERO_DP_3 in self.args.sharded_ddp
):
state_dict = self.model.state_dict()
if self.args.should_save:
self._save(output_dir, state_dict=state_dict)
elif self.deepspeed:
# this takes care of everything as long as we aren't under zero3
if self.args.should_save:
self._save(output_dir)
if is_deepspeed_zero3_enabled():
# It's too complicated to try to override different places where the weights dump gets
# saved, so since under zero3 the file is bogus, simply delete it. The user should
# either user deepspeed checkpoint to resume or to recover full weights use
# zero_to_fp32.py stored in the checkpoint.
if self.args.should_save:
file = os.path.join(output_dir, WEIGHTS_NAME)
if os.path.isfile(file):
# logger.info(f"deepspeed zero3: removing {file}, see zero_to_fp32.py to recover weights")
os.remove(file)
# now save the real model if stage3_gather_fp16_weights_on_model_save=True
# if false it will not be saved.
# This must be called on all ranks
self.deepspeed.save_fp16_model(output_dir, WEIGHTS_NAME)
elif self.args.should_save:
self._save(output_dir)
def _save_tpu(self, output_dir: Optional[str] = None):
output_dir = output_dir if output_dir is not None else self.args.output_dir
logger.info(f"Saving model checkpoint to {output_dir}")
if xm.is_master_ordinal():
os.makedirs(output_dir, exist_ok=True)
torch.save(self.args, os.path.join(output_dir, "training_args.bin"))
# Save a trained model and configuration using `save_pretrained()`.
# They can then be reloaded using `from_pretrained()`
xm.rendezvous("saving_checkpoint")
if not isinstance(self.model, PreTrainedModel):
if isinstance(unwrap_model(self.model), PreTrainedModel):
unwrap_model(self.model).save_pretrained(
output_dir,
save_config=self.args.should_save,
state_dict=self.model.state_dict(),
save_function=xm.save,
)
else:
logger.info("Trainer.model is not a `PreTrainedModel`, only saving its state dict.")
state_dict = self.model.state_dict()
xm.save(state_dict, os.path.join(output_dir, WEIGHTS_NAME))
else:
self.model.save_pretrained(output_dir, save_config=self.args.should_save, save_function=xm.save)
if self.tokenizer is not None and self.args.should_save:
self.tokenizer.save_pretrained(output_dir)
def _save(self, output_dir: Optional[str] = None, state_dict=None):
# If we are executing this function, we are the process zero, so we don't check for that.
output_dir = output_dir if output_dir is not None else self.args.output_dir
os.makedirs(output_dir, exist_ok=True)
logger.info(f"Saving model checkpoint to {output_dir}")
# Save a trained model and configuration using `save_pretrained()`.
# They can then be reloaded using `from_pretrained()`
if not isinstance(self.model, PreTrainedModel):
if isinstance(unwrap_model(self.model), PreTrainedModel):
if state_dict is None:
state_dict = self.model.state_dict()
unwrap_model(self.model).save_pretrained(output_dir, state_dict=state_dict)
else:
logger.info("Trainer.model is not a `PreTrainedModel`, only saving its state dict.")
if state_dict is None:
state_dict = self.model.state_dict()
torch.save(state_dict, os.path.join(output_dir, WEIGHTS_NAME))
else:
self.model.save_pretrained(output_dir, state_dict=state_dict)
if self.tokenizer is not None:
self.tokenizer.save_pretrained(output_dir)
# Good practice: save your training arguments together with the trained model
torch.save(self.args, os.path.join(output_dir, "training_args.bin"))
def store_flos(self):
# Storing the number of floating-point operations that went into the model
if self.args.local_rank != -1:
self.state.total_flos += distributed_broadcast_scalars([self.current_flos]).sum().item()
self.current_flos = 0
else:
self.state.total_flos += self.current_flos
self.current_flos = 0
def _sorted_checkpoints(
self, output_dir=None, checkpoint_prefix=PREFIX_CHECKPOINT_DIR, use_mtime=False
) -> List[str]:
ordering_and_checkpoint_path = []
glob_checkpoints = [str(x) for x in Path(output_dir).glob(f"{checkpoint_prefix}-*")]
for path in glob_checkpoints:
if use_mtime:
ordering_and_checkpoint_path.append((os.path.getmtime(path), path))
else:
regex_match = re.match(f".*{checkpoint_prefix}-([0-9]+)", path)
if regex_match is not None and regex_match.groups() is not None:
ordering_and_checkpoint_path.append((int(regex_match.groups()[0]), path))
checkpoints_sorted = sorted(ordering_and_checkpoint_path)
checkpoints_sorted = [checkpoint[1] for checkpoint in checkpoints_sorted]
# Make sure we don't delete the best model.
if self.state.best_model_checkpoint is not None:
best_model_index = checkpoints_sorted.index(str(Path(self.state.best_model_checkpoint)))
for i in range(best_model_index, len(checkpoints_sorted) - 2):
checkpoints_sorted[i], checkpoints_sorted[i + 1] = checkpoints_sorted[i + 1], checkpoints_sorted[i]
return checkpoints_sorted
def _rotate_checkpoints(self, use_mtime=False, output_dir=None) -> None:
if self.args.save_total_limit is None or self.args.save_total_limit <= 0:
return
# Check if we should delete older checkpoint(s)
checkpoints_sorted = self._sorted_checkpoints(use_mtime=use_mtime, output_dir=output_dir)
if len(checkpoints_sorted) <= self.args.save_total_limit:
return
# If save_total_limit=1 with load_best_model_at_end=True, we could end up deleting the last checkpoint, which
# we don't do to allow resuming.
save_total_limit = self.args.save_total_limit
if (
self.state.best_model_checkpoint is not None
and self.args.save_total_limit == 1
and checkpoints_sorted[-1] != self.state.best_model_checkpoint
):
save_total_limit = 2
number_of_checkpoints_to_delete = max(0, len(checkpoints_sorted) - save_total_limit)
checkpoints_to_be_deleted = checkpoints_sorted[:number_of_checkpoints_to_delete]
for checkpoint in checkpoints_to_be_deleted:
logger.info(f"Deleting older checkpoint [{checkpoint}] due to args.save_total_limit")
shutil.rmtree(checkpoint)
def evaluate(
self,
eval_dataset: Optional[Dataset] = None,
ignore_keys: Optional[List[str]] = None,
metric_key_prefix: str = "eval",
) -> Dict[str, float]:
"""
Run evaluation and returns metrics.
The calling script will be responsible for providing a method to compute metrics, as they are task-dependent
(pass it to the init :obj:`compute_metrics` argument).
You can also subclass and override this method to inject custom behavior.
Args:
eval_dataset (:obj:`Dataset`, `optional`):
Pass a dataset if you wish to override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`,
columns not accepted by the ``model.forward()`` method are automatically removed. It must implement the
:obj:`__len__` method.
ignore_keys (:obj:`Lst[str]`, `optional`):
A list of keys in the output of your model (if it is a dictionary) that should be ignored when
gathering predictions.
metric_key_prefix (:obj:`str`, `optional`, defaults to :obj:`"eval"`):
An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named
"eval_bleu" if the prefix is "eval" (default)
Returns:
A dictionary containing the evaluation loss and the potential metrics computed from the predictions. The
dictionary also contains the epoch number which comes from the training state.
"""
# memory metrics - must set up as early as possible
self._memory_tracker.start()
eval_dataloader = self.get_eval_dataloader(eval_dataset)
start_time = time.time()
eval_loop = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
output = eval_loop(
eval_dataloader,
description="Evaluation",
# No point gathering the predictions if there are no metrics, otherwise we defer to
# self.args.prediction_loss_only
prediction_loss_only=True if self.compute_metrics is None else None,
ignore_keys=ignore_keys,
metric_key_prefix=metric_key_prefix,
)
total_batch_size = self.args.eval_batch_size * self.args.world_size
output.metrics.update(
speed_metrics(
metric_key_prefix,
start_time,
num_samples=output.num_samples,
num_steps=math.ceil(output.num_samples / total_batch_size),
)
)
self.log(output.metrics)
if DebugOption.TPU_METRICS_DEBUG in self.args.debug:
# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
xm.master_print(met.metrics_report())
self.control = self.callback_handler.on_evaluate(self.args, self.state, self.control, output.metrics)
self._memory_tracker.stop_and_update_metrics(output.metrics)
return output.metrics
def predict(
self, test_dataset: Dataset, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "test"
) -> PredictionOutput:
"""
Run prediction and returns predictions and potential metrics.
Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method
will also return metrics, like in :obj:`evaluate()`.
Args:
test_dataset (:obj:`Dataset`):
Dataset to run the predictions on. If it is an :obj:`datasets.Dataset`, columns not accepted by the
``model.forward()`` method are automatically removed. Has to implement the method :obj:`__len__`
ignore_keys (:obj:`Lst[str]`, `optional`):
A list of keys in the output of your model (if it is a dictionary) that should be ignored when
gathering predictions.
metric_key_prefix (:obj:`str`, `optional`, defaults to :obj:`"test"`):
An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named
"test_bleu" if the prefix is "test" (default)
.. note::
If your predictions or labels have different sequence length (for instance because you're doing dynamic
padding in a token classification task) the predictions will be padded (on the right) to allow for
concatenation into one array. The padding index is -100.
Returns: `NamedTuple` A namedtuple with the following keys:
- predictions (:obj:`np.ndarray`): The predictions on :obj:`test_dataset`.
- label_ids (:obj:`np.ndarray`, `optional`): The labels (if the dataset contained some).
- metrics (:obj:`Dict[str, float]`, `optional`): The potential dictionary of metrics (if the dataset
contained labels).
"""
# memory metrics - must set up as early as possible
self._memory_tracker.start()
test_dataloader = self.get_test_dataloader(test_dataset)
start_time = time.time()
eval_loop = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
output = eval_loop(
test_dataloader, description="Prediction", ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix
)
total_batch_size = self.args.eval_batch_size * self.args.world_size
output.metrics.update(
speed_metrics(
metric_key_prefix,
start_time,
num_samples=output.num_samples,
num_steps=math.ceil(output.num_samples / total_batch_size),
)
)
self._memory_tracker.stop_and_update_metrics(output.metrics)
return PredictionOutput(predictions=output.predictions, label_ids=output.label_ids, metrics=output.metrics)
def evaluation_loop(
self,
dataloader: DataLoader,
description: str,
prediction_loss_only: Optional[bool] = None,
ignore_keys: Optional[List[str]] = None,
metric_key_prefix: str = "eval",
) -> EvalLoopOutput:
"""
Prediction/evaluation loop, shared by :obj:`Trainer.evaluate()` and :obj:`Trainer.predict()`.
Works both with or without labels.
"""
prediction_loss_only = (
prediction_loss_only if prediction_loss_only is not None else self.args.prediction_loss_only
)
# if eval is called w/o train init deepspeed here
if self.args.deepspeed and not self.deepspeed:
# XXX: eval doesn't have `resume_from_checkpoint` arg but we should be able to do eval
# from the checkpoint eventually
deepspeed_engine, _, _ = deepspeed_init(self, num_training_steps=0, resume_from_checkpoint=None)
self.model = deepspeed_engine.module
self.model_wrapped = deepspeed_engine
self.deepspeed = deepspeed_engine
# XXX: we don't need optim/sched for inference, but this needs to be sorted out, since
# for example the Z3-optimizer is a must for zero3 to work even for inference - what we
# don't need is the deepspeed basic optimizer which is self.optimizer.optimizer
deepspeed_engine.optimizer.optimizer = None
deepspeed_engine.lr_scheduler = None
model = self._wrap_model(self.model, training=False)
# if full fp16 is wanted on eval and this ``evaluation`` or ``predict`` isn't called while
# ``train`` is running, halve it first and then put on device
if not self.is_in_train and self.args.fp16_full_eval:
model = model.half().to(self.args.device)
batch_size = dataloader.batch_size
logger.info(f"***** Running {description} *****")
if isinstance(dataloader.dataset, collections.abc.Sized):
logger.info(f" Num examples = {self.num_examples(dataloader)}")
else:
logger.info(" Num examples: Unknown")
logger.info(f" Batch size = {batch_size}")
model.eval()
self.callback_handler.eval_dataloader = dataloader
# Do this before wrapping.
eval_dataset = dataloader.dataset
if is_torch_tpu_available():
dataloader = pl.ParallelLoader(dataloader, [self.args.device]).per_device_loader(self.args.device)
if self.args.past_index >= 0:
self._past = None
# Initialize containers
# losses/preds/labels on GPU/TPU (accumulated for eval_accumulation_steps)
losses_host = None
preds_host = None
labels_host = None
# losses/preds/labels on CPU (final containers)
all_losses = None
all_preds = None
all_labels = None
# Will be useful when we have an iterable dataset so don't know its length.
observed_num_examples = 0
# Main evaluation loop
for step, inputs in enumerate(dataloader):
# Update the observed num examples
observed_batch_size = find_batch_size(inputs)
if observed_batch_size is not None:
observed_num_examples += observed_batch_size
# Prediction step
loss, logits, labels = self.prediction_step(model, inputs, prediction_loss_only, ignore_keys=ignore_keys)
# Update containers on host
if loss is not None:
losses = self._nested_gather(loss.repeat(batch_size))
losses_host = losses if losses_host is None else torch.cat((losses_host, losses), dim=0)
if logits is not None:
logits = self._pad_across_processes(logits)
logits = self._nested_gather(logits)
preds_host = logits if preds_host is None else nested_concat(preds_host, logits, padding_index=-100)
if labels is not None:
labels = self._pad_across_processes(labels)
labels = self._nested_gather(labels)
labels_host = labels if labels_host is None else nested_concat(labels_host, labels, padding_index=-100)
self.control = self.callback_handler.on_prediction_step(self.args, self.state, self.control)
# Gather all tensors and put them back on the CPU if we have done enough accumulation steps.
if self.args.eval_accumulation_steps is not None and (step + 1) % self.args.eval_accumulation_steps == 0:
if losses_host is not None:
losses = nested_numpify(losses_host)
all_losses = losses if all_losses is None else np.concatenate((all_losses, losses), axis=0)
if preds_host is not None:
logits = nested_numpify(preds_host)
all_preds = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-100)
if labels_host is not None:
labels = nested_numpify(labels_host)
all_labels = (
labels if all_labels is None else nested_concat(all_labels, labels, padding_index=-100)
)
# Set back to None to begin a new accumulation
losses_host, preds_host, labels_host = None, None, None
if self.args.past_index and hasattr(self, "_past"):
# Clean the state at the end of the evaluation loop
delattr(self, "_past")
# Gather all remaining tensors and put them back on the CPU
if losses_host is not None:
losses = nested_numpify(losses_host)
all_losses = losses if all_losses is None else np.concatenate((all_losses, losses), axis=0)
if preds_host is not None:
logits = nested_numpify(preds_host)
all_preds = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-100)
if labels_host is not None:
labels = nested_numpify(labels_host)
all_labels = labels if all_labels is None else nested_concat(all_labels, labels, padding_index=-100)
# Number of samples
if not isinstance(eval_dataset, IterableDataset):
num_samples = len(eval_dataset)
# The instance check is weird and does not actually check for the type, but whether the dataset has the right
# methods. Therefore we need to make sure it also has the attribute.
elif isinstance(eval_dataset, IterableDatasetShard) and hasattr(eval_dataset, "num_examples"):
num_samples = eval_dataset.num_examples
else:
num_samples = observed_num_examples
# Number of losses has been rounded to a multiple of batch_size and in a distributed training, the number of
# samplers has been rounded to a multiple of batch_size, so we truncate.
if all_losses is not None:
all_losses = all_losses[:num_samples]
if all_preds is not None:
all_preds = nested_truncate(all_preds, num_samples)
if all_labels is not None:
all_labels = nested_truncate(all_labels, num_samples)
# Metrics!
if self.compute_metrics is not None and all_preds is not None and all_labels is not None:
metrics = self.compute_metrics(EvalPrediction(predictions=all_preds, label_ids=all_labels))
else:
metrics = {}
# To be JSON-serializable, we need to remove numpy types or zero-d tensors
metrics = denumpify_detensorize(metrics)
if all_losses is not None:
metrics[f"{metric_key_prefix}_loss"] = all_losses.mean().item()
# Prefix all keys with metric_key_prefix + '_'
for key in list(metrics.keys()):
if not key.startswith(f"{metric_key_prefix}_"):
metrics[f"{metric_key_prefix}_{key}"] = metrics.pop(key)
return EvalLoopOutput(predictions=all_preds, label_ids=all_labels, metrics=metrics, num_samples=num_samples)
def _nested_gather(self, tensors, name=None):
"""
Gather value of `tensors` (tensor or list/tuple of nested tensors) and convert them to numpy before
concatenating them to `gathered`
"""
if tensors is None:
return
if is_torch_tpu_available():
if name is None:
name = "nested_gather"
tensors = nested_xla_mesh_reduce(tensors, name)
elif is_sagemaker_mp_enabled():
tensors = smp_gather(tensors)
elif self.args.local_rank != -1:
tensors = distributed_concat(tensors)
return tensors
# Copied from Accelerate.
def _pad_across_processes(self, tensor, pad_index=-100):
"""
Recursively pad the tensors in a nested list/tuple/dictionary of tensors from all devices to the same size so
they can safely be gathered.
"""
if isinstance(tensor, (list, tuple)):
return type(tensor)(self._pad_across_processes(t, pad_index=pad_index) for t in tensor)
elif isinstance(tensor, dict):
return type(tensor)({k: self._pad_across_processes(v, pad_index=pad_index) for k, v in tensor.items()})
elif not isinstance(tensor, torch.Tensor):
raise TypeError(
f"Can't pad the values of type {type(tensor)}, only of nested list/tuple/dicts of tensors."
)
if len(tensor.shape) < 2:
return tensor
# Gather all sizes
size = torch.tensor(tensor.shape, device=tensor.device)[None]
sizes = self._nested_gather(size).cpu()
max_size = max(s[1] for s in sizes)
if tensor.shape[1] == max_size:
return tensor
# Then pad to the maximum size
old_size = tensor.shape
new_size = list(old_size)
new_size[1] = max_size
new_tensor = tensor.new_zeros(tuple(new_size)) + pad_index
new_tensor[:, : old_size[1]] = tensor
return new_tensor
def prediction_step(
self,
model: nn.Module,
inputs: Dict[str, Union[torch.Tensor, Any]],
prediction_loss_only: bool,
ignore_keys: Optional[List[str]] = None,
) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]:
"""
Perform an evaluation step on :obj:`model` using obj:`inputs`.
Subclass and override to inject custom behavior.
Args:
model (:obj:`nn.Module`):
The model to evaluate.
inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):
The inputs and targets of the model.
The dictionary will be unpacked before being fed to the model. Most models expect the targets under the
argument :obj:`labels`. Check your model's documentation for all accepted arguments.
prediction_loss_only (:obj:`bool`):
Whether or not to return the loss only.
ignore_keys (:obj:`Lst[str]`, `optional`):
A list of keys in the output of your model (if it is a dictionary) that should be ignored when
gathering predictions.
Return:
Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]: A tuple with the loss,
logits and labels (each being optional).
"""
has_labels = all(inputs.get(k) is not None for k in self.label_names)
inputs = self._prepare_inputs(inputs)
if ignore_keys is None:
if hasattr(self.model, "config"):
ignore_keys = getattr(self.model.config, "keys_to_ignore_at_inference", [])
else:
ignore_keys = []
# labels may be popped when computing the loss (label smoothing for instance) so we grab them first.
if has_labels:
labels = nested_detach(tuple(inputs.get(name) for name in self.label_names))
if len(labels) == 1:
labels = labels[0]
else:
labels = None
with torch.no_grad():
if is_sagemaker_mp_enabled():
raw_outputs = smp_forward_only(model, inputs)
if has_labels:
if isinstance(raw_outputs, dict):
loss_mb = raw_outputs["loss"]
logits_mb = tuple(v for k, v in raw_outputs.items() if k not in ignore_keys + ["loss"])
else:
loss_mb = raw_outputs[0]
logits_mb = raw_outputs[1:]
loss = loss_mb.reduce_mean().detach().cpu()
logits = smp_nested_concat(logits_mb)
else:
loss = None
if isinstance(raw_outputs, dict):
logits_mb = tuple(v for k, v in raw_outputs.items() if k not in ignore_keys)
else:
logits_mb = raw_outputs
logits = smp_nested_concat(logits_mb)
else:
if has_labels:
loss, outputs = self.compute_loss(model, inputs, return_outputs=True)
loss = loss.mean().detach()
if isinstance(outputs, dict):
logits = tuple(v for k, v in outputs.items() if k not in ignore_keys + ["loss"])
else:
logits = outputs[1:]
else:
loss = None
if self.use_amp:
with autocast():
outputs = model(**inputs)
else:
outputs = model(**inputs)
if isinstance(outputs, dict):
logits = tuple(v for k, v in outputs.items() if k not in ignore_keys)
else:
logits = outputs
# TODO: this needs to be fixed and made cleaner later.
if self.args.past_index >= 0:
self._past = outputs[self.args.past_index - 1]
if prediction_loss_only:
return (loss, None, None)
logits = nested_detach(logits)
if len(logits) == 1:
logits = logits[0]
return (loss, logits, labels)
def floating_point_ops(self, inputs: Dict[str, Union[torch.Tensor, Any]]):
"""
For models that inherit from :class:`~transformers.PreTrainedModel`, uses that method to compute the number of
floating point operations for every backward + forward pass. If using another model, either implement such a
method in the model or subclass and override this method.
Args:
inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):
The inputs and targets of the model.
Returns:
:obj:`int`: The number of floating-point operations.
"""
if hasattr(self.model, "floating_point_ops"):
return self.model.floating_point_ops(inputs)
else:
return 0
def init_git_repo(self):
"""
Initializes a git repo in :obj:`self.args.push_to_hub_model_id`.
"""
if not self.args.should_save:
return
use_auth_token = True if self.args.push_to_hub_token is None else self.args.push_to_hub_token
repo_url = PushToHubMixin._get_repo_url_from_name(
self.args.push_to_hub_model_id,
organization=self.args.push_to_hub_organization,
use_auth_token=use_auth_token,
)
self.repo = PushToHubMixin._create_or_get_repo(
self.args.output_dir, repo_url=repo_url, use_auth_token=use_auth_token
)
# By default, ignore the checkpoint folders
if not os.path.exists(os.path.join(self.args.output_dir, ".gitignore")):
with open(os.path.join(self.args.output_dir, ".gitignore"), "w", encoding="utf-8") as writer:
writer.writelines(["checkpoint-*/"])
def create_model_card(
self,
language: Optional[str] = None,
license: Optional[str] = None,
tags: Optional[str] = None,
model_name: Optional[str] = None,
finetuned_from: Optional[str] = None,
tasks: Optional[str] = None,
dataset_tags: Optional[Union[str, List[str]]] = None,
dataset: Optional[Union[str, List[str]]] = None,
dataset_args: Optional[Union[str, List[str]]] = None,
):
training_summary = TrainingSummary.from_trainer(
self,
language=language,
license=license,
tags=tags,
model_name=model_name,
finetuned_from=finetuned_from,
tasks=tasks,
dataset_tags=dataset_tags,
dataset=dataset,
dataset_args=dataset_args,
)
model_card = training_summary.to_model_card()
with open(os.path.join(self.args.output_dir, "README.md"), "w") as f:
f.write(model_card)
def push_to_hub(self, commit_message: Optional[str] = "add model", **kwargs) -> str:
"""
Upload `self.model` and `self.tokenizer` to the 🤗 model hub on the repo `self.args.push_to_hub_model_id`.
Parameters:
commit_message (:obj:`str`, `optional`, defaults to :obj:`"add model"`):
Message to commit while pushing.
kwargs:
Additional keyword arguments passed along to :meth:`~transformers.Trainer.create_model_card`.
Returns:
The url of the commit of your model in the given repository.
"""
if self.args.should_save:
self.create_model_card(model_name=self.args.push_to_hub_model_id, **kwargs)
# Needs to be executed on all processes for TPU training, but will only save on the processed determined by
# self.args.should_save.
self.save_model()
# Only push from one node.
if not self.is_world_process_zero():
return
return self.repo.push_to_hub(commit_message=commit_message)
#
# Deprecated code
#
def prediction_loop(
self,
dataloader: DataLoader,
description: str,
prediction_loss_only: Optional[bool] = None,
ignore_keys: Optional[List[str]] = None,
metric_key_prefix: str = "eval",
) -> PredictionOutput:
"""
Prediction/evaluation loop, shared by :obj:`Trainer.evaluate()` and :obj:`Trainer.predict()`.
Works both with or without labels.
"""
if not isinstance(dataloader.dataset, collections.abc.Sized):
raise ValueError("dataset must implement __len__")
prediction_loss_only = (
prediction_loss_only if prediction_loss_only is not None else self.args.prediction_loss_only
)
# if eval is called w/o train init deepspeed here
if self.args.deepspeed and not self.deepspeed:
# XXX: eval doesn't have `resume_from_checkpoint` arg but we should be able to do eval
# from the checkpoint eventually
deepspeed_engine, _, _ = deepspeed_init(self, num_training_steps=0, resume_from_checkpoint=None)
self.model = deepspeed_engine.module
self.model_wrapped = deepspeed_engine
self.deepspeed = deepspeed_engine
# XXX: we don't need optim/sched for inference, but this needs to be sorted out, since
# for example the Z3-optimizer is a must for zero3 to work even for inference - what we
# don't need is the deepspeed basic optimizer which is self.optimizer.optimizer
deepspeed_engine.optimizer.optimizer = None
deepspeed_engine.lr_scheduler = None
model = self._wrap_model(self.model, training=False)
# if full fp16 is wanted on eval and this ``evaluation`` or ``predict`` isn't called while
# ``train`` is running, halve it first and then put on device
if not self.is_in_train and self.args.fp16_full_eval:
model = model.half().to(self.args.device)
batch_size = dataloader.batch_size
num_examples = self.num_examples(dataloader)
logger.info(f"***** Running {description} *****")
logger.info(f" Num examples = {num_examples}")
logger.info(f" Batch size = {batch_size}")
losses_host: torch.Tensor = None
preds_host: Union[torch.Tensor, List[torch.Tensor]] = None
labels_host: Union[torch.Tensor, List[torch.Tensor]] = None
world_size = max(1, self.args.world_size)
eval_losses_gatherer = DistributedTensorGatherer(world_size, num_examples, make_multiple_of=batch_size)
if not prediction_loss_only:
# The actual number of eval_sample can be greater than num_examples in distributed settings (when we pass
# a batch size to the sampler)
make_multiple_of = None
if hasattr(dataloader, "sampler") and isinstance(dataloader.sampler, SequentialDistributedSampler):
make_multiple_of = dataloader.sampler.batch_size
preds_gatherer = DistributedTensorGatherer(world_size, num_examples, make_multiple_of=make_multiple_of)
labels_gatherer = DistributedTensorGatherer(world_size, num_examples, make_multiple_of=make_multiple_of)
model.eval()
if is_torch_tpu_available():
dataloader = pl.ParallelLoader(dataloader, [self.args.device]).per_device_loader(self.args.device)
if self.args.past_index >= 0:
self._past = None
self.callback_handler.eval_dataloader = dataloader
for step, inputs in enumerate(dataloader):
loss, logits, labels = self.prediction_step(model, inputs, prediction_loss_only, ignore_keys=ignore_keys)
if loss is not None:
losses = loss.repeat(batch_size)
losses_host = losses if losses_host is None else torch.cat((losses_host, losses), dim=0)
if logits is not None:
preds_host = logits if preds_host is None else nested_concat(preds_host, logits, padding_index=-100)
if labels is not None:
labels_host = labels if labels_host is None else nested_concat(labels_host, labels, padding_index=-100)
self.control = self.callback_handler.on_prediction_step(self.args, self.state, self.control)
# Gather all tensors and put them back on the CPU if we have done enough accumulation steps.
if self.args.eval_accumulation_steps is not None and (step + 1) % self.args.eval_accumulation_steps == 0:
eval_losses_gatherer.add_arrays(self._gather_and_numpify(losses_host, "eval_losses"))
if not prediction_loss_only:
preds_gatherer.add_arrays(self._gather_and_numpify(preds_host, "eval_preds"))
labels_gatherer.add_arrays(self._gather_and_numpify(labels_host, "eval_label_ids"))
# Set back to None to begin a new accumulation
losses_host, preds_host, labels_host = None, None, None
if self.args.past_index and hasattr(self, "_past"):
# Clean the state at the end of the evaluation loop
delattr(self, "_past")
# Gather all remaining tensors and put them back on the CPU
eval_losses_gatherer.add_arrays(self._gather_and_numpify(losses_host, "eval_losses"))
if not prediction_loss_only:
preds_gatherer.add_arrays(self._gather_and_numpify(preds_host, "eval_preds"))
labels_gatherer.add_arrays(self._gather_and_numpify(labels_host, "eval_label_ids"))
eval_loss = eval_losses_gatherer.finalize()
preds = preds_gatherer.finalize() if not prediction_loss_only else None
label_ids = labels_gatherer.finalize() if not prediction_loss_only else None
if self.compute_metrics is not None and preds is not None and label_ids is not None:
metrics = self.compute_metrics(EvalPrediction(predictions=preds, label_ids=label_ids))
else:
metrics = {}
# To be JSON-serializable, we need to remove numpy types or zero-d tensors
metrics = denumpify_detensorize(metrics)
if eval_loss is not None:
metrics[f"{metric_key_prefix}_loss"] = eval_loss.mean().item()
# Prefix all keys with metric_key_prefix + '_'
for key in list(metrics.keys()):
if not key.startswith(f"{metric_key_prefix}_"):
metrics[f"{metric_key_prefix}_{key}"] = metrics.pop(key)
return PredictionOutput(predictions=preds, label_ids=label_ids, metrics=metrics)
def _gather_and_numpify(self, tensors, name):
"""
Gather value of `tensors` (tensor or list/tuple of nested tensors) and convert them to numpy before
concatenating them to `gathered`
"""
if tensors is None:
return
if is_torch_tpu_available():
tensors = nested_xla_mesh_reduce(tensors, name)
elif is_sagemaker_mp_enabled():
tensors = smp_gather(tensors)
elif self.args.local_rank != -1:
tensors = distributed_concat(tensors)
return nested_numpify(tensors)
|
import abc
import logging
import mimetypes
import os
import shutil
import string
import tempfile
from inspect import isclass
from typing import (
Any,
Dict,
List,
Optional,
Tuple,
TYPE_CHECKING,
)
from markupsafe import escape
from galaxy import util
from galaxy.datatypes.metadata import (
MetadataElement, # import directly to maintain ease of use in Datatype class definitions
)
from galaxy.datatypes.sniff import (
build_sniff_from_prefix,
FilePrefix,
)
from galaxy.exceptions import ObjectNotFound
from galaxy.util import (
compression_utils,
file_reader,
FILENAME_VALID_CHARS,
inflector,
iter_start_of_line,
smart_str,
unicodify,
)
from galaxy.util.bunch import Bunch
from galaxy.util.sanitize_html import sanitize_html
from galaxy.util.zipstream import ZipstreamWrapper
from . import dataproviders as p_dataproviders
from . import metadata
if TYPE_CHECKING:
from galaxy.model import DatasetInstance
XSS_VULNERABLE_MIME_TYPES = [
'image/svg+xml', # Unfiltered by Galaxy and may contain JS that would be executed by some browsers.
'application/xml', # Some browsers will evalute SVG embedded JS in such XML documents.
]
DEFAULT_MIME_TYPE = 'text/plain' # Vulnerable mime types will be replaced with this.
log = logging.getLogger(__name__)
# Valid first column and strand column values vor bed, other formats
col1_startswith = ['chr', 'chl', 'groupun', 'reftig_', 'scaffold', 'super_', 'vcho']
valid_strand = ['+', '-', '.']
DOWNLOAD_FILENAME_PATTERN_DATASET = "Galaxy${hid}-[${name}].${ext}"
DOWNLOAD_FILENAME_PATTERN_COLLECTION_ELEMENT = "Galaxy${hdca_hid}-[${hdca_name}__${element_identifier}].${ext}"
DEFAULT_MAX_PEEK_SIZE = 1000000 # 1 MB
Headers = Dict[str, Any]
class DatatypeConverterNotFoundException(Exception):
pass
class DatatypeValidation:
def __init__(self, state, message):
self.state = state
self.message = message
@staticmethod
def validated():
return DatatypeValidation("ok", "Dataset validated by datatype validator.")
@staticmethod
def invalid(message):
return DatatypeValidation("invalid", message)
@staticmethod
def unvalidated():
return DatatypeValidation("unknown", "Dataset validation unimplemented for this datatype.")
def __repr__(self):
return f"DatatypeValidation[state={self.state},message={self.message}]"
def validate(dataset_instance):
try:
datatype_validation = dataset_instance.datatype.validate(dataset_instance)
except Exception as e:
datatype_validation = DatatypeValidation.invalid(f"Problem running datatype validation method [{str(e)}]")
return datatype_validation
def get_params_and_input_name(converter, deps, target_context=None):
# Generate parameter dictionary
params = {}
# determine input parameter name and add to params
input_name = 'input1'
for key, value in converter.inputs.items():
if deps and value.name in deps:
params[value.name] = deps[value.name]
elif value.type == 'data':
input_name = key
# add potentially required/common internal tool parameters e.g. '__job_resource'
if target_context:
for key, value in target_context.items():
if key.startswith('__'):
params[key] = value
return params, input_name
class DataMeta(abc.ABCMeta):
"""
Metaclass for Data class. Sets up metadata spec.
"""
def __init__(cls, name, bases, dict_):
cls.metadata_spec = metadata.MetadataSpecCollection()
for base in bases: # loop through bases (class/types) of cls
if hasattr(base, "metadata_spec"): # base of class Data (object) has no metadata
cls.metadata_spec.update(base.metadata_spec) # add contents of metadata spec of base class to cls
metadata.Statement.process(cls)
@p_dataproviders.decorators.has_dataproviders
class Data(metaclass=DataMeta):
"""
Base class for all datatypes. Implements basic interfaces as well
as class methods for metadata.
>>> class DataTest( Data ):
... MetadataElement( name="test" )
...
>>> DataTest.metadata_spec.test.name
'test'
>>> DataTest.metadata_spec.test.desc
'test'
>>> type( DataTest.metadata_spec.test.param )
<class 'galaxy.model.metadata.MetadataParameter'>
"""
edam_data = "data_0006"
edam_format = "format_1915"
file_ext = 'data'
# Data is not chunkable by default.
CHUNKABLE = False
#: Dictionary of metadata fields for this datatype
metadata_spec: metadata.MetadataSpecCollection
# Add metadata elements
MetadataElement(name="dbkey", desc="Database/Build", default="?", param=metadata.DBKeyParameter, multiple=False, no_value="?")
# Stores the set of display applications, and viewing methods, supported by this datatype
supported_display_apps: Dict[str, Any] = {}
# If False, the peek is regenerated whenever a dataset of this type is copied
copy_safe_peek = True
# The dataset contains binary data --> do not space_to_tab or convert newlines, etc.
# Allow binary file uploads of this type when True.
is_binary = True
# Composite datatypes
composite_type: Optional[str] = None
composite_files: Dict[str, Any] = {}
primary_file_name = 'index'
# Allow user to change between this datatype and others. If left to None,
# datatype change is allowed if the datatype is not composite.
allow_datatype_change: Optional[bool] = None
# A per datatype setting (inherited): max file size (in bytes) for setting optional metadata
_max_optional_metadata_filesize = None
# Trackster track type.
track_type: Optional[str] = None
# Data sources.
data_sources: Dict[str, str] = {}
dataproviders: Dict[str, Any]
def __init__(self, **kwd):
"""Initialize the datatype"""
self.supported_display_apps = self.supported_display_apps.copy()
self.composite_files = self.composite_files.copy()
self.display_applications = {}
@classmethod
def is_datatype_change_allowed(cls):
"""
Returns the value of the `allow_datatype_change` class attribute if set
in a subclass, or True iff the datatype is not composite.
"""
if cls.allow_datatype_change is not None:
return cls.allow_datatype_change
return cls.composite_type is None
def get_raw_data(self, dataset):
"""Returns the full data. To stream it open the file_name and read/write as needed"""
try:
return open(dataset.file_name, 'rb').read(-1)
except OSError:
log.exception('%s reading a file that does not exist %s', self.__class__.__name__, dataset.file_name)
return ''
def dataset_content_needs_grooming(self, file_name):
"""This function is called on an output dataset file after the content is initially generated."""
return False
def groom_dataset_content(self, file_name):
"""This function is called on an output dataset file if dataset_content_needs_grooming returns True."""
def init_meta(self, dataset, copy_from=None):
# Metadata should be left mostly uninitialized. Dataset will
# handle returning default values when metadata is not set.
# copy_from allows metadata to be passed in that will be
# copied. (although this seems ambiguous, see
# Dataset.set_metadata. It always copies the rhs in order to
# flag the object as modified for SQLAlchemy.
if copy_from:
dataset.metadata = copy_from.metadata
def set_meta(self, dataset: Any, overwrite=True, **kwd):
"""Unimplemented method, allows guessing of metadata from contents of file"""
return True
def missing_meta(self, dataset, check=None, skip=None):
"""
Checks for empty metadata values, Returns True if non-optional metadata is missing
Specifying a list of 'check' values will only check those names provided; when used, optionality is ignored
Specifying a list of 'skip' items will return True even when a named metadata value is missing
"""
if skip is None:
skip = []
if check:
to_check = ((to_check, dataset.metadata.get(to_check)) for to_check in check)
else:
to_check = dataset.metadata.items()
for key, value in to_check:
if key in skip or (not check and dataset.metadata.spec[key].get("optional")):
continue # we skip check for optional and nonrequested values here
if not value:
return True
return False
def set_max_optional_metadata_filesize(self, max_value):
try:
max_value = int(max_value)
except (TypeError, ValueError):
return
self.__class__._max_optional_metadata_filesize = max_value
def get_max_optional_metadata_filesize(self):
rval = self.__class__._max_optional_metadata_filesize
if rval is None:
return -1
return rval
max_optional_metadata_filesize = property(get_max_optional_metadata_filesize, set_max_optional_metadata_filesize)
def set_peek(self, dataset):
"""
Set the peek and blurb text
"""
if not dataset.dataset.purged:
dataset.peek = ''
dataset.blurb = 'data'
else:
dataset.peek = 'file does not exist'
dataset.blurb = 'file purged from disk'
def display_peek(self, dataset):
"""Create HTML table, used for displaying peek"""
out = ['<table cellspacing="0" cellpadding="3">']
try:
if not dataset.peek:
dataset.set_peek()
data = dataset.peek
lines = data.splitlines()
for line in lines:
line = line.strip()
if not line:
continue
out.append(f"<tr><td>{escape(unicodify(line, "utf-8"))}</td></tr>")
out.append('</table>')
return "".join(out)
except Exception as exc:
return f"Can't create peek: {unicodify(exc)}"
def _archive_main_file(self, archive, display_name, data_filename):
"""Called from _archive_composite_dataset to add central file to archive.
Unless subclassed, this will add the main dataset file (argument data_filename)
to the archive, as an HTML file with its filename derived from the dataset name
(argument outfname).
Returns a tuple of boolean, string, string: (error, msg, messagetype)
"""
error, msg, messagetype = False, "", ""
archname = f'{display_name}.html' # fake the real nature of the html file
try:
archive.write(data_filename, archname)
except OSError:
error = True
log.exception("Unable to add composite parent %s to temporary library download archive", data_filename)
msg = "Unable to create archive for download, please report this error"
messagetype = "error"
return error, msg, messagetype
def _archive_composite_dataset(self, trans, data, headers: Headers, do_action='zip'):
# save a composite object into a compressed archive for downloading
outfname = data.name[0:150]
outfname = ''.join(c in FILENAME_VALID_CHARS and c or '_' for c in outfname)
archive = ZipstreamWrapper(
archive_name=outfname,
upstream_mod_zip=trans.app.config.upstream_mod_zip,
upstream_gzip=trans.app.config.upstream_gzip
)
error = False
msg = ''
ext = data.extension
path = data.file_name
efp = data.extra_files_path
# Add any central file to the archive,
display_name = os.path.splitext(outfname)[0]
if not display_name.endswith(ext):
display_name = f'{display_name}_{ext}'
error, msg = self._archive_main_file(archive, display_name, path)[:2]
if not error:
# Add any child files to the archive,
for fpath, rpath in self.__archive_extra_files_path(extra_files_path=efp):
try:
archive.write(fpath, rpath)
except OSError:
error = True
log.exception("Unable to add %s to temporary library download archive", rpath)
msg = "Unable to create archive for download, please report this error"
continue
if not error:
headers.update(archive.get_headers())
return archive.response(), headers
return trans.show_error_message(msg), headers
def __archive_extra_files_path(self, extra_files_path):
"""Yield filepaths and relative filepaths for files in extra_files_path"""
for root, _, files in os.walk(extra_files_path):
for fname in files:
fpath = os.path.join(root, fname)
rpath = os.path.relpath(fpath, extra_files_path)
yield fpath, rpath
def _serve_raw(self, dataset, to_ext, headers: Headers, **kwd):
headers['Content-Length'] = str(os.stat(dataset.file_name).st_size)
headers["content-type"] = "application/octet-stream" # force octet-stream so Safari doesn't append mime extensions to filename
filename = self._download_filename(dataset, to_ext, hdca=kwd.get("hdca"), element_identifier=kwd.get("element_identifier"), filename_pattern=kwd.get("filename_pattern"))
headers["Content-Disposition"] = f'attachment; filename="{filename}"'
return open(dataset.file_name, mode='rb'), headers
def to_archive(self, dataset, name=""):
"""
Collect archive paths and file handles that need to be exported when archiving `dataset`.
:param dataset: HistoryDatasetAssociation
:param name: archive name, in collection context corresponds to collection name(s) and element_identifier,
joined by '/', e.g 'fastq_collection/sample1/forward'
"""
rel_paths = []
file_paths = []
if dataset.datatype.composite_type or dataset.extension == 'html':
main_file = f"{name}.html"
rel_paths.append(main_file)
file_paths.append(dataset.file_name)
for fpath, rpath in self.__archive_extra_files_path(dataset.extra_files_path):
rel_paths.append(os.path.join(name, rpath))
file_paths.append(fpath)
else:
rel_paths.append(f"{name or dataset.file_name}.{dataset.extension}")
file_paths.append(dataset.file_name)
return zip(file_paths, rel_paths)
def display_data(self, trans, data, preview=False, filename=None, to_ext=None, **kwd):
"""
Displays data in central pane if preview is `True`, else handles download.
Datatypes should be very careful if overridding this method and this interface
between datatypes and Galaxy will likely change.
TOOD: Document alternatives to overridding this method (data
providers?).
"""
headers = kwd.get("headers", {})
# Relocate all composite datatype display to a common location.
composite_extensions = trans.app.datatypes_registry.get_composite_extensions()
composite_extensions.append('html') # for archiving composite datatypes
# Prevent IE8 from sniffing content type since we're explicit about it. This prevents intentionally text/plain
# content from being rendered in the browser
headers['X-Content-Type-Options'] = 'nosniff'
if isinstance(data, str):
return smart_str(data), headers
if filename and filename != "index":
# For files in extra_files_path
extra_dir = data.dataset.extra_files_path_name
file_path = trans.app.object_store.get_filename(data.dataset, extra_dir=extra_dir, alt_name=filename)
if os.path.exists(file_path):
if os.path.isdir(file_path):
with tempfile.NamedTemporaryFile(mode='w', delete=False, dir=trans.app.config.new_file_path, prefix='gx_html_autocreate_') as tmp_fh:
tmp_file_name = tmp_fh.name
dir_items = sorted(os.listdir(file_path))
base_path, item_name = os.path.split(file_path)
tmp_fh.write('<html><head><h3>Directory %s contents: %d items</h3></head>\n' % (escape(item_name), len(dir_items)))
tmp_fh.write('<body><p/><table cellpadding="2">\n')
for index, fname in enumerate(dir_items):
if index % 2 == 0:
bgcolor = '#D8D8D8'
else:
bgcolor = '#FFFFFF'
# Can't have an href link here because there is no route
# defined for files contained within multiple subdirectory
# levels of the primary dataset. Something like this is
# close, but not quite correct:
# href = url_for(controller='dataset', action='display',
# dataset_id=trans.security.encode_id(data.dataset.id),
# preview=preview, filename=fname, to_ext=to_ext)
tmp_fh.write(f'<tr bgcolor="{bgcolor}"><td>{escape(fname)}</td></tr>\n')
tmp_fh.write('</table></body></html>\n')
return self._yield_user_file_content(trans, data, tmp_file_name, headers), headers
mime = mimetypes.guess_type(file_path)[0]
if not mime:
try:
mime = trans.app.datatypes_registry.get_mimetype_by_extension(".".split(file_path)[-1])
except Exception:
mime = "text/plain"
self._clean_and_set_mime_type(trans, mime, headers)
return self._yield_user_file_content(trans, data, file_path, headers), headers
else:
raise ObjectNotFound(f"Could not find '{filename}' on the extra files path {file_path}.")
self._clean_and_set_mime_type(trans, data.get_mime(), headers)
trans.log_event(f"Display dataset id: {str(data.id)}")
from galaxy.datatypes import ( # DBTODO REMOVE THIS AT REFACTOR
binary,
images,
text,
)
if to_ext or isinstance(
data.datatype, binary.Binary
): # Saving the file, or binary file
if data.extension in composite_extensions:
return self._archive_composite_dataset(trans, data, headers, do_action=kwd.get('do_action', 'zip'))
else:
headers['Content-Length'] = str(os.stat(data.file_name).st_size)
filename = self._download_filename(data, to_ext, hdca=kwd.get("hdca"), element_identifier=kwd.get("element_identifier"), filename_pattern=kwd.get("filename_pattern"))
headers['content-type'] = "application/octet-stream" # force octet-stream so Safari doesn't append mime extensions to filename
headers["Content-Disposition"] = f'attachment; filename="{filename}"'
return open(data.file_name, 'rb'), headers
if not os.path.exists(data.file_name):
raise ObjectNotFound(f"File Not Found ({data.file_name}).")
max_peek_size = DEFAULT_MAX_PEEK_SIZE # 1 MB
if isinstance(data.datatype, text.Html):
max_peek_size = 10000000 # 10 MB for html
preview = util.string_as_bool(preview)
if (
not preview
or isinstance(data.datatype, images.Image)
or os.stat(data.file_name).st_size < max_peek_size
):
return self._yield_user_file_content(trans, data, data.file_name, headers), headers
else:
headers["content-type"] = "text/html"
return trans.fill_template_mako("/dataset/large_file.mako",
truncated_data=open(data.file_name, 'rb').read(max_peek_size),
data=data), headers
def display_as_markdown(self, dataset_instance, markdown_format_helpers):
"""Prepare for embedding dataset into a basic Markdown document.
This is a somewhat experimental interface and should not be implemented
on datatypes not tightly tied to a Galaxy version (e.g. datatypes in the
Tool Shed).
Speaking very losely - the datatype should should load a bounded amount
of data from the supplied dataset instance and prepare for embedding it
into Markdown. This should be relatively vanilla Markdown - the result of
this is bleached and it should not contain nested Galaxy Markdown
directives.
If the data cannot reasonably be displayed, just indicate this and do
not throw an exception.
"""
if self.file_ext in {'png', 'jpg'}:
return self.handle_dataset_as_image(dataset_instance)
if self.is_binary:
result = "*cannot display binary content*\n"
else:
with open(dataset_instance.file_name) as f:
contents = f.read(DEFAULT_MAX_PEEK_SIZE)
result = markdown_format_helpers.literal_via_fence(contents)
if len(contents) == DEFAULT_MAX_PEEK_SIZE:
result += markdown_format_helpers.indicate_data_truncated()
return result
def _yield_user_file_content(self, trans, from_dataset, filename, headers: Headers):
"""This method is responsible for sanitizing the HTML if needed."""
if trans.app.config.sanitize_all_html and headers.get("content-type", None) == "text/html":
# Sanitize anytime we respond with plain text/html content.
# Check to see if this dataset's parent job is allowlisted
# We cannot currently trust imported datasets for rendering.
if not from_dataset.creating_job.imported and from_dataset.creating_job.tool_id.startswith(tuple(trans.app.config.sanitize_allowlist)):
return open(filename, mode='rb')
# This is returning to the browser, it needs to be encoded.
# TODO Ideally this happens a layer higher, but this is a bad
# issue affecting many tools
with open(filename) as f:
return sanitize_html(f.read()).encode('utf-8')
return open(filename, mode='rb')
def _download_filename(self, dataset, to_ext, hdca=None, element_identifier=None, filename_pattern=None):
def escape(raw_identifier):
return ''.join(c in FILENAME_VALID_CHARS and c or '_' for c in raw_identifier)[0:150]
if not to_ext or to_ext == "data":
# If a client requests to_ext with the extension 'data', they are
# deferring to the server, set it based on datatype.
to_ext = dataset.extension
template_values = {
"name": escape(dataset.name),
"ext": to_ext,
"hid": dataset.hid,
}
if not filename_pattern:
if hdca is None:
filename_pattern = DOWNLOAD_FILENAME_PATTERN_DATASET
else:
filename_pattern = DOWNLOAD_FILENAME_PATTERN_COLLECTION_ELEMENT
if hdca is not None:
# Use collection context to build up filename.
template_values["element_identifier"] = element_identifier
template_values["hdca_name"] = escape(hdca.name)
template_values["hdca_hid"] = hdca.hid
return string.Template(filename_pattern).substitute(**template_values)
def display_name(self, dataset):
"""Returns formatted html of dataset name"""
try:
return escape(unicodify(dataset.name, 'utf-8'))
except Exception:
return "name unavailable"
def display_info(self, dataset):
"""Returns formatted html of dataset info"""
try:
# Change new line chars to html
info: str = escape(dataset.info)
if info.find('\r\n') >= 0:
info = info.replace('\r\n', '<br/>')
if info.find('\r') >= 0:
info = info.replace('\r', '<br/>')
if info.find('\n') >= 0:
info = info.replace('\n', '<br/>')
info = unicodify(info, 'utf-8')
return info
except Exception:
return "info unavailable"
def repair_methods(self, dataset):
"""Unimplemented method, returns dict with method/option for repairing errors"""
return None
def get_mime(self):
"""Returns the mime type of the datatype"""
return 'application/octet-stream'
def add_display_app(self, app_id, label, file_function, links_function):
"""
Adds a display app to the datatype.
app_id is a unique id
label is the primary display label, e.g., display at 'UCSC'
file_function is a string containing the name of the function that returns a properly formatted display
links_function is a string containing the name of the function that returns a list of (link_name,link)
"""
self.supported_display_apps = self.supported_display_apps.copy()
self.supported_display_apps[app_id] = {'label': label, 'file_function': file_function, 'links_function': links_function}
def remove_display_app(self, app_id):
"""Removes a display app from the datatype"""
self.supported_display_apps = self.supported_display_apps.copy()
try:
del self.supported_display_apps[app_id]
except Exception:
log.exception('Tried to remove display app %s from datatype %s, but this display app is not declared.', type, self.__class__.__name__)
def clear_display_apps(self):
self.supported_display_apps = {}
def add_display_application(self, display_application):
"""New style display applications"""
assert display_application.id not in self.display_applications, 'Attempted to add a display application twice'
self.display_applications[display_application.id] = display_application
def get_display_application(self, key, default=None):
return self.display_applications.get(key, default)
def get_display_applications_by_dataset(self, dataset, trans):
rval = {}
for key, value in self.display_applications.items():
value = value.filter_by_dataset(dataset, trans)
if value.links:
rval[key] = value
return rval
def get_display_types(self):
"""Returns display types available"""
return list(self.supported_display_apps.keys())
def get_display_label(self, type):
"""Returns primary label for display app"""
try:
return self.supported_display_apps[type]['label']
except Exception:
return 'unknown'
def as_display_type(self, dataset, type, **kwd):
"""Returns modified file contents for a particular display type """
try:
if type in self.get_display_types():
return getattr(self, self.supported_display_apps[type]['file_function'])(dataset, **kwd)
except Exception:
log.exception('Function %s is referred to in datatype %s for displaying as type %s, but is not accessible', self.supported_display_apps[type]['file_function'], self.__class__.__name__, type)
return f"This display type ({type}) is not implemented for this datatype ({dataset.ext})."
def get_display_links(self, dataset, type, app, base_url, target_frame='_blank', **kwd):
"""
Returns a list of tuples of (name, link) for a particular display type. No check on
'access' permissions is done here - if you can view the dataset, you can also save it
or send it to a destination outside of Galaxy, so Galaxy security restrictions do not
apply anyway.
"""
try:
if app.config.enable_old_display_applications and type in self.get_display_types():
return target_frame, getattr(self, self.supported_display_apps[type]['links_function'])(dataset, type, app, base_url, **kwd)
except Exception:
log.exception('Function %s is referred to in datatype %s for generating links for type %s, but is not accessible',
self.supported_display_apps[type]['links_function'], self.__class__.__name__, type)
return target_frame, []
def get_converter_types(self, original_dataset, datatypes_registry):
"""Returns available converters by type for this dataset"""
return datatypes_registry.get_converters_by_datatype(original_dataset.ext)
def find_conversion_destination(
self, dataset, accepted_formats: List[str], datatypes_registry, **kwd
) -> Tuple[bool, Optional[str], Optional["DatasetInstance"]]:
"""Returns ( direct_match, converted_ext, existing converted dataset )"""
return datatypes_registry.find_conversion_destination_for_dataset_by_extensions(dataset, accepted_formats, **kwd)
def convert_dataset(self, trans, original_dataset, target_type, return_output=False, visible=True, deps=None, target_context=None, history=None):
"""This function adds a job to the queue to convert a dataset to another type. Returns a message about success/failure."""
converter = trans.app.datatypes_registry.get_converter_by_target_type(original_dataset.ext, target_type)
if converter is None:
raise DatatypeConverterNotFoundException(f"A converter does not exist for {original_dataset.ext} to {target_type}.")
params, input_name = get_params_and_input_name(converter, deps, target_context)
params[input_name] = original_dataset
# Make the target datatype available to the converter
params['__target_datatype__'] = target_type
# Run converter, job is dispatched through Queue
job, converted_datasets, *_ = converter.execute(trans, incoming=params, set_output_hid=visible, history=history)
trans.app.job_manager.enqueue(job, tool=converter)
if len(params) > 0:
trans.log_event(f"Converter params: {str(params)}", tool_id=converter.id)
if not visible:
for value in converted_datasets.values():
value.visible = False
if return_output:
return converted_datasets
return f"The file conversion of {converter.name} on data {original_dataset.hid} has been added to the Queue."
# We need to clear associated files before we set metadata
# so that as soon as metadata starts to be set, e.g. implicitly converted datasets are deleted and no longer available 'while' metadata is being set, not just after
# We'll also clear after setting metadata, for backwards compatibility
def after_setting_metadata(self, dataset):
"""This function is called on the dataset after metadata is set."""
dataset.clear_associated_files(metadata_safe=True)
def before_setting_metadata(self, dataset):
"""This function is called on the dataset before metadata is set."""
dataset.clear_associated_files(metadata_safe=True)
def __new_composite_file(self, name, optional=False, mimetype=None, description=None, substitute_name_with_metadata=None, is_binary=False, to_posix_lines=True, space_to_tab=False, **kwds):
kwds['name'] = name
kwds['optional'] = optional
kwds['mimetype'] = mimetype
kwds['description'] = description
kwds['substitute_name_with_metadata'] = substitute_name_with_metadata
kwds['is_binary'] = is_binary
kwds['to_posix_lines'] = to_posix_lines
kwds['space_to_tab'] = space_to_tab
return Bunch(**kwds)
def add_composite_file(self, name, **kwds):
# self.composite_files = self.composite_files.copy()
self.composite_files[name] = self.__new_composite_file(name, **kwds)
def __substitute_composite_key(self, key, composite_file, dataset=None):
if composite_file.substitute_name_with_metadata:
if dataset:
meta_value = str(dataset.metadata.get(composite_file.substitute_name_with_metadata))
else:
meta_value = self.spec[composite_file.substitute_name_with_metadata].default # type: ignore
return key % meta_value
return key
@property
def writable_files(self):
files = {}
if self.composite_type != 'auto_primary_file':
files[self.primary_file_name] = self.__new_composite_file(self.primary_file_name)
for key, value in self.get_composite_files().items():
files[key] = value
return files
def get_composite_files(self, dataset=None):
def substitute_composite_key(key, composite_file):
if composite_file.substitute_name_with_metadata:
if dataset:
meta_value = str(dataset.metadata.get(composite_file.substitute_name_with_metadata))
else:
meta_value = self.metadata_spec[composite_file.substitute_name_with_metadata].default
return key % meta_value
return key
files = {}
for key, value in self.composite_files.items():
files[substitute_composite_key(key, value)] = value
return files
def generate_primary_file(self, dataset=None):
raise Exception("generate_primary_file is not implemented for this datatype.")
@property
def has_resolution(self):
return False
def matches_any(self, target_datatypes: List[Any]) -> bool:
"""
Check if this datatype is of any of the target_datatypes or is
a subtype thereof.
"""
datatype_classes = tuple(datatype if isclass(datatype) else datatype.__class__ for datatype in target_datatypes)
return isinstance(self, datatype_classes)
@staticmethod
def merge(split_files, output_file):
"""
Merge files with copy.copyfileobj() will not hit the
max argument limitation of cat. gz and bz2 files are also working.
"""
if not split_files:
raise ValueError(f'Asked to merge zero files as {output_file}')
elif len(split_files) == 1:
shutil.copyfileobj(open(split_files[0], 'rb'), open(output_file, 'wb'))
else:
with open(output_file, 'wb') as fdst:
for fsrc in split_files:
shutil.copyfileobj(open(fsrc, 'rb'), fdst)
def get_visualizations(self, dataset):
"""
Returns a list of visualizations for datatype.
"""
if self.track_type:
return ['trackster', 'circster']
return []
# ------------- Dataproviders
def has_dataprovider(self, data_format):
"""
Returns True if `data_format` is available in `dataproviders`.
"""
return data_format in self.dataproviders
def dataprovider(self, dataset, data_format, **settings):
"""
Base dataprovider factory for all datatypes that returns the proper provider
for the given `data_format` or raises a `NoProviderAvailable`.
"""
if self.has_dataprovider(data_format):
return self.dataproviders[data_format](self, dataset, **settings)
raise p_dataproviders.exceptions.NoProviderAvailable(self, data_format)
def validate(self, dataset, **kwd):
return DatatypeValidation.unvalidated()
@p_dataproviders.decorators.dataprovider_factory("base")
def base_dataprovider(self, dataset, **settings):
dataset_source = p_dataproviders.dataset.DatasetDataProvider(dataset)
return p_dataproviders.base.DataProvider(dataset_source, **settings)
@p_dataproviders.decorators.dataprovider_factory(
"chunk", p_dataproviders.chunk.ChunkDataProvider.settings
)
def chunk_dataprovider(self, dataset, **settings):
dataset_source = p_dataproviders.dataset.DatasetDataProvider(dataset)
return p_dataproviders.chunk.ChunkDataProvider(dataset_source, **settings)
@p_dataproviders.decorators.dataprovider_factory(
"chunk64", p_dataproviders.chunk.Base64ChunkDataProvider.settings
)
def chunk64_dataprovider(self, dataset, **settings):
dataset_source = p_dataproviders.dataset.DatasetDataProvider(dataset)
return p_dataproviders.chunk.Base64ChunkDataProvider(dataset_source, **settings)
def _clean_and_set_mime_type(self, trans, mime, headers: Headers):
if mime.lower() in XSS_VULNERABLE_MIME_TYPES:
if not getattr(trans.app.config, "serve_xss_vulnerable_mimetypes", True):
mime = DEFAULT_MIME_TYPE
headers["content-type"] = mime
def handle_dataset_as_image(self, hda) -> str:
raise Exception("Unimplemented Method")
@p_dataproviders.decorators.has_dataproviders
class Text(Data):
edam_format = "format_2330"
file_ext = 'txt'
line_class = 'line'
is_binary = False
# Add metadata elements
MetadataElement(name="data_lines", default=0, desc="Number of data lines", readonly=True, optional=True, visible=False, no_value=0)
def get_mime(self):
"""Returns the mime type of the datatype"""
return 'text/plain'
def set_meta(self, dataset, **kwd):
"""
Set the number of lines of data in dataset.
"""
dataset.metadata.data_lines = self.count_data_lines(dataset)
def estimate_file_lines(self, dataset):
"""
Perform a rough estimate by extrapolating number of lines from a small read.
"""
sample_size = 1048576
try:
with compression_utils.get_fileobj(dataset.file_name) as dataset_fh:
dataset_read = dataset_fh.read(sample_size)
sample_lines = dataset_read.count('\n')
return int(sample_lines * (float(dataset.get_size()) / float(sample_size)))
except UnicodeDecodeError:
log.error(f'Unable to estimate lines in file {dataset.file_name}')
return None
def count_data_lines(self, dataset):
"""
Count the number of lines of data in dataset,
skipping all blank lines and comments.
"""
CHUNK_SIZE = 2 ** 15 # 32Kb
data_lines = 0
with compression_utils.get_fileobj(dataset.file_name) as in_file:
# FIXME: Potential encoding issue can prevent the ability to iterate over lines
# causing set_meta process to fail otherwise OK jobs. A better solution than
# a silent try/except is desirable.
try:
for line in iter_start_of_line(in_file, CHUNK_SIZE):
line = line.strip()
if line and not line.startswith('#'):
data_lines += 1
except UnicodeDecodeError:
log.error(f'Unable to count lines in file {dataset.file_name}')
return None
return data_lines
def set_peek(self, dataset, line_count=None, WIDTH=256, skipchars=None, line_wrap=True, **kwd):
"""
Set the peek. This method is used by various subclasses of Text.
"""
if not dataset.dataset.purged:
# The file must exist on disk for the get_file_peek() method
dataset.peek = get_file_peek(dataset.file_name, WIDTH=WIDTH, skipchars=skipchars, line_wrap=line_wrap)
if line_count is None:
# See if line_count is stored in the metadata
if dataset.metadata.data_lines:
dataset.blurb = f"{util.commaify(str(dataset.metadata.data_lines))} {inflector.cond_plural(dataset.metadata.data_lines, self.line_class)}"
else:
# Number of lines is not known ( this should not happen ), and auto-detect is
# needed to set metadata
# This can happen when the file is larger than max_optional_metadata_filesize.
if int(dataset.get_size()) <= 1048576:
# Small dataset, recount all lines and reset peek afterward.
lc = self.count_data_lines(dataset)
if lc is not None:
dataset.metadata.data_lines = lc
dataset.blurb = f"{util.commaify(str(lc))} {inflector.cond_plural(lc, self.line_class)}"
else:
dataset.blurb = "Error: Cannot count lines in dataset"
else:
est_lines = self.estimate_file_lines(dataset)
if est_lines is not None:
dataset.blurb = f"~{util.commaify(util.roundify(str(est_lines)))} {inflector.cond_plural(est_lines, self.line_class)}"
else:
dataset.blurb = "Error: Cannot estimate lines in dataset"
else:
dataset.blurb = f"{util.commaify(str(line_count))} {inflector.cond_plural(line_count, self.line_class)}"
else:
dataset.peek = 'file does not exist'
dataset.blurb = 'file purged from disk'
@classmethod
def split(cls, input_datasets, subdir_generator_function, split_params):
"""
Split the input files by line.
"""
if split_params is None:
return
if len(input_datasets) > 1:
raise Exception("Text file splitting does not support multiple files")
input_files = [ds.file_name for ds in input_datasets]
lines_per_file = None
chunk_size = None
if split_params['split_mode'] == 'number_of_parts':
lines_per_file = []
# Computing the length is expensive!
def _file_len(fname):
with open(fname) as f:
return sum(1 for _ in f)
length = _file_len(input_files[0])
parts = int(split_params['split_size'])
if length < parts:
parts = length
len_each, remainder = divmod(length, parts)
while length > 0:
chunk = len_each
if remainder > 0:
chunk += 1
lines_per_file.append(chunk)
remainder -= 1
length -= chunk
elif split_params['split_mode'] == 'to_size':
chunk_size = int(split_params['split_size'])
else:
raise Exception(f"Unsupported split mode {split_params["split_mode"]}")
f = open(input_files[0])
try:
chunk_idx = 0
file_done = False
part_file = None
while not file_done:
if lines_per_file is None:
this_chunk_size = chunk_size
elif chunk_idx < len(lines_per_file):
this_chunk_size = lines_per_file[chunk_idx]
chunk_idx += 1
lines_remaining = this_chunk_size
part_file = None
while lines_remaining > 0:
a_line = f.readline()
if a_line == '':
file_done = True
break
if part_file is None:
part_dir = subdir_generator_function()
part_path = os.path.join(part_dir, os.path.basename(input_files[0]))
part_file = open(part_path, 'w')
part_file.write(a_line)
lines_remaining -= 1
except Exception as e:
log.error('Unable to split files: %s', unicodify(e))
raise
finally:
f.close()
if part_file:
part_file.close()
# ------------- Dataproviders
@p_dataproviders.decorators.dataprovider_factory(
"line", p_dataproviders.line.FilteredLineDataProvider.settings
)
def line_dataprovider(self, dataset, **settings):
"""
Returns an iterator over the dataset's lines (that have been stripped)
optionally excluding blank lines and lines that start with a comment character.
"""
dataset_source = p_dataproviders.dataset.DatasetDataProvider(dataset)
return p_dataproviders.line.FilteredLineDataProvider(dataset_source, **settings)
@p_dataproviders.decorators.dataprovider_factory(
"regex-line", p_dataproviders.line.RegexLineDataProvider.settings
)
def regex_line_dataprovider(self, dataset, **settings):
"""
Returns an iterator over the dataset's lines
optionally including/excluding lines that match one or more regex filters.
"""
dataset_source = p_dataproviders.dataset.DatasetDataProvider(dataset)
return p_dataproviders.line.RegexLineDataProvider(dataset_source, **settings)
class Directory(Data):
"""Class representing a directory of files."""
class GenericAsn1(Text):
"""Class for generic ASN.1 text format"""
edam_data = "data_0849"
edam_format = "format_1966"
file_ext = 'asn1'
class LineCount(Text):
"""
Dataset contains a single line with a single integer that denotes the
line count for a related dataset. Used for custom builds.
"""
class Newick(Text):
"""New Hampshire/Newick Format"""
edam_data = "data_0872"
edam_format = "format_1910"
file_ext = "newick"
def sniff(self, filename):
""" Returning false as the newick format is too general and cannot be sniffed."""
return False
def get_visualizations(self, dataset):
"""
Returns a list of visualizations for datatype.
"""
return ['phyloviz']
@build_sniff_from_prefix
class Nexus(Text):
"""Nexus format as used By Paup, Mr Bayes, etc"""
edam_data = "data_0872"
edam_format = "format_1912"
file_ext = "nex"
def sniff_prefix(self, file_prefix: FilePrefix):
"""All Nexus Files Simply puts a '#NEXUS' in its first line"""
return file_prefix.string_io().read(6).upper() == "#NEXUS"
def get_visualizations(self, dataset):
"""
Returns a list of visualizations for datatype.
"""
return ['phyloviz']
# ------------- Utility methods --------------
# nice_size used to be here, but to resolve cyclical dependencies it's been
# moved to galaxy.util. It belongs there anyway since it's used outside
# datatypes.
nice_size = util.nice_size
def get_test_fname(fname):
"""Returns test data filename"""
path = os.path.dirname(__file__)
full_path = os.path.join(path, 'test', fname)
return full_path
def get_file_peek(file_name, WIDTH=256, LINE_COUNT=5, skipchars=None, line_wrap=True):
"""
Returns the first LINE_COUNT lines wrapped to WIDTH.
>>> def assert_peek_is(file_name, expected, *args, **kwd):
... path = get_test_fname(file_name)
... peek = get_file_peek(path, *args, **kwd)
... assert peek == expected, "%s != %s" % (peek, expected)
>>> assert_peek_is('0_nonewline', u'0')
>>> assert_peek_is('0.txt', u'0\\n')
>>> assert_peek_is('4.bed', u'chr22\\t30128507\\t31828507\\tuc003bnx.1_cds_2_0_chr22_29227_f\\t0\\t+\\n', LINE_COUNT=1)
>>> assert_peek_is('1.bed', u'chr1\\t147962192\\t147962580\\tCCDS989.1_cds_0_0_chr1_147962193_r\\t0\\t-\\nchr1\\t147984545\\t147984630\\tCCDS990.1_cds_0_0_chr1_147984546_f\\t0\\t+\\n', LINE_COUNT=2)
"""
# Set size for file.readline() to a negative number to force it to
# read until either a newline or EOF. Needed for datasets with very
# long lines.
if WIDTH == 'unlimited':
WIDTH = -1
if skipchars is None:
skipchars = []
lines = []
count = 0
last_line_break = False
with compression_utils.get_fileobj(file_name) as temp:
while count < LINE_COUNT:
try:
line = temp.readline(WIDTH)
except UnicodeDecodeError:
return "binary file"
if line == "":
break
last_line_break = False
if line.endswith('\n'):
line = line[:-1]
last_line_break = True
elif not line_wrap:
for i in file_reader(temp, 1):
if i == '\n':
last_line_break = True
if not i or i == '\n':
break
skip_line = False
for skipchar in skipchars:
if line.startswith(skipchar):
skip_line = True
break
if not skip_line:
lines.append(line)
count += 1
return '\n'.join(lines) + ('\n' if last_line_break else '')
| import abc
import logging
import mimetypes
import os
import shutil
import string
import tempfile
from inspect import isclass
from typing import (
Any,
Dict,
List,
Optional,
Tuple,
TYPE_CHECKING,
)
from markupsafe import escape
from galaxy import util
from galaxy.datatypes.metadata import (
MetadataElement, # import directly to maintain ease of use in Datatype class definitions
)
from galaxy.datatypes.sniff import (
build_sniff_from_prefix,
FilePrefix,
)
from galaxy.exceptions import ObjectNotFound
from galaxy.util import (
compression_utils,
file_reader,
FILENAME_VALID_CHARS,
inflector,
iter_start_of_line,
smart_str,
unicodify,
)
from galaxy.util.bunch import Bunch
from galaxy.util.sanitize_html import sanitize_html
from galaxy.util.zipstream import ZipstreamWrapper
from . import dataproviders as p_dataproviders
from . import metadata
if TYPE_CHECKING:
from galaxy.model import DatasetInstance
XSS_VULNERABLE_MIME_TYPES = [
'image/svg+xml', # Unfiltered by Galaxy and may contain JS that would be executed by some browsers.
'application/xml', # Some browsers will evalute SVG embedded JS in such XML documents.
]
DEFAULT_MIME_TYPE = 'text/plain' # Vulnerable mime types will be replaced with this.
log = logging.getLogger(__name__)
# Valid first column and strand column values vor bed, other formats
col1_startswith = ['chr', 'chl', 'groupun', 'reftig_', 'scaffold', 'super_', 'vcho']
valid_strand = ['+', '-', '.']
DOWNLOAD_FILENAME_PATTERN_DATASET = "Galaxy${hid}-[${name}].${ext}"
DOWNLOAD_FILENAME_PATTERN_COLLECTION_ELEMENT = "Galaxy${hdca_hid}-[${hdca_name}__${element_identifier}].${ext}"
DEFAULT_MAX_PEEK_SIZE = 1000000 # 1 MB
Headers = Dict[str, Any]
class DatatypeConverterNotFoundException(Exception):
pass
class DatatypeValidation:
def __init__(self, state, message):
self.state = state
self.message = message
@staticmethod
def validated():
return DatatypeValidation("ok", "Dataset validated by datatype validator.")
@staticmethod
def invalid(message):
return DatatypeValidation("invalid", message)
@staticmethod
def unvalidated():
return DatatypeValidation("unknown", "Dataset validation unimplemented for this datatype.")
def __repr__(self):
return f"DatatypeValidation[state={self.state},message={self.message}]"
def validate(dataset_instance):
try:
datatype_validation = dataset_instance.datatype.validate(dataset_instance)
except Exception as e:
datatype_validation = DatatypeValidation.invalid(f"Problem running datatype validation method [{str(e)}]")
return datatype_validation
def get_params_and_input_name(converter, deps, target_context=None):
# Generate parameter dictionary
params = {}
# determine input parameter name and add to params
input_name = 'input1'
for key, value in converter.inputs.items():
if deps and value.name in deps:
params[value.name] = deps[value.name]
elif value.type == 'data':
input_name = key
# add potentially required/common internal tool parameters e.g. '__job_resource'
if target_context:
for key, value in target_context.items():
if key.startswith('__'):
params[key] = value
return params, input_name
class DataMeta(abc.ABCMeta):
"""
Metaclass for Data class. Sets up metadata spec.
"""
def __init__(cls, name, bases, dict_):
cls.metadata_spec = metadata.MetadataSpecCollection()
for base in bases: # loop through bases (class/types) of cls
if hasattr(base, "metadata_spec"): # base of class Data (object) has no metadata
cls.metadata_spec.update(base.metadata_spec) # add contents of metadata spec of base class to cls
metadata.Statement.process(cls)
@p_dataproviders.decorators.has_dataproviders
class Data(metaclass=DataMeta):
"""
Base class for all datatypes. Implements basic interfaces as well
as class methods for metadata.
>>> class DataTest( Data ):
... MetadataElement( name="test" )
...
>>> DataTest.metadata_spec.test.name
'test'
>>> DataTest.metadata_spec.test.desc
'test'
>>> type( DataTest.metadata_spec.test.param )
<class 'galaxy.model.metadata.MetadataParameter'>
"""
edam_data = "data_0006"
edam_format = "format_1915"
file_ext = 'data'
# Data is not chunkable by default.
CHUNKABLE = False
#: Dictionary of metadata fields for this datatype
metadata_spec: metadata.MetadataSpecCollection
# Add metadata elements
MetadataElement(name="dbkey", desc="Database/Build", default="?", param=metadata.DBKeyParameter, multiple=False, no_value="?")
# Stores the set of display applications, and viewing methods, supported by this datatype
supported_display_apps: Dict[str, Any] = {}
# If False, the peek is regenerated whenever a dataset of this type is copied
copy_safe_peek = True
# The dataset contains binary data --> do not space_to_tab or convert newlines, etc.
# Allow binary file uploads of this type when True.
is_binary = True
# Composite datatypes
composite_type: Optional[str] = None
composite_files: Dict[str, Any] = {}
primary_file_name = 'index'
# Allow user to change between this datatype and others. If left to None,
# datatype change is allowed if the datatype is not composite.
allow_datatype_change: Optional[bool] = None
# A per datatype setting (inherited): max file size (in bytes) for setting optional metadata
_max_optional_metadata_filesize = None
# Trackster track type.
track_type: Optional[str] = None
# Data sources.
data_sources: Dict[str, str] = {}
dataproviders: Dict[str, Any]
def __init__(self, **kwd):
"""Initialize the datatype"""
self.supported_display_apps = self.supported_display_apps.copy()
self.composite_files = self.composite_files.copy()
self.display_applications = {}
@classmethod
def is_datatype_change_allowed(cls):
"""
Returns the value of the `allow_datatype_change` class attribute if set
in a subclass, or True iff the datatype is not composite.
"""
if cls.allow_datatype_change is not None:
return cls.allow_datatype_change
return cls.composite_type is None
def get_raw_data(self, dataset):
"""Returns the full data. To stream it open the file_name and read/write as needed"""
try:
return open(dataset.file_name, 'rb').read(-1)
except OSError:
log.exception('%s reading a file that does not exist %s', self.__class__.__name__, dataset.file_name)
return ''
def dataset_content_needs_grooming(self, file_name):
"""This function is called on an output dataset file after the content is initially generated."""
return False
def groom_dataset_content(self, file_name):
"""This function is called on an output dataset file if dataset_content_needs_grooming returns True."""
def init_meta(self, dataset, copy_from=None):
# Metadata should be left mostly uninitialized. Dataset will
# handle returning default values when metadata is not set.
# copy_from allows metadata to be passed in that will be
# copied. (although this seems ambiguous, see
# Dataset.set_metadata. It always copies the rhs in order to
# flag the object as modified for SQLAlchemy.
if copy_from:
dataset.metadata = copy_from.metadata
def set_meta(self, dataset: Any, overwrite=True, **kwd):
"""Unimplemented method, allows guessing of metadata from contents of file"""
return True
def missing_meta(self, dataset, check=None, skip=None):
"""
Checks for empty metadata values, Returns True if non-optional metadata is missing
Specifying a list of 'check' values will only check those names provided; when used, optionality is ignored
Specifying a list of 'skip' items will return True even when a named metadata value is missing
"""
if skip is None:
skip = []
if check:
to_check = ((to_check, dataset.metadata.get(to_check)) for to_check in check)
else:
to_check = dataset.metadata.items()
for key, value in to_check:
if key in skip or (not check and dataset.metadata.spec[key].get("optional")):
continue # we skip check for optional and nonrequested values here
if not value:
return True
return False
def set_max_optional_metadata_filesize(self, max_value):
try:
max_value = int(max_value)
except (TypeError, ValueError):
return
self.__class__._max_optional_metadata_filesize = max_value
def get_max_optional_metadata_filesize(self):
rval = self.__class__._max_optional_metadata_filesize
if rval is None:
return -1
return rval
max_optional_metadata_filesize = property(get_max_optional_metadata_filesize, set_max_optional_metadata_filesize)
def set_peek(self, dataset):
"""
Set the peek and blurb text
"""
if not dataset.dataset.purged:
dataset.peek = ''
dataset.blurb = 'data'
else:
dataset.peek = 'file does not exist'
dataset.blurb = 'file purged from disk'
def display_peek(self, dataset):
"""Create HTML table, used for displaying peek"""
out = ['<table cellspacing="0" cellpadding="3">']
try:
if not dataset.peek:
dataset.set_peek()
data = dataset.peek
lines = data.splitlines()
for line in lines:
line = line.strip()
if not line:
continue
out.append(f"<tr><td>{escape(unicodify(line, 'utf-8'))}</td></tr>")
out.append('</table>')
return "".join(out)
except Exception as exc:
return f"Can't create peek: {unicodify(exc)}"
def _archive_main_file(self, archive, display_name, data_filename):
"""Called from _archive_composite_dataset to add central file to archive.
Unless subclassed, this will add the main dataset file (argument data_filename)
to the archive, as an HTML file with its filename derived from the dataset name
(argument outfname).
Returns a tuple of boolean, string, string: (error, msg, messagetype)
"""
error, msg, messagetype = False, "", ""
archname = f'{display_name}.html' # fake the real nature of the html file
try:
archive.write(data_filename, archname)
except OSError:
error = True
log.exception("Unable to add composite parent %s to temporary library download archive", data_filename)
msg = "Unable to create archive for download, please report this error"
messagetype = "error"
return error, msg, messagetype
def _archive_composite_dataset(self, trans, data, headers: Headers, do_action='zip'):
# save a composite object into a compressed archive for downloading
outfname = data.name[0:150]
outfname = ''.join(c in FILENAME_VALID_CHARS and c or '_' for c in outfname)
archive = ZipstreamWrapper(
archive_name=outfname,
upstream_mod_zip=trans.app.config.upstream_mod_zip,
upstream_gzip=trans.app.config.upstream_gzip
)
error = False
msg = ''
ext = data.extension
path = data.file_name
efp = data.extra_files_path
# Add any central file to the archive,
display_name = os.path.splitext(outfname)[0]
if not display_name.endswith(ext):
display_name = f'{display_name}_{ext}'
error, msg = self._archive_main_file(archive, display_name, path)[:2]
if not error:
# Add any child files to the archive,
for fpath, rpath in self.__archive_extra_files_path(extra_files_path=efp):
try:
archive.write(fpath, rpath)
except OSError:
error = True
log.exception("Unable to add %s to temporary library download archive", rpath)
msg = "Unable to create archive for download, please report this error"
continue
if not error:
headers.update(archive.get_headers())
return archive.response(), headers
return trans.show_error_message(msg), headers
def __archive_extra_files_path(self, extra_files_path):
"""Yield filepaths and relative filepaths for files in extra_files_path"""
for root, _, files in os.walk(extra_files_path):
for fname in files:
fpath = os.path.join(root, fname)
rpath = os.path.relpath(fpath, extra_files_path)
yield fpath, rpath
def _serve_raw(self, dataset, to_ext, headers: Headers, **kwd):
headers['Content-Length'] = str(os.stat(dataset.file_name).st_size)
headers["content-type"] = "application/octet-stream" # force octet-stream so Safari doesn't append mime extensions to filename
filename = self._download_filename(dataset, to_ext, hdca=kwd.get("hdca"), element_identifier=kwd.get("element_identifier"), filename_pattern=kwd.get("filename_pattern"))
headers["Content-Disposition"] = f'attachment; filename="{filename}"'
return open(dataset.file_name, mode='rb'), headers
def to_archive(self, dataset, name=""):
"""
Collect archive paths and file handles that need to be exported when archiving `dataset`.
:param dataset: HistoryDatasetAssociation
:param name: archive name, in collection context corresponds to collection name(s) and element_identifier,
joined by '/', e.g 'fastq_collection/sample1/forward'
"""
rel_paths = []
file_paths = []
if dataset.datatype.composite_type or dataset.extension == 'html':
main_file = f"{name}.html"
rel_paths.append(main_file)
file_paths.append(dataset.file_name)
for fpath, rpath in self.__archive_extra_files_path(dataset.extra_files_path):
rel_paths.append(os.path.join(name, rpath))
file_paths.append(fpath)
else:
rel_paths.append(f"{name or dataset.file_name}.{dataset.extension}")
file_paths.append(dataset.file_name)
return zip(file_paths, rel_paths)
def display_data(self, trans, data, preview=False, filename=None, to_ext=None, **kwd):
"""
Displays data in central pane if preview is `True`, else handles download.
Datatypes should be very careful if overridding this method and this interface
between datatypes and Galaxy will likely change.
TOOD: Document alternatives to overridding this method (data
providers?).
"""
headers = kwd.get("headers", {})
# Relocate all composite datatype display to a common location.
composite_extensions = trans.app.datatypes_registry.get_composite_extensions()
composite_extensions.append('html') # for archiving composite datatypes
# Prevent IE8 from sniffing content type since we're explicit about it. This prevents intentionally text/plain
# content from being rendered in the browser
headers['X-Content-Type-Options'] = 'nosniff'
if isinstance(data, str):
return smart_str(data), headers
if filename and filename != "index":
# For files in extra_files_path
extra_dir = data.dataset.extra_files_path_name
file_path = trans.app.object_store.get_filename(data.dataset, extra_dir=extra_dir, alt_name=filename)
if os.path.exists(file_path):
if os.path.isdir(file_path):
with tempfile.NamedTemporaryFile(mode='w', delete=False, dir=trans.app.config.new_file_path, prefix='gx_html_autocreate_') as tmp_fh:
tmp_file_name = tmp_fh.name
dir_items = sorted(os.listdir(file_path))
base_path, item_name = os.path.split(file_path)
tmp_fh.write('<html><head><h3>Directory %s contents: %d items</h3></head>\n' % (escape(item_name), len(dir_items)))
tmp_fh.write('<body><p/><table cellpadding="2">\n')
for index, fname in enumerate(dir_items):
if index % 2 == 0:
bgcolor = '#D8D8D8'
else:
bgcolor = '#FFFFFF'
# Can't have an href link here because there is no route
# defined for files contained within multiple subdirectory
# levels of the primary dataset. Something like this is
# close, but not quite correct:
# href = url_for(controller='dataset', action='display',
# dataset_id=trans.security.encode_id(data.dataset.id),
# preview=preview, filename=fname, to_ext=to_ext)
tmp_fh.write(f'<tr bgcolor="{bgcolor}"><td>{escape(fname)}</td></tr>\n')
tmp_fh.write('</table></body></html>\n')
return self._yield_user_file_content(trans, data, tmp_file_name, headers), headers
mime = mimetypes.guess_type(file_path)[0]
if not mime:
try:
mime = trans.app.datatypes_registry.get_mimetype_by_extension(".".split(file_path)[-1])
except Exception:
mime = "text/plain"
self._clean_and_set_mime_type(trans, mime, headers)
return self._yield_user_file_content(trans, data, file_path, headers), headers
else:
raise ObjectNotFound(f"Could not find '{filename}' on the extra files path {file_path}.")
self._clean_and_set_mime_type(trans, data.get_mime(), headers)
trans.log_event(f"Display dataset id: {str(data.id)}")
from galaxy.datatypes import ( # DBTODO REMOVE THIS AT REFACTOR
binary,
images,
text,
)
if to_ext or isinstance(
data.datatype, binary.Binary
): # Saving the file, or binary file
if data.extension in composite_extensions:
return self._archive_composite_dataset(trans, data, headers, do_action=kwd.get('do_action', 'zip'))
else:
headers['Content-Length'] = str(os.stat(data.file_name).st_size)
filename = self._download_filename(data, to_ext, hdca=kwd.get("hdca"), element_identifier=kwd.get("element_identifier"), filename_pattern=kwd.get("filename_pattern"))
headers['content-type'] = "application/octet-stream" # force octet-stream so Safari doesn't append mime extensions to filename
headers["Content-Disposition"] = f'attachment; filename="{filename}"'
return open(data.file_name, 'rb'), headers
if not os.path.exists(data.file_name):
raise ObjectNotFound(f"File Not Found ({data.file_name}).")
max_peek_size = DEFAULT_MAX_PEEK_SIZE # 1 MB
if isinstance(data.datatype, text.Html):
max_peek_size = 10000000 # 10 MB for html
preview = util.string_as_bool(preview)
if (
not preview
or isinstance(data.datatype, images.Image)
or os.stat(data.file_name).st_size < max_peek_size
):
return self._yield_user_file_content(trans, data, data.file_name, headers), headers
else:
headers["content-type"] = "text/html"
return trans.fill_template_mako("/dataset/large_file.mako",
truncated_data=open(data.file_name, 'rb').read(max_peek_size),
data=data), headers
def display_as_markdown(self, dataset_instance, markdown_format_helpers):
"""Prepare for embedding dataset into a basic Markdown document.
This is a somewhat experimental interface and should not be implemented
on datatypes not tightly tied to a Galaxy version (e.g. datatypes in the
Tool Shed).
Speaking very losely - the datatype should should load a bounded amount
of data from the supplied dataset instance and prepare for embedding it
into Markdown. This should be relatively vanilla Markdown - the result of
this is bleached and it should not contain nested Galaxy Markdown
directives.
If the data cannot reasonably be displayed, just indicate this and do
not throw an exception.
"""
if self.file_ext in {'png', 'jpg'}:
return self.handle_dataset_as_image(dataset_instance)
if self.is_binary:
result = "*cannot display binary content*\n"
else:
with open(dataset_instance.file_name) as f:
contents = f.read(DEFAULT_MAX_PEEK_SIZE)
result = markdown_format_helpers.literal_via_fence(contents)
if len(contents) == DEFAULT_MAX_PEEK_SIZE:
result += markdown_format_helpers.indicate_data_truncated()
return result
def _yield_user_file_content(self, trans, from_dataset, filename, headers: Headers):
"""This method is responsible for sanitizing the HTML if needed."""
if trans.app.config.sanitize_all_html and headers.get("content-type", None) == "text/html":
# Sanitize anytime we respond with plain text/html content.
# Check to see if this dataset's parent job is allowlisted
# We cannot currently trust imported datasets for rendering.
if not from_dataset.creating_job.imported and from_dataset.creating_job.tool_id.startswith(tuple(trans.app.config.sanitize_allowlist)):
return open(filename, mode='rb')
# This is returning to the browser, it needs to be encoded.
# TODO Ideally this happens a layer higher, but this is a bad
# issue affecting many tools
with open(filename) as f:
return sanitize_html(f.read()).encode('utf-8')
return open(filename, mode='rb')
def _download_filename(self, dataset, to_ext, hdca=None, element_identifier=None, filename_pattern=None):
def escape(raw_identifier):
return ''.join(c in FILENAME_VALID_CHARS and c or '_' for c in raw_identifier)[0:150]
if not to_ext or to_ext == "data":
# If a client requests to_ext with the extension 'data', they are
# deferring to the server, set it based on datatype.
to_ext = dataset.extension
template_values = {
"name": escape(dataset.name),
"ext": to_ext,
"hid": dataset.hid,
}
if not filename_pattern:
if hdca is None:
filename_pattern = DOWNLOAD_FILENAME_PATTERN_DATASET
else:
filename_pattern = DOWNLOAD_FILENAME_PATTERN_COLLECTION_ELEMENT
if hdca is not None:
# Use collection context to build up filename.
template_values["element_identifier"] = element_identifier
template_values["hdca_name"] = escape(hdca.name)
template_values["hdca_hid"] = hdca.hid
return string.Template(filename_pattern).substitute(**template_values)
def display_name(self, dataset):
"""Returns formatted html of dataset name"""
try:
return escape(unicodify(dataset.name, 'utf-8'))
except Exception:
return "name unavailable"
def display_info(self, dataset):
"""Returns formatted html of dataset info"""
try:
# Change new line chars to html
info: str = escape(dataset.info)
if info.find('\r\n') >= 0:
info = info.replace('\r\n', '<br/>')
if info.find('\r') >= 0:
info = info.replace('\r', '<br/>')
if info.find('\n') >= 0:
info = info.replace('\n', '<br/>')
info = unicodify(info, 'utf-8')
return info
except Exception:
return "info unavailable"
def repair_methods(self, dataset):
"""Unimplemented method, returns dict with method/option for repairing errors"""
return None
def get_mime(self):
"""Returns the mime type of the datatype"""
return 'application/octet-stream'
def add_display_app(self, app_id, label, file_function, links_function):
"""
Adds a display app to the datatype.
app_id is a unique id
label is the primary display label, e.g., display at 'UCSC'
file_function is a string containing the name of the function that returns a properly formatted display
links_function is a string containing the name of the function that returns a list of (link_name,link)
"""
self.supported_display_apps = self.supported_display_apps.copy()
self.supported_display_apps[app_id] = {'label': label, 'file_function': file_function, 'links_function': links_function}
def remove_display_app(self, app_id):
"""Removes a display app from the datatype"""
self.supported_display_apps = self.supported_display_apps.copy()
try:
del self.supported_display_apps[app_id]
except Exception:
log.exception('Tried to remove display app %s from datatype %s, but this display app is not declared.', type, self.__class__.__name__)
def clear_display_apps(self):
self.supported_display_apps = {}
def add_display_application(self, display_application):
"""New style display applications"""
assert display_application.id not in self.display_applications, 'Attempted to add a display application twice'
self.display_applications[display_application.id] = display_application
def get_display_application(self, key, default=None):
return self.display_applications.get(key, default)
def get_display_applications_by_dataset(self, dataset, trans):
rval = {}
for key, value in self.display_applications.items():
value = value.filter_by_dataset(dataset, trans)
if value.links:
rval[key] = value
return rval
def get_display_types(self):
"""Returns display types available"""
return list(self.supported_display_apps.keys())
def get_display_label(self, type):
"""Returns primary label for display app"""
try:
return self.supported_display_apps[type]['label']
except Exception:
return 'unknown'
def as_display_type(self, dataset, type, **kwd):
"""Returns modified file contents for a particular display type """
try:
if type in self.get_display_types():
return getattr(self, self.supported_display_apps[type]['file_function'])(dataset, **kwd)
except Exception:
log.exception('Function %s is referred to in datatype %s for displaying as type %s, but is not accessible', self.supported_display_apps[type]['file_function'], self.__class__.__name__, type)
return f"This display type ({type}) is not implemented for this datatype ({dataset.ext})."
def get_display_links(self, dataset, type, app, base_url, target_frame='_blank', **kwd):
"""
Returns a list of tuples of (name, link) for a particular display type. No check on
'access' permissions is done here - if you can view the dataset, you can also save it
or send it to a destination outside of Galaxy, so Galaxy security restrictions do not
apply anyway.
"""
try:
if app.config.enable_old_display_applications and type in self.get_display_types():
return target_frame, getattr(self, self.supported_display_apps[type]['links_function'])(dataset, type, app, base_url, **kwd)
except Exception:
log.exception('Function %s is referred to in datatype %s for generating links for type %s, but is not accessible',
self.supported_display_apps[type]['links_function'], self.__class__.__name__, type)
return target_frame, []
def get_converter_types(self, original_dataset, datatypes_registry):
"""Returns available converters by type for this dataset"""
return datatypes_registry.get_converters_by_datatype(original_dataset.ext)
def find_conversion_destination(
self, dataset, accepted_formats: List[str], datatypes_registry, **kwd
) -> Tuple[bool, Optional[str], Optional["DatasetInstance"]]:
"""Returns ( direct_match, converted_ext, existing converted dataset )"""
return datatypes_registry.find_conversion_destination_for_dataset_by_extensions(dataset, accepted_formats, **kwd)
def convert_dataset(self, trans, original_dataset, target_type, return_output=False, visible=True, deps=None, target_context=None, history=None):
"""This function adds a job to the queue to convert a dataset to another type. Returns a message about success/failure."""
converter = trans.app.datatypes_registry.get_converter_by_target_type(original_dataset.ext, target_type)
if converter is None:
raise DatatypeConverterNotFoundException(f"A converter does not exist for {original_dataset.ext} to {target_type}.")
params, input_name = get_params_and_input_name(converter, deps, target_context)
params[input_name] = original_dataset
# Make the target datatype available to the converter
params['__target_datatype__'] = target_type
# Run converter, job is dispatched through Queue
job, converted_datasets, *_ = converter.execute(trans, incoming=params, set_output_hid=visible, history=history)
trans.app.job_manager.enqueue(job, tool=converter)
if len(params) > 0:
trans.log_event(f"Converter params: {str(params)}", tool_id=converter.id)
if not visible:
for value in converted_datasets.values():
value.visible = False
if return_output:
return converted_datasets
return f"The file conversion of {converter.name} on data {original_dataset.hid} has been added to the Queue."
# We need to clear associated files before we set metadata
# so that as soon as metadata starts to be set, e.g. implicitly converted datasets are deleted and no longer available 'while' metadata is being set, not just after
# We'll also clear after setting metadata, for backwards compatibility
def after_setting_metadata(self, dataset):
"""This function is called on the dataset after metadata is set."""
dataset.clear_associated_files(metadata_safe=True)
def before_setting_metadata(self, dataset):
"""This function is called on the dataset before metadata is set."""
dataset.clear_associated_files(metadata_safe=True)
def __new_composite_file(self, name, optional=False, mimetype=None, description=None, substitute_name_with_metadata=None, is_binary=False, to_posix_lines=True, space_to_tab=False, **kwds):
kwds['name'] = name
kwds['optional'] = optional
kwds['mimetype'] = mimetype
kwds['description'] = description
kwds['substitute_name_with_metadata'] = substitute_name_with_metadata
kwds['is_binary'] = is_binary
kwds['to_posix_lines'] = to_posix_lines
kwds['space_to_tab'] = space_to_tab
return Bunch(**kwds)
def add_composite_file(self, name, **kwds):
# self.composite_files = self.composite_files.copy()
self.composite_files[name] = self.__new_composite_file(name, **kwds)
def __substitute_composite_key(self, key, composite_file, dataset=None):
if composite_file.substitute_name_with_metadata:
if dataset:
meta_value = str(dataset.metadata.get(composite_file.substitute_name_with_metadata))
else:
meta_value = self.spec[composite_file.substitute_name_with_metadata].default # type: ignore
return key % meta_value
return key
@property
def writable_files(self):
files = {}
if self.composite_type != 'auto_primary_file':
files[self.primary_file_name] = self.__new_composite_file(self.primary_file_name)
for key, value in self.get_composite_files().items():
files[key] = value
return files
def get_composite_files(self, dataset=None):
def substitute_composite_key(key, composite_file):
if composite_file.substitute_name_with_metadata:
if dataset:
meta_value = str(dataset.metadata.get(composite_file.substitute_name_with_metadata))
else:
meta_value = self.metadata_spec[composite_file.substitute_name_with_metadata].default
return key % meta_value
return key
files = {}
for key, value in self.composite_files.items():
files[substitute_composite_key(key, value)] = value
return files
def generate_primary_file(self, dataset=None):
raise Exception("generate_primary_file is not implemented for this datatype.")
@property
def has_resolution(self):
return False
def matches_any(self, target_datatypes: List[Any]) -> bool:
"""
Check if this datatype is of any of the target_datatypes or is
a subtype thereof.
"""
datatype_classes = tuple(datatype if isclass(datatype) else datatype.__class__ for datatype in target_datatypes)
return isinstance(self, datatype_classes)
@staticmethod
def merge(split_files, output_file):
"""
Merge files with copy.copyfileobj() will not hit the
max argument limitation of cat. gz and bz2 files are also working.
"""
if not split_files:
raise ValueError(f'Asked to merge zero files as {output_file}')
elif len(split_files) == 1:
shutil.copyfileobj(open(split_files[0], 'rb'), open(output_file, 'wb'))
else:
with open(output_file, 'wb') as fdst:
for fsrc in split_files:
shutil.copyfileobj(open(fsrc, 'rb'), fdst)
def get_visualizations(self, dataset):
"""
Returns a list of visualizations for datatype.
"""
if self.track_type:
return ['trackster', 'circster']
return []
# ------------- Dataproviders
def has_dataprovider(self, data_format):
"""
Returns True if `data_format` is available in `dataproviders`.
"""
return data_format in self.dataproviders
def dataprovider(self, dataset, data_format, **settings):
"""
Base dataprovider factory for all datatypes that returns the proper provider
for the given `data_format` or raises a `NoProviderAvailable`.
"""
if self.has_dataprovider(data_format):
return self.dataproviders[data_format](self, dataset, **settings)
raise p_dataproviders.exceptions.NoProviderAvailable(self, data_format)
def validate(self, dataset, **kwd):
return DatatypeValidation.unvalidated()
@p_dataproviders.decorators.dataprovider_factory("base")
def base_dataprovider(self, dataset, **settings):
dataset_source = p_dataproviders.dataset.DatasetDataProvider(dataset)
return p_dataproviders.base.DataProvider(dataset_source, **settings)
@p_dataproviders.decorators.dataprovider_factory(
"chunk", p_dataproviders.chunk.ChunkDataProvider.settings
)
def chunk_dataprovider(self, dataset, **settings):
dataset_source = p_dataproviders.dataset.DatasetDataProvider(dataset)
return p_dataproviders.chunk.ChunkDataProvider(dataset_source, **settings)
@p_dataproviders.decorators.dataprovider_factory(
"chunk64", p_dataproviders.chunk.Base64ChunkDataProvider.settings
)
def chunk64_dataprovider(self, dataset, **settings):
dataset_source = p_dataproviders.dataset.DatasetDataProvider(dataset)
return p_dataproviders.chunk.Base64ChunkDataProvider(dataset_source, **settings)
def _clean_and_set_mime_type(self, trans, mime, headers: Headers):
if mime.lower() in XSS_VULNERABLE_MIME_TYPES:
if not getattr(trans.app.config, "serve_xss_vulnerable_mimetypes", True):
mime = DEFAULT_MIME_TYPE
headers["content-type"] = mime
def handle_dataset_as_image(self, hda) -> str:
raise Exception("Unimplemented Method")
@p_dataproviders.decorators.has_dataproviders
class Text(Data):
edam_format = "format_2330"
file_ext = 'txt'
line_class = 'line'
is_binary = False
# Add metadata elements
MetadataElement(name="data_lines", default=0, desc="Number of data lines", readonly=True, optional=True, visible=False, no_value=0)
def get_mime(self):
"""Returns the mime type of the datatype"""
return 'text/plain'
def set_meta(self, dataset, **kwd):
"""
Set the number of lines of data in dataset.
"""
dataset.metadata.data_lines = self.count_data_lines(dataset)
def estimate_file_lines(self, dataset):
"""
Perform a rough estimate by extrapolating number of lines from a small read.
"""
sample_size = 1048576
try:
with compression_utils.get_fileobj(dataset.file_name) as dataset_fh:
dataset_read = dataset_fh.read(sample_size)
sample_lines = dataset_read.count('\n')
return int(sample_lines * (float(dataset.get_size()) / float(sample_size)))
except UnicodeDecodeError:
log.error(f'Unable to estimate lines in file {dataset.file_name}')
return None
def count_data_lines(self, dataset):
"""
Count the number of lines of data in dataset,
skipping all blank lines and comments.
"""
CHUNK_SIZE = 2 ** 15 # 32Kb
data_lines = 0
with compression_utils.get_fileobj(dataset.file_name) as in_file:
# FIXME: Potential encoding issue can prevent the ability to iterate over lines
# causing set_meta process to fail otherwise OK jobs. A better solution than
# a silent try/except is desirable.
try:
for line in iter_start_of_line(in_file, CHUNK_SIZE):
line = line.strip()
if line and not line.startswith('#'):
data_lines += 1
except UnicodeDecodeError:
log.error(f'Unable to count lines in file {dataset.file_name}')
return None
return data_lines
def set_peek(self, dataset, line_count=None, WIDTH=256, skipchars=None, line_wrap=True, **kwd):
"""
Set the peek. This method is used by various subclasses of Text.
"""
if not dataset.dataset.purged:
# The file must exist on disk for the get_file_peek() method
dataset.peek = get_file_peek(dataset.file_name, WIDTH=WIDTH, skipchars=skipchars, line_wrap=line_wrap)
if line_count is None:
# See if line_count is stored in the metadata
if dataset.metadata.data_lines:
dataset.blurb = f"{util.commaify(str(dataset.metadata.data_lines))} {inflector.cond_plural(dataset.metadata.data_lines, self.line_class)}"
else:
# Number of lines is not known ( this should not happen ), and auto-detect is
# needed to set metadata
# This can happen when the file is larger than max_optional_metadata_filesize.
if int(dataset.get_size()) <= 1048576:
# Small dataset, recount all lines and reset peek afterward.
lc = self.count_data_lines(dataset)
if lc is not None:
dataset.metadata.data_lines = lc
dataset.blurb = f"{util.commaify(str(lc))} {inflector.cond_plural(lc, self.line_class)}"
else:
dataset.blurb = "Error: Cannot count lines in dataset"
else:
est_lines = self.estimate_file_lines(dataset)
if est_lines is not None:
dataset.blurb = f"~{util.commaify(util.roundify(str(est_lines)))} {inflector.cond_plural(est_lines, self.line_class)}"
else:
dataset.blurb = "Error: Cannot estimate lines in dataset"
else:
dataset.blurb = f"{util.commaify(str(line_count))} {inflector.cond_plural(line_count, self.line_class)}"
else:
dataset.peek = 'file does not exist'
dataset.blurb = 'file purged from disk'
@classmethod
def split(cls, input_datasets, subdir_generator_function, split_params):
"""
Split the input files by line.
"""
if split_params is None:
return
if len(input_datasets) > 1:
raise Exception("Text file splitting does not support multiple files")
input_files = [ds.file_name for ds in input_datasets]
lines_per_file = None
chunk_size = None
if split_params['split_mode'] == 'number_of_parts':
lines_per_file = []
# Computing the length is expensive!
def _file_len(fname):
with open(fname) as f:
return sum(1 for _ in f)
length = _file_len(input_files[0])
parts = int(split_params['split_size'])
if length < parts:
parts = length
len_each, remainder = divmod(length, parts)
while length > 0:
chunk = len_each
if remainder > 0:
chunk += 1
lines_per_file.append(chunk)
remainder -= 1
length -= chunk
elif split_params['split_mode'] == 'to_size':
chunk_size = int(split_params['split_size'])
else:
raise Exception(f"Unsupported split mode {split_params['split_mode']}")
f = open(input_files[0])
try:
chunk_idx = 0
file_done = False
part_file = None
while not file_done:
if lines_per_file is None:
this_chunk_size = chunk_size
elif chunk_idx < len(lines_per_file):
this_chunk_size = lines_per_file[chunk_idx]
chunk_idx += 1
lines_remaining = this_chunk_size
part_file = None
while lines_remaining > 0:
a_line = f.readline()
if a_line == '':
file_done = True
break
if part_file is None:
part_dir = subdir_generator_function()
part_path = os.path.join(part_dir, os.path.basename(input_files[0]))
part_file = open(part_path, 'w')
part_file.write(a_line)
lines_remaining -= 1
except Exception as e:
log.error('Unable to split files: %s', unicodify(e))
raise
finally:
f.close()
if part_file:
part_file.close()
# ------------- Dataproviders
@p_dataproviders.decorators.dataprovider_factory(
"line", p_dataproviders.line.FilteredLineDataProvider.settings
)
def line_dataprovider(self, dataset, **settings):
"""
Returns an iterator over the dataset's lines (that have been stripped)
optionally excluding blank lines and lines that start with a comment character.
"""
dataset_source = p_dataproviders.dataset.DatasetDataProvider(dataset)
return p_dataproviders.line.FilteredLineDataProvider(dataset_source, **settings)
@p_dataproviders.decorators.dataprovider_factory(
"regex-line", p_dataproviders.line.RegexLineDataProvider.settings
)
def regex_line_dataprovider(self, dataset, **settings):
"""
Returns an iterator over the dataset's lines
optionally including/excluding lines that match one or more regex filters.
"""
dataset_source = p_dataproviders.dataset.DatasetDataProvider(dataset)
return p_dataproviders.line.RegexLineDataProvider(dataset_source, **settings)
class Directory(Data):
"""Class representing a directory of files."""
class GenericAsn1(Text):
"""Class for generic ASN.1 text format"""
edam_data = "data_0849"
edam_format = "format_1966"
file_ext = 'asn1'
class LineCount(Text):
"""
Dataset contains a single line with a single integer that denotes the
line count for a related dataset. Used for custom builds.
"""
class Newick(Text):
"""New Hampshire/Newick Format"""
edam_data = "data_0872"
edam_format = "format_1910"
file_ext = "newick"
def sniff(self, filename):
""" Returning false as the newick format is too general and cannot be sniffed."""
return False
def get_visualizations(self, dataset):
"""
Returns a list of visualizations for datatype.
"""
return ['phyloviz']
@build_sniff_from_prefix
class Nexus(Text):
"""Nexus format as used By Paup, Mr Bayes, etc"""
edam_data = "data_0872"
edam_format = "format_1912"
file_ext = "nex"
def sniff_prefix(self, file_prefix: FilePrefix):
"""All Nexus Files Simply puts a '#NEXUS' in its first line"""
return file_prefix.string_io().read(6).upper() == "#NEXUS"
def get_visualizations(self, dataset):
"""
Returns a list of visualizations for datatype.
"""
return ['phyloviz']
# ------------- Utility methods --------------
# nice_size used to be here, but to resolve cyclical dependencies it's been
# moved to galaxy.util. It belongs there anyway since it's used outside
# datatypes.
nice_size = util.nice_size
def get_test_fname(fname):
"""Returns test data filename"""
path = os.path.dirname(__file__)
full_path = os.path.join(path, 'test', fname)
return full_path
def get_file_peek(file_name, WIDTH=256, LINE_COUNT=5, skipchars=None, line_wrap=True):
"""
Returns the first LINE_COUNT lines wrapped to WIDTH.
>>> def assert_peek_is(file_name, expected, *args, **kwd):
... path = get_test_fname(file_name)
... peek = get_file_peek(path, *args, **kwd)
... assert peek == expected, "%s != %s" % (peek, expected)
>>> assert_peek_is('0_nonewline', u'0')
>>> assert_peek_is('0.txt', u'0\\n')
>>> assert_peek_is('4.bed', u'chr22\\t30128507\\t31828507\\tuc003bnx.1_cds_2_0_chr22_29227_f\\t0\\t+\\n', LINE_COUNT=1)
>>> assert_peek_is('1.bed', u'chr1\\t147962192\\t147962580\\tCCDS989.1_cds_0_0_chr1_147962193_r\\t0\\t-\\nchr1\\t147984545\\t147984630\\tCCDS990.1_cds_0_0_chr1_147984546_f\\t0\\t+\\n', LINE_COUNT=2)
"""
# Set size for file.readline() to a negative number to force it to
# read until either a newline or EOF. Needed for datasets with very
# long lines.
if WIDTH == 'unlimited':
WIDTH = -1
if skipchars is None:
skipchars = []
lines = []
count = 0
last_line_break = False
with compression_utils.get_fileobj(file_name) as temp:
while count < LINE_COUNT:
try:
line = temp.readline(WIDTH)
except UnicodeDecodeError:
return "binary file"
if line == "":
break
last_line_break = False
if line.endswith('\n'):
line = line[:-1]
last_line_break = True
elif not line_wrap:
for i in file_reader(temp, 1):
if i == '\n':
last_line_break = True
if not i or i == '\n':
break
skip_line = False
for skipchar in skipchars:
if line.startswith(skipchar):
skip_line = True
break
if not skip_line:
lines.append(line)
count += 1
return '\n'.join(lines) + ('\n' if last_line_break else '')
|
import json
import os
import pytest
from detect_secrets.core import baseline
from detect_secrets.core import plugins
from detect_secrets.core.secrets_collection import SecretsCollection
from detect_secrets.core.usage import ParserBuilder
from detect_secrets.settings import get_settings
from testing.mocks import mock_named_temporary_file
@pytest.fixture
def parser():
return (
ParserBuilder()
.add_plugin_options()
.add_baseline_options()
)
class TestAddCustomLimits:
@staticmethod
def test_success(parser):
parser.parse_args(['--base64-limit', '5'])
assert get_settings().plugins['Base64HighEntropyString']['limit'] == 5.0
@staticmethod
@pytest.mark.parametrize(
'flag',
(
'--hex-limit',
'--base64-limit',
),
)
@pytest.mark.parametrize(
'value',
(
'-1',
'8.1',
),
)
def test_failure(parser, flag, value):
with pytest.raises(SystemExit):
parser.parse_args([flag, value])
@staticmethod
def test_precedence_with_only_baseline(parser):
with mock_named_temporary_file() as f:
f.write(
json.dumps({
'version': '0.0.1',
'plugins_used': [
{
'name': 'Base64HighEntropyString',
'base64_limit': 3,
},
],
'results': [],
}).encode(),
)
f.seek(0)
parser.parse_args(['--baseline', f.name])
assert get_settings().plugins['Base64HighEntropyString'] == {'limit': 3}
@staticmethod
def test_precedence_with_baseline_and_explicit_value(parser):
with mock_named_temporary_file() as f:
f.write(
json.dumps({
'version': '0.0.1',
'plugins_used': [
{
'name': 'Base64HighEntropyString',
'base64_limit': 3,
},
],
'results': [],
}).encode(),
)
f.seek(0)
parser.parse_args(['--baseline', f.name, '--base64-limit', '5'])
assert get_settings().plugins['Base64HighEntropyString'] == {'limit': 5}
class TestAddDisableFlag:
@staticmethod
def test_success(parser):
args = parser.parse_args([
'--disable-plugin', 'Base64HighEntropyString',
'--disable-plugin', 'AWSKeyDetector',
])
assert args.disable_plugin == {'AWSKeyDetector', 'Base64HighEntropyString'}
assert 'AWSKeyDetector' not in get_settings().plugins
assert 'Base64HighEntropyString' not in get_settings().plugins
assert get_settings().plugins
@staticmethod
def test_not_supplied(parser):
args = parser.parse_args([])
assert not args.disable_plugin
@staticmethod
def test_invalid_classname(parser):
with pytest.raises(SystemExit):
parser.parse_args(['--disable-plugin', 'InvalidClassName'])
@staticmethod
def test_precedence_with_baseline(parser):
with mock_named_temporary_file() as f:
f.write(
json.dumps({
'version': '0.0.1',
'plugins_used': [
{
'name': 'Base64HighEntropyString',
'base64_limit': 3,
},
{
'name': 'AWSKeyDetector',
},
],
'results': [],
}).encode(),
)
f.seek(0)
parser.parse_args([
'--baseline', f.name,
'--disable-plugin', 'Base64HighEntropyString',
])
assert len(get_settings().plugins) == 1
assert 'AWSKeyDetector' in get_settings().plugins
class TestCustomPlugins:
@staticmethod
def test_success(parser):
# Ensure it serializes accordingly.
parser.parse_args(['-p', 'testing/plugins.py'])
with mock_named_temporary_file() as f:
baseline.save_to_file(SecretsCollection(), f.name)
f.seek(0)
get_settings().clear()
plugins.util.get_mapping_from_secret_type_to_class.cache_clear()
assert 'HippoDetector' not in get_settings().plugins
parser.parse_args(['--baseline', f.name])
assert get_settings().plugins['HippoDetector'] == {
'path': f'file://{os.path.abspath('testing/plugins.py')}',
}
assert plugins.initialize.from_plugin_classname('HippoDetector')
@staticmethod
def test_failure(parser):
with pytest.raises(SystemExit):
parser.parse_args(['-p', 'test_data/config.env'])
| import json
import os
import pytest
from detect_secrets.core import baseline
from detect_secrets.core import plugins
from detect_secrets.core.secrets_collection import SecretsCollection
from detect_secrets.core.usage import ParserBuilder
from detect_secrets.settings import get_settings
from testing.mocks import mock_named_temporary_file
@pytest.fixture
def parser():
return (
ParserBuilder()
.add_plugin_options()
.add_baseline_options()
)
class TestAddCustomLimits:
@staticmethod
def test_success(parser):
parser.parse_args(['--base64-limit', '5'])
assert get_settings().plugins['Base64HighEntropyString']['limit'] == 5.0
@staticmethod
@pytest.mark.parametrize(
'flag',
(
'--hex-limit',
'--base64-limit',
),
)
@pytest.mark.parametrize(
'value',
(
'-1',
'8.1',
),
)
def test_failure(parser, flag, value):
with pytest.raises(SystemExit):
parser.parse_args([flag, value])
@staticmethod
def test_precedence_with_only_baseline(parser):
with mock_named_temporary_file() as f:
f.write(
json.dumps({
'version': '0.0.1',
'plugins_used': [
{
'name': 'Base64HighEntropyString',
'base64_limit': 3,
},
],
'results': [],
}).encode(),
)
f.seek(0)
parser.parse_args(['--baseline', f.name])
assert get_settings().plugins['Base64HighEntropyString'] == {'limit': 3}
@staticmethod
def test_precedence_with_baseline_and_explicit_value(parser):
with mock_named_temporary_file() as f:
f.write(
json.dumps({
'version': '0.0.1',
'plugins_used': [
{
'name': 'Base64HighEntropyString',
'base64_limit': 3,
},
],
'results': [],
}).encode(),
)
f.seek(0)
parser.parse_args(['--baseline', f.name, '--base64-limit', '5'])
assert get_settings().plugins['Base64HighEntropyString'] == {'limit': 5}
class TestAddDisableFlag:
@staticmethod
def test_success(parser):
args = parser.parse_args([
'--disable-plugin', 'Base64HighEntropyString',
'--disable-plugin', 'AWSKeyDetector',
])
assert args.disable_plugin == {'AWSKeyDetector', 'Base64HighEntropyString'}
assert 'AWSKeyDetector' not in get_settings().plugins
assert 'Base64HighEntropyString' not in get_settings().plugins
assert get_settings().plugins
@staticmethod
def test_not_supplied(parser):
args = parser.parse_args([])
assert not args.disable_plugin
@staticmethod
def test_invalid_classname(parser):
with pytest.raises(SystemExit):
parser.parse_args(['--disable-plugin', 'InvalidClassName'])
@staticmethod
def test_precedence_with_baseline(parser):
with mock_named_temporary_file() as f:
f.write(
json.dumps({
'version': '0.0.1',
'plugins_used': [
{
'name': 'Base64HighEntropyString',
'base64_limit': 3,
},
{
'name': 'AWSKeyDetector',
},
],
'results': [],
}).encode(),
)
f.seek(0)
parser.parse_args([
'--baseline', f.name,
'--disable-plugin', 'Base64HighEntropyString',
])
assert len(get_settings().plugins) == 1
assert 'AWSKeyDetector' in get_settings().plugins
class TestCustomPlugins:
@staticmethod
def test_success(parser):
# Ensure it serializes accordingly.
parser.parse_args(['-p', 'testing/plugins.py'])
with mock_named_temporary_file() as f:
baseline.save_to_file(SecretsCollection(), f.name)
f.seek(0)
get_settings().clear()
plugins.util.get_mapping_from_secret_type_to_class.cache_clear()
assert 'HippoDetector' not in get_settings().plugins
parser.parse_args(['--baseline', f.name])
assert get_settings().plugins['HippoDetector'] == {
'path': f'file://{os.path.abspath("testing/plugins.py")}',
}
assert plugins.initialize.from_plugin_classname('HippoDetector')
@staticmethod
def test_failure(parser):
with pytest.raises(SystemExit):
parser.parse_args(['-p', 'test_data/config.env'])
|
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import collections
import itertools
from edb.lang.ir import ast as irast
from edb.lang.ir import astexpr as irastexpr
from edb.lang.ir import utils as ir_utils
from edb.lang.edgeql import compiler as ql_compiler
from edb.lang.edgeql import ast as qlast
from edb.lang.schema import scalars as s_scalars
from edb.lang.schema import objtypes as s_objtypes
from edb.lang.schema import error as s_err
from edb.lang.schema import links as s_links
from edb.lang.schema import name as sn
from edb.lang.common import ast
from .datasources import introspection
from . import ast as pg_ast
from . import dbops
from . import deltadbops
from . import common
from . import types
from . import compiler
from . import codegen
class ConstraintMech:
def __init__(self):
self._constraints_cache = None
async def init_cache(self, connection):
self._constraints_cache = \
await self._populate_constraint_cache(connection)
def invalidate_schema_cache(self):
self._constraints_cache = None
async def _populate_constraint_cache(self, connection):
constraints = {}
rows = await introspection.constraints.fetch(
connection,
schema_pattern='edgedb%', constraint_pattern='%;schemaconstr%')
for row in rows:
constraints[row['constraint_name']] = row
return constraints
async def constraint_name_from_pg_name(self, connection, pg_name):
if self._constraints_cache is None:
self._constraints_cache = \
await self._populate_constraint_cache(connection)
try:
cdata = self._constraints_cache[pg_name]
except KeyError:
return None
else:
name = cdata['constraint_description']
name, _, _ = name.rpartition(';')
return sn.Name(name)
@classmethod
def _get_unique_refs(cls, tree):
# Check if the expression is
# std::is_dictinct(<arg>) [and std::is_distinct (<arg>)...]
expr = tree.expr.expr.result
astexpr = irastexpr.DistinctConjunctionExpr()
refs = astexpr.match(expr)
if refs is None:
return refs
else:
all_refs = []
for ref in refs:
# Unnest sequences in refs
all_refs.append(ref)
return all_refs
@classmethod
def _get_ref_storage_info(cls, schema, refs):
link_biased = {}
objtype_biased = {}
ref_ptrs = {}
for ref in refs:
rptr = ref.rptr
if rptr is not None:
ptr = ref.rptr.ptrcls
if ptr.is_link_property():
src = ref.rptr.source.rptr.ptrcls
if src.is_derived:
# This specialized pointer was derived specifically
# for the purposes of constraint expr compilation.
src = src.bases[0]
else:
src = ref.rptr.source.scls
ref_ptrs[ref] = (ptr, src)
for ref, (ptr, src) in ref_ptrs.items():
ptr_info = types.get_pointer_storage_info(
ptr, source=src, resolve_type=False)
# See if any of the refs are hosted in pointer tables and others
# are not...
if ptr_info.table_type == 'link':
link_biased[ref] = ptr_info
else:
objtype_biased[ref] = ptr_info
if link_biased and objtype_biased:
break
if link_biased and objtype_biased:
for ref in objtype_biased.copy():
ptr, src = ref_ptrs[ref]
ptr_info = types.get_pointer_storage_info(
ptr, source=src, resolve_type=False, link_bias=True)
if ptr_info.table_type == 'link':
link_biased[ref] = ptr_info
objtype_biased.pop(ref)
ref_tables = {}
for ref, ptr_info in itertools.chain(
objtype_biased.items(), link_biased.items()):
ptr, src = ref_ptrs[ref]
try:
ref_tables[ptr_info.table_name].append(
(ref, ptr, src, ptr_info))
except KeyError:
ref_tables[ptr_info.table_name] = [(ref, ptr, src, ptr_info)]
return ref_tables
@classmethod
def _edgeql_ref_to_pg_constr(cls, subject, tree, schema, link_bias):
sql_tree = compiler.compile_ir_to_sql_tree(
tree, schema=schema, singleton_mode=True)
if isinstance(sql_tree, pg_ast.SelectStmt):
# XXX: use ast pattern matcher for this
sql_expr = sql_tree.from_clause[0].relation\
.query.target_list[0].val
else:
sql_expr = sql_tree
if isinstance(tree, irast.Statement):
tree = tree.expr
if isinstance(tree.expr, irast.SelectStmt):
tree = tree.expr.result
is_multicol = isinstance(tree.expr, irast.Tuple)
# Determine if the sequence of references are all simple refs, not
# expressions. This influences the type of Postgres constraint used.
#
is_trivial = (
isinstance(sql_expr, pg_ast.ColumnRef) or (
isinstance(sql_expr, pg_ast.ImplicitRowExpr) and all(
isinstance(el, pg_ast.ColumnRef)
for el in sql_expr.args)))
# Find all field references
#
flt = lambda n: isinstance(n, pg_ast.ColumnRef) and len(n.name) == 1
refs = set(ast.find_children(sql_expr, flt))
if isinstance(subject, s_scalars.ScalarType):
# Domain constraint, replace <scalar_name> with VALUE
subject_pg_name = common.edgedb_name_to_pg_name(subject.name)
for ref in refs:
if ref.name != [subject_pg_name]:
raise ValueError(
f'unexpected node reference in '
f'ScalarType constraint: {'.'.join(ref.name)}'
)
# work around the immutability check
object.__setattr__(ref, 'name', ['VALUE'])
plain_expr = codegen.SQLSourceGenerator.to_source(sql_expr)
if is_multicol:
chunks = []
for elem in sql_expr.args:
chunks.append(codegen.SQLSourceGenerator.to_source(elem))
else:
chunks = [plain_expr]
if isinstance(sql_expr, pg_ast.ColumnRef):
refs.add(sql_expr)
for ref in refs:
ref.name.insert(0, 'NEW')
new_expr = codegen.SQLSourceGenerator.to_source(sql_expr)
for ref in refs:
ref.name[0] = 'OLD'
old_expr = codegen.SQLSourceGenerator.to_source(sql_expr)
exprdata = dict(
plain=plain_expr, plain_chunks=chunks, new=new_expr, old=old_expr)
return dict(
exprdata=exprdata, is_multicol=is_multicol, is_trivial=is_trivial)
@classmethod
def schema_constraint_to_backend_constraint(
cls, subject, constraint, schema):
assert constraint.subject is not None
ir = ql_compiler.compile_to_ir(
constraint.finalexpr, schema, anchors={qlast.Subject: subject})
terminal_refs = ir_utils.get_terminal_references(ir.expr.expr.result)
ref_tables = cls._get_ref_storage_info(schema, terminal_refs)
if len(ref_tables) > 1:
raise ValueError(
'backend: multi-table constraints are not currently supported')
elif ref_tables:
subject_db_name = next(iter(ref_tables))
else:
subject_db_name = common.scalar_name_to_domain_name(
subject.name, catenate=False)
link_bias = ref_tables and next(iter(ref_tables.values()))[0][
3].table_type == 'link'
unique_expr_refs = cls._get_unique_refs(ir)
pg_constr_data = {
'subject_db_name': subject_db_name,
'expressions': []
}
exprs = pg_constr_data['expressions']
if unique_expr_refs:
for ref in unique_expr_refs:
exprdata = cls._edgeql_ref_to_pg_constr(
subject, ref, schema, link_bias)
exprs.append(exprdata)
pg_constr_data['scope'] = 'relation'
pg_constr_data['type'] = 'unique'
pg_constr_data['subject_db_name'] = subject_db_name
else:
exprdata = cls._edgeql_ref_to_pg_constr(
subject, ir, schema, link_bias)
exprs.append(exprdata)
pg_constr_data['subject_db_name'] = subject_db_name
pg_constr_data['scope'] = 'row'
pg_constr_data['type'] = 'check'
if isinstance(constraint.subject, s_scalars.ScalarType):
constraint = SchemaDomainConstraint(
subject=subject, constraint=constraint,
pg_constr_data=pg_constr_data)
else:
constraint = SchemaTableConstraint(
subject=subject, constraint=constraint,
pg_constr_data=pg_constr_data)
return constraint
class SchemaDomainConstraint:
def __init__(self, subject, constraint, pg_constr_data):
self._subject = subject
self._constraint = constraint
self._pg_constr_data = pg_constr_data
@classmethod
def _domain_constraint(cls, constr):
domain_name = constr._pg_constr_data['subject_db_name']
expressions = constr._pg_constr_data['expressions']
constr = deltadbops.SchemaConstraintDomainConstraint(
domain_name, constr._constraint, expressions)
return constr
def create_ops(self):
ops = dbops.CommandGroup()
domconstr = self._domain_constraint(self)
add_constr = dbops.AlterDomainAddConstraint(
name=domconstr.get_subject_name(quote=False), constraint=domconstr)
ops.add_command(add_constr)
return ops
def rename_ops(self, orig_constr):
ops = dbops.CommandGroup()
domconstr = self._domain_constraint(self)
orig_domconstr = self._domain_constraint(orig_constr)
add_constr = dbops.AlterDomainRenameConstraint(
name=domconstr.get_subject_name(quote=False),
constraint=orig_domconstr, new_constraint=domconstr)
ops.add_command(add_constr)
return ops
def alter_ops(self, orig_constr):
ops = dbops.CommandGroup()
return ops
def delete_ops(self):
ops = dbops.CommandGroup()
domconstr = self._domain_constraint(self)
add_constr = dbops.AlterDomainDropConstraint(
name=domconstr.get_subject_name(quote=False), constraint=domconstr)
ops.add_command(add_constr)
return ops
class SchemaTableConstraint:
def __init__(self, subject, constraint, pg_constr_data):
self._subject = subject
self._constraint = constraint
self._pg_constr_data = pg_constr_data
@classmethod
def _table_constraint(cls, constr):
pg_c = constr._pg_constr_data
table_name = pg_c['subject_db_name']
expressions = pg_c['expressions']
constr = deltadbops.SchemaConstraintTableConstraint(
table_name, constraint=constr._constraint, exprdata=expressions,
scope=pg_c['scope'], type=pg_c['type'])
return constr
def create_ops(self):
ops = dbops.CommandGroup()
tabconstr = self._table_constraint(self)
add_constr = deltadbops.AlterTableAddInheritableConstraint(
name=tabconstr.get_subject_name(quote=False), constraint=tabconstr)
ops.add_command(add_constr)
return ops
def rename_ops(self, orig_constr):
ops = dbops.CommandGroup()
tabconstr = self._table_constraint(self)
orig_tabconstr = self._table_constraint(orig_constr)
rename_constr = deltadbops.AlterTableRenameInheritableConstraint(
name=tabconstr.get_subject_name(quote=False),
constraint=orig_tabconstr, new_constraint=tabconstr)
ops.add_command(rename_constr)
return ops
def alter_ops(self, orig_constr):
ops = dbops.CommandGroup()
tabconstr = self._table_constraint(self)
orig_tabconstr = self._table_constraint(orig_constr)
alter_constr = deltadbops.AlterTableAlterInheritableConstraint(
name=tabconstr.get_subject_name(quote=False),
constraint=orig_tabconstr, new_constraint=tabconstr)
ops.add_command(alter_constr)
return ops
def delete_ops(self):
ops = dbops.CommandGroup()
tabconstr = self._table_constraint(self)
add_constr = deltadbops.AlterTableDropInheritableConstraint(
name=tabconstr.get_subject_name(quote=False), constraint=tabconstr)
ops.add_command(add_constr)
return ops
class TypeMech:
def __init__(self):
self._column_cache = None
self._table_cache = None
def invalidate_schema_cache(self):
self._column_cache = None
self._table_cache = None
async def init_cache(self, connection):
await self._load_table_columns(('edgedb_%', None), connection)
async def _load_table_columns(self, table_name, connection):
cols = await introspection.tables.fetch_columns(
connection,
table_pattern=table_name[1], schema_pattern=table_name[0])
if self._column_cache is None:
self._column_cache = {}
for col in cols:
key = (col['table_schema'], col['table_name'])
try:
table_cols = self._column_cache[key]
except KeyError:
table_cols = collections.OrderedDict()
self._column_cache[key] = table_cols
table_cols[col['column_name']] = col
async def get_table_columns(self, table_name, connection=None,
cache='auto'):
if cache is not None:
cols = self.get_cached_table_columns(table_name)
if cols is None and cache != 'always':
cols = await self._load_table_columns(table_name, connection)
return self._column_cache.get(table_name)
def get_cached_table_columns(self, table_name):
if self._column_cache is not None:
cols = self._column_cache.get(table_name)
else:
cols = None
return cols
async def _load_type_attributes(self, type_name, connection):
cols = await introspection.types.fetch_attributes(
connection,
type_pattern=type_name[1], schema_pattern=type_name[0])
if self._column_cache is None:
self._column_cache = {}
for col in cols:
key = (col['type_schema'], col['type_name'])
try:
type_attrs = self._column_cache[key]
except KeyError:
type_attrs = collections.OrderedDict()
self._column_cache[key] = type_attrs
type_attrs[col['attribute_name']] = col
async def get_type_attributes(self, type_name, connection, cache='auto'):
if cache is not None and self._column_cache is not None:
cols = self._column_cache.get(type_name)
else:
cols = None
if cols is None and cache != 'always':
await self._load_type_attributes(type_name, connection)
return self._column_cache.get(type_name)
def get_table(self, scls, schema):
if self._table_cache is None:
self._table_cache = {}
table = self._table_cache.get(scls)
if table is None:
table_name = common.get_table_name(scls, catenate=False)
table = dbops.Table(table_name)
cols = []
if isinstance(scls, s_links.Link):
cols.extend([
dbops.Column(name='ptr_item_id', type='uuid'),
dbops.Column(name='std::source', type='uuid'),
dbops.Column(name='std::target', type='uuid')
])
elif isinstance(scls, s_objtypes.ObjectType):
cols.extend([dbops.Column(name='std::__type__', type='uuid')])
else:
assert False
if isinstance(scls, s_objtypes.ObjectType):
expected_table_type = 'ObjectType'
else:
expected_table_type = 'link'
for pointer_name, pointer in scls.pointers.items():
if not pointer.singular():
continue
if pointer_name == 'std::source':
continue
ptr_stor_info = types.get_pointer_storage_info(
pointer, schema=schema)
if ptr_stor_info.column_name == 'std::target':
continue
if ptr_stor_info.table_type == expected_table_type:
cols.append(
dbops.Column(
name=ptr_stor_info.column_name,
type=common.qname(*ptr_stor_info.column_type)))
table.add_columns(cols)
self._table_cache[scls] = table
return table
def ptr_default_to_col_default(schema, ptr, expr):
try:
ir = ql_compiler.compile_to_ir(expr, schema)
except s_err.SchemaError:
# Referene errors mean that is is a non-constant default
# referring to a not-yet-existing objects.
return None
if not ir_utils.is_const(ir):
return None
sql_expr = compiler.compile_ir_to_sql_tree(
ir, schema=schema, singleton_mode=True)
sql_text = codegen.SQLSourceGenerator.to_source(sql_expr)
return sql_text
| #
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import collections
import itertools
from edb.lang.ir import ast as irast
from edb.lang.ir import astexpr as irastexpr
from edb.lang.ir import utils as ir_utils
from edb.lang.edgeql import compiler as ql_compiler
from edb.lang.edgeql import ast as qlast
from edb.lang.schema import scalars as s_scalars
from edb.lang.schema import objtypes as s_objtypes
from edb.lang.schema import error as s_err
from edb.lang.schema import links as s_links
from edb.lang.schema import name as sn
from edb.lang.common import ast
from .datasources import introspection
from . import ast as pg_ast
from . import dbops
from . import deltadbops
from . import common
from . import types
from . import compiler
from . import codegen
class ConstraintMech:
def __init__(self):
self._constraints_cache = None
async def init_cache(self, connection):
self._constraints_cache = \
await self._populate_constraint_cache(connection)
def invalidate_schema_cache(self):
self._constraints_cache = None
async def _populate_constraint_cache(self, connection):
constraints = {}
rows = await introspection.constraints.fetch(
connection,
schema_pattern='edgedb%', constraint_pattern='%;schemaconstr%')
for row in rows:
constraints[row['constraint_name']] = row
return constraints
async def constraint_name_from_pg_name(self, connection, pg_name):
if self._constraints_cache is None:
self._constraints_cache = \
await self._populate_constraint_cache(connection)
try:
cdata = self._constraints_cache[pg_name]
except KeyError:
return None
else:
name = cdata['constraint_description']
name, _, _ = name.rpartition(';')
return sn.Name(name)
@classmethod
def _get_unique_refs(cls, tree):
# Check if the expression is
# std::is_dictinct(<arg>) [and std::is_distinct (<arg>)...]
expr = tree.expr.expr.result
astexpr = irastexpr.DistinctConjunctionExpr()
refs = astexpr.match(expr)
if refs is None:
return refs
else:
all_refs = []
for ref in refs:
# Unnest sequences in refs
all_refs.append(ref)
return all_refs
@classmethod
def _get_ref_storage_info(cls, schema, refs):
link_biased = {}
objtype_biased = {}
ref_ptrs = {}
for ref in refs:
rptr = ref.rptr
if rptr is not None:
ptr = ref.rptr.ptrcls
if ptr.is_link_property():
src = ref.rptr.source.rptr.ptrcls
if src.is_derived:
# This specialized pointer was derived specifically
# for the purposes of constraint expr compilation.
src = src.bases[0]
else:
src = ref.rptr.source.scls
ref_ptrs[ref] = (ptr, src)
for ref, (ptr, src) in ref_ptrs.items():
ptr_info = types.get_pointer_storage_info(
ptr, source=src, resolve_type=False)
# See if any of the refs are hosted in pointer tables and others
# are not...
if ptr_info.table_type == 'link':
link_biased[ref] = ptr_info
else:
objtype_biased[ref] = ptr_info
if link_biased and objtype_biased:
break
if link_biased and objtype_biased:
for ref in objtype_biased.copy():
ptr, src = ref_ptrs[ref]
ptr_info = types.get_pointer_storage_info(
ptr, source=src, resolve_type=False, link_bias=True)
if ptr_info.table_type == 'link':
link_biased[ref] = ptr_info
objtype_biased.pop(ref)
ref_tables = {}
for ref, ptr_info in itertools.chain(
objtype_biased.items(), link_biased.items()):
ptr, src = ref_ptrs[ref]
try:
ref_tables[ptr_info.table_name].append(
(ref, ptr, src, ptr_info))
except KeyError:
ref_tables[ptr_info.table_name] = [(ref, ptr, src, ptr_info)]
return ref_tables
@classmethod
def _edgeql_ref_to_pg_constr(cls, subject, tree, schema, link_bias):
sql_tree = compiler.compile_ir_to_sql_tree(
tree, schema=schema, singleton_mode=True)
if isinstance(sql_tree, pg_ast.SelectStmt):
# XXX: use ast pattern matcher for this
sql_expr = sql_tree.from_clause[0].relation\
.query.target_list[0].val
else:
sql_expr = sql_tree
if isinstance(tree, irast.Statement):
tree = tree.expr
if isinstance(tree.expr, irast.SelectStmt):
tree = tree.expr.result
is_multicol = isinstance(tree.expr, irast.Tuple)
# Determine if the sequence of references are all simple refs, not
# expressions. This influences the type of Postgres constraint used.
#
is_trivial = (
isinstance(sql_expr, pg_ast.ColumnRef) or (
isinstance(sql_expr, pg_ast.ImplicitRowExpr) and all(
isinstance(el, pg_ast.ColumnRef)
for el in sql_expr.args)))
# Find all field references
#
flt = lambda n: isinstance(n, pg_ast.ColumnRef) and len(n.name) == 1
refs = set(ast.find_children(sql_expr, flt))
if isinstance(subject, s_scalars.ScalarType):
# Domain constraint, replace <scalar_name> with VALUE
subject_pg_name = common.edgedb_name_to_pg_name(subject.name)
for ref in refs:
if ref.name != [subject_pg_name]:
raise ValueError(
f'unexpected node reference in '
f'ScalarType constraint: {".".join(ref.name)}'
)
# work around the immutability check
object.__setattr__(ref, 'name', ['VALUE'])
plain_expr = codegen.SQLSourceGenerator.to_source(sql_expr)
if is_multicol:
chunks = []
for elem in sql_expr.args:
chunks.append(codegen.SQLSourceGenerator.to_source(elem))
else:
chunks = [plain_expr]
if isinstance(sql_expr, pg_ast.ColumnRef):
refs.add(sql_expr)
for ref in refs:
ref.name.insert(0, 'NEW')
new_expr = codegen.SQLSourceGenerator.to_source(sql_expr)
for ref in refs:
ref.name[0] = 'OLD'
old_expr = codegen.SQLSourceGenerator.to_source(sql_expr)
exprdata = dict(
plain=plain_expr, plain_chunks=chunks, new=new_expr, old=old_expr)
return dict(
exprdata=exprdata, is_multicol=is_multicol, is_trivial=is_trivial)
@classmethod
def schema_constraint_to_backend_constraint(
cls, subject, constraint, schema):
assert constraint.subject is not None
ir = ql_compiler.compile_to_ir(
constraint.finalexpr, schema, anchors={qlast.Subject: subject})
terminal_refs = ir_utils.get_terminal_references(ir.expr.expr.result)
ref_tables = cls._get_ref_storage_info(schema, terminal_refs)
if len(ref_tables) > 1:
raise ValueError(
'backend: multi-table constraints are not currently supported')
elif ref_tables:
subject_db_name = next(iter(ref_tables))
else:
subject_db_name = common.scalar_name_to_domain_name(
subject.name, catenate=False)
link_bias = ref_tables and next(iter(ref_tables.values()))[0][
3].table_type == 'link'
unique_expr_refs = cls._get_unique_refs(ir)
pg_constr_data = {
'subject_db_name': subject_db_name,
'expressions': []
}
exprs = pg_constr_data['expressions']
if unique_expr_refs:
for ref in unique_expr_refs:
exprdata = cls._edgeql_ref_to_pg_constr(
subject, ref, schema, link_bias)
exprs.append(exprdata)
pg_constr_data['scope'] = 'relation'
pg_constr_data['type'] = 'unique'
pg_constr_data['subject_db_name'] = subject_db_name
else:
exprdata = cls._edgeql_ref_to_pg_constr(
subject, ir, schema, link_bias)
exprs.append(exprdata)
pg_constr_data['subject_db_name'] = subject_db_name
pg_constr_data['scope'] = 'row'
pg_constr_data['type'] = 'check'
if isinstance(constraint.subject, s_scalars.ScalarType):
constraint = SchemaDomainConstraint(
subject=subject, constraint=constraint,
pg_constr_data=pg_constr_data)
else:
constraint = SchemaTableConstraint(
subject=subject, constraint=constraint,
pg_constr_data=pg_constr_data)
return constraint
class SchemaDomainConstraint:
def __init__(self, subject, constraint, pg_constr_data):
self._subject = subject
self._constraint = constraint
self._pg_constr_data = pg_constr_data
@classmethod
def _domain_constraint(cls, constr):
domain_name = constr._pg_constr_data['subject_db_name']
expressions = constr._pg_constr_data['expressions']
constr = deltadbops.SchemaConstraintDomainConstraint(
domain_name, constr._constraint, expressions)
return constr
def create_ops(self):
ops = dbops.CommandGroup()
domconstr = self._domain_constraint(self)
add_constr = dbops.AlterDomainAddConstraint(
name=domconstr.get_subject_name(quote=False), constraint=domconstr)
ops.add_command(add_constr)
return ops
def rename_ops(self, orig_constr):
ops = dbops.CommandGroup()
domconstr = self._domain_constraint(self)
orig_domconstr = self._domain_constraint(orig_constr)
add_constr = dbops.AlterDomainRenameConstraint(
name=domconstr.get_subject_name(quote=False),
constraint=orig_domconstr, new_constraint=domconstr)
ops.add_command(add_constr)
return ops
def alter_ops(self, orig_constr):
ops = dbops.CommandGroup()
return ops
def delete_ops(self):
ops = dbops.CommandGroup()
domconstr = self._domain_constraint(self)
add_constr = dbops.AlterDomainDropConstraint(
name=domconstr.get_subject_name(quote=False), constraint=domconstr)
ops.add_command(add_constr)
return ops
class SchemaTableConstraint:
def __init__(self, subject, constraint, pg_constr_data):
self._subject = subject
self._constraint = constraint
self._pg_constr_data = pg_constr_data
@classmethod
def _table_constraint(cls, constr):
pg_c = constr._pg_constr_data
table_name = pg_c['subject_db_name']
expressions = pg_c['expressions']
constr = deltadbops.SchemaConstraintTableConstraint(
table_name, constraint=constr._constraint, exprdata=expressions,
scope=pg_c['scope'], type=pg_c['type'])
return constr
def create_ops(self):
ops = dbops.CommandGroup()
tabconstr = self._table_constraint(self)
add_constr = deltadbops.AlterTableAddInheritableConstraint(
name=tabconstr.get_subject_name(quote=False), constraint=tabconstr)
ops.add_command(add_constr)
return ops
def rename_ops(self, orig_constr):
ops = dbops.CommandGroup()
tabconstr = self._table_constraint(self)
orig_tabconstr = self._table_constraint(orig_constr)
rename_constr = deltadbops.AlterTableRenameInheritableConstraint(
name=tabconstr.get_subject_name(quote=False),
constraint=orig_tabconstr, new_constraint=tabconstr)
ops.add_command(rename_constr)
return ops
def alter_ops(self, orig_constr):
ops = dbops.CommandGroup()
tabconstr = self._table_constraint(self)
orig_tabconstr = self._table_constraint(orig_constr)
alter_constr = deltadbops.AlterTableAlterInheritableConstraint(
name=tabconstr.get_subject_name(quote=False),
constraint=orig_tabconstr, new_constraint=tabconstr)
ops.add_command(alter_constr)
return ops
def delete_ops(self):
ops = dbops.CommandGroup()
tabconstr = self._table_constraint(self)
add_constr = deltadbops.AlterTableDropInheritableConstraint(
name=tabconstr.get_subject_name(quote=False), constraint=tabconstr)
ops.add_command(add_constr)
return ops
class TypeMech:
def __init__(self):
self._column_cache = None
self._table_cache = None
def invalidate_schema_cache(self):
self._column_cache = None
self._table_cache = None
async def init_cache(self, connection):
await self._load_table_columns(('edgedb_%', None), connection)
async def _load_table_columns(self, table_name, connection):
cols = await introspection.tables.fetch_columns(
connection,
table_pattern=table_name[1], schema_pattern=table_name[0])
if self._column_cache is None:
self._column_cache = {}
for col in cols:
key = (col['table_schema'], col['table_name'])
try:
table_cols = self._column_cache[key]
except KeyError:
table_cols = collections.OrderedDict()
self._column_cache[key] = table_cols
table_cols[col['column_name']] = col
async def get_table_columns(self, table_name, connection=None,
cache='auto'):
if cache is not None:
cols = self.get_cached_table_columns(table_name)
if cols is None and cache != 'always':
cols = await self._load_table_columns(table_name, connection)
return self._column_cache.get(table_name)
def get_cached_table_columns(self, table_name):
if self._column_cache is not None:
cols = self._column_cache.get(table_name)
else:
cols = None
return cols
async def _load_type_attributes(self, type_name, connection):
cols = await introspection.types.fetch_attributes(
connection,
type_pattern=type_name[1], schema_pattern=type_name[0])
if self._column_cache is None:
self._column_cache = {}
for col in cols:
key = (col['type_schema'], col['type_name'])
try:
type_attrs = self._column_cache[key]
except KeyError:
type_attrs = collections.OrderedDict()
self._column_cache[key] = type_attrs
type_attrs[col['attribute_name']] = col
async def get_type_attributes(self, type_name, connection, cache='auto'):
if cache is not None and self._column_cache is not None:
cols = self._column_cache.get(type_name)
else:
cols = None
if cols is None and cache != 'always':
await self._load_type_attributes(type_name, connection)
return self._column_cache.get(type_name)
def get_table(self, scls, schema):
if self._table_cache is None:
self._table_cache = {}
table = self._table_cache.get(scls)
if table is None:
table_name = common.get_table_name(scls, catenate=False)
table = dbops.Table(table_name)
cols = []
if isinstance(scls, s_links.Link):
cols.extend([
dbops.Column(name='ptr_item_id', type='uuid'),
dbops.Column(name='std::source', type='uuid'),
dbops.Column(name='std::target', type='uuid')
])
elif isinstance(scls, s_objtypes.ObjectType):
cols.extend([dbops.Column(name='std::__type__', type='uuid')])
else:
assert False
if isinstance(scls, s_objtypes.ObjectType):
expected_table_type = 'ObjectType'
else:
expected_table_type = 'link'
for pointer_name, pointer in scls.pointers.items():
if not pointer.singular():
continue
if pointer_name == 'std::source':
continue
ptr_stor_info = types.get_pointer_storage_info(
pointer, schema=schema)
if ptr_stor_info.column_name == 'std::target':
continue
if ptr_stor_info.table_type == expected_table_type:
cols.append(
dbops.Column(
name=ptr_stor_info.column_name,
type=common.qname(*ptr_stor_info.column_type)))
table.add_columns(cols)
self._table_cache[scls] = table
return table
def ptr_default_to_col_default(schema, ptr, expr):
try:
ir = ql_compiler.compile_to_ir(expr, schema)
except s_err.SchemaError:
# Referene errors mean that is is a non-constant default
# referring to a not-yet-existing objects.
return None
if not ir_utils.is_const(ir):
return None
sql_expr = compiler.compile_ir_to_sql_tree(
ir, schema=schema, singleton_mode=True)
sql_text = codegen.SQLSourceGenerator.to_source(sql_expr)
return sql_text
|
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-节点管理(BlueKing-BK-NODEMAN) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at https://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
import logging
from collections import defaultdict
from celery.task import periodic_task
from django.db import transaction
from django.db.models import Q
from apps.node_man import constants, models
logger = logging.getLogger("celery")
@periodic_task(
run_every=constants.COLLECT_AUTO_TRIGGER_JOB_INTERVAL,
queue="backend", # 这个是用来在代码调用中指定队列的,例如: update_subscription_instances.delay()
options={"queue": "backend"}, # 这个是用来celery beat调度指定队列的
)
def collect_auto_trigger_job():
last_sub_task_id = models.GlobalSettings.get_config(models.GlobalSettings.KeyEnum.LAST_SUB_TASK_ID.value, None)
not_ready_task_info_map = models.GlobalSettings.get_config(
models.GlobalSettings.KeyEnum.NOT_READY_TASK_INFO_MAP.value, None
)
if last_sub_task_id is None:
last_sub_task_id = 0
models.GlobalSettings.set_config(models.GlobalSettings.KeyEnum.LAST_SUB_TASK_ID.value, last_sub_task_id)
if not_ready_task_info_map is None:
not_ready_task_info_map = {}
models.GlobalSettings.set_config(models.GlobalSettings.KeyEnum.NOT_READY_TASK_INFO_MAP.value, {})
not_ready_task_ids = list(int(not_ready_task_id_str) for not_ready_task_id_str in not_ready_task_info_map.keys())
all_auto_task_infos = models.SubscriptionTask.objects.filter(
Q(id__gt=last_sub_task_id) | Q(id__in=not_ready_task_ids), is_auto_trigger=True
).values("subscription_id", "id", "is_ready", "err_msg")
# 找出归属SaaS侧的订阅ID列表
subscription_ids = set(
models.Job.objects.filter(
is_auto_trigger=False,
subscription_id__in={auto_task_info["subscription_id"] for auto_task_info in all_auto_task_infos},
).values_list("subscription_id", flat=True)
)
subscriptions = models.Subscription.objects.filter(id__in=subscription_ids).values("id", "bk_biz_scope")
# 过滤非SaaS侧策略自动触发的订阅任务
auto_task_infos = [
auto_task_info
for auto_task_info in all_auto_task_infos
if auto_task_info["subscription_id"] in subscription_ids
]
logger.info(
f"collect_auto_trigger_job: auto_task_ids -> {[auto_task_info["id"] for auto_task_info in auto_task_infos]}"
)
# 考虑一个订阅中有多个自动触发task的情况
task_ids_gby_sub_id = defaultdict(list)
task_ids_gby_reason = {"NOT_READY": [], "READY": [], "ERROR": []}
for task_info in auto_task_infos:
# is_ready=False并且无错误信息时,该订阅任务仍处于创建状态
if not task_info["is_ready"]:
task_ids_gby_reason["ERROR" if task_info["err_msg"] else "NOT_READY"].append(task_info["id"])
continue
# 仅同步成功创建的的订阅任务
task_ids_gby_reason["READY"].append(task_info["id"])
task_ids_gby_sub_id[task_info["subscription_id"]].append(task_info["id"])
logger.info(
f"collect_auto_trigger_job: last_sub_task_id -> {last_sub_task_id}, "
f"task_ids_gby_reason -> {task_ids_gby_reason}, begin"
)
auto_jobs_to_be_created = []
for subscription in subscriptions:
# 任务未就绪或创建失败,跳过
if subscription["id"] not in task_ids_gby_sub_id:
continue
auto_jobs_to_be_created.append(
models.Job(
# 巡检的任务类型为安装
job_type=constants.JobType.MAIN_INSTALL_PLUGIN,
bk_biz_scope=subscription["bk_biz_scope"],
subscription_id=subscription["id"],
# 依赖calculate_statistics定时更新状态及实例状态统计
status=constants.JobStatusType.RUNNING,
statistics={f"{k}_count": 0 for k in ["success", "failed", "pending", "running", "total"]},
error_hosts=[],
created_by="admin",
# TODO 将历史多个自动触发task先行整合到一个job,后续根据实际情况考虑是否拆分
task_id_list=task_ids_gby_sub_id[subscription["id"]],
is_auto_trigger=True,
)
)
# 上一次未就绪在本次同步中已有结果,从未就绪记录中移除
for task_id in task_ids_gby_reason["READY"] + task_ids_gby_reason["ERROR"]:
# global setting 会将key转为str类型,在统计时也将整数转为str,保证统计准确
task_id = str(task_id)
not_ready_task_info_map.pop(task_id, None)
# 异步创建失败(ERROR)的任务无需同步,NOT_READY 的任务先行记录,若上一次的未就绪任务仍未就绪,重试次数+1
for task_id in task_ids_gby_reason["NOT_READY"]:
task_id = str(task_id)
not_ready_task_info_map[task_id] = not_ready_task_info_map.get(task_id, 0) + 1
# 指针后移至已完成同步id的最大值,若本轮无同步数据,指针位置不变
all_task_ids = {auto_task_info["id"] for auto_task_info in auto_task_infos}
# 仅统计新增task_id,防止指针回退
new_add_task_ids = all_task_ids - set(not_ready_task_ids)
last_sub_task_id = max(new_add_task_ids or [last_sub_task_id])
with transaction.atomic():
models.Job.objects.bulk_create(auto_jobs_to_be_created)
models.GlobalSettings.update_config(models.GlobalSettings.KeyEnum.LAST_SUB_TASK_ID.value, last_sub_task_id)
models.GlobalSettings.update_config(
models.GlobalSettings.KeyEnum.NOT_READY_TASK_INFO_MAP.value, not_ready_task_info_map
)
logger.info(
f"collect_auto_trigger_job: {models.GlobalSettings.KeyEnum.LAST_SUB_TASK_ID.value} -> {last_sub_task_id}, "
f"{models.GlobalSettings.KeyEnum.NOT_READY_TASK_INFO_MAP.value} -> {not_ready_task_info_map}"
)
return {
models.GlobalSettings.KeyEnum.LAST_SUB_TASK_ID.value: last_sub_task_id,
models.GlobalSettings.KeyEnum.NOT_READY_TASK_INFO_MAP.value: not_ready_task_info_map,
"TASK_IDS_GBY_REASON": task_ids_gby_reason,
}
| # -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-节点管理(BlueKing-BK-NODEMAN) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at https://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
import logging
from collections import defaultdict
from celery.task import periodic_task
from django.db import transaction
from django.db.models import Q
from apps.node_man import constants, models
logger = logging.getLogger("celery")
@periodic_task(
run_every=constants.COLLECT_AUTO_TRIGGER_JOB_INTERVAL,
queue="backend", # 这个是用来在代码调用中指定队列的,例如: update_subscription_instances.delay()
options={"queue": "backend"}, # 这个是用来celery beat调度指定队列的
)
def collect_auto_trigger_job():
last_sub_task_id = models.GlobalSettings.get_config(models.GlobalSettings.KeyEnum.LAST_SUB_TASK_ID.value, None)
not_ready_task_info_map = models.GlobalSettings.get_config(
models.GlobalSettings.KeyEnum.NOT_READY_TASK_INFO_MAP.value, None
)
if last_sub_task_id is None:
last_sub_task_id = 0
models.GlobalSettings.set_config(models.GlobalSettings.KeyEnum.LAST_SUB_TASK_ID.value, last_sub_task_id)
if not_ready_task_info_map is None:
not_ready_task_info_map = {}
models.GlobalSettings.set_config(models.GlobalSettings.KeyEnum.NOT_READY_TASK_INFO_MAP.value, {})
not_ready_task_ids = list(int(not_ready_task_id_str) for not_ready_task_id_str in not_ready_task_info_map.keys())
all_auto_task_infos = models.SubscriptionTask.objects.filter(
Q(id__gt=last_sub_task_id) | Q(id__in=not_ready_task_ids), is_auto_trigger=True
).values("subscription_id", "id", "is_ready", "err_msg")
# 找出归属SaaS侧的订阅ID列表
subscription_ids = set(
models.Job.objects.filter(
is_auto_trigger=False,
subscription_id__in={auto_task_info["subscription_id"] for auto_task_info in all_auto_task_infos},
).values_list("subscription_id", flat=True)
)
subscriptions = models.Subscription.objects.filter(id__in=subscription_ids).values("id", "bk_biz_scope")
# 过滤非SaaS侧策略自动触发的订阅任务
auto_task_infos = [
auto_task_info
for auto_task_info in all_auto_task_infos
if auto_task_info["subscription_id"] in subscription_ids
]
logger.info(
f"collect_auto_trigger_job: auto_task_ids -> {[auto_task_info['id'] for auto_task_info in auto_task_infos]}"
)
# 考虑一个订阅中有多个自动触发task的情况
task_ids_gby_sub_id = defaultdict(list)
task_ids_gby_reason = {"NOT_READY": [], "READY": [], "ERROR": []}
for task_info in auto_task_infos:
# is_ready=False并且无错误信息时,该订阅任务仍处于创建状态
if not task_info["is_ready"]:
task_ids_gby_reason["ERROR" if task_info["err_msg"] else "NOT_READY"].append(task_info["id"])
continue
# 仅同步成功创建的的订阅任务
task_ids_gby_reason["READY"].append(task_info["id"])
task_ids_gby_sub_id[task_info["subscription_id"]].append(task_info["id"])
logger.info(
f"collect_auto_trigger_job: last_sub_task_id -> {last_sub_task_id}, "
f"task_ids_gby_reason -> {task_ids_gby_reason}, begin"
)
auto_jobs_to_be_created = []
for subscription in subscriptions:
# 任务未就绪或创建失败,跳过
if subscription["id"] not in task_ids_gby_sub_id:
continue
auto_jobs_to_be_created.append(
models.Job(
# 巡检的任务类型为安装
job_type=constants.JobType.MAIN_INSTALL_PLUGIN,
bk_biz_scope=subscription["bk_biz_scope"],
subscription_id=subscription["id"],
# 依赖calculate_statistics定时更新状态及实例状态统计
status=constants.JobStatusType.RUNNING,
statistics={f"{k}_count": 0 for k in ["success", "failed", "pending", "running", "total"]},
error_hosts=[],
created_by="admin",
# TODO 将历史多个自动触发task先行整合到一个job,后续根据实际情况考虑是否拆分
task_id_list=task_ids_gby_sub_id[subscription["id"]],
is_auto_trigger=True,
)
)
# 上一次未就绪在本次同步中已有结果,从未就绪记录中移除
for task_id in task_ids_gby_reason["READY"] + task_ids_gby_reason["ERROR"]:
# global setting 会将key转为str类型,在统计时也将整数转为str,保证统计准确
task_id = str(task_id)
not_ready_task_info_map.pop(task_id, None)
# 异步创建失败(ERROR)的任务无需同步,NOT_READY 的任务先行记录,若上一次的未就绪任务仍未就绪,重试次数+1
for task_id in task_ids_gby_reason["NOT_READY"]:
task_id = str(task_id)
not_ready_task_info_map[task_id] = not_ready_task_info_map.get(task_id, 0) + 1
# 指针后移至已完成同步id的最大值,若本轮无同步数据,指针位置不变
all_task_ids = {auto_task_info["id"] for auto_task_info in auto_task_infos}
# 仅统计新增task_id,防止指针回退
new_add_task_ids = all_task_ids - set(not_ready_task_ids)
last_sub_task_id = max(new_add_task_ids or [last_sub_task_id])
with transaction.atomic():
models.Job.objects.bulk_create(auto_jobs_to_be_created)
models.GlobalSettings.update_config(models.GlobalSettings.KeyEnum.LAST_SUB_TASK_ID.value, last_sub_task_id)
models.GlobalSettings.update_config(
models.GlobalSettings.KeyEnum.NOT_READY_TASK_INFO_MAP.value, not_ready_task_info_map
)
logger.info(
f"collect_auto_trigger_job: {models.GlobalSettings.KeyEnum.LAST_SUB_TASK_ID.value} -> {last_sub_task_id}, "
f"{models.GlobalSettings.KeyEnum.NOT_READY_TASK_INFO_MAP.value} -> {not_ready_task_info_map}"
)
return {
models.GlobalSettings.KeyEnum.LAST_SUB_TASK_ID.value: last_sub_task_id,
models.GlobalSettings.KeyEnum.NOT_READY_TASK_INFO_MAP.value: not_ready_task_info_map,
"TASK_IDS_GBY_REASON": task_ids_gby_reason,
}
|
import os
import time
import fero
from fero import FeroError
from typing import Optional, Union
from marshmallow import (
Schema,
fields,
validate,
EXCLUDE,
)
from .common import FeroObject
class DataSourceSchema(Schema):
class Meta:
unknown = EXCLUDE
uuid = fields.UUID(required=True)
primary_key_column = fields.String(required=True, allow_none=True)
primary_datetime_column = fields.String(required=True, allow_none=True)
schema = fields.Dict(required=True, allow_none=True)
name = fields.String(required=True)
description = fields.String(required=True)
created = fields.DateTime(required=True)
modified = fields.DateTime(required=True)
ac_name = fields.String(required=True)
username = fields.String(required=True)
INITIALIZED = "I"
PROCESSING = "P"
LOADING_FILE = "L"
ANALYZING_FILE = "A"
WRITING_FILE = "W"
COMPRESSING_TABLE = "C"
READY = "R"
ERROR = "E"
status = fields.String(
validate=validate.OneOf(["I", "P", "L", "A", "W", "C", "R", "E"]), required=True
)
error_notices = fields.Dict(required=True, default=lambda: {"errors": []})
progress = fields.Integer(required=True, default=0)
overwrites = fields.Dict(required=True, allow_none=True)
transformed_source = fields.Bool(required=True, default=False)
live_source = fields.Bool(required=True, default=False)
default_upload_config = fields.Dict(required=False)
class DataSource(FeroObject):
schema_class = DataSourceSchema
def __getattr__(self, name: str):
return self._data.get(name)
def __repr__(self):
return f"<Data Source name={self.name}>"
__str__ = __repr__
def append_csv(self, file_path: str, wait_until_complete: bool = False):
"""Appends a specified csv file to the data source.
:param file_path: Location of the csv file to append
:type file_path: str
:raises FeroError: Raised if the file does not match a naive csv check
"""
if not file_path.endswith(".csv"):
raise FeroError("Fero only supports csv appends")
file_name = os.path.basename(file_path)
inbox_response = self._client.post(
f"/api/v2/data_source/{self.uuid}/inbox_url/",
{"file_name": file_name, "action": "A"},
)
with open(file_path) as fp:
self._client.upload_file(inbox_response, file_name, fp)
upload_status = UploadedFileStatus(self._client, inbox_response["upload_uuid"])
return (
upload_status.wait_until_complete()
if wait_until_complete
else upload_status
)
def replace_csv(self, file_path: str, wait_until_complete: bool = False):
"""Appends a specified csv file to the data source.
:param file_path: Location of the csv file to append
:type file_path: str
:raises FeroError: Raised if the file does not match a naive csv check
"""
if not file_path.endswith(".csv"):
raise FeroError("Fero only supports csv appends")
file_name = os.path.basename(file_path)
inbox_response = self._client.post(
f"/api/v2/data_source/{self.uuid}/inbox_url/",
{"file_name": file_name, "action": "R"},
)
with open(file_path) as fp:
self._client.upload_file(inbox_response, file_name, fp)
upload_status = UploadedFileStatus(self._client, inbox_response["upload_uuid"])
return (
upload_status.wait_until_complete()
if wait_until_complete
else upload_status
)
class UploadedFilesSchema(Schema):
class Meta:
unknown = EXCLUDE
uuid = fields.UUID(required=True)
INITIALIZED = "I"
PARSING = "P"
ANALYZING = "A"
CREATING = "C"
ERROR = "E"
DONE = "D"
DELETING = "R" # R for removing
USER_CONFIRMATION = "U"
status = fields.String(
validate=validate.OneOf(["I", "P", "A", "C", "R", "D", "E", "U"]), required=True
)
error_notices = fields.Dict(
required=True, default=lambda: {"global_notices": [], "parsing_notices": []}
)
class UploadedFileStatus:
def __init__(self, client: "fero.Fero", id: str):
self._id = id
self._client = client
self._status_data = None
self._schema = UploadedFilesSchema()
@staticmethod
def _check_status_complete(status: Optional[dict]) -> bool:
"""Checks status of the latest uploaded file response.
Returns true if complete, false if not complete and raises an error if the status is error.
"""
if status is None or status["status"] not in [
UploadedFilesSchema.ERROR,
UploadedFilesSchema.DONE,
]:
return False
if status["status"] == UploadedFilesSchema.ERROR:
errors = [
f'"{str(e)}"'
for e in status["error_notices"]["global_notices"]
+ status["error_notices"]["parsing_notices"]
]
error_message = f"Unable to upload file. The following error(s) occurred: {", ".join(errors)}"
raise FeroError(error_message)
return True
def get_upload_status(self) -> Union[dict, None]:
"""Gets current status of the uploaded files object
:return: True if file upload is completely processed, false if still processing
:rtype: Union[dict, None]
:raises FeroError: Raised if fero was unable to process the file
"""
raw_data = self._client.get(
f"/api/v2/uploaded_files/{self._id}/", allow_404=True
)
data = None
if raw_data is not None:
data = self._schema.load(raw_data)
return data
def wait_until_complete(self) -> "UploadedFileStatus":
status = self.get_upload_status()
while not self._check_status_complete(status):
time.sleep(0.5)
status = self.get_upload_status()
return self
| import os
import time
import fero
from fero import FeroError
from typing import Optional, Union
from marshmallow import (
Schema,
fields,
validate,
EXCLUDE,
)
from .common import FeroObject
class DataSourceSchema(Schema):
class Meta:
unknown = EXCLUDE
uuid = fields.UUID(required=True)
primary_key_column = fields.String(required=True, allow_none=True)
primary_datetime_column = fields.String(required=True, allow_none=True)
schema = fields.Dict(required=True, allow_none=True)
name = fields.String(required=True)
description = fields.String(required=True)
created = fields.DateTime(required=True)
modified = fields.DateTime(required=True)
ac_name = fields.String(required=True)
username = fields.String(required=True)
INITIALIZED = "I"
PROCESSING = "P"
LOADING_FILE = "L"
ANALYZING_FILE = "A"
WRITING_FILE = "W"
COMPRESSING_TABLE = "C"
READY = "R"
ERROR = "E"
status = fields.String(
validate=validate.OneOf(["I", "P", "L", "A", "W", "C", "R", "E"]), required=True
)
error_notices = fields.Dict(required=True, default=lambda: {"errors": []})
progress = fields.Integer(required=True, default=0)
overwrites = fields.Dict(required=True, allow_none=True)
transformed_source = fields.Bool(required=True, default=False)
live_source = fields.Bool(required=True, default=False)
default_upload_config = fields.Dict(required=False)
class DataSource(FeroObject):
schema_class = DataSourceSchema
def __getattr__(self, name: str):
return self._data.get(name)
def __repr__(self):
return f"<Data Source name={self.name}>"
__str__ = __repr__
def append_csv(self, file_path: str, wait_until_complete: bool = False):
"""Appends a specified csv file to the data source.
:param file_path: Location of the csv file to append
:type file_path: str
:raises FeroError: Raised if the file does not match a naive csv check
"""
if not file_path.endswith(".csv"):
raise FeroError("Fero only supports csv appends")
file_name = os.path.basename(file_path)
inbox_response = self._client.post(
f"/api/v2/data_source/{self.uuid}/inbox_url/",
{"file_name": file_name, "action": "A"},
)
with open(file_path) as fp:
self._client.upload_file(inbox_response, file_name, fp)
upload_status = UploadedFileStatus(self._client, inbox_response["upload_uuid"])
return (
upload_status.wait_until_complete()
if wait_until_complete
else upload_status
)
def replace_csv(self, file_path: str, wait_until_complete: bool = False):
"""Appends a specified csv file to the data source.
:param file_path: Location of the csv file to append
:type file_path: str
:raises FeroError: Raised if the file does not match a naive csv check
"""
if not file_path.endswith(".csv"):
raise FeroError("Fero only supports csv appends")
file_name = os.path.basename(file_path)
inbox_response = self._client.post(
f"/api/v2/data_source/{self.uuid}/inbox_url/",
{"file_name": file_name, "action": "R"},
)
with open(file_path) as fp:
self._client.upload_file(inbox_response, file_name, fp)
upload_status = UploadedFileStatus(self._client, inbox_response["upload_uuid"])
return (
upload_status.wait_until_complete()
if wait_until_complete
else upload_status
)
class UploadedFilesSchema(Schema):
class Meta:
unknown = EXCLUDE
uuid = fields.UUID(required=True)
INITIALIZED = "I"
PARSING = "P"
ANALYZING = "A"
CREATING = "C"
ERROR = "E"
DONE = "D"
DELETING = "R" # R for removing
USER_CONFIRMATION = "U"
status = fields.String(
validate=validate.OneOf(["I", "P", "A", "C", "R", "D", "E", "U"]), required=True
)
error_notices = fields.Dict(
required=True, default=lambda: {"global_notices": [], "parsing_notices": []}
)
class UploadedFileStatus:
def __init__(self, client: "fero.Fero", id: str):
self._id = id
self._client = client
self._status_data = None
self._schema = UploadedFilesSchema()
@staticmethod
def _check_status_complete(status: Optional[dict]) -> bool:
"""Checks status of the latest uploaded file response.
Returns true if complete, false if not complete and raises an error if the status is error.
"""
if status is None or status["status"] not in [
UploadedFilesSchema.ERROR,
UploadedFilesSchema.DONE,
]:
return False
if status["status"] == UploadedFilesSchema.ERROR:
errors = [
f'"{str(e)}"'
for e in status["error_notices"]["global_notices"]
+ status["error_notices"]["parsing_notices"]
]
error_message = f"Unable to upload file. The following error(s) occurred: {', '.join(errors)}"
raise FeroError(error_message)
return True
def get_upload_status(self) -> Union[dict, None]:
"""Gets current status of the uploaded files object
:return: True if file upload is completely processed, false if still processing
:rtype: Union[dict, None]
:raises FeroError: Raised if fero was unable to process the file
"""
raw_data = self._client.get(
f"/api/v2/uploaded_files/{self._id}/", allow_404=True
)
data = None
if raw_data is not None:
data = self._schema.load(raw_data)
return data
def wait_until_complete(self) -> "UploadedFileStatus":
status = self.get_upload_status()
while not self._check_status_complete(status):
time.sleep(0.5)
status = self.get_upload_status()
return self
|
from custom_components.xiaomi_cloud_map_extractor.common.vacuum import XiaomiCloudVacuum
class XiaomiCloudVacuumV2(XiaomiCloudVacuum):
def __init__(self, connector, country, user_id, device_id, model):
super().__init__(connector, country, user_id, device_id, model)
def get_map_url(self, map_name):
url = self._connector.get_api_url(self._country) + '/v2/home/get_interim_file_url'
params = {
"data": f'{{'obj_name':'{self._user_id}/{self._device_id}/{map_name}"}}'
}
api_response = self._connector.execute_api_call(url, params)
if api_response is None or "result" not in api_response or "url" not in api_response["result"]:
return None
return api_response["result"]["url"]
def should_get_map_from_vacuum(self):
return False
| from custom_components.xiaomi_cloud_map_extractor.common.vacuum import XiaomiCloudVacuum
class XiaomiCloudVacuumV2(XiaomiCloudVacuum):
def __init__(self, connector, country, user_id, device_id, model):
super().__init__(connector, country, user_id, device_id, model)
def get_map_url(self, map_name):
url = self._connector.get_api_url(self._country) + '/v2/home/get_interim_file_url'
params = {
"data": f'{{"obj_name":"{self._user_id}/{self._device_id}/{map_name}"}}'
}
api_response = self._connector.execute_api_call(url, params)
if api_response is None or "result" not in api_response or "url" not in api_response["result"]:
return None
return api_response["result"]["url"]
def should_get_map_from_vacuum(self):
return False
|
# BSD 3-Clause License
# Copyright (c) 2019-2021, engageLively
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import gviz_api
import pandas as pd
from galyleo.galyleo_constants import GALYLEO_SCHEMA_TYPES
import numpy
from galyleo.galyleo_constants import GALYLEO_STRING, GALYLEO_NUMBER, GALYLEO_BOOLEAN, GALYLEO_DATE, GALYLEO_DATETIME, GALYLEO_TIME_OF_DAY
from json import loads, dumps, JSONDecodeError
from galyleo.galyleo_exceptions import InvalidDataException
#
# Initialize with the table name
#
class GalyleoTable:
'''
A Galyleo Dashboard Table. Used to create a Galyleo Dashboard Table from any of a number of sources, and then generate an object that is suitable
for storage (as a JSON file). A GalyleoTable is very similar to a Google Visualization data table, and can be
converted to a Google Visualization Data Table on either the Python or the JavaScript side.
Convenience routines provided here to import data from pandas, and json format.
'''
def __init__(self, name:str):
"""
The DashboardTable Class. Sets the schema and data to be empty, and the name to be name
Args:
name (str): The nameo of the table
"""
self.name = name
self.schema = []
self.data = []
def equal(self, table, names_must_match = False):
"""
Test to see if this table is equal to another table, passed as
an argument. Two tables are equal if their schemas are the same
length and column names and types match, and if the data is the same,
and in the same order. If names_must_match == True (default is False),
then the names must also match
Args:
table (GalyleoTable): table to be checked for equality
names_must_match (bool): (default False) if True, table names must also match
Returns:
True if equal, False otherwise
"""
if (len(self.schema) != len(table.schema)):
return False
if (len(self.data) != len(table.data)):
return False
for i in range(len(self.schema)):
if (self.schema[i] != table.schema[i]):
return False
for i in range(len(self.data)):
if (self.data[i] != table.data[i]):
return False
if names_must_match:
return self.name == table.name
return True
#
# Check that a schema expressed as a list of tuples (name, type)
# matches a list of rows given as data. We let gviz_api do teh
# checking for us.
# Schema is a list of pairs [(<column_name>, <column_type>)]
# where column_type is one of GALYLEO_STRING, GALYLEO_NUMBER, GALYLEO_BOOLEAN,
# GALYLEO_DATE, GALYLEO_DATETIME, GALYLEO_TIME_OF_DAY. All of these are defined
# in galyleoconstants. data is a list of lists, where each list is a row of
# the table. Two conditions:
# (1) Each type must be one of types listed above
# (2) Each list in data must have the same length as the schema, and the type of each
# element must match the corresponding schema type
# throws an InvalidDataException if either of these are violeated
# parameters:
# schema: the schema as a list of pairs
# data: the data as a list of lists
#
def _check_schema_match(self, schema, data):
for row in data:
if (len(row) != len(schema)):
raise InvalidDataException(f"All rows must have length {len(schema)}")
try:
table = gviz_api.DataTable(schema)
table.LoadData(data)
table.ToJSon()
except gviz_api.DataTableException as schema_error:
raise InvalidDataException(schema_error)
def load_from_schema_and_data(self, schema:list, data:list):
"""
Load from a pair (schema, data).
Schema is a list of pairs [(<column_name>, <column_type>)]
where column_type is one of the Galyleo types (GALYLEO_STRING, GALYLEO_NUMBER, GALYLEO_BOOLEAN,
GALYLEO_DATE, GALYLEO_DATETIME, GALYLEO_TIME_OF_DAY). All of these are defined
in galyleo_constants. data is a list of lists, where each list is a row of
the table. Two conditions:
(1) Each type must be one of types listed above
(2) Each list in data must have the same length as the schema, and the type of each
element must match the corresponding schema type
throws an InvalidDataException if either of these are violated
Args:
schema (list of pairs, (name, type)): the schema as a list of pairs
data (list of lists): the data as a list of lists
"""
self._check_schema_match(schema, data)
self.schema = [{"name": record[0], "type": record[1]} for record in schema]
self.data = data # should I clone?
#
# An internal routine used to map a Pandas or Numpy type to a Galyleo
# type: mostly this involves mapping one of Numpy's many number types
# to GALYLEO_NUMBER. Used by load_from_dataframe. If a type is unrecognized
# it maps to GALYLEO_STRING
# parameters:
# dtype: a Numpy or Pandas primitive type
# returns: a Galyleo type
#
def _match_type(self, dtype):
type_map = {
GALYLEO_BOOLEAN: [numpy.bool_],
GALYLEO_NUMBER:[ numpy.byte, numpy.ubyte, numpy.short, numpy.ushort, numpy.intc, numpy.uintc, numpy.int_, numpy.uint, numpy.longlong, numpy.ulonglong, numpy.float16, numpy.single, numpy.double, numpy.longdouble, numpy.csingle, numpy.cdouble, numpy.clongdouble]
}
for galyleo_type in type_map.keys():
if dtype in type_map[galyleo_type]:
return galyleo_type
return GALYLEO_STRING
def load_from_dataframe(self, dataframe, schema = None):
"""
Load from a Pandas Dataframe. The schema is given in the optional second parameter,
as a list of records {"name": <name>, "type": <type>}, where type is a Galyleo type. (GALYLEO_STRING, GALYLEO_NUMBER, GALYLEO_BOOLEAN,
GALYLEO_DATE, GALYLEO_DATETIME, GALYLEO_TIME_OF_DAY).
If the second parameter is not present, the schema is derived from the name and
column types of the dataframe, and each row of the dataframe becomes a row
of the table.
Args:
dataframe (pandas dataframe): the pandas dataframe to load from
schema (list of dictionaries): if present, the schema in list of dictionary form; each dictionary is of the form {"name": <column name>, "type": <column type>}
"""
if schema:
self.schema = schema
else:
given_types = dataframe.dtypes
galyleo_types = [self._match_type(dtype) for dtype in given_types]
names = dataframe.columns
self.schema = [{"name": names[i], "type": galyleo_types[i]} for i in range(len(names))]
rows = [r for r in dataframe.iterrows()]
self.data = [r[1].tolist() for r in rows]
def as_dictionary(self):
"""
Return the form of the table as a dictionary. This is a dictionary
of the form:
{"name": <table_name>,"table": <table_struct>}
where table_struct is of the form:
{"columns": [<list of schema records],"rows": [<list of rows of the table>]}
A schema record is a record of the form:
{"name": < column_name>, "type": <column_type}, where type is one of the
Galyleo types (GALYLEO_STRING, GALYLEO_NUMBER, GALYLEO_BOOLEAN,
GALYLEO_DATE, GALYLEO_DATETIME, GALYLEO_TIME_OF_DAY). All of these are defined
in galyleo_constants.
Args:
None
Returns:
{"name": <table_name>, "table": {"columns": <list of schema records], "rows": [<list of rows of the table>]}}
"""
return {"name": self.name, "table": {"columns": self.schema, "rows": self.data}}
def load_from_dictionary(self, dict):
"""
load data from a dictionary of the form: {"columns": [<list of schema records], "rows": [<list of rows of the table>]}
A schema record is a record of the form:
{"name": < column_name>, "type": <column_type}, where type is one of the
Galyleo types (GALYLEO_STRING, GALYLEO_NUMBER, GALYLEO_BOOLEAN,
GALYLEO_DATE, GALYLEO_DATETIME, GALYLEO_TIME_OF_DAY).
Throws InvalidDataException if the dictionary is of the wrong format
or the rows don't match the columns.
Args:
dict: the table as a dictionary (a value returned by as_dictionary)
Throws:
InvalidDataException if dict is malformed
"""
self._check_fields(dict, {"columns", "rows"}, 'JSON table descriptor')
columns = dict["columns"]
for column in columns:
self._check_fields(column, {"name", "type"}, "Column description")
schema = [(record["name"], record["type"]) for record in columns]
self._check_schema_match(schema, dict["rows"])
self.schema = columns
self.data = dict["rows"]
def to_json(self):
"""
Return the table as a JSON string, suitable for transmitting as a message
or saving to a file. This is just a JSON form of the dictionary form of
the string. (See as_dictionary)
Returns:
as_dictionary() as a JSON string
"""
return dumps(self.as_dictionary())
#
# A utility to check if a dictionary contains all required keys
# Raises an InvalidDataException if any are missing, with the
# appropriate error message
# parameters:
# record: the record (dictionary) to be checked
# required_fields: the fields that must be in the record
# message_header: the phrase that must be in the message
#
def _check_fields(self, record, required_fields, message_header):
fields = set(record.keys())
if (not fields.issuperset(required_fields)):
raise InvalidDataException(f'{message_header} is missing fields {required_fields - fields}')
def from_json(self, json_form, overwrite_name = True):
"""
Load the table from a JSON string, of the form produced by toJSON(). Note
that if the overwrite_name parameter = True (the default), this will also
overwrite the table name.
Throws InvalidDataException id json_form is malformed
Args:
json_form: A JSON form of the Dictionary
Returns:
None
Throws:
InvalidDataException if json_form is malformed
"""
try:
record = loads(json_form)
except JSONDecodeError(msg):
raise InvalidDataException(msg)
if (type(record) != dict):
raise InvalidDataException(f'JSON form of table must be a dictionary, not {type(record)}')
self._check_fields(record, {"name", "table"}, 'JSON form of table')
self.load_from_dictionary(record["table"])
if (overwrite_name):
self.name = record["name"]
def aggregate_by(self, aggregate_column_names, new_column_name = "count", new_table_name = None):
"""
Create a new table by aggregating over multiple columns. The resulting table
contains the aggregate column names and the new column name, and for each
unique combination of values among the aggregate column names, the count of rows in this
table with that unique combination of values.
The new table will have name new_table_name
Throws an InvalidDataException if aggregate_column_names is not a subset of the names in self.schema
Args:
aggregate_column_names: names of the columns to aggregate over
new_column_name: name of the column for the aggregate count. Defaults to count
new_table_name: name of the new table. If omitted, defaults to None, in which case a name will be generated
Returns:
A new table with name new_table_name, or a generated name if new_table_name == None
Throws:
InvalidDataException if one of the column names is missing
"""
if (aggregate_column_names == None or len(aggregate_column_names) == 0):
raise InvalidDataException('No columns specified for aggregation')
column_names = set(aggregate_column_names)
columns = [entry for entry in self.schema if entry["name"] in column_names]
if (len(aggregate_column_names) != len(columns)):
# We have a missing column. Find it and throw the InvalidDataException
current_columns = set([entry["name"] for entry in columns])
missing_columns = column_names - current_columns
raise InvalidDataException(f'Columns {missing_columns} are not present in the schema')
# Make a table name
if (new_table_name == None):
letters = [name[0] for name in aggregate_column_names]
new_table_name = 'aggregate_' + ''.join([name[0] for name in aggregate_column_names])
# Collect the indices of the requested columns
indices = [i for i in range(len(self.schema)) if self.schema[i]["name"] in column_names]
# Collect the columns for each row, making each short_row a tuple so they can be
# indexed in a set
simple_keys = len(indices) == 1
if simple_keys:
short_rows = [row[indices[0]] for row in self.data]
else:
short_rows = [tuple([row[i] for i in indices]) for row in self.data]
keys = set(short_rows)
# Now that we have the unique keys, count the number of instances of each
count = {}
for key in keys: count[key] = 0
for key in short_rows: count[key] = count[key] + 1
# convert the keys from tuples to lists, add the count for each one, and
# filter out the 0's
data = []
for key in keys:
key_as_list = [key] if simple_keys else list(key)
data.append(key_as_list + [count[key]])
data = [row for row in data if row[-1] > 0]
# The schema is just the requested columns + new_column_name, and the type
# of new_column_name is a number. Then create the result table, load in the
# schema and data, and quit.
schema = columns[:] + [{"name": new_column_name, "type": GALYLEO_NUMBER}]
table = GalyleoTable(new_table_name)
table.load_from_dictionary({"columns": schema, "rows": data})
return table
def filter_by_function(self, column_name, function, new_table_name, column_types = {}):
'''
Create a new table, with name table_name, with rows such that
function(row[column_name]) == True. The new table will have
columns {self.columns} - {column_name}, same types, and same order
Throws an InvalidDataException if:
1. new_table_name is None or not a string
2. column_name is not a name of an existing column
3. if column_types is not empty, the type of the selected column doesn't match one of the allowed types
Args:
column_name: the column to filter by
function: a Boolean function with a single argument of the type of columns[column_name]
new_table_name: name of the new table
column_types: set of the allowed column types; if empty, any type is permitted
Returns:
A table with column[column_name] missing and filtered
Throws:
InvalidDataException if new_table_name is empty, column_name is not a name of an existing column, or the type of column_name isn't in column_types (if column_types is non-empty)
'''
if (not new_table_name ):
raise InvalidDataException('new_table_name cannot be empty')
if (not column_name):
raise InvalidDataException('column_name cannot be empty')
indices = [i for i in range(len(self.schema)) if self.schema[i]["name"] == column_name]
if (len(indices) == 0):
raise InvalidDataException(f'Column {column_name} not found in schema')
index = indices[0]
if (column_types):
if (not self.schema[index]["type"] in column_types):
raise InvalidDataException(f'Type {self.schema[index]['type']} not found in {column_types}')
data = [row[:index] + row[index+1:] for row in self.data if function(row[index])]
schema = self.schema[:index] + self.schema[index+1:]
result = GalyleoTable(new_table_name)
result.load_from_dictionary({"columns": schema, "rows": data})
return result
def filter_equal(self, column_name, value, new_table_name, column_types):
'''
A convenience method over filter_by_function. This is identical to
filter_by_function(column_name, lambda x: x == value, new_table_name, column_types)
Args:
column_name: the column to filter by
value: the value to march for equality
new_table_name: name of the new table
column_types: set of the allowed column types; if empty, any type is permitted
Returns:
A table with column[column_name] missing and filtered
Throws:
InvalidDataException if new_table_name is empty, column_name is not a name of an existing column, or the type of column_name isn't in column_types (if column_types is non-empty)
'''
return self.filter_by_function(column_name, lambda x: x == value, new_table_name, column_types)
def filter_range(self, column_name, range_as_tuple, new_table_name, column_types):
'''
A convenience method over filter_by_function. This is identical to
filter_by_function(column_name, lambda x: x >= range_as_tuple[0], x <= range_as_tuple[1], new_table_name, column_types)
Args:
column_name: the column to filter by
range_as_tupe: the tuple representing the range
new_table_name: name of the new table
column_types: set of the allowed column types; if empty, any type is permitted
Returns:
A table with column[column_name] missing and filtered
Throws:
InvalidDataException if new_table_name is empty, column_name is not a name of an existing column, or the type of column_name isn't in column_types (if column_types is non-empty), if len(range_as_tuple) != 2
'''
try:
assert(range_as_tuple and len(range_as_tuple) == 2)
except Exception:
raise InvalidDataException(f'{range_as_tuple} should be a tuple of length 2')
return self.filter_by_function(column_name, lambda x: x <= range_as_tuple[1] and x >= range_as_tuple[0], new_table_name, column_types)
#
# A utility to get the index of a column, given a name. Raises an InvalidDataException
# is no such column in the schema
#
# Args:
# column_name: name of the column
#
# Returns:
# index of the column
#
# Throws:
# InvalidDataException if there is no such column
#
def _get_column_index(self, column_name):
indices = [i for i in range(len(self.schema)) if self.schema[i]["name"] == column_name]
if (len(indices) == 0):
raise InvalidDataException(f'Column {column_name} is not in the schema')
return indices[0]
def pivot_on_column(self, pivot_column_name, value_column_name, new_table_name, pivot_column_values = {}, other_column = False):
'''
The pivot_on_column method breaks out value_column into n separate columns, one for each
member of pivot_column_values plus (if other_column = True), an "Other" column. This is easiest to see with an example. Consider a table with columns (Year, State, Party, Percentage). pivot_on_column('Party', {'Republican', 'Democratic'}, 'Percentage', 'pivot_table', False) would create a new table with columns Year, State, Republican, Democratic, where the values in the Republican and Democratic columns are the values in the Percentage column where the Party column value was Republican or Democratic, respectively. If Other = True, an additional column, Other, is found where the value is (generally) the sum of values where Party not equal Republican or Democratic
Args:
pivot_column_name: the column holding the keys to pivot on
value_column_name: the column holding the values to spread out over the pivots
new_table_name: name of the new table
pivot_column_values: the values to pivot on. If empty, all values used
other_column: if True, aggregate other values into a column
Returns:
A table as described in the comments above
Throws:
InvalidDataException if new_table_name is empty, pivot_column_name is not a name of an existing column, or value_column_name is not the name of an existing column
'''
names = [(new_table_name, 'new_table_name'), (pivot_column_name, 'pivot_column_name'), (value_column_name, 'value_column_name')]
for name in names:
if (not name[0]):
raise InvalidDataException(f'{name[1]} cannot be empty')
if (value_column_name == pivot_column_name):
raise InvalidDataException(f'Pivot and value columns cannot be identical: both are {value_column_name}')
value_column_index = self._get_column_index(value_column_name)
pivot_column_index = self._get_column_index(pivot_column_name)
key_columns = list(set(range(len(self.schema))) - {value_column_index, pivot_column_index})
key_columns.sort()
# Split each row into a dict:
# key (value of the other columns). Note this is a tuple so it can index a set
# pivot_value: value of the pivot column
# value: value of the value column
def make_record(row):
return {
"key": tuple([row[i] for i in key_columns]),
"pivot": row[pivot_column_index],
"value": row[value_column_index]
}
partition = [make_record(row) for row in self.data]
# get the set of all distinct keys
keys = set([record["key"] for record in partition])
# get the distinct values of the pivot column
pivot_value_set = set([record["pivot"] for record in partition])
# Note whether we will have an "Other" column. We will when:
# (a) other_column = True AND
# (b) pivot_column_values is not empty AND
# (c) there are columns in pivot_value_set - pivot_column_values
other_columns = pivot_value_set - pivot_column_values if pivot_column_values else {}
use_other = other_column and other_columns
if (pivot_column_values):
pivot_value_set = pivot_value_set.intersection(pivot_column_values)
value_column_type = self.schema[value_column_index]["type"]
def new_pivot_record():
initial_value = 0 if value_column_type == GALYLEO_NUMBER else None
result = {}
for name in pivot_value_set: result[name] = initial_value
result["Other"] = initial_value
return result
# set up the dictionary
pivot_records = {}
for key in keys: pivot_records[key] = new_pivot_record()
for record in partition:
pivot = record["pivot"]
if (pivot in pivot_value_set): pivot_records[key][pivot] = record["value"]
else: pivot_records[key]["Other"] = record["value"] + pivot_records[key]["Other"]
# Now just create and return the new table
new_schema = [self.schema[i] for i in key_columns]
pivot_schema = [{"name": name, "type": value_column_type} for name in pivot_value_set]
if (use_other):
pivot_schema.append({"name": "Other", "type": value_column_type})
def make_record(key_value):
result = list(key_value)
record = pivot_records[key_value]
values = [record[pivot] for pivot in pivot_value_set]
if (use_other): values.append(record["Other"])
return result + values
data = [make_record(key) for key in pivot_records]
result = GalyleoTable(new_table_name)
result.load_from_dictionary({"columns": new_schema + pivot_schema, "rows": data})
return result
| # BSD 3-Clause License
# Copyright (c) 2019-2021, engageLively
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import gviz_api
import pandas as pd
from galyleo.galyleo_constants import GALYLEO_SCHEMA_TYPES
import numpy
from galyleo.galyleo_constants import GALYLEO_STRING, GALYLEO_NUMBER, GALYLEO_BOOLEAN, GALYLEO_DATE, GALYLEO_DATETIME, GALYLEO_TIME_OF_DAY
from json import loads, dumps, JSONDecodeError
from galyleo.galyleo_exceptions import InvalidDataException
#
# Initialize with the table name
#
class GalyleoTable:
'''
A Galyleo Dashboard Table. Used to create a Galyleo Dashboard Table from any of a number of sources, and then generate an object that is suitable
for storage (as a JSON file). A GalyleoTable is very similar to a Google Visualization data table, and can be
converted to a Google Visualization Data Table on either the Python or the JavaScript side.
Convenience routines provided here to import data from pandas, and json format.
'''
def __init__(self, name:str):
"""
The DashboardTable Class. Sets the schema and data to be empty, and the name to be name
Args:
name (str): The nameo of the table
"""
self.name = name
self.schema = []
self.data = []
def equal(self, table, names_must_match = False):
"""
Test to see if this table is equal to another table, passed as
an argument. Two tables are equal if their schemas are the same
length and column names and types match, and if the data is the same,
and in the same order. If names_must_match == True (default is False),
then the names must also match
Args:
table (GalyleoTable): table to be checked for equality
names_must_match (bool): (default False) if True, table names must also match
Returns:
True if equal, False otherwise
"""
if (len(self.schema) != len(table.schema)):
return False
if (len(self.data) != len(table.data)):
return False
for i in range(len(self.schema)):
if (self.schema[i] != table.schema[i]):
return False
for i in range(len(self.data)):
if (self.data[i] != table.data[i]):
return False
if names_must_match:
return self.name == table.name
return True
#
# Check that a schema expressed as a list of tuples (name, type)
# matches a list of rows given as data. We let gviz_api do teh
# checking for us.
# Schema is a list of pairs [(<column_name>, <column_type>)]
# where column_type is one of GALYLEO_STRING, GALYLEO_NUMBER, GALYLEO_BOOLEAN,
# GALYLEO_DATE, GALYLEO_DATETIME, GALYLEO_TIME_OF_DAY. All of these are defined
# in galyleoconstants. data is a list of lists, where each list is a row of
# the table. Two conditions:
# (1) Each type must be one of types listed above
# (2) Each list in data must have the same length as the schema, and the type of each
# element must match the corresponding schema type
# throws an InvalidDataException if either of these are violeated
# parameters:
# schema: the schema as a list of pairs
# data: the data as a list of lists
#
def _check_schema_match(self, schema, data):
for row in data:
if (len(row) != len(schema)):
raise InvalidDataException(f"All rows must have length {len(schema)}")
try:
table = gviz_api.DataTable(schema)
table.LoadData(data)
table.ToJSon()
except gviz_api.DataTableException as schema_error:
raise InvalidDataException(schema_error)
def load_from_schema_and_data(self, schema:list, data:list):
"""
Load from a pair (schema, data).
Schema is a list of pairs [(<column_name>, <column_type>)]
where column_type is one of the Galyleo types (GALYLEO_STRING, GALYLEO_NUMBER, GALYLEO_BOOLEAN,
GALYLEO_DATE, GALYLEO_DATETIME, GALYLEO_TIME_OF_DAY). All of these are defined
in galyleo_constants. data is a list of lists, where each list is a row of
the table. Two conditions:
(1) Each type must be one of types listed above
(2) Each list in data must have the same length as the schema, and the type of each
element must match the corresponding schema type
throws an InvalidDataException if either of these are violated
Args:
schema (list of pairs, (name, type)): the schema as a list of pairs
data (list of lists): the data as a list of lists
"""
self._check_schema_match(schema, data)
self.schema = [{"name": record[0], "type": record[1]} for record in schema]
self.data = data # should I clone?
#
# An internal routine used to map a Pandas or Numpy type to a Galyleo
# type: mostly this involves mapping one of Numpy's many number types
# to GALYLEO_NUMBER. Used by load_from_dataframe. If a type is unrecognized
# it maps to GALYLEO_STRING
# parameters:
# dtype: a Numpy or Pandas primitive type
# returns: a Galyleo type
#
def _match_type(self, dtype):
type_map = {
GALYLEO_BOOLEAN: [numpy.bool_],
GALYLEO_NUMBER:[ numpy.byte, numpy.ubyte, numpy.short, numpy.ushort, numpy.intc, numpy.uintc, numpy.int_, numpy.uint, numpy.longlong, numpy.ulonglong, numpy.float16, numpy.single, numpy.double, numpy.longdouble, numpy.csingle, numpy.cdouble, numpy.clongdouble]
}
for galyleo_type in type_map.keys():
if dtype in type_map[galyleo_type]:
return galyleo_type
return GALYLEO_STRING
def load_from_dataframe(self, dataframe, schema = None):
"""
Load from a Pandas Dataframe. The schema is given in the optional second parameter,
as a list of records {"name": <name>, "type": <type>}, where type is a Galyleo type. (GALYLEO_STRING, GALYLEO_NUMBER, GALYLEO_BOOLEAN,
GALYLEO_DATE, GALYLEO_DATETIME, GALYLEO_TIME_OF_DAY).
If the second parameter is not present, the schema is derived from the name and
column types of the dataframe, and each row of the dataframe becomes a row
of the table.
Args:
dataframe (pandas dataframe): the pandas dataframe to load from
schema (list of dictionaries): if present, the schema in list of dictionary form; each dictionary is of the form {"name": <column name>, "type": <column type>}
"""
if schema:
self.schema = schema
else:
given_types = dataframe.dtypes
galyleo_types = [self._match_type(dtype) for dtype in given_types]
names = dataframe.columns
self.schema = [{"name": names[i], "type": galyleo_types[i]} for i in range(len(names))]
rows = [r for r in dataframe.iterrows()]
self.data = [r[1].tolist() for r in rows]
def as_dictionary(self):
"""
Return the form of the table as a dictionary. This is a dictionary
of the form:
{"name": <table_name>,"table": <table_struct>}
where table_struct is of the form:
{"columns": [<list of schema records],"rows": [<list of rows of the table>]}
A schema record is a record of the form:
{"name": < column_name>, "type": <column_type}, where type is one of the
Galyleo types (GALYLEO_STRING, GALYLEO_NUMBER, GALYLEO_BOOLEAN,
GALYLEO_DATE, GALYLEO_DATETIME, GALYLEO_TIME_OF_DAY). All of these are defined
in galyleo_constants.
Args:
None
Returns:
{"name": <table_name>, "table": {"columns": <list of schema records], "rows": [<list of rows of the table>]}}
"""
return {"name": self.name, "table": {"columns": self.schema, "rows": self.data}}
def load_from_dictionary(self, dict):
"""
load data from a dictionary of the form: {"columns": [<list of schema records], "rows": [<list of rows of the table>]}
A schema record is a record of the form:
{"name": < column_name>, "type": <column_type}, where type is one of the
Galyleo types (GALYLEO_STRING, GALYLEO_NUMBER, GALYLEO_BOOLEAN,
GALYLEO_DATE, GALYLEO_DATETIME, GALYLEO_TIME_OF_DAY).
Throws InvalidDataException if the dictionary is of the wrong format
or the rows don't match the columns.
Args:
dict: the table as a dictionary (a value returned by as_dictionary)
Throws:
InvalidDataException if dict is malformed
"""
self._check_fields(dict, {"columns", "rows"}, 'JSON table descriptor')
columns = dict["columns"]
for column in columns:
self._check_fields(column, {"name", "type"}, "Column description")
schema = [(record["name"], record["type"]) for record in columns]
self._check_schema_match(schema, dict["rows"])
self.schema = columns
self.data = dict["rows"]
def to_json(self):
"""
Return the table as a JSON string, suitable for transmitting as a message
or saving to a file. This is just a JSON form of the dictionary form of
the string. (See as_dictionary)
Returns:
as_dictionary() as a JSON string
"""
return dumps(self.as_dictionary())
#
# A utility to check if a dictionary contains all required keys
# Raises an InvalidDataException if any are missing, with the
# appropriate error message
# parameters:
# record: the record (dictionary) to be checked
# required_fields: the fields that must be in the record
# message_header: the phrase that must be in the message
#
def _check_fields(self, record, required_fields, message_header):
fields = set(record.keys())
if (not fields.issuperset(required_fields)):
raise InvalidDataException(f'{message_header} is missing fields {required_fields - fields}')
def from_json(self, json_form, overwrite_name = True):
"""
Load the table from a JSON string, of the form produced by toJSON(). Note
that if the overwrite_name parameter = True (the default), this will also
overwrite the table name.
Throws InvalidDataException id json_form is malformed
Args:
json_form: A JSON form of the Dictionary
Returns:
None
Throws:
InvalidDataException if json_form is malformed
"""
try:
record = loads(json_form)
except JSONDecodeError(msg):
raise InvalidDataException(msg)
if (type(record) != dict):
raise InvalidDataException(f'JSON form of table must be a dictionary, not {type(record)}')
self._check_fields(record, {"name", "table"}, 'JSON form of table')
self.load_from_dictionary(record["table"])
if (overwrite_name):
self.name = record["name"]
def aggregate_by(self, aggregate_column_names, new_column_name = "count", new_table_name = None):
"""
Create a new table by aggregating over multiple columns. The resulting table
contains the aggregate column names and the new column name, and for each
unique combination of values among the aggregate column names, the count of rows in this
table with that unique combination of values.
The new table will have name new_table_name
Throws an InvalidDataException if aggregate_column_names is not a subset of the names in self.schema
Args:
aggregate_column_names: names of the columns to aggregate over
new_column_name: name of the column for the aggregate count. Defaults to count
new_table_name: name of the new table. If omitted, defaults to None, in which case a name will be generated
Returns:
A new table with name new_table_name, or a generated name if new_table_name == None
Throws:
InvalidDataException if one of the column names is missing
"""
if (aggregate_column_names == None or len(aggregate_column_names) == 0):
raise InvalidDataException('No columns specified for aggregation')
column_names = set(aggregate_column_names)
columns = [entry for entry in self.schema if entry["name"] in column_names]
if (len(aggregate_column_names) != len(columns)):
# We have a missing column. Find it and throw the InvalidDataException
current_columns = set([entry["name"] for entry in columns])
missing_columns = column_names - current_columns
raise InvalidDataException(f'Columns {missing_columns} are not present in the schema')
# Make a table name
if (new_table_name == None):
letters = [name[0] for name in aggregate_column_names]
new_table_name = 'aggregate_' + ''.join([name[0] for name in aggregate_column_names])
# Collect the indices of the requested columns
indices = [i for i in range(len(self.schema)) if self.schema[i]["name"] in column_names]
# Collect the columns for each row, making each short_row a tuple so they can be
# indexed in a set
simple_keys = len(indices) == 1
if simple_keys:
short_rows = [row[indices[0]] for row in self.data]
else:
short_rows = [tuple([row[i] for i in indices]) for row in self.data]
keys = set(short_rows)
# Now that we have the unique keys, count the number of instances of each
count = {}
for key in keys: count[key] = 0
for key in short_rows: count[key] = count[key] + 1
# convert the keys from tuples to lists, add the count for each one, and
# filter out the 0's
data = []
for key in keys:
key_as_list = [key] if simple_keys else list(key)
data.append(key_as_list + [count[key]])
data = [row for row in data if row[-1] > 0]
# The schema is just the requested columns + new_column_name, and the type
# of new_column_name is a number. Then create the result table, load in the
# schema and data, and quit.
schema = columns[:] + [{"name": new_column_name, "type": GALYLEO_NUMBER}]
table = GalyleoTable(new_table_name)
table.load_from_dictionary({"columns": schema, "rows": data})
return table
def filter_by_function(self, column_name, function, new_table_name, column_types = {}):
'''
Create a new table, with name table_name, with rows such that
function(row[column_name]) == True. The new table will have
columns {self.columns} - {column_name}, same types, and same order
Throws an InvalidDataException if:
1. new_table_name is None or not a string
2. column_name is not a name of an existing column
3. if column_types is not empty, the type of the selected column doesn't match one of the allowed types
Args:
column_name: the column to filter by
function: a Boolean function with a single argument of the type of columns[column_name]
new_table_name: name of the new table
column_types: set of the allowed column types; if empty, any type is permitted
Returns:
A table with column[column_name] missing and filtered
Throws:
InvalidDataException if new_table_name is empty, column_name is not a name of an existing column, or the type of column_name isn't in column_types (if column_types is non-empty)
'''
if (not new_table_name ):
raise InvalidDataException('new_table_name cannot be empty')
if (not column_name):
raise InvalidDataException('column_name cannot be empty')
indices = [i for i in range(len(self.schema)) if self.schema[i]["name"] == column_name]
if (len(indices) == 0):
raise InvalidDataException(f'Column {column_name} not found in schema')
index = indices[0]
if (column_types):
if (not self.schema[index]["type"] in column_types):
raise InvalidDataException(f'Type {self.schema[index]["type"]} not found in {column_types}')
data = [row[:index] + row[index+1:] for row in self.data if function(row[index])]
schema = self.schema[:index] + self.schema[index+1:]
result = GalyleoTable(new_table_name)
result.load_from_dictionary({"columns": schema, "rows": data})
return result
def filter_equal(self, column_name, value, new_table_name, column_types):
'''
A convenience method over filter_by_function. This is identical to
filter_by_function(column_name, lambda x: x == value, new_table_name, column_types)
Args:
column_name: the column to filter by
value: the value to march for equality
new_table_name: name of the new table
column_types: set of the allowed column types; if empty, any type is permitted
Returns:
A table with column[column_name] missing and filtered
Throws:
InvalidDataException if new_table_name is empty, column_name is not a name of an existing column, or the type of column_name isn't in column_types (if column_types is non-empty)
'''
return self.filter_by_function(column_name, lambda x: x == value, new_table_name, column_types)
def filter_range(self, column_name, range_as_tuple, new_table_name, column_types):
'''
A convenience method over filter_by_function. This is identical to
filter_by_function(column_name, lambda x: x >= range_as_tuple[0], x <= range_as_tuple[1], new_table_name, column_types)
Args:
column_name: the column to filter by
range_as_tupe: the tuple representing the range
new_table_name: name of the new table
column_types: set of the allowed column types; if empty, any type is permitted
Returns:
A table with column[column_name] missing and filtered
Throws:
InvalidDataException if new_table_name is empty, column_name is not a name of an existing column, or the type of column_name isn't in column_types (if column_types is non-empty), if len(range_as_tuple) != 2
'''
try:
assert(range_as_tuple and len(range_as_tuple) == 2)
except Exception:
raise InvalidDataException(f'{range_as_tuple} should be a tuple of length 2')
return self.filter_by_function(column_name, lambda x: x <= range_as_tuple[1] and x >= range_as_tuple[0], new_table_name, column_types)
#
# A utility to get the index of a column, given a name. Raises an InvalidDataException
# is no such column in the schema
#
# Args:
# column_name: name of the column
#
# Returns:
# index of the column
#
# Throws:
# InvalidDataException if there is no such column
#
def _get_column_index(self, column_name):
indices = [i for i in range(len(self.schema)) if self.schema[i]["name"] == column_name]
if (len(indices) == 0):
raise InvalidDataException(f'Column {column_name} is not in the schema')
return indices[0]
def pivot_on_column(self, pivot_column_name, value_column_name, new_table_name, pivot_column_values = {}, other_column = False):
'''
The pivot_on_column method breaks out value_column into n separate columns, one for each
member of pivot_column_values plus (if other_column = True), an "Other" column. This is easiest to see with an example. Consider a table with columns (Year, State, Party, Percentage). pivot_on_column('Party', {'Republican', 'Democratic'}, 'Percentage', 'pivot_table', False) would create a new table with columns Year, State, Republican, Democratic, where the values in the Republican and Democratic columns are the values in the Percentage column where the Party column value was Republican or Democratic, respectively. If Other = True, an additional column, Other, is found where the value is (generally) the sum of values where Party not equal Republican or Democratic
Args:
pivot_column_name: the column holding the keys to pivot on
value_column_name: the column holding the values to spread out over the pivots
new_table_name: name of the new table
pivot_column_values: the values to pivot on. If empty, all values used
other_column: if True, aggregate other values into a column
Returns:
A table as described in the comments above
Throws:
InvalidDataException if new_table_name is empty, pivot_column_name is not a name of an existing column, or value_column_name is not the name of an existing column
'''
names = [(new_table_name, 'new_table_name'), (pivot_column_name, 'pivot_column_name'), (value_column_name, 'value_column_name')]
for name in names:
if (not name[0]):
raise InvalidDataException(f'{name[1]} cannot be empty')
if (value_column_name == pivot_column_name):
raise InvalidDataException(f'Pivot and value columns cannot be identical: both are {value_column_name}')
value_column_index = self._get_column_index(value_column_name)
pivot_column_index = self._get_column_index(pivot_column_name)
key_columns = list(set(range(len(self.schema))) - {value_column_index, pivot_column_index})
key_columns.sort()
# Split each row into a dict:
# key (value of the other columns). Note this is a tuple so it can index a set
# pivot_value: value of the pivot column
# value: value of the value column
def make_record(row):
return {
"key": tuple([row[i] for i in key_columns]),
"pivot": row[pivot_column_index],
"value": row[value_column_index]
}
partition = [make_record(row) for row in self.data]
# get the set of all distinct keys
keys = set([record["key"] for record in partition])
# get the distinct values of the pivot column
pivot_value_set = set([record["pivot"] for record in partition])
# Note whether we will have an "Other" column. We will when:
# (a) other_column = True AND
# (b) pivot_column_values is not empty AND
# (c) there are columns in pivot_value_set - pivot_column_values
other_columns = pivot_value_set - pivot_column_values if pivot_column_values else {}
use_other = other_column and other_columns
if (pivot_column_values):
pivot_value_set = pivot_value_set.intersection(pivot_column_values)
value_column_type = self.schema[value_column_index]["type"]
def new_pivot_record():
initial_value = 0 if value_column_type == GALYLEO_NUMBER else None
result = {}
for name in pivot_value_set: result[name] = initial_value
result["Other"] = initial_value
return result
# set up the dictionary
pivot_records = {}
for key in keys: pivot_records[key] = new_pivot_record()
for record in partition:
pivot = record["pivot"]
if (pivot in pivot_value_set): pivot_records[key][pivot] = record["value"]
else: pivot_records[key]["Other"] = record["value"] + pivot_records[key]["Other"]
# Now just create and return the new table
new_schema = [self.schema[i] for i in key_columns]
pivot_schema = [{"name": name, "type": value_column_type} for name in pivot_value_set]
if (use_other):
pivot_schema.append({"name": "Other", "type": value_column_type})
def make_record(key_value):
result = list(key_value)
record = pivot_records[key_value]
values = [record[pivot] for pivot in pivot_value_set]
if (use_other): values.append(record["Other"])
return result + values
data = [make_record(key) for key in pivot_records]
result = GalyleoTable(new_table_name)
result.load_from_dictionary({"columns": new_schema + pivot_schema, "rows": data})
return result
|
# Author: Zylo117
"""
COCO-Style Evaluations
put images here datasets/your_project_name/val_set_name/*.jpg
put annotations here datasets/your_project_name/annotations/instances_{val_set_name}.json
put weights here /path/to/your/weights/*.pth
change compound_coef
"""
import json
import os
import argparse
import torch
import yaml
from tqdm import tqdm
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
from backbone import EfficientDetBackbone
from efficientdet.utils import BBoxTransform, ClipBoxes
from utils.utils import preprocess, invert_affine, postprocess, boolean_string
ap = argparse.ArgumentParser()
project_name = "polyps_1"
efficientdet_version = 1
weights_file = "trained_weights/efficientdet-d1_best_89.pth"
# weights_file = "logs/polyps/efficientdet-d0_best.pth"
conf_threshold = 0.1
nms_threshold = 0.2
ap.add_argument('-p', '--project', type=str, default=project_name, help='project file that contains parameters')
ap.add_argument('-c', '--compound_coef', type=int, default=efficientdet_version, help='coefficients of efficientdet')
ap.add_argument('-w', '--weights', type=str, default=weights_file, help='/path/to/weights')
ap.add_argument('--nms_threshold', type=float, default=nms_threshold,
help='nms threshold, don\'t change it if not for testing purposes')
ap.add_argument('--cuda', type=boolean_string, default=True)
ap.add_argument('--device', type=int, default=0)
ap.add_argument('--float16', type=boolean_string, default=False)
ap.add_argument('--override', type=boolean_string, default=True, help='override previous bbox results file if exists')
args = ap.parse_args()
compound_coef = args.compound_coef
nms_threshold = args.nms_threshold
use_cuda = args.cuda
gpu = args.device
use_float16 = args.float16
override_prev_results = args.override
project_name = args.project
weights_path = f'weights/efficientdet-d{compound_coef}.pth' if args.weights is None else args.weights
print(f'running coco-style evaluation on project {project_name}, weights {weights_path}...')
params = yaml.safe_load(open(f'projects/{project_name}.yml'))
obj_list = params['obj_list']
input_sizes = [512, 640, 768, 896, 1024, 1280, 1280, 1536, 1536]
def evaluate_coco(img_path, set_name, image_ids, coco, model, threshold=0.05):
results = []
regressBoxes = BBoxTransform()
clipBoxes = ClipBoxes()
for image_id in tqdm(image_ids):
image_info = coco.loadImgs(image_id)[0]
image_path = img_path + image_info['file_name']
ori_imgs, framed_imgs, framed_metas = preprocess(image_path, max_size=input_sizes[compound_coef],
mean=params['mean'], std=params['std'])
x = torch.from_numpy(framed_imgs[0])
if use_cuda:
x = x.cuda(gpu)
if use_float16:
x = x.half()
else:
x = x.float()
else:
x = x.float()
x = x.unsqueeze(0).permute(0, 3, 1, 2)
features, regression, classification, anchors = model(x)
preds = postprocess(x,
anchors, regression, classification,
regressBoxes, clipBoxes,
threshold, nms_threshold)
if not preds:
continue
preds = invert_affine(framed_metas, preds)[0]
scores = preds['scores']
class_ids = preds['class_ids']
rois = preds['rois']
if rois.shape[0] > 0:
# x1,y1,x2,y2 -> x1,y1,w,h
rois[:, 2] -= rois[:, 0]
rois[:, 3] -= rois[:, 1]
bbox_score = scores
for roi_id in range(rois.shape[0]):
score = float(bbox_score[roi_id])
label = int(class_ids[roi_id])
box = rois[roi_id, :]
image_result = {
'image_id' : image_id,
'category_id': label + 1,
'score' : float(score),
'bbox' : box.tolist(),
}
results.append(image_result)
if not len(results):
raise Exception('the model does not provide any valid output, check model architecture and the data input')
# write output
filepath = f'{set_name}_bbox_results.json'
if os.path.exists(filepath):
os.remove(filepath)
json.dump(results, open(filepath, 'w'), indent=4)
def _eval(coco_gt, image_ids, pred_json_path):
# load results in COCO evaluation tool
coco_pred = coco_gt.loadRes(pred_json_path)
# run COCO evaluation
print('BBox')
coco_eval = COCOeval(coco_gt, coco_pred, 'bbox')
coco_eval.params.imgIds = image_ids
coco_eval.evaluate()
coco_eval.accumulate()
coco_eval.summarize()
return coco_eval.stats
if __name__ == '__main__':
SET_NAME = params['val_set']
VAL_GT = f'datasets/{params['project_name']}/annotations/instances_{SET_NAME}.json'
VAL_IMGS = f'datasets/{params['project_name']}/{SET_NAME}/'
MAX_IMAGES = 10000
coco_gt = COCO(VAL_GT)
image_ids = coco_gt.getImgIds()[:MAX_IMAGES]
if override_prev_results or not os.path.exists(f'{SET_NAME}_bbox_results.json'):
model = EfficientDetBackbone(compound_coef=compound_coef, num_classes=len(obj_list),
ratios=eval(params['anchors_ratios']), scales=eval(params['anchors_scales']))
model.load_state_dict(torch.load(weights_path, map_location=torch.device('cpu')))
model.requires_grad_(False)
model.eval()
if use_cuda:
model.cuda(gpu)
if use_float16:
model.half()
evaluate_coco(VAL_IMGS, SET_NAME, image_ids, coco_gt, model, conf_threshold)
coco_result = _eval(coco_gt, image_ids, f'{SET_NAME}_bbox_results.json')
| # Author: Zylo117
"""
COCO-Style Evaluations
put images here datasets/your_project_name/val_set_name/*.jpg
put annotations here datasets/your_project_name/annotations/instances_{val_set_name}.json
put weights here /path/to/your/weights/*.pth
change compound_coef
"""
import json
import os
import argparse
import torch
import yaml
from tqdm import tqdm
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
from backbone import EfficientDetBackbone
from efficientdet.utils import BBoxTransform, ClipBoxes
from utils.utils import preprocess, invert_affine, postprocess, boolean_string
ap = argparse.ArgumentParser()
project_name = "polyps_1"
efficientdet_version = 1
weights_file = "trained_weights/efficientdet-d1_best_89.pth"
# weights_file = "logs/polyps/efficientdet-d0_best.pth"
conf_threshold = 0.1
nms_threshold = 0.2
ap.add_argument('-p', '--project', type=str, default=project_name, help='project file that contains parameters')
ap.add_argument('-c', '--compound_coef', type=int, default=efficientdet_version, help='coefficients of efficientdet')
ap.add_argument('-w', '--weights', type=str, default=weights_file, help='/path/to/weights')
ap.add_argument('--nms_threshold', type=float, default=nms_threshold,
help='nms threshold, don\'t change it if not for testing purposes')
ap.add_argument('--cuda', type=boolean_string, default=True)
ap.add_argument('--device', type=int, default=0)
ap.add_argument('--float16', type=boolean_string, default=False)
ap.add_argument('--override', type=boolean_string, default=True, help='override previous bbox results file if exists')
args = ap.parse_args()
compound_coef = args.compound_coef
nms_threshold = args.nms_threshold
use_cuda = args.cuda
gpu = args.device
use_float16 = args.float16
override_prev_results = args.override
project_name = args.project
weights_path = f'weights/efficientdet-d{compound_coef}.pth' if args.weights is None else args.weights
print(f'running coco-style evaluation on project {project_name}, weights {weights_path}...')
params = yaml.safe_load(open(f'projects/{project_name}.yml'))
obj_list = params['obj_list']
input_sizes = [512, 640, 768, 896, 1024, 1280, 1280, 1536, 1536]
def evaluate_coco(img_path, set_name, image_ids, coco, model, threshold=0.05):
results = []
regressBoxes = BBoxTransform()
clipBoxes = ClipBoxes()
for image_id in tqdm(image_ids):
image_info = coco.loadImgs(image_id)[0]
image_path = img_path + image_info['file_name']
ori_imgs, framed_imgs, framed_metas = preprocess(image_path, max_size=input_sizes[compound_coef],
mean=params['mean'], std=params['std'])
x = torch.from_numpy(framed_imgs[0])
if use_cuda:
x = x.cuda(gpu)
if use_float16:
x = x.half()
else:
x = x.float()
else:
x = x.float()
x = x.unsqueeze(0).permute(0, 3, 1, 2)
features, regression, classification, anchors = model(x)
preds = postprocess(x,
anchors, regression, classification,
regressBoxes, clipBoxes,
threshold, nms_threshold)
if not preds:
continue
preds = invert_affine(framed_metas, preds)[0]
scores = preds['scores']
class_ids = preds['class_ids']
rois = preds['rois']
if rois.shape[0] > 0:
# x1,y1,x2,y2 -> x1,y1,w,h
rois[:, 2] -= rois[:, 0]
rois[:, 3] -= rois[:, 1]
bbox_score = scores
for roi_id in range(rois.shape[0]):
score = float(bbox_score[roi_id])
label = int(class_ids[roi_id])
box = rois[roi_id, :]
image_result = {
'image_id' : image_id,
'category_id': label + 1,
'score' : float(score),
'bbox' : box.tolist(),
}
results.append(image_result)
if not len(results):
raise Exception('the model does not provide any valid output, check model architecture and the data input')
# write output
filepath = f'{set_name}_bbox_results.json'
if os.path.exists(filepath):
os.remove(filepath)
json.dump(results, open(filepath, 'w'), indent=4)
def _eval(coco_gt, image_ids, pred_json_path):
# load results in COCO evaluation tool
coco_pred = coco_gt.loadRes(pred_json_path)
# run COCO evaluation
print('BBox')
coco_eval = COCOeval(coco_gt, coco_pred, 'bbox')
coco_eval.params.imgIds = image_ids
coco_eval.evaluate()
coco_eval.accumulate()
coco_eval.summarize()
return coco_eval.stats
if __name__ == '__main__':
SET_NAME = params['val_set']
VAL_GT = f'datasets/{params["project_name"]}/annotations/instances_{SET_NAME}.json'
VAL_IMGS = f'datasets/{params["project_name"]}/{SET_NAME}/'
MAX_IMAGES = 10000
coco_gt = COCO(VAL_GT)
image_ids = coco_gt.getImgIds()[:MAX_IMAGES]
if override_prev_results or not os.path.exists(f'{SET_NAME}_bbox_results.json'):
model = EfficientDetBackbone(compound_coef=compound_coef, num_classes=len(obj_list),
ratios=eval(params['anchors_ratios']), scales=eval(params['anchors_scales']))
model.load_state_dict(torch.load(weights_path, map_location=torch.device('cpu')))
model.requires_grad_(False)
model.eval()
if use_cuda:
model.cuda(gpu)
if use_float16:
model.half()
evaluate_coco(VAL_IMGS, SET_NAME, image_ids, coco_gt, model, conf_threshold)
coco_result = _eval(coco_gt, image_ids, f'{SET_NAME}_bbox_results.json')
|
import asyncio
from decimal import Decimal
from typing import Awaitable, Optional
from unittest import TestCase
from unittest.mock import AsyncMock
import hummingbot.connector.exchange.huobi.huobi_constants as CONSTANTS
from hummingbot.connector.exchange.huobi.huobi_exchange import HuobiExchange
from hummingbot.core.data_type.trade_fee import TokenAmount
from hummingbot.core.event.event_logger import EventLogger
from hummingbot.core.event.events import (
BuyOrderCompletedEvent,
MarketEvent,
OrderFilledEvent,
OrderType,
TradeType,
)
class HuobiExchangeTests(TestCase):
# the level is required to receive logs from the data source logger
level = 0
@classmethod
def setUpClass(cls) -> None:
super().setUpClass()
cls.base_asset = "COINALPHA"
cls.quote_asset = "HBOT"
cls.trading_pair = f"{cls.base_asset}-{cls.quote_asset}"
cls.symbol = f"{cls.base_asset}{cls.quote_asset}"
cls.listen_key = "TEST_LISTEN_KEY"
def setUp(self) -> None:
super().setUp()
self.log_records = []
self.test_task: Optional[asyncio.Task] = None
self.exchange = HuobiExchange(
huobi_api_key="testAPIKey",
huobi_secret_key="testSecret",
trading_pairs=[self.trading_pair],
)
self.exchange.logger().setLevel(1)
self.exchange.logger().addHandler(self)
self._initialize_event_loggers()
def tearDown(self) -> None:
self.test_task and self.test_task.cancel()
super().tearDown()
def _initialize_event_loggers(self):
self.buy_order_completed_logger = EventLogger()
self.sell_order_completed_logger = EventLogger()
self.order_filled_logger = EventLogger()
events_and_loggers = [
(MarketEvent.BuyOrderCompleted, self.buy_order_completed_logger),
(MarketEvent.SellOrderCompleted, self.sell_order_completed_logger),
(MarketEvent.OrderFilled, self.order_filled_logger)]
for event, logger in events_and_loggers:
self.exchange.add_listener(event, logger)
def handle(self, record):
self.log_records.append(record)
def _is_logged(self, log_level: str, message: str) -> bool:
return any(record.levelname == log_level and record.getMessage() == message for record in self.log_records)
def async_run_with_timeout(self, coroutine: Awaitable, timeout: float = 1):
ret = asyncio.get_event_loop().run_until_complete(asyncio.wait_for(coroutine, timeout))
return ret
def test_order_fill_event_takes_fee_from_update_event(self):
self.exchange.start_tracking_order(
order_id="OID1",
exchange_order_id="99998888",
trading_pair=self.trading_pair,
order_type=OrderType.LIMIT,
trade_type=TradeType.BUY,
price=Decimal("10000"),
amount=Decimal("1"),
)
order = self.exchange.in_flight_orders.get("OID1")
partial_fill = {
"eventType": "trade",
"symbol": "choinalphahbot",
"orderId": 99998888,
"tradePrice": "10050.0",
"tradeVolume": "0.1",
"orderSide": "buy",
"aggressor": True,
"tradeId": 1,
"tradeTime": 998787897878,
"transactFee": "10.00",
"feeDeduct ": "0",
"feeDeductType": "",
"feeCurrency": "usdt",
"accountId": 9912791,
"source": "spot-api",
"orderPrice": "10000",
"orderSize": "1",
"clientOrderId": "OID1",
"orderCreateTime": 998787897878,
"orderStatus": "partial-filled"
}
message = {
"ch": CONSTANTS.HUOBI_TRADE_DETAILS_TOPIC,
"data": partial_fill
}
mock_user_stream = AsyncMock()
mock_user_stream.get.side_effect = [message, asyncio.CancelledError()]
self.exchange.user_stream_tracker._user_stream = mock_user_stream
self.test_task = asyncio.get_event_loop().create_task(self.exchange._user_stream_event_listener())
try:
self.async_run_with_timeout(self.test_task)
except asyncio.CancelledError:
pass
self.assertEqual(Decimal("10"), order.fee_paid)
self.assertEqual(1, len(self.order_filled_logger.event_log))
fill_event: OrderFilledEvent = self.order_filled_logger.event_log[0]
self.assertEqual(Decimal("0"), fill_event.trade_fee.percent)
self.assertEqual([TokenAmount(partial_fill["feeCurrency"].upper(), Decimal(partial_fill["transactFee"]))],
fill_event.trade_fee.flat_fees)
self.assertTrue(self._is_logged(
"INFO",
f"Filled {Decimal(partial_fill["tradeVolume"])} out of {order.amount} of order "
f"{order.order_type.name}-{order.client_order_id}"
))
self.assertEqual(0, len(self.buy_order_completed_logger.event_log))
complete_fill = {
"eventType": "trade",
"symbol": "choinalphahbot",
"orderId": 99998888,
"tradePrice": "10060.0",
"tradeVolume": "0.9",
"orderSide": "buy",
"aggressor": True,
"tradeId": 2,
"tradeTime": 998787897878,
"transactFee": "30.0",
"feeDeduct ": "0",
"feeDeductType": "",
"feeCurrency": "usdt",
"accountId": 9912791,
"source": "spot-api",
"orderPrice": "10000",
"orderSize": "1",
"clientOrderId": "OID1",
"orderCreateTime": 998787897878,
"orderStatus": "partial-filled"
}
message["data"] = complete_fill
mock_user_stream = AsyncMock()
mock_user_stream.get.side_effect = [message, asyncio.CancelledError()]
self.exchange.user_stream_tracker._user_stream = mock_user_stream
self.test_task = asyncio.get_event_loop().create_task(self.exchange._user_stream_event_listener())
try:
self.async_run_with_timeout(self.test_task)
except asyncio.CancelledError:
pass
self.assertEqual(Decimal("40"), order.fee_paid)
self.assertEqual(2, len(self.order_filled_logger.event_log))
fill_event: OrderFilledEvent = self.order_filled_logger.event_log[1]
self.assertEqual(Decimal("0"), fill_event.trade_fee.percent)
self.assertEqual([TokenAmount(complete_fill["feeCurrency"].upper(), Decimal(complete_fill["transactFee"]))],
fill_event.trade_fee.flat_fees)
# The order should be marked as complete only when the "done" event arrives, not with the fill event
self.assertFalse(self._is_logged(
"INFO",
f"The LIMIT_BUY order {order.client_order_id} has completed according to order delta websocket API."
))
self.assertEqual(0, len(self.buy_order_completed_logger.event_log))
def test_order_fill_event_processed_before_order_complete_event(self):
self.exchange.start_tracking_order(
order_id="OID1",
exchange_order_id="99998888",
trading_pair=self.trading_pair,
order_type=OrderType.LIMIT,
trade_type=TradeType.BUY,
price=Decimal("10000"),
amount=Decimal("1"),
)
order = self.exchange.in_flight_orders.get("OID1")
complete_fill = {
"eventType": "trade",
"symbol": "choinalphahbot",
"orderId": 99998888,
"tradePrice": "10060.0",
"tradeVolume": "1",
"orderSide": "buy",
"aggressor": True,
"tradeId": 1,
"tradeTime": 998787897878,
"transactFee": "30.0",
"feeDeduct ": "0",
"feeDeductType": "",
"feeCurrency": "usdt",
"accountId": 9912791,
"source": "spot-api",
"orderPrice": "10000",
"orderSize": "1",
"clientOrderId": "OID1",
"orderCreateTime": 998787897878,
"orderStatus": "partial-filled"
}
fill_message = {
"ch": CONSTANTS.HUOBI_TRADE_DETAILS_TOPIC,
"data": complete_fill
}
update_data = {
"tradePrice": "10060.0",
"tradeVolume": "1",
"tradeId": 1,
"tradeTime": 1583854188883,
"aggressor": True,
"remainAmt": "0.0",
"execAmt": "1",
"orderId": 99998888,
"type": "buy-limit",
"clientOrderId": "OID1",
"orderSource": "spot-api",
"orderPrice": "10000",
"orderSize": "1",
"orderStatus": "filled",
"symbol": "btcusdt",
"eventType": "trade"
}
update_message = {
"action": "push",
"ch": CONSTANTS.HUOBI_ORDER_UPDATE_TOPIC,
"data": update_data,
}
mock_user_stream = AsyncMock()
# We simulate the case when the order update arrives before the order fill
mock_user_stream.get.side_effect = [update_message, fill_message, asyncio.CancelledError()]
self.exchange.user_stream_tracker._user_stream = mock_user_stream
self.test_task = asyncio.get_event_loop().create_task(self.exchange._user_stream_event_listener())
try:
self.async_run_with_timeout(self.test_task)
except asyncio.CancelledError:
pass
self.async_run_with_timeout(order.wait_until_completely_filled())
self.assertEqual(Decimal("30"), order.fee_paid)
self.assertEqual(1, len(self.order_filled_logger.event_log))
fill_event: OrderFilledEvent = self.order_filled_logger.event_log[0]
self.assertEqual(Decimal("0"), fill_event.trade_fee.percent)
self.assertEqual([TokenAmount(complete_fill["feeCurrency"].upper(), Decimal(complete_fill["transactFee"]))],
fill_event.trade_fee.flat_fees)
self.assertTrue(self._is_logged(
"INFO",
f"Filled {Decimal(complete_fill["tradeVolume"])} out of {order.amount} of order "
f"{order.order_type.name}-{order.client_order_id}"
))
self.assertTrue(self._is_logged(
"INFO",
f"The {order.trade_type.name} order {order.client_order_id} "
f"has completed according to order delta websocket API."
))
self.assertEqual(1, len(self.buy_order_completed_logger.event_log))
buy_event: BuyOrderCompletedEvent = self.buy_order_completed_logger.event_log[0]
self.assertEqual(complete_fill["feeCurrency"].upper(), buy_event.fee_asset)
self.assertEqual(Decimal(complete_fill["transactFee"]), buy_event.fee_amount)
| import asyncio
from decimal import Decimal
from typing import Awaitable, Optional
from unittest import TestCase
from unittest.mock import AsyncMock
import hummingbot.connector.exchange.huobi.huobi_constants as CONSTANTS
from hummingbot.connector.exchange.huobi.huobi_exchange import HuobiExchange
from hummingbot.core.data_type.trade_fee import TokenAmount
from hummingbot.core.event.event_logger import EventLogger
from hummingbot.core.event.events import (
BuyOrderCompletedEvent,
MarketEvent,
OrderFilledEvent,
OrderType,
TradeType,
)
class HuobiExchangeTests(TestCase):
# the level is required to receive logs from the data source logger
level = 0
@classmethod
def setUpClass(cls) -> None:
super().setUpClass()
cls.base_asset = "COINALPHA"
cls.quote_asset = "HBOT"
cls.trading_pair = f"{cls.base_asset}-{cls.quote_asset}"
cls.symbol = f"{cls.base_asset}{cls.quote_asset}"
cls.listen_key = "TEST_LISTEN_KEY"
def setUp(self) -> None:
super().setUp()
self.log_records = []
self.test_task: Optional[asyncio.Task] = None
self.exchange = HuobiExchange(
huobi_api_key="testAPIKey",
huobi_secret_key="testSecret",
trading_pairs=[self.trading_pair],
)
self.exchange.logger().setLevel(1)
self.exchange.logger().addHandler(self)
self._initialize_event_loggers()
def tearDown(self) -> None:
self.test_task and self.test_task.cancel()
super().tearDown()
def _initialize_event_loggers(self):
self.buy_order_completed_logger = EventLogger()
self.sell_order_completed_logger = EventLogger()
self.order_filled_logger = EventLogger()
events_and_loggers = [
(MarketEvent.BuyOrderCompleted, self.buy_order_completed_logger),
(MarketEvent.SellOrderCompleted, self.sell_order_completed_logger),
(MarketEvent.OrderFilled, self.order_filled_logger)]
for event, logger in events_and_loggers:
self.exchange.add_listener(event, logger)
def handle(self, record):
self.log_records.append(record)
def _is_logged(self, log_level: str, message: str) -> bool:
return any(record.levelname == log_level and record.getMessage() == message for record in self.log_records)
def async_run_with_timeout(self, coroutine: Awaitable, timeout: float = 1):
ret = asyncio.get_event_loop().run_until_complete(asyncio.wait_for(coroutine, timeout))
return ret
def test_order_fill_event_takes_fee_from_update_event(self):
self.exchange.start_tracking_order(
order_id="OID1",
exchange_order_id="99998888",
trading_pair=self.trading_pair,
order_type=OrderType.LIMIT,
trade_type=TradeType.BUY,
price=Decimal("10000"),
amount=Decimal("1"),
)
order = self.exchange.in_flight_orders.get("OID1")
partial_fill = {
"eventType": "trade",
"symbol": "choinalphahbot",
"orderId": 99998888,
"tradePrice": "10050.0",
"tradeVolume": "0.1",
"orderSide": "buy",
"aggressor": True,
"tradeId": 1,
"tradeTime": 998787897878,
"transactFee": "10.00",
"feeDeduct ": "0",
"feeDeductType": "",
"feeCurrency": "usdt",
"accountId": 9912791,
"source": "spot-api",
"orderPrice": "10000",
"orderSize": "1",
"clientOrderId": "OID1",
"orderCreateTime": 998787897878,
"orderStatus": "partial-filled"
}
message = {
"ch": CONSTANTS.HUOBI_TRADE_DETAILS_TOPIC,
"data": partial_fill
}
mock_user_stream = AsyncMock()
mock_user_stream.get.side_effect = [message, asyncio.CancelledError()]
self.exchange.user_stream_tracker._user_stream = mock_user_stream
self.test_task = asyncio.get_event_loop().create_task(self.exchange._user_stream_event_listener())
try:
self.async_run_with_timeout(self.test_task)
except asyncio.CancelledError:
pass
self.assertEqual(Decimal("10"), order.fee_paid)
self.assertEqual(1, len(self.order_filled_logger.event_log))
fill_event: OrderFilledEvent = self.order_filled_logger.event_log[0]
self.assertEqual(Decimal("0"), fill_event.trade_fee.percent)
self.assertEqual([TokenAmount(partial_fill["feeCurrency"].upper(), Decimal(partial_fill["transactFee"]))],
fill_event.trade_fee.flat_fees)
self.assertTrue(self._is_logged(
"INFO",
f"Filled {Decimal(partial_fill['tradeVolume'])} out of {order.amount} of order "
f"{order.order_type.name}-{order.client_order_id}"
))
self.assertEqual(0, len(self.buy_order_completed_logger.event_log))
complete_fill = {
"eventType": "trade",
"symbol": "choinalphahbot",
"orderId": 99998888,
"tradePrice": "10060.0",
"tradeVolume": "0.9",
"orderSide": "buy",
"aggressor": True,
"tradeId": 2,
"tradeTime": 998787897878,
"transactFee": "30.0",
"feeDeduct ": "0",
"feeDeductType": "",
"feeCurrency": "usdt",
"accountId": 9912791,
"source": "spot-api",
"orderPrice": "10000",
"orderSize": "1",
"clientOrderId": "OID1",
"orderCreateTime": 998787897878,
"orderStatus": "partial-filled"
}
message["data"] = complete_fill
mock_user_stream = AsyncMock()
mock_user_stream.get.side_effect = [message, asyncio.CancelledError()]
self.exchange.user_stream_tracker._user_stream = mock_user_stream
self.test_task = asyncio.get_event_loop().create_task(self.exchange._user_stream_event_listener())
try:
self.async_run_with_timeout(self.test_task)
except asyncio.CancelledError:
pass
self.assertEqual(Decimal("40"), order.fee_paid)
self.assertEqual(2, len(self.order_filled_logger.event_log))
fill_event: OrderFilledEvent = self.order_filled_logger.event_log[1]
self.assertEqual(Decimal("0"), fill_event.trade_fee.percent)
self.assertEqual([TokenAmount(complete_fill["feeCurrency"].upper(), Decimal(complete_fill["transactFee"]))],
fill_event.trade_fee.flat_fees)
# The order should be marked as complete only when the "done" event arrives, not with the fill event
self.assertFalse(self._is_logged(
"INFO",
f"The LIMIT_BUY order {order.client_order_id} has completed according to order delta websocket API."
))
self.assertEqual(0, len(self.buy_order_completed_logger.event_log))
def test_order_fill_event_processed_before_order_complete_event(self):
self.exchange.start_tracking_order(
order_id="OID1",
exchange_order_id="99998888",
trading_pair=self.trading_pair,
order_type=OrderType.LIMIT,
trade_type=TradeType.BUY,
price=Decimal("10000"),
amount=Decimal("1"),
)
order = self.exchange.in_flight_orders.get("OID1")
complete_fill = {
"eventType": "trade",
"symbol": "choinalphahbot",
"orderId": 99998888,
"tradePrice": "10060.0",
"tradeVolume": "1",
"orderSide": "buy",
"aggressor": True,
"tradeId": 1,
"tradeTime": 998787897878,
"transactFee": "30.0",
"feeDeduct ": "0",
"feeDeductType": "",
"feeCurrency": "usdt",
"accountId": 9912791,
"source": "spot-api",
"orderPrice": "10000",
"orderSize": "1",
"clientOrderId": "OID1",
"orderCreateTime": 998787897878,
"orderStatus": "partial-filled"
}
fill_message = {
"ch": CONSTANTS.HUOBI_TRADE_DETAILS_TOPIC,
"data": complete_fill
}
update_data = {
"tradePrice": "10060.0",
"tradeVolume": "1",
"tradeId": 1,
"tradeTime": 1583854188883,
"aggressor": True,
"remainAmt": "0.0",
"execAmt": "1",
"orderId": 99998888,
"type": "buy-limit",
"clientOrderId": "OID1",
"orderSource": "spot-api",
"orderPrice": "10000",
"orderSize": "1",
"orderStatus": "filled",
"symbol": "btcusdt",
"eventType": "trade"
}
update_message = {
"action": "push",
"ch": CONSTANTS.HUOBI_ORDER_UPDATE_TOPIC,
"data": update_data,
}
mock_user_stream = AsyncMock()
# We simulate the case when the order update arrives before the order fill
mock_user_stream.get.side_effect = [update_message, fill_message, asyncio.CancelledError()]
self.exchange.user_stream_tracker._user_stream = mock_user_stream
self.test_task = asyncio.get_event_loop().create_task(self.exchange._user_stream_event_listener())
try:
self.async_run_with_timeout(self.test_task)
except asyncio.CancelledError:
pass
self.async_run_with_timeout(order.wait_until_completely_filled())
self.assertEqual(Decimal("30"), order.fee_paid)
self.assertEqual(1, len(self.order_filled_logger.event_log))
fill_event: OrderFilledEvent = self.order_filled_logger.event_log[0]
self.assertEqual(Decimal("0"), fill_event.trade_fee.percent)
self.assertEqual([TokenAmount(complete_fill["feeCurrency"].upper(), Decimal(complete_fill["transactFee"]))],
fill_event.trade_fee.flat_fees)
self.assertTrue(self._is_logged(
"INFO",
f"Filled {Decimal(complete_fill['tradeVolume'])} out of {order.amount} of order "
f"{order.order_type.name}-{order.client_order_id}"
))
self.assertTrue(self._is_logged(
"INFO",
f"The {order.trade_type.name} order {order.client_order_id} "
f"has completed according to order delta websocket API."
))
self.assertEqual(1, len(self.buy_order_completed_logger.event_log))
buy_event: BuyOrderCompletedEvent = self.buy_order_completed_logger.event_log[0]
self.assertEqual(complete_fill["feeCurrency"].upper(), buy_event.fee_asset)
self.assertEqual(Decimal(complete_fill["transactFee"]), buy_event.fee_amount)
|
from werkzeug.exceptions import NotFound, BadRequest
from db import db
from helpers.data_preparation import data_preparate_for_commit
from helpers.loger_config import custom_logger
from models import TariffTypeModel
from models.tarif_el import TarifPiceModel
from schemas.request.tarif_price import TarifPriceRequestSchema, PriceForConcretTarType
class TarifPricesManager:
@staticmethod
def input_new_price(data):
if not TariffTypeModel.query.filter_by(id=data["tarif_id"]).first():
custom_logger(
"error",
f"Function input_new_price: try to insert data with invalid type_id: {data["tarif_id"]}",
)
raise BadRequest("This type is not valid")
schema = TarifPriceRequestSchema()
result = TarifPiceModel(**data)
data_preparate_for_commit(result)
return schema.dump(result)
@staticmethod
def get_all_tarife_prices():
schema = TarifPriceRequestSchema()
result = TarifPiceModel.query.all()
return schema.dump(result, many=True)
class TarifPriceFromConcretTypeManager:
@staticmethod
def get_result(_id):
result = TarifPiceModel.query.filter_by(id=_id)
if result.first():
return result
raise NotFound("Invalid id")
@staticmethod
def edit_result(_id, data):
price = TarifPriceFromConcretTypeManager.get_result(_id)
price.update(data)
return price
@staticmethod
def delete_result(_id):
price = TarifPriceFromConcretTypeManager.get_result(_id)
db.session.delete(price.first())
custom_logger(
"error",
f"Function delete_result: delete price with id {_id}",
)
return 204
class PriceForConcretTypeManager:
@staticmethod
def get_price_from_type(type):
schema = PriceForConcretTarType()
try:
search_type = TariffTypeModel.query.filter_by(name=type).first()
result = TarifPiceModel.query.filter_by(tarif_id=search_type.id)
return schema.dump(result, many=True)
except Exception:
raise NotFound("Invalid type")
| from werkzeug.exceptions import NotFound, BadRequest
from db import db
from helpers.data_preparation import data_preparate_for_commit
from helpers.loger_config import custom_logger
from models import TariffTypeModel
from models.tarif_el import TarifPiceModel
from schemas.request.tarif_price import TarifPriceRequestSchema, PriceForConcretTarType
class TarifPricesManager:
@staticmethod
def input_new_price(data):
if not TariffTypeModel.query.filter_by(id=data["tarif_id"]).first():
custom_logger(
"error",
f"Function input_new_price: try to insert data with invalid type_id: {data['tarif_id']}",
)
raise BadRequest("This type is not valid")
schema = TarifPriceRequestSchema()
result = TarifPiceModel(**data)
data_preparate_for_commit(result)
return schema.dump(result)
@staticmethod
def get_all_tarife_prices():
schema = TarifPriceRequestSchema()
result = TarifPiceModel.query.all()
return schema.dump(result, many=True)
class TarifPriceFromConcretTypeManager:
@staticmethod
def get_result(_id):
result = TarifPiceModel.query.filter_by(id=_id)
if result.first():
return result
raise NotFound("Invalid id")
@staticmethod
def edit_result(_id, data):
price = TarifPriceFromConcretTypeManager.get_result(_id)
price.update(data)
return price
@staticmethod
def delete_result(_id):
price = TarifPriceFromConcretTypeManager.get_result(_id)
db.session.delete(price.first())
custom_logger(
"error",
f"Function delete_result: delete price with id {_id}",
)
return 204
class PriceForConcretTypeManager:
@staticmethod
def get_price_from_type(type):
schema = PriceForConcretTarType()
try:
search_type = TariffTypeModel.query.filter_by(name=type).first()
result = TarifPiceModel.query.filter_by(tarif_id=search_type.id)
return schema.dump(result, many=True)
except Exception:
raise NotFound("Invalid type")
|
import os
import sys
import time
from collections import namedtuple
import pendulum
from dagster import check, seven
from dagster.core.definitions.run_request import InstigatorType
from dagster.core.definitions.sensor_definition import DefaultSensorStatus, SensorExecutionData
from dagster.core.errors import DagsterError
from dagster.core.host_representation import PipelineSelector
from dagster.core.instance import DagsterInstance
from dagster.core.scheduler.instigation import (
InstigatorState,
InstigatorStatus,
SensorInstigatorData,
TickData,
TickStatus,
)
from dagster.core.storage.pipeline_run import PipelineRun, PipelineRunStatus, PipelineRunsFilter
from dagster.core.storage.tags import RUN_KEY_TAG, check_tags
from dagster.core.telemetry import SENSOR_RUN_CREATED, hash_name, log_action
from dagster.core.workspace import IWorkspace
from dagster.utils import merge_dicts
from dagster.utils.error import serializable_error_info_from_exc_info
RECORDED_TICK_STATES = [TickStatus.SUCCESS, TickStatus.FAILURE]
FULFILLED_TICK_STATES = [TickStatus.SKIPPED, TickStatus.SUCCESS]
MIN_INTERVAL_LOOP_TIME = 5
class DagsterSensorDaemonError(DagsterError):
"""Error when running the SensorDaemon"""
class SkippedSensorRun(namedtuple("SkippedSensorRun", "run_key existing_run")):
"""Placeholder for runs that are skipped during the run_key idempotence check"""
class SensorLaunchContext:
def __init__(self, external_sensor, job_state, tick, instance, logger):
self._external_sensor = external_sensor
self._instance = instance
self._logger = logger
self._job_state = job_state
self._tick = tick
@property
def status(self):
return self._tick.status
@property
def logger(self):
return self._logger
@property
def run_count(self):
return len(self._tick.run_ids)
def update_state(self, status, **kwargs):
skip_reason = kwargs.get("skip_reason")
cursor = kwargs.get("cursor")
origin_run_id = kwargs.get("origin_run_id")
if "skip_reason" in kwargs:
del kwargs["skip_reason"]
if "cursor" in kwargs:
del kwargs["cursor"]
if "origin_run_id" in kwargs:
del kwargs["origin_run_id"]
if kwargs:
check.inst_param(status, "status", TickStatus)
if status:
self._tick = self._tick.with_status(status=status, **kwargs)
if skip_reason:
self._tick = self._tick.with_reason(skip_reason=skip_reason)
if cursor:
self._tick = self._tick.with_cursor(cursor)
if origin_run_id:
self._tick = self._tick.with_origin_run(origin_run_id)
def add_run(self, run_id, run_key=None):
self._tick = self._tick.with_run(run_id, run_key)
def _write(self):
self._instance.update_job_tick(self._tick)
if self._tick.status in FULFILLED_TICK_STATES:
last_run_key = (
self._job_state.job_specific_data.last_run_key
if self._job_state.job_specific_data
else None
)
if self._tick.run_keys:
last_run_key = self._tick.run_keys[-1]
self._instance.update_job_state(
self._job_state.with_data(
SensorInstigatorData(
last_tick_timestamp=self._tick.timestamp,
last_run_key=last_run_key,
min_interval=self._external_sensor.min_interval_seconds,
cursor=self._tick.cursor,
)
)
)
def __enter__(self):
return self
def __exit__(self, exception_type, exception_value, traceback):
# Log the error if the failure wasn't an interrupt or the daemon generator stopping
if exception_value and not isinstance(exception_value, (KeyboardInterrupt, GeneratorExit)):
error_data = serializable_error_info_from_exc_info(sys.exc_info())
self.update_state(TickStatus.FAILURE, error=error_data)
self._write()
self._instance.purge_job_ticks(
self._job_state.job_origin_id,
tick_status=TickStatus.SKIPPED,
before=pendulum.now("UTC").subtract(days=7).timestamp(), # keep the last 7 days
)
def _check_for_debug_crash(debug_crash_flags, key):
if not debug_crash_flags:
return
kill_signal = debug_crash_flags.get(key)
if not kill_signal:
return
os.kill(os.getpid(), kill_signal)
time.sleep(10)
raise Exception("Process didn't terminate after sending crash signal")
RELOAD_WORKSPACE = 60
def execute_sensor_iteration_loop(instance, workspace, logger, until=None):
"""
Helper function that performs sensor evaluations on a tighter loop, while reusing grpc locations
within a given daemon interval. Rather than relying on the daemon machinery to run the
iteration loop every 30 seconds, sensors are continuously evaluated, every 5 seconds. We rely on
each sensor definition's min_interval to check that sensor evaluations are spaced appropriately.
"""
workspace_loaded_time = pendulum.now("UTC").timestamp()
workspace_iteration = 0
start_time = pendulum.now("UTC").timestamp()
while True:
start_time = pendulum.now("UTC").timestamp()
if until and start_time >= until:
# provide a way of organically ending the loop to support test environment
break
if start_time - workspace_loaded_time > RELOAD_WORKSPACE:
workspace.cleanup()
workspace_loaded_time = pendulum.now("UTC").timestamp()
workspace_iteration = 0
yield from execute_sensor_iteration(
instance, logger, workspace, log_verbose_checks=(workspace_iteration == 0)
)
loop_duration = pendulum.now("UTC").timestamp() - start_time
sleep_time = max(0, MIN_INTERVAL_LOOP_TIME - loop_duration)
time.sleep(sleep_time)
yield
workspace_iteration += 1
def execute_sensor_iteration(
instance, logger, workspace, log_verbose_checks=True, debug_crash_flags=None
):
check.inst_param(workspace, "workspace", IWorkspace)
check.inst_param(instance, "instance", DagsterInstance)
workspace_snapshot = {
location_entry.origin: location_entry
for location_entry in workspace.get_workspace_snapshot().values()
}
all_sensor_states = {
sensor_state.origin.get_id(): sensor_state
for sensor_state in instance.all_stored_job_state(job_type=InstigatorType.SENSOR)
}
sensors = {}
for location_entry in workspace_snapshot.values():
repo_location = location_entry.repository_location
if repo_location:
for repo in repo_location.get_repositories().values():
for sensor in repo.get_external_sensors():
origin_id = sensor.get_external_origin().get_id()
if sensor.get_current_instigator_state(
all_sensor_states.get(origin_id)
).is_running:
sensors[origin_id] = sensor
elif location_entry.load_error and log_verbose_checks:
logger.warning(
f"Could not load location {location_entry.origin.location_name} to check for sensors due to the following error: {location_entry.load_error}"
)
if log_verbose_checks:
unloadable_sensor_states = {
origin_id: sensor_state
for origin_id, sensor_state in all_sensor_states.items()
if origin_id not in sensors and sensor_state.status == InstigatorStatus.RUNNING
}
for sensor_state in unloadable_sensor_states.values():
sensor_name = sensor_state.origin.instigator_name
repo_location_origin = (
sensor_state.origin.external_repository_origin.repository_location_origin
)
repo_location_name = repo_location_origin.location_name
repo_name = sensor_state.origin.external_repository_origin.repository_name
if (
repo_location_origin not in workspace_snapshot
or not workspace_snapshot[repo_location_origin].repository_location
):
logger.warning(
f"Sensor {sensor_name} was started from a location "
f"{repo_location_name} that can no longer be found in the workspace, or has "
"metadata that has changed since the sensor was started. You can turn off "
"this sensor in the Dagit UI from the Status tab."
)
elif not workspace_snapshot[repo_location_origin].repository_location.has_repository(
repo_name
):
logger.warning(
f"Could not find repository {repo_name} in location {repo_location_name} to "
+ f"run sensor {sensor_name}. If this repository no longer exists, you can "
+ "turn off the sensor in the Dagit UI from the Status tab.",
)
else:
logger.warning(
f"Could not find sensor {sensor_name} in repository {repo_name}. If this "
"sensor no longer exists, you can turn it off in the Dagit UI from the "
"Status tab.",
)
if not sensors:
if log_verbose_checks:
logger.info("Not checking for any runs since no sensors have been started.")
yield
return
now = pendulum.now("UTC")
for external_sensor in sensors.values():
sensor_name = external_sensor.name
sensor_debug_crash_flags = debug_crash_flags.get(sensor_name) if debug_crash_flags else None
error_info = None
try:
sensor_state = all_sensor_states.get(external_sensor.get_external_origin().get_id())
if not sensor_state:
assert external_sensor.default_status == DefaultSensorStatus.RUNNING
sensor_state = InstigatorState(
external_sensor.get_external_origin(),
InstigatorType.SENSOR,
InstigatorStatus.AUTOMATICALLY_RUNNING,
SensorInstigatorData(min_interval=external_sensor.min_interval_seconds),
)
instance.add_job_state(sensor_state)
elif _is_under_min_interval(sensor_state, external_sensor, now):
continue
tick = instance.create_job_tick(
TickData(
job_origin_id=sensor_state.job_origin_id,
job_name=sensor_state.job_name,
job_type=InstigatorType.SENSOR,
status=TickStatus.STARTED,
timestamp=now.timestamp(),
)
)
_check_for_debug_crash(sensor_debug_crash_flags, "TICK_CREATED")
with SensorLaunchContext(
external_sensor, sensor_state, tick, instance, logger
) as tick_context:
_check_for_debug_crash(sensor_debug_crash_flags, "TICK_HELD")
yield from _evaluate_sensor(
tick_context,
instance,
workspace,
external_sensor,
sensor_state,
sensor_debug_crash_flags,
)
except Exception:
error_info = serializable_error_info_from_exc_info(sys.exc_info())
logger.error(
"Sensor daemon caught an error for sensor {sensor_name} : {error_info}".format(
sensor_name=external_sensor.name,
error_info=error_info.to_string(),
)
)
yield error_info
def _evaluate_sensor(
context,
instance,
workspace,
external_sensor,
job_state,
sensor_debug_crash_flags=None,
):
context.logger.info(f"Checking for new runs for sensor: {external_sensor.name}")
sensor_origin = external_sensor.get_external_origin()
repository_handle = external_sensor.handle.repository_handle
repo_location = workspace.get_location(
sensor_origin.external_repository_origin.repository_location_origin
)
sensor_runtime_data = repo_location.get_external_sensor_execution_data(
instance,
repository_handle,
external_sensor.name,
job_state.job_specific_data.last_tick_timestamp if job_state.job_specific_data else None,
job_state.job_specific_data.last_run_key if job_state.job_specific_data else None,
job_state.job_specific_data.cursor if job_state.job_specific_data else None,
)
yield
assert isinstance(sensor_runtime_data, SensorExecutionData)
if not sensor_runtime_data.run_requests:
if sensor_runtime_data.pipeline_run_reactions:
for pipeline_run_reaction in sensor_runtime_data.pipeline_run_reactions:
origin_run_id = pipeline_run_reaction.pipeline_run.run_id
if pipeline_run_reaction.error:
context.logger.error(
f"Got a reaction request for run {origin_run_id} but execution errorred: {pipeline_run_reaction.error}"
)
context.update_state(
TickStatus.FAILURE,
cursor=sensor_runtime_data.cursor,
error=pipeline_run_reaction.error,
)
else:
# log to the original pipeline run
message = (
f'Sensor "{external_sensor.name}" acted on run status '
f"{pipeline_run_reaction.pipeline_run.status.value} of run {origin_run_id}."
)
instance.report_engine_event(
message=message, pipeline_run=pipeline_run_reaction.pipeline_run
)
context.logger.info(
f"Completed a reaction request for run {origin_run_id}: {message}"
)
context.update_state(
TickStatus.SUCCESS,
cursor=sensor_runtime_data.cursor,
origin_run_id=origin_run_id,
)
elif sensor_runtime_data.skip_message:
context.logger.info(
f"Sensor {external_sensor.name} skipped: {sensor_runtime_data.skip_message}"
)
context.update_state(
TickStatus.SKIPPED,
skip_reason=sensor_runtime_data.skip_message,
cursor=sensor_runtime_data.cursor,
)
else:
context.logger.info(f"No run requests returned for {external_sensor.name}, skipping")
context.update_state(TickStatus.SKIPPED, cursor=sensor_runtime_data.cursor)
yield
return
skipped_runs = []
for run_request in sensor_runtime_data.run_requests:
target_data = external_sensor.get_target_data(run_request.job_name)
pipeline_selector = PipelineSelector(
location_name=repo_location.name,
repository_name=sensor_origin.external_repository_origin.repository_name,
pipeline_name=target_data.pipeline_name,
solid_selection=target_data.solid_selection,
)
external_pipeline = repo_location.get_external_pipeline(pipeline_selector)
run = _get_or_create_sensor_run(
context,
instance,
repo_location,
external_sensor,
external_pipeline,
run_request,
target_data,
)
if isinstance(run, SkippedSensorRun):
skipped_runs.append(run)
yield
continue
_check_for_debug_crash(sensor_debug_crash_flags, "RUN_CREATED")
error_info = None
try:
context.logger.info(
"Launching run for {sensor_name}".format(sensor_name=external_sensor.name)
)
instance.submit_run(run.run_id, workspace)
context.logger.info(
"Completed launch of run {run_id} for {sensor_name}".format(
run_id=run.run_id, sensor_name=external_sensor.name
)
)
except Exception:
error_info = serializable_error_info_from_exc_info(sys.exc_info())
context.logger.error(
f"Run {run.run_id} created successfully but failed to launch: " f"{str(error_info)}"
)
yield error_info
_check_for_debug_crash(sensor_debug_crash_flags, "RUN_LAUNCHED")
context.add_run(run_id=run.run_id, run_key=run_request.run_key)
if skipped_runs:
run_keys = [skipped.run_key for skipped in skipped_runs]
skipped_count = len(skipped_runs)
context.logger.info(
f"Skipping {skipped_count} {"run" if skipped_count == 1 else "runs"} for sensor "
f"{external_sensor.name} already completed with run keys: {seven.json.dumps(run_keys)}"
)
if context.run_count:
context.update_state(TickStatus.SUCCESS, cursor=sensor_runtime_data.cursor)
else:
context.update_state(TickStatus.SKIPPED, cursor=sensor_runtime_data.cursor)
yield
def _is_under_min_interval(job_state, external_sensor, now):
if not job_state.job_specific_data:
return False
if not job_state.job_specific_data.last_tick_timestamp:
return False
if not external_sensor.min_interval_seconds:
return False
elapsed = now.timestamp() - job_state.job_specific_data.last_tick_timestamp
return elapsed < external_sensor.min_interval_seconds
def _get_or_create_sensor_run(
context, instance, repo_location, external_sensor, external_pipeline, run_request, target_data
):
if not run_request.run_key:
return _create_sensor_run(
instance, repo_location, external_sensor, external_pipeline, run_request, target_data
)
existing_runs = instance.get_runs(
PipelineRunsFilter(
tags=merge_dicts(
PipelineRun.tags_for_sensor(external_sensor),
{RUN_KEY_TAG: run_request.run_key},
)
)
)
if len(existing_runs):
run = existing_runs[0]
if run.status != PipelineRunStatus.NOT_STARTED:
# A run already exists and was launched for this time period,
# but the daemon must have crashed before the tick could be put
# into a SUCCESS state
context.logger.info(f"Skipping run for {run_request.run_key}, found {run.run_id}.")
return SkippedSensorRun(run_key=run_request.run_key, existing_run=run)
else:
context.logger.info(
f"Run {run.run_id} already created with the run key "
f"`{run_request.run_key}` for {external_sensor.name}"
)
return run
context.logger.info(f"Creating new run for {external_sensor.name}")
return _create_sensor_run(
instance, repo_location, external_sensor, external_pipeline, run_request, target_data
)
def _create_sensor_run(
instance, repo_location, external_sensor, external_pipeline, run_request, target_data
):
from dagster.daemon.daemon import get_telemetry_daemon_session_id
external_execution_plan = repo_location.get_external_execution_plan(
external_pipeline,
run_request.run_config,
target_data.mode,
step_keys_to_execute=None,
known_state=None,
instance=instance,
)
execution_plan_snapshot = external_execution_plan.execution_plan_snapshot
pipeline_tags = external_pipeline.tags or {}
check_tags(pipeline_tags, "pipeline_tags")
tags = merge_dicts(
merge_dicts(pipeline_tags, run_request.tags),
PipelineRun.tags_for_sensor(external_sensor),
)
if run_request.run_key:
tags[RUN_KEY_TAG] = run_request.run_key
log_action(
instance,
SENSOR_RUN_CREATED,
metadata={
"DAEMON_SESSION_ID": get_telemetry_daemon_session_id(),
"SENSOR_NAME_HASH": hash_name(external_sensor.name),
"pipeline_name_hash": hash_name(external_pipeline.name),
"repo_hash": hash_name(repo_location.name),
},
)
return instance.create_run(
pipeline_name=target_data.pipeline_name,
run_id=None,
run_config=run_request.run_config,
mode=target_data.mode,
solids_to_execute=external_pipeline.solids_to_execute,
step_keys_to_execute=None,
status=PipelineRunStatus.NOT_STARTED,
solid_selection=target_data.solid_selection,
root_run_id=None,
parent_run_id=None,
tags=tags,
pipeline_snapshot=external_pipeline.pipeline_snapshot,
execution_plan_snapshot=execution_plan_snapshot,
parent_pipeline_snapshot=external_pipeline.parent_pipeline_snapshot,
external_pipeline_origin=external_pipeline.get_external_origin(),
pipeline_code_origin=external_pipeline.get_python_origin(),
)
| import os
import sys
import time
from collections import namedtuple
import pendulum
from dagster import check, seven
from dagster.core.definitions.run_request import InstigatorType
from dagster.core.definitions.sensor_definition import DefaultSensorStatus, SensorExecutionData
from dagster.core.errors import DagsterError
from dagster.core.host_representation import PipelineSelector
from dagster.core.instance import DagsterInstance
from dagster.core.scheduler.instigation import (
InstigatorState,
InstigatorStatus,
SensorInstigatorData,
TickData,
TickStatus,
)
from dagster.core.storage.pipeline_run import PipelineRun, PipelineRunStatus, PipelineRunsFilter
from dagster.core.storage.tags import RUN_KEY_TAG, check_tags
from dagster.core.telemetry import SENSOR_RUN_CREATED, hash_name, log_action
from dagster.core.workspace import IWorkspace
from dagster.utils import merge_dicts
from dagster.utils.error import serializable_error_info_from_exc_info
RECORDED_TICK_STATES = [TickStatus.SUCCESS, TickStatus.FAILURE]
FULFILLED_TICK_STATES = [TickStatus.SKIPPED, TickStatus.SUCCESS]
MIN_INTERVAL_LOOP_TIME = 5
class DagsterSensorDaemonError(DagsterError):
"""Error when running the SensorDaemon"""
class SkippedSensorRun(namedtuple("SkippedSensorRun", "run_key existing_run")):
"""Placeholder for runs that are skipped during the run_key idempotence check"""
class SensorLaunchContext:
def __init__(self, external_sensor, job_state, tick, instance, logger):
self._external_sensor = external_sensor
self._instance = instance
self._logger = logger
self._job_state = job_state
self._tick = tick
@property
def status(self):
return self._tick.status
@property
def logger(self):
return self._logger
@property
def run_count(self):
return len(self._tick.run_ids)
def update_state(self, status, **kwargs):
skip_reason = kwargs.get("skip_reason")
cursor = kwargs.get("cursor")
origin_run_id = kwargs.get("origin_run_id")
if "skip_reason" in kwargs:
del kwargs["skip_reason"]
if "cursor" in kwargs:
del kwargs["cursor"]
if "origin_run_id" in kwargs:
del kwargs["origin_run_id"]
if kwargs:
check.inst_param(status, "status", TickStatus)
if status:
self._tick = self._tick.with_status(status=status, **kwargs)
if skip_reason:
self._tick = self._tick.with_reason(skip_reason=skip_reason)
if cursor:
self._tick = self._tick.with_cursor(cursor)
if origin_run_id:
self._tick = self._tick.with_origin_run(origin_run_id)
def add_run(self, run_id, run_key=None):
self._tick = self._tick.with_run(run_id, run_key)
def _write(self):
self._instance.update_job_tick(self._tick)
if self._tick.status in FULFILLED_TICK_STATES:
last_run_key = (
self._job_state.job_specific_data.last_run_key
if self._job_state.job_specific_data
else None
)
if self._tick.run_keys:
last_run_key = self._tick.run_keys[-1]
self._instance.update_job_state(
self._job_state.with_data(
SensorInstigatorData(
last_tick_timestamp=self._tick.timestamp,
last_run_key=last_run_key,
min_interval=self._external_sensor.min_interval_seconds,
cursor=self._tick.cursor,
)
)
)
def __enter__(self):
return self
def __exit__(self, exception_type, exception_value, traceback):
# Log the error if the failure wasn't an interrupt or the daemon generator stopping
if exception_value and not isinstance(exception_value, (KeyboardInterrupt, GeneratorExit)):
error_data = serializable_error_info_from_exc_info(sys.exc_info())
self.update_state(TickStatus.FAILURE, error=error_data)
self._write()
self._instance.purge_job_ticks(
self._job_state.job_origin_id,
tick_status=TickStatus.SKIPPED,
before=pendulum.now("UTC").subtract(days=7).timestamp(), # keep the last 7 days
)
def _check_for_debug_crash(debug_crash_flags, key):
if not debug_crash_flags:
return
kill_signal = debug_crash_flags.get(key)
if not kill_signal:
return
os.kill(os.getpid(), kill_signal)
time.sleep(10)
raise Exception("Process didn't terminate after sending crash signal")
RELOAD_WORKSPACE = 60
def execute_sensor_iteration_loop(instance, workspace, logger, until=None):
"""
Helper function that performs sensor evaluations on a tighter loop, while reusing grpc locations
within a given daemon interval. Rather than relying on the daemon machinery to run the
iteration loop every 30 seconds, sensors are continuously evaluated, every 5 seconds. We rely on
each sensor definition's min_interval to check that sensor evaluations are spaced appropriately.
"""
workspace_loaded_time = pendulum.now("UTC").timestamp()
workspace_iteration = 0
start_time = pendulum.now("UTC").timestamp()
while True:
start_time = pendulum.now("UTC").timestamp()
if until and start_time >= until:
# provide a way of organically ending the loop to support test environment
break
if start_time - workspace_loaded_time > RELOAD_WORKSPACE:
workspace.cleanup()
workspace_loaded_time = pendulum.now("UTC").timestamp()
workspace_iteration = 0
yield from execute_sensor_iteration(
instance, logger, workspace, log_verbose_checks=(workspace_iteration == 0)
)
loop_duration = pendulum.now("UTC").timestamp() - start_time
sleep_time = max(0, MIN_INTERVAL_LOOP_TIME - loop_duration)
time.sleep(sleep_time)
yield
workspace_iteration += 1
def execute_sensor_iteration(
instance, logger, workspace, log_verbose_checks=True, debug_crash_flags=None
):
check.inst_param(workspace, "workspace", IWorkspace)
check.inst_param(instance, "instance", DagsterInstance)
workspace_snapshot = {
location_entry.origin: location_entry
for location_entry in workspace.get_workspace_snapshot().values()
}
all_sensor_states = {
sensor_state.origin.get_id(): sensor_state
for sensor_state in instance.all_stored_job_state(job_type=InstigatorType.SENSOR)
}
sensors = {}
for location_entry in workspace_snapshot.values():
repo_location = location_entry.repository_location
if repo_location:
for repo in repo_location.get_repositories().values():
for sensor in repo.get_external_sensors():
origin_id = sensor.get_external_origin().get_id()
if sensor.get_current_instigator_state(
all_sensor_states.get(origin_id)
).is_running:
sensors[origin_id] = sensor
elif location_entry.load_error and log_verbose_checks:
logger.warning(
f"Could not load location {location_entry.origin.location_name} to check for sensors due to the following error: {location_entry.load_error}"
)
if log_verbose_checks:
unloadable_sensor_states = {
origin_id: sensor_state
for origin_id, sensor_state in all_sensor_states.items()
if origin_id not in sensors and sensor_state.status == InstigatorStatus.RUNNING
}
for sensor_state in unloadable_sensor_states.values():
sensor_name = sensor_state.origin.instigator_name
repo_location_origin = (
sensor_state.origin.external_repository_origin.repository_location_origin
)
repo_location_name = repo_location_origin.location_name
repo_name = sensor_state.origin.external_repository_origin.repository_name
if (
repo_location_origin not in workspace_snapshot
or not workspace_snapshot[repo_location_origin].repository_location
):
logger.warning(
f"Sensor {sensor_name} was started from a location "
f"{repo_location_name} that can no longer be found in the workspace, or has "
"metadata that has changed since the sensor was started. You can turn off "
"this sensor in the Dagit UI from the Status tab."
)
elif not workspace_snapshot[repo_location_origin].repository_location.has_repository(
repo_name
):
logger.warning(
f"Could not find repository {repo_name} in location {repo_location_name} to "
+ f"run sensor {sensor_name}. If this repository no longer exists, you can "
+ "turn off the sensor in the Dagit UI from the Status tab.",
)
else:
logger.warning(
f"Could not find sensor {sensor_name} in repository {repo_name}. If this "
"sensor no longer exists, you can turn it off in the Dagit UI from the "
"Status tab.",
)
if not sensors:
if log_verbose_checks:
logger.info("Not checking for any runs since no sensors have been started.")
yield
return
now = pendulum.now("UTC")
for external_sensor in sensors.values():
sensor_name = external_sensor.name
sensor_debug_crash_flags = debug_crash_flags.get(sensor_name) if debug_crash_flags else None
error_info = None
try:
sensor_state = all_sensor_states.get(external_sensor.get_external_origin().get_id())
if not sensor_state:
assert external_sensor.default_status == DefaultSensorStatus.RUNNING
sensor_state = InstigatorState(
external_sensor.get_external_origin(),
InstigatorType.SENSOR,
InstigatorStatus.AUTOMATICALLY_RUNNING,
SensorInstigatorData(min_interval=external_sensor.min_interval_seconds),
)
instance.add_job_state(sensor_state)
elif _is_under_min_interval(sensor_state, external_sensor, now):
continue
tick = instance.create_job_tick(
TickData(
job_origin_id=sensor_state.job_origin_id,
job_name=sensor_state.job_name,
job_type=InstigatorType.SENSOR,
status=TickStatus.STARTED,
timestamp=now.timestamp(),
)
)
_check_for_debug_crash(sensor_debug_crash_flags, "TICK_CREATED")
with SensorLaunchContext(
external_sensor, sensor_state, tick, instance, logger
) as tick_context:
_check_for_debug_crash(sensor_debug_crash_flags, "TICK_HELD")
yield from _evaluate_sensor(
tick_context,
instance,
workspace,
external_sensor,
sensor_state,
sensor_debug_crash_flags,
)
except Exception:
error_info = serializable_error_info_from_exc_info(sys.exc_info())
logger.error(
"Sensor daemon caught an error for sensor {sensor_name} : {error_info}".format(
sensor_name=external_sensor.name,
error_info=error_info.to_string(),
)
)
yield error_info
def _evaluate_sensor(
context,
instance,
workspace,
external_sensor,
job_state,
sensor_debug_crash_flags=None,
):
context.logger.info(f"Checking for new runs for sensor: {external_sensor.name}")
sensor_origin = external_sensor.get_external_origin()
repository_handle = external_sensor.handle.repository_handle
repo_location = workspace.get_location(
sensor_origin.external_repository_origin.repository_location_origin
)
sensor_runtime_data = repo_location.get_external_sensor_execution_data(
instance,
repository_handle,
external_sensor.name,
job_state.job_specific_data.last_tick_timestamp if job_state.job_specific_data else None,
job_state.job_specific_data.last_run_key if job_state.job_specific_data else None,
job_state.job_specific_data.cursor if job_state.job_specific_data else None,
)
yield
assert isinstance(sensor_runtime_data, SensorExecutionData)
if not sensor_runtime_data.run_requests:
if sensor_runtime_data.pipeline_run_reactions:
for pipeline_run_reaction in sensor_runtime_data.pipeline_run_reactions:
origin_run_id = pipeline_run_reaction.pipeline_run.run_id
if pipeline_run_reaction.error:
context.logger.error(
f"Got a reaction request for run {origin_run_id} but execution errorred: {pipeline_run_reaction.error}"
)
context.update_state(
TickStatus.FAILURE,
cursor=sensor_runtime_data.cursor,
error=pipeline_run_reaction.error,
)
else:
# log to the original pipeline run
message = (
f'Sensor "{external_sensor.name}" acted on run status '
f"{pipeline_run_reaction.pipeline_run.status.value} of run {origin_run_id}."
)
instance.report_engine_event(
message=message, pipeline_run=pipeline_run_reaction.pipeline_run
)
context.logger.info(
f"Completed a reaction request for run {origin_run_id}: {message}"
)
context.update_state(
TickStatus.SUCCESS,
cursor=sensor_runtime_data.cursor,
origin_run_id=origin_run_id,
)
elif sensor_runtime_data.skip_message:
context.logger.info(
f"Sensor {external_sensor.name} skipped: {sensor_runtime_data.skip_message}"
)
context.update_state(
TickStatus.SKIPPED,
skip_reason=sensor_runtime_data.skip_message,
cursor=sensor_runtime_data.cursor,
)
else:
context.logger.info(f"No run requests returned for {external_sensor.name}, skipping")
context.update_state(TickStatus.SKIPPED, cursor=sensor_runtime_data.cursor)
yield
return
skipped_runs = []
for run_request in sensor_runtime_data.run_requests:
target_data = external_sensor.get_target_data(run_request.job_name)
pipeline_selector = PipelineSelector(
location_name=repo_location.name,
repository_name=sensor_origin.external_repository_origin.repository_name,
pipeline_name=target_data.pipeline_name,
solid_selection=target_data.solid_selection,
)
external_pipeline = repo_location.get_external_pipeline(pipeline_selector)
run = _get_or_create_sensor_run(
context,
instance,
repo_location,
external_sensor,
external_pipeline,
run_request,
target_data,
)
if isinstance(run, SkippedSensorRun):
skipped_runs.append(run)
yield
continue
_check_for_debug_crash(sensor_debug_crash_flags, "RUN_CREATED")
error_info = None
try:
context.logger.info(
"Launching run for {sensor_name}".format(sensor_name=external_sensor.name)
)
instance.submit_run(run.run_id, workspace)
context.logger.info(
"Completed launch of run {run_id} for {sensor_name}".format(
run_id=run.run_id, sensor_name=external_sensor.name
)
)
except Exception:
error_info = serializable_error_info_from_exc_info(sys.exc_info())
context.logger.error(
f"Run {run.run_id} created successfully but failed to launch: " f"{str(error_info)}"
)
yield error_info
_check_for_debug_crash(sensor_debug_crash_flags, "RUN_LAUNCHED")
context.add_run(run_id=run.run_id, run_key=run_request.run_key)
if skipped_runs:
run_keys = [skipped.run_key for skipped in skipped_runs]
skipped_count = len(skipped_runs)
context.logger.info(
f"Skipping {skipped_count} {'run' if skipped_count == 1 else 'runs'} for sensor "
f"{external_sensor.name} already completed with run keys: {seven.json.dumps(run_keys)}"
)
if context.run_count:
context.update_state(TickStatus.SUCCESS, cursor=sensor_runtime_data.cursor)
else:
context.update_state(TickStatus.SKIPPED, cursor=sensor_runtime_data.cursor)
yield
def _is_under_min_interval(job_state, external_sensor, now):
if not job_state.job_specific_data:
return False
if not job_state.job_specific_data.last_tick_timestamp:
return False
if not external_sensor.min_interval_seconds:
return False
elapsed = now.timestamp() - job_state.job_specific_data.last_tick_timestamp
return elapsed < external_sensor.min_interval_seconds
def _get_or_create_sensor_run(
context, instance, repo_location, external_sensor, external_pipeline, run_request, target_data
):
if not run_request.run_key:
return _create_sensor_run(
instance, repo_location, external_sensor, external_pipeline, run_request, target_data
)
existing_runs = instance.get_runs(
PipelineRunsFilter(
tags=merge_dicts(
PipelineRun.tags_for_sensor(external_sensor),
{RUN_KEY_TAG: run_request.run_key},
)
)
)
if len(existing_runs):
run = existing_runs[0]
if run.status != PipelineRunStatus.NOT_STARTED:
# A run already exists and was launched for this time period,
# but the daemon must have crashed before the tick could be put
# into a SUCCESS state
context.logger.info(f"Skipping run for {run_request.run_key}, found {run.run_id}.")
return SkippedSensorRun(run_key=run_request.run_key, existing_run=run)
else:
context.logger.info(
f"Run {run.run_id} already created with the run key "
f"`{run_request.run_key}` for {external_sensor.name}"
)
return run
context.logger.info(f"Creating new run for {external_sensor.name}")
return _create_sensor_run(
instance, repo_location, external_sensor, external_pipeline, run_request, target_data
)
def _create_sensor_run(
instance, repo_location, external_sensor, external_pipeline, run_request, target_data
):
from dagster.daemon.daemon import get_telemetry_daemon_session_id
external_execution_plan = repo_location.get_external_execution_plan(
external_pipeline,
run_request.run_config,
target_data.mode,
step_keys_to_execute=None,
known_state=None,
instance=instance,
)
execution_plan_snapshot = external_execution_plan.execution_plan_snapshot
pipeline_tags = external_pipeline.tags or {}
check_tags(pipeline_tags, "pipeline_tags")
tags = merge_dicts(
merge_dicts(pipeline_tags, run_request.tags),
PipelineRun.tags_for_sensor(external_sensor),
)
if run_request.run_key:
tags[RUN_KEY_TAG] = run_request.run_key
log_action(
instance,
SENSOR_RUN_CREATED,
metadata={
"DAEMON_SESSION_ID": get_telemetry_daemon_session_id(),
"SENSOR_NAME_HASH": hash_name(external_sensor.name),
"pipeline_name_hash": hash_name(external_pipeline.name),
"repo_hash": hash_name(repo_location.name),
},
)
return instance.create_run(
pipeline_name=target_data.pipeline_name,
run_id=None,
run_config=run_request.run_config,
mode=target_data.mode,
solids_to_execute=external_pipeline.solids_to_execute,
step_keys_to_execute=None,
status=PipelineRunStatus.NOT_STARTED,
solid_selection=target_data.solid_selection,
root_run_id=None,
parent_run_id=None,
tags=tags,
pipeline_snapshot=external_pipeline.pipeline_snapshot,
execution_plan_snapshot=execution_plan_snapshot,
parent_pipeline_snapshot=external_pipeline.parent_pipeline_snapshot,
external_pipeline_origin=external_pipeline.get_external_origin(),
pipeline_code_origin=external_pipeline.get_python_origin(),
)
|
import re
from requests import get
from datetime import datetime
from time import sleep
from bs4 import BeautifulSoup
now = datetime.now()
time = datetime.strftime(now, "\n%d-%B-%Y\t%H:%M:%S:%f\n")
types = {
"dollar": {
"name": "DOLAR",
"path": "/serbest-piyasa/amerikan-dolari",
"tag": "div",
"class": "market-data",
"regex": "DOLAR(\S+)"
},
"pound": {
"name": "STERLIN/POUND",
"path": "/serbest-piyasa/amerikan-dolari",
"tag": "div",
"class": "market-data",
"regex": "STERLİN(\S+)"
},
"gram_gold": {
"name": "GRAM GOLD",
"path": "/serbest-piyasa/amerikan-dolari",
"tag": "div",
"class": "market-data",
"regex": "ALTIN(\S+)"
},
"euro": {
"name": "EURO",
"path": "/serbest-piyasa/amerikan-dolari",
"tag": "div",
"class": "market-data",
"regex": "EURO(\S+)"
}
}
types_2 = {
"bitcoin": {
"name": "BITCOIN",
"path": "/kripto-paralar/bitcoin",
"tag": "ul",
"class": "piyasa-ozeti",
"regex": "Bitcoin\s+%\s-?[\d,]+\s+\$?([\d\.,]+)"
}
}
def exc_try():
for typ in types:
exchangeURL = "https://kur.doviz.com" + types[typ]["path"]
r = get(exchangeURL)
soup = BeautifulSoup(r.content, "html.parser")
marketSumForex = soup.find_all("div", {"class": "market-data"})
divs = soup.find_all(types[typ]["tag"], {types[typ]["class"]})
all_texts = divs[-1].text
raw_text = all_texts.replace("\n", "")
value = re.findall(types[typ]["regex"], raw_text)[0]
value_rep = value.replace(".", "").replace(",", ".")
value_last = round(float(value_rep), 2)
print(
f"{decor}\n\tCompared to {types[typ]["name"]}\nThe value of it, right now: ₺ {value_last}\n\t\tYou may have {round(amount/(value_last), 4)}")
def btc_try():
# dollar
exchangeURL = "https://kur.doviz.com" + types["dollar"]["path"]
r = get(exchangeURL)
soup = BeautifulSoup(r.content, "html.parser")
marketSumForex = soup.find_all("div", {"class": "market-data"})
divs = soup.find_all(types["dollar"]["tag"], {types["dollar"]["class"]})
all_texts = divs[-1].text
raw_text = all_texts.replace("\n", "")
value = re.findall(types["dollar"]["regex"], raw_text)[0]
value_rep = value.replace(".", "").replace(",", ".")
value_last_dollar = round(float(value_rep), 2)
# bitcoin
exchangeURL = "https://kur.doviz.com" + types_2["bitcoin"]["path"]
r = get(exchangeURL)
soup = BeautifulSoup(r.content, "html.parser")
marketSumForex = soup.find_all("div", {"class": "market-data"})
divs = soup.find_all(types_2["bitcoin"]["tag"], {
types_2["bitcoin"]["class"]})
all_texts = divs[-1].text
raw_text = all_texts.replace("\n", "")
value = re.findall(types_2["bitcoin"]["regex"], raw_text)[-1]
value_rep = value.replace(".", "").replace(",", ".")
value_last_btc = round(float(value_rep), 2)
btc_try = value_last_dollar * value_last_btc
print(
f"{decor}\n\tCompared to {types_2["bitcoin"]["name"]}\n\t\tYou may have {round(amount/(btc_try), 8)}")
if __name__ == '__main__':
while True:
decor = ("*"*50)
msg = "Welcome to Instant Exchange Convertor".center(50, "*")
exe = input(
f"\n{decor}\n{msg}\n{decor}\nFor starting, type 's'\nFor quitting, type 'q'\nWhat\'s your choice: ")
if exe == "s" or exe == "S":
amount = round(
float(input(f"\nPlease enter an amount (TRY) to invest in: ")), 2)
print(
f"\nThe exact moment right now is; {time}\nYou have '₺ {amount}' for investing.\nAccording to the instant situation of the markets;")
exc_try()
btc_try()
sleep(60)
print("\nRestarting in 10 secs...")
sleep(10)
elif exe == "q" or exe == "Q":
print("\nProgram is shutting down... Open it again whenever you need to.")
sleep(10)
break
else:
print("Type error! Please try again with correct letter;")
exe
| import re
from requests import get
from datetime import datetime
from time import sleep
from bs4 import BeautifulSoup
now = datetime.now()
time = datetime.strftime(now, "\n%d-%B-%Y\t%H:%M:%S:%f\n")
types = {
"dollar": {
"name": "DOLAR",
"path": "/serbest-piyasa/amerikan-dolari",
"tag": "div",
"class": "market-data",
"regex": "DOLAR(\S+)"
},
"pound": {
"name": "STERLIN/POUND",
"path": "/serbest-piyasa/amerikan-dolari",
"tag": "div",
"class": "market-data",
"regex": "STERLİN(\S+)"
},
"gram_gold": {
"name": "GRAM GOLD",
"path": "/serbest-piyasa/amerikan-dolari",
"tag": "div",
"class": "market-data",
"regex": "ALTIN(\S+)"
},
"euro": {
"name": "EURO",
"path": "/serbest-piyasa/amerikan-dolari",
"tag": "div",
"class": "market-data",
"regex": "EURO(\S+)"
}
}
types_2 = {
"bitcoin": {
"name": "BITCOIN",
"path": "/kripto-paralar/bitcoin",
"tag": "ul",
"class": "piyasa-ozeti",
"regex": "Bitcoin\s+%\s-?[\d,]+\s+\$?([\d\.,]+)"
}
}
def exc_try():
for typ in types:
exchangeURL = "https://kur.doviz.com" + types[typ]["path"]
r = get(exchangeURL)
soup = BeautifulSoup(r.content, "html.parser")
marketSumForex = soup.find_all("div", {"class": "market-data"})
divs = soup.find_all(types[typ]["tag"], {types[typ]["class"]})
all_texts = divs[-1].text
raw_text = all_texts.replace("\n", "")
value = re.findall(types[typ]["regex"], raw_text)[0]
value_rep = value.replace(".", "").replace(",", ".")
value_last = round(float(value_rep), 2)
print(
f"{decor}\n\tCompared to {types[typ]['name']}\nThe value of it, right now: ₺ {value_last}\n\t\tYou may have {round(amount/(value_last), 4)}")
def btc_try():
# dollar
exchangeURL = "https://kur.doviz.com" + types["dollar"]["path"]
r = get(exchangeURL)
soup = BeautifulSoup(r.content, "html.parser")
marketSumForex = soup.find_all("div", {"class": "market-data"})
divs = soup.find_all(types["dollar"]["tag"], {types["dollar"]["class"]})
all_texts = divs[-1].text
raw_text = all_texts.replace("\n", "")
value = re.findall(types["dollar"]["regex"], raw_text)[0]
value_rep = value.replace(".", "").replace(",", ".")
value_last_dollar = round(float(value_rep), 2)
# bitcoin
exchangeURL = "https://kur.doviz.com" + types_2["bitcoin"]["path"]
r = get(exchangeURL)
soup = BeautifulSoup(r.content, "html.parser")
marketSumForex = soup.find_all("div", {"class": "market-data"})
divs = soup.find_all(types_2["bitcoin"]["tag"], {
types_2["bitcoin"]["class"]})
all_texts = divs[-1].text
raw_text = all_texts.replace("\n", "")
value = re.findall(types_2["bitcoin"]["regex"], raw_text)[-1]
value_rep = value.replace(".", "").replace(",", ".")
value_last_btc = round(float(value_rep), 2)
btc_try = value_last_dollar * value_last_btc
print(
f"{decor}\n\tCompared to {types_2['bitcoin']['name']}\n\t\tYou may have {round(amount/(btc_try), 8)}")
if __name__ == '__main__':
while True:
decor = ("*"*50)
msg = "Welcome to Instant Exchange Convertor".center(50, "*")
exe = input(
f"\n{decor}\n{msg}\n{decor}\nFor starting, type 's'\nFor quitting, type 'q'\nWhat\'s your choice: ")
if exe == "s" or exe == "S":
amount = round(
float(input(f"\nPlease enter an amount (TRY) to invest in: ")), 2)
print(
f"\nThe exact moment right now is; {time}\nYou have '₺ {amount}' for investing.\nAccording to the instant situation of the markets;")
exc_try()
btc_try()
sleep(60)
print("\nRestarting in 10 secs...")
sleep(10)
elif exe == "q" or exe == "Q":
print("\nProgram is shutting down... Open it again whenever you need to.")
sleep(10)
break
else:
print("Type error! Please try again with correct letter;")
exe
|
from BaseUserHandler import *
import datetime as dt
class EditExerciseHandler(BaseUserHandler):
def get(self, course, assignment, exercise):
try:
if self.is_administrator() or self.is_instructor_for_course(course) or self.is_assistant_for_course(course):
exercises = self.content.get_exercises(course, assignment)
exercise_basics = self.content.get_exercise_basics(course, assignment, exercise)
exercise_details = self.content.get_exercise_details(course, assignment, exercise)
exercise_details["expected_text_output"] = format_output_as_html(exercise_details["expected_text_output"])
next_prev_exercises = self.content.get_next_prev_exercises(course, assignment, exercise, exercises)
self.render("edit_exercise.html", courses=self.content.get_courses(), assignments=self.content.get_assignments(course), exercises=exercises, tests=self.content.get_tests(course, assignment, exercise), exercise_statuses=self.content.get_exercise_statuses(course, assignment, self.get_user_info()["user_id"]), course_basics=self.content.get_course_basics(course), assignment_basics=self.content.get_assignment_basics(course, assignment), exercise_basics=exercise_basics, exercise_details=exercise_details, json_files=escape_json_string(json.dumps(exercise_details["data_files"])), next_exercise=next_prev_exercises["next"], prev_exercise=next_prev_exercises["previous"], code_completion_path=self.settings_dict["back_ends"][exercise_details["back_end"]]["code_completion_path"], back_ends=sort_nicely(self.settings_dict["back_ends"].keys()), result=None, user_info=self.get_user_info(), old_text_output='', old_image_output='', old_tests=[])
else:
self.render("permissions.html")
except Exception as inst:
render_error(self, traceback.format_exc())
def post(self, course, assignment, exercise):
try:
if not self.is_administrator() and not self.is_instructor_for_course(course) or self.is_assistant_for_course(course):
self.render("permissions.html")
return
exercise_basics = self.content.get_exercise_basics(course, assignment, exercise)
exercise_details = self.content.get_exercise_details(course, assignment, exercise)
# Saves previous outputs and tests in case 'maintain_output' is selected.
old_text_output = exercise_details["expected_text_output"]
old_image_output = exercise_details["expected_image_output"]
old_tests = exercise_details["tests"]
# Saves number of old tests. If there are fewer old than new tests, CodeBuddy will later raise a warning.
num_old_tests = len(old_tests)
exercise_basics["title"] = self.get_body_argument("title").strip() #required
exercise_basics["visible"] = self.get_body_argument("is_visible") == "Yes"
exercise_details["instructions"] = remove_html_tags(self.get_body_argument("instructions").strip().replace("\r", ""))
exercise_details["back_end"] = self.get_body_argument("back_end")
exercise_details["output_type"] = self.get_body_argument("output_type")
exercise_details["allow_any_response"] = self.get_body_argument("allow_any_response") == "Yes"
exercise_details["answer_code"] = self.get_body_argument("answer_code_text").strip().replace("\r", "") #required (usually)
exercise_details["answer_description"] = self.get_body_argument("answer_description").strip().replace("\r", "")
exercise_details["hint"] = self.get_body_argument("hint").strip().replace("\r", "")
exercise_details["max_submissions"] = int(self.get_body_argument("max_submissions"))
exercise_details["starter_code"] = self.get_body_argument("starter_code_text").strip().replace("\r", "")
exercise_details["credit"] = self.get_body_argument("credit").strip().replace("\r", "")
exercise_details["show_expected"] = self.get_body_argument("show_expected") == "Yes"
exercise_details["show_answer"] = self.get_body_argument("show_answer") == "Yes"
exercise_details["show_student_submissions"] = self.get_body_argument("show_student_submissions") == "Yes"
exercise_details["enable_pair_programming"] = self.get_body_argument("enable_pair_programming") == "Yes"
exercise_details["hold_output_constant"] = self.get_body_argument("hold_output_constant") == "Yes"
# Saves check_code into a temporary variable to reload into exercise_details after code has finished executing.
exercise_details["check_code"] = ""
check_code = self.get_body_argument("check_code_text").strip().replace("\r", "")
tests = self.get_body_argument("tests_json")
tests = json.loads(tests) if tests and len(tests) != 0 else []
exercise_details["tests"] = tests
old_files = self.get_body_argument("file_container")
new_files = self.request.files
if old_files and old_files != "{}":
old_files = json.loads(old_files)
exercise_details["data_files"] = old_files
else:
exercise_details["data_files"] = {}
result = "Success: The exercise was saved!"
if exercise_basics["title"] == "" or exercise_details["instructions"] == "" or (not exercise_details["allow_any_response"] and exercise_details["answer_code"] == ""):
result = "Error: One of the required fields is missing."
else:
if self.content.has_duplicate_title(self.content.get_exercises(course, assignment), exercise_basics["id"], exercise_basics["title"]):
result = "Error: An exercise with that title already exists in this assignment."
else:
if len(exercise_basics["title"]) > 80:
result = "Error: The title cannot exceed 80 characters."
else:
#if not re.match('^[a-zA-Z0-9()\s\"\-]*$', exercise_basics["title"]):
# result = "Error: The title can only contain alphanumeric characters, spaces, hyphens, and parentheses."
#else:
if new_files:
data_files = {}
total_size = 0
#create data_files dictionary
for fileInput, fileContents in new_files.items():
for i in range(len(fileContents)):
data_files[fileContents[i]["filename"]] = fileContents[i]["body"].decode("utf-8")
total_size += len(fileContents[i]["body"])
exercise_details["data_files"].update(data_files)
# Make sure total file size is not larger than 10 MB across all files.
if total_size > 10 * 1024 * 1024:
result = f"Error: Your total file size is too large ({total_size} bytes)."
if exercise_basics['exists'] and exercise_details["hold_output_constant"]:
# Sets exercise_details["tests"] temporarily in order to check exercise output
exercise_details["expected_text_output"], exercise_details["expected_image_output"], exercise_details["tests"] = exec_code(self.settings_dict, exercise_details["answer_code"], exercise_basics, exercise_details)
diff, passed, test_outcomes = check_exercise_output(exercise_details, old_text_output, old_image_output, old_tests)
if not passed or not all(list(map(lambda x: x["passed"], test_outcomes))):
result = "Error: new output does not match pre-existing output."
else:
# Returns exercise_details['tests'] to its new tests.
exercise_details["tests"] = tests
if not result.startswith("Error:"):
old_tests = []
old_text_output = old_image_output = ''
self.content.specify_exercise_basics(exercise_basics, exercise_basics["title"], exercise_basics["visible"])
self.content.specify_exercise_details(exercise_details, exercise_details["instructions"], exercise_details["back_end"], exercise_details["output_type"], exercise_details["answer_code"], exercise_details["answer_description"], exercise_details["hint"], exercise_details["max_submissions"], exercise_details["starter_code"], exercise_details["test_code"], exercise_details["credit"], exercise_details["data_files"], exercise_details["show_expected"], exercise_details["show_test_code"], exercise_details["show_answer"], exercise_details["show_student_submissions"], "", "", None, dt.datetime.now(), exercise_details["enable_pair_programming"], exercise_details["check_code"], exercise_details["tests"])
text_output, image_output, tests = exec_code(self.settings_dict, exercise_details["answer_code"], exercise_basics, exercise_details)
# Calculates number of empty test outputs to aid instructor in debugging.
empty_tests = list(filter(lambda x: x["text_output"] == "" and x["image_output"] == "", tests))
# Loads test outcomes into dictionary with test code.
tests_dict = []
for i in range(len(tests)):
tests_dict.append({**tests[i], **exercise_details["tests"][i]})
exercise_details["tests"] = tests_dict
exercise_details["expected_text_output"] = text_output.strip()
exercise_details["expected_image_output"] = image_output
if not exercise_details["allow_any_response"] and text_output == "" and image_output == "" and len(empty_tests) == len(tests):
result = f"Error: No output was produced."
else:
# If some but not all of tests have empty outputs, the exercise will still be saved but the instructor will be flagged with all tests that didn't produce any output.
if len(empty_tests) > 0:
result = f"Warning: {len(empty_tests)} of your tests produced no output."
if exercise:
# Get scores from content (which also contains data about the number of submissions in an exercise)
scores = self.content.get_exercise_scores(course, assignment, exercise)
num_submissions = sum(list(map(lambda x: int(x[1]["num_submissions"]), scores)))
else:
num_submissions = 0
# If number of tests is greater than before last save and number of submissions on this exercise is greater than zero, raise warning.
if num_old_tests < len(tests) and num_submissions > 0:
result = f"Warning: You have increased the number of tests, and this exercise already has {num_submissions} submissions. This will render the output of those submissions unviewable for students. However, their submission scores will not change."
exercise_details["check_code"] = check_code
exercise = self.content.save_exercise(exercise_basics, exercise_details)
exercise_basics = self.content.get_exercise_basics(course, assignment, exercise)
exercise_details = self.content.get_exercise_details(course, assignment, exercise)
exercises = self.content.get_exercises(course, assignment)
next_prev_exercises = self.content.get_next_prev_exercises(course, assignment, exercise, exercises)
self.render("edit_exercise.html", courses=self.content.get_courses(), assignments=self.content.get_assignments(course), exercises=exercises, tests=self.content.get_tests(course, assignment, exercise), exercise_statuses=self.content.get_exercise_statuses(course, assignment, self.get_user_info()["user_id"]), course_basics=self.content.get_course_basics(course), assignment_basics=self.content.get_assignment_basics(course, assignment), exercise_basics=exercise_basics, exercise_details=exercise_details, json_files=escape_json_string(json.dumps(exercise_details["data_files"])), next_exercise=next_prev_exercises["next"], prev_exercise=next_prev_exercises["previous"], code_completion_path=self.settings_dict["back_ends"][exercise_details["back_end"]]["code_completion_path"], back_ends=sort_nicely(self.settings_dict["back_ends"].keys()), result=result, user_info=self.get_user_info(), old_text_output=old_text_output, old_image_output=old_image_output, old_tests=old_tests)
except ConnectionError as inst:
render_error(self, "The front-end server was unable to contact the back-end server.")
except ReadTimeout as inst:
render_error(self, f"Your solution timed out after {self.settings_dict["back_ends"][exercise_details["back_end"]]["timeout_seconds"]} seconds.")
except Exception as inst:
render_error(self, traceback.format_exc())
| from BaseUserHandler import *
import datetime as dt
class EditExerciseHandler(BaseUserHandler):
def get(self, course, assignment, exercise):
try:
if self.is_administrator() or self.is_instructor_for_course(course) or self.is_assistant_for_course(course):
exercises = self.content.get_exercises(course, assignment)
exercise_basics = self.content.get_exercise_basics(course, assignment, exercise)
exercise_details = self.content.get_exercise_details(course, assignment, exercise)
exercise_details["expected_text_output"] = format_output_as_html(exercise_details["expected_text_output"])
next_prev_exercises = self.content.get_next_prev_exercises(course, assignment, exercise, exercises)
self.render("edit_exercise.html", courses=self.content.get_courses(), assignments=self.content.get_assignments(course), exercises=exercises, tests=self.content.get_tests(course, assignment, exercise), exercise_statuses=self.content.get_exercise_statuses(course, assignment, self.get_user_info()["user_id"]), course_basics=self.content.get_course_basics(course), assignment_basics=self.content.get_assignment_basics(course, assignment), exercise_basics=exercise_basics, exercise_details=exercise_details, json_files=escape_json_string(json.dumps(exercise_details["data_files"])), next_exercise=next_prev_exercises["next"], prev_exercise=next_prev_exercises["previous"], code_completion_path=self.settings_dict["back_ends"][exercise_details["back_end"]]["code_completion_path"], back_ends=sort_nicely(self.settings_dict["back_ends"].keys()), result=None, user_info=self.get_user_info(), old_text_output='', old_image_output='', old_tests=[])
else:
self.render("permissions.html")
except Exception as inst:
render_error(self, traceback.format_exc())
def post(self, course, assignment, exercise):
try:
if not self.is_administrator() and not self.is_instructor_for_course(course) or self.is_assistant_for_course(course):
self.render("permissions.html")
return
exercise_basics = self.content.get_exercise_basics(course, assignment, exercise)
exercise_details = self.content.get_exercise_details(course, assignment, exercise)
# Saves previous outputs and tests in case 'maintain_output' is selected.
old_text_output = exercise_details["expected_text_output"]
old_image_output = exercise_details["expected_image_output"]
old_tests = exercise_details["tests"]
# Saves number of old tests. If there are fewer old than new tests, CodeBuddy will later raise a warning.
num_old_tests = len(old_tests)
exercise_basics["title"] = self.get_body_argument("title").strip() #required
exercise_basics["visible"] = self.get_body_argument("is_visible") == "Yes"
exercise_details["instructions"] = remove_html_tags(self.get_body_argument("instructions").strip().replace("\r", ""))
exercise_details["back_end"] = self.get_body_argument("back_end")
exercise_details["output_type"] = self.get_body_argument("output_type")
exercise_details["allow_any_response"] = self.get_body_argument("allow_any_response") == "Yes"
exercise_details["answer_code"] = self.get_body_argument("answer_code_text").strip().replace("\r", "") #required (usually)
exercise_details["answer_description"] = self.get_body_argument("answer_description").strip().replace("\r", "")
exercise_details["hint"] = self.get_body_argument("hint").strip().replace("\r", "")
exercise_details["max_submissions"] = int(self.get_body_argument("max_submissions"))
exercise_details["starter_code"] = self.get_body_argument("starter_code_text").strip().replace("\r", "")
exercise_details["credit"] = self.get_body_argument("credit").strip().replace("\r", "")
exercise_details["show_expected"] = self.get_body_argument("show_expected") == "Yes"
exercise_details["show_answer"] = self.get_body_argument("show_answer") == "Yes"
exercise_details["show_student_submissions"] = self.get_body_argument("show_student_submissions") == "Yes"
exercise_details["enable_pair_programming"] = self.get_body_argument("enable_pair_programming") == "Yes"
exercise_details["hold_output_constant"] = self.get_body_argument("hold_output_constant") == "Yes"
# Saves check_code into a temporary variable to reload into exercise_details after code has finished executing.
exercise_details["check_code"] = ""
check_code = self.get_body_argument("check_code_text").strip().replace("\r", "")
tests = self.get_body_argument("tests_json")
tests = json.loads(tests) if tests and len(tests) != 0 else []
exercise_details["tests"] = tests
old_files = self.get_body_argument("file_container")
new_files = self.request.files
if old_files and old_files != "{}":
old_files = json.loads(old_files)
exercise_details["data_files"] = old_files
else:
exercise_details["data_files"] = {}
result = "Success: The exercise was saved!"
if exercise_basics["title"] == "" or exercise_details["instructions"] == "" or (not exercise_details["allow_any_response"] and exercise_details["answer_code"] == ""):
result = "Error: One of the required fields is missing."
else:
if self.content.has_duplicate_title(self.content.get_exercises(course, assignment), exercise_basics["id"], exercise_basics["title"]):
result = "Error: An exercise with that title already exists in this assignment."
else:
if len(exercise_basics["title"]) > 80:
result = "Error: The title cannot exceed 80 characters."
else:
#if not re.match('^[a-zA-Z0-9()\s\"\-]*$', exercise_basics["title"]):
# result = "Error: The title can only contain alphanumeric characters, spaces, hyphens, and parentheses."
#else:
if new_files:
data_files = {}
total_size = 0
#create data_files dictionary
for fileInput, fileContents in new_files.items():
for i in range(len(fileContents)):
data_files[fileContents[i]["filename"]] = fileContents[i]["body"].decode("utf-8")
total_size += len(fileContents[i]["body"])
exercise_details["data_files"].update(data_files)
# Make sure total file size is not larger than 10 MB across all files.
if total_size > 10 * 1024 * 1024:
result = f"Error: Your total file size is too large ({total_size} bytes)."
if exercise_basics['exists'] and exercise_details["hold_output_constant"]:
# Sets exercise_details["tests"] temporarily in order to check exercise output
exercise_details["expected_text_output"], exercise_details["expected_image_output"], exercise_details["tests"] = exec_code(self.settings_dict, exercise_details["answer_code"], exercise_basics, exercise_details)
diff, passed, test_outcomes = check_exercise_output(exercise_details, old_text_output, old_image_output, old_tests)
if not passed or not all(list(map(lambda x: x["passed"], test_outcomes))):
result = "Error: new output does not match pre-existing output."
else:
# Returns exercise_details['tests'] to its new tests.
exercise_details["tests"] = tests
if not result.startswith("Error:"):
old_tests = []
old_text_output = old_image_output = ''
self.content.specify_exercise_basics(exercise_basics, exercise_basics["title"], exercise_basics["visible"])
self.content.specify_exercise_details(exercise_details, exercise_details["instructions"], exercise_details["back_end"], exercise_details["output_type"], exercise_details["answer_code"], exercise_details["answer_description"], exercise_details["hint"], exercise_details["max_submissions"], exercise_details["starter_code"], exercise_details["test_code"], exercise_details["credit"], exercise_details["data_files"], exercise_details["show_expected"], exercise_details["show_test_code"], exercise_details["show_answer"], exercise_details["show_student_submissions"], "", "", None, dt.datetime.now(), exercise_details["enable_pair_programming"], exercise_details["check_code"], exercise_details["tests"])
text_output, image_output, tests = exec_code(self.settings_dict, exercise_details["answer_code"], exercise_basics, exercise_details)
# Calculates number of empty test outputs to aid instructor in debugging.
empty_tests = list(filter(lambda x: x["text_output"] == "" and x["image_output"] == "", tests))
# Loads test outcomes into dictionary with test code.
tests_dict = []
for i in range(len(tests)):
tests_dict.append({**tests[i], **exercise_details["tests"][i]})
exercise_details["tests"] = tests_dict
exercise_details["expected_text_output"] = text_output.strip()
exercise_details["expected_image_output"] = image_output
if not exercise_details["allow_any_response"] and text_output == "" and image_output == "" and len(empty_tests) == len(tests):
result = f"Error: No output was produced."
else:
# If some but not all of tests have empty outputs, the exercise will still be saved but the instructor will be flagged with all tests that didn't produce any output.
if len(empty_tests) > 0:
result = f"Warning: {len(empty_tests)} of your tests produced no output."
if exercise:
# Get scores from content (which also contains data about the number of submissions in an exercise)
scores = self.content.get_exercise_scores(course, assignment, exercise)
num_submissions = sum(list(map(lambda x: int(x[1]["num_submissions"]), scores)))
else:
num_submissions = 0
# If number of tests is greater than before last save and number of submissions on this exercise is greater than zero, raise warning.
if num_old_tests < len(tests) and num_submissions > 0:
result = f"Warning: You have increased the number of tests, and this exercise already has {num_submissions} submissions. This will render the output of those submissions unviewable for students. However, their submission scores will not change."
exercise_details["check_code"] = check_code
exercise = self.content.save_exercise(exercise_basics, exercise_details)
exercise_basics = self.content.get_exercise_basics(course, assignment, exercise)
exercise_details = self.content.get_exercise_details(course, assignment, exercise)
exercises = self.content.get_exercises(course, assignment)
next_prev_exercises = self.content.get_next_prev_exercises(course, assignment, exercise, exercises)
self.render("edit_exercise.html", courses=self.content.get_courses(), assignments=self.content.get_assignments(course), exercises=exercises, tests=self.content.get_tests(course, assignment, exercise), exercise_statuses=self.content.get_exercise_statuses(course, assignment, self.get_user_info()["user_id"]), course_basics=self.content.get_course_basics(course), assignment_basics=self.content.get_assignment_basics(course, assignment), exercise_basics=exercise_basics, exercise_details=exercise_details, json_files=escape_json_string(json.dumps(exercise_details["data_files"])), next_exercise=next_prev_exercises["next"], prev_exercise=next_prev_exercises["previous"], code_completion_path=self.settings_dict["back_ends"][exercise_details["back_end"]]["code_completion_path"], back_ends=sort_nicely(self.settings_dict["back_ends"].keys()), result=result, user_info=self.get_user_info(), old_text_output=old_text_output, old_image_output=old_image_output, old_tests=old_tests)
except ConnectionError as inst:
render_error(self, "The front-end server was unable to contact the back-end server.")
except ReadTimeout as inst:
render_error(self, f"Your solution timed out after {self.settings_dict['back_ends'][exercise_details['back_end']]['timeout_seconds']} seconds.")
except Exception as inst:
render_error(self, traceback.format_exc())
|
"""mycloud URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from common.config import get_config
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myfiles.urls'), name='myfiles')
]
urlpatterns = [
path(f'{get_config('context')}/', include(urlpatterns))
]
| """mycloud URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from common.config import get_config
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myfiles.urls'), name='myfiles')
]
urlpatterns = [
path(f'{get_config("context")}/', include(urlpatterns))
]
|
"""Driver module for `vara-cs`."""
import logging
import os
import re
import typing as tp
from argparse import ArgumentParser, ArgumentTypeError, _SubParsersAction
from enum import Enum
from pathlib import Path
from argparse_utils import enum_action
from plumbum import FG, colors, local
from varats.base.sampling_method import NormalSamplingMethod
from varats.data.discover_reports import initialize_reports
from varats.mapping.commit_map import create_lazy_commit_map_loader
from varats.paper.case_study import load_case_study_from_file, store_case_study
from varats.paper_mgmt import paper_config_manager as PCM
from varats.paper_mgmt.case_study import (
get_revisions_status_for_case_study,
ExtenderStrategy,
extend_case_study,
generate_case_study,
)
from varats.paper_mgmt.paper_config import get_paper_config
from varats.plots.discover_plots import initialize_plots
from varats.project.project_util import get_local_project_git_path
from varats.projects.discover_projects import initialize_projects
from varats.provider.release.release_provider import ReleaseType
from varats.report.report import FileStatusExtension, MetaReport
from varats.tools.tool_util import configuration_lookup_error_handler
from varats.utils.cli_util import (
cli_list_choice,
initialize_cli_tool,
cli_yn_choice,
)
from varats.utils.settings import vara_cfg
LOG = logging.getLogger(__name__)
def main() -> None:
"""Allow easier management of case studies."""
initialize_cli_tool()
initialize_projects()
initialize_reports()
initialize_plots() # needed for vara-cs ext smooth_plot
parser = ArgumentParser("vara-cs")
sub_parsers = parser.add_subparsers(help="Subcommand", dest="subcommand")
__create_status_parser(sub_parsers) # vara-cs status
__create_gen_parser(sub_parsers) # vara-cs gen
__create_ext_parser(sub_parsers) # vara-cs ext
__create_package_parser(sub_parsers) # vara-cs package
__create_view_parser(sub_parsers) # vara-cs view
__create_cleanup_parser(sub_parsers) # vara-cs cleanup
args = {k: v for k, v in vars(parser.parse_args()).items() if v is not None}
if 'subcommand' not in args:
parser.print_help()
return
__casestudy_exec_command(args, parser)
@configuration_lookup_error_handler
def __casestudy_exec_command(
args: tp.Dict[str, tp.Any], parser: ArgumentParser
) -> None:
if args['subcommand'] == 'status':
__casestudy_status(args, parser)
elif args['subcommand'] == 'gen' or args['subcommand'] == 'ext':
__casestudy_create_or_extend(args, parser)
elif args['subcommand'] == 'package':
__casestudy_package(args, parser)
elif args['subcommand'] == 'view':
__casestudy_view(args)
elif args['subcommand'] == 'cleanup':
__casestudy_cleanup(args, parser)
def __create_status_parser(sub_parsers: _SubParsersAction) -> None:
status_parser = sub_parsers.add_parser(
'status', help="Show status of current case study"
)
status_parser.add_argument(
"report_name",
help=(
"Provide a report name to "
"select which files are considered for the status"
),
choices=MetaReport.REPORT_TYPES.keys(),
type=str,
default=".*"
)
status_parser.add_argument(
"--filter-regex",
help="Provide a regex to filter the shown case studies",
type=str,
default=".*"
)
status_parser.add_argument(
"--paper_config",
help="Use this paper config instead of the configured one",
default=None
)
status_parser.add_argument(
"-s",
"--short",
help="Only print a short summary",
action="store_true",
default=False
)
status_parser.add_argument(
"--list-revs",
help="Print a list of revisions for every stage and every case study",
action="store_true",
default=False
)
status_parser.add_argument(
"--ws",
help="Print status with stage separation",
action="store_true",
default=False
)
status_parser.add_argument(
"--sorted",
help="Sort the revisions in the order they are printed by git log.",
action="store_true",
default=False
)
status_parser.add_argument(
"--legend",
help="Print status with legend",
action="store_true",
default=False
)
status_parser.add_argument(
"--force-color",
help="Force colored output also when not connected to a terminal "
"(e.g. when piping to less -r).",
action="store_true",
default=False
)
def __add_common_args(sub_parser: ArgumentParser) -> None:
"""Group common args to provide all args on different sub parsers."""
sub_parser.add_argument(
"--git-path", help="Path to git repository", default=None
)
sub_parser.add_argument(
"-p", "--project", help="Project name", default=None
)
sub_parser.add_argument(
"--end", help="End of the commit range (inclusive)", default="HEAD"
)
sub_parser.add_argument(
"--start", help="Start of the commit range (exclusive)", default=None
)
sub_parser.add_argument(
"--extra-revs",
nargs="+",
default=[],
help="Add a list of additional revisions to the case-study"
)
sub_parser.add_argument(
"--revs-per-year",
type=int,
default=0,
help="Add this many revisions per year to the case-study."
)
sub_parser.add_argument(
"--revs-year-sep",
action="store_true",
default=False,
help="Separate the revisions in different stages per year "
"(when using \'--revs-per-year\')."
)
sub_parser.add_argument(
"--num-rev",
type=int,
default=10,
help="Number of revisions to select."
)
sub_parser.add_argument(
"--ignore-blocked",
action="store_true",
default=False,
help="Ignore revisions that are marked as blocked."
)
def __create_gen_parser(sub_parsers: _SubParsersAction) -> None:
gen_parser = sub_parsers.add_parser('gen', help="Generate a case study.")
gen_parser.add_argument(
"paper_config_path",
help="Path to paper_config folder (e.g., paper_configs/ase-17)"
)
gen_parser.add_argument(
"distribution",
choices=[
x.name()
for x in NormalSamplingMethod.normal_sampling_method_types()
]
)
gen_parser.add_argument(
"-v", "--version", type=int, default=0, help="Case study version."
)
__add_common_args(gen_parser)
def __create_ext_parser(sub_parsers: _SubParsersAction) -> None:
ext_parser = sub_parsers.add_parser(
'ext', help="Extend an existing case study."
)
ext_parser.add_argument("case_study_path", help="Path to case_study")
ext_parser.add_argument(
"strategy",
action=enum_action(ExtenderStrategy),
help="Extender strategy"
)
ext_parser.add_argument(
"--distribution",
choices=[
x.name()
for x in NormalSamplingMethod.normal_sampling_method_types()
]
)
ext_parser.add_argument("--release-type", action=enum_action(ReleaseType))
ext_parser.add_argument(
"--merge-stage",
default=-1,
type=int,
help="Merge the new revision(s) into stage `n`; defaults to last stage."
)
ext_parser.add_argument(
"--new-stage",
help="Add the new revision(s) to a new stage.",
default=False,
action='store_true'
)
ext_parser.add_argument(
"--boundary-gradient",
type=int,
default=5,
help="Maximal expected gradient in percent between " +
"two revisions, e.g., 5 for 5%%"
)
ext_parser.add_argument(
"--plot-type", help="Plot to calculate new revisions from."
)
ext_parser.add_argument(
"--report-type",
help="Passed to the plot given via --plot-type.",
default="EmptyReport"
)
ext_parser.add_argument(
"--result-folder", help="Folder in which to search for result files."
)
__add_common_args(ext_parser)
def __create_package_parser(sub_parsers: _SubParsersAction) -> None:
package_parser = sub_parsers.add_parser(
'package', help="Case study packaging util"
)
package_parser.add_argument("-o", "--output", help="Output file")
package_parser.add_argument(
"--filter-regex",
help="Provide a regex to only include case "
"studies that match the filter.",
type=str,
default=".*"
)
package_parser.add_argument(
"--report-names",
help=(
"Provide a report name to "
"select which files are considered for the status"
),
choices=MetaReport.REPORT_TYPES.keys(),
type=str,
nargs="*",
default=[]
)
def __create_view_parser(sub_parsers: _SubParsersAction) -> None:
view_parser = sub_parsers.add_parser('view', help="View report files.")
view_parser.add_argument(
"report_type",
help="Report type of the result files.",
choices=MetaReport.REPORT_TYPES.keys(),
type=str
)
view_parser.add_argument(
"project", help="Project to view result files for."
)
view_parser.add_argument(
"commit_hash", help="Commit hash to view result files for.", nargs='?'
)
view_parser.add_argument(
"--newest-only",
action="store_true",
default=False,
help="Only report the newest file for each matched commit hash"
)
def __create_cleanup_parser(sub_parsers: _SubParsersAction) -> None:
cleanup_parser = sub_parsers.add_parser(
'cleanup', help="Cleanup report files."
)
cleanup_parser.add_argument(
"cleanup_type",
help="The type of the performed cleanup action.",
action=enum_action(CleanupType)
)
cleanup_parser.add_argument(
"-f",
"--filter-regex",
help="Regex to determine which report files should be deleted.",
default="",
type=str
)
cleanup_parser.add_argument(
"--silent",
action="store_true",
default=False,
help="Hide the output of the matching filenames."
)
def __casestudy_status(
args: tp.Dict[str, tp.Any], parser: ArgumentParser
) -> None:
if args.get("force_color", False):
colors.use_color = True
if 'paper_config' in args:
vara_cfg()['paper_config']['current_config'] = args['paper_config']
if args['short'] and args['list_revs']:
parser.error(
"At most one argument of: --short, --list-revs can be used."
)
if args['short'] and args['ws']:
parser.error("At most one argument of: --short, --ws can be used.")
PCM.show_status_of_case_studies(
args['report_name'], args['filter_regex'], args['short'],
args['sorted'], args['list_revs'], args['ws'], args['legend']
)
def __casestudy_create_or_extend(
args: tp.Dict[str, tp.Any], parser: ArgumentParser
) -> None:
if "project" not in args and "git_path" not in args:
parser.error("need --project or --git-path")
if "project" in args and "git_path" not in args:
args['git_path'] = str(get_local_project_git_path(args['project']))
if "git_path" in args and "project" not in args:
args['project'] = Path(args['git_path']).stem.replace("-HEAD", "")
args['get_cmap'] = create_lazy_commit_map_loader(
args['project'], args.get('cmap', None), args['end'],
args['start'] if 'start' in args else None
)
cmap = args['get_cmap']()
# Rewrite requested distribution with initialized object
if 'distribution' in args:
sampling_method = NormalSamplingMethod.get_sampling_method_type(
args['distribution']
)()
args['distribution'] = sampling_method
if args['subcommand'] == 'ext':
case_study = load_case_study_from_file(Path(args['case_study_path']))
# If no merge_stage was specified add it to the last
if args['merge_stage'] == -1:
args['merge_stage'] = max(case_study.num_stages - 1, 0)
# If + was specified we add a new stage
if args['new_stage']:
args['merge_stage'] = case_study.num_stages
# Setup default result folder
if 'result_folder' not in args and args[
'strategy'] is ExtenderStrategy.smooth_plot:
args['project'] = case_study.project_name
args['result_folder'] = str(vara_cfg()['result_dir']
) + "/" + args['project']
LOG.info(f"Result folder defaults to: {args["result_folder"]}")
extend_case_study(case_study, cmap, args['strategy'], **args)
store_case_study(case_study, Path(args['case_study_path']))
else:
args['paper_config_path'] = Path(args['paper_config_path'])
if not args['paper_config_path'].exists():
raise ArgumentTypeError("Paper path does not exist")
# Specify merge_stage as 0 for creating new case studies
args['merge_stage'] = 0
case_study = generate_case_study(
sampling_method, cmap, args['version'], args['project'], **args
)
store_case_study(case_study, args['paper_config_path'])
def __casestudy_package(
args: tp.Dict[str, tp.Any], parser: ArgumentParser
) -> None:
output_path = Path(args["output"])
if output_path.suffix == '':
output_path = Path(str(output_path) + ".zip")
if output_path.suffix == '.zip':
vara_root = Path(str(vara_cfg()["config_file"])).parent
if Path(os.getcwd()) != vara_root:
LOG.info(
f"Packaging needs to be called from VaRA root dir, "
f"changing dir to {vara_root}"
)
os.chdir(vara_root)
PCM.package_paper_config(
output_path, re.compile(args['filter_regex']), args['report_names']
)
else:
parser.error(
"--output has the wrong file type extension. "
"Please do not provide any other file type extension than .zip"
)
def __init_commit_hash(args: tp.Dict[str, tp.Any]) -> str:
result_file_type = MetaReport.REPORT_TYPES[args["report_type"]]
project_name = args["project"]
if "commit_hash" not in args:
# Ask the user to provide a commit hash
print("No commit hash was provided.")
commit_hash = ""
paper_config = get_paper_config()
available_commit_hashes = []
# Compute available commit hashes
for case_study in paper_config.get_case_studies(project_name):
available_commit_hashes.extend(
get_revisions_status_for_case_study(
case_study, result_file_type, tag_blocked=False
)
)
max_num_hashes = 42
if len(available_commit_hashes) > max_num_hashes:
print("Found to many commit hashes, truncating selection...")
# Create call backs for cli choice
def set_commit_hash(
choice_pair: tp.Tuple[str, FileStatusExtension]
) -> None:
nonlocal commit_hash
commit_hash = choice_pair[0][:10]
statuses = FileStatusExtension.get_physical_file_statuses().union(
FileStatusExtension.get_virtual_file_statuses()
)
longest_file_status_extension = max([
len(status.name) for status in statuses
])
def result_file_to_list_entry(
commit_status_pair: tp.Tuple[str, FileStatusExtension]
) -> str:
status = commit_status_pair[1].get_colored_status().rjust(
longest_file_status_extension +
commit_status_pair[1].num_color_characters(), " "
)
return f"[{status}] {commit_status_pair[0][:10]}"
# Ask user which commit we should use
try:
cli_list_choice(
"Please select a hash:",
available_commit_hashes[:max_num_hashes],
result_file_to_list_entry,
set_commit_hash,
start_label=1,
default=1,
)
except EOFError:
raise LookupError
if commit_hash == "":
print("Could not find processed commit hash.")
raise LookupError
return commit_hash
return tp.cast(str, args["commit_hash"])
def __casestudy_view(args: tp.Dict[str, tp.Any]) -> None:
result_file_type = MetaReport.REPORT_TYPES[args["report_type"]]
project_name = args["project"]
try:
commit_hash = __init_commit_hash(args)
except LookupError:
return
result_files = PCM.get_result_files(
result_file_type, project_name, commit_hash,
args.get("newest_only", False)
)
result_files.sort(
key=lambda report_file: report_file.stat().st_mtime_ns, reverse=True
)
if not result_files:
print("No matching result files found.")
return
print(
f"Found {len(result_files)} matching result files (newest to oldest):"
)
statuses = FileStatusExtension.get_physical_file_statuses().union(
FileStatusExtension.get_virtual_file_statuses()
)
longest_file_status_extension = max([
len(status.name) for status in statuses
])
def result_file_to_list_entry(result_file: Path) -> str:
file_status = result_file_type.get_status_from_result_file(
result_file.name
)
status = (
file_status.get_colored_status().rjust(
longest_file_status_extension +
file_status.num_color_characters(), " "
)
)
return f"[{status}] {result_file.name}"
def open_in_editor(result_file: Path) -> None:
_ = editor[str(result_file)] & FG
editor_name = local.env["EDITOR"]
if not editor_name:
editor_name = "vim"
editor = local[editor_name]
try:
cli_list_choice(
"Select a number to open a file",
result_files,
result_file_to_list_entry,
open_in_editor,
start_label=1,
default=1,
repeat=True
)
except EOFError:
return
def __casestudy_cleanup(
args: tp.Dict[str, tp.Any], parser: ArgumentParser
) -> None:
cleanup_type = args['cleanup_type']
if cleanup_type == CleanupType.error:
_remove_error_result_files()
if cleanup_type == CleanupType.old:
_remove_old_result_files()
if cleanup_type == CleanupType.regex:
if not args['filter_regex']:
parser.error("Specify a regex filter with --filter-regex or -f")
_remove_result_files_by_regex(args['filter_regex'], args['silent'])
def _remove_old_result_files() -> None:
paper_config = get_paper_config()
result_dir = Path(str(vara_cfg()['result_dir']))
for case_study in paper_config.get_all_case_studies():
old_files: tp.List[Path] = []
newer_files: tp.Dict[str, Path] = dict()
result_dir_cs = result_dir / case_study.project_name
if not result_dir_cs.exists():
continue
for opt_res_file in result_dir_cs.iterdir():
commit_hash = MetaReport.get_commit_hash_from_result_file(
opt_res_file.name
)
if case_study.has_revision(commit_hash):
current_file = newer_files.get(commit_hash)
if current_file is None:
newer_files[commit_hash] = opt_res_file
else:
if (
current_file.stat().st_mtime_ns <
opt_res_file.stat().st_mtime_ns
):
newer_files[commit_hash] = opt_res_file
old_files.append(current_file)
else:
old_files.append(opt_res_file)
for file in old_files:
if file.exists():
os.remove(file)
def _find_result_dir_paths_of_projects() -> tp.List[Path]:
result_dir_path = Path(vara_cfg()["result_dir"].value)
existing_paper_config_result_dir_paths = []
paper_config = get_paper_config()
project_names = [
cs.project_name for cs in paper_config.get_all_case_studies()
]
for project_name in project_names:
path = Path(result_dir_path / project_name)
if Path.exists(path):
existing_paper_config_result_dir_paths.append(path)
return existing_paper_config_result_dir_paths
def _remove_error_result_files() -> None:
result_dir_paths = _find_result_dir_paths_of_projects()
for result_dir_path in result_dir_paths:
result_file_names = os.listdir(result_dir_path)
for result_file_name in result_file_names:
if MetaReport.is_result_file(result_file_name) and (
MetaReport.
result_file_has_status_compileerror(result_file_name) or
MetaReport.result_file_has_status_failed(result_file_name)
):
os.remove(result_dir_path / result_file_name)
def _remove_result_files_by_regex(regex_filter: str, hide: bool) -> None:
result_dir_paths = _find_result_dir_paths_of_projects()
for result_dir_path in result_dir_paths:
result_file_names = os.listdir(result_dir_path)
files_to_delete: tp.List[str] = []
for result_file_name in result_file_names:
match = re.match(regex_filter, result_file_name)
if match is not None:
files_to_delete.append(result_file_name)
if not files_to_delete:
print(f"No matching result files in {result_dir_path} found.")
continue
if not hide:
for file_name in files_to_delete:
print(f"{file_name}")
print(
f"Found {len(files_to_delete)} matching"
"result files in {result_dir_path}:"
)
try:
if cli_yn_choice("Do you want to delete these files", "n"):
for file_name in files_to_delete:
if Path.exists(result_dir_path / file_name):
os.remove(result_dir_path / file_name)
except EOFError:
continue
class CleanupType(Enum):
old = 0
error = 1
regex = 2
if __name__ == '__main__':
main()
| """Driver module for `vara-cs`."""
import logging
import os
import re
import typing as tp
from argparse import ArgumentParser, ArgumentTypeError, _SubParsersAction
from enum import Enum
from pathlib import Path
from argparse_utils import enum_action
from plumbum import FG, colors, local
from varats.base.sampling_method import NormalSamplingMethod
from varats.data.discover_reports import initialize_reports
from varats.mapping.commit_map import create_lazy_commit_map_loader
from varats.paper.case_study import load_case_study_from_file, store_case_study
from varats.paper_mgmt import paper_config_manager as PCM
from varats.paper_mgmt.case_study import (
get_revisions_status_for_case_study,
ExtenderStrategy,
extend_case_study,
generate_case_study,
)
from varats.paper_mgmt.paper_config import get_paper_config
from varats.plots.discover_plots import initialize_plots
from varats.project.project_util import get_local_project_git_path
from varats.projects.discover_projects import initialize_projects
from varats.provider.release.release_provider import ReleaseType
from varats.report.report import FileStatusExtension, MetaReport
from varats.tools.tool_util import configuration_lookup_error_handler
from varats.utils.cli_util import (
cli_list_choice,
initialize_cli_tool,
cli_yn_choice,
)
from varats.utils.settings import vara_cfg
LOG = logging.getLogger(__name__)
def main() -> None:
"""Allow easier management of case studies."""
initialize_cli_tool()
initialize_projects()
initialize_reports()
initialize_plots() # needed for vara-cs ext smooth_plot
parser = ArgumentParser("vara-cs")
sub_parsers = parser.add_subparsers(help="Subcommand", dest="subcommand")
__create_status_parser(sub_parsers) # vara-cs status
__create_gen_parser(sub_parsers) # vara-cs gen
__create_ext_parser(sub_parsers) # vara-cs ext
__create_package_parser(sub_parsers) # vara-cs package
__create_view_parser(sub_parsers) # vara-cs view
__create_cleanup_parser(sub_parsers) # vara-cs cleanup
args = {k: v for k, v in vars(parser.parse_args()).items() if v is not None}
if 'subcommand' not in args:
parser.print_help()
return
__casestudy_exec_command(args, parser)
@configuration_lookup_error_handler
def __casestudy_exec_command(
args: tp.Dict[str, tp.Any], parser: ArgumentParser
) -> None:
if args['subcommand'] == 'status':
__casestudy_status(args, parser)
elif args['subcommand'] == 'gen' or args['subcommand'] == 'ext':
__casestudy_create_or_extend(args, parser)
elif args['subcommand'] == 'package':
__casestudy_package(args, parser)
elif args['subcommand'] == 'view':
__casestudy_view(args)
elif args['subcommand'] == 'cleanup':
__casestudy_cleanup(args, parser)
def __create_status_parser(sub_parsers: _SubParsersAction) -> None:
status_parser = sub_parsers.add_parser(
'status', help="Show status of current case study"
)
status_parser.add_argument(
"report_name",
help=(
"Provide a report name to "
"select which files are considered for the status"
),
choices=MetaReport.REPORT_TYPES.keys(),
type=str,
default=".*"
)
status_parser.add_argument(
"--filter-regex",
help="Provide a regex to filter the shown case studies",
type=str,
default=".*"
)
status_parser.add_argument(
"--paper_config",
help="Use this paper config instead of the configured one",
default=None
)
status_parser.add_argument(
"-s",
"--short",
help="Only print a short summary",
action="store_true",
default=False
)
status_parser.add_argument(
"--list-revs",
help="Print a list of revisions for every stage and every case study",
action="store_true",
default=False
)
status_parser.add_argument(
"--ws",
help="Print status with stage separation",
action="store_true",
default=False
)
status_parser.add_argument(
"--sorted",
help="Sort the revisions in the order they are printed by git log.",
action="store_true",
default=False
)
status_parser.add_argument(
"--legend",
help="Print status with legend",
action="store_true",
default=False
)
status_parser.add_argument(
"--force-color",
help="Force colored output also when not connected to a terminal "
"(e.g. when piping to less -r).",
action="store_true",
default=False
)
def __add_common_args(sub_parser: ArgumentParser) -> None:
"""Group common args to provide all args on different sub parsers."""
sub_parser.add_argument(
"--git-path", help="Path to git repository", default=None
)
sub_parser.add_argument(
"-p", "--project", help="Project name", default=None
)
sub_parser.add_argument(
"--end", help="End of the commit range (inclusive)", default="HEAD"
)
sub_parser.add_argument(
"--start", help="Start of the commit range (exclusive)", default=None
)
sub_parser.add_argument(
"--extra-revs",
nargs="+",
default=[],
help="Add a list of additional revisions to the case-study"
)
sub_parser.add_argument(
"--revs-per-year",
type=int,
default=0,
help="Add this many revisions per year to the case-study."
)
sub_parser.add_argument(
"--revs-year-sep",
action="store_true",
default=False,
help="Separate the revisions in different stages per year "
"(when using \'--revs-per-year\')."
)
sub_parser.add_argument(
"--num-rev",
type=int,
default=10,
help="Number of revisions to select."
)
sub_parser.add_argument(
"--ignore-blocked",
action="store_true",
default=False,
help="Ignore revisions that are marked as blocked."
)
def __create_gen_parser(sub_parsers: _SubParsersAction) -> None:
gen_parser = sub_parsers.add_parser('gen', help="Generate a case study.")
gen_parser.add_argument(
"paper_config_path",
help="Path to paper_config folder (e.g., paper_configs/ase-17)"
)
gen_parser.add_argument(
"distribution",
choices=[
x.name()
for x in NormalSamplingMethod.normal_sampling_method_types()
]
)
gen_parser.add_argument(
"-v", "--version", type=int, default=0, help="Case study version."
)
__add_common_args(gen_parser)
def __create_ext_parser(sub_parsers: _SubParsersAction) -> None:
ext_parser = sub_parsers.add_parser(
'ext', help="Extend an existing case study."
)
ext_parser.add_argument("case_study_path", help="Path to case_study")
ext_parser.add_argument(
"strategy",
action=enum_action(ExtenderStrategy),
help="Extender strategy"
)
ext_parser.add_argument(
"--distribution",
choices=[
x.name()
for x in NormalSamplingMethod.normal_sampling_method_types()
]
)
ext_parser.add_argument("--release-type", action=enum_action(ReleaseType))
ext_parser.add_argument(
"--merge-stage",
default=-1,
type=int,
help="Merge the new revision(s) into stage `n`; defaults to last stage."
)
ext_parser.add_argument(
"--new-stage",
help="Add the new revision(s) to a new stage.",
default=False,
action='store_true'
)
ext_parser.add_argument(
"--boundary-gradient",
type=int,
default=5,
help="Maximal expected gradient in percent between " +
"two revisions, e.g., 5 for 5%%"
)
ext_parser.add_argument(
"--plot-type", help="Plot to calculate new revisions from."
)
ext_parser.add_argument(
"--report-type",
help="Passed to the plot given via --plot-type.",
default="EmptyReport"
)
ext_parser.add_argument(
"--result-folder", help="Folder in which to search for result files."
)
__add_common_args(ext_parser)
def __create_package_parser(sub_parsers: _SubParsersAction) -> None:
package_parser = sub_parsers.add_parser(
'package', help="Case study packaging util"
)
package_parser.add_argument("-o", "--output", help="Output file")
package_parser.add_argument(
"--filter-regex",
help="Provide a regex to only include case "
"studies that match the filter.",
type=str,
default=".*"
)
package_parser.add_argument(
"--report-names",
help=(
"Provide a report name to "
"select which files are considered for the status"
),
choices=MetaReport.REPORT_TYPES.keys(),
type=str,
nargs="*",
default=[]
)
def __create_view_parser(sub_parsers: _SubParsersAction) -> None:
view_parser = sub_parsers.add_parser('view', help="View report files.")
view_parser.add_argument(
"report_type",
help="Report type of the result files.",
choices=MetaReport.REPORT_TYPES.keys(),
type=str
)
view_parser.add_argument(
"project", help="Project to view result files for."
)
view_parser.add_argument(
"commit_hash", help="Commit hash to view result files for.", nargs='?'
)
view_parser.add_argument(
"--newest-only",
action="store_true",
default=False,
help="Only report the newest file for each matched commit hash"
)
def __create_cleanup_parser(sub_parsers: _SubParsersAction) -> None:
cleanup_parser = sub_parsers.add_parser(
'cleanup', help="Cleanup report files."
)
cleanup_parser.add_argument(
"cleanup_type",
help="The type of the performed cleanup action.",
action=enum_action(CleanupType)
)
cleanup_parser.add_argument(
"-f",
"--filter-regex",
help="Regex to determine which report files should be deleted.",
default="",
type=str
)
cleanup_parser.add_argument(
"--silent",
action="store_true",
default=False,
help="Hide the output of the matching filenames."
)
def __casestudy_status(
args: tp.Dict[str, tp.Any], parser: ArgumentParser
) -> None:
if args.get("force_color", False):
colors.use_color = True
if 'paper_config' in args:
vara_cfg()['paper_config']['current_config'] = args['paper_config']
if args['short'] and args['list_revs']:
parser.error(
"At most one argument of: --short, --list-revs can be used."
)
if args['short'] and args['ws']:
parser.error("At most one argument of: --short, --ws can be used.")
PCM.show_status_of_case_studies(
args['report_name'], args['filter_regex'], args['short'],
args['sorted'], args['list_revs'], args['ws'], args['legend']
)
def __casestudy_create_or_extend(
args: tp.Dict[str, tp.Any], parser: ArgumentParser
) -> None:
if "project" not in args and "git_path" not in args:
parser.error("need --project or --git-path")
if "project" in args and "git_path" not in args:
args['git_path'] = str(get_local_project_git_path(args['project']))
if "git_path" in args and "project" not in args:
args['project'] = Path(args['git_path']).stem.replace("-HEAD", "")
args['get_cmap'] = create_lazy_commit_map_loader(
args['project'], args.get('cmap', None), args['end'],
args['start'] if 'start' in args else None
)
cmap = args['get_cmap']()
# Rewrite requested distribution with initialized object
if 'distribution' in args:
sampling_method = NormalSamplingMethod.get_sampling_method_type(
args['distribution']
)()
args['distribution'] = sampling_method
if args['subcommand'] == 'ext':
case_study = load_case_study_from_file(Path(args['case_study_path']))
# If no merge_stage was specified add it to the last
if args['merge_stage'] == -1:
args['merge_stage'] = max(case_study.num_stages - 1, 0)
# If + was specified we add a new stage
if args['new_stage']:
args['merge_stage'] = case_study.num_stages
# Setup default result folder
if 'result_folder' not in args and args[
'strategy'] is ExtenderStrategy.smooth_plot:
args['project'] = case_study.project_name
args['result_folder'] = str(vara_cfg()['result_dir']
) + "/" + args['project']
LOG.info(f"Result folder defaults to: {args['result_folder']}")
extend_case_study(case_study, cmap, args['strategy'], **args)
store_case_study(case_study, Path(args['case_study_path']))
else:
args['paper_config_path'] = Path(args['paper_config_path'])
if not args['paper_config_path'].exists():
raise ArgumentTypeError("Paper path does not exist")
# Specify merge_stage as 0 for creating new case studies
args['merge_stage'] = 0
case_study = generate_case_study(
sampling_method, cmap, args['version'], args['project'], **args
)
store_case_study(case_study, args['paper_config_path'])
def __casestudy_package(
args: tp.Dict[str, tp.Any], parser: ArgumentParser
) -> None:
output_path = Path(args["output"])
if output_path.suffix == '':
output_path = Path(str(output_path) + ".zip")
if output_path.suffix == '.zip':
vara_root = Path(str(vara_cfg()["config_file"])).parent
if Path(os.getcwd()) != vara_root:
LOG.info(
f"Packaging needs to be called from VaRA root dir, "
f"changing dir to {vara_root}"
)
os.chdir(vara_root)
PCM.package_paper_config(
output_path, re.compile(args['filter_regex']), args['report_names']
)
else:
parser.error(
"--output has the wrong file type extension. "
"Please do not provide any other file type extension than .zip"
)
def __init_commit_hash(args: tp.Dict[str, tp.Any]) -> str:
result_file_type = MetaReport.REPORT_TYPES[args["report_type"]]
project_name = args["project"]
if "commit_hash" not in args:
# Ask the user to provide a commit hash
print("No commit hash was provided.")
commit_hash = ""
paper_config = get_paper_config()
available_commit_hashes = []
# Compute available commit hashes
for case_study in paper_config.get_case_studies(project_name):
available_commit_hashes.extend(
get_revisions_status_for_case_study(
case_study, result_file_type, tag_blocked=False
)
)
max_num_hashes = 42
if len(available_commit_hashes) > max_num_hashes:
print("Found to many commit hashes, truncating selection...")
# Create call backs for cli choice
def set_commit_hash(
choice_pair: tp.Tuple[str, FileStatusExtension]
) -> None:
nonlocal commit_hash
commit_hash = choice_pair[0][:10]
statuses = FileStatusExtension.get_physical_file_statuses().union(
FileStatusExtension.get_virtual_file_statuses()
)
longest_file_status_extension = max([
len(status.name) for status in statuses
])
def result_file_to_list_entry(
commit_status_pair: tp.Tuple[str, FileStatusExtension]
) -> str:
status = commit_status_pair[1].get_colored_status().rjust(
longest_file_status_extension +
commit_status_pair[1].num_color_characters(), " "
)
return f"[{status}] {commit_status_pair[0][:10]}"
# Ask user which commit we should use
try:
cli_list_choice(
"Please select a hash:",
available_commit_hashes[:max_num_hashes],
result_file_to_list_entry,
set_commit_hash,
start_label=1,
default=1,
)
except EOFError:
raise LookupError
if commit_hash == "":
print("Could not find processed commit hash.")
raise LookupError
return commit_hash
return tp.cast(str, args["commit_hash"])
def __casestudy_view(args: tp.Dict[str, tp.Any]) -> None:
result_file_type = MetaReport.REPORT_TYPES[args["report_type"]]
project_name = args["project"]
try:
commit_hash = __init_commit_hash(args)
except LookupError:
return
result_files = PCM.get_result_files(
result_file_type, project_name, commit_hash,
args.get("newest_only", False)
)
result_files.sort(
key=lambda report_file: report_file.stat().st_mtime_ns, reverse=True
)
if not result_files:
print("No matching result files found.")
return
print(
f"Found {len(result_files)} matching result files (newest to oldest):"
)
statuses = FileStatusExtension.get_physical_file_statuses().union(
FileStatusExtension.get_virtual_file_statuses()
)
longest_file_status_extension = max([
len(status.name) for status in statuses
])
def result_file_to_list_entry(result_file: Path) -> str:
file_status = result_file_type.get_status_from_result_file(
result_file.name
)
status = (
file_status.get_colored_status().rjust(
longest_file_status_extension +
file_status.num_color_characters(), " "
)
)
return f"[{status}] {result_file.name}"
def open_in_editor(result_file: Path) -> None:
_ = editor[str(result_file)] & FG
editor_name = local.env["EDITOR"]
if not editor_name:
editor_name = "vim"
editor = local[editor_name]
try:
cli_list_choice(
"Select a number to open a file",
result_files,
result_file_to_list_entry,
open_in_editor,
start_label=1,
default=1,
repeat=True
)
except EOFError:
return
def __casestudy_cleanup(
args: tp.Dict[str, tp.Any], parser: ArgumentParser
) -> None:
cleanup_type = args['cleanup_type']
if cleanup_type == CleanupType.error:
_remove_error_result_files()
if cleanup_type == CleanupType.old:
_remove_old_result_files()
if cleanup_type == CleanupType.regex:
if not args['filter_regex']:
parser.error("Specify a regex filter with --filter-regex or -f")
_remove_result_files_by_regex(args['filter_regex'], args['silent'])
def _remove_old_result_files() -> None:
paper_config = get_paper_config()
result_dir = Path(str(vara_cfg()['result_dir']))
for case_study in paper_config.get_all_case_studies():
old_files: tp.List[Path] = []
newer_files: tp.Dict[str, Path] = dict()
result_dir_cs = result_dir / case_study.project_name
if not result_dir_cs.exists():
continue
for opt_res_file in result_dir_cs.iterdir():
commit_hash = MetaReport.get_commit_hash_from_result_file(
opt_res_file.name
)
if case_study.has_revision(commit_hash):
current_file = newer_files.get(commit_hash)
if current_file is None:
newer_files[commit_hash] = opt_res_file
else:
if (
current_file.stat().st_mtime_ns <
opt_res_file.stat().st_mtime_ns
):
newer_files[commit_hash] = opt_res_file
old_files.append(current_file)
else:
old_files.append(opt_res_file)
for file in old_files:
if file.exists():
os.remove(file)
def _find_result_dir_paths_of_projects() -> tp.List[Path]:
result_dir_path = Path(vara_cfg()["result_dir"].value)
existing_paper_config_result_dir_paths = []
paper_config = get_paper_config()
project_names = [
cs.project_name for cs in paper_config.get_all_case_studies()
]
for project_name in project_names:
path = Path(result_dir_path / project_name)
if Path.exists(path):
existing_paper_config_result_dir_paths.append(path)
return existing_paper_config_result_dir_paths
def _remove_error_result_files() -> None:
result_dir_paths = _find_result_dir_paths_of_projects()
for result_dir_path in result_dir_paths:
result_file_names = os.listdir(result_dir_path)
for result_file_name in result_file_names:
if MetaReport.is_result_file(result_file_name) and (
MetaReport.
result_file_has_status_compileerror(result_file_name) or
MetaReport.result_file_has_status_failed(result_file_name)
):
os.remove(result_dir_path / result_file_name)
def _remove_result_files_by_regex(regex_filter: str, hide: bool) -> None:
result_dir_paths = _find_result_dir_paths_of_projects()
for result_dir_path in result_dir_paths:
result_file_names = os.listdir(result_dir_path)
files_to_delete: tp.List[str] = []
for result_file_name in result_file_names:
match = re.match(regex_filter, result_file_name)
if match is not None:
files_to_delete.append(result_file_name)
if not files_to_delete:
print(f"No matching result files in {result_dir_path} found.")
continue
if not hide:
for file_name in files_to_delete:
print(f"{file_name}")
print(
f"Found {len(files_to_delete)} matching"
"result files in {result_dir_path}:"
)
try:
if cli_yn_choice("Do you want to delete these files", "n"):
for file_name in files_to_delete:
if Path.exists(result_dir_path / file_name):
os.remove(result_dir_path / file_name)
except EOFError:
continue
class CleanupType(Enum):
old = 0
error = 1
regex = 2
if __name__ == '__main__':
main()
|
"""
Universe configuration builder.
"""
# absolute_import needed for tool_shed package.
import collections
import configparser
import errno
import ipaddress
import logging
import logging.config
import os
import re
import signal
import socket
import string
import sys
import tempfile
import threading
import time
from datetime import timedelta
from typing import Dict, Optional, Set
import yaml
from beaker.cache import CacheManager
from beaker.util import parse_cache_config_options
from galaxy.config.schema import AppSchema
from galaxy.containers import parse_containers_config
from galaxy.exceptions import ConfigurationError
from galaxy.model import mapping
from galaxy.model.database_utils import database_exists
from galaxy.model.tool_shed_install.migrate.check import create_or_verify_database as tsi_create_or_verify_database
from galaxy.util import (
ExecutionTimer,
listify,
string_as_bool,
unicodify,
)
from galaxy.util.custom_logging import LOGLV_TRACE
from galaxy.util.dbkeys import GenomeBuilds
from galaxy.util.properties import (
find_config_file,
read_properties_from_file,
running_from_source,
)
from galaxy.web.formatting import expand_pretty_datetime_format
from galaxy.web_stack import (
get_stack_facts,
register_postfork_function
)
from ..version import VERSION_MAJOR, VERSION_MINOR
log = logging.getLogger(__name__)
GALAXY_APP_NAME = 'galaxy'
GALAXY_CONFIG_SCHEMA_PATH = 'lib/galaxy/webapps/galaxy/config_schema.yml'
LOGGING_CONFIG_DEFAULT = {
'disable_existing_loggers': False,
'version': 1,
'root': {
'handlers': ['console'],
'level': 'DEBUG',
},
'loggers': {
'paste.httpserver.ThreadPool': {
'level': 'WARN',
'qualname': 'paste.httpserver.ThreadPool',
},
'sqlalchemy_json.track': {
'level': 'WARN',
'qualname': 'sqlalchemy_json.track',
},
'urllib3.connectionpool': {
'level': 'WARN',
'qualname': 'urllib3.connectionpool',
},
'routes.middleware': {
'level': 'WARN',
'qualname': 'routes.middleware',
},
'amqp': {
'level': 'INFO',
'qualname': 'amqp',
},
'botocore': {
'level': 'INFO',
'qualname': 'botocore',
},
},
'filters': {
'stack': {
'()': 'galaxy.web_stack.application_stack_log_filter',
},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'stack',
'level': 'DEBUG',
'stream': 'ext://sys.stderr',
'filters': ['stack'],
},
},
'formatters': {
'stack': {
'()': 'galaxy.web_stack.application_stack_log_formatter',
},
},
}
"""Default value for logging configuration, passed to :func:`logging.config.dictConfig`"""
def find_root(kwargs):
return os.path.abspath(kwargs.get('root_dir', '.'))
class BaseAppConfiguration:
# Override in subclasses (optional): {KEY: config option, VALUE: deprecated directory name}
# If VALUE == first directory in a user-supplied path that resolves to KEY, it will be stripped from that path
renamed_options: Optional[Dict[str, str]] = None
deprecated_dirs: Dict[str, str] = {}
paths_to_check_against_root: Set[str] = set() # backward compatibility: if resolved path doesn't exist, try resolving w.r.t root
add_sample_file_to_defaults: Set[str] = set() # for these options, add sample config files to their defaults
listify_options: Set[str] = set() # values for these options are processed as lists of values
def __init__(self, **kwargs):
self._preprocess_kwargs(kwargs)
self._kwargs = kwargs # Save these as a record of explicitly set options
self.config_dict = kwargs
self.root = find_root(kwargs)
self._set_config_base(kwargs)
self.schema = self._load_schema() # Load schema from schema definition file
self._raw_config = self.schema.defaults.copy() # Save schema defaults as initial config values (raw_config)
self._update_raw_config_from_kwargs(kwargs) # Overwrite raw_config with values passed in kwargs
self._create_attributes_from_raw_config() # Create attributes based on raw_config
self._preprocess_paths_to_resolve() # Any preprocessing steps that need to happen before paths are resolved
self._resolve_paths() # Overwrite attribute values with resolved paths
self._postprocess_paths_to_resolve() # Any steps that need to happen after paths are resolved
def _preprocess_kwargs(self, kwargs):
self._process_renamed_options(kwargs)
self._fix_postgresql_dburl(kwargs)
def _process_renamed_options(self, kwargs):
"""Update kwargs to set any unset renamed options to values of old-named options, if set.
Does not remove the old options from kwargs so that deprecated option usage can be logged.
"""
if self.renamed_options is not None:
for old, new in self.renamed_options.items():
if old in kwargs and new not in kwargs:
kwargs[new] = kwargs[old]
def _fix_postgresql_dburl(self, kwargs):
"""
Fix deprecated database URLs (postgres... >> postgresql...)
https://docs.sqlalchemy.org/en/14/changelog/changelog_14.html#change-3687655465c25a39b968b4f5f6e9170b
"""
old_dialect, new_dialect = 'postgres', 'postgresql'
old_prefixes = (f'{old_dialect}:', f'{old_dialect}+') # check for postgres://foo and postgres+driver//foo
offset = len(old_dialect)
keys = ('database_connection', 'install_database_connection')
for key in keys:
if key in kwargs:
value = kwargs[key]
for prefix in old_prefixes:
if value.startswith(prefix):
value = f'{new_dialect}{value[offset:]}'
kwargs[key] = value
log.warning('PostgreSQL database URLs of the form "postgres://" have been '
'deprecated. Please use "postgresql://".')
def is_set(self, key):
"""Check if a configuration option has been explicitly set."""
# NOTE: This will check all supplied keyword arguments, including those not in the schema.
# To check only schema options, change the line below to `if property not in self._raw_config:`
if key not in self._raw_config:
log.warning(f"Configuration option does not exist: '{key}'")
return key in self._kwargs
def resolve_path(self, path):
"""Resolve a path relative to Galaxy's root."""
return self._in_root_dir(path)
def _set_config_base(self, config_kwargs):
def _set_global_conf():
self.config_file = find_config_file('galaxy')
self.global_conf = config_kwargs.get('global_conf')
self.global_conf_parser = configparser.ConfigParser()
if not self.config_file and self.global_conf and "__file__" in self.global_conf:
self.config_file = os.path.join(self.root, self.global_conf['__file__'])
if self.config_file is None:
log.warning("No Galaxy config file found, running from current working directory: %s", os.getcwd())
else:
try:
self.global_conf_parser.read(self.config_file)
except OSError:
raise
except Exception:
pass # Not an INI file
def _set_config_directories():
# Set config_dir to value from kwargs OR dirname of config_file OR None
_config_dir = os.path.dirname(self.config_file) if self.config_file else None
self.config_dir = config_kwargs.get('config_dir', _config_dir)
# Make path absolute before using it as base for other paths
if self.config_dir:
self.config_dir = os.path.abspath(self.config_dir)
self.data_dir = config_kwargs.get('data_dir')
if self.data_dir:
self.data_dir = os.path.abspath(self.data_dir)
self.sample_config_dir = os.path.join(os.path.dirname(__file__), 'sample')
if self.sample_config_dir:
self.sample_config_dir = os.path.abspath(self.sample_config_dir)
self.managed_config_dir = config_kwargs.get('managed_config_dir')
if self.managed_config_dir:
self.managed_config_dir = os.path.abspath(self.managed_config_dir)
if running_from_source:
if not self.config_dir:
self.config_dir = os.path.join(self.root, 'config')
if not self.data_dir:
self.data_dir = os.path.join(self.root, 'database')
if not self.managed_config_dir:
self.managed_config_dir = self.config_dir
else:
if not self.config_dir:
self.config_dir = os.getcwd()
if not self.data_dir:
self.data_dir = self._in_config_dir('data')
if not self.managed_config_dir:
self.managed_config_dir = self._in_data_dir('config')
# TODO: do we still need to support ../shed_tools when running_from_source?
self.shed_tools_dir = self._in_data_dir('shed_tools')
log.debug("Configuration directory is %s", self.config_dir)
log.debug("Data directory is %s", self.data_dir)
log.debug("Managed config directory is %s", self.managed_config_dir)
_set_global_conf()
_set_config_directories()
def _load_schema(self):
# Override in subclasses
raise Exception('Not implemented')
def _preprocess_paths_to_resolve(self):
# For these options, if option is not set, listify its defaults and add a sample config file.
if self.add_sample_file_to_defaults:
for key in self.add_sample_file_to_defaults:
if not self.is_set(key):
defaults = listify(getattr(self, key), do_strip=True)
sample = f'{defaults[-1]}.sample' # if there are multiple defaults, use last as template
sample = self._in_sample_dir(sample) # resolve w.r.t sample_dir
defaults.append(sample)
setattr(self, key, defaults)
def _postprocess_paths_to_resolve(self):
def select_one_path_from_list():
# To consider: options with a sample file added to defaults except options that can have multiple values.
# If value is not set, check each path in list; set to first path that exists; if none exist, set to last path in list.
keys = self.add_sample_file_to_defaults - self.listify_options if self.listify_options else self.add_sample_file_to_defaults
for key in keys:
if not self.is_set(key):
paths = getattr(self, key)
for path in paths:
if self._path_exists(path):
setattr(self, key, path)
break
else:
setattr(self, key, paths[-1]) # TODO: we assume it exists; but we've already checked in the loop! Raise error instead?
def select_one_or_all_paths_from_list():
# Values for these options are lists of paths. If value is not set, use defaults if all paths in list exist;
# otherwise, set to last path in list.
for key in self.listify_options:
if not self.is_set(key):
paths = getattr(self, key)
for path in paths:
if not self._path_exists(path):
setattr(self, key, [paths[-1]]) # value is a list
break
if self.add_sample_file_to_defaults: # Currently, this is the ONLY case when we need to pick one file from a list
select_one_path_from_list()
if self.listify_options:
select_one_or_all_paths_from_list()
def _path_exists(self, path): # factored out so we can mock it in tests
return os.path.exists(path)
def _set_alt_paths(self, option, *alt_paths):
# If `option` is not set, check *alt_paths. Set `option` to first path that exists and return it.
if not self.is_set(option):
for path in alt_paths:
if self._path_exists(path):
setattr(self, option, path)
return path
def _update_raw_config_from_kwargs(self, kwargs):
def convert_datatype(key, value):
datatype = self.schema.app_schema[key].get('type')
# check for `not None` explicitly (value can be falsy)
if value is not None and datatype in type_converters:
# convert value or each item in value to type `datatype`
f = type_converters[datatype]
if isinstance(value, list):
return [f(item) for item in value]
else:
return f(value)
return value
def strip_deprecated_dir(key, value):
resolves_to = self.schema.paths_to_resolve.get(key)
if resolves_to: # value contains paths that will be resolved
paths = listify(value, do_strip=True)
for i, path in enumerate(paths):
first_dir = path.split(os.sep)[0] # get first directory component
if first_dir == self.deprecated_dirs.get(resolves_to): # first_dir is deprecated for this option
ignore = first_dir + os.sep
log.warning(
"Paths for the '%s' option are now relative to '%s', remove the leading '%s' "
"to suppress this warning: %s", key, resolves_to, ignore, path
)
paths[i] = path[len(ignore):]
# return list or string, depending on type of `value`
if isinstance(value, list):
return paths
return ','.join(paths)
return value
type_converters = {'bool': string_as_bool, 'int': int, 'float': float, 'str': str}
for key, value in kwargs.items():
if key in self.schema.app_schema:
value = convert_datatype(key, value)
if value and self.deprecated_dirs:
value = strip_deprecated_dir(key, value)
self._raw_config[key] = value
def _create_attributes_from_raw_config(self):
# `base_configs` are a special case: these attributes have been created and will be ignored
# by the code below. Trying to overwrite any other existing attributes will raise an error.
base_configs = {'config_dir', 'data_dir', 'managed_config_dir'}
for key, value in self._raw_config.items():
if not hasattr(self, key):
setattr(self, key, value)
elif key not in base_configs:
raise ConfigurationError(f"Attempting to override existing attribute '{key}'")
def _resolve_paths(self):
def resolve(key):
if key in _cache: # resolve each path only once
return _cache[key]
path = getattr(self, key) # path prior to being resolved
parent = self.schema.paths_to_resolve.get(key)
if not parent: # base case: nothing else needs resolving
return path
parent_path = resolve(parent) # recursively resolve parent path
if path is not None:
path = os.path.join(parent_path, path) # resolve path
else:
path = parent_path # or use parent path
setattr(self, key, path) # update property
_cache[key] = path # cache it!
return path
_cache = {}
for key in self.schema.paths_to_resolve:
value = getattr(self, key)
# Check if value is a list or should be listified; if so, listify and resolve each item separately.
if type(value) is list or (self.listify_options and key in self.listify_options):
saved_values = listify(getattr(self, key), do_strip=True) # listify and save original value
setattr(self, key, '_') # replace value with temporary placeholder
resolve(key) # resolve temporary value (`_` becomes `parent-path/_`)
resolved_base = getattr(self, key)[:-1] # get rid of placeholder in resolved path
# apply resolved base to saved values
resolved_paths = [os.path.join(resolved_base, value) for value in saved_values]
setattr(self, key, resolved_paths) # set config.key to a list of resolved paths
else:
resolve(key)
# Check options that have been set and may need to be resolved w.r.t. root
if self.is_set(key) and self.paths_to_check_against_root and key in self.paths_to_check_against_root:
self._check_against_root(key)
def _check_against_root(self, key):
def get_path(current_path, initial_path):
# if path does not exist and was set as relative:
if not self._path_exists(current_path) and not os.path.isabs(initial_path):
new_path = self._in_root_dir(initial_path)
if self._path_exists(new_path): # That's a bingo!
resolves_to = self.schema.paths_to_resolve.get(key)
log.warning(
"Paths for the '{0}' option should be relative to '{1}'. To suppress this warning, "
"move '{0}' into '{1}', or set it's value to an absolute path.".format(key, resolves_to)
)
return new_path
return current_path
current_value = getattr(self, key) # resolved path or list of resolved paths
if type(current_value) is list:
initial_paths = listify(self._raw_config[key], do_strip=True) # initial unresolved paths
updated_paths = []
# check and, if needed, update each path in the list
for current_path, initial_path in zip(current_value, initial_paths):
path = get_path(current_path, initial_path)
updated_paths.append(path) # add to new list regardless of whether path has changed or not
setattr(self, key, updated_paths) # update: one or more paths may have changed
else:
initial_path = self._raw_config[key] # initial unresolved path
path = get_path(current_value, initial_path)
if path != current_value:
setattr(self, key, path) # update if path has changed
def _in_root_dir(self, path):
return self._in_dir(self.root, path)
def _in_managed_config_dir(self, path):
return self._in_dir(self.managed_config_dir, path)
def _in_config_dir(self, path):
return self._in_dir(self.config_dir, path)
def _in_sample_dir(self, path):
return self._in_dir(self.sample_config_dir, path)
def _in_data_dir(self, path):
return self._in_dir(self.data_dir, path)
def _in_dir(self, _dir, path):
return os.path.join(_dir, path) if path else None
class CommonConfigurationMixin:
"""Shared configuration settings code for Galaxy and ToolShed."""
@property
def admin_users(self):
return self._admin_users
@admin_users.setter
def admin_users(self, value):
self._admin_users = value
self.admin_users_list = listify(value)
def is_admin_user(self, user):
"""Determine if the provided user is listed in `admin_users`."""
return user and (user.email in self.admin_users_list or user.bootstrap_admin_user)
@property
def sentry_dsn_public(self):
"""
Sentry URL with private key removed for use in client side scripts,
sentry server will need to be configured to accept events
"""
if self.sentry_dsn:
return re.sub(r"^([^:/?#]+:)?//(\w+):(\w+)", r"\1//\2", self.sentry_dsn)
def get_bool(self, key, default):
# Warning: the value of self.config_dict['foo'] may be different from self.foo
if key in self.config_dict:
return string_as_bool(self.config_dict[key])
else:
return default
def get(self, key, default=None):
# Warning: the value of self.config_dict['foo'] may be different from self.foo
return self.config_dict.get(key, default)
def _ensure_directory(self, path):
if path not in [None, False] and not os.path.isdir(path):
try:
os.makedirs(path)
except Exception as e:
raise ConfigurationError(f"Unable to create missing directory: {path}\n{unicodify(e)}")
class GalaxyAppConfiguration(BaseAppConfiguration, CommonConfigurationMixin):
deprecated_options = ('database_file', 'track_jobs_in_database', 'blacklist_file', 'whitelist_file',
'sanitize_whitelist_file', 'user_library_import_symlink_whitelist', 'fetch_url_whitelist',
'containers_resolvers_config_file')
renamed_options = {
'blacklist_file': 'email_domain_blocklist_file',
'whitelist_file': 'email_domain_allowlist_file',
'sanitize_whitelist_file': 'sanitize_allowlist_file',
'user_library_import_symlink_whitelist': 'user_library_import_symlink_allowlist',
'fetch_url_whitelist': 'fetch_url_allowlist',
'containers_resolvers_config_file': 'container_resolvers_config_file',
}
default_config_file_name = 'galaxy.yml'
deprecated_dirs = {'config_dir': 'config', 'data_dir': 'database'}
paths_to_check_against_root = {
'auth_config_file',
'build_sites_config_file',
'containers_config_file',
'data_manager_config_file',
'datatypes_config_file',
'dependency_resolvers_config_file',
'error_report_file',
'job_config_file',
'job_metrics_config_file',
'job_resource_params_file',
'local_conda_mapping_file',
'migrated_tools_config',
'modules_mapping_files',
'object_store_config_file',
'oidc_backends_config_file',
'oidc_config_file',
'shed_data_manager_config_file',
'shed_tool_config_file',
'shed_tool_data_table_config',
'tool_destinations_config_file',
'tool_sheds_config_file',
'user_preferences_extra_conf_path',
'workflow_resource_params_file',
'workflow_schedulers_config_file',
'markdown_export_css',
'markdown_export_css_pages',
'markdown_export_css_invocation_reports',
'file_path',
'tool_data_table_config_path',
'tool_config_file',
}
add_sample_file_to_defaults = {
'build_sites_config_file',
'datatypes_config_file',
'job_metrics_config_file',
'tool_data_table_config_path',
'tool_config_file',
}
listify_options = {
'tool_data_table_config_path',
'tool_config_file',
}
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._override_tempdir(kwargs)
self._process_config(kwargs)
def _load_schema(self):
# Schemas are symlinked to the root of the galaxy-app package
config_schema_path = os.path.join(os.path.dirname(__file__), os.pardir, 'config_schema.yml')
if os.path.exists(GALAXY_CONFIG_SCHEMA_PATH):
config_schema_path = GALAXY_CONFIG_SCHEMA_PATH
return AppSchema(config_schema_path, GALAXY_APP_NAME)
def _override_tempdir(self, kwargs):
if string_as_bool(kwargs.get("override_tempdir", "True")):
tempfile.tempdir = self.new_file_path
def config_value_for_host(self, config_option, host):
val = getattr(self, config_option)
if config_option in self.schema.per_host_options:
per_host_option = f"{config_option}_by_host"
if per_host_option in self.config_dict:
per_host = self.config_dict[per_host_option] or {}
for host_key, host_val in per_host.items():
if host_key in host:
val = host_val
break
return val
def _process_config(self, kwargs):
# Backwards compatibility for names used in too many places to fix
self.datatypes_config = self.datatypes_config_file
self.tool_configs = self.tool_config_file
# Collect the umask and primary gid from the environment
self.umask = os.umask(0o77) # get the current umask
os.umask(self.umask) # can't get w/o set, so set it back
self.gid = os.getgid() # if running under newgrp(1) we'll need to fix the group of data created on the cluster
self.version_major = VERSION_MAJOR
self.version_minor = VERSION_MINOR
# Database related configuration
self.check_migrate_databases = kwargs.get('check_migrate_databases', True)
if not self.database_connection: # Provide default if not supplied by user
db_path = self._in_data_dir('universe.sqlite')
self.database_connection = f'sqlite:///{db_path}?isolation_level=IMMEDIATE'
self.database_engine_options = get_database_engine_options(kwargs)
self.database_create_tables = string_as_bool(kwargs.get('database_create_tables', 'True'))
self.database_encoding = kwargs.get('database_encoding') # Create new databases with this encoding
self.thread_local_log = None
if self.enable_per_request_sql_debugging:
self.thread_local_log = threading.local()
# Install database related configuration (if different)
self.install_database_engine_options = get_database_engine_options(kwargs, model_prefix="install_")
self.shared_home_dir = kwargs.get("shared_home_dir")
self.cookie_path = kwargs.get("cookie_path")
self.tool_path = self._in_root_dir(self.tool_path)
self.tool_data_path = self._in_root_dir(self.tool_data_path)
if not running_from_source and kwargs.get("tool_data_path") is None:
self.tool_data_path = self._in_data_dir(self.schema.defaults['tool_data_path'])
self.builds_file_path = os.path.join(self.tool_data_path, self.builds_file_path)
self.len_file_path = os.path.join(self.tool_data_path, self.len_file_path)
self.oidc = {}
self.integrated_tool_panel_config = self._in_managed_config_dir(self.integrated_tool_panel_config)
integrated_tool_panel_tracking_directory = kwargs.get('integrated_tool_panel_tracking_directory')
if integrated_tool_panel_tracking_directory:
self.integrated_tool_panel_tracking_directory = self._in_root_dir(integrated_tool_panel_tracking_directory)
else:
self.integrated_tool_panel_tracking_directory = None
self.toolbox_filter_base_modules = listify(self.toolbox_filter_base_modules)
self.tool_filters = listify(self.tool_filters, do_strip=True)
self.tool_label_filters = listify(self.tool_label_filters, do_strip=True)
self.tool_section_filters = listify(self.tool_section_filters, do_strip=True)
self.user_tool_filters = listify(self.user_tool_filters, do_strip=True)
self.user_tool_label_filters = listify(self.user_tool_label_filters, do_strip=True)
self.user_tool_section_filters = listify(self.user_tool_section_filters, do_strip=True)
self.has_user_tool_filters = bool(self.user_tool_filters or self.user_tool_label_filters or self.user_tool_section_filters)
self.password_expiration_period = timedelta(days=int(self.password_expiration_period))
if self.shed_tool_data_path:
self.shed_tool_data_path = self._in_root_dir(self.shed_tool_data_path)
else:
self.shed_tool_data_path = self.tool_data_path
self.running_functional_tests = string_as_bool(kwargs.get('running_functional_tests', False))
if isinstance(self.hours_between_check, str):
self.hours_between_check = float(self.hours_between_check)
try:
if isinstance(self.hours_between_check, int):
if self.hours_between_check < 1 or self.hours_between_check > 24:
self.hours_between_check = 12
elif isinstance(self.hours_between_check, float):
# If we're running functional tests, the minimum hours between check should be reduced to 0.001, or 3.6 seconds.
if self.running_functional_tests:
if self.hours_between_check < 0.001 or self.hours_between_check > 24.0:
self.hours_between_check = 12.0
else:
if self.hours_between_check < 1.0 or self.hours_between_check > 24.0:
self.hours_between_check = 12.0
else:
self.hours_between_check = 12
except Exception:
self.hours_between_check = 12
self.update_integrated_tool_panel = kwargs.get("update_integrated_tool_panel", True)
self.galaxy_data_manager_data_path = self.galaxy_data_manager_data_path or self.tool_data_path
self.tool_secret = kwargs.get("tool_secret", "")
self.metadata_strategy = kwargs.get("metadata_strategy", "directory")
self.use_remote_user = self.use_remote_user or self.single_user
self.fetch_url_allowlist_ips = [
ipaddress.ip_network(unicodify(ip.strip())) # If it has a slash, assume 127.0.0.1/24 notation
if '/' in ip else
ipaddress.ip_address(unicodify(ip.strip())) # Otherwise interpret it as an ip address.
for ip in kwargs.get("fetch_url_allowlist", "").split(',')
if len(ip.strip()) > 0
]
self.template_path = self._in_root_dir(kwargs.get("template_path", "templates"))
self.job_queue_cleanup_interval = int(kwargs.get("job_queue_cleanup_interval", "5"))
self.cluster_files_directory = self._in_root_dir(self.cluster_files_directory)
# Fall back to legacy job_working_directory config variable if set.
self.jobs_directory = self._in_data_dir(kwargs.get("jobs_directory", self.job_working_directory))
if self.preserve_python_environment not in ["legacy_only", "legacy_and_local", "always"]:
log.warning("preserve_python_environment set to unknown value [%s], defaulting to legacy_only")
self.preserve_python_environment = "legacy_only"
self.nodejs_path = kwargs.get("nodejs_path")
self.container_image_cache_path = self._in_data_dir(kwargs.get("container_image_cache_path", "container_cache"))
self.output_size_limit = int(kwargs.get('output_size_limit', 0))
# activation_email was used until release_15.03
activation_email = kwargs.get('activation_email')
self.email_from = self.email_from or activation_email
self.email_domain_blocklist_content = self._load_list_from_file(self._in_config_dir(self.email_domain_blocklist_file)) if self.email_domain_blocklist_file else None
self.email_domain_allowlist_content = self._load_list_from_file(self._in_config_dir(self.email_domain_allowlist_file)) if self.email_domain_allowlist_file else None
# These are not even beta - just experiments - don't use them unless
# you want yours tools to be broken in the future.
self.enable_beta_tool_formats = string_as_bool(kwargs.get('enable_beta_tool_formats', 'False'))
if self.workflow_resource_params_mapper and ':' not in self.workflow_resource_params_mapper:
# Assume it is not a Python function, so a file; else: a Python function
self.workflow_resource_params_mapper = self._in_root_dir(self.workflow_resource_params_mapper)
self.pbs_application_server = kwargs.get('pbs_application_server', "")
self.pbs_dataset_server = kwargs.get('pbs_dataset_server', "")
self.pbs_dataset_path = kwargs.get('pbs_dataset_path', "")
self.pbs_stage_path = kwargs.get('pbs_stage_path', "")
_sanitize_allowlist_path = self._in_managed_config_dir(self.sanitize_allowlist_file)
if not os.path.isfile(_sanitize_allowlist_path): # then check old default location
for deprecated in (
self._in_managed_config_dir('sanitize_whitelist.txt'),
self._in_root_dir('config/sanitize_whitelist.txt')):
if os.path.isfile(deprecated):
log.warning("The path '%s' for the 'sanitize_allowlist_file' config option is "
"deprecated and will be no longer checked in a future release. Please consult "
"the latest version of the sample configuration file." % deprecated)
_sanitize_allowlist_path = deprecated
break
self.sanitize_allowlist_file = _sanitize_allowlist_path
self.allowed_origin_hostnames = self._parse_allowed_origin_hostnames(self.allowed_origin_hostnames)
if "trust_jupyter_notebook_conversion" not in kwargs:
# if option not set, check IPython-named alternative, falling back to schema default if not set either
_default = self.trust_jupyter_notebook_conversion
self.trust_jupyter_notebook_conversion = string_as_bool(kwargs.get('trust_ipython_notebook_conversion', _default))
# Configuration for the message box directly below the masthead.
self.blog_url = kwargs.get('blog_url')
self.user_library_import_symlink_allowlist = listify(self.user_library_import_symlink_allowlist, do_strip=True)
self.user_library_import_dir_auto_creation = self.user_library_import_dir_auto_creation if self.user_library_import_dir else False
# Searching data libraries
self.ftp_upload_dir_template = kwargs.get('ftp_upload_dir_template', '${ftp_upload_dir}%s${ftp_upload_dir_identifier}' % os.path.sep)
# Support older library-specific path paste option but just default to the new
# allow_path_paste value.
self.allow_library_path_paste = string_as_bool(kwargs.get('allow_library_path_paste', self.allow_path_paste))
self.disable_library_comptypes = kwargs.get('disable_library_comptypes', '').lower().split(',')
self.check_upload_content = string_as_bool(kwargs.get('check_upload_content', True))
# On can mildly speed up Galaxy startup time by disabling index of help,
# not needed on production systems but useful if running many functional tests.
self.index_tool_help = string_as_bool(kwargs.get("index_tool_help", True))
self.tool_labels_boost = kwargs.get("tool_labels_boost", 1)
default_tool_test_data_directories = os.environ.get("GALAXY_TEST_FILE_DIR", self._in_root_dir("test-data"))
self.tool_test_data_directories = kwargs.get("tool_test_data_directories", default_tool_test_data_directories)
# Deployers may either specify a complete list of mapping files or get the default for free and just
# specify a local mapping file to adapt and extend the default one.
if "conda_mapping_files" not in kwargs:
_default_mapping = self._in_root_dir(os.path.join("lib", "galaxy", "tool_util", "deps", "resolvers", "default_conda_mapping.yml"))
# dependency resolution options are consumed via config_dict - so don't populate
# self, populate config_dict
self.config_dict["conda_mapping_files"] = [self.local_conda_mapping_file, _default_mapping]
if self.container_resolvers_config_file:
self.container_resolvers_config_file = self._in_config_dir(self.container_resolvers_config_file)
# tool_dependency_dir can be "none" (in old configs). If so, set it to None
if self.tool_dependency_dir and self.tool_dependency_dir.lower() == 'none':
self.tool_dependency_dir = None
if self.involucro_path is None:
target_dir = self.tool_dependency_dir or self.schema.defaults['tool_dependency_dir']
self.involucro_path = self._in_data_dir(os.path.join(target_dir, "involucro"))
self.involucro_path = self._in_root_dir(self.involucro_path)
if self.mulled_channels:
self.mulled_channels = [c.strip() for c in self.mulled_channels.split(',')]
default_job_resubmission_condition = kwargs.get('default_job_resubmission_condition', '')
if not default_job_resubmission_condition.strip():
default_job_resubmission_condition = None
self.default_job_resubmission_condition = default_job_resubmission_condition
# Configuration options for taking advantage of nginx features
if self.nginx_upload_store:
self.nginx_upload_store = os.path.abspath(self.nginx_upload_store)
self.object_store = kwargs.get('object_store', 'disk')
self.object_store_check_old_style = string_as_bool(kwargs.get('object_store_check_old_style', False))
self.object_store_cache_path = self._in_root_dir(kwargs.get("object_store_cache_path", self._in_data_dir("object_store_cache")))
self._configure_dataset_storage()
# Handle AWS-specific config options for backward compatibility
if kwargs.get('aws_access_key') is not None:
self.os_access_key = kwargs.get('aws_access_key')
self.os_secret_key = kwargs.get('aws_secret_key')
self.os_bucket_name = kwargs.get('s3_bucket')
self.os_use_reduced_redundancy = kwargs.get('use_reduced_redundancy', False)
else:
self.os_access_key = kwargs.get('os_access_key')
self.os_secret_key = kwargs.get('os_secret_key')
self.os_bucket_name = kwargs.get('os_bucket_name')
self.os_use_reduced_redundancy = kwargs.get('os_use_reduced_redundancy', False)
self.os_host = kwargs.get('os_host')
self.os_port = kwargs.get('os_port')
self.os_is_secure = string_as_bool(kwargs.get('os_is_secure', True))
self.os_conn_path = kwargs.get('os_conn_path', '/')
self.object_store_cache_size = float(kwargs.get('object_store_cache_size', -1))
self.distributed_object_store_config_file = kwargs.get('distributed_object_store_config_file')
if self.distributed_object_store_config_file is not None:
self.distributed_object_store_config_file = self._in_root_dir(self.distributed_object_store_config_file)
self.irods_root_collection_path = kwargs.get('irods_root_collection_path')
self.irods_default_resource = kwargs.get('irods_default_resource')
# Heartbeat log file name override
if self.global_conf is not None and 'heartbeat_log' in self.global_conf:
self.heartbeat_log = self.global_conf['heartbeat_log']
# Determine which 'server:' this is
self.server_name = 'main'
for arg in sys.argv:
# Crummy, but PasteScript does not give you a way to determine this
if arg.lower().startswith('--server-name='):
self.server_name = arg.split('=', 1)[-1]
# Allow explicit override of server name in config params
if "server_name" in kwargs:
self.server_name = kwargs.get("server_name")
# The application stack code may manipulate the server name. It also needs to be accessible via the get() method
# for galaxy.util.facts()
self.config_dict['base_server_name'] = self.base_server_name = self.server_name
# Store all configured server names for the message queue routing
self.server_names = []
for section in self.global_conf_parser.sections():
if section.startswith('server:'):
self.server_names.append(section.replace('server:', '', 1))
self._set_galaxy_infrastructure_url(kwargs)
# Asynchronous execution process pools - limited functionality for now, attach_to_pools is designed to allow
# webless Galaxy server processes to attach to arbitrary message queues (e.g. as job handlers) so they do not
# have to be explicitly defined as such in the job configuration.
self.attach_to_pools = kwargs.get('attach_to_pools', []) or []
# Store advanced job management config
self.job_handlers = [x.strip() for x in kwargs.get('job_handlers', self.server_name).split(',')]
self.default_job_handlers = [x.strip() for x in kwargs.get('default_job_handlers', ','.join(self.job_handlers)).split(',')]
# Galaxy internal control queue configuration.
# If specified in universe, use it, otherwise we use whatever 'real'
# database is specified. Lastly, we create and use new sqlite database
# (to minimize locking) as a final option.
if 'amqp_internal_connection' in kwargs:
self.amqp_internal_connection = kwargs.get('amqp_internal_connection')
# TODO Get extra amqp args as necessary for ssl
elif 'database_connection' in kwargs:
self.amqp_internal_connection = f"sqlalchemy+{self.database_connection}"
else:
self.amqp_internal_connection = f"sqlalchemy+sqlite:///{self._in_data_dir("control.sqlite")}?isolation_level=IMMEDIATE"
self.pretty_datetime_format = expand_pretty_datetime_format(self.pretty_datetime_format)
try:
with open(self.user_preferences_extra_conf_path) as stream:
self.user_preferences_extra = yaml.safe_load(stream)
except Exception:
if self.is_set('user_preferences_extra_conf_path'):
log.warning(f'Config file ({self.user_preferences_extra_conf_path}) could not be found or is malformed.')
self.user_preferences_extra = {'preferences': {}}
# Experimental: This will not be enabled by default and will hide
# nonproduction code.
# The api_folders refers to whether the API exposes the /folders section.
self.api_folders = string_as_bool(kwargs.get('api_folders', False))
# This is for testing new library browsing capabilities.
self.new_lib_browse = string_as_bool(kwargs.get('new_lib_browse', False))
# Logging configuration with logging.config.configDict:
# Statistics and profiling with statsd
self.statsd_host = kwargs.get('statsd_host', '')
ie_dirs = self.interactive_environment_plugins_directory
self.gie_dirs = [d.strip() for d in (ie_dirs.split(",") if ie_dirs else [])]
if ie_dirs:
self.visualization_plugins_directory += f",{ie_dirs}"
self.proxy_session_map = self.dynamic_proxy_session_map
self.manage_dynamic_proxy = self.dynamic_proxy_manage # Set to false if being launched externally
# InteractiveTools propagator mapping file
self.interactivetools_map = self._in_root_dir(kwargs.get("interactivetools_map", self._in_data_dir("interactivetools_map.sqlite")))
self.containers_conf = parse_containers_config(self.containers_config_file)
# Compliance/Policy variables
self.redact_username_during_deletion = False
self.redact_email_during_deletion = False
self.redact_ip_address = False
self.redact_username_in_logs = False
self.redact_email_in_job_name = False
self.redact_user_details_in_bugreport = False
self.redact_user_address_during_deletion = False
# GDPR compliance mode changes values on a number of variables. Other
# policies could change (non)overlapping subsets of these variables.
if self.enable_beta_gdpr:
self.expose_user_name = False
self.expose_user_email = False
self.redact_username_during_deletion = True
self.redact_email_during_deletion = True
self.redact_ip_address = True
self.redact_username_in_logs = True
self.redact_email_in_job_name = True
self.redact_user_details_in_bugreport = True
self.redact_user_address_during_deletion = True
self.allow_user_deletion = True
LOGGING_CONFIG_DEFAULT['formatters']['brief'] = {
'format': '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
}
LOGGING_CONFIG_DEFAULT['handlers']['compliance_log'] = {
'class': 'logging.handlers.RotatingFileHandler',
'formatter': 'brief',
'filename': 'compliance.log',
'backupCount': 0,
}
LOGGING_CONFIG_DEFAULT['loggers']['COMPLIANCE'] = {
'handlers': ['compliance_log'],
'level': 'DEBUG',
'qualname': 'COMPLIANCE'
}
log_destination = kwargs.get("log_destination")
galaxy_daemon_log_destination = os.environ.get('GALAXY_DAEMON_LOG')
if log_destination == "stdout":
LOGGING_CONFIG_DEFAULT['handlers']['console'] = {
'class': 'logging.StreamHandler',
'formatter': 'stack',
'level': 'DEBUG',
'stream': 'ext://sys.stdout',
'filters': ['stack']
}
elif log_destination:
LOGGING_CONFIG_DEFAULT['handlers']['console'] = {
'class': 'logging.FileHandler',
'formatter': 'stack',
'level': 'DEBUG',
'filename': log_destination,
'filters': ['stack']
}
if galaxy_daemon_log_destination:
LOGGING_CONFIG_DEFAULT['handlers']['files'] = {
'class': 'logging.FileHandler',
'formatter': 'stack',
'level': 'DEBUG',
'filename': galaxy_daemon_log_destination,
'filters': ['stack']
}
LOGGING_CONFIG_DEFAULT['root']['handlers'].append('files')
def _configure_dataset_storage(self):
# The default for `file_path` has changed in 20.05; we may need to fall back to the old default
self._set_alt_paths('file_path', self._in_data_dir('files')) # this is called BEFORE guessing id/uuid
ID, UUID = 'id', 'uuid'
if self.is_set('object_store_store_by'):
assert self.object_store_store_by in [ID, UUID], f"Invalid value for object_store_store_by [{self.object_store_store_by}]"
elif os.path.basename(self.file_path) == 'objects':
self.object_store_store_by = UUID
else:
self.object_store_store_by = ID
def _load_list_from_file(self, filepath):
with open(filepath) as f:
return [line.strip() for line in f]
def _set_galaxy_infrastructure_url(self, kwargs):
# indicate if this was not set explicitly, so dependending on the context a better default
# can be used (request url in a web thread, Docker parent in IE stuff, etc.)
self.galaxy_infrastructure_url_set = kwargs.get('galaxy_infrastructure_url') is not None
if "HOST_IP" in self.galaxy_infrastructure_url:
self.galaxy_infrastructure_url = string.Template(self.galaxy_infrastructure_url).safe_substitute({
'HOST_IP': socket.gethostbyname(socket.gethostname())
})
if "GALAXY_WEB_PORT" in self.galaxy_infrastructure_url:
port = os.environ.get('GALAXY_WEB_PORT')
if not port:
raise Exception('$GALAXY_WEB_PORT set in galaxy_infrastructure_url, but environment variable not set')
self.galaxy_infrastructure_url = string.Template(self.galaxy_infrastructure_url).safe_substitute({
'GALAXY_WEB_PORT': port
})
if "UWSGI_PORT" in self.galaxy_infrastructure_url:
import uwsgi
http = unicodify(uwsgi.opt['http'])
host, port = http.split(":", 1)
assert port, "galaxy_infrastructure_url depends on dynamic PORT determination but port unknown"
self.galaxy_infrastructure_url = string.Template(self.galaxy_infrastructure_url).safe_substitute({
'UWSGI_PORT': port
})
def reload_sanitize_allowlist(self, explicit=True):
self.sanitize_allowlist = []
try:
with open(self.sanitize_allowlist_file) as f:
for line in f.readlines():
if not line.startswith("#"):
self.sanitize_allowlist.append(line.strip())
except OSError:
if explicit:
log.warning("Sanitize log file explicitly specified as '%s' but does not exist, continuing with no tools allowlisted.", self.sanitize_allowlist_file)
def ensure_tempdir(self):
self._ensure_directory(self.new_file_path)
def check(self):
# Check that required directories exist; attempt to create otherwise
paths_to_check = [
self.data_dir,
self.ftp_upload_dir,
self.library_import_dir,
self.managed_config_dir,
self.new_file_path,
self.nginx_upload_store,
self.object_store_cache_path,
self.template_cache_path,
self.tool_data_path,
self.user_library_import_dir,
]
for path in paths_to_check:
self._ensure_directory(path)
# Check that required files exist
tool_configs = self.tool_configs
for path in tool_configs:
if not os.path.exists(path) and path not in (self.shed_tool_config_file, self.migrated_tools_config):
raise ConfigurationError(f"Tool config file not found: {path}")
for datatypes_config in listify(self.datatypes_config):
if not os.path.isfile(datatypes_config):
raise ConfigurationError(f"Datatypes config file not found: {datatypes_config}")
# Check for deprecated options.
for key in self.config_dict.keys():
if key in self.deprecated_options:
log.warning(f"Config option '{key}' is deprecated and will be removed in a future release. Please consult the latest version of the sample configuration file.")
@staticmethod
def _parse_allowed_origin_hostnames(allowed_origin_hostnames):
"""
Parse a CSV list of strings/regexp of hostnames that should be allowed
to use CORS and will be sent the Access-Control-Allow-Origin header.
"""
allowed_origin_hostnames_list = listify(allowed_origin_hostnames)
if not allowed_origin_hostnames_list:
return None
def parse(string):
# a string enclosed in fwd slashes will be parsed as a regexp: e.g. /<some val>/
if string[0] == '/' and string[-1] == '/':
string = string[1:-1]
return re.compile(string, flags=(re.UNICODE))
return string
return [parse(v) for v in allowed_origin_hostnames_list if v]
# legacy naming
Configuration = GalaxyAppConfiguration
def reload_config_options(current_config):
"""Reload modified reloadable config options."""
modified_config = read_properties_from_file(current_config.config_file)
for option in current_config.schema.reloadable_options:
if option in modified_config:
# compare to raw value, as that one is set only on load and reload
if current_config._raw_config[option] != modified_config[option]:
current_config._raw_config[option] = modified_config[option]
setattr(current_config, option, modified_config[option])
log.info(f'Reloaded {option}')
def get_database_engine_options(kwargs, model_prefix=''):
"""
Allow options for the SQLAlchemy database engine to be passed by using
the prefix "database_engine_option".
"""
conversions = {
'convert_unicode': string_as_bool,
'pool_timeout': int,
'echo': string_as_bool,
'echo_pool': string_as_bool,
'pool_recycle': int,
'pool_size': int,
'max_overflow': int,
'pool_threadlocal': string_as_bool,
'server_side_cursors': string_as_bool
}
prefix = f"{model_prefix}database_engine_option_"
prefix_len = len(prefix)
rval = {}
for key, value in kwargs.items():
if key.startswith(prefix):
key = key[prefix_len:]
if key in conversions:
value = conversions[key](value)
rval[key] = value
return rval
def get_database_url(config):
db_url = config.database_connection
return db_url
def init_models_from_config(config, map_install_models=False, object_store=None, trace_logger=None):
db_url = get_database_url(config)
model = mapping.init(
config.file_path,
db_url,
config.database_engine_options,
map_install_models=map_install_models,
database_query_profiling_proxy=config.database_query_profiling_proxy,
object_store=object_store,
trace_logger=trace_logger,
use_pbkdf2=config.get_bool('use_pbkdf2', True),
slow_query_log_threshold=config.slow_query_log_threshold,
thread_local_log=config.thread_local_log,
log_query_counts=config.database_log_query_counts,
)
return model
def configure_logging(config):
"""Allow some basic logging configuration to be read from ini file.
This should be able to consume either a galaxy.config.Configuration object
or a simple dictionary of configuration variables.
"""
# Get root logger
logging.addLevelName(LOGLV_TRACE, "TRACE")
root = logging.getLogger()
# PasteScript will have already configured the logger if the
# 'loggers' section was found in the config file, otherwise we do
# some simple setup using the 'log_*' values from the config.
parser = getattr(config, "global_conf_parser", None)
if parser:
paste_configures_logging = config.global_conf_parser.has_section("loggers")
else:
paste_configures_logging = False
auto_configure_logging = not paste_configures_logging and string_as_bool(config.get("auto_configure_logging", "True"))
if auto_configure_logging:
logging_conf = config.get('logging', None)
if logging_conf is None:
# if using the default logging config, honor the log_level setting
logging_conf = LOGGING_CONFIG_DEFAULT
if config.get('log_level', 'DEBUG') != 'DEBUG':
logging_conf['handlers']['console']['level'] = config.get('log_level', 'DEBUG')
# configure logging with logging dict in config, template *FileHandler handler filenames with the `filename_template` option
for name, conf in logging_conf.get('handlers', {}).items():
if conf['class'].startswith('logging.') and conf['class'].endswith('FileHandler') and 'filename_template' in conf:
conf['filename'] = conf.pop('filename_template').format(**get_stack_facts(config=config))
logging_conf['handlers'][name] = conf
logging.config.dictConfig(logging_conf)
if getattr(config, "sentry_dsn", None):
from raven.handlers.logging import SentryHandler
sentry_handler = SentryHandler(config.sentry_dsn)
sentry_handler.setLevel(logging.WARN)
register_postfork_function(root.addHandler, sentry_handler)
class ConfiguresGalaxyMixin:
"""Shared code for configuring Galaxy-like app objects."""
def _configure_genome_builds(self, data_table_name="__dbkeys__", load_old_style=True):
self.genome_builds = GenomeBuilds(self, data_table_name=data_table_name, load_old_style=load_old_style)
def wait_for_toolbox_reload(self, old_toolbox):
timer = ExecutionTimer()
log.debug('Waiting for toolbox reload')
# Wait till toolbox reload has been triggered (or more than 60 seconds have passed)
while timer.elapsed < 60:
if self.toolbox.has_reloaded(old_toolbox):
log.debug('Finished waiting for toolbox reload %s', timer)
break
time.sleep(0.1)
else:
log.warning('Waiting for toolbox reload timed out after 60 seconds')
def _configure_tool_config_files(self):
if self.config.shed_tool_config_file not in self.config.tool_configs:
self.config.tool_configs.append(self.config.shed_tool_config_file)
# The value of migrated_tools_config is the file reserved for containing only those tools that have been
# eliminated from the distribution and moved to the tool shed. If migration checking is disabled, only add it if
# it exists (since this may be an existing deployment where migrations were previously run).
if ((self.config.check_migrate_tools or os.path.exists(self.config.migrated_tools_config))
and self.config.migrated_tools_config not in self.config.tool_configs):
self.config.tool_configs.append(self.config.migrated_tools_config)
def _configure_toolbox(self):
from galaxy import tools
from galaxy.managers.citations import CitationsManager
from galaxy.tool_util.deps import containers
from galaxy.tool_util.deps.dependencies import AppInfo
import galaxy.tools.search
self.citations_manager = CitationsManager(self)
from galaxy.managers.tools import DynamicToolManager
self.dynamic_tools_manager = DynamicToolManager(self)
self._toolbox_lock = threading.RLock()
self.toolbox = tools.ToolBox(self.config.tool_configs, self.config.tool_path, self)
galaxy_root_dir = os.path.abspath(self.config.root)
file_path = os.path.abspath(self.config.file_path)
app_info = AppInfo(
galaxy_root_dir=galaxy_root_dir,
default_file_path=file_path,
tool_data_path=self.config.tool_data_path,
shed_tool_data_path=self.config.shed_tool_data_path,
outputs_to_working_directory=self.config.outputs_to_working_directory,
container_image_cache_path=self.config.container_image_cache_path,
library_import_dir=self.config.library_import_dir,
enable_mulled_containers=self.config.enable_mulled_containers,
container_resolvers_config_file=self.config.container_resolvers_config_file,
container_resolvers_config_dict=self.config.container_resolvers,
involucro_path=self.config.involucro_path,
involucro_auto_init=self.config.involucro_auto_init,
mulled_channels=self.config.mulled_channels,
)
mulled_resolution_cache = None
if self.config.mulled_resolution_cache_type:
cache_opts = {
'cache.type': self.config.mulled_resolution_cache_type,
'cache.data_dir': self.config.mulled_resolution_cache_data_dir,
'cache.lock_dir': self.config.mulled_resolution_cache_lock_dir,
}
mulled_resolution_cache = CacheManager(**parse_cache_config_options(cache_opts)).get_cache('mulled_resolution')
self.container_finder = containers.ContainerFinder(app_info, mulled_resolution_cache=mulled_resolution_cache)
self._set_enabled_container_types()
index_help = getattr(self.config, "index_tool_help", True)
self.toolbox_search = galaxy.tools.search.ToolBoxSearch(self.toolbox, index_dir=self.config.tool_search_index_dir, index_help=index_help)
def reindex_tool_search(self):
# Call this when tools are added or removed.
self.toolbox_search.build_index(tool_cache=self.tool_cache)
self.tool_cache.reset_status()
def _set_enabled_container_types(self):
container_types_to_destinations = collections.defaultdict(list)
for destinations in self.job_config.destinations.values():
for destination in destinations:
for enabled_container_type in self.container_finder._enabled_container_types(destination.params):
container_types_to_destinations[enabled_container_type].append(destination)
self.toolbox.dependency_manager.set_enabled_container_types(container_types_to_destinations)
self.toolbox.dependency_manager.resolver_classes.update(self.container_finder.default_container_registry.resolver_classes)
self.toolbox.dependency_manager.dependency_resolvers.extend(self.container_finder.default_container_registry.container_resolvers)
def _configure_tool_data_tables(self, from_shed_config):
from galaxy.tools.data import ToolDataTableManager
# Initialize tool data tables using the config defined by self.config.tool_data_table_config_path.
self.tool_data_tables = ToolDataTableManager(tool_data_path=self.config.tool_data_path,
config_filename=self.config.tool_data_table_config_path,
other_config_dict=self.config)
# Load additional entries defined by self.config.shed_tool_data_table_config into tool data tables.
try:
self.tool_data_tables.load_from_config_file(config_filename=self.config.shed_tool_data_table_config,
tool_data_path=self.tool_data_tables.tool_data_path,
from_shed_config=from_shed_config)
except OSError as exc:
# Missing shed_tool_data_table_config is okay if it's the default
if exc.errno != errno.ENOENT or self.config.is_set('shed_tool_data_table_config'):
raise
def _configure_datatypes_registry(self, installed_repository_manager=None):
from galaxy.datatypes import registry
# Create an empty datatypes registry.
self.datatypes_registry = registry.Registry(self.config)
if installed_repository_manager:
# Load proprietary datatypes defined in datatypes_conf.xml files in all installed tool shed repositories. We
# load proprietary datatypes before datatypes in the distribution because Galaxy's default sniffers include some
# generic sniffers (eg text,xml) which catch anything, so it's impossible for proprietary sniffers to be used.
# However, if there is a conflict (2 datatypes with the same extension) between a proprietary datatype and a datatype
# in the Galaxy distribution, the datatype in the Galaxy distribution will take precedence. If there is a conflict
# between 2 proprietary datatypes, the datatype from the repository that was installed earliest will take precedence.
installed_repository_manager.load_proprietary_datatypes()
# Load the data types in the Galaxy distribution, which are defined in self.config.datatypes_config.
datatypes_configs = self.config.datatypes_config
for datatypes_config in listify(datatypes_configs):
# Setting override=False would make earlier files would take
# precedence - but then they wouldn't override tool shed
# datatypes.
self.datatypes_registry.load_datatypes(self.config.root, datatypes_config, override=True)
def _configure_object_store(self, **kwds):
from galaxy.objectstore import build_object_store_from_config
self.object_store = build_object_store_from_config(self.config, **kwds)
def _configure_security(self):
from galaxy.security import idencoding
self.security = idencoding.IdEncodingHelper(id_secret=self.config.id_secret)
def _configure_tool_shed_registry(self):
import galaxy.tool_shed.tool_shed_registry
# Set up the tool sheds registry
if os.path.isfile(self.config.tool_sheds_config_file):
self.tool_shed_registry = galaxy.tool_shed.tool_shed_registry.Registry(self.config.tool_sheds_config_file)
else:
self.tool_shed_registry = galaxy.tool_shed.tool_shed_registry.Registry()
def _configure_models(self, check_migrate_databases=False, check_migrate_tools=False, config_file=None):
"""Preconditions: object_store must be set on self."""
db_url = get_database_url(self.config)
install_db_url = self.config.install_database_connection
# TODO: Consider more aggressive check here that this is not the same
# database file under the hood.
combined_install_database = not(install_db_url and install_db_url != db_url)
install_db_url = install_db_url or db_url
install_database_options = self.config.database_engine_options if combined_install_database else self.config.install_database_engine_options
if self.config.database_wait:
self._wait_for_database(db_url)
if getattr(self.config, "max_metadata_value_size", None):
from galaxy.model import custom_types
custom_types.MAX_METADATA_VALUE_SIZE = self.config.max_metadata_value_size
if check_migrate_databases:
# Initialize database / check for appropriate schema version. # If this
# is a new installation, we'll restrict the tool migration messaging.
from galaxy.model.migrate.check import create_or_verify_database
create_or_verify_database(db_url, config_file, self.config.database_engine_options, app=self, map_install_models=combined_install_database)
if not combined_install_database:
tsi_create_or_verify_database(install_db_url, install_database_options, app=self)
if check_migrate_tools:
# Alert the Galaxy admin to tools that have been moved from the distribution to the tool shed.
from galaxy.tool_shed.galaxy_install.migrate.check import verify_tools
verify_tools(self, install_db_url, config_file, install_database_options)
self.model = init_models_from_config(
self.config,
map_install_models=combined_install_database,
object_store=self.object_store,
trace_logger=getattr(self, "trace_logger", None)
)
if combined_install_database:
log.info("Install database targetting Galaxy's database configuration.")
self.install_model = self.model
else:
from galaxy.model.tool_shed_install import mapping as install_mapping
install_db_url = self.config.install_database_connection
log.info(f"Install database using its own connection {install_db_url}")
self.install_model = install_mapping.init(install_db_url,
install_database_options)
def _configure_signal_handlers(self, handlers):
for sig, handler in handlers.items():
signal.signal(sig, handler)
def _wait_for_database(self, url):
attempts = self.config.database_wait_attempts
pause = self.config.database_wait_sleep
for i in range(1, attempts):
try:
database_exists(url)
break
except Exception:
log.info("Waiting for database: attempt %d of %d" % (i, attempts))
time.sleep(pause)
@property
def tool_dependency_dir(self):
return self.toolbox.dependency_manager.default_base_path
| """
Universe configuration builder.
"""
# absolute_import needed for tool_shed package.
import collections
import configparser
import errno
import ipaddress
import logging
import logging.config
import os
import re
import signal
import socket
import string
import sys
import tempfile
import threading
import time
from datetime import timedelta
from typing import Dict, Optional, Set
import yaml
from beaker.cache import CacheManager
from beaker.util import parse_cache_config_options
from galaxy.config.schema import AppSchema
from galaxy.containers import parse_containers_config
from galaxy.exceptions import ConfigurationError
from galaxy.model import mapping
from galaxy.model.database_utils import database_exists
from galaxy.model.tool_shed_install.migrate.check import create_or_verify_database as tsi_create_or_verify_database
from galaxy.util import (
ExecutionTimer,
listify,
string_as_bool,
unicodify,
)
from galaxy.util.custom_logging import LOGLV_TRACE
from galaxy.util.dbkeys import GenomeBuilds
from galaxy.util.properties import (
find_config_file,
read_properties_from_file,
running_from_source,
)
from galaxy.web.formatting import expand_pretty_datetime_format
from galaxy.web_stack import (
get_stack_facts,
register_postfork_function
)
from ..version import VERSION_MAJOR, VERSION_MINOR
log = logging.getLogger(__name__)
GALAXY_APP_NAME = 'galaxy'
GALAXY_CONFIG_SCHEMA_PATH = 'lib/galaxy/webapps/galaxy/config_schema.yml'
LOGGING_CONFIG_DEFAULT = {
'disable_existing_loggers': False,
'version': 1,
'root': {
'handlers': ['console'],
'level': 'DEBUG',
},
'loggers': {
'paste.httpserver.ThreadPool': {
'level': 'WARN',
'qualname': 'paste.httpserver.ThreadPool',
},
'sqlalchemy_json.track': {
'level': 'WARN',
'qualname': 'sqlalchemy_json.track',
},
'urllib3.connectionpool': {
'level': 'WARN',
'qualname': 'urllib3.connectionpool',
},
'routes.middleware': {
'level': 'WARN',
'qualname': 'routes.middleware',
},
'amqp': {
'level': 'INFO',
'qualname': 'amqp',
},
'botocore': {
'level': 'INFO',
'qualname': 'botocore',
},
},
'filters': {
'stack': {
'()': 'galaxy.web_stack.application_stack_log_filter',
},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'stack',
'level': 'DEBUG',
'stream': 'ext://sys.stderr',
'filters': ['stack'],
},
},
'formatters': {
'stack': {
'()': 'galaxy.web_stack.application_stack_log_formatter',
},
},
}
"""Default value for logging configuration, passed to :func:`logging.config.dictConfig`"""
def find_root(kwargs):
return os.path.abspath(kwargs.get('root_dir', '.'))
class BaseAppConfiguration:
# Override in subclasses (optional): {KEY: config option, VALUE: deprecated directory name}
# If VALUE == first directory in a user-supplied path that resolves to KEY, it will be stripped from that path
renamed_options: Optional[Dict[str, str]] = None
deprecated_dirs: Dict[str, str] = {}
paths_to_check_against_root: Set[str] = set() # backward compatibility: if resolved path doesn't exist, try resolving w.r.t root
add_sample_file_to_defaults: Set[str] = set() # for these options, add sample config files to their defaults
listify_options: Set[str] = set() # values for these options are processed as lists of values
def __init__(self, **kwargs):
self._preprocess_kwargs(kwargs)
self._kwargs = kwargs # Save these as a record of explicitly set options
self.config_dict = kwargs
self.root = find_root(kwargs)
self._set_config_base(kwargs)
self.schema = self._load_schema() # Load schema from schema definition file
self._raw_config = self.schema.defaults.copy() # Save schema defaults as initial config values (raw_config)
self._update_raw_config_from_kwargs(kwargs) # Overwrite raw_config with values passed in kwargs
self._create_attributes_from_raw_config() # Create attributes based on raw_config
self._preprocess_paths_to_resolve() # Any preprocessing steps that need to happen before paths are resolved
self._resolve_paths() # Overwrite attribute values with resolved paths
self._postprocess_paths_to_resolve() # Any steps that need to happen after paths are resolved
def _preprocess_kwargs(self, kwargs):
self._process_renamed_options(kwargs)
self._fix_postgresql_dburl(kwargs)
def _process_renamed_options(self, kwargs):
"""Update kwargs to set any unset renamed options to values of old-named options, if set.
Does not remove the old options from kwargs so that deprecated option usage can be logged.
"""
if self.renamed_options is not None:
for old, new in self.renamed_options.items():
if old in kwargs and new not in kwargs:
kwargs[new] = kwargs[old]
def _fix_postgresql_dburl(self, kwargs):
"""
Fix deprecated database URLs (postgres... >> postgresql...)
https://docs.sqlalchemy.org/en/14/changelog/changelog_14.html#change-3687655465c25a39b968b4f5f6e9170b
"""
old_dialect, new_dialect = 'postgres', 'postgresql'
old_prefixes = (f'{old_dialect}:', f'{old_dialect}+') # check for postgres://foo and postgres+driver//foo
offset = len(old_dialect)
keys = ('database_connection', 'install_database_connection')
for key in keys:
if key in kwargs:
value = kwargs[key]
for prefix in old_prefixes:
if value.startswith(prefix):
value = f'{new_dialect}{value[offset:]}'
kwargs[key] = value
log.warning('PostgreSQL database URLs of the form "postgres://" have been '
'deprecated. Please use "postgresql://".')
def is_set(self, key):
"""Check if a configuration option has been explicitly set."""
# NOTE: This will check all supplied keyword arguments, including those not in the schema.
# To check only schema options, change the line below to `if property not in self._raw_config:`
if key not in self._raw_config:
log.warning(f"Configuration option does not exist: '{key}'")
return key in self._kwargs
def resolve_path(self, path):
"""Resolve a path relative to Galaxy's root."""
return self._in_root_dir(path)
def _set_config_base(self, config_kwargs):
def _set_global_conf():
self.config_file = find_config_file('galaxy')
self.global_conf = config_kwargs.get('global_conf')
self.global_conf_parser = configparser.ConfigParser()
if not self.config_file and self.global_conf and "__file__" in self.global_conf:
self.config_file = os.path.join(self.root, self.global_conf['__file__'])
if self.config_file is None:
log.warning("No Galaxy config file found, running from current working directory: %s", os.getcwd())
else:
try:
self.global_conf_parser.read(self.config_file)
except OSError:
raise
except Exception:
pass # Not an INI file
def _set_config_directories():
# Set config_dir to value from kwargs OR dirname of config_file OR None
_config_dir = os.path.dirname(self.config_file) if self.config_file else None
self.config_dir = config_kwargs.get('config_dir', _config_dir)
# Make path absolute before using it as base for other paths
if self.config_dir:
self.config_dir = os.path.abspath(self.config_dir)
self.data_dir = config_kwargs.get('data_dir')
if self.data_dir:
self.data_dir = os.path.abspath(self.data_dir)
self.sample_config_dir = os.path.join(os.path.dirname(__file__), 'sample')
if self.sample_config_dir:
self.sample_config_dir = os.path.abspath(self.sample_config_dir)
self.managed_config_dir = config_kwargs.get('managed_config_dir')
if self.managed_config_dir:
self.managed_config_dir = os.path.abspath(self.managed_config_dir)
if running_from_source:
if not self.config_dir:
self.config_dir = os.path.join(self.root, 'config')
if not self.data_dir:
self.data_dir = os.path.join(self.root, 'database')
if not self.managed_config_dir:
self.managed_config_dir = self.config_dir
else:
if not self.config_dir:
self.config_dir = os.getcwd()
if not self.data_dir:
self.data_dir = self._in_config_dir('data')
if not self.managed_config_dir:
self.managed_config_dir = self._in_data_dir('config')
# TODO: do we still need to support ../shed_tools when running_from_source?
self.shed_tools_dir = self._in_data_dir('shed_tools')
log.debug("Configuration directory is %s", self.config_dir)
log.debug("Data directory is %s", self.data_dir)
log.debug("Managed config directory is %s", self.managed_config_dir)
_set_global_conf()
_set_config_directories()
def _load_schema(self):
# Override in subclasses
raise Exception('Not implemented')
def _preprocess_paths_to_resolve(self):
# For these options, if option is not set, listify its defaults and add a sample config file.
if self.add_sample_file_to_defaults:
for key in self.add_sample_file_to_defaults:
if not self.is_set(key):
defaults = listify(getattr(self, key), do_strip=True)
sample = f'{defaults[-1]}.sample' # if there are multiple defaults, use last as template
sample = self._in_sample_dir(sample) # resolve w.r.t sample_dir
defaults.append(sample)
setattr(self, key, defaults)
def _postprocess_paths_to_resolve(self):
def select_one_path_from_list():
# To consider: options with a sample file added to defaults except options that can have multiple values.
# If value is not set, check each path in list; set to first path that exists; if none exist, set to last path in list.
keys = self.add_sample_file_to_defaults - self.listify_options if self.listify_options else self.add_sample_file_to_defaults
for key in keys:
if not self.is_set(key):
paths = getattr(self, key)
for path in paths:
if self._path_exists(path):
setattr(self, key, path)
break
else:
setattr(self, key, paths[-1]) # TODO: we assume it exists; but we've already checked in the loop! Raise error instead?
def select_one_or_all_paths_from_list():
# Values for these options are lists of paths. If value is not set, use defaults if all paths in list exist;
# otherwise, set to last path in list.
for key in self.listify_options:
if not self.is_set(key):
paths = getattr(self, key)
for path in paths:
if not self._path_exists(path):
setattr(self, key, [paths[-1]]) # value is a list
break
if self.add_sample_file_to_defaults: # Currently, this is the ONLY case when we need to pick one file from a list
select_one_path_from_list()
if self.listify_options:
select_one_or_all_paths_from_list()
def _path_exists(self, path): # factored out so we can mock it in tests
return os.path.exists(path)
def _set_alt_paths(self, option, *alt_paths):
# If `option` is not set, check *alt_paths. Set `option` to first path that exists and return it.
if not self.is_set(option):
for path in alt_paths:
if self._path_exists(path):
setattr(self, option, path)
return path
def _update_raw_config_from_kwargs(self, kwargs):
def convert_datatype(key, value):
datatype = self.schema.app_schema[key].get('type')
# check for `not None` explicitly (value can be falsy)
if value is not None and datatype in type_converters:
# convert value or each item in value to type `datatype`
f = type_converters[datatype]
if isinstance(value, list):
return [f(item) for item in value]
else:
return f(value)
return value
def strip_deprecated_dir(key, value):
resolves_to = self.schema.paths_to_resolve.get(key)
if resolves_to: # value contains paths that will be resolved
paths = listify(value, do_strip=True)
for i, path in enumerate(paths):
first_dir = path.split(os.sep)[0] # get first directory component
if first_dir == self.deprecated_dirs.get(resolves_to): # first_dir is deprecated for this option
ignore = first_dir + os.sep
log.warning(
"Paths for the '%s' option are now relative to '%s', remove the leading '%s' "
"to suppress this warning: %s", key, resolves_to, ignore, path
)
paths[i] = path[len(ignore):]
# return list or string, depending on type of `value`
if isinstance(value, list):
return paths
return ','.join(paths)
return value
type_converters = {'bool': string_as_bool, 'int': int, 'float': float, 'str': str}
for key, value in kwargs.items():
if key in self.schema.app_schema:
value = convert_datatype(key, value)
if value and self.deprecated_dirs:
value = strip_deprecated_dir(key, value)
self._raw_config[key] = value
def _create_attributes_from_raw_config(self):
# `base_configs` are a special case: these attributes have been created and will be ignored
# by the code below. Trying to overwrite any other existing attributes will raise an error.
base_configs = {'config_dir', 'data_dir', 'managed_config_dir'}
for key, value in self._raw_config.items():
if not hasattr(self, key):
setattr(self, key, value)
elif key not in base_configs:
raise ConfigurationError(f"Attempting to override existing attribute '{key}'")
def _resolve_paths(self):
def resolve(key):
if key in _cache: # resolve each path only once
return _cache[key]
path = getattr(self, key) # path prior to being resolved
parent = self.schema.paths_to_resolve.get(key)
if not parent: # base case: nothing else needs resolving
return path
parent_path = resolve(parent) # recursively resolve parent path
if path is not None:
path = os.path.join(parent_path, path) # resolve path
else:
path = parent_path # or use parent path
setattr(self, key, path) # update property
_cache[key] = path # cache it!
return path
_cache = {}
for key in self.schema.paths_to_resolve:
value = getattr(self, key)
# Check if value is a list or should be listified; if so, listify and resolve each item separately.
if type(value) is list or (self.listify_options and key in self.listify_options):
saved_values = listify(getattr(self, key), do_strip=True) # listify and save original value
setattr(self, key, '_') # replace value with temporary placeholder
resolve(key) # resolve temporary value (`_` becomes `parent-path/_`)
resolved_base = getattr(self, key)[:-1] # get rid of placeholder in resolved path
# apply resolved base to saved values
resolved_paths = [os.path.join(resolved_base, value) for value in saved_values]
setattr(self, key, resolved_paths) # set config.key to a list of resolved paths
else:
resolve(key)
# Check options that have been set and may need to be resolved w.r.t. root
if self.is_set(key) and self.paths_to_check_against_root and key in self.paths_to_check_against_root:
self._check_against_root(key)
def _check_against_root(self, key):
def get_path(current_path, initial_path):
# if path does not exist and was set as relative:
if not self._path_exists(current_path) and not os.path.isabs(initial_path):
new_path = self._in_root_dir(initial_path)
if self._path_exists(new_path): # That's a bingo!
resolves_to = self.schema.paths_to_resolve.get(key)
log.warning(
"Paths for the '{0}' option should be relative to '{1}'. To suppress this warning, "
"move '{0}' into '{1}', or set it's value to an absolute path.".format(key, resolves_to)
)
return new_path
return current_path
current_value = getattr(self, key) # resolved path or list of resolved paths
if type(current_value) is list:
initial_paths = listify(self._raw_config[key], do_strip=True) # initial unresolved paths
updated_paths = []
# check and, if needed, update each path in the list
for current_path, initial_path in zip(current_value, initial_paths):
path = get_path(current_path, initial_path)
updated_paths.append(path) # add to new list regardless of whether path has changed or not
setattr(self, key, updated_paths) # update: one or more paths may have changed
else:
initial_path = self._raw_config[key] # initial unresolved path
path = get_path(current_value, initial_path)
if path != current_value:
setattr(self, key, path) # update if path has changed
def _in_root_dir(self, path):
return self._in_dir(self.root, path)
def _in_managed_config_dir(self, path):
return self._in_dir(self.managed_config_dir, path)
def _in_config_dir(self, path):
return self._in_dir(self.config_dir, path)
def _in_sample_dir(self, path):
return self._in_dir(self.sample_config_dir, path)
def _in_data_dir(self, path):
return self._in_dir(self.data_dir, path)
def _in_dir(self, _dir, path):
return os.path.join(_dir, path) if path else None
class CommonConfigurationMixin:
"""Shared configuration settings code for Galaxy and ToolShed."""
@property
def admin_users(self):
return self._admin_users
@admin_users.setter
def admin_users(self, value):
self._admin_users = value
self.admin_users_list = listify(value)
def is_admin_user(self, user):
"""Determine if the provided user is listed in `admin_users`."""
return user and (user.email in self.admin_users_list or user.bootstrap_admin_user)
@property
def sentry_dsn_public(self):
"""
Sentry URL with private key removed for use in client side scripts,
sentry server will need to be configured to accept events
"""
if self.sentry_dsn:
return re.sub(r"^([^:/?#]+:)?//(\w+):(\w+)", r"\1//\2", self.sentry_dsn)
def get_bool(self, key, default):
# Warning: the value of self.config_dict['foo'] may be different from self.foo
if key in self.config_dict:
return string_as_bool(self.config_dict[key])
else:
return default
def get(self, key, default=None):
# Warning: the value of self.config_dict['foo'] may be different from self.foo
return self.config_dict.get(key, default)
def _ensure_directory(self, path):
if path not in [None, False] and not os.path.isdir(path):
try:
os.makedirs(path)
except Exception as e:
raise ConfigurationError(f"Unable to create missing directory: {path}\n{unicodify(e)}")
class GalaxyAppConfiguration(BaseAppConfiguration, CommonConfigurationMixin):
deprecated_options = ('database_file', 'track_jobs_in_database', 'blacklist_file', 'whitelist_file',
'sanitize_whitelist_file', 'user_library_import_symlink_whitelist', 'fetch_url_whitelist',
'containers_resolvers_config_file')
renamed_options = {
'blacklist_file': 'email_domain_blocklist_file',
'whitelist_file': 'email_domain_allowlist_file',
'sanitize_whitelist_file': 'sanitize_allowlist_file',
'user_library_import_symlink_whitelist': 'user_library_import_symlink_allowlist',
'fetch_url_whitelist': 'fetch_url_allowlist',
'containers_resolvers_config_file': 'container_resolvers_config_file',
}
default_config_file_name = 'galaxy.yml'
deprecated_dirs = {'config_dir': 'config', 'data_dir': 'database'}
paths_to_check_against_root = {
'auth_config_file',
'build_sites_config_file',
'containers_config_file',
'data_manager_config_file',
'datatypes_config_file',
'dependency_resolvers_config_file',
'error_report_file',
'job_config_file',
'job_metrics_config_file',
'job_resource_params_file',
'local_conda_mapping_file',
'migrated_tools_config',
'modules_mapping_files',
'object_store_config_file',
'oidc_backends_config_file',
'oidc_config_file',
'shed_data_manager_config_file',
'shed_tool_config_file',
'shed_tool_data_table_config',
'tool_destinations_config_file',
'tool_sheds_config_file',
'user_preferences_extra_conf_path',
'workflow_resource_params_file',
'workflow_schedulers_config_file',
'markdown_export_css',
'markdown_export_css_pages',
'markdown_export_css_invocation_reports',
'file_path',
'tool_data_table_config_path',
'tool_config_file',
}
add_sample_file_to_defaults = {
'build_sites_config_file',
'datatypes_config_file',
'job_metrics_config_file',
'tool_data_table_config_path',
'tool_config_file',
}
listify_options = {
'tool_data_table_config_path',
'tool_config_file',
}
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._override_tempdir(kwargs)
self._process_config(kwargs)
def _load_schema(self):
# Schemas are symlinked to the root of the galaxy-app package
config_schema_path = os.path.join(os.path.dirname(__file__), os.pardir, 'config_schema.yml')
if os.path.exists(GALAXY_CONFIG_SCHEMA_PATH):
config_schema_path = GALAXY_CONFIG_SCHEMA_PATH
return AppSchema(config_schema_path, GALAXY_APP_NAME)
def _override_tempdir(self, kwargs):
if string_as_bool(kwargs.get("override_tempdir", "True")):
tempfile.tempdir = self.new_file_path
def config_value_for_host(self, config_option, host):
val = getattr(self, config_option)
if config_option in self.schema.per_host_options:
per_host_option = f"{config_option}_by_host"
if per_host_option in self.config_dict:
per_host = self.config_dict[per_host_option] or {}
for host_key, host_val in per_host.items():
if host_key in host:
val = host_val
break
return val
def _process_config(self, kwargs):
# Backwards compatibility for names used in too many places to fix
self.datatypes_config = self.datatypes_config_file
self.tool_configs = self.tool_config_file
# Collect the umask and primary gid from the environment
self.umask = os.umask(0o77) # get the current umask
os.umask(self.umask) # can't get w/o set, so set it back
self.gid = os.getgid() # if running under newgrp(1) we'll need to fix the group of data created on the cluster
self.version_major = VERSION_MAJOR
self.version_minor = VERSION_MINOR
# Database related configuration
self.check_migrate_databases = kwargs.get('check_migrate_databases', True)
if not self.database_connection: # Provide default if not supplied by user
db_path = self._in_data_dir('universe.sqlite')
self.database_connection = f'sqlite:///{db_path}?isolation_level=IMMEDIATE'
self.database_engine_options = get_database_engine_options(kwargs)
self.database_create_tables = string_as_bool(kwargs.get('database_create_tables', 'True'))
self.database_encoding = kwargs.get('database_encoding') # Create new databases with this encoding
self.thread_local_log = None
if self.enable_per_request_sql_debugging:
self.thread_local_log = threading.local()
# Install database related configuration (if different)
self.install_database_engine_options = get_database_engine_options(kwargs, model_prefix="install_")
self.shared_home_dir = kwargs.get("shared_home_dir")
self.cookie_path = kwargs.get("cookie_path")
self.tool_path = self._in_root_dir(self.tool_path)
self.tool_data_path = self._in_root_dir(self.tool_data_path)
if not running_from_source and kwargs.get("tool_data_path") is None:
self.tool_data_path = self._in_data_dir(self.schema.defaults['tool_data_path'])
self.builds_file_path = os.path.join(self.tool_data_path, self.builds_file_path)
self.len_file_path = os.path.join(self.tool_data_path, self.len_file_path)
self.oidc = {}
self.integrated_tool_panel_config = self._in_managed_config_dir(self.integrated_tool_panel_config)
integrated_tool_panel_tracking_directory = kwargs.get('integrated_tool_panel_tracking_directory')
if integrated_tool_panel_tracking_directory:
self.integrated_tool_panel_tracking_directory = self._in_root_dir(integrated_tool_panel_tracking_directory)
else:
self.integrated_tool_panel_tracking_directory = None
self.toolbox_filter_base_modules = listify(self.toolbox_filter_base_modules)
self.tool_filters = listify(self.tool_filters, do_strip=True)
self.tool_label_filters = listify(self.tool_label_filters, do_strip=True)
self.tool_section_filters = listify(self.tool_section_filters, do_strip=True)
self.user_tool_filters = listify(self.user_tool_filters, do_strip=True)
self.user_tool_label_filters = listify(self.user_tool_label_filters, do_strip=True)
self.user_tool_section_filters = listify(self.user_tool_section_filters, do_strip=True)
self.has_user_tool_filters = bool(self.user_tool_filters or self.user_tool_label_filters or self.user_tool_section_filters)
self.password_expiration_period = timedelta(days=int(self.password_expiration_period))
if self.shed_tool_data_path:
self.shed_tool_data_path = self._in_root_dir(self.shed_tool_data_path)
else:
self.shed_tool_data_path = self.tool_data_path
self.running_functional_tests = string_as_bool(kwargs.get('running_functional_tests', False))
if isinstance(self.hours_between_check, str):
self.hours_between_check = float(self.hours_between_check)
try:
if isinstance(self.hours_between_check, int):
if self.hours_between_check < 1 or self.hours_between_check > 24:
self.hours_between_check = 12
elif isinstance(self.hours_between_check, float):
# If we're running functional tests, the minimum hours between check should be reduced to 0.001, or 3.6 seconds.
if self.running_functional_tests:
if self.hours_between_check < 0.001 or self.hours_between_check > 24.0:
self.hours_between_check = 12.0
else:
if self.hours_between_check < 1.0 or self.hours_between_check > 24.0:
self.hours_between_check = 12.0
else:
self.hours_between_check = 12
except Exception:
self.hours_between_check = 12
self.update_integrated_tool_panel = kwargs.get("update_integrated_tool_panel", True)
self.galaxy_data_manager_data_path = self.galaxy_data_manager_data_path or self.tool_data_path
self.tool_secret = kwargs.get("tool_secret", "")
self.metadata_strategy = kwargs.get("metadata_strategy", "directory")
self.use_remote_user = self.use_remote_user or self.single_user
self.fetch_url_allowlist_ips = [
ipaddress.ip_network(unicodify(ip.strip())) # If it has a slash, assume 127.0.0.1/24 notation
if '/' in ip else
ipaddress.ip_address(unicodify(ip.strip())) # Otherwise interpret it as an ip address.
for ip in kwargs.get("fetch_url_allowlist", "").split(',')
if len(ip.strip()) > 0
]
self.template_path = self._in_root_dir(kwargs.get("template_path", "templates"))
self.job_queue_cleanup_interval = int(kwargs.get("job_queue_cleanup_interval", "5"))
self.cluster_files_directory = self._in_root_dir(self.cluster_files_directory)
# Fall back to legacy job_working_directory config variable if set.
self.jobs_directory = self._in_data_dir(kwargs.get("jobs_directory", self.job_working_directory))
if self.preserve_python_environment not in ["legacy_only", "legacy_and_local", "always"]:
log.warning("preserve_python_environment set to unknown value [%s], defaulting to legacy_only")
self.preserve_python_environment = "legacy_only"
self.nodejs_path = kwargs.get("nodejs_path")
self.container_image_cache_path = self._in_data_dir(kwargs.get("container_image_cache_path", "container_cache"))
self.output_size_limit = int(kwargs.get('output_size_limit', 0))
# activation_email was used until release_15.03
activation_email = kwargs.get('activation_email')
self.email_from = self.email_from or activation_email
self.email_domain_blocklist_content = self._load_list_from_file(self._in_config_dir(self.email_domain_blocklist_file)) if self.email_domain_blocklist_file else None
self.email_domain_allowlist_content = self._load_list_from_file(self._in_config_dir(self.email_domain_allowlist_file)) if self.email_domain_allowlist_file else None
# These are not even beta - just experiments - don't use them unless
# you want yours tools to be broken in the future.
self.enable_beta_tool_formats = string_as_bool(kwargs.get('enable_beta_tool_formats', 'False'))
if self.workflow_resource_params_mapper and ':' not in self.workflow_resource_params_mapper:
# Assume it is not a Python function, so a file; else: a Python function
self.workflow_resource_params_mapper = self._in_root_dir(self.workflow_resource_params_mapper)
self.pbs_application_server = kwargs.get('pbs_application_server', "")
self.pbs_dataset_server = kwargs.get('pbs_dataset_server', "")
self.pbs_dataset_path = kwargs.get('pbs_dataset_path', "")
self.pbs_stage_path = kwargs.get('pbs_stage_path', "")
_sanitize_allowlist_path = self._in_managed_config_dir(self.sanitize_allowlist_file)
if not os.path.isfile(_sanitize_allowlist_path): # then check old default location
for deprecated in (
self._in_managed_config_dir('sanitize_whitelist.txt'),
self._in_root_dir('config/sanitize_whitelist.txt')):
if os.path.isfile(deprecated):
log.warning("The path '%s' for the 'sanitize_allowlist_file' config option is "
"deprecated and will be no longer checked in a future release. Please consult "
"the latest version of the sample configuration file." % deprecated)
_sanitize_allowlist_path = deprecated
break
self.sanitize_allowlist_file = _sanitize_allowlist_path
self.allowed_origin_hostnames = self._parse_allowed_origin_hostnames(self.allowed_origin_hostnames)
if "trust_jupyter_notebook_conversion" not in kwargs:
# if option not set, check IPython-named alternative, falling back to schema default if not set either
_default = self.trust_jupyter_notebook_conversion
self.trust_jupyter_notebook_conversion = string_as_bool(kwargs.get('trust_ipython_notebook_conversion', _default))
# Configuration for the message box directly below the masthead.
self.blog_url = kwargs.get('blog_url')
self.user_library_import_symlink_allowlist = listify(self.user_library_import_symlink_allowlist, do_strip=True)
self.user_library_import_dir_auto_creation = self.user_library_import_dir_auto_creation if self.user_library_import_dir else False
# Searching data libraries
self.ftp_upload_dir_template = kwargs.get('ftp_upload_dir_template', '${ftp_upload_dir}%s${ftp_upload_dir_identifier}' % os.path.sep)
# Support older library-specific path paste option but just default to the new
# allow_path_paste value.
self.allow_library_path_paste = string_as_bool(kwargs.get('allow_library_path_paste', self.allow_path_paste))
self.disable_library_comptypes = kwargs.get('disable_library_comptypes', '').lower().split(',')
self.check_upload_content = string_as_bool(kwargs.get('check_upload_content', True))
# On can mildly speed up Galaxy startup time by disabling index of help,
# not needed on production systems but useful if running many functional tests.
self.index_tool_help = string_as_bool(kwargs.get("index_tool_help", True))
self.tool_labels_boost = kwargs.get("tool_labels_boost", 1)
default_tool_test_data_directories = os.environ.get("GALAXY_TEST_FILE_DIR", self._in_root_dir("test-data"))
self.tool_test_data_directories = kwargs.get("tool_test_data_directories", default_tool_test_data_directories)
# Deployers may either specify a complete list of mapping files or get the default for free and just
# specify a local mapping file to adapt and extend the default one.
if "conda_mapping_files" not in kwargs:
_default_mapping = self._in_root_dir(os.path.join("lib", "galaxy", "tool_util", "deps", "resolvers", "default_conda_mapping.yml"))
# dependency resolution options are consumed via config_dict - so don't populate
# self, populate config_dict
self.config_dict["conda_mapping_files"] = [self.local_conda_mapping_file, _default_mapping]
if self.container_resolvers_config_file:
self.container_resolvers_config_file = self._in_config_dir(self.container_resolvers_config_file)
# tool_dependency_dir can be "none" (in old configs). If so, set it to None
if self.tool_dependency_dir and self.tool_dependency_dir.lower() == 'none':
self.tool_dependency_dir = None
if self.involucro_path is None:
target_dir = self.tool_dependency_dir or self.schema.defaults['tool_dependency_dir']
self.involucro_path = self._in_data_dir(os.path.join(target_dir, "involucro"))
self.involucro_path = self._in_root_dir(self.involucro_path)
if self.mulled_channels:
self.mulled_channels = [c.strip() for c in self.mulled_channels.split(',')]
default_job_resubmission_condition = kwargs.get('default_job_resubmission_condition', '')
if not default_job_resubmission_condition.strip():
default_job_resubmission_condition = None
self.default_job_resubmission_condition = default_job_resubmission_condition
# Configuration options for taking advantage of nginx features
if self.nginx_upload_store:
self.nginx_upload_store = os.path.abspath(self.nginx_upload_store)
self.object_store = kwargs.get('object_store', 'disk')
self.object_store_check_old_style = string_as_bool(kwargs.get('object_store_check_old_style', False))
self.object_store_cache_path = self._in_root_dir(kwargs.get("object_store_cache_path", self._in_data_dir("object_store_cache")))
self._configure_dataset_storage()
# Handle AWS-specific config options for backward compatibility
if kwargs.get('aws_access_key') is not None:
self.os_access_key = kwargs.get('aws_access_key')
self.os_secret_key = kwargs.get('aws_secret_key')
self.os_bucket_name = kwargs.get('s3_bucket')
self.os_use_reduced_redundancy = kwargs.get('use_reduced_redundancy', False)
else:
self.os_access_key = kwargs.get('os_access_key')
self.os_secret_key = kwargs.get('os_secret_key')
self.os_bucket_name = kwargs.get('os_bucket_name')
self.os_use_reduced_redundancy = kwargs.get('os_use_reduced_redundancy', False)
self.os_host = kwargs.get('os_host')
self.os_port = kwargs.get('os_port')
self.os_is_secure = string_as_bool(kwargs.get('os_is_secure', True))
self.os_conn_path = kwargs.get('os_conn_path', '/')
self.object_store_cache_size = float(kwargs.get('object_store_cache_size', -1))
self.distributed_object_store_config_file = kwargs.get('distributed_object_store_config_file')
if self.distributed_object_store_config_file is not None:
self.distributed_object_store_config_file = self._in_root_dir(self.distributed_object_store_config_file)
self.irods_root_collection_path = kwargs.get('irods_root_collection_path')
self.irods_default_resource = kwargs.get('irods_default_resource')
# Heartbeat log file name override
if self.global_conf is not None and 'heartbeat_log' in self.global_conf:
self.heartbeat_log = self.global_conf['heartbeat_log']
# Determine which 'server:' this is
self.server_name = 'main'
for arg in sys.argv:
# Crummy, but PasteScript does not give you a way to determine this
if arg.lower().startswith('--server-name='):
self.server_name = arg.split('=', 1)[-1]
# Allow explicit override of server name in config params
if "server_name" in kwargs:
self.server_name = kwargs.get("server_name")
# The application stack code may manipulate the server name. It also needs to be accessible via the get() method
# for galaxy.util.facts()
self.config_dict['base_server_name'] = self.base_server_name = self.server_name
# Store all configured server names for the message queue routing
self.server_names = []
for section in self.global_conf_parser.sections():
if section.startswith('server:'):
self.server_names.append(section.replace('server:', '', 1))
self._set_galaxy_infrastructure_url(kwargs)
# Asynchronous execution process pools - limited functionality for now, attach_to_pools is designed to allow
# webless Galaxy server processes to attach to arbitrary message queues (e.g. as job handlers) so they do not
# have to be explicitly defined as such in the job configuration.
self.attach_to_pools = kwargs.get('attach_to_pools', []) or []
# Store advanced job management config
self.job_handlers = [x.strip() for x in kwargs.get('job_handlers', self.server_name).split(',')]
self.default_job_handlers = [x.strip() for x in kwargs.get('default_job_handlers', ','.join(self.job_handlers)).split(',')]
# Galaxy internal control queue configuration.
# If specified in universe, use it, otherwise we use whatever 'real'
# database is specified. Lastly, we create and use new sqlite database
# (to minimize locking) as a final option.
if 'amqp_internal_connection' in kwargs:
self.amqp_internal_connection = kwargs.get('amqp_internal_connection')
# TODO Get extra amqp args as necessary for ssl
elif 'database_connection' in kwargs:
self.amqp_internal_connection = f"sqlalchemy+{self.database_connection}"
else:
self.amqp_internal_connection = f"sqlalchemy+sqlite:///{self._in_data_dir('control.sqlite')}?isolation_level=IMMEDIATE"
self.pretty_datetime_format = expand_pretty_datetime_format(self.pretty_datetime_format)
try:
with open(self.user_preferences_extra_conf_path) as stream:
self.user_preferences_extra = yaml.safe_load(stream)
except Exception:
if self.is_set('user_preferences_extra_conf_path'):
log.warning(f'Config file ({self.user_preferences_extra_conf_path}) could not be found or is malformed.')
self.user_preferences_extra = {'preferences': {}}
# Experimental: This will not be enabled by default and will hide
# nonproduction code.
# The api_folders refers to whether the API exposes the /folders section.
self.api_folders = string_as_bool(kwargs.get('api_folders', False))
# This is for testing new library browsing capabilities.
self.new_lib_browse = string_as_bool(kwargs.get('new_lib_browse', False))
# Logging configuration with logging.config.configDict:
# Statistics and profiling with statsd
self.statsd_host = kwargs.get('statsd_host', '')
ie_dirs = self.interactive_environment_plugins_directory
self.gie_dirs = [d.strip() for d in (ie_dirs.split(",") if ie_dirs else [])]
if ie_dirs:
self.visualization_plugins_directory += f",{ie_dirs}"
self.proxy_session_map = self.dynamic_proxy_session_map
self.manage_dynamic_proxy = self.dynamic_proxy_manage # Set to false if being launched externally
# InteractiveTools propagator mapping file
self.interactivetools_map = self._in_root_dir(kwargs.get("interactivetools_map", self._in_data_dir("interactivetools_map.sqlite")))
self.containers_conf = parse_containers_config(self.containers_config_file)
# Compliance/Policy variables
self.redact_username_during_deletion = False
self.redact_email_during_deletion = False
self.redact_ip_address = False
self.redact_username_in_logs = False
self.redact_email_in_job_name = False
self.redact_user_details_in_bugreport = False
self.redact_user_address_during_deletion = False
# GDPR compliance mode changes values on a number of variables. Other
# policies could change (non)overlapping subsets of these variables.
if self.enable_beta_gdpr:
self.expose_user_name = False
self.expose_user_email = False
self.redact_username_during_deletion = True
self.redact_email_during_deletion = True
self.redact_ip_address = True
self.redact_username_in_logs = True
self.redact_email_in_job_name = True
self.redact_user_details_in_bugreport = True
self.redact_user_address_during_deletion = True
self.allow_user_deletion = True
LOGGING_CONFIG_DEFAULT['formatters']['brief'] = {
'format': '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
}
LOGGING_CONFIG_DEFAULT['handlers']['compliance_log'] = {
'class': 'logging.handlers.RotatingFileHandler',
'formatter': 'brief',
'filename': 'compliance.log',
'backupCount': 0,
}
LOGGING_CONFIG_DEFAULT['loggers']['COMPLIANCE'] = {
'handlers': ['compliance_log'],
'level': 'DEBUG',
'qualname': 'COMPLIANCE'
}
log_destination = kwargs.get("log_destination")
galaxy_daemon_log_destination = os.environ.get('GALAXY_DAEMON_LOG')
if log_destination == "stdout":
LOGGING_CONFIG_DEFAULT['handlers']['console'] = {
'class': 'logging.StreamHandler',
'formatter': 'stack',
'level': 'DEBUG',
'stream': 'ext://sys.stdout',
'filters': ['stack']
}
elif log_destination:
LOGGING_CONFIG_DEFAULT['handlers']['console'] = {
'class': 'logging.FileHandler',
'formatter': 'stack',
'level': 'DEBUG',
'filename': log_destination,
'filters': ['stack']
}
if galaxy_daemon_log_destination:
LOGGING_CONFIG_DEFAULT['handlers']['files'] = {
'class': 'logging.FileHandler',
'formatter': 'stack',
'level': 'DEBUG',
'filename': galaxy_daemon_log_destination,
'filters': ['stack']
}
LOGGING_CONFIG_DEFAULT['root']['handlers'].append('files')
def _configure_dataset_storage(self):
# The default for `file_path` has changed in 20.05; we may need to fall back to the old default
self._set_alt_paths('file_path', self._in_data_dir('files')) # this is called BEFORE guessing id/uuid
ID, UUID = 'id', 'uuid'
if self.is_set('object_store_store_by'):
assert self.object_store_store_by in [ID, UUID], f"Invalid value for object_store_store_by [{self.object_store_store_by}]"
elif os.path.basename(self.file_path) == 'objects':
self.object_store_store_by = UUID
else:
self.object_store_store_by = ID
def _load_list_from_file(self, filepath):
with open(filepath) as f:
return [line.strip() for line in f]
def _set_galaxy_infrastructure_url(self, kwargs):
# indicate if this was not set explicitly, so dependending on the context a better default
# can be used (request url in a web thread, Docker parent in IE stuff, etc.)
self.galaxy_infrastructure_url_set = kwargs.get('galaxy_infrastructure_url') is not None
if "HOST_IP" in self.galaxy_infrastructure_url:
self.galaxy_infrastructure_url = string.Template(self.galaxy_infrastructure_url).safe_substitute({
'HOST_IP': socket.gethostbyname(socket.gethostname())
})
if "GALAXY_WEB_PORT" in self.galaxy_infrastructure_url:
port = os.environ.get('GALAXY_WEB_PORT')
if not port:
raise Exception('$GALAXY_WEB_PORT set in galaxy_infrastructure_url, but environment variable not set')
self.galaxy_infrastructure_url = string.Template(self.galaxy_infrastructure_url).safe_substitute({
'GALAXY_WEB_PORT': port
})
if "UWSGI_PORT" in self.galaxy_infrastructure_url:
import uwsgi
http = unicodify(uwsgi.opt['http'])
host, port = http.split(":", 1)
assert port, "galaxy_infrastructure_url depends on dynamic PORT determination but port unknown"
self.galaxy_infrastructure_url = string.Template(self.galaxy_infrastructure_url).safe_substitute({
'UWSGI_PORT': port
})
def reload_sanitize_allowlist(self, explicit=True):
self.sanitize_allowlist = []
try:
with open(self.sanitize_allowlist_file) as f:
for line in f.readlines():
if not line.startswith("#"):
self.sanitize_allowlist.append(line.strip())
except OSError:
if explicit:
log.warning("Sanitize log file explicitly specified as '%s' but does not exist, continuing with no tools allowlisted.", self.sanitize_allowlist_file)
def ensure_tempdir(self):
self._ensure_directory(self.new_file_path)
def check(self):
# Check that required directories exist; attempt to create otherwise
paths_to_check = [
self.data_dir,
self.ftp_upload_dir,
self.library_import_dir,
self.managed_config_dir,
self.new_file_path,
self.nginx_upload_store,
self.object_store_cache_path,
self.template_cache_path,
self.tool_data_path,
self.user_library_import_dir,
]
for path in paths_to_check:
self._ensure_directory(path)
# Check that required files exist
tool_configs = self.tool_configs
for path in tool_configs:
if not os.path.exists(path) and path not in (self.shed_tool_config_file, self.migrated_tools_config):
raise ConfigurationError(f"Tool config file not found: {path}")
for datatypes_config in listify(self.datatypes_config):
if not os.path.isfile(datatypes_config):
raise ConfigurationError(f"Datatypes config file not found: {datatypes_config}")
# Check for deprecated options.
for key in self.config_dict.keys():
if key in self.deprecated_options:
log.warning(f"Config option '{key}' is deprecated and will be removed in a future release. Please consult the latest version of the sample configuration file.")
@staticmethod
def _parse_allowed_origin_hostnames(allowed_origin_hostnames):
"""
Parse a CSV list of strings/regexp of hostnames that should be allowed
to use CORS and will be sent the Access-Control-Allow-Origin header.
"""
allowed_origin_hostnames_list = listify(allowed_origin_hostnames)
if not allowed_origin_hostnames_list:
return None
def parse(string):
# a string enclosed in fwd slashes will be parsed as a regexp: e.g. /<some val>/
if string[0] == '/' and string[-1] == '/':
string = string[1:-1]
return re.compile(string, flags=(re.UNICODE))
return string
return [parse(v) for v in allowed_origin_hostnames_list if v]
# legacy naming
Configuration = GalaxyAppConfiguration
def reload_config_options(current_config):
"""Reload modified reloadable config options."""
modified_config = read_properties_from_file(current_config.config_file)
for option in current_config.schema.reloadable_options:
if option in modified_config:
# compare to raw value, as that one is set only on load and reload
if current_config._raw_config[option] != modified_config[option]:
current_config._raw_config[option] = modified_config[option]
setattr(current_config, option, modified_config[option])
log.info(f'Reloaded {option}')
def get_database_engine_options(kwargs, model_prefix=''):
"""
Allow options for the SQLAlchemy database engine to be passed by using
the prefix "database_engine_option".
"""
conversions = {
'convert_unicode': string_as_bool,
'pool_timeout': int,
'echo': string_as_bool,
'echo_pool': string_as_bool,
'pool_recycle': int,
'pool_size': int,
'max_overflow': int,
'pool_threadlocal': string_as_bool,
'server_side_cursors': string_as_bool
}
prefix = f"{model_prefix}database_engine_option_"
prefix_len = len(prefix)
rval = {}
for key, value in kwargs.items():
if key.startswith(prefix):
key = key[prefix_len:]
if key in conversions:
value = conversions[key](value)
rval[key] = value
return rval
def get_database_url(config):
db_url = config.database_connection
return db_url
def init_models_from_config(config, map_install_models=False, object_store=None, trace_logger=None):
db_url = get_database_url(config)
model = mapping.init(
config.file_path,
db_url,
config.database_engine_options,
map_install_models=map_install_models,
database_query_profiling_proxy=config.database_query_profiling_proxy,
object_store=object_store,
trace_logger=trace_logger,
use_pbkdf2=config.get_bool('use_pbkdf2', True),
slow_query_log_threshold=config.slow_query_log_threshold,
thread_local_log=config.thread_local_log,
log_query_counts=config.database_log_query_counts,
)
return model
def configure_logging(config):
"""Allow some basic logging configuration to be read from ini file.
This should be able to consume either a galaxy.config.Configuration object
or a simple dictionary of configuration variables.
"""
# Get root logger
logging.addLevelName(LOGLV_TRACE, "TRACE")
root = logging.getLogger()
# PasteScript will have already configured the logger if the
# 'loggers' section was found in the config file, otherwise we do
# some simple setup using the 'log_*' values from the config.
parser = getattr(config, "global_conf_parser", None)
if parser:
paste_configures_logging = config.global_conf_parser.has_section("loggers")
else:
paste_configures_logging = False
auto_configure_logging = not paste_configures_logging and string_as_bool(config.get("auto_configure_logging", "True"))
if auto_configure_logging:
logging_conf = config.get('logging', None)
if logging_conf is None:
# if using the default logging config, honor the log_level setting
logging_conf = LOGGING_CONFIG_DEFAULT
if config.get('log_level', 'DEBUG') != 'DEBUG':
logging_conf['handlers']['console']['level'] = config.get('log_level', 'DEBUG')
# configure logging with logging dict in config, template *FileHandler handler filenames with the `filename_template` option
for name, conf in logging_conf.get('handlers', {}).items():
if conf['class'].startswith('logging.') and conf['class'].endswith('FileHandler') and 'filename_template' in conf:
conf['filename'] = conf.pop('filename_template').format(**get_stack_facts(config=config))
logging_conf['handlers'][name] = conf
logging.config.dictConfig(logging_conf)
if getattr(config, "sentry_dsn", None):
from raven.handlers.logging import SentryHandler
sentry_handler = SentryHandler(config.sentry_dsn)
sentry_handler.setLevel(logging.WARN)
register_postfork_function(root.addHandler, sentry_handler)
class ConfiguresGalaxyMixin:
"""Shared code for configuring Galaxy-like app objects."""
def _configure_genome_builds(self, data_table_name="__dbkeys__", load_old_style=True):
self.genome_builds = GenomeBuilds(self, data_table_name=data_table_name, load_old_style=load_old_style)
def wait_for_toolbox_reload(self, old_toolbox):
timer = ExecutionTimer()
log.debug('Waiting for toolbox reload')
# Wait till toolbox reload has been triggered (or more than 60 seconds have passed)
while timer.elapsed < 60:
if self.toolbox.has_reloaded(old_toolbox):
log.debug('Finished waiting for toolbox reload %s', timer)
break
time.sleep(0.1)
else:
log.warning('Waiting for toolbox reload timed out after 60 seconds')
def _configure_tool_config_files(self):
if self.config.shed_tool_config_file not in self.config.tool_configs:
self.config.tool_configs.append(self.config.shed_tool_config_file)
# The value of migrated_tools_config is the file reserved for containing only those tools that have been
# eliminated from the distribution and moved to the tool shed. If migration checking is disabled, only add it if
# it exists (since this may be an existing deployment where migrations were previously run).
if ((self.config.check_migrate_tools or os.path.exists(self.config.migrated_tools_config))
and self.config.migrated_tools_config not in self.config.tool_configs):
self.config.tool_configs.append(self.config.migrated_tools_config)
def _configure_toolbox(self):
from galaxy import tools
from galaxy.managers.citations import CitationsManager
from galaxy.tool_util.deps import containers
from galaxy.tool_util.deps.dependencies import AppInfo
import galaxy.tools.search
self.citations_manager = CitationsManager(self)
from galaxy.managers.tools import DynamicToolManager
self.dynamic_tools_manager = DynamicToolManager(self)
self._toolbox_lock = threading.RLock()
self.toolbox = tools.ToolBox(self.config.tool_configs, self.config.tool_path, self)
galaxy_root_dir = os.path.abspath(self.config.root)
file_path = os.path.abspath(self.config.file_path)
app_info = AppInfo(
galaxy_root_dir=galaxy_root_dir,
default_file_path=file_path,
tool_data_path=self.config.tool_data_path,
shed_tool_data_path=self.config.shed_tool_data_path,
outputs_to_working_directory=self.config.outputs_to_working_directory,
container_image_cache_path=self.config.container_image_cache_path,
library_import_dir=self.config.library_import_dir,
enable_mulled_containers=self.config.enable_mulled_containers,
container_resolvers_config_file=self.config.container_resolvers_config_file,
container_resolvers_config_dict=self.config.container_resolvers,
involucro_path=self.config.involucro_path,
involucro_auto_init=self.config.involucro_auto_init,
mulled_channels=self.config.mulled_channels,
)
mulled_resolution_cache = None
if self.config.mulled_resolution_cache_type:
cache_opts = {
'cache.type': self.config.mulled_resolution_cache_type,
'cache.data_dir': self.config.mulled_resolution_cache_data_dir,
'cache.lock_dir': self.config.mulled_resolution_cache_lock_dir,
}
mulled_resolution_cache = CacheManager(**parse_cache_config_options(cache_opts)).get_cache('mulled_resolution')
self.container_finder = containers.ContainerFinder(app_info, mulled_resolution_cache=mulled_resolution_cache)
self._set_enabled_container_types()
index_help = getattr(self.config, "index_tool_help", True)
self.toolbox_search = galaxy.tools.search.ToolBoxSearch(self.toolbox, index_dir=self.config.tool_search_index_dir, index_help=index_help)
def reindex_tool_search(self):
# Call this when tools are added or removed.
self.toolbox_search.build_index(tool_cache=self.tool_cache)
self.tool_cache.reset_status()
def _set_enabled_container_types(self):
container_types_to_destinations = collections.defaultdict(list)
for destinations in self.job_config.destinations.values():
for destination in destinations:
for enabled_container_type in self.container_finder._enabled_container_types(destination.params):
container_types_to_destinations[enabled_container_type].append(destination)
self.toolbox.dependency_manager.set_enabled_container_types(container_types_to_destinations)
self.toolbox.dependency_manager.resolver_classes.update(self.container_finder.default_container_registry.resolver_classes)
self.toolbox.dependency_manager.dependency_resolvers.extend(self.container_finder.default_container_registry.container_resolvers)
def _configure_tool_data_tables(self, from_shed_config):
from galaxy.tools.data import ToolDataTableManager
# Initialize tool data tables using the config defined by self.config.tool_data_table_config_path.
self.tool_data_tables = ToolDataTableManager(tool_data_path=self.config.tool_data_path,
config_filename=self.config.tool_data_table_config_path,
other_config_dict=self.config)
# Load additional entries defined by self.config.shed_tool_data_table_config into tool data tables.
try:
self.tool_data_tables.load_from_config_file(config_filename=self.config.shed_tool_data_table_config,
tool_data_path=self.tool_data_tables.tool_data_path,
from_shed_config=from_shed_config)
except OSError as exc:
# Missing shed_tool_data_table_config is okay if it's the default
if exc.errno != errno.ENOENT or self.config.is_set('shed_tool_data_table_config'):
raise
def _configure_datatypes_registry(self, installed_repository_manager=None):
from galaxy.datatypes import registry
# Create an empty datatypes registry.
self.datatypes_registry = registry.Registry(self.config)
if installed_repository_manager:
# Load proprietary datatypes defined in datatypes_conf.xml files in all installed tool shed repositories. We
# load proprietary datatypes before datatypes in the distribution because Galaxy's default sniffers include some
# generic sniffers (eg text,xml) which catch anything, so it's impossible for proprietary sniffers to be used.
# However, if there is a conflict (2 datatypes with the same extension) between a proprietary datatype and a datatype
# in the Galaxy distribution, the datatype in the Galaxy distribution will take precedence. If there is a conflict
# between 2 proprietary datatypes, the datatype from the repository that was installed earliest will take precedence.
installed_repository_manager.load_proprietary_datatypes()
# Load the data types in the Galaxy distribution, which are defined in self.config.datatypes_config.
datatypes_configs = self.config.datatypes_config
for datatypes_config in listify(datatypes_configs):
# Setting override=False would make earlier files would take
# precedence - but then they wouldn't override tool shed
# datatypes.
self.datatypes_registry.load_datatypes(self.config.root, datatypes_config, override=True)
def _configure_object_store(self, **kwds):
from galaxy.objectstore import build_object_store_from_config
self.object_store = build_object_store_from_config(self.config, **kwds)
def _configure_security(self):
from galaxy.security import idencoding
self.security = idencoding.IdEncodingHelper(id_secret=self.config.id_secret)
def _configure_tool_shed_registry(self):
import galaxy.tool_shed.tool_shed_registry
# Set up the tool sheds registry
if os.path.isfile(self.config.tool_sheds_config_file):
self.tool_shed_registry = galaxy.tool_shed.tool_shed_registry.Registry(self.config.tool_sheds_config_file)
else:
self.tool_shed_registry = galaxy.tool_shed.tool_shed_registry.Registry()
def _configure_models(self, check_migrate_databases=False, check_migrate_tools=False, config_file=None):
"""Preconditions: object_store must be set on self."""
db_url = get_database_url(self.config)
install_db_url = self.config.install_database_connection
# TODO: Consider more aggressive check here that this is not the same
# database file under the hood.
combined_install_database = not(install_db_url and install_db_url != db_url)
install_db_url = install_db_url or db_url
install_database_options = self.config.database_engine_options if combined_install_database else self.config.install_database_engine_options
if self.config.database_wait:
self._wait_for_database(db_url)
if getattr(self.config, "max_metadata_value_size", None):
from galaxy.model import custom_types
custom_types.MAX_METADATA_VALUE_SIZE = self.config.max_metadata_value_size
if check_migrate_databases:
# Initialize database / check for appropriate schema version. # If this
# is a new installation, we'll restrict the tool migration messaging.
from galaxy.model.migrate.check import create_or_verify_database
create_or_verify_database(db_url, config_file, self.config.database_engine_options, app=self, map_install_models=combined_install_database)
if not combined_install_database:
tsi_create_or_verify_database(install_db_url, install_database_options, app=self)
if check_migrate_tools:
# Alert the Galaxy admin to tools that have been moved from the distribution to the tool shed.
from galaxy.tool_shed.galaxy_install.migrate.check import verify_tools
verify_tools(self, install_db_url, config_file, install_database_options)
self.model = init_models_from_config(
self.config,
map_install_models=combined_install_database,
object_store=self.object_store,
trace_logger=getattr(self, "trace_logger", None)
)
if combined_install_database:
log.info("Install database targetting Galaxy's database configuration.")
self.install_model = self.model
else:
from galaxy.model.tool_shed_install import mapping as install_mapping
install_db_url = self.config.install_database_connection
log.info(f"Install database using its own connection {install_db_url}")
self.install_model = install_mapping.init(install_db_url,
install_database_options)
def _configure_signal_handlers(self, handlers):
for sig, handler in handlers.items():
signal.signal(sig, handler)
def _wait_for_database(self, url):
attempts = self.config.database_wait_attempts
pause = self.config.database_wait_sleep
for i in range(1, attempts):
try:
database_exists(url)
break
except Exception:
log.info("Waiting for database: attempt %d of %d" % (i, attempts))
time.sleep(pause)
@property
def tool_dependency_dir(self):
return self.toolbox.dependency_manager.default_base_path
|
import os
import pandas as pd
from babel.numbers import format_currency, format_decimal
from notify.exceptions import EnvironmentVariablesError
def format_numbers(df: pd.DataFrame, currency_columns: list = None, number_columns: list = None):
"""
Deze functie converteerd currency (bedrag) en number (getal) kolommen naar geformatteerde tekstvelden.
Parameters
----------
df: pd.DataFrame
dataset waarin kolommen staan die geconverteerd dienen te worden
currency_columns: list
lijst met kolomnamen die geconverteerd worden naar € kolommen en formats.
number_columns: list
lijst met kolomnamen die geconverteerd worden naar nummer kolommen met nederlandse annotatie.
Returns
-------
df: pd.DataFrame
dataset met kolommen die gebruikt kunnen worden voor het presenteren van
bedragen en nummers (locale=NL).
"""
# format de bedrag kolommen
if number_columns is None:
number_columns = []
if currency_columns is None:
currency_columns = []
for col in currency_columns:
df[col] = df[col].apply(lambda x: format_currency(number=x, currency="EUR", locale="nl_NL"))
# format de nummer kolommen
for col in number_columns:
df[col] = df[col].apply(lambda x: format_decimal(number=x, locale="nl_NL"))
return df
def check_environment_variables(required_variables: list):
"""
Test if environment variables are set.
Parameters
----------
required_variables: list
list of required variables that need to be present in environment variables.
Returns
-------
None
"""
values = [os.environ.get(x) for x in required_variables]
if not all(values):
raise EnvironmentVariablesError(f"One of the environment variables {", ".join(required_variables)} is not set")
def dataframe_to_html(df: pd.DataFrame) -> str:
"""
Deze functie zet een dataframe om in een opgemaakte HTML table. Wanneer de gebruiker zelfstandig een HTML bericht
opbouwt, kan deze functie uitkomst bieden voor het invoegen van html tabellen.
Parameters
----------
df: pd.DataFrame
dataframe die in een HTML table geconverteerd dient te worden.
Returns
-------
pretty_html_table: str
html body voor de gegeneerde HTML tabel
"""
html_table = df.to_html(index=False, classes="styled-table", justify="center")
pretty_html_table = (
"""
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Dataframe report</title>
<style type="text/css" media="screen">
h1 {
background-color: #a8a8a8;
display: flex;
flex-direction: column;
justify-content: center;
text-align: center;
}
.styled-table {
border-collapse: collapse;
margin: 25px 0;
font-size: 0.9em;
font-family: sans-serif;
min-width: 400px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
}
.styled-table thead tr {
background-color: #009879;
color: #ffffff;
text-align: left;
}
.styled-table th,
.styled-table td {
padding: 12px 15px;
}
.styled-table tbody tr {
border-bottom: thin solid #dddddd;
}
.styled-table tbody tr:nth-of-type(even) {
background-color: #f3f3f3;
}
.styled-table tbody tr.active-row {
font-weight: bold;
color: #009879;
}
.styled-table tbody tr:last-of-type {
border-bottom: 2px solid #009879;
}
</style>
</head>
<body>"""
+ html_table
+ "</body>"
)
return pretty_html_table
| import os
import pandas as pd
from babel.numbers import format_currency, format_decimal
from notify.exceptions import EnvironmentVariablesError
def format_numbers(df: pd.DataFrame, currency_columns: list = None, number_columns: list = None):
"""
Deze functie converteerd currency (bedrag) en number (getal) kolommen naar geformatteerde tekstvelden.
Parameters
----------
df: pd.DataFrame
dataset waarin kolommen staan die geconverteerd dienen te worden
currency_columns: list
lijst met kolomnamen die geconverteerd worden naar € kolommen en formats.
number_columns: list
lijst met kolomnamen die geconverteerd worden naar nummer kolommen met nederlandse annotatie.
Returns
-------
df: pd.DataFrame
dataset met kolommen die gebruikt kunnen worden voor het presenteren van
bedragen en nummers (locale=NL).
"""
# format de bedrag kolommen
if number_columns is None:
number_columns = []
if currency_columns is None:
currency_columns = []
for col in currency_columns:
df[col] = df[col].apply(lambda x: format_currency(number=x, currency="EUR", locale="nl_NL"))
# format de nummer kolommen
for col in number_columns:
df[col] = df[col].apply(lambda x: format_decimal(number=x, locale="nl_NL"))
return df
def check_environment_variables(required_variables: list):
"""
Test if environment variables are set.
Parameters
----------
required_variables: list
list of required variables that need to be present in environment variables.
Returns
-------
None
"""
values = [os.environ.get(x) for x in required_variables]
if not all(values):
raise EnvironmentVariablesError(f"One of the environment variables {', '.join(required_variables)} is not set")
def dataframe_to_html(df: pd.DataFrame) -> str:
"""
Deze functie zet een dataframe om in een opgemaakte HTML table. Wanneer de gebruiker zelfstandig een HTML bericht
opbouwt, kan deze functie uitkomst bieden voor het invoegen van html tabellen.
Parameters
----------
df: pd.DataFrame
dataframe die in een HTML table geconverteerd dient te worden.
Returns
-------
pretty_html_table: str
html body voor de gegeneerde HTML tabel
"""
html_table = df.to_html(index=False, classes="styled-table", justify="center")
pretty_html_table = (
"""
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Dataframe report</title>
<style type="text/css" media="screen">
h1 {
background-color: #a8a8a8;
display: flex;
flex-direction: column;
justify-content: center;
text-align: center;
}
.styled-table {
border-collapse: collapse;
margin: 25px 0;
font-size: 0.9em;
font-family: sans-serif;
min-width: 400px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
}
.styled-table thead tr {
background-color: #009879;
color: #ffffff;
text-align: left;
}
.styled-table th,
.styled-table td {
padding: 12px 15px;
}
.styled-table tbody tr {
border-bottom: thin solid #dddddd;
}
.styled-table tbody tr:nth-of-type(even) {
background-color: #f3f3f3;
}
.styled-table tbody tr.active-row {
font-weight: bold;
color: #009879;
}
.styled-table tbody tr:last-of-type {
border-bottom: 2px solid #009879;
}
</style>
</head>
<body>"""
+ html_table
+ "</body>"
)
return pretty_html_table
|
# Copyright 2020 Google, LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This tests the Pub/Sub to Cloud Run integration
import datetime
import os
import subprocess
import time
import uuid
from google.api_core.exceptions import NotFound
from google.cloud import logging_v2
from google.cloud import pubsub_v1
import pytest
SUFFIX = uuid.uuid4().hex[0:6]
PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"]
CLOUD_RUN_SERVICE = f"pubsub-test-{SUFFIX}"
TOPIC = f"pubsub-test_{SUFFIX}"
IMAGE_NAME = f"gcr.io/{PROJECT}/pubsub-test-{SUFFIX}"
@pytest.fixture
def container_image():
# Build container image for Cloud Run deployment
subprocess.run(
[
"gcloud",
"builds",
"submit",
"--tag",
IMAGE_NAME,
"--project",
PROJECT,
"--quiet",
],
check=True,
)
yield IMAGE_NAME
# Delete container image
subprocess.run(
[
"gcloud",
"container",
"images",
"delete",
IMAGE_NAME,
"--quiet",
"--project",
PROJECT,
],
check=True,
)
@pytest.fixture
def deployed_service(container_image):
# Deploy image to Cloud Run
subprocess.run(
[
"gcloud",
"run",
"deploy",
CLOUD_RUN_SERVICE,
"--image",
container_image,
"--region=us-central1",
"--project",
PROJECT,
"--platform=managed",
"--no-allow-unauthenticated",
],
check=True,
)
yield CLOUD_RUN_SERVICE
subprocess.run(
[
"gcloud",
"run",
"services",
"delete",
CLOUD_RUN_SERVICE,
"--platform=managed",
"--region=us-central1",
"--quiet",
"--project",
PROJECT,
],
check=True,
)
@pytest.fixture
def service_url(deployed_service):
# Get the URL for the cloud run service
service_url = subprocess.run(
[
"gcloud",
"run",
"--project",
PROJECT,
"--platform=managed",
"--region=us-central1",
"services",
"describe",
CLOUD_RUN_SERVICE,
"--format=value(status.url)",
],
stdout=subprocess.PIPE,
check=True,
).stdout.strip()
yield service_url.decode()
@pytest.fixture()
def pubsub_topic():
publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(PROJECT, TOPIC)
publisher.create_topic(request={"name": topic_path})
yield TOPIC
try:
publisher.delete_topic(request={"topic": topic_path})
except NotFound:
print("Topic not found, it was either never created or was already deleted.")
@pytest.fixture(autouse=True)
def pubsub_subscription(pubsub_topic, service_url):
# Create pubsub push subscription to Cloud Run Service
# Attach service account with Cloud Run Invoker role
# See tutorial for details on setting up service-account:
# https://cloud.google.com/run/docs/tutorials/pubsub
publisher = pubsub_v1.PublisherClient()
subscriber = pubsub_v1.SubscriberClient()
subscription_id = f"{pubsub_topic}_sub"
topic_path = publisher.topic_path(PROJECT, pubsub_topic)
subscription_path = subscriber.subscription_path(PROJECT, subscription_id)
push_config = pubsub_v1.types.PushConfig(
push_endpoint=service_url,
oidc_token=pubsub_v1.types.PushConfig.OidcToken(
service_account_email=f"cloud-run-invoker@{PROJECT}.iam.gserviceaccount.com"
),
)
# wrapping in 'with' block automatically calls close on gRPC channel
with subscriber:
subscriber.create_subscription(
request={
"name": subscription_path,
"topic": topic_path,
"push_config": push_config,
}
)
yield
subscriber = pubsub_v1.SubscriberClient()
# delete subscription
with subscriber:
try:
subscriber.delete_subscription(request={"subscription": subscription_path})
except NotFound:
print(
"Unable to delete - subscription either never created or already deleted."
)
def test_end_to_end(pubsub_topic):
# Post the message "Runner" to the topic
publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(PROJECT, pubsub_topic)
message = "Runner"
data = message.encode("utf-8")
# When you publish a message, the client returns a future.
future = publisher.publish(topic_path, data)
future.result()
# Check the logs for "Hello Runner"
time.sleep(20) # Slight delay writing to stackdriver
client = logging_v2.LoggingServiceV2Client()
resource_names = [f"projects/{PROJECT}"]
# We add timestamp for making the query faster.
now = datetime.datetime.now(datetime.timezone.utc)
filter_date = now - datetime.timedelta(minutes=1)
filters = (
f"timestamp>=\"{filter_date.isoformat("T")}\" "
"resource.type=cloud_run_revision "
f"AND resource.labels.service_name={CLOUD_RUN_SERVICE} "
)
# Retry a maximum number of 10 times to find results in stackdriver
found = False
for x in range(10):
iterator = client.list_log_entries(resource_names, filter_=filters)
for entry in iterator:
if entry.text_payload == "Hello Runner!":
found = True
break
# When message found, exit loop
if found is True:
break
time.sleep(5) # Slight delay before retry
assert found
| # Copyright 2020 Google, LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This tests the Pub/Sub to Cloud Run integration
import datetime
import os
import subprocess
import time
import uuid
from google.api_core.exceptions import NotFound
from google.cloud import logging_v2
from google.cloud import pubsub_v1
import pytest
SUFFIX = uuid.uuid4().hex[0:6]
PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"]
CLOUD_RUN_SERVICE = f"pubsub-test-{SUFFIX}"
TOPIC = f"pubsub-test_{SUFFIX}"
IMAGE_NAME = f"gcr.io/{PROJECT}/pubsub-test-{SUFFIX}"
@pytest.fixture
def container_image():
# Build container image for Cloud Run deployment
subprocess.run(
[
"gcloud",
"builds",
"submit",
"--tag",
IMAGE_NAME,
"--project",
PROJECT,
"--quiet",
],
check=True,
)
yield IMAGE_NAME
# Delete container image
subprocess.run(
[
"gcloud",
"container",
"images",
"delete",
IMAGE_NAME,
"--quiet",
"--project",
PROJECT,
],
check=True,
)
@pytest.fixture
def deployed_service(container_image):
# Deploy image to Cloud Run
subprocess.run(
[
"gcloud",
"run",
"deploy",
CLOUD_RUN_SERVICE,
"--image",
container_image,
"--region=us-central1",
"--project",
PROJECT,
"--platform=managed",
"--no-allow-unauthenticated",
],
check=True,
)
yield CLOUD_RUN_SERVICE
subprocess.run(
[
"gcloud",
"run",
"services",
"delete",
CLOUD_RUN_SERVICE,
"--platform=managed",
"--region=us-central1",
"--quiet",
"--project",
PROJECT,
],
check=True,
)
@pytest.fixture
def service_url(deployed_service):
# Get the URL for the cloud run service
service_url = subprocess.run(
[
"gcloud",
"run",
"--project",
PROJECT,
"--platform=managed",
"--region=us-central1",
"services",
"describe",
CLOUD_RUN_SERVICE,
"--format=value(status.url)",
],
stdout=subprocess.PIPE,
check=True,
).stdout.strip()
yield service_url.decode()
@pytest.fixture()
def pubsub_topic():
publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(PROJECT, TOPIC)
publisher.create_topic(request={"name": topic_path})
yield TOPIC
try:
publisher.delete_topic(request={"topic": topic_path})
except NotFound:
print("Topic not found, it was either never created or was already deleted.")
@pytest.fixture(autouse=True)
def pubsub_subscription(pubsub_topic, service_url):
# Create pubsub push subscription to Cloud Run Service
# Attach service account with Cloud Run Invoker role
# See tutorial for details on setting up service-account:
# https://cloud.google.com/run/docs/tutorials/pubsub
publisher = pubsub_v1.PublisherClient()
subscriber = pubsub_v1.SubscriberClient()
subscription_id = f"{pubsub_topic}_sub"
topic_path = publisher.topic_path(PROJECT, pubsub_topic)
subscription_path = subscriber.subscription_path(PROJECT, subscription_id)
push_config = pubsub_v1.types.PushConfig(
push_endpoint=service_url,
oidc_token=pubsub_v1.types.PushConfig.OidcToken(
service_account_email=f"cloud-run-invoker@{PROJECT}.iam.gserviceaccount.com"
),
)
# wrapping in 'with' block automatically calls close on gRPC channel
with subscriber:
subscriber.create_subscription(
request={
"name": subscription_path,
"topic": topic_path,
"push_config": push_config,
}
)
yield
subscriber = pubsub_v1.SubscriberClient()
# delete subscription
with subscriber:
try:
subscriber.delete_subscription(request={"subscription": subscription_path})
except NotFound:
print(
"Unable to delete - subscription either never created or already deleted."
)
def test_end_to_end(pubsub_topic):
# Post the message "Runner" to the topic
publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(PROJECT, pubsub_topic)
message = "Runner"
data = message.encode("utf-8")
# When you publish a message, the client returns a future.
future = publisher.publish(topic_path, data)
future.result()
# Check the logs for "Hello Runner"
time.sleep(20) # Slight delay writing to stackdriver
client = logging_v2.LoggingServiceV2Client()
resource_names = [f"projects/{PROJECT}"]
# We add timestamp for making the query faster.
now = datetime.datetime.now(datetime.timezone.utc)
filter_date = now - datetime.timedelta(minutes=1)
filters = (
f"timestamp>=\"{filter_date.isoformat('T')}\" "
"resource.type=cloud_run_revision "
f"AND resource.labels.service_name={CLOUD_RUN_SERVICE} "
)
# Retry a maximum number of 10 times to find results in stackdriver
found = False
for x in range(10):
iterator = client.list_log_entries(resource_names, filter_=filters)
for entry in iterator:
if entry.text_payload == "Hello Runner!":
found = True
break
# When message found, exit loop
if found is True:
break
time.sleep(5) # Slight delay before retry
assert found
|
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Model classes representing a tensor comprehension.
These classes model the language more at an AST level as evaluated. Reasoning
about it typically involves processing this form into config objects that
represent actual op definitions (i.e. YAML).
"""
from typing import Any, Dict, List, Optional, Sequence, Set, Tuple
from enum import Enum
from ..... import ir as _ir
from .affine import *
from .scalar_expr import *
from .types import *
from .yaml_helper import *
# Type aliases.
AffineDimList = Dict[str, _ir.AffineExpr]
class TensorExpression:
"""An expression that can appear on the RHS of a comprehension."""
def to_scalar_expression(self) -> ScalarExpression:
raise NotImplementedError()
def visit_tensor_exprs(self, callback):
"""Visits all tensor expression reachable by the expression."""
callback(self)
def collect_dim_uses(self, uses: Set["DimDef"]):
"""Collects all DimDefs reachable through this expression."""
results = set()
def visit_dim_def(dim_def):
if isinstance(dim_def, DimDef):
uses.add(dim_def)
def visit_affine_exprs(expr):
if isinstance(expr, TensorUse):
for ind in expr.indices:
ind.visit_affine_exprs(visit_dim_def)
if isinstance(expr, ReduceApply):
for ind in expr.reduce.reduce_dims:
ind.visit_affine_exprs(visit_dim_def)
self.visit_tensor_exprs(visit_affine_exprs)
def collect_tensor_uses(self, uses: Set["TensorUse"]):
"""Collects all TensorUses reachable through this expression."""
def visit_tensor_use(expr):
if isinstance(expr, TensorUse):
uses.add(expr)
self.visit_tensor_exprs(visit_tensor_use)
def collect_indices(self, indices: Set["index"]):
"""Collects all index accesses reachable through this expression."""
def visit_index(expr):
if isinstance(expr, index):
indices.add(expr)
self.visit_tensor_exprs(visit_index)
def collect_scalar_uses(self, uses: Set["ScalarDef"]):
"""Collects all ScalarDefs reachable through this expression."""
def visit_scalar_def(expr):
if isinstance(expr, ScalarDef):
uses.add(expr)
self.visit_tensor_exprs(visit_scalar_def)
def __add__(self, rhs: "TensorExpression") -> "TensorExpression":
return PrimFn.add(self, rhs)
def __mul__(self, rhs) -> "TensorExpression":
return PrimFn.mul(self, rhs)
def __sub__(self, rhs) -> "TensorExpression":
return PrimFn.sub(self, rhs)
def __hash__(self):
return hash(id(self))
class TensorUse(TensorExpression):
"""A used tensor represented by its (tensor_name, indices).
Note that forming a comprehension via direct assignment is performed through
__setitem__ on the TensorDef level. However, performing a reduction with
compound ops (+=, *=, etc) is done by doing a:
TensorDef.__getitem__
TensorUse.__iadd__
TensorDef.__setitem__
"""
def __init__(self, operand_def: "OperandDef",
indices: Sequence[AffineExprDef]):
self.operand_def = operand_def
self.indices = tuple(indices)
def to_scalar_expression(self) -> ScalarExpression:
return ScalarArg(self.tensor_name).expr()
@property
def tensor_name(self) -> str:
name = self.operand_def.name
assert name is not None, "TensorDef not attached"
return name
def __iadd__(self, rhs: TensorExpression) -> TensorExpression:
return ReduceFn.add(*self._compute_reduce_dims(rhs))(rhs)
def _compute_reduce_dims(self, rhs: TensorExpression) -> Set[DimDef]:
"""For implicit reductions, computes default reduction dims.
Assumes that the rhs is the expression being reduced and self is being
reduced into. Any indices referenced on the rhs and not in self are
considered reduction dims and will be ordered as encountered on the rhs.
"""
rhs_dims = set()
lhs_dims = set()
rhs.collect_dim_uses(rhs_dims)
self.collect_dim_uses(lhs_dims)
return rhs_dims - lhs_dims
def __repr__(self):
return f"{self.tensor_name}[{", ".join([repr(i) for i in self.indices])}]"
class OperandKind(Enum):
InputTensor = 0
Scalar = 1
OutputTensor = 2
Attribute = 3
class OperandDef:
"""Definition of an operand passed to an operation.
Keep the meta information of Tensor, Scalar, and Attribute operands and
provide the shared registration functionality.
"""
def __init__(self,
kind: OperandKind,
type_var: TypeVar,
size_exprs: Optional[Sequence[AffineExprDef]] = None,
index_dims: Optional[Sequence[DimDef]] = None):
if not isinstance(type_var, TypeVar):
raise ValueError(
f"OperandDef requires a TypeVar but got {repr(type_var)}")
self.owner = None # type: Optional["LinalgOpDef"]
self.type_var = type_var
self.size_exprs = size_exprs
self.index_dims = index_dims
self.kind = kind
self.name = None # type: Optional[str]
self.registered_index = -1 # type: int
def attach(self, index: int, name: str, owner: "LinalgOpDef"):
if self.owner:
raise ValueError(f"OperandDef already registered with op: {self}")
self.registered_index = index
self.name = name
self.owner = owner
def __hash__(self):
return hash(id(self))
def __repr__(self):
return (f"{self.name}:OperandDef(kind={self.kind.name}, "
f"type={repr(self.type_var)}, size_exprs={self.size_exprs}), "
f"index_dims={self.index_dims})")
class TensorDef:
"""Tensor operand definition.
Tensor operands are indexed using the associated indexing_map when forwarded
to the body of the structured op. A unique name identifies the tensor operands
and an index determines their position in the operation's parameter list. A
tensor definition takes type, a shape, and an optional flag to mark output
tensors. Additionally, a tuple of index dimensions may be used to map the
tensor to the loop dimensions of the operation. This mapping is needed to
compute the indexing map of shape-only tensors that have no uses.
"""
def __init__(self,
type_var: TypeVar,
*shape: AffineExprDef,
index_dims: Optional[Sequence[DimDef]] = None,
output: bool = False):
if index_dims and len(shape) != len(index_dims):
raise ValueError(f"Expected the shape rank {len(shape)} to match the "
f"number of index_dims {len(index_dims)}")
if index_dims and any(not isinstance(dim, DimDef) for dim in index_dims):
raise ValueError(f"TensorDef requires index dims of type DimDef but "
f"got {index_dims}")
kind = OperandKind.OutputTensor if output else OperandKind.InputTensor
self.operand_def = OperandDef(
kind, type_var, size_exprs=shape, index_dims=index_dims)
def __getitem__(self, dims) -> TensorUse:
assert self.operand_def.owner, "TensorDef is not attached to an op"
state = AffineBuildState(
global_state=self.operand_def.owner._affine_state,
allow_new_symbols=False)
if not isinstance(dims, tuple):
dims = (dims,) # Handle single subscript case.
# Special case: (None) is a 0d-scalar use.
if dims == (None,):
dims = ()
exprs = []
for expr_def in dims:
if not isinstance(expr_def, AffineExprDef):
raise KeyError(
"A TensorDef can only be subscripted by a tuple of affine dims")
exprs.append(expr_def)
return TensorUse(self.operand_def, exprs)
def __setitem__(self, dims, value):
"""Creates a new 1:1 comprehension by binding this tensor to an expression.
Note that due to the way assignment works in Python, we have to capture
direct assignment as a setitem on the TensorDef.
"""
if not isinstance(value, TensorExpression):
raise ValueError(f"Only TensorExpressions can be assigned to TensorDefs. "
f"Got: {repr(value)}")
use = self[dims]
comp = Comprehension((use, value))
self.operand_def.owner.comprehensions.append(comp)
class ScalarDef(TensorExpression):
"""Scalar operand definition.
Scalar operands are forwarded to the body of the structured op as they are.
A unique name identifies the scalars and an index determines their position in
the operation's parameter list.
"""
def __init__(self, type_var: TypeVar):
self.operand_def = OperandDef(OperandKind.Scalar, type_var)
@property
def scalar_name(self) -> str:
name = self.operand_def.name
assert name is not None, "ScalarDef not attached"
return name
def to_scalar_expression(self) -> ScalarExpression:
return ScalarArg(self.scalar_name).expr()
class AttributeDef:
"""Index Attribute definition.
Index attributes provide a way to define and set symbols that can be used in
indexing expressions. Every attribute specifies a tuple of symbols that at
compile-time are replaced by integer values.
"""
yaml_tag = "!LinalgAttributeDef"
def __init__(self, *sizes: SymbolDef):
if any(not isinstance(size, SymbolDef) for size in sizes):
raise ValueError(f"AttributeDef requires sizes of type SymbolDef but got "
f"{sizes}")
self.operand_def = OperandDef(OperandKind.Attribute, I64, size_exprs=sizes)
class Comprehension:
"""Represents a single comprehension."""
def __init__(self, *bindings: Tuple[TensorUse, TensorExpression]):
self.definitions = list() # List[TensorUse]
self.values = list() # List[TensorExpression]
# Find the lhs to reduction rhs.
for assign, value in bindings:
if isinstance(value, ReduceApply):
if value.lhs:
raise ValueError(f"Reduction expression already assigns: {value}")
value.lhs = assign
self.definitions.append(assign)
self.values.append(value)
@property
def all_reduction_dims(self) -> Set[Tuple[DimDef, ...]]:
"""Gets the reduction dims for the comprehension or None."""
result = set()
for use in self.values:
if isinstance(use, ReduceApply):
result.add(use.reduce.reduce_dims)
else:
result.add(tuple())
return result
def __repr__(self):
if len(self.definitions) > 1:
defs_repr = f"({", ".join(repr(d) for d in self.definitions)})"
values_repr = f"({", ".join(repr(v) for v in self.values)})"
else:
defs_repr = f"{repr(self.definitions[0])}"
values_repr = f"{repr(self.values[0])}"
return f"{defs_repr} = {values_repr}"
class PrimFnType:
"""Primitive operations."""
def __init__(self, prim_name: str):
self.prim_name = prim_name
def __call__(self, *args):
return PrimApply(self, args)
def reduce(self, *reduce_dims: DimDef):
"""Shortcut to create a Reduce operation from this primitive."""
return ReduceFnType(self, *reduce_dims)
def __repr__(self):
return f"{self.prim_name}"
class PrimFn:
add = PrimFnType("add")
exp = PrimFnType("exp")
log = PrimFnType("log")
mul = PrimFnType("mul")
max = PrimFnType("max")
min = PrimFnType("min")
sub = PrimFnType("sub")
class ReduceFnType:
"""A reduction operator that reduces into its LHS from its RHS."""
def __init__(self, operator: PrimFnType, *reduce_dims: DimDef):
"""Initializes the ReduceFn with a primitive function and dims."""
if not isinstance(operator, PrimFnType):
raise ValueError(f"Reduce expected a Prim operator but got {operator}")
self.operator = operator
self.reduce_dims = tuple(reduce_dims)
def __call__(self, *args: TensorExpression):
return ReduceApply(self, args)
def __repr__(self):
return (f"reduce_{self.operator.prim_name}"
f"({", ".join(repr(d) for d in self.reduce_dims)})")
class ReduceFn:
add = PrimFn.add.reduce
mul = PrimFn.mul.reduce
max = PrimFn.max.reduce
min = PrimFn.min.reduce
class PrimApply(TensorExpression):
"""Application of a primitive."""
def __init__(self, prim: PrimFnType, args: Sequence[TensorExpression]):
self.prim = prim
self.args = tuple(args)
def to_scalar_expression(self) -> ScalarExpression:
return ScalarApplyFn(self.prim.prim_name,
*[arg.to_scalar_expression() for arg in self.args
]).expr()
def visit_tensor_exprs(self, callback):
super().visit_tensor_exprs(callback)
for arg in self.args:
arg.visit_tensor_exprs(callback)
def __repr__(self):
return f"{repr(self.prim)}({", ".join(repr(a) for a in self.args)})"
class const(TensorExpression):
"""Returns the given constant floating point or integer value."""
def __init__(self, value: Any):
with _ir.Context():
if isinstance(value, float):
self.value = str(_ir.FloatAttr.get_f64(float(value)))
elif isinstance(value, int):
self.value = str(
_ir.IntegerAttr.get(_ir.IntegerType.get_signless(64), int(value)))
else:
raise ValueError(f"const requires int or float but got {type(value)}")
def to_scalar_expression(self) -> ScalarExpression:
return ScalarConst(self.value).expr()
def __repr__(self):
return f"const({self.type_var}, {self.value})"
class index(TensorExpression):
"""Returns the iteration index for a given dimension name.
Resolves the given dimension name to obtain its position in the iteration
domain of the operation.
"""
def __init__(self, dim: DimDef):
self.dim_def = dim
self.dim = -1
def resolve_dimension_name(self, affine_state: AffineBuildState):
self.dim = affine_state.get_dim(self.dim_def.dimname)
def to_scalar_expression(self) -> ScalarExpression:
assert self.dim != -1, "Dimension name not resolved"
return ScalarIndex(self.dim).expr()
def __repr__(self):
return f"index({repr(self.dim)})"
class cast(TensorExpression):
"""Casts the element type to a type (typically symbolic TypeVar)."""
def __init__(self, to_type: TypeVar, operand: TensorExpression):
self.to_type = to_type
self.operand = operand
def to_scalar_expression(self) -> ScalarExpression:
return ScalarSymbolicCast(self.to_type,
self.operand.to_scalar_expression()).expr()
def visit_tensor_exprs(self, callback):
super().visit_tensor_exprs(callback)
self.operand.visit_tensor_exprs(callback)
def __repr__(self):
return f"cast({self.to_type}, {repr(self.operand)})"
class ReduceApply(TensorExpression):
"""Application of a reduction.
This captures the lhs separately (initial value) separately from the rhs.
"""
def __init__(self, reduce: ReduceFnType, args: Sequence[TensorExpression]):
self.reduce = reduce
self.lhs = None # type: Optional[TensorUse]
self.args = tuple(args)
def to_scalar_expression(self) -> ScalarExpression:
if self.lhs is None:
raise ValueError(f"Cannot scalarize a ReduceApply that has not been "
f"bound to its lhs: {self}")
full_args = [self.lhs.to_scalar_expression()
] + [arg.to_scalar_expression() for arg in self.args]
return ScalarApplyFn(self.reduce.operator.prim_name, *full_args).expr()
def visit_tensor_exprs(self, callback):
for arg in self.args:
arg.visit_tensor_exprs(callback)
def __repr__(self):
return f"{repr(self.reduce)}({", ".join(repr(a) for a in self.args)})"
class OpInterfaceDef:
"""An interface that an op implements."""
def __init__(self, cpp_name: str):
self.cpp_name = cpp_name
ContractionOpInterface = OpInterfaceDef("LinalgContractionOpInterface")
class OpMetadataDef(YAMLObject):
"""Metadata about the op (generally not behavior impacting)."""
yaml_tag = "!LinalgOpMetadata"
def __init__(self, name: str, cpp_class_name: Optional[str],
doc: Optional[str]):
self.name = name
self.cpp_class_name = cpp_class_name if cpp_class_name is not None else name
self.doc = doc
self.implements = [] # type: List[OpInterfaceDef]
def to_yaml_custom_dict(self):
d = dict(
name=self.name,
cpp_class_name=self.cpp_class_name,
doc=self.doc,
)
if self.implements:
d["implements"] = [intr.cpp_name for intr in self.implements]
return d
class LinalgOpDef:
"""Definition of a linalg op."""
def __init__(self,
name: str,
cpp_class_name: Optional[str] = None,
doc: Optional[str] = None):
self.metadata = OpMetadataDef(
name=name, cpp_class_name=cpp_class_name, doc=doc)
self.registered_operands = dict() # type: Dict[str, OperandDef]
self.domain = list() # type: List[DimDef]
self.comprehensions = list() # type: List[Comprehension]
self._affine_state = AffineBuildState()
def add_operand(self, name: str, operand: OperandDef):
"""Registers an operand."""
if name in self.registered_operands:
raise ValueError(f"The operand {name} is already registered "
f"to {self.registered_operands["name"]}")
# Ensure output tensors are registered after input tensors and scalars and
# attributes are registered after all other operand types.
registered_kinds = [
operand.kind.value for operand in self.registered_operands.values()
]
if registered_kinds:
maximum = max(registered_kinds)
if maximum > operand.kind.value and maximum > OperandKind.Scalar.value:
raise ValueError(
f"The operand {name} of kind {operand.kind.name} is registered "
f"after an operand of kind {OperandKind(maximum).name}")
operand.attach(len(self.registered_operands), name, self)
self.registered_operands[name] = operand
def __repr__(self):
lines = [
f"LinalgOpDef({self.metadata.name} -> {self.metadata.cpp_class_name},"
]
for name, operand in self.registered_operands.items():
lines.append(f" {operand}")
if self.comprehensions:
lines[-1] += " {"
for comprehension in self.comprehensions:
lines.append(f" {comprehension}")
lines.append("}")
return "\n".join(lines)
| # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Model classes representing a tensor comprehension.
These classes model the language more at an AST level as evaluated. Reasoning
about it typically involves processing this form into config objects that
represent actual op definitions (i.e. YAML).
"""
from typing import Any, Dict, List, Optional, Sequence, Set, Tuple
from enum import Enum
from ..... import ir as _ir
from .affine import *
from .scalar_expr import *
from .types import *
from .yaml_helper import *
# Type aliases.
AffineDimList = Dict[str, _ir.AffineExpr]
class TensorExpression:
"""An expression that can appear on the RHS of a comprehension."""
def to_scalar_expression(self) -> ScalarExpression:
raise NotImplementedError()
def visit_tensor_exprs(self, callback):
"""Visits all tensor expression reachable by the expression."""
callback(self)
def collect_dim_uses(self, uses: Set["DimDef"]):
"""Collects all DimDefs reachable through this expression."""
results = set()
def visit_dim_def(dim_def):
if isinstance(dim_def, DimDef):
uses.add(dim_def)
def visit_affine_exprs(expr):
if isinstance(expr, TensorUse):
for ind in expr.indices:
ind.visit_affine_exprs(visit_dim_def)
if isinstance(expr, ReduceApply):
for ind in expr.reduce.reduce_dims:
ind.visit_affine_exprs(visit_dim_def)
self.visit_tensor_exprs(visit_affine_exprs)
def collect_tensor_uses(self, uses: Set["TensorUse"]):
"""Collects all TensorUses reachable through this expression."""
def visit_tensor_use(expr):
if isinstance(expr, TensorUse):
uses.add(expr)
self.visit_tensor_exprs(visit_tensor_use)
def collect_indices(self, indices: Set["index"]):
"""Collects all index accesses reachable through this expression."""
def visit_index(expr):
if isinstance(expr, index):
indices.add(expr)
self.visit_tensor_exprs(visit_index)
def collect_scalar_uses(self, uses: Set["ScalarDef"]):
"""Collects all ScalarDefs reachable through this expression."""
def visit_scalar_def(expr):
if isinstance(expr, ScalarDef):
uses.add(expr)
self.visit_tensor_exprs(visit_scalar_def)
def __add__(self, rhs: "TensorExpression") -> "TensorExpression":
return PrimFn.add(self, rhs)
def __mul__(self, rhs) -> "TensorExpression":
return PrimFn.mul(self, rhs)
def __sub__(self, rhs) -> "TensorExpression":
return PrimFn.sub(self, rhs)
def __hash__(self):
return hash(id(self))
class TensorUse(TensorExpression):
"""A used tensor represented by its (tensor_name, indices).
Note that forming a comprehension via direct assignment is performed through
__setitem__ on the TensorDef level. However, performing a reduction with
compound ops (+=, *=, etc) is done by doing a:
TensorDef.__getitem__
TensorUse.__iadd__
TensorDef.__setitem__
"""
def __init__(self, operand_def: "OperandDef",
indices: Sequence[AffineExprDef]):
self.operand_def = operand_def
self.indices = tuple(indices)
def to_scalar_expression(self) -> ScalarExpression:
return ScalarArg(self.tensor_name).expr()
@property
def tensor_name(self) -> str:
name = self.operand_def.name
assert name is not None, "TensorDef not attached"
return name
def __iadd__(self, rhs: TensorExpression) -> TensorExpression:
return ReduceFn.add(*self._compute_reduce_dims(rhs))(rhs)
def _compute_reduce_dims(self, rhs: TensorExpression) -> Set[DimDef]:
"""For implicit reductions, computes default reduction dims.
Assumes that the rhs is the expression being reduced and self is being
reduced into. Any indices referenced on the rhs and not in self are
considered reduction dims and will be ordered as encountered on the rhs.
"""
rhs_dims = set()
lhs_dims = set()
rhs.collect_dim_uses(rhs_dims)
self.collect_dim_uses(lhs_dims)
return rhs_dims - lhs_dims
def __repr__(self):
return f"{self.tensor_name}[{', '.join([repr(i) for i in self.indices])}]"
class OperandKind(Enum):
InputTensor = 0
Scalar = 1
OutputTensor = 2
Attribute = 3
class OperandDef:
"""Definition of an operand passed to an operation.
Keep the meta information of Tensor, Scalar, and Attribute operands and
provide the shared registration functionality.
"""
def __init__(self,
kind: OperandKind,
type_var: TypeVar,
size_exprs: Optional[Sequence[AffineExprDef]] = None,
index_dims: Optional[Sequence[DimDef]] = None):
if not isinstance(type_var, TypeVar):
raise ValueError(
f"OperandDef requires a TypeVar but got {repr(type_var)}")
self.owner = None # type: Optional["LinalgOpDef"]
self.type_var = type_var
self.size_exprs = size_exprs
self.index_dims = index_dims
self.kind = kind
self.name = None # type: Optional[str]
self.registered_index = -1 # type: int
def attach(self, index: int, name: str, owner: "LinalgOpDef"):
if self.owner:
raise ValueError(f"OperandDef already registered with op: {self}")
self.registered_index = index
self.name = name
self.owner = owner
def __hash__(self):
return hash(id(self))
def __repr__(self):
return (f"{self.name}:OperandDef(kind={self.kind.name}, "
f"type={repr(self.type_var)}, size_exprs={self.size_exprs}), "
f"index_dims={self.index_dims})")
class TensorDef:
"""Tensor operand definition.
Tensor operands are indexed using the associated indexing_map when forwarded
to the body of the structured op. A unique name identifies the tensor operands
and an index determines their position in the operation's parameter list. A
tensor definition takes type, a shape, and an optional flag to mark output
tensors. Additionally, a tuple of index dimensions may be used to map the
tensor to the loop dimensions of the operation. This mapping is needed to
compute the indexing map of shape-only tensors that have no uses.
"""
def __init__(self,
type_var: TypeVar,
*shape: AffineExprDef,
index_dims: Optional[Sequence[DimDef]] = None,
output: bool = False):
if index_dims and len(shape) != len(index_dims):
raise ValueError(f"Expected the shape rank {len(shape)} to match the "
f"number of index_dims {len(index_dims)}")
if index_dims and any(not isinstance(dim, DimDef) for dim in index_dims):
raise ValueError(f"TensorDef requires index dims of type DimDef but "
f"got {index_dims}")
kind = OperandKind.OutputTensor if output else OperandKind.InputTensor
self.operand_def = OperandDef(
kind, type_var, size_exprs=shape, index_dims=index_dims)
def __getitem__(self, dims) -> TensorUse:
assert self.operand_def.owner, "TensorDef is not attached to an op"
state = AffineBuildState(
global_state=self.operand_def.owner._affine_state,
allow_new_symbols=False)
if not isinstance(dims, tuple):
dims = (dims,) # Handle single subscript case.
# Special case: (None) is a 0d-scalar use.
if dims == (None,):
dims = ()
exprs = []
for expr_def in dims:
if not isinstance(expr_def, AffineExprDef):
raise KeyError(
"A TensorDef can only be subscripted by a tuple of affine dims")
exprs.append(expr_def)
return TensorUse(self.operand_def, exprs)
def __setitem__(self, dims, value):
"""Creates a new 1:1 comprehension by binding this tensor to an expression.
Note that due to the way assignment works in Python, we have to capture
direct assignment as a setitem on the TensorDef.
"""
if not isinstance(value, TensorExpression):
raise ValueError(f"Only TensorExpressions can be assigned to TensorDefs. "
f"Got: {repr(value)}")
use = self[dims]
comp = Comprehension((use, value))
self.operand_def.owner.comprehensions.append(comp)
class ScalarDef(TensorExpression):
"""Scalar operand definition.
Scalar operands are forwarded to the body of the structured op as they are.
A unique name identifies the scalars and an index determines their position in
the operation's parameter list.
"""
def __init__(self, type_var: TypeVar):
self.operand_def = OperandDef(OperandKind.Scalar, type_var)
@property
def scalar_name(self) -> str:
name = self.operand_def.name
assert name is not None, "ScalarDef not attached"
return name
def to_scalar_expression(self) -> ScalarExpression:
return ScalarArg(self.scalar_name).expr()
class AttributeDef:
"""Index Attribute definition.
Index attributes provide a way to define and set symbols that can be used in
indexing expressions. Every attribute specifies a tuple of symbols that at
compile-time are replaced by integer values.
"""
yaml_tag = "!LinalgAttributeDef"
def __init__(self, *sizes: SymbolDef):
if any(not isinstance(size, SymbolDef) for size in sizes):
raise ValueError(f"AttributeDef requires sizes of type SymbolDef but got "
f"{sizes}")
self.operand_def = OperandDef(OperandKind.Attribute, I64, size_exprs=sizes)
class Comprehension:
"""Represents a single comprehension."""
def __init__(self, *bindings: Tuple[TensorUse, TensorExpression]):
self.definitions = list() # List[TensorUse]
self.values = list() # List[TensorExpression]
# Find the lhs to reduction rhs.
for assign, value in bindings:
if isinstance(value, ReduceApply):
if value.lhs:
raise ValueError(f"Reduction expression already assigns: {value}")
value.lhs = assign
self.definitions.append(assign)
self.values.append(value)
@property
def all_reduction_dims(self) -> Set[Tuple[DimDef, ...]]:
"""Gets the reduction dims for the comprehension or None."""
result = set()
for use in self.values:
if isinstance(use, ReduceApply):
result.add(use.reduce.reduce_dims)
else:
result.add(tuple())
return result
def __repr__(self):
if len(self.definitions) > 1:
defs_repr = f"({', '.join(repr(d) for d in self.definitions)})"
values_repr = f"({', '.join(repr(v) for v in self.values)})"
else:
defs_repr = f"{repr(self.definitions[0])}"
values_repr = f"{repr(self.values[0])}"
return f"{defs_repr} = {values_repr}"
class PrimFnType:
"""Primitive operations."""
def __init__(self, prim_name: str):
self.prim_name = prim_name
def __call__(self, *args):
return PrimApply(self, args)
def reduce(self, *reduce_dims: DimDef):
"""Shortcut to create a Reduce operation from this primitive."""
return ReduceFnType(self, *reduce_dims)
def __repr__(self):
return f"{self.prim_name}"
class PrimFn:
add = PrimFnType("add")
exp = PrimFnType("exp")
log = PrimFnType("log")
mul = PrimFnType("mul")
max = PrimFnType("max")
min = PrimFnType("min")
sub = PrimFnType("sub")
class ReduceFnType:
"""A reduction operator that reduces into its LHS from its RHS."""
def __init__(self, operator: PrimFnType, *reduce_dims: DimDef):
"""Initializes the ReduceFn with a primitive function and dims."""
if not isinstance(operator, PrimFnType):
raise ValueError(f"Reduce expected a Prim operator but got {operator}")
self.operator = operator
self.reduce_dims = tuple(reduce_dims)
def __call__(self, *args: TensorExpression):
return ReduceApply(self, args)
def __repr__(self):
return (f"reduce_{self.operator.prim_name}"
f"({', '.join(repr(d) for d in self.reduce_dims)})")
class ReduceFn:
add = PrimFn.add.reduce
mul = PrimFn.mul.reduce
max = PrimFn.max.reduce
min = PrimFn.min.reduce
class PrimApply(TensorExpression):
"""Application of a primitive."""
def __init__(self, prim: PrimFnType, args: Sequence[TensorExpression]):
self.prim = prim
self.args = tuple(args)
def to_scalar_expression(self) -> ScalarExpression:
return ScalarApplyFn(self.prim.prim_name,
*[arg.to_scalar_expression() for arg in self.args
]).expr()
def visit_tensor_exprs(self, callback):
super().visit_tensor_exprs(callback)
for arg in self.args:
arg.visit_tensor_exprs(callback)
def __repr__(self):
return f"{repr(self.prim)}({', '.join(repr(a) for a in self.args)})"
class const(TensorExpression):
"""Returns the given constant floating point or integer value."""
def __init__(self, value: Any):
with _ir.Context():
if isinstance(value, float):
self.value = str(_ir.FloatAttr.get_f64(float(value)))
elif isinstance(value, int):
self.value = str(
_ir.IntegerAttr.get(_ir.IntegerType.get_signless(64), int(value)))
else:
raise ValueError(f"const requires int or float but got {type(value)}")
def to_scalar_expression(self) -> ScalarExpression:
return ScalarConst(self.value).expr()
def __repr__(self):
return f"const({self.type_var}, {self.value})"
class index(TensorExpression):
"""Returns the iteration index for a given dimension name.
Resolves the given dimension name to obtain its position in the iteration
domain of the operation.
"""
def __init__(self, dim: DimDef):
self.dim_def = dim
self.dim = -1
def resolve_dimension_name(self, affine_state: AffineBuildState):
self.dim = affine_state.get_dim(self.dim_def.dimname)
def to_scalar_expression(self) -> ScalarExpression:
assert self.dim != -1, "Dimension name not resolved"
return ScalarIndex(self.dim).expr()
def __repr__(self):
return f"index({repr(self.dim)})"
class cast(TensorExpression):
"""Casts the element type to a type (typically symbolic TypeVar)."""
def __init__(self, to_type: TypeVar, operand: TensorExpression):
self.to_type = to_type
self.operand = operand
def to_scalar_expression(self) -> ScalarExpression:
return ScalarSymbolicCast(self.to_type,
self.operand.to_scalar_expression()).expr()
def visit_tensor_exprs(self, callback):
super().visit_tensor_exprs(callback)
self.operand.visit_tensor_exprs(callback)
def __repr__(self):
return f"cast({self.to_type}, {repr(self.operand)})"
class ReduceApply(TensorExpression):
"""Application of a reduction.
This captures the lhs separately (initial value) separately from the rhs.
"""
def __init__(self, reduce: ReduceFnType, args: Sequence[TensorExpression]):
self.reduce = reduce
self.lhs = None # type: Optional[TensorUse]
self.args = tuple(args)
def to_scalar_expression(self) -> ScalarExpression:
if self.lhs is None:
raise ValueError(f"Cannot scalarize a ReduceApply that has not been "
f"bound to its lhs: {self}")
full_args = [self.lhs.to_scalar_expression()
] + [arg.to_scalar_expression() for arg in self.args]
return ScalarApplyFn(self.reduce.operator.prim_name, *full_args).expr()
def visit_tensor_exprs(self, callback):
for arg in self.args:
arg.visit_tensor_exprs(callback)
def __repr__(self):
return f"{repr(self.reduce)}({', '.join(repr(a) for a in self.args)})"
class OpInterfaceDef:
"""An interface that an op implements."""
def __init__(self, cpp_name: str):
self.cpp_name = cpp_name
ContractionOpInterface = OpInterfaceDef("LinalgContractionOpInterface")
class OpMetadataDef(YAMLObject):
"""Metadata about the op (generally not behavior impacting)."""
yaml_tag = "!LinalgOpMetadata"
def __init__(self, name: str, cpp_class_name: Optional[str],
doc: Optional[str]):
self.name = name
self.cpp_class_name = cpp_class_name if cpp_class_name is not None else name
self.doc = doc
self.implements = [] # type: List[OpInterfaceDef]
def to_yaml_custom_dict(self):
d = dict(
name=self.name,
cpp_class_name=self.cpp_class_name,
doc=self.doc,
)
if self.implements:
d["implements"] = [intr.cpp_name for intr in self.implements]
return d
class LinalgOpDef:
"""Definition of a linalg op."""
def __init__(self,
name: str,
cpp_class_name: Optional[str] = None,
doc: Optional[str] = None):
self.metadata = OpMetadataDef(
name=name, cpp_class_name=cpp_class_name, doc=doc)
self.registered_operands = dict() # type: Dict[str, OperandDef]
self.domain = list() # type: List[DimDef]
self.comprehensions = list() # type: List[Comprehension]
self._affine_state = AffineBuildState()
def add_operand(self, name: str, operand: OperandDef):
"""Registers an operand."""
if name in self.registered_operands:
raise ValueError(f"The operand {name} is already registered "
f"to {self.registered_operands['name']}")
# Ensure output tensors are registered after input tensors and scalars and
# attributes are registered after all other operand types.
registered_kinds = [
operand.kind.value for operand in self.registered_operands.values()
]
if registered_kinds:
maximum = max(registered_kinds)
if maximum > operand.kind.value and maximum > OperandKind.Scalar.value:
raise ValueError(
f"The operand {name} of kind {operand.kind.name} is registered "
f"after an operand of kind {OperandKind(maximum).name}")
operand.attach(len(self.registered_operands), name, self)
self.registered_operands[name] = operand
def __repr__(self):
lines = [
f"LinalgOpDef({self.metadata.name} -> {self.metadata.cpp_class_name},"
]
for name, operand in self.registered_operands.items():
lines.append(f" {operand}")
if self.comprehensions:
lines[-1] += " {"
for comprehension in self.comprehensions:
lines.append(f" {comprehension}")
lines.append("}")
return "\n".join(lines)
|
import logging
from tqdm import tqdm
from typing import Optional, Union
from brainscore.metrics import Score
from brainscore.model_interface import BrainModel
from brainscore.utils import fullname
from model_tools.activations.pca import LayerPCA
from model_tools.brain_transformation import TemporalIgnore
from model_tools.utils import make_list
from result_caching import store_xarray, store
class LayerMappedModel(BrainModel):
def __init__(self, identifier, activations_model, region_layer_map, visual_degrees=None):
self._identifier = identifier
self.activations_model = activations_model
self._visual_degrees = visual_degrees
self.region_layer_map = region_layer_map
self.recorded_regions = []
@property
def identifier(self):
return self._identifier
def look_at(self, stimuli, number_of_trials=1):
layer_regions = {}
for region in self.recorded_regions:
layers = self.region_layer_map[region]
layers = make_list(layers)
for layer in layers:
assert layer not in layer_regions, f"layer {layer} has already been assigned for {layer_regions[layer]}"
layer_regions[layer] = region
activations = self.run_activations(stimuli, layers=list(layer_regions.keys()), number_of_trials=number_of_trials)
activations['region'] = 'neuroid', [layer_regions[layer] for layer in activations['layer'].values]
return activations
def run_activations(self, stimuli, layers, number_of_trials=1):
activations = self.activations_model(stimuli, layers=layers)
return activations
def start_task(self, task):
if task != BrainModel.Task.passive:
raise NotImplementedError()
def start_recording(self, recording_target: BrainModel.RecordingTarget):
self.recorded_regions = [recording_target]
def visual_degrees(self) -> int:
return self._visual_degrees
class LayerSelection:
def __init__(self, model_identifier, activations_model, layers, visual_degrees):
"""
:param model_identifier: this is separate from the container name because it only refers to
the combination of (model, preprocessing), i.e. no mapping.
"""
self.model_identifier = model_identifier
self._layer_scoring = LayerScores(model_identifier=model_identifier, activations_model=activations_model,
visual_degrees=visual_degrees)
self.layers = layers
self._logger = logging.getLogger(fullname(self))
def __call__(self, selection_identifier, benchmark):
# for layer-mapping, attach LayerPCA so that we can cache activations
model_identifier = self.model_identifier
pca_hooked = LayerPCA.is_hooked(self._layer_scoring._activations_model)
if not pca_hooked:
pca_handle = LayerPCA.hook(self._layer_scoring._activations_model, n_components=1000)
identifier = self._layer_scoring._activations_model.identifier
self._layer_scoring._activations_model.identifier = identifier + "-pca_1000"
model_identifier += "-pca_1000"
result = self._call(model_identifier=model_identifier, selection_identifier=selection_identifier,
benchmark=benchmark)
if not pca_hooked:
pca_handle.remove()
self._layer_scoring._activations_model.identifier = identifier
return result
@store(identifier_ignore=['benchmark', 'benchmark'])
def _call(self, model_identifier, selection_identifier, benchmark):
self._logger.debug("Finding best layer")
layer_scores = self._layer_scoring(benchmark=benchmark, benchmark_identifier=selection_identifier,
layers=self.layers, prerun=True)
self._logger.debug("Layer scores (unceiled): " + ", ".join([
f"{layer} -> {layer_scores.raw.sel(layer=layer, aggregation="center").values:.3f}"
f"+-{layer_scores.raw.sel(layer=layer, aggregation="error").values:.3f}"
for layer in layer_scores['layer'].values]))
best_layer = layer_scores['layer'].values[layer_scores.sel(aggregation='center').argmax()]
return best_layer
class LayerScores:
def __init__(self, model_identifier, activations_model, visual_degrees):
self.model_identifier = model_identifier
self._activations_model = activations_model
self._visual_degrees = visual_degrees
self._logger = logging.getLogger(fullname(self))
def __call__(self, benchmark, layers, benchmark_identifier=None, prerun=False):
return self._call(model_identifier=self.model_identifier,
benchmark_identifier=benchmark_identifier or benchmark.identifier,
visual_degrees=self._visual_degrees,
model=self._activations_model, benchmark=benchmark, layers=layers, prerun=prerun)
@store_xarray(identifier_ignore=['model', 'benchmark', 'layers', 'prerun'], combine_fields={'layers': 'layer'})
def _call(self, model_identifier, benchmark_identifier, visual_degrees, # storage fields
model, benchmark, layers, prerun=False):
layer_scores = []
for i, layer in enumerate(tqdm(layers, desc="layers")):
layer_model = self._create_mapped_model(region=benchmark.region, layer=layer, model=model,
model_identifier=model_identifier, visual_degrees=visual_degrees)
layer_model = TemporalIgnore(layer_model)
if i == 0 and prerun: # pre-run activations together to avoid running every layer separately
# we can only pre-run stimuli in response to the benchmark, since we might otherwise be missing
# visual_degrees resizing.
layer_model = PreRunLayers(model=model, layers=layers, forward=layer_model)
score = benchmark(layer_model)
score = score.expand_dims('layer')
score['layer'] = [layer]
layer_scores.append(score)
layer_scores = Score.merge(*layer_scores)
layer_scores = layer_scores.sel(layer=layers) # preserve layer ordering
return layer_scores
def _create_mapped_model(self, region, layer, model, model_identifier, visual_degrees):
return LayerMappedModel(identifier=f"{model_identifier}-{layer}", visual_degrees=visual_degrees,
# per-layer identifier to avoid overlap
activations_model=model, region_layer_map={region: layer})
class PreRunLayers:
def __init__(self, model, layers, forward):
self._model = model
self._layers = layers
self._forward = forward
def look_at(self, stimuli, number_of_trials=1):
self._model(layers=self._layers, stimuli=stimuli)
return self._forward.look_at(stimuli, number_of_trials=number_of_trials)
def __getattr__(self, item):
if item in ['look_at']:
return super(PreRunLayers, self).__getattr__(item)
return getattr(self._forward, item)
| import logging
from tqdm import tqdm
from typing import Optional, Union
from brainscore.metrics import Score
from brainscore.model_interface import BrainModel
from brainscore.utils import fullname
from model_tools.activations.pca import LayerPCA
from model_tools.brain_transformation import TemporalIgnore
from model_tools.utils import make_list
from result_caching import store_xarray, store
class LayerMappedModel(BrainModel):
def __init__(self, identifier, activations_model, region_layer_map, visual_degrees=None):
self._identifier = identifier
self.activations_model = activations_model
self._visual_degrees = visual_degrees
self.region_layer_map = region_layer_map
self.recorded_regions = []
@property
def identifier(self):
return self._identifier
def look_at(self, stimuli, number_of_trials=1):
layer_regions = {}
for region in self.recorded_regions:
layers = self.region_layer_map[region]
layers = make_list(layers)
for layer in layers:
assert layer not in layer_regions, f"layer {layer} has already been assigned for {layer_regions[layer]}"
layer_regions[layer] = region
activations = self.run_activations(stimuli, layers=list(layer_regions.keys()), number_of_trials=number_of_trials)
activations['region'] = 'neuroid', [layer_regions[layer] for layer in activations['layer'].values]
return activations
def run_activations(self, stimuli, layers, number_of_trials=1):
activations = self.activations_model(stimuli, layers=layers)
return activations
def start_task(self, task):
if task != BrainModel.Task.passive:
raise NotImplementedError()
def start_recording(self, recording_target: BrainModel.RecordingTarget):
self.recorded_regions = [recording_target]
def visual_degrees(self) -> int:
return self._visual_degrees
class LayerSelection:
def __init__(self, model_identifier, activations_model, layers, visual_degrees):
"""
:param model_identifier: this is separate from the container name because it only refers to
the combination of (model, preprocessing), i.e. no mapping.
"""
self.model_identifier = model_identifier
self._layer_scoring = LayerScores(model_identifier=model_identifier, activations_model=activations_model,
visual_degrees=visual_degrees)
self.layers = layers
self._logger = logging.getLogger(fullname(self))
def __call__(self, selection_identifier, benchmark):
# for layer-mapping, attach LayerPCA so that we can cache activations
model_identifier = self.model_identifier
pca_hooked = LayerPCA.is_hooked(self._layer_scoring._activations_model)
if not pca_hooked:
pca_handle = LayerPCA.hook(self._layer_scoring._activations_model, n_components=1000)
identifier = self._layer_scoring._activations_model.identifier
self._layer_scoring._activations_model.identifier = identifier + "-pca_1000"
model_identifier += "-pca_1000"
result = self._call(model_identifier=model_identifier, selection_identifier=selection_identifier,
benchmark=benchmark)
if not pca_hooked:
pca_handle.remove()
self._layer_scoring._activations_model.identifier = identifier
return result
@store(identifier_ignore=['benchmark', 'benchmark'])
def _call(self, model_identifier, selection_identifier, benchmark):
self._logger.debug("Finding best layer")
layer_scores = self._layer_scoring(benchmark=benchmark, benchmark_identifier=selection_identifier,
layers=self.layers, prerun=True)
self._logger.debug("Layer scores (unceiled): " + ", ".join([
f"{layer} -> {layer_scores.raw.sel(layer=layer, aggregation='center').values:.3f}"
f"+-{layer_scores.raw.sel(layer=layer, aggregation='error').values:.3f}"
for layer in layer_scores['layer'].values]))
best_layer = layer_scores['layer'].values[layer_scores.sel(aggregation='center').argmax()]
return best_layer
class LayerScores:
def __init__(self, model_identifier, activations_model, visual_degrees):
self.model_identifier = model_identifier
self._activations_model = activations_model
self._visual_degrees = visual_degrees
self._logger = logging.getLogger(fullname(self))
def __call__(self, benchmark, layers, benchmark_identifier=None, prerun=False):
return self._call(model_identifier=self.model_identifier,
benchmark_identifier=benchmark_identifier or benchmark.identifier,
visual_degrees=self._visual_degrees,
model=self._activations_model, benchmark=benchmark, layers=layers, prerun=prerun)
@store_xarray(identifier_ignore=['model', 'benchmark', 'layers', 'prerun'], combine_fields={'layers': 'layer'})
def _call(self, model_identifier, benchmark_identifier, visual_degrees, # storage fields
model, benchmark, layers, prerun=False):
layer_scores = []
for i, layer in enumerate(tqdm(layers, desc="layers")):
layer_model = self._create_mapped_model(region=benchmark.region, layer=layer, model=model,
model_identifier=model_identifier, visual_degrees=visual_degrees)
layer_model = TemporalIgnore(layer_model)
if i == 0 and prerun: # pre-run activations together to avoid running every layer separately
# we can only pre-run stimuli in response to the benchmark, since we might otherwise be missing
# visual_degrees resizing.
layer_model = PreRunLayers(model=model, layers=layers, forward=layer_model)
score = benchmark(layer_model)
score = score.expand_dims('layer')
score['layer'] = [layer]
layer_scores.append(score)
layer_scores = Score.merge(*layer_scores)
layer_scores = layer_scores.sel(layer=layers) # preserve layer ordering
return layer_scores
def _create_mapped_model(self, region, layer, model, model_identifier, visual_degrees):
return LayerMappedModel(identifier=f"{model_identifier}-{layer}", visual_degrees=visual_degrees,
# per-layer identifier to avoid overlap
activations_model=model, region_layer_map={region: layer})
class PreRunLayers:
def __init__(self, model, layers, forward):
self._model = model
self._layers = layers
self._forward = forward
def look_at(self, stimuli, number_of_trials=1):
self._model(layers=self._layers, stimuli=stimuli)
return self._forward.look_at(stimuli, number_of_trials=number_of_trials)
def __getattr__(self, item):
if item in ['look_at']:
return super(PreRunLayers, self).__getattr__(item)
return getattr(self._forward, item)
|
import os
import sys
import io
import pytz
import yaml
from datetime import datetime
import rx
from rx import operators as ops
from concurrent.futures import ProcessPoolExecutor
from urllib.request import urlopen
from csv import DictReader
from functools import partial
from collections import namedtuple
from rich import print
from rich.progress import Progress
from rich.progress import TextColumn, TimeElapsedColumn, SpinnerColumn
from histdatacom.fx_enums import TimeFormat
from histdatacom.utils import get_csv_dialect
from histdatacom.concurrency import get_pool_cpu_count
from histdatacom.concurrency import ProcessPool
from histdatacom.concurrency import InfluxDBWriter
from histdatacom.api import _API
class _Influx():
def __init__(self, args, records_current_, records_next_, csv_chunks_queue_):
self.args = args
global records_current
records_current = records_current_
global records_next
records_next = records_next_
global csv_chunks_queue
csv_chunks_queue = csv_chunks_queue_
def init_counters(self, csv_chunks_queue_, records_current_, records_next_, args_):
global csv_chunks_queue
csv_chunks_queue = csv_chunks_queue_
global records_current
records_current = records_current_
global records_next
records_next = records_next_
global args
args = args_
def parse_csv_row(self, row, record):
# line protocol example: myMeasurement,tag1=value1,tag2=value2 fieldKey="fieldValue" 1556813561098000000
measurement = f"{record.data_fxpair}"
tags = f"source=histdata.com,format={record.data_format},timeframe={record.data_timeframe}".replace(" ", "")
time = self.convert_datetime_to_utc_timestamp(record.data_format,
record.data_timeframe,
row)
match record.data_timeframe:
case "M1":
fields = f"openbid={row["openBid"]},highbid={row["highBid"]},lowbid={row["lowBid"]},closebid={row["closeBid"]}".replace(" ", "")
case "T":
fields = f"bidquote={row["bidQuote"]},askquote={row["askQuote"]}".replace(" ", "")
line_protocol = f"{measurement},{tags} {fields} {time}"
return line_protocol
def parse_csv_rows(self, rows, record):
mapfunc = partial(self.parse_csv_row, record=record)
_parsed_rows = list(map(mapfunc, rows))
csv_chunks_queue.put(_parsed_rows)
def parse_jay_row(self, row, record):
measurement = f"{record.data_fxpair}"
tags = f"source=histdata.com,format={record.data_format},timeframe={record.data_timeframe}".replace(" ", "")
match record.data_timeframe:
case "M1":
_row = namedtuple('_row', ['datetime', 'open', 'high', 'low', 'close', 'vol'])
named_row = _row(row[0], row[1], row[2], row[3], row[4], row[5])
fields = f"openbid={named_row.open},highbid={named_row.high},lowbid={named_row.low},closebid={named_row.close}".replace(" ", "")
time = str(named_row.datetime)
case "T":
_row = namedtuple('_row', ['datetime','bid','ask','vol'])
named_row = _row(row[0], row[1], row[2], row[3])
fields = f"bidquote={named_row.bid},askquote={named_row.ask}".replace(" ", "")
time = str(named_row.datetime)
line_protocol = f"{measurement},{tags} {fields} {time}"
return line_protocol
def parse_jay_rows(self, iterable, record):
mapfunc = partial(self.parse_jay_row, record=record)
_parsed_rows = list(map(mapfunc, iterable))
csv_chunks_queue.put(_parsed_rows)
def import_file(self, record, args, records_current, records_next, csv_chunks_queue):
try:
if str.lower(record.data_format) == "ascii":
jay_path = f"{record.data_dir}.data"
if os.path.exists(jay_path):
self.import_jay(record, args, records_current, records_next, csv_chunks_queue)
elif "CSV" in record.status:
if "ZIP" in record.status:
_API.test_for_jay_or_create(record, args)
self.import_jay(record, args,
records_current, records_next,
csv_chunks_queue)
else:
self.import_csv(record, args,
records_current, records_next,
csv_chunks_queue)
records_next.put(record)
except Exception:
print("Unexpected error from here:", sys.exc_info())
record.delete_into_file()
raise
finally:
records_current.task_done()
def import_jay(self, record, args, records_current, records_next, csv_chunks_queue):
jay = _API.import_jay_data(record.data_dir + record.jay_filename)
with ProcessPoolExecutor(max_workers=2,
initializer=self.init_counters,
initargs=(csv_chunks_queue,
records_current,
records_next,
self.args.copy())) as executor:
data = rx.from_iterable(jay.to_tuples()) \
.pipe(ops.buffer_with_count(25_000),
ops.flat_map(
lambda rows: executor.submit(self.parse_jay_rows, rows, record)))
data.subscribe(
on_next=lambda x: None,
on_error=lambda er: print(f"Unexpected error: {er}"))
record.status = "INFLUX_UPLOAD"
record.write_info_file(base_dir=args['default_download_dir'])
def import_csv(self, record, args, records_current, records_next, csv_chunks_queue):
csv_path = record.data_dir + record.csv_filename
file_endpoint = f"file://{record.data_dir}{record.csv_filename}"
res = urlopen(file_endpoint)
io_wrapper = io.TextIOWrapper(res)
with ProcessPoolExecutor(max_workers=2,
initializer=self.init_counters,
initargs=(csv_chunks_queue,
records_current,
records_next,
self.args.copy())) as executor:
fieldnames = self.fieldnames_match(record.data_format, record.data_timeframe)
dialect = get_csv_dialect(csv_path)
data = rx.from_iterable(
DictReader(io_wrapper,
fieldnames=fieldnames,
dialect=dialect)) \
.pipe(
ops.buffer_with_count(25_000),
ops.flat_map(
lambda rows: executor.submit(self.parse_csv_rows, rows, record)))
data.subscribe(
on_next=lambda x: None,
on_error=lambda er: print(f"Unexpected error: {er}"))
os.remove(csv_path)
record.status = "INFLUX_UPLOAD"
record.write_info_file(base_dir=args['default_download_dir'])
def import_data(self, records_current, records_next, csv_chunks_queue):
writer = InfluxDBWriter(self.args, csv_chunks_queue)
writer.start()
pool = ProcessPool(self.import_file,
self.args,
"Adding", "CSVs to influx queue...",
get_pool_cpu_count(self.args['cpu_utilization']) - 1\
if get_pool_cpu_count(self.args['cpu_utilization']) >= 2 \
else 1,
join=False,
dump=False)
pool(records_current, records_next, csv_chunks_queue)
with Progress(TextColumn(text_format="[cyan]...finishing upload to influxdb"),
SpinnerColumn(), SpinnerColumn(), SpinnerColumn(),
TimeElapsedColumn()) as progress:
task_id = progress.add_task("waiting", total=0)
records_current.join()
csv_chunks_queue.put(None)
csv_chunks_queue.join()
progress.advance(task_id, 0.75)
print("[cyan] done.")
records_next.dump_to_queue(records_current)
@classmethod
def load_influx_yaml(cls):
if os.path.exists('influxdb.yaml'):
with open('influxdb.yaml', 'r') as file:
try:
yamlfile = yaml.safe_load(file)
except yaml.YAMLError as exc:
print(exc)
sys.exit()
return yamlfile
print(""" ERROR: -I flag is used to import data to a influxdb instance...
there is no influxdb.yaml file in working directory.
did you forget to set it up?
""")
sys.exit()
@classmethod
def fieldnames_match(cls, csv_format, timeframe):
try:
match csv_format:
case "ASCII" if timeframe == "M1":
fieldnames = ["msSinceEpochUTC", "openBid", "highBid", "lowBid", "closeBid", "Volume"]
case "ASCII" if timeframe == "T":
fieldnames = ["msSinceEpochUTC", "bidQuote", "askQuote", "Volume"]
case _:
raise ValueError("Invalid format for influx import")
return fieldnames
except ValueError as err:
print(err)
sys.exit()
@classmethod
def get_timeformat(cls, csv_format, timeframe):
format_enum_key = f'{str(csv_format)}_{str(timeframe)}'
return TimeFormat[format_enum_key].value
@classmethod
def convert_datetime_to_utc_timestamp(cls, csv_format, timeframe, row):
est_timestamp = row["msSinceEpochUTC"]
date_object = datetime.strptime(est_timestamp, cls.get_timeformat(csv_format, timeframe))
tz_date_object = date_object.replace(tzinfo=pytz.timezone("Etc/GMT-5"))
timestamp = int(tz_date_object.timestamp() * 1000)
return str(timestamp)
| import os
import sys
import io
import pytz
import yaml
from datetime import datetime
import rx
from rx import operators as ops
from concurrent.futures import ProcessPoolExecutor
from urllib.request import urlopen
from csv import DictReader
from functools import partial
from collections import namedtuple
from rich import print
from rich.progress import Progress
from rich.progress import TextColumn, TimeElapsedColumn, SpinnerColumn
from histdatacom.fx_enums import TimeFormat
from histdatacom.utils import get_csv_dialect
from histdatacom.concurrency import get_pool_cpu_count
from histdatacom.concurrency import ProcessPool
from histdatacom.concurrency import InfluxDBWriter
from histdatacom.api import _API
class _Influx():
def __init__(self, args, records_current_, records_next_, csv_chunks_queue_):
self.args = args
global records_current
records_current = records_current_
global records_next
records_next = records_next_
global csv_chunks_queue
csv_chunks_queue = csv_chunks_queue_
def init_counters(self, csv_chunks_queue_, records_current_, records_next_, args_):
global csv_chunks_queue
csv_chunks_queue = csv_chunks_queue_
global records_current
records_current = records_current_
global records_next
records_next = records_next_
global args
args = args_
def parse_csv_row(self, row, record):
# line protocol example: myMeasurement,tag1=value1,tag2=value2 fieldKey="fieldValue" 1556813561098000000
measurement = f"{record.data_fxpair}"
tags = f"source=histdata.com,format={record.data_format},timeframe={record.data_timeframe}".replace(" ", "")
time = self.convert_datetime_to_utc_timestamp(record.data_format,
record.data_timeframe,
row)
match record.data_timeframe:
case "M1":
fields = f"openbid={row['openBid']},highbid={row['highBid']},lowbid={row['lowBid']},closebid={row['closeBid']}".replace(" ", "")
case "T":
fields = f"bidquote={row['bidQuote']},askquote={row['askQuote']}".replace(" ", "")
line_protocol = f"{measurement},{tags} {fields} {time}"
return line_protocol
def parse_csv_rows(self, rows, record):
mapfunc = partial(self.parse_csv_row, record=record)
_parsed_rows = list(map(mapfunc, rows))
csv_chunks_queue.put(_parsed_rows)
def parse_jay_row(self, row, record):
measurement = f"{record.data_fxpair}"
tags = f"source=histdata.com,format={record.data_format},timeframe={record.data_timeframe}".replace(" ", "")
match record.data_timeframe:
case "M1":
_row = namedtuple('_row', ['datetime', 'open', 'high', 'low', 'close', 'vol'])
named_row = _row(row[0], row[1], row[2], row[3], row[4], row[5])
fields = f"openbid={named_row.open},highbid={named_row.high},lowbid={named_row.low},closebid={named_row.close}".replace(" ", "")
time = str(named_row.datetime)
case "T":
_row = namedtuple('_row', ['datetime','bid','ask','vol'])
named_row = _row(row[0], row[1], row[2], row[3])
fields = f"bidquote={named_row.bid},askquote={named_row.ask}".replace(" ", "")
time = str(named_row.datetime)
line_protocol = f"{measurement},{tags} {fields} {time}"
return line_protocol
def parse_jay_rows(self, iterable, record):
mapfunc = partial(self.parse_jay_row, record=record)
_parsed_rows = list(map(mapfunc, iterable))
csv_chunks_queue.put(_parsed_rows)
def import_file(self, record, args, records_current, records_next, csv_chunks_queue):
try:
if str.lower(record.data_format) == "ascii":
jay_path = f"{record.data_dir}.data"
if os.path.exists(jay_path):
self.import_jay(record, args, records_current, records_next, csv_chunks_queue)
elif "CSV" in record.status:
if "ZIP" in record.status:
_API.test_for_jay_or_create(record, args)
self.import_jay(record, args,
records_current, records_next,
csv_chunks_queue)
else:
self.import_csv(record, args,
records_current, records_next,
csv_chunks_queue)
records_next.put(record)
except Exception:
print("Unexpected error from here:", sys.exc_info())
record.delete_into_file()
raise
finally:
records_current.task_done()
def import_jay(self, record, args, records_current, records_next, csv_chunks_queue):
jay = _API.import_jay_data(record.data_dir + record.jay_filename)
with ProcessPoolExecutor(max_workers=2,
initializer=self.init_counters,
initargs=(csv_chunks_queue,
records_current,
records_next,
self.args.copy())) as executor:
data = rx.from_iterable(jay.to_tuples()) \
.pipe(ops.buffer_with_count(25_000),
ops.flat_map(
lambda rows: executor.submit(self.parse_jay_rows, rows, record)))
data.subscribe(
on_next=lambda x: None,
on_error=lambda er: print(f"Unexpected error: {er}"))
record.status = "INFLUX_UPLOAD"
record.write_info_file(base_dir=args['default_download_dir'])
def import_csv(self, record, args, records_current, records_next, csv_chunks_queue):
csv_path = record.data_dir + record.csv_filename
file_endpoint = f"file://{record.data_dir}{record.csv_filename}"
res = urlopen(file_endpoint)
io_wrapper = io.TextIOWrapper(res)
with ProcessPoolExecutor(max_workers=2,
initializer=self.init_counters,
initargs=(csv_chunks_queue,
records_current,
records_next,
self.args.copy())) as executor:
fieldnames = self.fieldnames_match(record.data_format, record.data_timeframe)
dialect = get_csv_dialect(csv_path)
data = rx.from_iterable(
DictReader(io_wrapper,
fieldnames=fieldnames,
dialect=dialect)) \
.pipe(
ops.buffer_with_count(25_000),
ops.flat_map(
lambda rows: executor.submit(self.parse_csv_rows, rows, record)))
data.subscribe(
on_next=lambda x: None,
on_error=lambda er: print(f"Unexpected error: {er}"))
os.remove(csv_path)
record.status = "INFLUX_UPLOAD"
record.write_info_file(base_dir=args['default_download_dir'])
def import_data(self, records_current, records_next, csv_chunks_queue):
writer = InfluxDBWriter(self.args, csv_chunks_queue)
writer.start()
pool = ProcessPool(self.import_file,
self.args,
"Adding", "CSVs to influx queue...",
get_pool_cpu_count(self.args['cpu_utilization']) - 1\
if get_pool_cpu_count(self.args['cpu_utilization']) >= 2 \
else 1,
join=False,
dump=False)
pool(records_current, records_next, csv_chunks_queue)
with Progress(TextColumn(text_format="[cyan]...finishing upload to influxdb"),
SpinnerColumn(), SpinnerColumn(), SpinnerColumn(),
TimeElapsedColumn()) as progress:
task_id = progress.add_task("waiting", total=0)
records_current.join()
csv_chunks_queue.put(None)
csv_chunks_queue.join()
progress.advance(task_id, 0.75)
print("[cyan] done.")
records_next.dump_to_queue(records_current)
@classmethod
def load_influx_yaml(cls):
if os.path.exists('influxdb.yaml'):
with open('influxdb.yaml', 'r') as file:
try:
yamlfile = yaml.safe_load(file)
except yaml.YAMLError as exc:
print(exc)
sys.exit()
return yamlfile
print(""" ERROR: -I flag is used to import data to a influxdb instance...
there is no influxdb.yaml file in working directory.
did you forget to set it up?
""")
sys.exit()
@classmethod
def fieldnames_match(cls, csv_format, timeframe):
try:
match csv_format:
case "ASCII" if timeframe == "M1":
fieldnames = ["msSinceEpochUTC", "openBid", "highBid", "lowBid", "closeBid", "Volume"]
case "ASCII" if timeframe == "T":
fieldnames = ["msSinceEpochUTC", "bidQuote", "askQuote", "Volume"]
case _:
raise ValueError("Invalid format for influx import")
return fieldnames
except ValueError as err:
print(err)
sys.exit()
@classmethod
def get_timeformat(cls, csv_format, timeframe):
format_enum_key = f'{str(csv_format)}_{str(timeframe)}'
return TimeFormat[format_enum_key].value
@classmethod
def convert_datetime_to_utc_timestamp(cls, csv_format, timeframe, row):
est_timestamp = row["msSinceEpochUTC"]
date_object = datetime.strptime(est_timestamp, cls.get_timeformat(csv_format, timeframe))
tz_date_object = date_object.replace(tzinfo=pytz.timezone("Etc/GMT-5"))
timestamp = int(tz_date_object.timestamp() * 1000)
return str(timestamp)
|
import urllib.request
from invoke import task
import json
import os
import logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def download_releases(base_dir, repo, target_dir):
if not base_dir:
base_dir = f"../release"
asset_dir = f"{base_dir}/{target_dir}"
if not os.path.exists(asset_dir):
os.makedirs(asset_dir)
release_json_path = f'{asset_dir}/releases.json'
urllib.request.urlretrieve(
f"https://api.github.com/repos/{repo}/releases", filename=release_json_path)
with open(release_json_path) as json_file:
tags = json.load(json_file)
logger.info(f"{release_json_path} downloaded")
for tag in tags:
if not tag['prerelease']:
tag_dir = f"{asset_dir}/{tag["tag_name"]}"
if not os.path.exists(tag_dir):
os.makedirs(tag_dir)
for asset in tag['assets']:
asset_path = f"{tag_dir}/{asset["name"]}"
if not os.path.exists(asset_path):
download_url = asset['browser_download_url']
logger.info(f"start to request {download_url}")
urllib.request.urlretrieve(
download_url, filename=asset_path)
else:
logger.debug(f"skip to download {asset_path}")
@task
def sync_release(c, base_dir=None, repo=None, target=None):
download_releases(base_dir, repo, target)
| import urllib.request
from invoke import task
import json
import os
import logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def download_releases(base_dir, repo, target_dir):
if not base_dir:
base_dir = f"../release"
asset_dir = f"{base_dir}/{target_dir}"
if not os.path.exists(asset_dir):
os.makedirs(asset_dir)
release_json_path = f'{asset_dir}/releases.json'
urllib.request.urlretrieve(
f"https://api.github.com/repos/{repo}/releases", filename=release_json_path)
with open(release_json_path) as json_file:
tags = json.load(json_file)
logger.info(f"{release_json_path} downloaded")
for tag in tags:
if not tag['prerelease']:
tag_dir = f"{asset_dir}/{tag['tag_name']}"
if not os.path.exists(tag_dir):
os.makedirs(tag_dir)
for asset in tag['assets']:
asset_path = f"{tag_dir}/{asset['name']}"
if not os.path.exists(asset_path):
download_url = asset['browser_download_url']
logger.info(f"start to request {download_url}")
urllib.request.urlretrieve(
download_url, filename=asset_path)
else:
logger.debug(f"skip to download {asset_path}")
@task
def sync_release(c, base_dir=None, repo=None, target=None):
download_releases(base_dir, repo, target)
|
##############################################################################
# Copyright by The HDF Group. #
# All rights reserved. #
# #
# This file is part of HSDS (HDF5 Scalable Data Service), Libraries and #
# Utilities. The full HSDS copyright notice, including #
# terms governing use, modification, and redistribution, is contained in #
# the file COPYING, which can be found at the root of the source code #
# distribution tree. If you do not have access to this file, you may #
# request a copy from help@hdfgroup.org. #
##############################################################################
import sys
import aiohttp
import logging
import asyncio
try:
import h5py
import h5pyd
import numpy as np
except ImportError as e:
sys.stderr.write("ERROR : %s : install it to use this utility...\n" % str(e))
sys.exit(1)
if __name__ == "utillib":
from chunkiter import ChunkIterator
else:
from .chunkiter import ChunkIterator
def dump_dtype(dt):
if not isinstance(dt, np.dtype):
raise TypeError("expected np.dtype, but got: {}".format(type(dt)))
if len(dt) > 0:
out = "{"
for name in dt.fields:
subdt = dt.fields[name][0]
out += "{}: {} |".format(name, dump_dtype(subdt))
out = out[:-1] + "}"
else:
ref = h5py.check_dtype(ref=dt)
if ref:
out = str(ref)
else:
vlen = h5py.check_dtype(vlen=dt)
if vlen:
out = "VLEN: " + dump_dtype(vlen)
else:
out = str(dt)
return out
def is_h5py(obj):
# Return True if objref is a h5py object and False is not
if isinstance(obj, object) and isinstance(obj.id.id, int):
return True
else:
return False
def is_reference(val):
try:
if isinstance(val, object) and val.__class__.__name__ == "Reference":
return True
elif isinstance(val, type) and val.__name__ == "Reference":
return True
except AttributeError as ae:
msg = "is_reference for {} error: {}".format(val, ae)
logging.error(msg)
return False
def is_regionreference(val):
try:
if isinstance(val, object) and val.__class__.__name__ == "RegionReference":
return True
elif isinstance(val, type) and val.__name__ == "RegionReference":
return True
except AttributeError as ae:
msg = "is_reference for {} error: {}".format(val, ae)
logging.error(msg)
return False
def has_reference(dtype):
has_ref = False
if len(dtype) > 0:
for name in dtype.fields:
item = dtype.fields[name]
if has_reference(item[0]):
has_ref = True
break
elif dtype.metadata and 'ref' in dtype.metadata:
basedt = dtype.metadata['ref']
has_ref = is_reference(basedt)
elif dtype.metadata and 'vlen' in dtype.metadata:
basedt = dtype.metadata['vlen']
has_ref = has_reference(basedt)
return has_ref
def convert_dtype(srcdt, ctx):
""" Return a dtype based on input dtype, converting any Reference types from
h5py style to h5pyd and vice-versa.
"""
msg = "convert dtype: {}, type: {},".format(srcdt, type(srcdt))
logging.info(msg)
if len(srcdt) > 0:
fields = []
for name in srcdt.fields:
item = srcdt.fields[name]
# item is a tuple of dtype and integer offset
field_dt = convert_dtype(item[0], ctx)
fields.append((name, field_dt))
tgt_dt = np.dtype(fields)
else:
# check if this a "special dtype"
if srcdt.metadata and 'ref' in srcdt.metadata:
ref = srcdt.metadata['ref']
if is_reference(ref):
if is_h5py(ctx['fout']):
tgt_dt = h5py.special_dtype(ref=h5py.Reference)
else:
tgt_dt = h5pyd.special_dtype(ref=h5pyd.Reference)
elif is_regionreference(ref):
if is_h5py(ctx['fout']):
tgt_dt = h5py.special_dtype(ref=h5py.RegionReference)
else:
tgt_dt = h5py.special_dtype(ref=h5py.RegionReference)
else:
msg = "Unexpected ref type: {}".format(srcdt)
logging.error(msg)
raise TypeError(msg)
elif srcdt.metadata and 'vlen' in srcdt.metadata:
src_vlen = srcdt.metadata['vlen']
if isinstance(src_vlen, np.dtype):
tgt_base = convert_dtype(src_vlen, ctx)
else:
tgt_base = src_vlen
if is_h5py(ctx['fout']):
tgt_dt = h5py.special_dtype(vlen=tgt_base)
else:
tgt_dt = h5pyd.special_dtype(vlen=tgt_base)
else:
tgt_dt = srcdt
return tgt_dt
#----------------------------------------------------------------------------------
def copy_element(val, src_dt, tgt_dt, ctx):
logging.debug("copy_element, val: " + str(val) + " val type: " + str(type(val)) + "src_dt: " + dump_dtype(src_dt) + " tgt_dt: " + dump_dtype(tgt_dt))
fin = ctx["fin"]
fout = ctx["fout"]
out = None
if len(src_dt) > 0:
out_fields = []
i = 0
for name in src_dt.fields:
field_src_dt = src_dt.fields[name][0]
field_tgt_dt = tgt_dt.fields[name][0]
field_val = val[i]
i += 1
out_field = copy_element(field_val, field_src_dt, field_tgt_dt, ctx)
out_fields.append(out_field)
out = tuple(out_fields)
elif src_dt.metadata and 'ref' in src_dt.metadata:
if not tgt_dt.metadata or 'ref' not in tgt_dt.metadata:
raise TypeError("Expected tgt dtype to be ref, but got: {}".format(tgt_dt))
ref = tgt_dt.metadata['ref']
if is_reference(ref):
# initialize out to null ref
if is_h5py(ctx['fout']):
out = h5py.Reference() # null h5py ref
else:
out = '' # h5pyd refs are strings
if ref:
try:
fin_obj = fin[val]
except AttributeError as ae:
msg = "Unable able to get obj for ref value: {}".format(ae)
logging.error(msg)
print(msg)
return None
# TBD - for hsget, the name property is not getting set
h5path = fin_obj.name
if not h5path:
msg = "No path found for ref object"
logging.warn(msg)
if ctx["verbose"]:
print(msg)
else:
fout_obj = fout[h5path]
if is_h5py(ctx['fout']):
out = fout_obj.ref
else:
out = str(fout_obj.ref) # convert to string for JSON serialization
elif is_regionreference(ref):
out = "tbd"
else:
raise TypeError("Unexpected ref type: {}".format(type(ref)))
elif src_dt.metadata and 'vlen' in src_dt.metadata:
logging.debug("copy_elment, got vlen element, dt: {}".format(src_dt.metadata["vlen"]))
if not isinstance(val, np.ndarray):
raise TypeError("Expecting ndarray or vlen element, but got: {}".format(type(val)))
if not tgt_dt.metadata or 'vlen' not in tgt_dt.metadata:
raise TypeError("Expected tgt dtype to be vlen, but got: {}".format(tgt_dt))
src_vlen_dt = src_dt.metadata["vlen"]
tgt_vlen_dt = tgt_dt.metadata["vlen"]
if has_reference(src_vlen_dt):
if len(val.shape) == 0:
# scalar array
e = val[()]
v = copy_element(e, src_vlen_dt, tgt_vlen_dt, ctx)
out = np.array(v, dtype=tgt_dt)
else:
out = np.zeros(val.shape, dtype=tgt_dt)
for i in range(len(out)):
e = val[i]
out[i] = copy_element(e, src_vlen_dt, tgt_vlen_dt, ctx)
else:
# can just directly copy the array
out = np.zeros(val.shape, dtype=tgt_dt)
out[...] = val[...]
else:
out = val # can just copy as is
return out
#----------------------------------------------------------------------------------
def copy_array(src_arr, ctx):
""" Copy the numpy array to a new array.
Convert any reference type to point to item in the target's hierarchy.
"""
if not isinstance(src_arr, np.ndarray):
raise TypeError("Expecting ndarray, but got: {}".format(src_arr))
tgt_dt = convert_dtype(src_arr.dtype, ctx)
tgt_arr = np.zeros(src_arr.shape, dtype=tgt_dt)
if has_reference(src_arr.dtype):
# flatten array to simplify iteration
count = np.product(src_arr.shape)
tgt_arr_flat = tgt_arr.reshape((count,))
src_arr_flat = src_arr.reshape((count,))
for i in range(count):
element = copy_element(src_arr_flat[i], src_arr.dtype, tgt_dt, ctx)
tgt_arr_flat[i] = element
tgt_arr = tgt_arr_flat.reshape(src_arr.shape)
else:
# can just copy the entire array
tgt_arr[...] = src_arr[...]
return tgt_arr
#----------------------------------------------------------------------------------
def copy_attribute(desobj, name, srcobj, ctx):
msg = "creating attribute {} in {}".format(name, srcobj.name)
logging.debug(msg)
if ctx["verbose"]:
print(msg)
try:
srcarr = srcobj.attrs[name]
if isinstance(srcarr, np.ndarray):
tgtarr = copy_array(srcarr, ctx)
desobj.attrs.create(name, tgtarr)
else:
# scalars are just read as the native type
desobj.attrs.create(name, srcarr)
except (IOError, TypeError) as e:
msg = "ERROR: failed to create attribute {} of object {} -- {}".format(name, desobj.name, str(e))
logging.error(msg)
print(msg)
# copy_attribute
#----------------------------------------------------------------------------------
def create_dataset(dobj, ctx):
""" create a dataset using the properties of the passed in h5py dataset.
If successful, proceed to copy attributes and data.
"""
msg = "creating dataset {}, shape: {}, type: {}".format(dobj.name, dobj.shape, dobj.dtype)
logging.info(msg)
if ctx["verbose"]:
print(msg)
fout = ctx["fout"]
deflate = ctx["deflate"]
fillvalue = None
try:
# can trigger a runtime error if fillvalue is undefined
fillvalue = dobj.fillvalue
except RuntimeError:
pass # ignore
chunks=None
if dobj.chunks:
chunks = tuple(dobj.chunks)
try:
tgt_dtype = convert_dtype(dobj.dtype, ctx)
compression_filter = dobj.compression
compression_opts = dobj.compression_opts
if deflate is not None and compression_filter is None:
compression_filter = "gzip"
compression_opts = deflate
if ctx["verbose"]:
print("applying gzip filter with level: {}".format(deflate))
dset = fout.create_dataset( dobj.name, shape=dobj.shape, dtype=tgt_dtype, chunks=chunks, \
compression=compression_filter, shuffle=dobj.shuffle, \
fletcher32=dobj.fletcher32, maxshape=dobj.maxshape, \
compression_opts=compression_opts, fillvalue=fillvalue, \
scaleoffset=dobj.scaleoffset)
msg = "dataset created, uuid: {}, chunk_size: {}".format(dset.id.id, str(dset.chunks))
logging.info(msg)
if ctx["verbose"]:
print(msg)
except (IOError, TypeError, KeyError) as e:
msg = "ERROR: failed to create dataset: {}".format(str(e))
logging.error(msg)
print(msg)
return
# create_dataset
#----------------------------------------------------------------------------------
def write_dataset(src, tgt, ctx):
""" write values from src dataset to target dataset.
"""
msg = "write_dataset src: {} to tgt: {}, shape: {}, type: {}".format(src.name, tgt.name, src.shape, src.dtype)
logging.info(msg)
domain = tgt.file.filename
dsetid = tgt.id.id
msg = f"domain: {domain} dsetid: {dsetid}"
logging.info(msg)
if ctx["verbose"]:
print(msg)
if src.shape is None:
# null space dataset
msg = "no data for null space dataset: {}".format(src.name)
logging.info(msg)
if ctx["verbose"]:
print(msg)
return # no data
if len(src.shape) == 0:
# scalar dataset
x = src[()]
msg = "writing: {} for scalar dataset: {}".format(x, src.name)
logging.info(msg)
if ctx["verbose"]:
print(msg)
tgt[()] = x
return
msg = "iterating over chunks for {}".format(src.name)
logging.info(msg)
if ctx["verbose"]:
print(msg)
url = f"{ctx["endpoint"]}/datasets/{dsetid}/value"
logging.debug(f"url: {url}")
loop = ctx["loop"]
session = ctx["session"]
try:
it = ChunkIterator(tgt)
futures = []
for s in it:
msg = "writing dataset data for slice: {}".format(s)
logging.info(msg)
if ctx["verbose"]:
print(msg)
arr = src[s]
selection = getSliceQueryParam(s)
logging.debug(f"select:{selection}")
params = {}
params["domain"] = domain
params["select"] = selection
futures.append(write_chunk(session, url, params, arr))
if len(futures) >= ctx["maxtasks"]:
loop.run_until_complete(asyncio.gather(*futures))
futures = []
# send off any remaining chnks
loop.run_until_complete(asyncio.gather(*futures))
except Exception as e:
logging.error(f"got Exception: {e}")
msg = "done with dataload for {}".format(src.name)
logging.info(msg)
if ctx["verbose"]:
print(msg)
# write_dataset
# construct HSDS query param from selection
def getSliceQueryParam(sel):
sel_param="["
if isinstance(sel, tuple):
for s in sel:
if len(sel_param) > 1:
sel_param += ","
sel_param += f"{s.start}:{s.stop}"
else:
sel_param += f"{sel.start}:{sel.stop}"
sel_param += "]"
return sel_param
async def write_chunk(session, url, params, arr):
# TBD: do normal h5yd write for vlen data
msg = f"writing chunk for slice: {params["select"]}"
logging.info(msg)
data = arr.tobytes()
try:
async with session.put(url, data=data, params=params) as rsp:
logging.info("status: {}".format(rsp.status))
if rsp.status != 200:
raise IOError(f"expected status 200 but got {rsp.status}")
except ConnectionError as ce:
logging.error("connection error: {}".format(ce))
raise IOError("Connection Error")
#logging.info(msg)
#self.PUT(req, body=body, format=format, params=params)
#----------------------------------------------------------------------------------
def create_links(gsrc, gdes, ctx):
# add soft and external links
if ctx["verbose"]:
print("create_links: {}".format(gsrc.name))
for title in gsrc:
if ctx["verbose"]:
print("got link: {}".format(title))
lnk = gsrc.get(title, getlink=True)
link_classname = lnk.__class__.__name__
if link_classname == "HardLink":
logging.debug("Got hardlink: {}".format(title))
# TBD: handle the case where multiple hardlinks point to same object
elif link_classname == "SoftLink":
msg = "creating SoftLink({}) with title: {}".format(lnk.path, title)
if ctx["verbose"]:
print(msg)
logging.info(msg)
if is_h5py(gdes):
soft_link = h5py.SoftLink(lnk.path)
else:
soft_link = h5pyd.SoftLink(lnk.path)
gdes[title] = soft_link
elif link_classname == "ExternalLink":
msg = "creating ExternalLink({}, {}) with title: {}".format(lnk.filename, lnk.path, title)
if ctx["verbose"]:
print(msg)
logging.info(msg)
if is_h5py(gdes):
ext_link = h5py.ExternalLink(lnk.filename, lnk.path)
else:
ext_link = h5pyd.ExternalLink(lnk.filename, lnk.path)
gdes[title] = ext_link
else:
msg = "Unexpected link type: {}".format(lnk.__class__.__name__)
logging.warning(msg)
if ctx["verbose"]:
print(msg)
def create_group(gobj, ctx):
msg = "creating group {}".format(gobj.name)
logging.info(msg)
if ctx["verbose"]:
print(msg)
fout = ctx["fout"]
grp = fout.create_group(gobj.name)
# create any soft/external links
create_links(gobj, grp, ctx)
# create_group
#----------------------------------------------------------------------------------
def create_datatype(obj, ctx):
msg = "creating datatype {}".format(obj.name)
logging.info(msg)
if ctx["verbose"]:
print(msg)
fout = ctx["fout"]
fout[obj.name] = obj.dtype
# create_datatype
#----------------------------------------------------------------------------------
def load_file(fin, fout, verbose=False, nodata=False, deflate=None, endpoint=None, username=None, password=None, maxtasks=10):
logging.info("input file: {}".format(fin.filename))
logging.info("output file: {}".format(fout.filename))
print(f"load_file, maxtasks: {maxtasks}")
# it would be nice to make a class out of these functions, but that
# makes it heard to use visititems iterator.
# instead, create a context object to pass arround common state
ctx = {}
ctx["fin"] = fin
ctx["fout"] = fout
ctx["verbose"] = verbose
ctx["nodata"] = nodata
ctx["deflate"] = deflate
ctx["endpoint"] = endpoint
ctx["username"] = username
ctx["password"] = password
ctx["maxtasks"] = maxtasks
loop = asyncio.get_event_loop()
ctx["loop"] = loop
connector = aiohttp.TCPConnector(limit=maxtasks)
auth = aiohttp.BasicAuth(login=username, password=password)
headers = {'Content-Type': "application/octet-stream" }
session = aiohttp.ClientSession(auth=auth, headers=headers, loop=loop, connector=connector)
ctx["session"] = session
# create any root attributes
for ga in fin.attrs:
copy_attribute(fout, ga, fin, ctx)
# create root soft/external links
create_links(fin, fout, ctx)
def object_create_helper(name, obj):
class_name = obj.__class__.__name__
if class_name == "Dataset":
create_dataset(obj, ctx)
elif class_name == "Group":
create_group(obj, ctx)
elif class_name == "Datatype":
create_datatype(obj, ctx)
else:
logging.error("no handler for object class: {}".format(type(obj)))
def object_copy_helper(name, obj):
class_name = obj.__class__.__name__
if class_name == "Dataset":
tgt = fout[obj.name]
write_dataset(obj, tgt, ctx)
elif class_name == "Group":
logging.debug("skip copy for group: {}".format(obj.name))
elif class_name == "Datatype":
logging.debug("skip copy for datatype: {}".format(obj.name))
else:
logging.error("no handler for object class: {}".format(type(obj)))
def object_attribute_helper(name, obj):
tgt = fout[obj.name]
for ga in obj.attrs:
copy_attribute(tgt, ga, obj, ctx)
# build a rough map of the file using the internal function above
fin.visititems(object_create_helper)
# copy over any attributes
fin.visititems(object_attribute_helper)
if not nodata:
# copy dataset data
fin.visititems(object_copy_helper)
# Fully flush the h5py handle.
fout.close()
# close up the source domain, see reason(s) for this below
fin.close()
if verbose:
print("closing session")
loop.run_until_complete(session.close())
if verbose:
print("closing connector")
connector.close()
if verbose:
print("closing loop")
loop = ctx["loop"]
loop.close()
msg="load_file complete"
logging.info(msg)
if verbose:
print(msg)
return 0
# load_file
| ##############################################################################
# Copyright by The HDF Group. #
# All rights reserved. #
# #
# This file is part of HSDS (HDF5 Scalable Data Service), Libraries and #
# Utilities. The full HSDS copyright notice, including #
# terms governing use, modification, and redistribution, is contained in #
# the file COPYING, which can be found at the root of the source code #
# distribution tree. If you do not have access to this file, you may #
# request a copy from help@hdfgroup.org. #
##############################################################################
import sys
import aiohttp
import logging
import asyncio
try:
import h5py
import h5pyd
import numpy as np
except ImportError as e:
sys.stderr.write("ERROR : %s : install it to use this utility...\n" % str(e))
sys.exit(1)
if __name__ == "utillib":
from chunkiter import ChunkIterator
else:
from .chunkiter import ChunkIterator
def dump_dtype(dt):
if not isinstance(dt, np.dtype):
raise TypeError("expected np.dtype, but got: {}".format(type(dt)))
if len(dt) > 0:
out = "{"
for name in dt.fields:
subdt = dt.fields[name][0]
out += "{}: {} |".format(name, dump_dtype(subdt))
out = out[:-1] + "}"
else:
ref = h5py.check_dtype(ref=dt)
if ref:
out = str(ref)
else:
vlen = h5py.check_dtype(vlen=dt)
if vlen:
out = "VLEN: " + dump_dtype(vlen)
else:
out = str(dt)
return out
def is_h5py(obj):
# Return True if objref is a h5py object and False is not
if isinstance(obj, object) and isinstance(obj.id.id, int):
return True
else:
return False
def is_reference(val):
try:
if isinstance(val, object) and val.__class__.__name__ == "Reference":
return True
elif isinstance(val, type) and val.__name__ == "Reference":
return True
except AttributeError as ae:
msg = "is_reference for {} error: {}".format(val, ae)
logging.error(msg)
return False
def is_regionreference(val):
try:
if isinstance(val, object) and val.__class__.__name__ == "RegionReference":
return True
elif isinstance(val, type) and val.__name__ == "RegionReference":
return True
except AttributeError as ae:
msg = "is_reference for {} error: {}".format(val, ae)
logging.error(msg)
return False
def has_reference(dtype):
has_ref = False
if len(dtype) > 0:
for name in dtype.fields:
item = dtype.fields[name]
if has_reference(item[0]):
has_ref = True
break
elif dtype.metadata and 'ref' in dtype.metadata:
basedt = dtype.metadata['ref']
has_ref = is_reference(basedt)
elif dtype.metadata and 'vlen' in dtype.metadata:
basedt = dtype.metadata['vlen']
has_ref = has_reference(basedt)
return has_ref
def convert_dtype(srcdt, ctx):
""" Return a dtype based on input dtype, converting any Reference types from
h5py style to h5pyd and vice-versa.
"""
msg = "convert dtype: {}, type: {},".format(srcdt, type(srcdt))
logging.info(msg)
if len(srcdt) > 0:
fields = []
for name in srcdt.fields:
item = srcdt.fields[name]
# item is a tuple of dtype and integer offset
field_dt = convert_dtype(item[0], ctx)
fields.append((name, field_dt))
tgt_dt = np.dtype(fields)
else:
# check if this a "special dtype"
if srcdt.metadata and 'ref' in srcdt.metadata:
ref = srcdt.metadata['ref']
if is_reference(ref):
if is_h5py(ctx['fout']):
tgt_dt = h5py.special_dtype(ref=h5py.Reference)
else:
tgt_dt = h5pyd.special_dtype(ref=h5pyd.Reference)
elif is_regionreference(ref):
if is_h5py(ctx['fout']):
tgt_dt = h5py.special_dtype(ref=h5py.RegionReference)
else:
tgt_dt = h5py.special_dtype(ref=h5py.RegionReference)
else:
msg = "Unexpected ref type: {}".format(srcdt)
logging.error(msg)
raise TypeError(msg)
elif srcdt.metadata and 'vlen' in srcdt.metadata:
src_vlen = srcdt.metadata['vlen']
if isinstance(src_vlen, np.dtype):
tgt_base = convert_dtype(src_vlen, ctx)
else:
tgt_base = src_vlen
if is_h5py(ctx['fout']):
tgt_dt = h5py.special_dtype(vlen=tgt_base)
else:
tgt_dt = h5pyd.special_dtype(vlen=tgt_base)
else:
tgt_dt = srcdt
return tgt_dt
#----------------------------------------------------------------------------------
def copy_element(val, src_dt, tgt_dt, ctx):
logging.debug("copy_element, val: " + str(val) + " val type: " + str(type(val)) + "src_dt: " + dump_dtype(src_dt) + " tgt_dt: " + dump_dtype(tgt_dt))
fin = ctx["fin"]
fout = ctx["fout"]
out = None
if len(src_dt) > 0:
out_fields = []
i = 0
for name in src_dt.fields:
field_src_dt = src_dt.fields[name][0]
field_tgt_dt = tgt_dt.fields[name][0]
field_val = val[i]
i += 1
out_field = copy_element(field_val, field_src_dt, field_tgt_dt, ctx)
out_fields.append(out_field)
out = tuple(out_fields)
elif src_dt.metadata and 'ref' in src_dt.metadata:
if not tgt_dt.metadata or 'ref' not in tgt_dt.metadata:
raise TypeError("Expected tgt dtype to be ref, but got: {}".format(tgt_dt))
ref = tgt_dt.metadata['ref']
if is_reference(ref):
# initialize out to null ref
if is_h5py(ctx['fout']):
out = h5py.Reference() # null h5py ref
else:
out = '' # h5pyd refs are strings
if ref:
try:
fin_obj = fin[val]
except AttributeError as ae:
msg = "Unable able to get obj for ref value: {}".format(ae)
logging.error(msg)
print(msg)
return None
# TBD - for hsget, the name property is not getting set
h5path = fin_obj.name
if not h5path:
msg = "No path found for ref object"
logging.warn(msg)
if ctx["verbose"]:
print(msg)
else:
fout_obj = fout[h5path]
if is_h5py(ctx['fout']):
out = fout_obj.ref
else:
out = str(fout_obj.ref) # convert to string for JSON serialization
elif is_regionreference(ref):
out = "tbd"
else:
raise TypeError("Unexpected ref type: {}".format(type(ref)))
elif src_dt.metadata and 'vlen' in src_dt.metadata:
logging.debug("copy_elment, got vlen element, dt: {}".format(src_dt.metadata["vlen"]))
if not isinstance(val, np.ndarray):
raise TypeError("Expecting ndarray or vlen element, but got: {}".format(type(val)))
if not tgt_dt.metadata or 'vlen' not in tgt_dt.metadata:
raise TypeError("Expected tgt dtype to be vlen, but got: {}".format(tgt_dt))
src_vlen_dt = src_dt.metadata["vlen"]
tgt_vlen_dt = tgt_dt.metadata["vlen"]
if has_reference(src_vlen_dt):
if len(val.shape) == 0:
# scalar array
e = val[()]
v = copy_element(e, src_vlen_dt, tgt_vlen_dt, ctx)
out = np.array(v, dtype=tgt_dt)
else:
out = np.zeros(val.shape, dtype=tgt_dt)
for i in range(len(out)):
e = val[i]
out[i] = copy_element(e, src_vlen_dt, tgt_vlen_dt, ctx)
else:
# can just directly copy the array
out = np.zeros(val.shape, dtype=tgt_dt)
out[...] = val[...]
else:
out = val # can just copy as is
return out
#----------------------------------------------------------------------------------
def copy_array(src_arr, ctx):
""" Copy the numpy array to a new array.
Convert any reference type to point to item in the target's hierarchy.
"""
if not isinstance(src_arr, np.ndarray):
raise TypeError("Expecting ndarray, but got: {}".format(src_arr))
tgt_dt = convert_dtype(src_arr.dtype, ctx)
tgt_arr = np.zeros(src_arr.shape, dtype=tgt_dt)
if has_reference(src_arr.dtype):
# flatten array to simplify iteration
count = np.product(src_arr.shape)
tgt_arr_flat = tgt_arr.reshape((count,))
src_arr_flat = src_arr.reshape((count,))
for i in range(count):
element = copy_element(src_arr_flat[i], src_arr.dtype, tgt_dt, ctx)
tgt_arr_flat[i] = element
tgt_arr = tgt_arr_flat.reshape(src_arr.shape)
else:
# can just copy the entire array
tgt_arr[...] = src_arr[...]
return tgt_arr
#----------------------------------------------------------------------------------
def copy_attribute(desobj, name, srcobj, ctx):
msg = "creating attribute {} in {}".format(name, srcobj.name)
logging.debug(msg)
if ctx["verbose"]:
print(msg)
try:
srcarr = srcobj.attrs[name]
if isinstance(srcarr, np.ndarray):
tgtarr = copy_array(srcarr, ctx)
desobj.attrs.create(name, tgtarr)
else:
# scalars are just read as the native type
desobj.attrs.create(name, srcarr)
except (IOError, TypeError) as e:
msg = "ERROR: failed to create attribute {} of object {} -- {}".format(name, desobj.name, str(e))
logging.error(msg)
print(msg)
# copy_attribute
#----------------------------------------------------------------------------------
def create_dataset(dobj, ctx):
""" create a dataset using the properties of the passed in h5py dataset.
If successful, proceed to copy attributes and data.
"""
msg = "creating dataset {}, shape: {}, type: {}".format(dobj.name, dobj.shape, dobj.dtype)
logging.info(msg)
if ctx["verbose"]:
print(msg)
fout = ctx["fout"]
deflate = ctx["deflate"]
fillvalue = None
try:
# can trigger a runtime error if fillvalue is undefined
fillvalue = dobj.fillvalue
except RuntimeError:
pass # ignore
chunks=None
if dobj.chunks:
chunks = tuple(dobj.chunks)
try:
tgt_dtype = convert_dtype(dobj.dtype, ctx)
compression_filter = dobj.compression
compression_opts = dobj.compression_opts
if deflate is not None and compression_filter is None:
compression_filter = "gzip"
compression_opts = deflate
if ctx["verbose"]:
print("applying gzip filter with level: {}".format(deflate))
dset = fout.create_dataset( dobj.name, shape=dobj.shape, dtype=tgt_dtype, chunks=chunks, \
compression=compression_filter, shuffle=dobj.shuffle, \
fletcher32=dobj.fletcher32, maxshape=dobj.maxshape, \
compression_opts=compression_opts, fillvalue=fillvalue, \
scaleoffset=dobj.scaleoffset)
msg = "dataset created, uuid: {}, chunk_size: {}".format(dset.id.id, str(dset.chunks))
logging.info(msg)
if ctx["verbose"]:
print(msg)
except (IOError, TypeError, KeyError) as e:
msg = "ERROR: failed to create dataset: {}".format(str(e))
logging.error(msg)
print(msg)
return
# create_dataset
#----------------------------------------------------------------------------------
def write_dataset(src, tgt, ctx):
""" write values from src dataset to target dataset.
"""
msg = "write_dataset src: {} to tgt: {}, shape: {}, type: {}".format(src.name, tgt.name, src.shape, src.dtype)
logging.info(msg)
domain = tgt.file.filename
dsetid = tgt.id.id
msg = f"domain: {domain} dsetid: {dsetid}"
logging.info(msg)
if ctx["verbose"]:
print(msg)
if src.shape is None:
# null space dataset
msg = "no data for null space dataset: {}".format(src.name)
logging.info(msg)
if ctx["verbose"]:
print(msg)
return # no data
if len(src.shape) == 0:
# scalar dataset
x = src[()]
msg = "writing: {} for scalar dataset: {}".format(x, src.name)
logging.info(msg)
if ctx["verbose"]:
print(msg)
tgt[()] = x
return
msg = "iterating over chunks for {}".format(src.name)
logging.info(msg)
if ctx["verbose"]:
print(msg)
url = f"{ctx['endpoint']}/datasets/{dsetid}/value"
logging.debug(f"url: {url}")
loop = ctx["loop"]
session = ctx["session"]
try:
it = ChunkIterator(tgt)
futures = []
for s in it:
msg = "writing dataset data for slice: {}".format(s)
logging.info(msg)
if ctx["verbose"]:
print(msg)
arr = src[s]
selection = getSliceQueryParam(s)
logging.debug(f"select:{selection}")
params = {}
params["domain"] = domain
params["select"] = selection
futures.append(write_chunk(session, url, params, arr))
if len(futures) >= ctx["maxtasks"]:
loop.run_until_complete(asyncio.gather(*futures))
futures = []
# send off any remaining chnks
loop.run_until_complete(asyncio.gather(*futures))
except Exception as e:
logging.error(f"got Exception: {e}")
msg = "done with dataload for {}".format(src.name)
logging.info(msg)
if ctx["verbose"]:
print(msg)
# write_dataset
# construct HSDS query param from selection
def getSliceQueryParam(sel):
sel_param="["
if isinstance(sel, tuple):
for s in sel:
if len(sel_param) > 1:
sel_param += ","
sel_param += f"{s.start}:{s.stop}"
else:
sel_param += f"{sel.start}:{sel.stop}"
sel_param += "]"
return sel_param
async def write_chunk(session, url, params, arr):
# TBD: do normal h5yd write for vlen data
msg = f"writing chunk for slice: {params['select']}"
logging.info(msg)
data = arr.tobytes()
try:
async with session.put(url, data=data, params=params) as rsp:
logging.info("status: {}".format(rsp.status))
if rsp.status != 200:
raise IOError(f"expected status 200 but got {rsp.status}")
except ConnectionError as ce:
logging.error("connection error: {}".format(ce))
raise IOError("Connection Error")
#logging.info(msg)
#self.PUT(req, body=body, format=format, params=params)
#----------------------------------------------------------------------------------
def create_links(gsrc, gdes, ctx):
# add soft and external links
if ctx["verbose"]:
print("create_links: {}".format(gsrc.name))
for title in gsrc:
if ctx["verbose"]:
print("got link: {}".format(title))
lnk = gsrc.get(title, getlink=True)
link_classname = lnk.__class__.__name__
if link_classname == "HardLink":
logging.debug("Got hardlink: {}".format(title))
# TBD: handle the case where multiple hardlinks point to same object
elif link_classname == "SoftLink":
msg = "creating SoftLink({}) with title: {}".format(lnk.path, title)
if ctx["verbose"]:
print(msg)
logging.info(msg)
if is_h5py(gdes):
soft_link = h5py.SoftLink(lnk.path)
else:
soft_link = h5pyd.SoftLink(lnk.path)
gdes[title] = soft_link
elif link_classname == "ExternalLink":
msg = "creating ExternalLink({}, {}) with title: {}".format(lnk.filename, lnk.path, title)
if ctx["verbose"]:
print(msg)
logging.info(msg)
if is_h5py(gdes):
ext_link = h5py.ExternalLink(lnk.filename, lnk.path)
else:
ext_link = h5pyd.ExternalLink(lnk.filename, lnk.path)
gdes[title] = ext_link
else:
msg = "Unexpected link type: {}".format(lnk.__class__.__name__)
logging.warning(msg)
if ctx["verbose"]:
print(msg)
def create_group(gobj, ctx):
msg = "creating group {}".format(gobj.name)
logging.info(msg)
if ctx["verbose"]:
print(msg)
fout = ctx["fout"]
grp = fout.create_group(gobj.name)
# create any soft/external links
create_links(gobj, grp, ctx)
# create_group
#----------------------------------------------------------------------------------
def create_datatype(obj, ctx):
msg = "creating datatype {}".format(obj.name)
logging.info(msg)
if ctx["verbose"]:
print(msg)
fout = ctx["fout"]
fout[obj.name] = obj.dtype
# create_datatype
#----------------------------------------------------------------------------------
def load_file(fin, fout, verbose=False, nodata=False, deflate=None, endpoint=None, username=None, password=None, maxtasks=10):
logging.info("input file: {}".format(fin.filename))
logging.info("output file: {}".format(fout.filename))
print(f"load_file, maxtasks: {maxtasks}")
# it would be nice to make a class out of these functions, but that
# makes it heard to use visititems iterator.
# instead, create a context object to pass arround common state
ctx = {}
ctx["fin"] = fin
ctx["fout"] = fout
ctx["verbose"] = verbose
ctx["nodata"] = nodata
ctx["deflate"] = deflate
ctx["endpoint"] = endpoint
ctx["username"] = username
ctx["password"] = password
ctx["maxtasks"] = maxtasks
loop = asyncio.get_event_loop()
ctx["loop"] = loop
connector = aiohttp.TCPConnector(limit=maxtasks)
auth = aiohttp.BasicAuth(login=username, password=password)
headers = {'Content-Type': "application/octet-stream" }
session = aiohttp.ClientSession(auth=auth, headers=headers, loop=loop, connector=connector)
ctx["session"] = session
# create any root attributes
for ga in fin.attrs:
copy_attribute(fout, ga, fin, ctx)
# create root soft/external links
create_links(fin, fout, ctx)
def object_create_helper(name, obj):
class_name = obj.__class__.__name__
if class_name == "Dataset":
create_dataset(obj, ctx)
elif class_name == "Group":
create_group(obj, ctx)
elif class_name == "Datatype":
create_datatype(obj, ctx)
else:
logging.error("no handler for object class: {}".format(type(obj)))
def object_copy_helper(name, obj):
class_name = obj.__class__.__name__
if class_name == "Dataset":
tgt = fout[obj.name]
write_dataset(obj, tgt, ctx)
elif class_name == "Group":
logging.debug("skip copy for group: {}".format(obj.name))
elif class_name == "Datatype":
logging.debug("skip copy for datatype: {}".format(obj.name))
else:
logging.error("no handler for object class: {}".format(type(obj)))
def object_attribute_helper(name, obj):
tgt = fout[obj.name]
for ga in obj.attrs:
copy_attribute(tgt, ga, obj, ctx)
# build a rough map of the file using the internal function above
fin.visititems(object_create_helper)
# copy over any attributes
fin.visititems(object_attribute_helper)
if not nodata:
# copy dataset data
fin.visititems(object_copy_helper)
# Fully flush the h5py handle.
fout.close()
# close up the source domain, see reason(s) for this below
fin.close()
if verbose:
print("closing session")
loop.run_until_complete(session.close())
if verbose:
print("closing connector")
connector.close()
if verbose:
print("closing loop")
loop = ctx["loop"]
loop.close()
msg="load_file complete"
logging.info(msg)
if verbose:
print(msg)
return 0
# load_file
|
import ssl
import smtplib
import imaplib
import email
class MailBot:
"""
Sending and receiving mail
This contains all methods to interact with smtp and imap servers
"""
# Configs - should not need to change
ssl_port = 465
smtp_server = "smtp.gmail.com"
imap_server = "imap.gmail.com"
@classmethod
def read_email(cls, pp, email_id):
with imaplib.IMAP4_SSL(cls.imap_server) as im:
im.login(pp.bot_email, pp.bot_pass)
im.select("inbox")
email_id_bytes = str.encode(str(email_id))
_, response = im.fetch(email_id_bytes, "(RFC822)")
try:
return email.message_from_bytes(response[0][1])
except TypeError:
return None
@classmethod
def send_email(cls, pp, msg):
context = ssl.create_default_context()
msg["From"] = pp.bot_email
with smtplib.SMTP_SSL(cls.smtp_server, cls.ssl_port, context=context) as server:
server.login(pp.bot_email, pp.bot_pass)
server.send_message(msg)
@classmethod
def get_email_ids(cls, pp):
with imaplib.IMAP4_SSL(cls.imap_server) as im:
im.login(pp.bot_email, pp.bot_pass)
im.select("inbox")
_, email_ids = im.search(None, "ALL")
return [int(i) for i in email_ids[0].split()]
class PrepBot:
"""
Prepares/decodes an email.message.EmailMessage instance
"""
@staticmethod
def decipher_payload(msg):
msg_pl = msg.get_payload()
if isinstance(msg_pl, str):
return msg_pl
elif type(msg_pl) == list:
return msg_pl[0].get_payload()
@staticmethod
def decipher_sender(msg):
msg_sender = msg["From"]
msg_sender_email = msg_sender.split("<")[-1].replace(">", "")
msg_sender_name = msg_sender.split("<")[0].strip()
return (msg_sender_name, msg_sender_email)
@staticmethod
def construct_msg(recipient_email, text, subject=None):
# Prepare message
msg = email.message.EmailMessage()
msg["Subject"] = subject
msg["To"] = recipient_email
msg.set_content(text)
return msg
@staticmethod
def construct_fwd_email(msg, recipient_email, pre_text=""):
msg_text = PrepBot.decipher_payload(msg)
new_msg_text = (
f"{pre_text} \r\n\r\n ----------------------- \r\n\r\n {msg_text}"
)
new_msg_subject = f"AutoFW: {msg["Subject"]}"
fw_msg = PrepBot.construct_msg(
recipient_email=recipient_email, text=new_msg_text, subject=new_msg_subject
)
return fw_msg
class ScanBot:
"""
Searches for hallmarks
"""
@staticmethod
def scan_text(msg, srchtxt):
msgtxt = PrepBot.decipher_payload(msg)
return srchtxt.lower() in msgtxt.lower()
@staticmethod
def scan_sender(msg, srchtxt, how="email"):
(sender_name, sender_email) = PrepBot.decipher_sender(msg)
if how == "email":
return srchtxt.lower() in sender_email.lower()
elif how == "name":
return srchtxt.lower() in sender_name.lower()
| import ssl
import smtplib
import imaplib
import email
class MailBot:
"""
Sending and receiving mail
This contains all methods to interact with smtp and imap servers
"""
# Configs - should not need to change
ssl_port = 465
smtp_server = "smtp.gmail.com"
imap_server = "imap.gmail.com"
@classmethod
def read_email(cls, pp, email_id):
with imaplib.IMAP4_SSL(cls.imap_server) as im:
im.login(pp.bot_email, pp.bot_pass)
im.select("inbox")
email_id_bytes = str.encode(str(email_id))
_, response = im.fetch(email_id_bytes, "(RFC822)")
try:
return email.message_from_bytes(response[0][1])
except TypeError:
return None
@classmethod
def send_email(cls, pp, msg):
context = ssl.create_default_context()
msg["From"] = pp.bot_email
with smtplib.SMTP_SSL(cls.smtp_server, cls.ssl_port, context=context) as server:
server.login(pp.bot_email, pp.bot_pass)
server.send_message(msg)
@classmethod
def get_email_ids(cls, pp):
with imaplib.IMAP4_SSL(cls.imap_server) as im:
im.login(pp.bot_email, pp.bot_pass)
im.select("inbox")
_, email_ids = im.search(None, "ALL")
return [int(i) for i in email_ids[0].split()]
class PrepBot:
"""
Prepares/decodes an email.message.EmailMessage instance
"""
@staticmethod
def decipher_payload(msg):
msg_pl = msg.get_payload()
if isinstance(msg_pl, str):
return msg_pl
elif type(msg_pl) == list:
return msg_pl[0].get_payload()
@staticmethod
def decipher_sender(msg):
msg_sender = msg["From"]
msg_sender_email = msg_sender.split("<")[-1].replace(">", "")
msg_sender_name = msg_sender.split("<")[0].strip()
return (msg_sender_name, msg_sender_email)
@staticmethod
def construct_msg(recipient_email, text, subject=None):
# Prepare message
msg = email.message.EmailMessage()
msg["Subject"] = subject
msg["To"] = recipient_email
msg.set_content(text)
return msg
@staticmethod
def construct_fwd_email(msg, recipient_email, pre_text=""):
msg_text = PrepBot.decipher_payload(msg)
new_msg_text = (
f"{pre_text} \r\n\r\n ----------------------- \r\n\r\n {msg_text}"
)
new_msg_subject = f"AutoFW: {msg['Subject']}"
fw_msg = PrepBot.construct_msg(
recipient_email=recipient_email, text=new_msg_text, subject=new_msg_subject
)
return fw_msg
class ScanBot:
"""
Searches for hallmarks
"""
@staticmethod
def scan_text(msg, srchtxt):
msgtxt = PrepBot.decipher_payload(msg)
return srchtxt.lower() in msgtxt.lower()
@staticmethod
def scan_sender(msg, srchtxt, how="email"):
(sender_name, sender_email) = PrepBot.decipher_sender(msg)
if how == "email":
return srchtxt.lower() in sender_email.lower()
elif how == "name":
return srchtxt.lower() in sender_name.lower()
|
# pylint:disable=unused-variable
# pylint:disable=unused-argument
# pylint:disable=redefined-outer-name
import os
from copy import deepcopy
from typing import Dict
import aiohttp
import pytest
import tenacity
from minio import Minio
from servicelib.minio_utils import MinioRetryPolicyUponInitialization
from yarl import URL
from .helpers.utils_docker import get_service_published_port
@pytest.fixture(scope="module")
def storage_endpoint(docker_stack: Dict, testing_environ_vars: Dict) -> URL:
prefix = testing_environ_vars["SWARM_STACK_NAME"]
assert f"{prefix}_storage" in docker_stack["services"]
default_port = testing_environ_vars["STORAGE_ENDPOINT"].split(":")[1]
endpoint = f"127.0.0.1:{get_service_published_port("storage", default_port)}"
# nodeports takes its configuration from env variables
old_environ = deepcopy(os.environ)
os.environ["STORAGE_ENDPOINT"] = endpoint
yield URL(f"http://{endpoint}")
# restore environ
os.environ = old_environ
@pytest.fixture(scope="function")
async def storage_service(
minio_service: Minio, storage_endpoint: URL, docker_stack: Dict
) -> URL:
await wait_till_storage_responsive(storage_endpoint)
yield storage_endpoint
# HELPERS --
# TODO: this can be used by ANY of the simcore services!
@tenacity.retry(**MinioRetryPolicyUponInitialization().kwargs)
async def wait_till_storage_responsive(storage_endpoint: URL):
async with aiohttp.ClientSession() as session:
async with session.get(storage_endpoint.with_path("/v0/")) as resp:
assert resp.status == 200
data = await resp.json()
assert "data" in data
assert data["data"] is not None
| # pylint:disable=unused-variable
# pylint:disable=unused-argument
# pylint:disable=redefined-outer-name
import os
from copy import deepcopy
from typing import Dict
import aiohttp
import pytest
import tenacity
from minio import Minio
from servicelib.minio_utils import MinioRetryPolicyUponInitialization
from yarl import URL
from .helpers.utils_docker import get_service_published_port
@pytest.fixture(scope="module")
def storage_endpoint(docker_stack: Dict, testing_environ_vars: Dict) -> URL:
prefix = testing_environ_vars["SWARM_STACK_NAME"]
assert f"{prefix}_storage" in docker_stack["services"]
default_port = testing_environ_vars["STORAGE_ENDPOINT"].split(":")[1]
endpoint = f"127.0.0.1:{get_service_published_port('storage', default_port)}"
# nodeports takes its configuration from env variables
old_environ = deepcopy(os.environ)
os.environ["STORAGE_ENDPOINT"] = endpoint
yield URL(f"http://{endpoint}")
# restore environ
os.environ = old_environ
@pytest.fixture(scope="function")
async def storage_service(
minio_service: Minio, storage_endpoint: URL, docker_stack: Dict
) -> URL:
await wait_till_storage_responsive(storage_endpoint)
yield storage_endpoint
# HELPERS --
# TODO: this can be used by ANY of the simcore services!
@tenacity.retry(**MinioRetryPolicyUponInitialization().kwargs)
async def wait_till_storage_responsive(storage_endpoint: URL):
async with aiohttp.ClientSession() as session:
async with session.get(storage_endpoint.with_path("/v0/")) as resp:
assert resp.status == 200
data = await resp.json()
assert "data" in data
assert data["data"] is not None
|
# Copyright (c) Aishwarya Kamath & Nicolas Carion. Licensed under the Apache License 2.0. All Rights Reserved
import argparse
import json
import math
import os
import pickle
from collections import Counter, defaultdict
from copy import deepcopy
from functools import partial
from multiprocessing import Pool
from pathlib import Path
from typing import Dict, List, Tuple
import sys
PACKAGE_PARENT = ".."
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))
import torch
from tqdm import tqdm
from utils.boxes import box_iou_helper, combine_boxes, get_boxes_equiv, obj_to_box, region_to_box, xyxy_to_xywh
from utils.dump import Annotation, Datapoint
from utils.spans import (
PreprocessError,
consolidate_spans,
get_canonical_spans,
span_intersect_spanlist,
spanlist_intersect_spanlist,
)
from utils.text import get_root_and_nouns, normalize_sentence, normalize_whitespace, simplify_punctuation
from utils.unionfind import UnionFind
def parse_args():
parser = argparse.ArgumentParser("Visual Genome conversion script")
parser.add_argument(
"--dataset_path",
required=True,
type=str,
help="Path to the VG dataset. Should contain region graphs",
)
parser.add_argument(
"--out_path",
default=None,
type=str,
help="Path where to export the resulting dataset.",
)
parser.add_argument(
"--nb_process",
default=1,
type=str,
help="Number of concurrent processes to use to dump the data",
)
return parser.parse_args()
def preprocess_region(region):
filtered_region = {
"caption": simplify_punctuation(normalize_whitespace(region["phrase"])),
"original_image_id": region["image_id"],
"original_region_id": region["region_id"],
"boxes": [],
"tokens_positive": [],
"found_objects": False,
}
if len(filtered_region["caption"]) < 3:
raise PreprocessError("caption too short, skipping" + filtered_region["caption"])
_, _, root_spans, negative_spans = get_root_and_nouns(filtered_region["caption"].lower(), False)
# Filter objects that have multiple synsets, they are likely to be spurious
obj_synsets = set([o["synsets"][0] for o in region["objects"] if len(o["synsets"]) == 1])
synsets_count = Counter([s["synset_name"] for s in region["synsets"]])
# Filter synsets that occur multiple times, since we don't have mapping to objects
all_synsets = set([s["synset_name"] for s in region["synsets"] if synsets_count[s["synset_name"]] == 1])
authorized_synsets = obj_synsets.intersection(all_synsets)
syn2span: Dict[str, Tuple[int, int]] = {
s["synset_name"]: (s["entity_idx_start"], s["entity_idx_end"])
for s in region["synsets"]
if s["synset_name"] in authorized_synsets
}
synlist, spanlist = [], []
for k, s in syn2span.items():
synlist.append(k)
spanlist.append([s])
# the spans positions may have been altered by the whitespace removal, so we recompute here
spanlist, new_caption = get_canonical_spans(spanlist, region["phrase"], whitespace_only=True)
if new_caption.lower().strip() != filtered_region["caption"].lower().strip():
raise PreprocessError(f"Inconsistent whitespace removal: '{new_caption}" vs "{filtered_region["caption"]}'")
assert len(synlist) == len(spanlist)
syn2span = {k: v[0] for k, v in zip(synlist, spanlist)}
root_objs = []
other_objs: Dict[Tuple[int, int], List[List[int]]] = {}
for obj in region["objects"]:
if len(obj["synsets"]) == 1 and obj["synsets"][0] in authorized_synsets:
cur_span = syn2span[obj["synsets"][0]]
if span_intersect_spanlist(cur_span, root_spans):
root_objs.append(obj_to_box(obj))
filtered_region["found_objects"] = True
else:
if cur_span not in other_objs:
other_objs[cur_span] = []
negative_spans.append(cur_span)
other_objs[cur_span].append(obj_to_box(obj))
filtered_region["found_objects"] = True
if len(root_objs) == 0:
# If we don't have a box for the root of the sentence, we use the box of the region itself.
root_objs.append(region_to_box(region))
dedup_root_objs = combine_boxes(root_objs)
filtered_region["boxes"] += dedup_root_objs
root_spans = consolidate_spans(root_spans, filtered_region["caption"])
filtered_region["tokens_positive"] += [root_spans for _ in range(len(dedup_root_objs))]
for span, objs in other_objs.items():
dedup_objs = combine_boxes(objs)
filtered_region["boxes"] += dedup_objs
cur_spans = consolidate_spans([span], filtered_region["caption"])
filtered_region["tokens_positive"] += [cur_spans for _ in range(len(dedup_objs))]
filtered_region["tokens_negative"] = consolidate_spans(negative_spans, filtered_region["caption"])
return filtered_region
def deduplicate_regions(regions, iou_threshold=0.5):
"""This functions accepts pre-processed region descriptions for a given image, and removes regions that are redundant.
Two regions are deemed redundant if 1) the text is closely matching 2) the IOU between region boxes is > iou_threshold
A cleaned description is returned.
"""
def helper_merge(regions):
if len(regions) <= 1:
return regions
uf = UnionFind(len(regions))
for r in regions:
spans, txt2 = get_canonical_spans(r["tokens_positive"], r["caption"])
if txt != txt2:
raise PreprocessError(f"inconsistent canonicalization fct. Mismatch: '{txt}' and '{txt2}'")
r["cano_tokens"] = spans
for r1 in range(len(regions)):
for r2 in range(r1 + 1, len(regions)):
compatible = True
assert len(regions[r1]["boxes"]) == len(regions[r1]["cano_tokens"])
assert len(regions[r2]["boxes"]) == len(regions[r2]["cano_tokens"])
ious = box_iou_helper(regions[r1]["boxes"], regions[r2]["boxes"])
for b1 in range(len(regions[r1]["cano_tokens"])):
for b2 in range(len(regions[r2]["cano_tokens"])):
if (len(regions[r1]["cano_tokens"][b1]) == 0 or len(regions[r2]["cano_tokens"][b2]) == 0) or (
spanlist_intersect_spanlist(regions[r1]["cano_tokens"][b1], regions[r2]["cano_tokens"][b2])
and ious[b1][b2] < iou_threshold
):
compatible = False
break
if not compatible:
break
if compatible:
uf.unite(r1, r2)
compo2regions = defaultdict(list)
for i, r in enumerate(regions):
compo2regions[uf.find(i)].append(r)
final_regions = []
for reg_list in compo2regions.values():
if len(reg_list) == 1:
final_regions.append(reg_list[0])
else:
# We pick as representative of this cluster the region with the most boxes
sorted_regions = sorted([(len(r["boxes"]), i) for i, r in enumerate(reg_list)], reverse=True)
reg_ids = [sr[1] for sr in sorted_regions]
# We need to put the boxes and token spans in buckets
cano_spans_buckets = []
orig_spans_buckets = []
boxes_buckets = []
for idx in reg_ids:
for b in range(len(reg_list[idx]["boxes"])):
# find the bucket
bucket = -1
for j in range(len(cano_spans_buckets)):
if spanlist_intersect_spanlist(reg_list[idx]["cano_tokens"][b], cano_spans_buckets[j]):
bucket = j
break
if bucket == -1:
# bucket not found, creating one.
if idx != reg_ids[0]:
# This shouldn't happen. But if it does, we give up on the merging
return regions
assert idx == reg_ids[0], (
"TODO: if this triggers, it means another regions has token spans than aren't covered by the main region."
+ "We need to create a new token span, which involve finding the span in the original sentencen of the main region. Don't forget to update the negative tokens"
)
bucket = len(orig_spans_buckets)
orig_spans_buckets.append(reg_list[idx]["tokens_positive"][b])
cano_spans_buckets.append(reg_list[idx]["cano_tokens"][b])
boxes_buckets.append([reg_list[idx]["boxes"][b]])
else:
boxes_buckets[bucket].append(reg_list[idx]["boxes"][b])
assert len(orig_spans_buckets) == len(boxes_buckets)
merged_region = deepcopy(reg_list[reg_ids[0]])
merged_region["tokens_positive"] = []
merged_region["boxes"] = []
for i in range(len(boxes_buckets)):
dedup_objs = combine_boxes(boxes_buckets[i], iou_threshold=0.5)
merged_region["boxes"] += dedup_objs
merged_region["tokens_positive"] += [orig_spans_buckets[i] for _ in range(len(dedup_objs))]
final_regions.append(merged_region)
for r in final_regions:
del r["cano_tokens"]
return final_regions
txt2region = defaultdict(list)
for r in regions:
txt2region[normalize_sentence(r["caption"])].append(r)
stupid_sentence_set = set(["wall", "side", "building"])
final_regions = []
for txt, regions in txt2region.items():
# Edge case, we remove the sentences like "the wall on the side of the building" which are uninformative and have spurious boxes
if "wall" in txt and set(txt.strip().split(" ")).issubset(stupid_sentence_set):
continue
if len(regions) == 1:
final_regions.append(deepcopy(regions[0]))
else:
# print(txt)
regions_with_boxes = [r for r in regions if r["found_objects"]]
all_boxes = sum([r["boxes"] for r in regions_with_boxes], [])
# print("regions with boxes", len(regions_with_boxes))
regions_without_boxes = []
for r in regions:
if not r["found_objects"]:
# we consider than one of the region with boxes will be better suited and drop this one
# if there is a positive iou. Otherwise, we have to keep it
if len(regions_with_boxes) == 0 or box_iou_helper(all_boxes, r["boxes"]).max().item() < 0.1:
regions_without_boxes.append(r)
# print("regions without boxes", len(regions_without_boxes))
try:
new_regions_with_boxes = helper_merge(regions_with_boxes)
except PreprocessError as e:
print("skipping", e)
# Ouch, hit a cornercase, we give up on the merge
new_regions_with_boxes = regions_with_boxes
try:
new_regions_without_boxes = helper_merge(regions_without_boxes)
except PreprocessError as e:
print("skipping", e)
# Ouch, hit a cornercase, we give up on the merge
new_regions_without_boxes = regions_without_boxes
# now collapse into one big region. We do it only when the captions are exactly matching, otherwise it's a nightmare to recompute spans
capt2region = defaultdict(list)
for r in new_regions_with_boxes + new_regions_without_boxes:
capt2region[r["caption"]].append(r)
for capt, reg_list in capt2region.items():
all_boxes = sum([r["boxes"] for r in reg_list], [])
all_tokens = sum([r["tokens_positive"] for r in reg_list], [])
compo2boxes, compo2id = get_boxes_equiv(all_boxes, iou_threshold=0.75)
final_boxes = []
final_tokens = []
if compo2boxes is not None:
for compo in compo2boxes.keys():
box_list = compo2boxes[compo]
id_list = compo2id[compo]
final_boxes.append(xyxy_to_xywh(torch.stack(box_list, 0).mean(0)).tolist())
final_tokens.append(consolidate_spans(sum([all_tokens[i] for i in id_list], []), capt))
else:
final_boxes = all_boxes
final_tokens = all_tokens
merged_region = {
"caption": capt,
"original_image_id": reg_list[0]["original_image_id"],
"original_region_id": reg_list[0]["original_region_id"],
"boxes": final_boxes,
"tokens_positive": final_tokens,
"tokens_negative": consolidate_spans(sum([r["tokens_negative"] for r in reg_list], []), capt),
"found_objects": False,
}
final_regions.append(merged_region)
return final_regions
def _get_all_datapoints(output_path: Path, img_list, proc_id: int):
# image2ann_map = defaultdict(lambda: defaultdict(list))
print(f"process {proc_id} got job queue of", len(img_list))
all_datapoints: List[Datapoint] = []
for i, data in enumerate(tqdm(img_list)):
# print(f"status {i}/{len(img_list)}")
all_regions = []
for r in data["regions"]:
try:
all_regions.append(preprocess_region(r))
except PreprocessError as e:
print("Dropping region, preprocess failed", e)
all_regions = deduplicate_regions(all_regions)
# all_regions = deduplicate_regions([preprocess_region(r) for r in data["regions"]])
for region in all_regions:
cur_datapoint = Datapoint(
image_id=data["image_id"],
dataset_name="VG",
tokens_negative=region["tokens_negative"],
original_id=region["original_region_id"],
caption=region["caption"],
annotations=[],
)
assert len(region["boxes"]) == len(region["tokens_positive"])
converted_bbox = torch.as_tensor(region["boxes"], dtype=torch.float)
areas = converted_bbox[:, -1] * converted_bbox[:, -2]
# Convert to (x,y,x,y) format
converted_bbox[:, 2:] += converted_bbox[:, :2]
for i in range(len(region["boxes"])):
cur_ann = Annotation(
area=float(areas[i]),
iscrowd=0,
category_id=1,
bbox=region["boxes"][i],
giou_friendly_bbox=converted_bbox[i].tolist(),
tokens_positive=region["tokens_positive"][i],
)
cur_datapoint.annotations.append(cur_ann)
all_datapoints.append(cur_datapoint)
print(f"Process {proc_id} dumping...")
pickle.dump(all_datapoints, open(output_path / f"vg_train_dump_{proc_id}.pkl", "wb"))
print(f"Process {proc_id} done.")
del all_datapoints
return None
# return image2ann_map
def chunk_list(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i : i + n]
def get_all_datapoints(dataset_path: Path, output_path: Path, nb_proc: int):
print("loading region graphs....")
with open(dataset_path / "region_graphs.json", "r") as f:
VG_region_graph = json.load(f)
print("loading success!")
# return _get_image2ann_mapping(VG_region_graph)
chunks = list(chunk_list(VG_region_graph, math.ceil(len(VG_region_graph) / (18 * nb_proc))))
# sub_part = sum(chunks[:3], [])
# chunks = list(chunk_list(sub_part, math.ceil(len(sub_part) / nb_proc)))
proc_id = list(range(len(chunks)))
# assert len(chunks) == nb_proc
with Pool(nb_proc) as p:
p.starmap(partial(_get_all_datapoints, output_path), zip(chunks, proc_id))
return None
def main(args):
vg_path = Path(args.dataset_path)
output_path = Path(args.out_path) if args.out_path is not None else vg_path
os.makedirs(str(output_path), exist_ok=True)
get_all_datapoints(vg_path, output_path, int(args.nb_process))
if __name__ == "__main__":
main(parse_args())
| # Copyright (c) Aishwarya Kamath & Nicolas Carion. Licensed under the Apache License 2.0. All Rights Reserved
import argparse
import json
import math
import os
import pickle
from collections import Counter, defaultdict
from copy import deepcopy
from functools import partial
from multiprocessing import Pool
from pathlib import Path
from typing import Dict, List, Tuple
import sys
PACKAGE_PARENT = ".."
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))
import torch
from tqdm import tqdm
from utils.boxes import box_iou_helper, combine_boxes, get_boxes_equiv, obj_to_box, region_to_box, xyxy_to_xywh
from utils.dump import Annotation, Datapoint
from utils.spans import (
PreprocessError,
consolidate_spans,
get_canonical_spans,
span_intersect_spanlist,
spanlist_intersect_spanlist,
)
from utils.text import get_root_and_nouns, normalize_sentence, normalize_whitespace, simplify_punctuation
from utils.unionfind import UnionFind
def parse_args():
parser = argparse.ArgumentParser("Visual Genome conversion script")
parser.add_argument(
"--dataset_path",
required=True,
type=str,
help="Path to the VG dataset. Should contain region graphs",
)
parser.add_argument(
"--out_path",
default=None,
type=str,
help="Path where to export the resulting dataset.",
)
parser.add_argument(
"--nb_process",
default=1,
type=str,
help="Number of concurrent processes to use to dump the data",
)
return parser.parse_args()
def preprocess_region(region):
filtered_region = {
"caption": simplify_punctuation(normalize_whitespace(region["phrase"])),
"original_image_id": region["image_id"],
"original_region_id": region["region_id"],
"boxes": [],
"tokens_positive": [],
"found_objects": False,
}
if len(filtered_region["caption"]) < 3:
raise PreprocessError("caption too short, skipping" + filtered_region["caption"])
_, _, root_spans, negative_spans = get_root_and_nouns(filtered_region["caption"].lower(), False)
# Filter objects that have multiple synsets, they are likely to be spurious
obj_synsets = set([o["synsets"][0] for o in region["objects"] if len(o["synsets"]) == 1])
synsets_count = Counter([s["synset_name"] for s in region["synsets"]])
# Filter synsets that occur multiple times, since we don't have mapping to objects
all_synsets = set([s["synset_name"] for s in region["synsets"] if synsets_count[s["synset_name"]] == 1])
authorized_synsets = obj_synsets.intersection(all_synsets)
syn2span: Dict[str, Tuple[int, int]] = {
s["synset_name"]: (s["entity_idx_start"], s["entity_idx_end"])
for s in region["synsets"]
if s["synset_name"] in authorized_synsets
}
synlist, spanlist = [], []
for k, s in syn2span.items():
synlist.append(k)
spanlist.append([s])
# the spans positions may have been altered by the whitespace removal, so we recompute here
spanlist, new_caption = get_canonical_spans(spanlist, region["phrase"], whitespace_only=True)
if new_caption.lower().strip() != filtered_region["caption"].lower().strip():
raise PreprocessError(f"Inconsistent whitespace removal: '{new_caption}' vs '{filtered_region['caption']}'")
assert len(synlist) == len(spanlist)
syn2span = {k: v[0] for k, v in zip(synlist, spanlist)}
root_objs = []
other_objs: Dict[Tuple[int, int], List[List[int]]] = {}
for obj in region["objects"]:
if len(obj["synsets"]) == 1 and obj["synsets"][0] in authorized_synsets:
cur_span = syn2span[obj["synsets"][0]]
if span_intersect_spanlist(cur_span, root_spans):
root_objs.append(obj_to_box(obj))
filtered_region["found_objects"] = True
else:
if cur_span not in other_objs:
other_objs[cur_span] = []
negative_spans.append(cur_span)
other_objs[cur_span].append(obj_to_box(obj))
filtered_region["found_objects"] = True
if len(root_objs) == 0:
# If we don't have a box for the root of the sentence, we use the box of the region itself.
root_objs.append(region_to_box(region))
dedup_root_objs = combine_boxes(root_objs)
filtered_region["boxes"] += dedup_root_objs
root_spans = consolidate_spans(root_spans, filtered_region["caption"])
filtered_region["tokens_positive"] += [root_spans for _ in range(len(dedup_root_objs))]
for span, objs in other_objs.items():
dedup_objs = combine_boxes(objs)
filtered_region["boxes"] += dedup_objs
cur_spans = consolidate_spans([span], filtered_region["caption"])
filtered_region["tokens_positive"] += [cur_spans for _ in range(len(dedup_objs))]
filtered_region["tokens_negative"] = consolidate_spans(negative_spans, filtered_region["caption"])
return filtered_region
def deduplicate_regions(regions, iou_threshold=0.5):
"""This functions accepts pre-processed region descriptions for a given image, and removes regions that are redundant.
Two regions are deemed redundant if 1) the text is closely matching 2) the IOU between region boxes is > iou_threshold
A cleaned description is returned.
"""
def helper_merge(regions):
if len(regions) <= 1:
return regions
uf = UnionFind(len(regions))
for r in regions:
spans, txt2 = get_canonical_spans(r["tokens_positive"], r["caption"])
if txt != txt2:
raise PreprocessError(f"inconsistent canonicalization fct. Mismatch: '{txt}' and '{txt2}'")
r["cano_tokens"] = spans
for r1 in range(len(regions)):
for r2 in range(r1 + 1, len(regions)):
compatible = True
assert len(regions[r1]["boxes"]) == len(regions[r1]["cano_tokens"])
assert len(regions[r2]["boxes"]) == len(regions[r2]["cano_tokens"])
ious = box_iou_helper(regions[r1]["boxes"], regions[r2]["boxes"])
for b1 in range(len(regions[r1]["cano_tokens"])):
for b2 in range(len(regions[r2]["cano_tokens"])):
if (len(regions[r1]["cano_tokens"][b1]) == 0 or len(regions[r2]["cano_tokens"][b2]) == 0) or (
spanlist_intersect_spanlist(regions[r1]["cano_tokens"][b1], regions[r2]["cano_tokens"][b2])
and ious[b1][b2] < iou_threshold
):
compatible = False
break
if not compatible:
break
if compatible:
uf.unite(r1, r2)
compo2regions = defaultdict(list)
for i, r in enumerate(regions):
compo2regions[uf.find(i)].append(r)
final_regions = []
for reg_list in compo2regions.values():
if len(reg_list) == 1:
final_regions.append(reg_list[0])
else:
# We pick as representative of this cluster the region with the most boxes
sorted_regions = sorted([(len(r["boxes"]), i) for i, r in enumerate(reg_list)], reverse=True)
reg_ids = [sr[1] for sr in sorted_regions]
# We need to put the boxes and token spans in buckets
cano_spans_buckets = []
orig_spans_buckets = []
boxes_buckets = []
for idx in reg_ids:
for b in range(len(reg_list[idx]["boxes"])):
# find the bucket
bucket = -1
for j in range(len(cano_spans_buckets)):
if spanlist_intersect_spanlist(reg_list[idx]["cano_tokens"][b], cano_spans_buckets[j]):
bucket = j
break
if bucket == -1:
# bucket not found, creating one.
if idx != reg_ids[0]:
# This shouldn't happen. But if it does, we give up on the merging
return regions
assert idx == reg_ids[0], (
"TODO: if this triggers, it means another regions has token spans than aren't covered by the main region."
+ "We need to create a new token span, which involve finding the span in the original sentencen of the main region. Don't forget to update the negative tokens"
)
bucket = len(orig_spans_buckets)
orig_spans_buckets.append(reg_list[idx]["tokens_positive"][b])
cano_spans_buckets.append(reg_list[idx]["cano_tokens"][b])
boxes_buckets.append([reg_list[idx]["boxes"][b]])
else:
boxes_buckets[bucket].append(reg_list[idx]["boxes"][b])
assert len(orig_spans_buckets) == len(boxes_buckets)
merged_region = deepcopy(reg_list[reg_ids[0]])
merged_region["tokens_positive"] = []
merged_region["boxes"] = []
for i in range(len(boxes_buckets)):
dedup_objs = combine_boxes(boxes_buckets[i], iou_threshold=0.5)
merged_region["boxes"] += dedup_objs
merged_region["tokens_positive"] += [orig_spans_buckets[i] for _ in range(len(dedup_objs))]
final_regions.append(merged_region)
for r in final_regions:
del r["cano_tokens"]
return final_regions
txt2region = defaultdict(list)
for r in regions:
txt2region[normalize_sentence(r["caption"])].append(r)
stupid_sentence_set = set(["wall", "side", "building"])
final_regions = []
for txt, regions in txt2region.items():
# Edge case, we remove the sentences like "the wall on the side of the building" which are uninformative and have spurious boxes
if "wall" in txt and set(txt.strip().split(" ")).issubset(stupid_sentence_set):
continue
if len(regions) == 1:
final_regions.append(deepcopy(regions[0]))
else:
# print(txt)
regions_with_boxes = [r for r in regions if r["found_objects"]]
all_boxes = sum([r["boxes"] for r in regions_with_boxes], [])
# print("regions with boxes", len(regions_with_boxes))
regions_without_boxes = []
for r in regions:
if not r["found_objects"]:
# we consider than one of the region with boxes will be better suited and drop this one
# if there is a positive iou. Otherwise, we have to keep it
if len(regions_with_boxes) == 0 or box_iou_helper(all_boxes, r["boxes"]).max().item() < 0.1:
regions_without_boxes.append(r)
# print("regions without boxes", len(regions_without_boxes))
try:
new_regions_with_boxes = helper_merge(regions_with_boxes)
except PreprocessError as e:
print("skipping", e)
# Ouch, hit a cornercase, we give up on the merge
new_regions_with_boxes = regions_with_boxes
try:
new_regions_without_boxes = helper_merge(regions_without_boxes)
except PreprocessError as e:
print("skipping", e)
# Ouch, hit a cornercase, we give up on the merge
new_regions_without_boxes = regions_without_boxes
# now collapse into one big region. We do it only when the captions are exactly matching, otherwise it's a nightmare to recompute spans
capt2region = defaultdict(list)
for r in new_regions_with_boxes + new_regions_without_boxes:
capt2region[r["caption"]].append(r)
for capt, reg_list in capt2region.items():
all_boxes = sum([r["boxes"] for r in reg_list], [])
all_tokens = sum([r["tokens_positive"] for r in reg_list], [])
compo2boxes, compo2id = get_boxes_equiv(all_boxes, iou_threshold=0.75)
final_boxes = []
final_tokens = []
if compo2boxes is not None:
for compo in compo2boxes.keys():
box_list = compo2boxes[compo]
id_list = compo2id[compo]
final_boxes.append(xyxy_to_xywh(torch.stack(box_list, 0).mean(0)).tolist())
final_tokens.append(consolidate_spans(sum([all_tokens[i] for i in id_list], []), capt))
else:
final_boxes = all_boxes
final_tokens = all_tokens
merged_region = {
"caption": capt,
"original_image_id": reg_list[0]["original_image_id"],
"original_region_id": reg_list[0]["original_region_id"],
"boxes": final_boxes,
"tokens_positive": final_tokens,
"tokens_negative": consolidate_spans(sum([r["tokens_negative"] for r in reg_list], []), capt),
"found_objects": False,
}
final_regions.append(merged_region)
return final_regions
def _get_all_datapoints(output_path: Path, img_list, proc_id: int):
# image2ann_map = defaultdict(lambda: defaultdict(list))
print(f"process {proc_id} got job queue of", len(img_list))
all_datapoints: List[Datapoint] = []
for i, data in enumerate(tqdm(img_list)):
# print(f"status {i}/{len(img_list)}")
all_regions = []
for r in data["regions"]:
try:
all_regions.append(preprocess_region(r))
except PreprocessError as e:
print("Dropping region, preprocess failed", e)
all_regions = deduplicate_regions(all_regions)
# all_regions = deduplicate_regions([preprocess_region(r) for r in data["regions"]])
for region in all_regions:
cur_datapoint = Datapoint(
image_id=data["image_id"],
dataset_name="VG",
tokens_negative=region["tokens_negative"],
original_id=region["original_region_id"],
caption=region["caption"],
annotations=[],
)
assert len(region["boxes"]) == len(region["tokens_positive"])
converted_bbox = torch.as_tensor(region["boxes"], dtype=torch.float)
areas = converted_bbox[:, -1] * converted_bbox[:, -2]
# Convert to (x,y,x,y) format
converted_bbox[:, 2:] += converted_bbox[:, :2]
for i in range(len(region["boxes"])):
cur_ann = Annotation(
area=float(areas[i]),
iscrowd=0,
category_id=1,
bbox=region["boxes"][i],
giou_friendly_bbox=converted_bbox[i].tolist(),
tokens_positive=region["tokens_positive"][i],
)
cur_datapoint.annotations.append(cur_ann)
all_datapoints.append(cur_datapoint)
print(f"Process {proc_id} dumping...")
pickle.dump(all_datapoints, open(output_path / f"vg_train_dump_{proc_id}.pkl", "wb"))
print(f"Process {proc_id} done.")
del all_datapoints
return None
# return image2ann_map
def chunk_list(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i : i + n]
def get_all_datapoints(dataset_path: Path, output_path: Path, nb_proc: int):
print("loading region graphs....")
with open(dataset_path / "region_graphs.json", "r") as f:
VG_region_graph = json.load(f)
print("loading success!")
# return _get_image2ann_mapping(VG_region_graph)
chunks = list(chunk_list(VG_region_graph, math.ceil(len(VG_region_graph) / (18 * nb_proc))))
# sub_part = sum(chunks[:3], [])
# chunks = list(chunk_list(sub_part, math.ceil(len(sub_part) / nb_proc)))
proc_id = list(range(len(chunks)))
# assert len(chunks) == nb_proc
with Pool(nb_proc) as p:
p.starmap(partial(_get_all_datapoints, output_path), zip(chunks, proc_id))
return None
def main(args):
vg_path = Path(args.dataset_path)
output_path = Path(args.out_path) if args.out_path is not None else vg_path
os.makedirs(str(output_path), exist_ok=True)
get_all_datapoints(vg_path, output_path, int(args.nb_process))
if __name__ == "__main__":
main(parse_args())
|
"""well.py: resqpy well module providing trajectory, deviation survey, blocked well, wellbore frame and marker frame and md datum classes.
Example::
# Wellbore interpretations
for well in model.iter_wellbore_interpretations():
print(well.title)
for trajectory in well.iter_trajectories():
print(trajectory.title)
for frame in trajectory.iter_wellbore_frames():
print(frame.title)
# Measured depths
mds = frame.node_mds
# Logs
log_collection = frame.logs
for log in log_collection:
values = log.values()
"""
# todo: create a trajectory from a deviation survey, assuming minimum curvature
version = '20th October 2021'
# Nexus is a registered trademark of the Halliburton Company
# RMS and ROXAR are registered trademarks of Roxar Software Solutions AS, an Emerson company
import logging
log = logging.getLogger(__name__)
log.debug('well.py version ' + version)
import math as maths
import os
import warnings
import lasio
import numpy as np
import pandas as pd
import resqpy.crs as crs
import resqpy.lines as rql
import resqpy.olio.grid_functions as gf
import resqpy.olio.intersection as intersect
import resqpy.olio.keyword_files as kf
import resqpy.olio.uuid as bu
import resqpy.olio.vector_utilities as vec
import resqpy.olio.wellspec_keywords as wsk
import resqpy.olio.write_hdf5 as rwh5
import resqpy.olio.xml_et as rqet
import resqpy.organize as rqo
import resqpy.property as rqp
import resqpy.weights_and_measures as bwam
from resqpy.olio.base import BaseResqpy
from resqpy.olio.xml_namespaces import curly_namespace as ns
valid_md_reference_list = [
"ground level", "kelly bushing", "mean sea level", "derrick floor", "casing flange", "arbitrary point",
"crown valve", "rotary bushing", "rotary table", "sea floor", "lowest astronomical tide", "mean higher high water",
"mean high water", "mean lower low water", "mean low water", "mean tide level", "kickoff point"
]
# todo: could require/maintain DeviationSurvey mds in same units as md datum object's crs vertical units?
class MdDatum(BaseResqpy):
"""Class for RESQML measured depth datum."""
resqml_type = 'MdDatum'
def __init__(
self,
parent_model,
uuid = None,
md_datum_root = None,
crs_uuid = None,
crs_root = None, # deprecated
location = None,
md_reference = 'mean sea level',
title = None,
originator = None,
extra_metadata = None):
"""Initialises a new MdDatum object.
arguments:
parent_model (model.Model object): the model which the new md datum belongs to
uuid: If not None, load from existing object. Else, create new.
md_datum_root (optional): DEPRECATED: the root node of the xml tree representing the md datum;
if not None, the new md datum object is initialised based on data in the tree;
if None, the new object is initialised from the remaining arguments
crs_uuid (uuid.UUID): required if initialising from values
crs_root: DEPRECATED, use crs_uuid instead; the root node of the coordinate reference system
xml tree; ignored if uuid or md_datum_root is not None or crs_uuid is not None
location: (triple float): the x, y, z location of the new measured depth datum;
ignored if uuid or md_datum_root is not None
md_reference (string): human readable resqml standard string indicating the real
world nature of the datum, eg. 'kelly bushing'; the full list of options is
available as the global variable valid_md_reference_list in this module;
ignored if uuid or md_datum_root is not None
title (str, optional): the citation title to use for a new datum;
ignored if uuid or md_datum_root is not None
originator (str, optional): the name of the person creating the datum, defaults to login id;
ignored if uuid or md_datum_root is not None
extra_metadata (dict, optional): string key, value pairs to add as extra metadata for the datum;
ignored if uuid or md_datum_root is not None
returns:
the newly instantiated measured depth datum object
note:
this function does not create an xml node for the md datum; call the create_xml() method afterwards
if initialising from data other than an existing RESQML object
"""
if crs_root is not None:
warnings.warn("Attribute 'crs_root' is deprecated. Use 'crs_uuid'", DeprecationWarning)
# TODO: remove crs_root argument
self.location = location
self.md_reference = md_reference
self.crs_uuid = crs_uuid
super().__init__(model = parent_model,
uuid = uuid,
title = title,
originator = originator,
extra_metadata = extra_metadata,
root_node = md_datum_root)
# temporary code to sort out crs reference, till crs_root arg is retired
if self.crs_uuid is None and crs_root is not None:
self.crs_uuid = rqet.uuid_for_part_root(crs_root)
assert self.crs_uuid is not None
if self.root is None and (location is not None or md_reference):
assert location is not None and md_reference
assert md_reference in valid_md_reference_list
assert len(location) == 3
def _load_from_xml(self):
md_datum_root = self.root
assert md_datum_root is not None
location_node = rqet.find_tag(md_datum_root, 'Location')
self.location = (rqet.find_tag_float(location_node,
'Coordinate1'), rqet.find_tag_float(location_node, 'Coordinate2'),
rqet.find_tag_float(location_node, 'Coordinate3'))
self.md_reference = rqet.node_text(rqet.find_tag(md_datum_root, 'MdReference')).strip().lower()
assert self.md_reference in valid_md_reference_list
self.crs_uuid = self.extract_crs_uuid()
@property
def crs_root(self):
"""XML node corresponding to self.crs_uuid."""
return self.model.root_for_uuid(self.crs_uuid)
# todo: the following function is almost identical to one in the grid module: it should be made common and put in model.py
def extract_crs_uuid(self):
"""Returns uuid for coordinate reference system, as stored in reference node of this md datum's xml tree."""
if self.crs_uuid is not None:
return self.crs_uuid
crs_root = rqet.find_tag(self.root, 'LocalCrs')
uuid_str = rqet.find_tag(crs_root, 'UUID').text
self.crs_uuid = bu.uuid_from_string(uuid_str)
return self.crs_uuid
def extract_crs_root(self):
"""Returns root in parent model xml parts forest of coordinate reference system used by this md datum."""
if self.crs_uuid is None:
self.extract_crs_uuid()
return self.crs_root
def create_part(self):
"""Creates xml for this md datum object and adds to parent model as a part; returns root node for part."""
# note: deprecated, call create_xml() directly
assert self.root is None
assert self.location is not None
self.create_xml(add_as_part = True)
def create_xml(self, add_as_part = True, add_relationships = True, title = None, originator = None):
"""Creates xml for a measured depth datum element; crs node must already exist; optionally adds as part.
arguments:
add_as_part (boolean, default True): if True, the newly created xml node is added as a part
in the model
add_relationships (boolean, default True): if True, a relationship xml part is created relating the
new md datum part to the crs
title (string): used as the citation Title text for the new md datum node
originator (string, optional): the name of the human being who created the md datum part;
default is to use the login name
returns:
the newly created measured depth datum xml node
"""
md_reference = self.md_reference.lower()
assert md_reference in valid_md_reference_list, 'invalid measured depth reference: ' + md_reference
if title:
self.title = title
if not self.title:
self.title = 'measured depth datum'
crs_uuid = self.crs_uuid
assert crs_uuid is not None
datum = super().create_xml(add_as_part = False, originator = originator)
self.model.create_solitary_point3d('Location', datum, self.location)
md_ref = rqet.SubElement(datum, ns['resqml2'] + 'MdReference')
md_ref.set(ns['xsi'] + 'type', ns['resqml2'] + 'MdReference')
md_ref.text = md_reference
self.model.create_crs_reference(crs_uuid = crs_uuid, root = datum)
if add_as_part:
self.model.add_part('obj_MdDatum', self.uuid, datum)
if add_relationships:
self.model.create_reciprocal_relationship(datum, 'destinationObject', self.crs_root, 'sourceObject')
return datum
def is_equivalent(self, other):
"""Implements equals operator, comparing metadata items deemed significant."""
if not isinstance(other, self.__class__):
return False
if self.md_reference != other.md_reference or not np.allclose(self.location, other.location):
return False
return bu.matching_uuids(self.crs_uuid, other.crs_uuid)
class DeviationSurvey(BaseResqpy):
"""Class for RESQML wellbore deviation survey.
RESQML documentation:
Specifies the station data from a deviation survey.
The deviation survey does not provide a complete specification of the
geometry of a wellbore trajectory. Although a minimum-curvature
algorithm is used in most cases, the implementation varies sufficiently
that no single algorithmic specification is available as a data transfer
standard.
Instead, the geometry of a RESQML wellbore trajectory is represented by
a parametric line, parameterized by the MD.
CRS and units of measure do not need to be consistent with the CRS and
units of measure for wellbore trajectory representation.
"""
resqml_type = 'DeviationSurveyRepresentation'
def __init__(self,
parent_model,
uuid = None,
title = None,
deviation_survey_root = None,
represented_interp = None,
md_datum = None,
md_uom = 'm',
angle_uom = 'dega',
measured_depths = None,
azimuths = None,
inclinations = None,
station_count = None,
first_station = None,
is_final = False,
originator = None,
extra_metadata = None):
"""Load or create a DeviationSurvey object.
If uuid is given, loads from XML. Else, create new. If loading from disk, other
parameters will be overwritten.
Args:
parent_model (model.Model): the model which the new survey belongs to
uuid (uuid.UUID): If given, loads from disk. Else, creates new.
title (str): Citation title
deviation_survey_root: DEPCRECATED. If given, load from disk.
represented_interp (wellbore interpretation): if present, is noted as the wellbore
interpretation object which this deviation survey relates to
md_datum (MdDatum): the datum that the depths for this survey are measured from
md_uom (string, default 'm'): a resqml length unit of measure applicable to the
measured depths; should be 'm' or 'ft'
angle_uom (string): a resqml angle unit; should be 'dega' or 'rad'
measured_depths (np.array): 1d array
azimuths (np.array): 1d array
inclindations (np.array): 1d array
station_count (int): length of measured_depths, azimuths & inclinations
first_station (tuple): (x, y, z) of first point in survey, in crs for md datum
is_final (bool): whether survey is a finalised deviation survey
originator (str): name of author
extra_metadata (dict, optional): extra metadata key, value pairs
Returns:
DeviationSurvey
Notes:
this method does not create an xml node, nor write hdf5 arrays
"""
self.is_final = is_final
self.md_uom = bwam.rq_length_unit(md_uom)
self.angles_in_degrees = angle_uom.strip().lower().startswith('deg')
"""boolean: True for degrees, False for radians (nothing else supported). Should be 'dega' or 'rad'"""
# Array data
self.measured_depths = _as_optional_array(measured_depths)
self.azimuths = _as_optional_array(azimuths)
self.inclinations = _as_optional_array(inclinations)
if station_count is None and measured_depths is not None:
station_count = len(measured_depths)
self.station_count = station_count
self.first_station = first_station
# Referenced objects
self.md_datum = md_datum # md datum is an object in its own right, with a related crs!
self.wellbore_interpretation = represented_interp
# TODO: remove deviation_survey_root, use just uuid
super().__init__(model = parent_model,
uuid = uuid,
title = title,
originator = originator,
extra_metadata = extra_metadata,
root_node = deviation_survey_root)
@classmethod
def from_data_frame(cls,
parent_model,
data_frame,
md_datum = None,
md_col = 'MD',
azimuth_col = 'AZIM_GN',
inclination_col = 'INCL',
x_col = 'X',
y_col = 'Y',
z_col = 'Z',
md_uom = 'm',
angle_uom = 'dega'):
"""Load MD, aximuth & inclination data from a pandas data frame.
Args:
parent_model (model.Model): the parent resqml model
data_frame: a pandas dataframe holding the deviation survey data
md_datum (MdDatum object): the datum that the depths for this survey are measured from
md_col (string, default 'MD'): the name of the column holding measured depth values
azimuth_col (string, default 'AZIM_GN'): the name of the column holding azimuth values relative
to the north direction (+ve y axis) of the coordinate reference system
inclination_col (string, default 'INCL'): the name of the column holding inclination values
x_col (string, default 'X'): the name of the column holding an x value in the first row
y_col (string, default 'Y'): the name of the column holding an Y value in the first row
z_col (string, default 'Z'): the name of the column holding an z value in the first row
md_uom (string, default 'm'): a resqml length unit of measure applicable to the
measured depths; should be 'm' or 'ft'
angle_uom (string, default 'dega'): a resqml angle unit of measure applicable to both
the azimuth and inclination data
Returns:
DeviationSurvey
Note:
The X, Y & Z columns are only used to set the first station location (from the first row)
"""
for col in [md_col, azimuth_col, inclination_col, x_col, y_col, z_col]:
assert col in data_frame.columns
station_count = len(data_frame)
assert station_count >= 2 # vertical well could be hamdled by allowing a single station in survey?
# self.md_uom = bwam.p_length_unit(md_uom)
start = data_frame.iloc[0]
return cls(parent_model = parent_model,
station_count = station_count,
md_datum = md_datum,
md_uom = md_uom,
angle_uom = angle_uom,
first_station = (start[x_col], start[y_col], start[z_col]),
measured_depths = data_frame[md_col].values,
azimuths = data_frame[azimuth_col].values,
inclinations = data_frame[inclination_col].values,
is_final = True) # assume this is a finalised deviation survey
@classmethod
def from_ascii_file(cls,
parent_model,
deviation_survey_file,
comment_character = '#',
space_separated_instead_of_csv = False,
md_col = 'MD',
azimuth_col = 'AZIM_GN',
inclination_col = 'INCL',
x_col = 'X',
y_col = 'Y',
z_col = 'Z',
md_uom = 'm',
angle_uom = 'dega',
md_datum = None):
"""Load MD, aximuth & inclination data from an ascii deviation survey file.
Arguments:
parent_model (model.Model): the parent resqml model
deviation_survey_file (string): the filename of an ascii file holding the deviation survey data
comment_character (string): the character to be treated as introducing comments
space_separated_instead_of_csv (boolea, default False): if False, csv format expected;
if True, columns are expected to be seperated by white space
md_col (string, default 'MD'): the name of the column holding measured depth values
azimuth_col (string, default 'AZIM_GN'): the name of the column holding azimuth values relative
to the north direction (+ve y axis) of the coordinate reference system
inclination_col (string, default 'INCL'): the name of the column holding inclination values
x_col (string, default 'X'): the name of the column holding an x value in the first row
y_col (string, default 'Y'): the name of the column holding an Y value in the first row
z_col (string, default 'Z'): the name of the column holding an z value in the first row
md_uom (string, default 'm'): a resqml length unit of measure applicable to the
measured depths; should be 'm' or 'ft'
angle_uom (string, default 'dega'): a resqml angle unit of measure applicable to both
the azimuth and inclination data
md_datum (MdDatum object): the datum that the depths for this survey are measured from
Returns:
DeviationSurvey
Note:
The X, Y & Z columns are only used to set the first station location (from the first row)
"""
try:
df = pd.read_csv(deviation_survey_file,
comment = comment_character,
delim_whitespace = space_separated_instead_of_csv)
if df is None:
raise Exception
except Exception:
log.error('failed to read ascii deviation survey file ' + deviation_survey_file)
raise
return cls.from_data_frame(parent_model,
df,
md_col = md_col,
azimuth_col = azimuth_col,
inclination_col = inclination_col,
x_col = x_col,
y_col = y_col,
z_col = z_col,
md_uom = md_uom,
angle_uom = angle_uom,
md_datum = md_datum)
def _load_from_xml(self):
"""Load attributes from xml and associated hdf5 data.
This is invoked as part of the init method when an existing uuid is given.
Returns:
[bool]: True if sucessful
"""
# Get node from self.uuid
node = self.root
assert node is not None
# Load XML data
self.md_uom = rqet.length_units_from_node(rqet.find_tag(node, 'MdUom', must_exist = True))
self.angle_uom = rqet.find_tag_text(node, 'AngleUom', must_exist = True)
self.station_count = rqet.find_tag_int(node, 'StationCount', must_exist = True)
self.first_station = extract_xyz(rqet.find_tag(node, 'FirstStationLocation', must_exist = True))
self.is_final = rqet.find_tag_bool(node, 'IsFinal')
# Load HDF5 data
mds_node = rqet.find_tag(node, 'Mds', must_exist = True)
load_hdf5_array(self, mds_node, 'measured_depths')
azimuths_node = rqet.find_tag(node, 'Azimuths', must_exist = True)
load_hdf5_array(self, azimuths_node, 'azimuths')
inclinations_node = rqet.find_tag(node, 'Inclinations', must_exist = True)
load_hdf5_array(self, inclinations_node, 'inclinations')
# Set related objects
self.md_datum = self._load_related_datum()
self.represented_interp = self._load_related_wellbore_interp()
# Validate
assert self.measured_depths is not None
assert len(self.measured_depths) > 0
return True
def create_xml(self,
ext_uuid = None,
md_datum_root = None,
md_datum_xyz = None,
add_as_part = True,
add_relationships = True,
title = None,
originator = None):
"""Creates a deviation survey representation xml element from this DeviationSurvey object.
arguments:
ext_uuid (uuid.UUID): the uuid of the hdf5 external part holding the deviation survey arrays
md_datum_root: the root xml node for the measured depth datum that the deviation survey depths
are based on
md_datum_xyz: TODO: document this
add_as_part (boolean, default True): if True, the newly created xml node is added as a part
in the model
add_relationships (boolean, default True): if True, a relationship xml part is created relating the
new deviation survey part to the measured depth datum part
title (string): used as the citation Title text; should usually refer to the well name in a
human readable way
originator (string, optional): the name of the human being who created the deviation survey part;
default is to use the login name
returns:
the newly created deviation survey xml node
"""
assert self.station_count > 0
if ext_uuid is None:
ext_uuid = self.model.h5_uuid()
if md_datum_root is None:
if self.md_datum is None:
if md_datum_xyz is None:
raise ValueError("Must provide a MD Datum for the DeviationSurvey")
self.md_datum = MdDatum(self.model, location = md_datum_xyz)
if self.md_datum.root is None:
md_datum_root = self.md_datum.create_xml()
else:
md_datum_root = self.md_datum.root
assert md_datum_root is not None
# Create root node, write citation block
ds_node = super().create_xml(title = title, originator = originator, add_as_part = False)
if_node = rqet.SubElement(ds_node, ns['resqml2'] + 'IsFinal')
if_node.set(ns['xsi'] + 'type', ns['xsd'] + 'boolean')
if_node.text = str(self.is_final).lower()
sc_node = rqet.SubElement(ds_node, ns['resqml2'] + 'StationCount')
sc_node.set(ns['xsi'] + 'type', ns['xsd'] + 'positiveInteger')
sc_node.text = str(self.station_count)
md_uom = rqet.SubElement(ds_node, ns['resqml2'] + 'MdUom')
md_uom.set(ns['xsi'] + 'type', ns['eml'] + 'LengthUom')
md_uom.text = bwam.rq_length_unit(self.md_uom)
self.model.create_md_datum_reference(md_datum_root, root = ds_node)
self.model.create_solitary_point3d('FirstStationLocation', ds_node, self.first_station)
angle_uom = rqet.SubElement(ds_node, ns['resqml2'] + 'AngleUom')
angle_uom.set(ns['xsi'] + 'type', ns['eml'] + 'PlaneAngleUom')
if self.angles_in_degrees:
angle_uom.text = 'dega'
else:
angle_uom.text = 'rad'
mds = rqet.SubElement(ds_node, ns['resqml2'] + 'Mds')
mds.set(ns['xsi'] + 'type', ns['resqml2'] + 'DoubleHdf5Array')
mds.text = rqet.null_xml_text
mds_values_node = rqet.SubElement(mds, ns['resqml2'] + 'Values')
mds_values_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'Hdf5Dataset')
mds_values_node.text = rqet.null_xml_text
self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'Mds', root = mds_values_node)
azimuths = rqet.SubElement(ds_node, ns['resqml2'] + 'Azimuths')
azimuths.set(ns['xsi'] + 'type', ns['resqml2'] + 'DoubleHdf5Array')
azimuths.text = rqet.null_xml_text
azimuths_values_node = rqet.SubElement(azimuths, ns['resqml2'] + 'Values')
azimuths_values_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'Hdf5Dataset')
azimuths_values_node.text = rqet.null_xml_text
self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'Azimuths', root = azimuths_values_node)
inclinations = rqet.SubElement(ds_node, ns['resqml2'] + 'Inclinations')
inclinations.set(ns['xsi'] + 'type', ns['resqml2'] + 'DoubleHdf5Array')
inclinations.text = rqet.null_xml_text
inclinations_values_node = rqet.SubElement(inclinations, ns['resqml2'] + 'Values')
inclinations_values_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'Hdf5Dataset')
inclinations_values_node.text = rqet.null_xml_text
self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'Inclinations', root = inclinations_values_node)
interp_root = None
if self.wellbore_interpretation is not None:
interp_root = self.wellbore_interpretation.root
self.model.create_ref_node('RepresentedInterpretation',
rqet.find_nested_tags_text(interp_root, ['Citation', 'Title']),
bu.uuid_from_string(interp_root.attrib['uuid']),
content_type = 'obj_WellboreInterpretation',
root = ds_node)
if add_as_part:
self.model.add_part('obj_DeviationSurveyRepresentation', self.uuid, ds_node)
if add_relationships:
# todo: check following relationship
self.model.create_reciprocal_relationship(ds_node, 'destinationObject', md_datum_root, 'sourceObject')
if interp_root is not None:
self.model.create_reciprocal_relationship(ds_node, 'destinationObject', interp_root, 'sourceObject')
ext_part = rqet.part_name_for_object('obj_EpcExternalPartReference', ext_uuid, prefixed = False)
ext_node = self.model.root_for_part(ext_part)
self.model.create_reciprocal_relationship(ds_node, 'mlToExternalPartProxy', ext_node,
'externalPartProxyToMl')
return ds_node
def write_hdf5(self, file_name = None, mode = 'a'):
"""Create or append to an hdf5 file, writing datasets for the measured depths, azimuths, and inclinations."""
# NB: array data must all have been set up prior to calling this function
h5_reg = rwh5.H5Register(self.model)
h5_reg.register_dataset(self.uuid, 'Mds', self.measured_depths, dtype = float)
h5_reg.register_dataset(self.uuid, 'Azimuths', self.azimuths, dtype = float)
h5_reg.register_dataset(self.uuid, 'Inclinations', self.inclinations, dtype = float)
h5_reg.write(file = file_name, mode = mode)
def _load_related_datum(self):
"""Return related MdDatum object from XML if present."""
md_datum_uuid = bu.uuid_from_string(rqet.find_tag(rqet.find_tag(self.root, 'MdDatum'), 'UUID'))
if md_datum_uuid is not None:
md_datum_part = 'obj_MdDatum_' + str(md_datum_uuid) + '.xml'
md_datum = MdDatum(self.model, md_datum_root = self.model.root_for_part(md_datum_part, is_rels = False))
else:
md_datum = None
return md_datum
def _load_related_wellbore_interp(self):
"""Return related wellbore interp object from XML if present."""
interp_uuid = rqet.find_nested_tags_text(self.root, ['RepresentedInterpretation', 'UUID'])
if interp_uuid is None:
represented_interp = None
else:
represented_interp = rqo.WellboreInterpretation(self.model, uuid = interp_uuid)
return represented_interp
class Trajectory(BaseResqpy):
"""Class for RESQML Wellbore Trajectory Representation (Geometry).
note:
resqml allows trajectory to have different crs to the measured depth datum crs;
however, this code requires the trajectory to be in the same crs as the md datum
"""
resqml_type = 'WellboreTrajectoryRepresentation'
well_name = rqo._alias_for_attribute("title")
def __init__(
self,
parent_model,
trajectory_root = None, # deprecated
uuid = None,
md_datum = None,
deviation_survey = None,
data_frame = None,
grid = None,
cell_kji0_list = None,
wellspec_file = None,
spline_mode = 'cube',
deviation_survey_file = None,
survey_file_space_separated = False,
length_uom = None,
md_domain = None,
represented_interp = None,
well_name = None,
set_tangent_vectors = False,
hdf5_source_model = None,
originator = None,
extra_metadata = None):
"""Creates a new trajectory object and optionally loads it from xml, deviation survey, pandas dataframe, or
ascii file.
arguments:
parent_model (model.Model object): the model which the new trajectory belongs to
trajectory_root (DEPRECATED): use uuid instead; the root node of an xml tree representing the trajectory;
if not None, the new trajectory object is initialised based on the data in the tree;
if None, one of the other arguments is used
md_datum (MdDatum object): the datum that the depths for this trajectory are measured from;
not used if uuid or trajectory_root is not None
deviation_survey (DeviationSurvey object, optional): if present and uuid and trajectory_root are None
then the trajectory is derived from the deviation survey based on minimum curvature
data_frame (optional): a pandas dataframe with columns 'MD', 'X', 'Y' and 'Z', holding
the measured depths, and corresponding node locations; ignored if uuid or trajectory_root is not None
grid (grid.Grid object, optional): only required if initialising from a list of cell indices;
ignored otherwise
cell_kji0_list (numpy int array of shape (N, 3)): ordered list of cell indices to be visited by
the trajectory; ignored if uuid or trajectory_root is not None
wellspec_file (string, optional): name of an ascii file containing Nexus WELLSPEC data; well_name
and length_uom arguments must be passed
spline_mode (string, default 'cube'): one of 'none', 'linear', 'square', or 'cube'; affects spline
tangent generation; only relevant if initialising from list of cells
deviation_survey_file (string): filename of an ascii file holding the trajectory
in a tabular form; ignored if uuid or trajectory_root is not None
survey_file_space_separated (boolean, default False): if True, deviation survey file is
space separated; if False, comma separated (csv); ignored unless loading from survey file
length_uom (string, default 'm'): a resqml length unit of measure applicable to the
measured depths; should be 'm' or 'ft'
md_domain (string, optional): if present, must be 'logger' or 'driller'; the source of the original
deviation data; ignored if uuid or trajectory_root is not None
represented_interp (wellbore interpretation object, optional): if present, is noted as the wellbore
interpretation object which this trajectory relates to; ignored if uuid or trajectory_root is not None
well_name (string, optional): used as citation title
set_tangent_vectors (boolean, default False): if True and tangent vectors are not loaded then they will
be computed from the control points
hdf5_source_model (model.Model, optional): if present this model is used to determine the hdf5 file
name from which to load the trajectory's array data; if None, the parent_model is used as usual
originator (str, optional): the name of the person creating the trajectory, defaults to login id;
ignored if uuid or trajectory_root is not None
extra_metadata (dict, optional): string key, value pairs to add as extra metadata for the trajectory;
ignored if uuid or trajectory_root is not None
returns:
the newly created wellbore trajectory object
notes:
if starting from a deviation survey file, there are two routes: create a deviation survey object first,
using the azimuth and inclination data, then generate a trajectory from that based on minimum curvature;
or, create a trajectory directly using X, Y, Z data from the deviation survey file (ie. minimum
curvature or other algorithm already applied externally);
if not loading from xml, then the crs is set to that used by the measured depth datum, or if that is not
available then the default crs for the model
:meta common:
"""
self.crs_uuid = None
self.title = well_name
self.start_md = None
self.finish_md = None
self.md_uom = length_uom
self.md_domain = md_domain
self.md_datum = md_datum # md datum is an object in its own right, with a related crs!
# parametric line geometry elements
self.knot_count = None
self.line_kind_index = None
# 0 for vertical
# 1 for linear spline
# 2 for natural cubic spline
# 3 for cubic spline
# 4 for z linear cubic spline
# 5 for minimum-curvature spline # in practice this is the value actually used in datasets
# (-1) for null: no line
self.measured_depths = None # known as control point parameters in the parametric line geometry
self.control_points = None # xyz array of shape (knot_count, 3)
self.tangent_vectors = None # optional xyz tangent vector array, if present has same shape as control points)
self.deviation_survey = deviation_survey # optional related deviation survey
self.wellbore_interpretation = represented_interp
self.wellbore_feature = None
self.feature_and_interpretation_to_be_written = False
# todo: parent intersection for multi-lateral wells
# todo: witsml trajectory reference (optional)
super().__init__(model = parent_model,
uuid = uuid,
title = well_name,
originator = originator,
extra_metadata = extra_metadata,
root_node = trajectory_root)
if self.root is not None:
return
if set_tangent_vectors and self.knot_count > 1 and self.tangent_vectors is None:
self.set_tangents()
elif self.deviation_survey is not None:
self.compute_from_deviation_survey(method = 'minimum curvature', set_tangent_vectors = set_tangent_vectors)
elif data_frame is not None:
self.load_from_data_frame(data_frame,
md_uom = length_uom,
md_datum = md_datum,
set_tangent_vectors = set_tangent_vectors)
elif cell_kji0_list is not None:
self.load_from_cell_list(grid, cell_kji0_list, spline_mode, length_uom)
elif wellspec_file:
self.load_from_wellspec(grid, wellspec_file, well_name, spline_mode, length_uom)
elif deviation_survey_file:
self.load_from_ascii_file(deviation_survey_file,
space_separated_instead_of_csv = survey_file_space_separated,
md_uom = length_uom,
md_datum = md_datum,
title = well_name,
set_tangent_vectors = set_tangent_vectors)
# todo: create from already loaded deviation_survey node (ie. derive xyz points)
if self.crs_uuid is None:
if self.md_datum is not None:
self.crs_uuid = self.md_datum.crs_uuid
else:
self.crs_uuid = self.model.crs_uuid
if not self.title:
self.title = 'well trajectory'
if self.md_datum is None and self.control_points is not None:
self.md_datum = MdDatum(self.model, crs_uuid = self.crs_uuid, location = self.control_points[0])
@property
def crs_root(self):
"""XML node corresponding to self.crs_uuid."""
return self.model.root_for_uuid(self.crs_uuid)
def iter_wellbore_frames(self):
"""Iterable of all WellboreFrames associated with a trajectory.
Yields:
frame: instance of :class:`resqpy.organize.WellboreFrame`
:meta common:
"""
uuids = self.model.uuids(obj_type = "WellboreFrameRepresentation", related_uuid = self.uuid)
for uuid in uuids:
yield WellboreFrame(self.model, uuid = uuid)
def _load_from_xml(self):
"""Loads the trajectory object from an xml node (and associated hdf5 data)."""
node = self.root
assert node is not None
self.start_md = float(rqet.node_text(rqet.find_tag(node, 'StartMd')).strip())
self.finish_md = float(rqet.node_text(rqet.find_tag(node, 'FinishMd')).strip())
self.md_uom = rqet.length_units_from_node(rqet.find_tag(node, 'MdUom'))
self.md_domain = rqet.node_text(rqet.find_tag(node, 'MdDomain'))
geometry_node = rqet.find_tag(node, 'Geometry')
self.crs_uuid = bu.uuid_from_string(rqet.find_nested_tags_text(geometry_node, ['LocalCrs', 'UUID']))
self.knot_count = int(rqet.node_text(rqet.find_tag(geometry_node, 'KnotCount')).strip())
self.line_kind_index = int(rqet.node_text(rqet.find_tag(geometry_node, 'LineKindIndex')).strip())
mds_node = rqet.find_tag(geometry_node, 'ControlPointParameters')
if mds_node is not None: # not required for vertical or z linear cubic spline
load_hdf5_array(self, mds_node, 'measured_depths')
control_points_node = rqet.find_tag(geometry_node, 'ControlPoints')
load_hdf5_array(self, control_points_node, 'control_points', tag = 'Coordinates')
tangents_node = rqet.find_tag(geometry_node, 'TangentVectors')
if tangents_node is not None:
load_hdf5_array(self, tangents_node, 'tangent_vectors', tag = 'Coordinates')
relatives_model = self.model # if hdf5_source_model is None else hdf5_source_model
# md_datum - separate part, referred to in this tree
md_datum_uuid = bu.uuid_from_string(rqet.find_nested_tags_text(node, ['MdDatum', 'UUID']))
assert md_datum_uuid is not None, 'failed to fetch uuid of md datum for trajectory'
md_datum_part = relatives_model.part_for_uuid(md_datum_uuid)
assert md_datum_part, 'md datum part not found in model'
self.md_datum = MdDatum(self.model, uuid = relatives_model.uuid_for_part(md_datum_part))
ds_uuid = bu.uuid_from_string(rqet.find_nested_tags_text(node, ['DeviationSurvey', 'UUID']))
if ds_uuid is not None: # this will probably not work when relatives model is different from self.model
ds_part = rqet.part_name_for_object('obj_DeviationSurveyRepresentation_', ds_uuid)
self.deviation_survey = DeviationSurvey(self.model,
uuid = relatives_model.uuid_for_part(ds_part, is_rels = False),
md_datum = self.md_datum)
interp_uuid = rqet.find_nested_tags_text(node, ['RepresentedInterpretation', 'UUID'])
if interp_uuid is None:
self.wellbore_interpretation = None
else:
self.wellbore_interpretation = rqo.WellboreInterpretation(self.model, uuid = interp_uuid)
def compute_from_deviation_survey(self,
survey = None,
method = 'minimum curvature',
md_domain = None,
set_tangent_vectors = True):
"""Derive wellbore trajectory from deviation survey azimuth and inclination data."""
if survey is None:
assert self.deviation_survey is not None
survey = self.deviation_survey
else:
self.deviation_survey = survey
assert method in ['minimum curvature'] # if adding other methods, set line_kind_index appropriately
self.knot_count = survey.station_count
assert self.knot_count >= 2 # vertical well could be hamdled by allowing a single station in survey?
self.line_kind_index = 5 # minimum curvature spline
self.measured_depths = survey.measured_depths.copy()
self.md_uom = survey.md_uom
if not self.title:
self.title = rqet.find_nested_tags_text(survey.root_node, ['Citation', 'Title'])
self.start_md = self.measured_depths[0]
self.finish_md = self.measured_depths[-1]
if md_domain is not None:
self.md_domain = md_domain
self.control_points = np.empty((self.knot_count, 3))
self.control_points[0, :] = survey.first_station
for sp in range(1, self.knot_count):
i1 = survey.inclinations[sp - 1]
i2 = survey.inclinations[sp]
az1 = survey.azimuths[sp - 1]
az2 = survey.azimuths[sp]
delta_md = survey.measured_depths[sp] - survey.measured_depths[sp - 1]
assert delta_md > 0.0
if i1 == i2 and az1 == az2:
matrix = vec.rotation_3d_matrix((180.0 - i1, -az1, 0.0)) # TODO: check sign of az1
delta_v = vec.rotate_vector(matrix, np.array([0.0, delta_md, 0.0]))
else:
i1 = maths.radians(i1)
i2 = maths.radians(i2)
az1 = maths.radians(az1)
az2 = maths.radians(az2)
sin_i1 = maths.sin(i1)
sin_i2 = maths.sin(i2)
cos_theta = min(max(maths.cos(i2 - i1) - sin_i1 * sin_i2 * (1.0 - maths.cos(az2 - az1)), -1.0), 1.0)
theta = maths.acos(cos_theta)
# theta = maths.acos(sin_i1 * sin_i2 * maths.cos(az2 - az1) + (maths.cos(i1) * maths.cos(i2)))
assert theta != 0.0 # shouldn't happen as covered by if clause above
half_rf = maths.tan(0.5 * theta) / theta
delta_y = delta_md * half_rf * ((sin_i1 * maths.cos(az1)) + (sin_i2 * maths.cos(az2)))
delta_x = delta_md * half_rf * ((sin_i1 * maths.sin(az1)) + (sin_i2 * maths.sin(az2)))
delta_z = delta_md * half_rf * (maths.cos(i1) + maths.cos(i2))
delta_v = np.array((delta_x, delta_y, delta_z))
self.control_points[sp] = self.control_points[sp - 1] + delta_v
self.tangent_vectors = None
if set_tangent_vectors:
self.set_tangents()
self.md_datum = survey.md_datum
def load_from_data_frame(
self,
data_frame,
md_col = 'MD',
x_col = 'X',
y_col = 'Y',
z_col = 'Z',
md_uom = 'm',
md_domain = None,
md_datum = None, # MdDatum object
title = None,
set_tangent_vectors = True):
"""Load MD and control points (xyz) data from a pandas data frame."""
try:
for col in [md_col, x_col, y_col, z_col]:
assert col in data_frame.columns
self.knot_count = len(data_frame)
assert self.knot_count >= 2 # vertical well could be hamdled by allowing a single station in survey?
self.line_kind_index = 5 # assume minimum curvature spline
# self.md_uom = bwam.p_length_unit(md_uom)
self.md_uom = bwam.rq_length_unit(md_uom)
start = data_frame.iloc[0]
finish = data_frame.iloc[-1]
if title:
self.title = title
self.start_md = start[md_col]
self.finish_md = finish[md_col]
if md_domain is not None:
self.md_domain = md_domain
self.measured_depths = np.empty(self.knot_count)
self.measured_depths[:] = data_frame[md_col]
self.control_points = np.empty((self.knot_count, 3))
self.control_points[:, 0] = data_frame[x_col]
self.control_points[:, 1] = data_frame[y_col]
self.control_points[:, 2] = data_frame[z_col]
self.tangent_vectors = None
if set_tangent_vectors:
self.set_tangents()
self.md_datum = md_datum
except Exception:
log.exception('failed to load trajectory object from data frame')
def load_from_cell_list(self, grid, cell_kji0_list, spline_mode = 'cube', md_uom = 'm'):
"""Loads the trajectory object based on the centre points of a list of cells."""
assert grid is not None, 'grid argument missing for trajectory initislisation from cell list'
cell_kji0_list = np.array(cell_kji0_list, dtype = int)
assert cell_kji0_list.ndim == 2 and cell_kji0_list.shape[1] == 3
assert spline_mode in ['none', 'linear', 'square', 'cube']
cell_centres = grid.centre_point_list(cell_kji0_list)
knot_count = len(cell_kji0_list) + 2
self.line_kind_index = 5 # 5 means minimum curvature spline; todo: set to cubic spline value?
self.md_uom = bwam.rq_length_unit(md_uom)
self.start_md = 0.0
points = np.empty((knot_count, 3))
points[1:-1] = cell_centres
points[0] = points[1]
points[0, 2] = 0.0
points[-1] = points[-2]
points[-1, 2] *= 1.05
if spline_mode == 'none':
self.knot_count = knot_count
self.control_points = points
else:
self.control_points = rql.spline(points, tangent_weight = spline_mode, min_subdivisions = 3)
self.knot_count = len(self.control_points)
self.set_measured_depths()
def load_from_wellspec(self, grid, wellspec_file, well_name, spline_mode = 'cube', md_uom = 'm'):
col_list = ['IW', 'JW', 'L']
wellspec_dict = wsk.load_wellspecs(wellspec_file, well = well_name, column_list = col_list)
assert len(wellspec_dict) == 1, 'no wellspec data found in file ' + wellspec_file + ' for well ' + well_name
df = wellspec_dict[well_name]
assert len(df) > 0, 'no rows of perforation data found in wellspec for well ' + well_name
cell_kji0_list = np.empty((len(df), 3), dtype = int)
cell_kji0_list[:, 0] = df['L']
cell_kji0_list[:, 1] = df['JW']
cell_kji0_list[:, 2] = df['IW']
self.load_from_cell_list(grid, cell_kji0_list, spline_mode, md_uom)
def load_from_ascii_file(self,
trajectory_file,
comment_character = '#',
space_separated_instead_of_csv = False,
md_col = 'MD',
x_col = 'X',
y_col = 'Y',
z_col = 'Z',
md_uom = 'm',
md_domain = None,
md_datum = None,
well_col = None,
title = None,
set_tangent_vectors = True):
"""Loads the trajectory object from an ascii file with columns for MD, X, Y & Z (and optionally WELL)."""
if not title and not self.title:
self.title = 'well trajectory'
try:
df = pd.read_csv(trajectory_file,
comment = comment_character,
delim_whitespace = space_separated_instead_of_csv)
if df is None:
raise Exception
except Exception:
log.error('failed to read ascii deviation survey file ' + str(trajectory_file))
raise
if well_col and well_col not in df.columns:
log.warning('well column ' + str(well_col) + ' not found in ascii trajectory file ' + str(trajectory_file))
well_col = None
if well_col is None:
for col in df.columns:
if str(col).upper().startswith('WELL'):
well_col = col
break
if title: # filter data frame by well name
if well_col:
df = df[df[well_col] == title]
if len(df) == 0:
log.error('no data found for well ' + str(title) + ' in file ' + str(trajectory_file))
elif well_col is not None:
if len(set(df[well_col])) > 1:
raise Exception(
'attempt to set trajectory for unidentified well from ascii file holding data for multiple wells')
self.load_from_data_frame(df,
md_col = md_col,
x_col = x_col,
y_col = y_col,
z_col = z_col,
md_uom = md_uom,
md_domain = md_domain,
md_datum = md_datum,
title = title,
set_tangent_vectors = set_tangent_vectors)
def set_tangents(self, force = False, write_hdf5 = False, weight = 'cube'):
"""Calculates tangent vectors based on control points.
arguments:
force (boolean, default False): if False and tangent vectors already exist then the existing ones are used;
if True or no tangents vectors exist then they are computed
write_hdf5 (boolean, default False): if True and new tangent vectors are computed then the array is also written
directly to the hdf5 file
weight (string, default 'linear'): one of 'linear', 'square', 'cube'; if linear, each tangent is the mean of the
direction vectors of the two trjectory segments which meet at the knot; the square and cube options give
increased weight to the direction vector of shorter segments (usually better)
returns:
numpy float array of shape (knot_count, 3) being the tangents in xyz, 'pointing' in the direction of increased
knot index; the tangents are also stored as an attribute of the object
note:
the write_hdf5() method writes all the array data for the trajectory, including the tangent vectors; only set
the write_hdf5 argument to this method to True if the other arrays for the trajectory already exist in the hdf5 file
"""
if self.tangent_vectors is not None and not force:
return self.tangent_vectors
assert self.knot_count is not None and self.knot_count >= 2
assert self.control_points is not None and len(self.control_points) == self.knot_count
self.tangent_vectors = rql.tangents(self.control_points, weight = weight)
if write_hdf5:
h5_reg = rwh5.H5Register(self.model)
h5_reg.register_dataset(self.uuid, 'tangentVectors', self.tangent_vectors)
h5_reg.write(file = self.model.h5_filename(), mode = 'a')
return self.tangent_vectors
def dataframe(self, md_col = 'MD', x_col = 'X', y_col = 'Y', z_col = 'Z'):
"""Returns a pandas data frame containing MD and control points (xyz) data.
note:
set md_col to None for a dataframe containing only X, Y & Z data
:meta common:
"""
if md_col:
column_list = [md_col, x_col, y_col, z_col]
else:
column_list = [x_col, y_col, z_col]
data_frame = pd.DataFrame(columns = column_list)
if md_col:
data_frame[md_col] = self.measured_depths
data_frame[x_col] = self.control_points[:, 0]
data_frame[y_col] = self.control_points[:, 1]
data_frame[z_col] = self.control_points[:, 2]
return data_frame
def write_to_ascii_file(self,
trajectory_file,
mode = 'w',
space_separated_instead_of_csv = False,
md_col = 'MD',
x_col = 'X',
y_col = 'Y',
z_col = 'Z'):
"""Writes trajectory to an ascii file.
note:
set md_col to None for a dataframe containing only X, Y & Z data
"""
df = self.dataframe(md_col = md_col, x_col = x_col, y_col = y_col, z_col = z_col)
sep = ' ' if space_separated_instead_of_csv else ','
df.to_csv(trajectory_file, sep = sep, index = False, mode = mode)
def xyz_for_md(self, md):
"""Returns an xyz triplet corresponding to the given measured depth; uses simple linear interpolation between
knots.
args:
md (float): measured depth for which xyz location is required; units must be those of self.md_uom
returns:
triple float being x, y, z coordinates of point on trajectory corresponding to given measured depth
note:
the algorithm uses a simple linear interpolation between neighbouring knots (control points) on the trajectory;
if the measured depth is less than zero or greater than the finish md, a single None is returned; if the md is
less than the start md then a linear interpolation between the md datum location and the first knot is returned
:meta common:
"""
def interpolate(p1, p2, f):
return f * p2 + (1.0 - f) * p1
def search(md, i1, i2):
if i2 - i1 <= 1:
if md == self.measured_depths[i1]:
return self.control_points[i1]
return interpolate(self.control_points[i1], self.control_points[i1 + 1],
(md - self.measured_depths[i1]) /
(self.measured_depths[i1 + 1] - self.measured_depths[i1]))
im = i1 + (i2 - i1) // 2
if self.measured_depths[im] >= md:
return search(md, i1, im)
return search(md, im, i2)
if md < 0.0 or md > self.finish_md or md > self.measured_depths[-1]:
return None
if md <= self.start_md:
if self.start_md == 0.0:
return self.md_datum.location
return interpolate(np.array(self.md_datum.location), self.control_points[0], md / self.start_md)
return search(md, 0, self.knot_count - 1)
def splined_trajectory(self,
well_name,
min_subdivisions = 1,
max_segment_length = None,
max_degrees_per_knot = 5.0,
use_tangents_if_present = True,
store_tangents_if_calculated = True):
"""Creates and returns a new Trajectory derived as a cubic spline of this trajectory.
arguments:
well_name (string): the name to use as the citation title for the new trajectory
min_subdivisions (+ve integer, default 1): the minimum number of segments in the trajectory for each
segment in this trajectory
max_segment_length (float, optional): if present, each segment of this trajectory is subdivided so
that the naive subdivided length is not greater than the specified length
max_degrees_per_knot (float, default 5.0): the maximum number of degrees
use_tangents_if_present (boolean, default False): if True, any tangent vectors in this trajectory
are used during splining
store_tangents_if_calculated (boolean, default True): if True any tangents calculated by the method
are stored in the object (causing any previous tangents to be discarded); however, the new tangents
are not written to the hdf5 file by this method
returns:
Trajectory object with control points lying on a cubic spline of the points of this trajectory
notes:
this method is typically used to smoothe an artificial or simulator trajectory;
measured depths are re-calculated and will differ from those in this trajectory;
unexpected behaviour may occur if the z units are different from the xy units in the crs;
if tangent vectors for neighbouring points in this trajectory are pointing in opposite directions,
the resulting spline is likely to be bad;
the max_segment_length is applied when deciding how many subdivisions to make for a segment in this
trajectory, based on the stright line segment length; segments in the resulting spline may exceed this
length;
similarly max_degrees_per_knot assumes a simply bend between neighbouring knots; if the position of the
control points results in a loop, the value may be exceeded in the spline;
the hdf5 data for the splined trajectory is not written by this method, neither is the xml created;
no interpretation object is created by this method
NB: direction of tangent vectors affects results, set use_tangents_if_present = False to
ensure locally calculated tangent vectors are used
"""
assert self.knot_count > 1 and self.control_points is not None
assert min_subdivisions >= 1
assert max_segment_length is None or max_segment_length > 0.0
assert max_degrees_per_knot is None or max_degrees_per_knot > 0.0
if not well_name:
well_name = self.title
tangent_vectors = self.tangent_vectors
if tangent_vectors is None or not use_tangents_if_present:
tangent_vectors = rql.tangents(self.control_points, weight = 'square')
if store_tangents_if_calculated:
self.tangent_vectors = tangent_vectors
spline_traj = Trajectory(self.model,
well_name = well_name,
md_datum = self.md_datum,
length_uom = self.md_uom,
md_domain = self.md_domain)
spline_traj.line_kind_index = self.line_kind_index # not sure how we should really be setting this
spline_traj.crs_uuid = self.crs_uuid
spline_traj.start_md = self.start_md
spline_traj.deviation_survey = self.deviation_survey
spline_traj.control_points = rql.spline(self.control_points,
tangent_vectors = tangent_vectors,
min_subdivisions = min_subdivisions,
max_segment_length = max_segment_length,
max_degrees_per_knot = max_degrees_per_knot)
spline_traj.knot_count = len(spline_traj.control_points)
spline_traj.set_measured_depths()
return spline_traj
def set_measured_depths(self):
"""Sets the measured depths from the start_md value and the control points."""
self.measured_depths = np.empty(self.knot_count)
self.measured_depths[0] = self.start_md
for sk in range(1, self.knot_count):
self.measured_depths[sk] = (self.measured_depths[sk - 1] +
vec.naive_length(self.control_points[sk] - self.control_points[sk - 1]))
self.finish_md = self.measured_depths[-1]
return self.measured_depths
def create_feature_and_interpretation(self):
"""Instantiate new empty WellboreFeature and WellboreInterpretation objects, if a wellboreinterpretation does
not already exist.
Uses the trajectory citation title as the well name
"""
log.debug("Creating a new WellboreInterpretation..")
log.debug(f"WellboreFeature exists: {self.wellbore_feature is not None}")
log.debug(f"WellboreInterpretation exists: {self.wellbore_interpretation is not None}")
if self.wellbore_interpretation is None:
log.info(f"Creating WellboreInterpretation and WellboreFeature with name {self.title}")
self.wellbore_feature = rqo.WellboreFeature(parent_model = self.model, feature_name = self.title)
self.wellbore_interpretation = rqo.WellboreInterpretation(parent_model = self.model,
wellbore_feature = self.wellbore_feature)
self.feature_and_interpretation_to_be_written = True
else:
raise ValueError("Cannot add WellboreFeature, trajectory already has an associated WellboreInterpretation")
def create_xml(self,
ext_uuid = None,
wbt_uuid = None,
md_datum_root = None,
md_datum_xyz = None,
add_as_part = True,
add_relationships = True,
title = None,
originator = None):
"""Create a wellbore trajectory representation node from a Trajectory object, optionally add as part.
notes:
measured depth datum xml node must be in place before calling this function;
branching well structures (multi-laterals) are supported by the resqml standard but not yet by
this code;
optional witsml trajectory reference not yet supported here
:meta common:
"""
if title:
self.title = title
if not self.title:
self.title = 'wellbore trajectory'
if ext_uuid is None:
ext_uuid = self.model.h5_uuid()
if self.feature_and_interpretation_to_be_written:
if self.wellbore_interpretation is None:
self.create_feature_and_interpretation()
if self.wellbore_feature is not None:
self.wellbore_feature.create_xml(add_as_part = add_as_part, originator = originator)
self.wellbore_interpretation.create_xml(add_as_part = add_as_part,
add_relationships = add_relationships,
originator = originator)
if md_datum_root is None:
if self.md_datum is None:
assert md_datum_xyz is not None
self.md_datum = MdDatum(self.model, location = md_datum_xyz)
if self.md_datum.root is None:
md_datum_root = self.md_datum.create_xml()
else:
md_datum_root = self.md_datum.root
wbt_node = super().create_xml(originator = originator, add_as_part = False)
start_node = rqet.SubElement(wbt_node, ns['resqml2'] + 'StartMd')
start_node.set(ns['xsi'] + 'type', ns['xsd'] + 'double')
start_node.text = str(self.start_md)
finish_node = rqet.SubElement(wbt_node, ns['resqml2'] + 'FinishMd')
finish_node.set(ns['xsi'] + 'type', ns['xsd'] + 'double')
finish_node.text = str(self.finish_md)
md_uom = rqet.SubElement(wbt_node, ns['resqml2'] + 'MdUom')
md_uom.set(ns['xsi'] + 'type', ns['eml'] + 'LengthUom')
md_uom.text = bwam.rq_length_unit(self.md_uom)
self.model.create_md_datum_reference(self.md_datum.root, root = wbt_node)
if self.line_kind_index != 0: # 0 means vertical well, which doesn't need a geometry
# todo: check geometry elements for parametric curve flavours other than minimum curvature
geom = rqet.SubElement(wbt_node, ns['resqml2'] + 'Geometry')
geom.set(ns['xsi'] + 'type', ns['resqml2'] + 'ParametricLineGeometry')
geom.text = '\n'
# note: resqml standard allows trajectory to be in different crs to md datum
# however, this module often uses the md datum crs, if the trajectory has been imported
if self.crs_uuid is None:
self.crs_uuid = self.md_datum.crs_uuid
assert self.crs_uuid is not None
self.model.create_crs_reference(crs_uuid = self.crs_uuid, root = geom)
kc_node = rqet.SubElement(geom, ns['resqml2'] + 'KnotCount')
kc_node.set(ns['xsi'] + 'type', ns['xsd'] + 'positiveInteger')
kc_node.text = str(self.knot_count)
lki_node = rqet.SubElement(geom, ns['resqml2'] + 'LineKindIndex')
lki_node.set(ns['xsi'] + 'type', ns['xsd'] + 'integer')
lki_node.text = str(self.line_kind_index)
cpp_node = rqet.SubElement(geom, ns['resqml2'] + 'ControlPointParameters')
cpp_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'DoubleHdf5Array')
cpp_node.text = rqet.null_xml_text
cpp_values_node = rqet.SubElement(cpp_node, ns['resqml2'] + 'Values')
cpp_values_node.set(ns['xsi'] + 'type', ns['eml'] + 'Hdf5Dataset')
cpp_values_node.text = rqet.null_xml_text
self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'controlPointParameters', root = cpp_values_node)
cp_node = rqet.SubElement(geom, ns['resqml2'] + 'ControlPoints')
cp_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'Point3dHdf5Array')
cp_node.text = rqet.null_xml_text
cp_coords_node = rqet.SubElement(cp_node, ns['resqml2'] + 'Coordinates')
cp_coords_node.set(ns['xsi'] + 'type', ns['eml'] + 'Hdf5Dataset')
cp_coords_node.text = rqet.null_xml_text
self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'controlPoints', root = cp_coords_node)
if self.tangent_vectors is not None:
tv_node = rqet.SubElement(geom, ns['resqml2'] + 'TangentVectors')
tv_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'Point3dHdf5Array')
tv_node.text = rqet.null_xml_text
tv_coords_node = rqet.SubElement(tv_node, ns['resqml2'] + 'Coordinates')
tv_coords_node.set(ns['xsi'] + 'type', ns['eml'] + 'Hdf5Dataset')
tv_coords_node.text = rqet.null_xml_text
self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'tangentVectors', root = tv_coords_node)
if self.md_domain:
domain_node = rqet.SubElement(wbt_node, ns['resqml2'] + 'MdDomain')
domain_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'MdDomain')
domain_node.text = self.md_domain
if self.deviation_survey is not None:
ds_root = self.deviation_survey.root_node
self.model.create_ref_node('DeviationSurvey',
rqet.find_tag(rqet.find_tag(ds_root, 'Citation'), 'Title').text,
bu.uuid_from_string(ds_root.attrib['uuid']),
content_type = 'obj_DeviationSurveyRepresentation',
root = wbt_node)
interp_root = None
if self.wellbore_interpretation is not None:
interp_root = self.wellbore_interpretation.root
self.model.create_ref_node('RepresentedInterpretation',
rqet.find_nested_tags_text(interp_root, ['Citation', 'Title']),
bu.uuid_from_string(interp_root.attrib['uuid']),
content_type = 'obj_WellboreInterpretation',
root = wbt_node)
if add_as_part:
self.model.add_part('obj_WellboreTrajectoryRepresentation', self.uuid, wbt_node)
if add_relationships:
crs_root = self.crs_root
self.model.create_reciprocal_relationship(wbt_node, 'destinationObject', crs_root, 'sourceObject')
self.model.create_reciprocal_relationship(wbt_node, 'destinationObject', self.md_datum.root,
'sourceObject')
if self.deviation_survey is not None:
self.model.create_reciprocal_relationship(wbt_node, 'destinationObject',
self.deviation_survey.root_node, 'sourceObject')
if interp_root is not None:
self.model.create_reciprocal_relationship(wbt_node, 'destinationObject', interp_root,
'sourceObject')
ext_part = rqet.part_name_for_object('obj_EpcExternalPartReference', ext_uuid, prefixed = False)
ext_node = self.model.root_for_part(ext_part)
self.model.create_reciprocal_relationship(wbt_node, 'mlToExternalPartProxy', ext_node,
'externalPartProxyToMl')
return wbt_node
def write_hdf5(self, file_name = None, mode = 'a'):
"""Create or append to an hdf5 file, writing datasets for the measured depths, control points and tangent
vectors.
:meta common:
"""
# NB: array data must all have been set up prior to calling this function
if self.uuid is None:
self.uuid = bu.new_uuid()
h5_reg = rwh5.H5Register(self.model)
h5_reg.register_dataset(self.uuid, 'controlPointParameters', self.measured_depths)
h5_reg.register_dataset(self.uuid, 'controlPoints', self.control_points)
if self.tangent_vectors is not None:
h5_reg.register_dataset(self.uuid, 'tangentVectors', self.tangent_vectors)
h5_reg.write(file = file_name, mode = mode)
def __eq__(self, other):
"""Implements equals operator.
Compares class type and uuid
"""
# TODO: more detailed equality comparison
other_uuid = getattr(other, "uuid", None)
return isinstance(other, self.__class__) and bu.matching_uuids(self.uuid, other_uuid)
class WellboreFrame(BaseResqpy):
"""Class for RESQML WellboreFrameRepresentation objects (supporting well log Properties)
RESQML documentation:
Representation of a wellbore that is organized along a wellbore trajectory by its MD values.
RESQML uses MD values to associate properties on points and to organize association of
properties on intervals between MD points.
Roughly equivalent to a Techlog "dataset" object with a given depth reference.
The `logs` attribute is a :class:`resqpy.property.WellLogCollection` of all logs in the frame.
"""
resqml_type = 'WellboreFrameRepresentation'
def __init__(self,
parent_model,
frame_root = None,
uuid = None,
trajectory = None,
mds = None,
represented_interp = None,
title = None,
originator = None,
extra_metadata = None):
"""Creates a new wellbore frame object and optionally loads it from xml or list of measured depths.
arguments:
parent_model (model.Model object): the model which the new wellbore frame belongs to
frame_root (optional): DEPRECATED. the root node of an xml tree representing the wellbore frame;
if not None, the new wellbore frame object is initialised based on the data in the tree;
if None, an empty wellbore frame object is returned
trajectory (Trajectory object, optional): the trajectory of the well; required if loading from
list of measured depths
mds (optional numpy 1D array, tuple or list of floats): ordered list of measured depths which
will constitute the frame; ignored if frame_root is not None
represented_interp (wellbore interpretation object, optional): if present, is noted as the wellbore
interpretation object which this frame relates to; ignored if frame_root is not None
title (str, optional): the citation title to use for a new wellbore frame;
ignored if uuid or frame_root is not None
originator (str, optional): the name of the person creating the wellbore frame, defaults to login id;
ignored if uuid or frame_root is not None
extra_metadata (dict, optional): string key, value pairs to add as extra metadata for the wellbore frame;
ignored if uuid or frame_root is not None
returns:
the newly created wellbore frame object
note:
if initialising from a list of measured depths, the wellbore trajectory object must already exist
"""
#: Associated wellbore trajectory, an instance of :class:`resqpy.well.Trajectory`.
self.trajectory = trajectory
self.trajectory_uuid = None if trajectory is None else trajectory.uuid
#: Instance of :class:`resqpy.organize.WellboreInterpretation`
self.wellbore_interpretation = represented_interp
self.wellbore_feature = None
self.feature_and_interpretation_to_be_written = False
#: number of measured depth nodes, each being an entry or exit point of trajectory with a cell
self.node_count = None
#: node_count measured depths (in same units and datum as trajectory) of cell entry and/or exit points
self.node_mds = None
#: All logs associated with the wellbore frame; an instance of :class:`resqpy.property.WellLogCollection`
self.logs = None
super().__init__(model = parent_model,
uuid = uuid,
title = title,
originator = originator,
extra_metadata = extra_metadata,
root_node = frame_root)
if self.root is None and trajectory is not None and mds is not None and len(mds) > 1:
self.node_count = len(mds)
self.node_mds = np.array(mds)
assert self.node_mds is not None and self.node_mds.ndim == 1
# UUID needs to have been created before LogCollection can be made
# TODO: Figure out when this should be created, and how it is kept in sync when new logs are created
self.logs = rqp.WellLogCollection(frame = self)
def _load_from_xml(self):
"""Loads the wellbore frame object from an xml node (and associated hdf5 data)."""
# NB: node is the root level xml node, not a node in the md list!
node = self.root
assert node is not None
trajectory_uuid = bu.uuid_from_string(rqet.find_nested_tags_text(node, ['Trajectory', 'UUID']))
assert trajectory_uuid is not None, 'wellbore frame trajectory reference not found in xml'
if self.trajectory is None:
self.trajectory = Trajectory(self.model, uuid = trajectory_uuid)
else:
assert bu.matching_uuids(self.trajectory.uuid, trajectory_uuid), 'wellbore frame trajectory uuid mismatch'
self.node_count = rqet.find_tag_int(node, 'NodeCount')
assert self.node_count is not None, 'node count not found in xml for wellbore frame'
assert self.node_count > 1, 'fewer than 2 nodes for wellbore frame'
mds_node = rqet.find_tag(node, 'NodeMd')
assert mds_node is not None, 'wellbore frame measured depths hdf5 reference not found in xml'
load_hdf5_array(self, mds_node, 'node_mds')
assert self.node_mds is not None and self.node_mds.ndim == 1 and self.node_mds.size == self.node_count
interp_uuid = rqet.find_nested_tags_text(node, ['RepresentedInterpretation', 'UUID'])
if interp_uuid is None:
self.wellbore_interpretation = None
else:
self.wellbore_interpretation = rqo.WellboreInterpretation(self.model, uuid = interp_uuid)
# Create well log collection of all log data
self.logs = rqp.WellLogCollection(frame = self)
def extract_crs_root(self):
"""Returns the xml root node of the coordinate reference system used by the related trajectory."""
if self.trajectory is None:
return None
return self.trajectory.crs_root
def create_feature_and_interpretation(self):
"""Instantiate new empty WellboreFeature and WellboreInterpretation objects, if a wellboreinterpretation does
not already exist.
Uses the wellboreframe citation title as the well name
"""
if self.wellbore_interpretation is not None:
log.info(f"Creating WellboreInterpretation and WellboreFeature with name {self.title}")
self.wellbore_feature = rqo.WellboreFeature(parent_model = self.model, feature_name = self.title)
self.wellbore_interpretation = rqo.WellboreInterpretation(parent_model = self.model,
wellbore_feature = self.wellbore_feature)
self.feature_and_interpretation_to_be_written = True
else:
log.info("WellboreInterpretation already exists")
def write_hdf5(self, file_name = None, mode = 'a'):
"""Create or append to an hdf5 file, writing datasets for the measured depths."""
# NB: array data must have been set up prior to calling this function
if self.uuid is None:
self.uuid = bu.new_uuid()
h5_reg = rwh5.H5Register(self.model)
h5_reg.register_dataset(self.uuid, 'NodeMd', self.node_mds)
h5_reg.write(file = file_name, mode = mode)
def create_xml(self,
ext_uuid = None,
add_as_part = True,
add_relationships = True,
title = None,
originator = None):
"""Create a wellbore frame representation node from this WellboreFrame object, optionally add as part.
note:
trajectory xml node must be in place before calling this function
"""
assert self.trajectory is not None, 'trajectory object missing'
assert self.trajectory.root is not None, 'trajectory xml not established'
if self.feature_and_interpretation_to_be_written:
if self.wellbore_interpretation is None:
self.create_feature_and_interpretation()
if self.wellbore_feature is not None:
self.wellbore_feature.create_xml(add_as_part = add_as_part, originator = originator)
self.wellbore_interpretation.create_xml(add_as_part = add_as_part,
add_relationships = add_relationships,
originator = originator)
if ext_uuid is None:
ext_uuid = self.model.h5_uuid()
if title:
self.title = title
if not self.title:
self.title = 'wellbore frame'
wf_node = super().create_xml(originator = originator, add_as_part = False)
# wellbore frame elements
nc_node = rqet.SubElement(wf_node, ns['resqml2'] + 'NodeCount')
nc_node.set(ns['xsi'] + 'type', ns['xsd'] + 'positiveInteger')
nc_node.text = str(self.node_count)
mds_node = rqet.SubElement(wf_node, ns['resqml2'] + 'NodeMd')
mds_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'DoubleHdf5Array')
mds_node.text = rqet.null_xml_text
mds_values_node = rqet.SubElement(mds_node, ns['resqml2'] + 'Values')
mds_values_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'Hdf5Dataset')
mds_values_node.text = rqet.null_xml_text
self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'NodeMd', root = mds_values_node)
traj_root = self.trajectory.root
self.model.create_ref_node('Trajectory',
rqet.find_nested_tags_text(traj_root, ['Citation', 'Title']),
bu.uuid_from_string(traj_root.attrib['uuid']),
content_type = 'obj_WellboreTrajectoryRepresentation',
root = wf_node)
if self.wellbore_interpretation is not None:
interp_root = self.wellbore_interpretation.root
self.model.create_ref_node('RepresentedInterpretation',
rqet.find_nested_tags_text(interp_root, ['Citation', 'Title']),
bu.uuid_from_string(interp_root.attrib['uuid']),
content_type = 'obj_WellboreInterpretation',
root = wf_node)
if add_as_part:
self.model.add_part('obj_WellboreFrameRepresentation', self.uuid, wf_node)
if add_relationships:
self.model.create_reciprocal_relationship(wf_node, 'destinationObject', self.trajectory.root,
'sourceObject')
ext_part = rqet.part_name_for_object('obj_EpcExternalPartReference', ext_uuid, prefixed = False)
ext_node = self.model.root_for_part(ext_part)
self.model.create_reciprocal_relationship(wf_node, 'mlToExternalPartProxy', ext_node,
'externalPartProxyToMl')
if self.wellbore_interpretation is not None:
interp_root = self.wellbore_interpretation.root
self.model.create_reciprocal_relationship(wf_node, 'destinationObject', interp_root, 'sourceObject')
return wf_node
class BlockedWell(BaseResqpy):
"""Class for RESQML Blocked Wellbore Representation (Wells), ie cells visited by wellbore.
RESQML documentation:
The information that allows you to locate, on one or several grids (existing or planned),
the intersection of volume (cells) and surface (faces) elements with a wellbore trajectory
(existing or planned).
note:
measured depth data must be in same crs as those for the related trajectory
"""
resqml_type = 'BlockedWellboreRepresentation'
well_name = rqo._alias_for_attribute("title")
def __init__(self,
parent_model,
blocked_well_root = None,
uuid = None,
grid = None,
trajectory = None,
wellspec_file = None,
cellio_file = None,
column_ji0 = None,
well_name = None,
check_grid_name = False,
use_face_centres = False,
represented_interp = None,
originator = None,
extra_metadata = None,
add_wellspec_properties = False):
"""Creates a new blocked well object and optionally loads it from xml, or trajectory, or Nexus wellspec file.
arguments:
parent_model (model.Model object): the model which the new blocked well belongs to
blocked_well_root (DEPRECATED): the root node of an xml tree representing the blocked well;
if not None, the new blocked well object is initialised based on the data in the tree;
if None, the other arguments are used
grid (optional, grid.Grid object): required if intialising from a trajectory or wellspec file;
not used if blocked_well_root is not None
trajectory (optional, Trajectory object): the trajectory of the well, to be intersected with the grid;
not used if blocked_well_root is not None
wellspec_file (optional, string): filename of an ascii file holding the Nexus wellspec data;
ignored if blocked_well_root is not None or trajectory is not None
cellio_file (optional, string): filename of an ascii file holding the RMS exported blocked well data;
ignored if blocked_well_root is not None or trajectory is not None or wellspec_file is not None
column_ji0 (optional, pair of ints): column indices (j0, i0) for a 'vertical' well; ignored if
blocked_well_root is not None or trajectory is not None or wellspec_file is not None or
cellio_file is not None
well_name (string): the well name as given in the wellspec or cellio file; required if loading from
one of those files; or the name to be used as citation title for a column well
check_grid_name (boolean, default False): if True, the GRID column of the wellspec data will be checked
for a match with the citation title of the grid object; perforations for other grids will be skipped;
if False, all wellspec data is assumed to relate to the grid; only relevant when loading from wellspec
use_face_centres (boolean, default False): if True, cell face centre points are used for the entry and
exit points when constructing the simulation trajectory; if False and ANGLA & ANGLV data are available
then entry and exit points are constructed based on a straight line at those angles passing through
the centre of the cell; only relevant when loading from wellspec
represented_interp (wellbore interpretation object, optional): if present, is noted as the wellbore
interpretation object which this frame relates to; ignored if blocked_well_root is not None
originator (str, optional): the name of the person creating the blocked well, defaults to login id;
ignored if uuid or blocked_well_root is not None
extra_metadata (dict, optional): string key, value pairs to add as extra metadata for the blocked well;
ignored if uuid or blocked_well_root is not None
add_wellspec_properties (boolean or list of str, default False): if not False, and initialising from
a wellspec file, the blocked well has its hdf5 data written and xml created and properties are
fully created; if a list is provided the elements must be numerical wellspec column names;
if True, all numerical columns other than the cell indices are added as properties
returns:
the newly created blocked well object
notes:
if starting from a wellspec file or column indices, a 'simulation' trajectory and md datum objects are
constructed to go with the blocked well;
column wells might not be truly vertical - the trajectory will consist of linear segments joining the
centres of the k faces in the column;
optional RESQML attributes are not handled by this code (WITSML log reference, interval stratigraphic units,
cell fluid phase units);
mysterious RESQML WellboreFrameIndexableElements is not used in any other RESQML classes and is therefore
not used here
:meta common:
"""
self.trajectory = trajectory #: trajectory object associated with the wellbore
self.trajectory_to_be_written = False
self.feature_to_be_written = False
self.interpretation_to_be_written = False
self.node_count = None #: number of measured depth nodes, each being an entry or exit point of trajectory with a cell
self.node_mds = None #: node_count measured depths (in same units and datum as trajectory) of cell entry and/or exit points
self.cell_count = None #: number of blocked intervals (<= node_count - 1)
self.cell_indices = None #: cell_count natural cell indices, paired with non-null grid_indices
self.grid_indices = None #: node_count-1 indices into grid list for each interval in node_mds; -1 for unblocked interval
self.face_pair_indices = None #: entry, exit face per cell indices, -1 for Target Depth termination within a cell
self.grid_list = [
] #: list of grid objects indexed by grid_indices; for now only handles 1 grid unless loading from xml
self.wellbore_interpretation = None #: associated wellbore interpretation object
self.wellbore_feature = None #: associated wellbore feature object
#: All logs associated with the blockedwellbore; an instance of :class:`resqpy.property.WellIntervalPropertyCollection`
self.logs = None
self.cellind_null = None
self.gridind_null = None
self.facepair_null = None
# face_index_map maps from (axis, p01) to face index value in range 0..5
# this is the default as indicated on page 139 (but not p. 180) of the RESQML Usage Gude v2.0.1
# also assumes K is generally increasing downwards
# see DevOps backlog item 269001 discussion for more information
# self.face_index_map = np.array([[0, 1], [4, 2], [5, 3]], dtype = int)
self.face_index_map = np.array([[0, 1], [2, 4], [5, 3]], dtype = int) # order: top, base, J-, I+, J+, I-
# and the inverse, maps from 0..5 to (axis, p01)
# self.face_index_inverse_map = np.array([[0, 0], [0, 1], [1, 1], [2, 1], [1, 0], [2, 0]], dtype = int)
self.face_index_inverse_map = np.array([[0, 0], [0, 1], [1, 0], [2, 1], [1, 1], [2, 0]], dtype = int)
# note: the rework_face_pairs() method, below, overwrites the face indices based on I, J cell indices
super().__init__(model = parent_model,
uuid = uuid,
title = well_name,
originator = originator,
extra_metadata = extra_metadata,
root_node = blocked_well_root)
if self.root is None:
self.wellbore_interpretation = represented_interp
if grid is None and (self.trajectory is not None or wellspec_file is not None or cellio_file is not None or
column_ji0 is not None):
grid = self.model.grid()
if self.trajectory is not None:
self.compute_from_trajectory(self.trajectory, grid)
elif wellspec_file is not None:
okay = self.derive_from_wellspec(wellspec_file,
well_name,
grid,
check_grid_name = check_grid_name,
use_face_centres = use_face_centres,
add_properties = add_wellspec_properties)
elif cellio_file is not None:
okay = self.import_from_rms_cellio(cellio_file, well_name, grid)
if not okay:
self.node_count = 0
elif column_ji0 is not None:
okay = self.set_for_column(well_name, grid, column_ji0)
self.gridind_null = -1
self.facepair_null = -1
self.cellind_null = -1
# else an empty object is returned
def _load_from_xml(self):
"""Loads the blocked wellbore object from an xml node (and associated hdf5 data)."""
node = self.root
assert node is not None
trajectory_uuid = bu.uuid_from_string(rqet.find_nested_tags_text(node, ['Trajectory', 'UUID']))
assert trajectory_uuid is not None, 'blocked well trajectory reference not found in xml'
if self.trajectory is None:
self.trajectory = Trajectory(self.model, uuid = trajectory_uuid)
else:
assert bu.matching_uuids(self.trajectory.uuid, trajectory_uuid), 'blocked well trajectory uuid mismatch'
self.node_count = rqet.find_tag_int(node, 'NodeCount')
assert self.node_count is not None and self.node_count >= 2, 'problem with blocked well node count'
mds_node = rqet.find_tag(node, 'NodeMd')
assert mds_node is not None, 'blocked well node measured depths hdf5 reference not found in xml'
load_hdf5_array(self, mds_node, 'node_mds')
# Statement below has no effect, is this a bug?
self.node_mds is not None and self.node_mds.ndim == 1 and self.node_mds.size == self.node_count
self.cell_count = rqet.find_tag_int(node, 'CellCount')
assert self.cell_count is not None and self.cell_count > 0
# TODO: remove this if block once RMS export issue resolved
if self.cell_count == self.node_count:
extended_mds = np.empty((self.node_mds.size + 1,))
extended_mds[:-1] = self.node_mds
extended_mds[-1] = self.node_mds[-1] + 1.0
self.node_mds = extended_mds
self.node_count += 1
assert self.cell_count < self.node_count
ci_node = rqet.find_tag(node, 'CellIndices')
assert ci_node is not None, 'blocked well cell indices hdf5 reference not found in xml'
load_hdf5_array(self, ci_node, 'cell_indices', dtype = int)
assert (self.cell_indices is not None and self.cell_indices.ndim == 1 and
self.cell_indices.size == self.cell_count), 'mismatch in number of cell indices for blocked well'
self.cellind_null = rqet.find_tag_int(ci_node, 'NullValue')
if self.cellind_null is None:
self.cellind_null = -1 # if no Null found assume -1 default
fi_node = rqet.find_tag(node, 'LocalFacePairPerCellIndices')
assert fi_node is not None, 'blocked well face indices hdf5 reference not found in xml'
load_hdf5_array(self, fi_node, 'raw_face_indices', dtype = 'int')
assert self.raw_face_indices is not None, 'failed to load face indices for blocked well'
assert self.raw_face_indices.size == 2 * self.cell_count, 'mismatch in number of cell faces for blocked well'
if self.raw_face_indices.ndim > 1:
self.raw_face_indices = self.raw_face_indices.reshape((self.raw_face_indices.size,))
mask = np.where(self.raw_face_indices == -1)
self.raw_face_indices[mask] = 0
self.face_pair_indices = self.face_index_inverse_map[self.raw_face_indices]
self.face_pair_indices[mask] = (-1, -1)
self.face_pair_indices = self.face_pair_indices.reshape((-1, 2, 2))
del self.raw_face_indices
self.facepair_null = rqet.find_tag_int(fi_node, 'NullValue')
if self.facepair_null is None:
self.facepair_null = -1
gi_node = rqet.find_tag(node, 'GridIndices')
assert gi_node is not None, 'blocked well grid indices hdf5 reference not found in xml'
load_hdf5_array(self, gi_node, 'grid_indices', dtype = 'int')
assert self.grid_indices is not None and self.grid_indices.ndim == 1 and self.grid_indices.size == self.node_count - 1
unique_grid_indices = np.unique(self.grid_indices) # sorted list of unique values
self.gridind_null = rqet.find_tag_int(gi_node, 'NullValue')
if self.gridind_null is None:
self.gridind_null = -1 # if no Null found assume -1 default
grid_node_list = rqet.list_of_tag(node, 'Grid')
assert len(grid_node_list) > 0, 'blocked well grid reference(s) not found in xml'
assert unique_grid_indices[0] >= -1 and unique_grid_indices[-1] < len(
grid_node_list), 'blocked well grid index out of range'
assert np.count_nonzero(
self.grid_indices >= 0) == self.cell_count, 'mismatch in number of blocked well intervals'
self.grid_list = []
for grid_ref_node in grid_node_list:
grid_node = self.model.referenced_node(grid_ref_node)
assert grid_node is not None, 'grid referenced in blocked well xml is not present in model'
grid_uuid = rqet.uuid_for_part_root(grid_node)
grid_obj = self.model.grid(uuid = grid_uuid, find_properties = False)
self.grid_list.append(grid_obj)
interp_uuid = rqet.find_nested_tags_text(node, ['RepresentedInterpretation', 'UUID'])
if interp_uuid is None:
self.wellbore_interpretation = None
else:
self.wellbore_interpretation = rqo.WellboreInterpretation(self.model, uuid = interp_uuid)
# Create blocked well log collection of all log data
self.logs = rqp.WellIntervalPropertyCollection(frame = self)
# Set up matches between cell_indices and grid_indices
self.cell_grid_link = self.map_cell_and_grid_indices()
def map_cell_and_grid_indices(self):
"""Returns a list of index values linking the grid_indices to cell_indices.
note:
length will match grid_indices, and will show -1 where cell is unblocked
"""
indexmap = []
j = 0
for i in self.grid_indices:
if i == -1:
indexmap.append(-1)
else:
indexmap.append(j)
j += 1
return indexmap
def compressed_grid_indices(self):
"""Returns a list of grid indices excluding the -1 elements (unblocked intervals).
note:
length will match that of cell_indices
"""
compressed = []
for i in self.grid_indices:
if i >= 0:
compressed.append(i)
assert len(compressed) == self.cell_count
return compressed
def number_of_grids(self):
"""Returns the number of grids referenced by the blocked well object."""
if self.grid_list is None:
return 0
return len(self.grid_list)
def single_grid(self):
"""Asserts that exactly one grid is being referenced and returns a grid object for that grid."""
assert len(self.grid_list) == 1, 'blocked well is not referring to exactly one grid'
return self.grid_list[0]
def grid_uuid_list(self):
"""Returns a list of the uuids of the grids referenced by the blocked well object.
:meta common:
"""
uuid_list = []
if self.grid_list is None:
return uuid_list
for g in self.grid_list:
uuid_list.append(g.uuid)
return uuid_list
def cell_indices_kji0(self):
"""Returns a numpy int array of shape (N, 3) of cells visited by well, for a single grid situation.
:meta common:
"""
grid = self.single_grid()
return grid.denaturalized_cell_indices(self.cell_indices)
def cell_indices_and_grid_list(self):
"""Returns a numpy int array of shape (N, 3) of cells visited by well, and a list of grid objects of length N.
:meta common:
"""
grid_for_cell_list = []
grid_indices = self.compressed_grid_indices()
assert len(grid_indices) == self.cell_count
cell_indices = np.empty((self.cell_count, 3), dtype = int)
for cell_number in range(self.cell_count):
grid = self.grid_list[grid_indices[cell_number]]
grid_for_cell_list.append(grid)
cell_indices[cell_number] = grid.denaturalized_cell_index(self.cell_indices[cell_number])
return cell_indices, grid_for_cell_list
def cell_indices_for_grid_uuid(self, grid_uuid):
"""Returns a numpy int array of shape (N, 3) of cells visited by well in specified grid.
:meta common:
"""
if isinstance(grid_uuid, str):
grid_uuid = bu.uuid_from_string(grid_uuid)
ci_list, grid_list = self.cell_indices_and_grid_list()
mask = np.zeros((len(ci_list),), dtype = bool)
for cell_number in range(len(ci_list)):
mask[cell_number] = bu.matching_uuids(grid_list[cell_number].uuid, grid_uuid)
ci_selected = ci_list[mask]
return ci_selected
def box(self, grid_uuid = None):
"""Returns the KJI box containing the cells visited by the well, for single grid if grid_uuid is None."""
if grid_uuid is None:
cells_kji0 = self.cell_indices_kji0()
else:
cells_kji0 = self.cell_indices_for_grid_uuid(grid_uuid)
if cells_kji0 is None or len(cells_kji0) == 0:
return None
well_box = np.empty((2, 3), dtype = int)
well_box[0] = np.min(cells_kji0, axis = 0)
well_box[1] = np.max(cells_kji0, axis = 0)
return well_box
def face_pair_array(self):
"""Returns numpy int array of shape (N, 2, 2) being pairs of face (axis, polarity) pairs, to go with
cell_kji0_array().
note:
each of the N rows in the returned array is of the form:
((entry_face_axis, entry_face_polarity), (exit_face_axis, exit_face_polarity))
where the axis values are in the range 0 to 2 for k, j & i respectively, and
the polarity values are zero for the 'negative' face and 1 for the 'positive' face;
exit values may be -1 to indicate TD within the cell (ie. no exit point)
"""
return self.face_pair_indices
def compute_from_trajectory(self,
trajectory,
grid,
active_only = False,
quad_triangles = True,
use_single_layer_tactics = True):
"""Populate this blocked wellbore object based on intersection of trajectory with cells of grid.
arguments:
trajectory (Trajectory object): the trajectory to intersect with the grid; control_points and crs_root attributes must
be populated
grid (grid.Grid object): the grid with which to intersect the trajectory
active_only (boolean, default False): if True, only active cells are included as blocked intervals
quad_triangles (boolean, default True): if True, 4 triangles per cell face are used for the intersection calculations;
if False, only 2 triangles per face are used
use_single_layer_tactics (boolean, default True): if True and the grid does not have k gaps, initial intersection
calculations with fault planes or the outer IK & JK skin of the grid are calculated as if the grid is a single
layer (and only after an intersection is thus found is the actual layer identified); this significantly speeds up
computation but may cause failure in the presence of significantly non-straight pillars and could (rarely) cause
problems where a fault plane is significantly skewed (non-planar) even if individual pillars are straight
note:
this method is computationally intensive and might take ~30 seconds for a tyipical grid and trajectory; large grids,
grids with k gaps, or setting use_single_layer_tactics False will typically result in significantly longer processing time
"""
import resqpy.grid_surface as rgs # was causing circular import issue when at global level
# note: see also extract_box_for_well code
assert trajectory is not None and grid is not None
if np.any(np.isnan(grid.points_ref(masked = False))):
log.warning('grid does not have geometry defined everywhere: attempting fill')
import resqpy.derived_model as rqdm
fill_grid = rqdm.copy_grid(grid)
fill_grid.set_geometry_is_defined(nullify_partial_pillars = True, complete_all = True)
# note: may need to write hdf5 and create xml for fill_grid, depending on use in populate_blocked_well_from_trajectory()
# fill_grid.write_hdf_from_caches()
# fill_grid.create_xml
grid = fill_grid
assert trajectory.control_points is not None and trajectory.crs_root is not None and grid.crs_root is not None
assert len(trajectory.control_points)
self.trajectory = trajectory
if not self.well_name:
self.well_name = trajectory.title
bw = rgs.populate_blocked_well_from_trajectory(self,
grid,
active_only = active_only,
quad_triangles = quad_triangles,
lazy = False,
use_single_layer_tactics = use_single_layer_tactics)
if bw is None:
raise Exception('failed to generate blocked well from trajectory with uuid: ' + str(trajectory.uuid))
assert bw is self
def set_for_column(self, well_name, grid, col_ji0, skip_inactive = True):
"""Populates empty blocked well for a 'vertical' well in given column; creates simulation trajectory and md
datum."""
if well_name:
self.well_name = well_name
col_list = ['IW', 'JW', 'L', 'ANGLA', 'ANGLV'] # NB: L is Layer, ie. k
df = pd.DataFrame(columns = col_list)
pinch_col = grid.pinched_out(cache_cp_array = True, cache_pinchout_array = True)[:, col_ji0[0], col_ji0[1]]
if skip_inactive and grid.inactive is not None:
inactive_col = grid.inactive[:, col_ji0[0], col_ji0[1]]
else:
inactive_col = np.zeros(grid.nk, dtype = bool)
for k0 in range(grid.nk):
if pinch_col[k0] or inactive_col[k0]:
continue
# note: leaving ANGLA & ANGLV columns as NA will cause K face centres to be used when deriving from dataframe
row_dict = {'IW': col_ji0[1] + 1, 'JW': col_ji0[0] + 1, 'L': k0 + 1}
df = df.append(row_dict, ignore_index = True)
return self.derive_from_dataframe(df, self.well_name, grid, use_face_centres = True)
def derive_from_wellspec(self,
wellspec_file,
well_name,
grid,
check_grid_name = False,
use_face_centres = False,
add_properties = True):
"""Populates empty blocked well from Nexus WELLSPEC data; creates simulation trajectory and md datum.
args:
wellspec_file (string): path of Nexus ascii file holding WELLSPEC keyword
well_name (string): the name of the well as used in the wellspec data
grid (grid.Grid object): the grid object which the cell indices in the wellspec data relate to
check_grid_name (boolean, default False): if True, the GRID column of the wellspec data will be checked
for a match with the citation title of the grid object; perforations for other grids will be skipped;
if False, all wellspec data is assumed to relate to the grid
use_face_centres (boolean, default False): if True, cell face centre points are used for the entry and
exit points when constructing the simulation trajectory; if False and ANGLA & ANGLV data are available
then entry and exit points are constructed based on a straight line at those angles passing through
the centre of the cell
add_properties (bool or list of str, default True): if True, WELLSPEC columns (other than IW, JW, L & GRID)
are added as property parts for the blocked well; if a list is passed, it must contain a subset of the
columns in the WELLSPEC data
returns:
self if successful; None otherwise
note:
if add_properties is True or present as a list, this method will write the hdf5, create the xml and add
parts to the model for this blocked well and the properties
"""
if well_name:
self.well_name = well_name
else:
well_name = self.well_name
if add_properties:
if isinstance(add_properties, list):
col_list = ['IW', 'JW', 'L'] + [col.upper() for col in add_properties if col not in ['IW', 'JW', 'L']]
else:
col_list = []
else:
col_list = ['IW', 'JW', 'L', 'ANGLA', 'ANGLV']
if check_grid_name:
grid_name = rqet.citation_title_for_node(grid.root).upper()
if not grid_name:
check_grid_name = False
else:
col_list.append('GRID')
wellspec_dict = wsk.load_wellspecs(wellspec_file, well = well_name, column_list = col_list)
assert len(wellspec_dict) == 1, 'no wellspec data found in file ' + wellspec_file + ' for well ' + well_name
df = wellspec_dict[well_name]
assert len(df) > 0, 'no rows of perforation data found in wellspec for well ' + well_name
name_for_check = grid_name if check_grid_name else None
return self.derive_from_dataframe(df,
well_name,
grid,
grid_name_to_check = name_for_check,
use_face_centres = use_face_centres,
add_as_properties = add_properties)
def derive_from_cell_list(self, cell_kji0_list, well_name, grid):
"""Populate empty blocked well from numpy int array of shape (N, 3) being list of cells."""
df = pd.DataFrame(columns = ['IW', 'JW', 'L'])
df['IW'] = cell_kji0_list[:, 2] + 1
df['JW'] = cell_kji0_list[:, 1] + 1
df['L'] = cell_kji0_list[:, 0] + 1
return self.derive_from_dataframe(df, well_name, grid, use_face_centres = True)
def derive_from_dataframe(self,
df,
well_name,
grid,
grid_name_to_check = None,
use_face_centres = True,
add_as_properties = False):
"""Populate empty blocked well from WELLSPEC-like dataframe; first columns must be IW, JW, L (i, j, k).
note:
if add_as_properties is True or present as a list of wellspec column names, both the blocked well and
the properties will have their hdf5 data written, xml created and be added as parts to the model
"""
def cell_kji0_from_df(df, df_row):
row = df.iloc[df_row]
if pd.isna(row[0]) or pd.isna(row[1]) or pd.isna(row[2]):
return None
cell_kji0 = np.empty((3,), dtype = int)
cell_kji0[:] = row[2], row[1], row[0]
cell_kji0[:] -= 1
return cell_kji0
if well_name:
self.well_name = well_name
else:
well_name = self.well_name
assert len(df) > 0, 'empty dataframe for blocked well ' + str(well_name)
length_uom = grid.z_units()
assert grid.xy_units() == length_uom, 'mixed length units in grid crs'
previous_xyz = None
trajectory_mds = []
trajectory_points = [] # entries paired with trajectory_mds
blocked_intervals = [
] # will have one fewer entries than trajectory nodes; 0 = blocked, -1 = not blocked (for grid indices)
blocked_cells_kji0 = [] # will have length equal to number of 0's in blocked intervals
blocked_face_pairs = [
] # same length as blocked_cells_kji0; each is ((entry axis, entry polarity), (exit axis, exit polarity))
log.debug('wellspec dataframe for well ' + str(well_name) + ' has ' + str(len(df)) + ' row' + _pl(len(df)))
skipped_warning_grid = None
angles_present = ('ANGLV' in df.columns and 'ANGLA' in df.columns and not pd.isnull(df.iloc[0]['ANGLV']) and
not pd.isnull(df.iloc[0]['ANGLA']))
# TODO: remove these temporary overrides
angles_present = False
use_face_centres = True
if not angles_present and not use_face_centres:
log.warning(f'ANGLV and/or ANGLA data unavailable for well {well_name}: using face centres')
use_face_centres = True
for i in range(len(df)): # for each row in the dataframe for this well
cell_kji0 = cell_kji0_from_df(df, i)
if cell_kji0 is None:
log.error('missing cell index in wellspec data for well ' + str(well_name) + ' row ' + str(i + 1))
continue
row = df.iloc[i]
if grid_name_to_check and pd.notna(row['GRID']) and grid_name_to_check != str(row['GRID']).upper():
other_grid = str(row['GRID'])
if skipped_warning_grid != other_grid:
log.warning('skipping perforation(s) in grid ' + other_grid + ' for well ' + str(well_name))
skipped_warning_grid = other_grid
continue
cp = grid.corner_points(cell_kji0 = cell_kji0, cache_resqml_array = False)
assert not np.any(np.isnan(cp)), 'missing geometry for perforation cell for well ' + str(well_name)
if angles_present:
log.debug('row ' + str(i) + ': using angles')
angla = row['ANGLA']
inclination = row['ANGLV']
if inclination < 0.1:
azimuth = 0.0
else:
i_vector = np.sum(cp[:, :, 1] - cp[:, :, 0], axis = (0, 1))
azimuth = vec.azimuth(i_vector) - angla # see Nexus keyword reference doc
well_vector = vec.unit_vector_from_azimuth_and_inclination(azimuth, inclination) * 10000.0
# todo: the following might be producing NaN's when vector passes precisely through an edge
(entry_axis, entry_polarity, entry_xyz, exit_axis, exit_polarity,
exit_xyz) = find_entry_and_exit(cp, -well_vector, well_vector, well_name)
else:
# fabricate entry and exit axes and polarities based on indices alone
# note: could use geometry but here a cheap rough-and-ready approach is used
log.debug('row ' + str(i) + ': using cell moves')
if i == 0:
entry_axis, entry_polarity = 0, 0 # K-
else:
entry_move = cell_kji0 - blocked_cells_kji0[-1]
log.debug(f'entry move: {entry_move}')
if entry_move[1] == 0 and entry_move[2] == 0: # K move
entry_axis = 0
entry_polarity = 0 if entry_move[0] >= 0 else 1
elif abs(entry_move[1]) > abs(entry_move[2]): # J dominant move
entry_axis = 1
entry_polarity = 0 if entry_move[1] >= 0 else 1
else: # I dominant move
entry_axis = 2
entry_polarity = 0 if entry_move[2] >= 0 else 1
if i == len(df) - 1:
exit_axis, exit_polarity = entry_axis, 1 - entry_polarity
else:
next_cell_kji0 = cell_kji0_from_df(df, i + 1)
if next_cell_kji0 is None:
exit_axis, exit_polarity = entry_axis, 1 - entry_polarity
else:
exit_move = next_cell_kji0 - cell_kji0
log.debug(f'exit move: {exit_move}')
if exit_move[1] == 0 and exit_move[2] == 0: # K move
exit_axis = 0
exit_polarity = 1 if exit_move[0] >= 0 else 0
elif abs(exit_move[1]) > abs(exit_move[2]): # J dominant move
exit_axis = 1
exit_polarity = 1 if exit_move[1] >= 0 else 0
else: # I dominant move
exit_axis = 2
exit_polarity = 1 if exit_move[2] >= 0 else 0
if use_face_centres: # override the vector based xyz entry and exit points with face centres
if entry_axis == 0:
entry_xyz = np.mean(cp[entry_polarity, :, :], axis = (0, 1))
elif entry_axis == 1:
entry_xyz = np.mean(cp[:, entry_polarity, :], axis = (0, 1))
else:
entry_xyz = np.mean(cp[:, :, entry_polarity], axis = (0, 1)) # entry_axis == 2, ie. I
if exit_axis == 0:
exit_xyz = np.mean(cp[exit_polarity, :, :], axis = (0, 1))
elif exit_axis == 1:
exit_xyz = np.mean(cp[:, exit_polarity, :], axis = (0, 1))
else:
exit_xyz = np.mean(cp[:, :, exit_polarity], axis = (0, 1)) # exit_axis == 2, ie. I
log.debug(
f'cell: {cell_kji0}; entry axis: {entry_axis}; polarity {entry_polarity}; exit axis: {exit_axis}; polarity {exit_polarity}'
)
if previous_xyz is None: # first entry
log.debug('adding mean sea level trajectory start')
previous_xyz = entry_xyz.copy()
previous_xyz[2] = 0.0 # use depth zero as md datum
trajectory_mds.append(0.0)
trajectory_points.append(previous_xyz)
if not vec.isclose(previous_xyz, entry_xyz, tolerance = 0.05): # add an unblocked interval
log.debug('adding unblocked interval')
trajectory_points.append(entry_xyz)
new_md = trajectory_mds[-1] + vec.naive_length(
entry_xyz - previous_xyz) # assumes x, y & z units are same
trajectory_mds.append(new_md)
blocked_intervals.append(-1) # unblocked interval
previous_xyz = entry_xyz
log.debug('adding blocked interval for cell kji0: ' + str(cell_kji0))
trajectory_points.append(exit_xyz)
new_md = trajectory_mds[-1] + vec.naive_length(exit_xyz - previous_xyz) # assumes x, y & z units are same
trajectory_mds.append(new_md)
blocked_intervals.append(0) # blocked interval
previous_xyz = exit_xyz
blocked_cells_kji0.append(cell_kji0)
blocked_face_pairs.append(((entry_axis, entry_polarity), (exit_axis, exit_polarity)))
blocked_count = len(blocked_cells_kji0)
if blocked_count == 0:
log.warning('no intervals blocked for well ' + str(well_name))
return None
else:
log.info(str(blocked_count) + ' interval' + _pl(blocked_count) + ' blocked for well ' + str(well_name))
self.node_count = len(trajectory_mds)
self.node_mds = np.array(trajectory_mds)
self.cell_count = len(blocked_cells_kji0)
self.grid_indices = np.array(blocked_intervals, dtype = int) # NB. only supporting one grid at the moment
self.cell_indices = grid.natural_cell_indices(np.array(blocked_cells_kji0))
self.face_pair_indices = np.array(blocked_face_pairs, dtype = int)
self.grid_list = [grid]
# if last segment terminates at bottom face in bottom layer, add a tail to trajectory
if blocked_count > 0 and exit_axis == 0 and exit_polarity == 1 and cell_kji0[
0] == grid.nk - 1 and grid.k_direction_is_down:
tail_length = 10.0 # metres or feet
tail_xyz = trajectory_points[-1].copy()
tail_xyz[2] += tail_length * (1.0 if grid.z_inc_down() else -1.0)
trajectory_points.append(tail_xyz)
new_md = trajectory_mds[-1] + tail_length
trajectory_mds.append(new_md)
self.create_md_datum_and_trajectory(grid, trajectory_mds, trajectory_points, length_uom, well_name)
if add_as_properties and len(df.columns) > 3:
# NB: atypical writing of hdf5 data and xml creation in order to support related properties
self.write_hdf5()
self.create_xml()
if isinstance(add_as_properties, list):
for col in add_as_properties:
assert col in df.columns[3:] # could just skip missing columns
property_columns = add_as_properties
else:
property_columns = df.columns[3:]
self._add_df_properties(df, property_columns, length_uom = length_uom)
return self
def import_from_rms_cellio(self, cellio_file, well_name, grid, include_overburden_unblocked_interval = False):
"""Populates empty blocked well from RMS cell I/O data; creates simulation trajectory and md datum.
args:
cellio_file (string): path of RMS ascii export file holding blocked well cell I/O data; cell entry and
exit points are expected
well_name (string): the name of the well as used in the cell I/O file
grid (grid.Grid object): the grid object which the cell indices in the cell I/O data relate to
returns:
self if successful; None otherwise
"""
if well_name:
self.well_name = well_name
else:
well_name = self.well_name
grid_name = rqet.citation_title_for_node(grid.root)
length_uom = grid.z_units()
grid_z_inc_down = crs.Crs(grid.model, uuid = grid.crs_uuid).z_inc_down
log.debug('grid z increasing downwards: ' + str(grid_z_inc_down) + '(type: ' + str(type(grid_z_inc_down)) + ')')
cellio_z_inc_down = None
try:
assert ' ' not in well_name, 'cannot import for well name containing spaces'
with open(cellio_file, 'r') as fp:
while True:
kf.skip_blank_lines_and_comments(fp)
line = fp.readline() # file format version number?
assert line, 'well ' + str(well_name) + ' not found in file ' + str(cellio_file)
fp.readline() # 'Undefined'
words = fp.readline().split()
assert len(words), 'missing header info in cell I/O file'
if words[0].upper() == well_name.upper():
break
while not kf.blank_line(fp):
fp.readline() # skip to block of data for next well
header_lines = int(fp.readline().strip())
for _ in range(header_lines):
fp.readline()
previous_xyz = None
trajectory_mds = []
trajectory_points = [] # entries paired with trajectory_mds
blocked_intervals = [
] # will have one fewer entries than trajectory nodes; 0 = blocked, -1 = not blocked (for grid indices)
blocked_cells_kji0 = [] # will have length equal to number of 0's in blocked intervals
blocked_face_pairs = [
] # same length as blocked_cells_kji0; each is ((entry axis, entry polarity), (exit axis, exit polarity))
while not kf.blank_line(fp):
line = fp.readline()
words = line.split()
assert len(words) >= 9, 'not enough items on data line in cell I/O file, minimum 9 expected'
i1, j1, k1 = int(words[0]), int(words[1]), int(words[2])
cell_kji0 = np.array((k1 - 1, j1 - 1, i1 - 1), dtype = int)
assert np.all(0 <= cell_kji0) and np.all(
cell_kji0 < grid.extent_kji), 'cell I/O cell index not within grid extent'
entry_xyz = np.array((float(words[3]), float(words[4]), float(words[5])))
exit_xyz = np.array((float(words[6]), float(words[7]), float(words[8])))
if cellio_z_inc_down is None:
cellio_z_inc_down = bool(entry_xyz[2] + exit_xyz[2] > 0.0)
if cellio_z_inc_down != grid_z_inc_down:
entry_xyz[2] = -entry_xyz[2]
exit_xyz[2] = -exit_xyz[2]
cp = grid.corner_points(cell_kji0 = cell_kji0, cache_resqml_array = False)
assert not np.any(np.isnan(cp)), 'missing geometry for perforation cell(kji0) ' + str(
cell_kji0) + ' for well ' + str(well_name)
cell_centre = np.mean(cp, axis = (0, 1, 2))
# let's hope everything is in the same coordinate reference system!
entry_vector = 100.0 * (entry_xyz - cell_centre)
exit_vector = 100.0 * (exit_xyz - cell_centre)
(entry_axis, entry_polarity, facial_entry_xyz, exit_axis, exit_polarity,
facial_exit_xyz) = find_entry_and_exit(cp, entry_vector, exit_vector, well_name)
if previous_xyz is None: # first entry
previous_xyz = entry_xyz.copy()
if include_overburden_unblocked_interval:
log.debug('adding mean sea level trajectory start')
previous_xyz[2] = 0.0 # use depth zero as md datum
trajectory_mds.append(previous_xyz[2])
trajectory_points.append(previous_xyz)
if not vec.isclose(previous_xyz, entry_xyz, tolerance = 0.05): # add an unblocked interval
log.debug('adding unblocked interval')
trajectory_points.append(entry_xyz)
new_md = trajectory_mds[-1] + vec.naive_length(
entry_xyz - previous_xyz) # assumes x, y & z units are same
trajectory_mds.append(new_md)
blocked_intervals.append(-1) # unblocked interval
previous_xyz = entry_xyz
log.debug('adding blocked interval for cell kji0: ' + str(cell_kji0))
trajectory_points.append(exit_xyz)
new_md = trajectory_mds[-1] + vec.naive_length(
exit_xyz - previous_xyz) # assumes x, y & z units are same
trajectory_mds.append(new_md)
blocked_intervals.append(0) # blocked interval
previous_xyz = exit_xyz
blocked_cells_kji0.append(cell_kji0)
blocked_face_pairs.append(((entry_axis, entry_polarity), (exit_axis, exit_polarity)))
blocked_count = len(blocked_cells_kji0)
if blocked_count == 0:
log.warning('no intervals blocked for well ' + well_name + ' in grid ' + str(grid_name))
return None
else:
log.info(
str(blocked_count) + ' interval' + _pl(blocked_count) + ' blocked for well ' + well_name +
' in grid ' + str(grid_name))
self.create_md_datum_and_trajectory(grid,
trajectory_mds,
trajectory_points,
length_uom,
well_name,
set_depth_zero = True,
set_tangent_vectors = True)
self.node_count = len(trajectory_mds)
self.node_mds = np.array(trajectory_mds)
self.cell_count = len(blocked_cells_kji0)
self.grid_indices = np.array(blocked_intervals,
dtype = int) # NB. only supporting one grid at the moment
self.cell_indices = grid.natural_cell_indices(np.array(blocked_cells_kji0))
self.face_pair_indices = np.array(blocked_face_pairs)
self.grid_list = [grid]
except Exception:
log.exception('failed to import info for blocked well ' + str(well_name) + ' from cell I/O file ' +
str(cellio_file))
return None
return self
def dataframe(self,
i_col = 'IW',
j_col = 'JW',
k_col = 'L',
one_based = True,
extra_columns_list = [],
ntg_uuid = None,
perm_i_uuid = None,
perm_j_uuid = None,
perm_k_uuid = None,
satw_uuid = None,
sato_uuid = None,
satg_uuid = None,
region_uuid = None,
radw = None,
skin = None,
stat = None,
active_only = False,
min_k0 = None,
max_k0 = None,
k0_list = None,
min_length = None,
min_kh = None,
max_depth = None,
max_satw = None,
min_sato = None,
max_satg = None,
perforation_list = None,
region_list = None,
depth_inc_down = None,
set_k_face_intervals_vertical = False,
anglv_ref = 'normal ij down',
angla_plane_ref = None,
length_mode = 'MD',
length_uom = None,
use_face_centres = False,
preferential_perforation = True,
add_as_properties = False,
use_properties = False):
"""Returns a pandas data frame containing WELLSPEC style data.
arguments:
i_col (string, default 'IW'): the column name to use for cell I index values
j_col (string, default 'JW'): the column name to use for cell J index values
k_col (string, default 'L'): the column name to use for cell K index values
one_based (boolean, default True): if True, simulator protocol i, j & k values are placed in I, J & K columns;
if False, resqml zero based values; this does not affect the interpretation of min_k0 & max_k0 arguments
extra_columns_list (list of string, optional): list of WELLSPEC column names to include in the dataframe, from currently
recognised values: 'GRID', 'ANGLA', 'ANGLV', 'LENGTH', 'KH', 'DEPTH', 'MD', 'X', 'Y', 'RADW', 'SKIN', 'PPERF', 'RADB', 'WI', 'WBC'
ntg_uuid (uuid.UUID, optional): the uuid of the net to gross ratio property; if present is used to downgrade the i & j
permeabilities in the calculation of KH; ignored if 'KH' not in the extra column list and min_kh is not specified;
the argument may also be a dictionary mapping from grid uuid to ntg uuid; if no net to gross data is provided, it
is effectively assumed to be one (or, equivalently, the I & J permeability data is applicable to the gross rock); see
also preferential_perforation argument which can cause adjustment of effective ntg in partially perforated cells
perm_i_uuid (uuid.UUID or dictionary, optional): the uuid of the permeability property in the I direction;
required if 'KH' is included in the extra columns list and min_kh is not specified; ignored otherwise;
the argument may also be a dictionary mapping from grid uuid to perm I uuid
perm_j_uuid (uuid.UUID, optional): the uuid (or dict) of the permeability property in the J direction;
defaults to perm_i_uuid
perm_k_uuid (uuid.UUID, optional): the uuid (or dict) of the permeability property in the K direction;
defaults to perm_i_uuid
satw_uuid (uuid.UUID, optional): the uuid of a water saturation property; required if max_satw is specified; may also
be a dictionary mapping from grid uuid to satw uuid; ignored if max_satw is None
sato_uuid (uuid.UUID, optional): the uuid of an oil saturation property; required if min_sato is specified; may also
be a dictionary mapping from grid uuid to sato uuid; ignored if min_sato is None
satg_uuid (uuid.UUID, optional): the uuid of a gas saturation property; required if max_satg is specified; may also
be a dictionary mapping from grid uuid to satg uuid; ignored if max_satg is None
region_uuid (uuid.UUID, optional): the uuid of a discrete or categorical property, required if region_list is not None;
may also be a dictionary mapping from grid uuid to region uuid; ignored if region_list is None
radw (float, optional): if present, the wellbore radius used for all perforations; must be in correct units for intended
use of the WELLSPEC style dataframe; will default to 0.25 if 'RADW' is included in the extra column list
skin (float, optional): if present, a skin column is included with values set to this constant
stat (string, optional): if present, should be 'ON' or 'OFF' and is used for all perforations; will default to 'ON' if
'STAT' is included in the extra column list
active_only (boolean, default False): if True, only cells that are flagged in the grid object as active are included;
if False, cells are included whether active or not
min_k0 (int, optional): if present, perforations in layers above this are excluded (layer number will be applied
naively to all grids – not recommended when working with more than one grid with different layering)
max_k0 (int, optional): if present, perforations in layers below this are excluded (layer number will be applied
naively to all grids – not recommended when working with more than one grid with different layering)
k0_list (list of int, optional): if present, only perforations in cells in these layers are included (layer numbers
will be applied naively to all grids – not recommended when working with more than one grid with different layering)
min_length (float, optional): if present, a minimum length for an individual perforation interval to be included;
units are the length units of the trajectory object unless length_uom argument is set
min_kh (float, optional): if present, the minimum permeability x length value for which an individual interval is
included; permeabilty uuid(s) must be supplied for the kh calculation; units of the length component are those
of the trajectory object unless length_uom argument is set
max_depth (float, optional): if present, rows are excluded for cells with a centre point depth greater than this value;
max_depth should be positive downwards, with units of measure those of the grid z coordinates
max_satw (float, optional): if present, perforations in cells where the water saturation exceeds this value will
be excluded; satw_uuid must be supplied if this argument is present
min_sato (float, optional): if present, perforations in cells where the oil saturation is less than this value will
be excluded; sato_uuid must be supplied if this argument is present
max_satg (float, optional): if present, perforations in cells where the gas saturation exceeds this value will
be excluded; satg_uuid must be supplied if this argument is present
perforation_list (list of (float, float), optional): if present, a list of perforated intervals; each entry is the
start and end measured depths for a perforation; these do not need to align with cell boundaries
region_list (list of int, optional): if present, a list of region numbers for which rows are to be included; the
property holding the region data is identified by the region_uuid argument
depth_inc_down (boolean, optional): if present and True, the depth values will increase with depth; if False or None,
the direction of the depth values will be determined by the z increasing downwards indicator in the trajectory crs
set_k_face_intervals_vertical (boolean, default False): if True, intervals with entry through K- and exit through K+
will have angla and anglv set to 0.0 (vertical); if False angles will be computed depending on geometry
anglv_ref (string, default 'normal ij down'): either 'gravity', 'z down' (same as gravity), 'z+', 'k down', 'k+',
'normal ij', or 'normal ij down';
the ANGLV angles are relative to a local (per cell) reference vector selected by this keyword
angla_plane_ref (string, optional): string indicating normal vector defining plane onto which trajectory and I axis are
projected for the calculation of ANGLA; options as for anglv_ref, or 'normal well i+' which results in no projection;
defaults to the same as anglv_ref
length_mode (string, default 'MD'): 'MD' or 'straight' indicating which length to use; 'md' takes measured depth
difference between exit and entry; 'straight' uses a naive straight line length between entry and exit;
this will affect values for LENGTH, KH, DEPTH, X & Y
length_uom (string, optional): if present, either 'm' or 'ft': the length units to use for the LENGTH, KH, MD, DEPTH,
X & Y columns if they are present in extra_columns_list; also used to interpret min_length and min_kh; if None, the
length units of the trajectory attribute are used LENGTH, KH & MD and those of the grid are used for DEPTH, X & Y;
RADW value, if present, is assumed to be in the correct units and is not changed; also used implicitly to determine
conversion constant used in calculation of wellbore constant (WBC)
use_face_centres (boolean, default False): if True, the centre points of the entry and exit faces will determine the
vector used as the basis of ANGLA and ANGLV calculations; if False, the trajectory locations for the entry and exit
measured depths will be used
preferential_perforation (boolean, default True): if perforation_list is given, and KH is requested or a min_kh given,
the perforated intervals are assumed to penetrate pay rock preferentially: an effective ntg weighting is computed
to account for any residual non-pay perforated interval; ignored if perforation_list is None or kh values are not
being computed
add_as_properties (boolean or list of str, default False): if True, each column in the extra_columns_list (excluding
GRID and STAT) is added as a property with the blocked well as supporting representation and 'cells' as the
indexable element; any cell that is excluded from the dataframe will have corresponding entries of NaN in all the
properties; if a list is provided it must be a subset of extra_columns_list
use_properties (boolean or list of str, default False): if True, each column in the extra_columns_list (excluding
GRID and STAT) is populated from a property with citation title matching the column name, if it exists
notes:
units of length along wellbore will be those of the trajectory's length_uom (also applies to K.H values) unless
the length_uom argument is used;
the constraints are applied independently for each row and a row is excluded if it fails any constraint;
the min_k0 and max_k0 arguments do not stop later rows within the layer range from being included;
the min_length and min_kh limits apply to individual cell intervals and thus depend on cell size;
the water and oil saturation limits are for saturations at a single time and affect whether the interval
is included in the dataframe – there is no functionality to support turning perforations off and on over time;
the saturation limits do not stop deeper intervals with qualifying saturations from being included;
the k0_list, perforation_list and region_list arguments should be set to None to disable the corresponding functionality,
if set to an empty list, no rows will be included in the dataframe;
if add_as_properties is True, the blocked well must already have been added as a part to the model;
at add_as_properties and use_properties cannot both be True;
add_as_properties and use_properties are only currently functional for single grid blocked wells;
at present, unit conversion is not handled when using properties
:meta common:
"""
def prop_array(uuid_or_dict, grid):
assert uuid_or_dict is not None and grid is not None
if isinstance(uuid_or_dict, dict):
prop_uuid = uuid_or_dict[grid.uuid]
else:
prop_uuid = uuid_or_dict # uuid either in form of string or uuid.UUID
return grid.property_collection.single_array_ref(uuid = prop_uuid)
def get_ref_vector(grid, grid_crs, cell_kji0, mode):
# gravity = np.array((0.0, 0.0, 1.0))
if mode == 'normal well i+':
return None # ANGLA only: option for no projection onto a plane
ref_vector = None
# options for anglv or angla reference: 'z down', 'z+', 'k down', 'k+', 'normal ij', 'normal ij down'
cell_axial_vectors = None
if not mode.startswith('z'):
cell_axial_vectors = grid.interface_vectors_kji(cell_kji0)
if mode == 'z+':
ref_vector = np.array((0.0, 0.0, 1.0))
elif mode == 'z down':
if grid_crs.z_inc_down:
ref_vector = np.array((0.0, 0.0, 1.0))
else:
ref_vector = np.array((0.0, 0.0, -1.0))
elif mode in ['k+', 'k down']:
ref_vector = vec.unit_vector(cell_axial_vectors[0])
if mode == 'k down' and not grid.k_direction_is_down:
ref_vector = -ref_vector
else: # normal to plane of ij axes
ref_vector = vec.unit_vector(vec.cross_product(cell_axial_vectors[1], cell_axial_vectors[2]))
if mode == 'normal ij down':
if grid_crs.z_inc_down:
if ref_vector[2] < 0.0:
ref_vector = -ref_vector
else:
if ref_vector[2] > 0.0:
ref_vector = -ref_vector
if ref_vector is None or ref_vector[2] == 0.0:
if grid_crs.z_inc_down:
ref_vector = np.array((0.0, 0.0, 1.0))
else:
ref_vector = np.array((0.0, 0.0, -1.0))
return ref_vector
assert length_mode in ['MD', 'straight']
assert length_uom is None or length_uom in ['m', 'ft']
assert anglv_ref in ['gravity', 'z down', 'z+', 'k down', 'k+', 'normal ij', 'normal ij down']
if anglv_ref == 'gravity':
anglv_ref = 'z down'
if angla_plane_ref is None:
angla_plane_ref = anglv_ref
assert angla_plane_ref in [
'gravity', 'z down', 'z+', 'k down', 'k+', 'normal ij', 'normal ij down', 'normal well i+'
]
if angla_plane_ref == 'gravity':
angla_plane_ref = 'z down'
column_list = [i_col, j_col, k_col]
if extra_columns_list:
for extra in extra_columns_list:
assert extra.upper() in [
'GRID', 'ANGLA', 'ANGLV', 'LENGTH', 'KH', 'DEPTH', 'MD', 'X', 'Y', 'SKIN', 'RADW', 'PPERF', 'RADB',
'WI', 'WBC'
]
column_list.append(extra.upper())
else:
add_as_properties = use_properties = False
assert not (add_as_properties and use_properties)
pc = rqp.PropertyCollection(support = self) if use_properties else None
pc_titles = [] if pc is None else pc.titles()
isotropic_perm = None
if min_length is not None and min_length <= 0.0:
min_length = None
if min_kh is not None and min_kh <= 0.0:
min_kh = None
if max_satw is not None and max_satw >= 1.0:
max_satw = None
if min_sato is not None and min_sato <= 0.0:
min_sato = None
if max_satg is not None and max_satg >= 1.0:
max_satg = None
doing_kh = False
if ('KH' in column_list or min_kh is not None) and 'KH' not in pc_titles:
assert perm_i_uuid is not None, 'KH requested (or minimum specified) without I direction permeabilty being specified'
doing_kh = True
if 'WBC' in column_list and 'WBC' not in pc_titles:
assert perm_i_uuid is not None, 'WBC requested without I direction permeabilty being specified'
doing_kh = True
do_well_inflow = (('WI' in column_list and 'WI' not in pc_titles) or
('WBC' in column_list and 'WBC' not in pc_titles) or
('RADB' in column_list and 'RADB' not in pc_titles))
if do_well_inflow:
assert perm_i_uuid is not None, 'WI, RADB or WBC requested without I direction permeabilty being specified'
if doing_kh or do_well_inflow:
if perm_j_uuid is None and perm_k_uuid is None:
isotropic_perm = True
else:
if perm_j_uuid is None:
perm_j_uuid = perm_i_uuid
if perm_k_uuid is None:
perm_k_uuid = perm_i_uuid
# following line assumes arguments are passed in same form; if not, some unnecessary maths might be done
isotropic_perm = (bu.matching_uuids(perm_i_uuid, perm_j_uuid) and
bu.matching_uuids(perm_i_uuid, perm_k_uuid))
if max_satw is not None:
assert satw_uuid is not None, 'water saturation limit specified without saturation property array'
if min_sato is not None:
assert sato_uuid is not None, 'oil saturation limit specified without saturation property array'
if max_satg is not None:
assert satg_uuid is not None, 'gas saturation limit specified without saturation property array'
if region_list is not None:
assert region_uuid is not None, 'region list specified without region property array'
if radw is not None and 'RADW' not in column_list:
column_list.append('RADW')
if radw is None:
radw = 0.25
if skin is not None and 'SKIN' not in column_list:
column_list.append('SKIN')
if skin is None:
skin = 0.0
if stat is not None:
assert str(stat).upper() in ['ON', 'OFF']
stat = str(stat).upper()
if 'STAT' not in column_list:
column_list.append('STAT')
else:
stat = 'ON'
if 'GRID' not in column_list and self.number_of_grids() > 1:
log.error('creating blocked well dataframe without GRID column for well that intersects more than one grid')
if 'LENGTH' in column_list and 'PPERF' in column_list and 'KH' not in column_list and perforation_list is not None:
log.warning(
'both LENGTH and PPERF will include effects of partial perforation; only one should be used in WELLSPEC'
)
elif (perforation_list is not None and 'LENGTH' not in column_list and 'PPERF' not in column_list and
'KH' not in column_list and 'WBC' not in column_list):
log.warning('perforation list supplied but no use of LENGTH, KH, PPERF nor WBC')
if min_k0 is None:
min_k0 = 0
else:
assert min_k0 >= 0
if max_k0 is not None:
assert min_k0 <= max_k0
if k0_list is not None and len(k0_list) == 0:
log.warning('no layers included for blocked well dataframe: no rows will be included')
if perforation_list is not None and len(perforation_list) == 0:
log.warning('empty perforation list specified for blocked well dataframe: no rows will be included')
doing_angles = (('ANGLA' in column_list and 'ANGLA' not in pc_titles) or
('ANGLV' in column_list and 'ANGLV' not in pc_titles) or doing_kh or do_well_inflow)
doing_xyz = (('X' in column_list and 'X' not in pc_titles) or ('Y' in column_list and 'Y' not in pc_titles) or
('DEPTH' in column_list and 'DEPTH' not in pc_titles))
doing_entry_exit = doing_angles or ('LENGTH' in column_list and 'LENGTH' not in pc_titles and
length_mode == 'straight')
grid_crs_list = []
for grid in self.grid_list:
grid_crs = crs.Crs(self.model, uuid = grid.crs_uuid)
grid_crs_list.append(grid_crs)
if grid_crs.z_units != grid_crs.xy_units and (len(column_list) > 1 or
(len(column_list) == 1 and
column_list[0] != 'GRID')) is not None:
log.error('grid ' + str(rqet.citation_title_for_node(grid.root_node)) +
' has z units different to xy units: some WELLSPEC data likely to be wrong')
k_face_check = np.zeros((2, 2), dtype = int)
k_face_check[1, 1] = 1 # now represents entry, exit of K-, K+
k_face_check_end = k_face_check.copy()
k_face_check_end[1] = -1 # entry through K-, terminating (TD) within cell
if self.trajectory is None or self.trajectory.crs_root is None:
traj_crs = None
traj_z_inc_down = None
else:
traj_crs = crs.Crs(self.trajectory.model, uuid = self.trajectory.crs_uuid)
assert traj_crs.xy_units == traj_crs.z_units
traj_z_inc_down = traj_crs.z_inc_down
df = pd.DataFrame(columns = column_list)
df = df.astype({i_col: int, j_col: int, k_col: int})
ci = -1
row_ci_list = []
if self.node_count is None or self.node_count < 2:
interval_count = 0
else:
interval_count = self.node_count - 1
for interval in range(interval_count):
if self.grid_indices[interval] < 0:
continue # unblocked interval
ci += 1
row_dict = {}
grid = self.grid_list[self.grid_indices[interval]]
grid_crs = grid_crs_list[self.grid_indices[interval]]
grid_name = rqet.citation_title_for_node(grid.root).replace(' ', '_')
natural_cell = self.cell_indices[ci]
cell_kji0 = grid.denaturalized_cell_index(natural_cell)
tuple_kji0 = tuple(cell_kji0)
if max_depth is not None:
cell_depth = grid.centre_point(cell_kji0)[2]
if not grid_crs.z_inc_down:
cell_depth = -cell_depth
if cell_depth > max_depth:
continue
if active_only and grid.inactive is not None and grid.inactive[tuple_kji0]:
continue
if (min_k0 is not None and cell_kji0[0] < min_k0) or (max_k0 is not None and cell_kji0[0] > max_k0):
continue
if k0_list is not None and cell_kji0[0] not in k0_list:
continue
if region_list is not None and prop_array(region_uuid, grid)[tuple_kji0] not in region_list:
continue
if max_satw is not None and prop_array(satw_uuid, grid)[tuple_kji0] > max_satw:
continue
if min_sato is not None and prop_array(sato_uuid, grid)[tuple_kji0] < min_sato:
continue
if max_satg is not None and prop_array(satg_uuid, grid)[tuple_kji0] > max_satg:
continue
if 'PPERF' in pc_titles:
part_perf_fraction = pc.single_array_ref(citation_title = 'PPERF')[ci]
else:
part_perf_fraction = 1.0
if perforation_list is not None:
perf_length = 0.0
for perf_start, perf_end in perforation_list:
if perf_end <= self.node_mds[interval] or perf_start >= self.node_mds[interval + 1]:
continue
if perf_start <= self.node_mds[interval]:
if perf_end >= self.node_mds[interval + 1]:
perf_length += self.node_mds[interval + 1] - self.node_mds[interval]
break
else:
perf_length += perf_end - self.node_mds[interval]
else:
if perf_end >= self.node_mds[interval + 1]:
perf_length += self.node_mds[interval + 1] - perf_start
else:
perf_length += perf_end - perf_start
if perf_length == 0.0:
continue
part_perf_fraction = min(1.0, perf_length / (self.node_mds[interval + 1] - self.node_mds[interval]))
# log.debug('kji0: ' + str(cell_kji0))
entry_xyz = None
exit_xyz = None
if doing_entry_exit:
assert self.trajectory is not None
if use_face_centres:
entry_xyz = grid.face_centre(cell_kji0, self.face_pair_indices[interval, 0, 0],
self.face_pair_indices[interval, 0, 1])
if self.face_pair_indices[interval, 1, 0] >= 0:
exit_xyz = grid.face_centre(cell_kji0, self.face_pair_indices[interval, 1, 0],
self.face_pair_indices[interval, 1, 1])
else:
exit_xyz = grid.face_centre(cell_kji0, self.face_pair_indices[interval, 0, 0],
1 - self.face_pair_indices[interval, 0, 1])
ee_crs = grid_crs
else:
entry_xyz = self.trajectory.xyz_for_md(self.node_mds[interval])
exit_xyz = self.trajectory.xyz_for_md(self.node_mds[interval + 1])
ee_crs = traj_crs
if length_mode == 'MD':
length = self.node_mds[interval + 1] - self.node_mds[interval]
if length_uom is not None and self.trajectory is not None and length_uom != self.trajectory.md_uom:
length = bwam.convert_lengths(length, self.trajectory.md_uom, length_uom)
else: # use straight line length between entry and exit
length = vec.naive_length(np.array(exit_xyz) -
np.array(entry_xyz)) # trajectory crs, unless use_face_centres!
if length_uom is not None:
length = bwam.convert_lengths(length, ee_crs.z_units, length_uom)
elif self.trajectory is not None:
length = bwam.convert_lengths(length, ee_crs.z_units, self.trajectory.md_uom)
if perforation_list is not None:
length *= part_perf_fraction
if min_length is not None and length < min_length:
continue
sine_anglv = sine_angla = 0.0
cosine_anglv = cosine_angla = 1.0
xyz = (np.NaN, np.NaN, np.NaN)
md = 0.5 * (self.node_mds[interval + 1] + self.node_mds[interval])
anglv = pc.single_array_ref(citation_title = 'ANGLV')[ci] if 'ANGLV' in pc_titles else None
angla = pc.single_array_ref(citation_title = 'ANGLA')[ci] if 'ANGLA' in pc_titles else None
if doing_angles and not (set_k_face_intervals_vertical and
(np.all(self.face_pair_indices[ci] == k_face_check) or
np.all(self.face_pair_indices[ci] == k_face_check_end))):
vector = vec.unit_vector(np.array(exit_xyz) -
np.array(entry_xyz)) # nominal wellbore vector for interval
if traj_z_inc_down is not None and traj_z_inc_down != grid_crs.z_inc_down:
vector[2] = -vector[2]
v_ref_vector = get_ref_vector(grid, grid_crs, cell_kji0, anglv_ref)
# log.debug('v ref vector: ' + str(v_ref_vector))
if angla_plane_ref == anglv_ref:
a_ref_vector = v_ref_vector
else:
a_ref_vector = get_ref_vector(grid, grid_crs, cell_kji0, angla_plane_ref)
# log.debug('a ref vector: ' + str(a_ref_vector))
if anglv is not None:
anglv_rad = vec.radians_from_degrees(anglv)
cosine_anglv = maths.cos(anglv_rad)
sine_anglv = maths.sin(anglv_rad)
else:
cosine_anglv = min(max(vec.dot_product(vector, v_ref_vector), -1.0), 1.0)
anglv_rad = maths.acos(cosine_anglv)
sine_anglv = maths.sin(anglv_rad)
anglv = vec.degrees_from_radians(anglv_rad)
# log.debug('anglv: ' + str(anglv))
if anglv != 0.0:
# project well vector and i-axis vector onto plane defined by normal vector a_ref_vector
i_axis = grid.interface_vector(cell_kji0, 2)
i_axis = vec.unit_vector(i_axis)
if a_ref_vector is not None: # project vector and i axis onto a plane
vector -= vec.dot_product(vector, a_ref_vector) * a_ref_vector
vector = vec.unit_vector(vector)
# log.debug('i axis unit vector: ' + str(i_axis))
i_axis -= vec.dot_product(i_axis, a_ref_vector) * a_ref_vector
i_axis = vec.unit_vector(i_axis)
# log.debug('i axis unit vector in reference plane: ' + str(i_axis))
if angla is not None:
angla_rad = vec.radians_from_degrees(angla)
cosine_angla = maths.cos(angla_rad)
sine_angla = maths.sin(angla_rad)
else:
cosine_angla = min(max(vec.dot_product(vector, i_axis), -1.0), 1.0)
angla_rad = maths.acos(cosine_angla)
# negate angla if vector is 'clockwise from' i_axis when viewed from above, projected in the xy plane
# todo: have discussion around angla sign under different ijk handedness (and z inc direction?)
sine_angla = maths.sin(angla_rad)
angla = vec.degrees_from_radians(angla_rad)
if vec.clockwise((0.0, 0.0), i_axis, vector) > 0.0:
angla = -angla
angle_rad = -angla_rad
sine_angla = -sine_angla
# log.debug('angla: ' + str(angla))
else:
if angla is None:
angla = 0.0
if anglv is None:
anglv = 0.0
if doing_kh or do_well_inflow:
if ntg_uuid is None:
ntg = 1.0
ntg_is_one = True
else:
ntg = prop_array(ntg_uuid, grid)[tuple_kji0]
ntg_is_one = maths.isclose(ntg, 1.0, rel_tol = 0.001)
if isotropic_perm and ntg_is_one:
k_i = k_j = k_k = prop_array(perm_i_uuid, grid)[tuple_kji0]
else:
if preferential_perforation and not ntg_is_one:
if part_perf_fraction <= ntg:
ntg = 1.0 # effective ntg when perforated intervals are in pay
else:
ntg /= part_perf_fraction # adjusted ntg when some perforations in non-pay
# todo: check netgross facet type in property perm i & j parts: if set to gross then don't multiply by ntg below
k_i = prop_array(perm_i_uuid, grid)[tuple_kji0] * ntg
k_j = prop_array(perm_j_uuid, grid)[tuple_kji0] * ntg
k_k = prop_array(perm_k_uuid, grid)[tuple_kji0]
if doing_kh:
if isotropic_perm and ntg_is_one:
kh = length * prop_array(perm_i_uuid, grid)[tuple_kji0]
else:
if np.isnan(k_i) or np.isnan(k_j):
kh = 0.0
elif anglv == 0.0:
kh = length * maths.sqrt(k_i * k_j)
elif np.isnan(k_k):
kh = 0.0
else:
k_e = maths.pow(k_i * k_j * k_k, 1.0 / 3.0)
if k_e == 0.0:
kh = 0.0
else:
l_i = length * maths.sqrt(k_e / k_i) * sine_anglv * cosine_angla
l_j = length * maths.sqrt(k_e / k_j) * sine_anglv * sine_angla
l_k = length * maths.sqrt(k_e / k_k) * cosine_anglv
l_p = maths.sqrt(l_i * l_i + l_j * l_j + l_k * l_k)
kh = k_e * l_p
if min_kh is not None and kh < min_kh:
continue
elif 'KH' in pc_titles:
kh = pc.single_array_ref(citation_title = 'KH')[ci]
else:
kh = None
if 'LENGTH' in pc_titles:
length = pc.single_array_ref(citation_title = 'LENGTH')[ci]
if 'RADW' in pc_titles:
radw = pc.single_array_ref(citation_title = 'RADW')[ci]
assert radw > 0.0
if 'SKIN' in pc_titles:
skin = pc.single_array_ref(citation_title = 'SKIN')[ci]
radb = wi = wbc = None
if 'RADB' in pc_titles:
radb = pc.single_array_ref(citation_title = 'RADB')[ci]
if 'WI' in pc_titles:
wi = pc.single_array_ref(citation_title = 'WI')[ci]
if 'WBC' in pc_titles:
wbc = pc.single_array_ref(citation_title = 'WBC')[ci]
if do_well_inflow:
if isotropic_perm and ntg_is_one:
k_ei = k_ej = k_ek = k_i
radw_e = radw
else:
k_ei = maths.sqrt(k_j * k_k)
k_ej = maths.sqrt(k_i * k_k)
k_ek = maths.sqrt(k_i * k_j)
r_wi = 0.0 if k_ei == 0.0 else 0.5 * radw * (maths.sqrt(k_ei / k_j) + maths.sqrt(k_ei / k_k))
r_wj = 0.0 if k_ej == 0.0 else 0.5 * radw * (maths.sqrt(k_ej / k_i) + maths.sqrt(k_ej / k_k))
r_wk = 0.0 if k_ek == 0.0 else 0.5 * radw * (maths.sqrt(k_ek / k_i) + maths.sqrt(k_ek / k_j))
rwi = r_wi * sine_anglv * cosine_angla
rwj = r_wj * sine_anglv * sine_angla
rwk = r_wk * cosine_anglv
radw_e = maths.sqrt(rwi * rwi + rwj * rwj + rwk * rwk)
if radw_e == 0.0:
radw_e = radw # no permeability in this situation anyway
cell_axial_vectors = grid.interface_vectors_kji(cell_kji0)
d2 = np.empty(3)
for axis in range(3):
d2[axis] = np.sum(cell_axial_vectors[axis] * cell_axial_vectors[axis])
r_bi = 0.0 if k_ei == 0.0 else 0.14 * maths.sqrt(k_ei * (d2[1] / k_j + d2[0] / k_k))
r_bj = 0.0 if k_ej == 0.0 else 0.14 * maths.sqrt(k_ej * (d2[2] / k_i + d2[0] / k_k))
r_bk = 0.0 if k_ek == 0.0 else 0.14 * maths.sqrt(k_ek * (d2[2] / k_i + d2[1] / k_j))
rbi = r_bi * sine_anglv * cosine_angla
rbj = r_bj * sine_anglv * sine_angla
rbk = r_bk * cosine_anglv
radb_e = maths.sqrt(rbi * rbi + rbj * rbj + rbk * rbk)
if radb is None:
radb = radw * radb_e / radw_e
if wi is None:
wi = 0.0 if radb <= 0.0 else 2.0 * maths.pi / (maths.log(radb / radw) + skin)
if 'WBC' in column_list and wbc is None:
conversion_constant = 8.5270171e-5 if length_uom == 'm' else 0.006328286
wbc = conversion_constant * kh * wi # note: pperf aleady accounted for in kh
if doing_xyz:
if length_mode == 'MD' and self.trajectory is not None:
xyz = self.trajectory.xyz_for_md(md)
if length_uom is not None and length_uom != self.trajectory.md_uom:
bwam.convert_lengths(xyz, traj_crs.z_units, length_uom)
if depth_inc_down and traj_z_inc_down is False:
xyz[2] = -xyz[2]
else:
xyz = 0.5 * (np.array(exit_xyz) + np.array(entry_xyz))
if length_uom is not None and length_uom != ee_crs.z_units:
bwam.convert_lengths(xyz, ee_crs.z_units, length_uom)
if depth_inc_down and ee_crs.z_inc_down is False:
xyz[2] = -xyz[2]
xyz = np.array(xyz)
if 'X' in pc_titles:
xyz[0] = pc.single_array_ref(citation_title = 'X')[ci]
if 'Y' in pc_titles:
xyz[1] = pc.single_array_ref(citation_title = 'Y')[ci]
if 'DEPTH' in pc_titles:
xyz[2] = pc.single_array_ref(citation_title = 'DEPTH')[ci]
if length_uom is not None and self.trajectory is not None and length_uom != self.trajectory.md_uom:
md = bwam.convert_lengths(md, self.trajectory.md_uom, length_uom)
if 'MD' in pc_titles:
md = pc.single_array_ref(citation_title = 'MD')[ci]
for col_index in range(len(column_list)):
column = column_list[col_index]
if col_index < 3:
if one_based:
row_dict[column] = cell_kji0[2 - col_index] + 1
else:
row_dict[column] = cell_kji0[2 - col_index]
elif column == 'GRID':
row_dict['GRID'] = grid_name # todo: worry about spaces and quotes
elif column == 'RADW':
row_dict['RADW'] = radw
elif column == 'SKIN':
row_dict['SKIN'] = skin
elif column == 'ANGLA':
row_dict['ANGLA'] = angla
elif column == 'ANGLV':
row_dict['ANGLV'] = anglv
elif column == 'LENGTH':
# note: length units are those of trajectory length uom if length mode is MD and length_uom is None
row_dict['LENGTH'] = length
elif column == 'KH':
row_dict['KH'] = kh
elif column == 'DEPTH':
row_dict['DEPTH'] = xyz[2]
elif column == 'MD':
row_dict['MD'] = md
elif column == 'X':
row_dict['X'] = xyz[0]
elif column == 'Y':
row_dict['Y'] = xyz[1]
elif column == 'STAT':
row_dict['STAT'] = stat
elif column == 'PPERF':
row_dict['PPERF'] = part_perf_fraction
elif column == 'RADB':
row_dict['RADB'] = radb
elif column == 'WI':
row_dict['WI'] = wi
elif column == 'WBC': # note: not a valid WELLSPEC column name
row_dict['WBC'] = wbc
df = df.append(row_dict, ignore_index = True)
row_ci_list.append(ci)
if add_as_properties:
if isinstance(add_as_properties, list):
for col in add_as_properties:
assert col in extra_columns_list
property_columns = add_as_properties
else:
property_columns = extra_columns_list
self._add_df_properties(df, property_columns, row_ci_list = row_ci_list, length_uom = length_uom)
return df
def _add_df_properties(self, df, columns, row_ci_list = None, length_uom = None):
# creates a property part for each named column, based on the dataframe values
# column name used as the citation title
# self must already exist as a part in the model
# currently only handles single grid situations
# todo: rewrite to add separate property objects for each grid references by the blocked well
log.debug('_add_df_props: df:')
log.debug(f'\n{df}')
log.debug(f'columns: {columns}')
assert len(self.grid_list) == 1
if columns is None or len(columns) == 0 or len(df) == 0:
return
if row_ci_list is None:
row_ci_list = np.arange(self.cell_count)
assert len(row_ci_list) == len(df)
if length_uom is None:
length_uom = self.trajectory.md_uom
extra_pc = rqp.PropertyCollection()
extra_pc.set_support(support = self)
ci_map = np.array(row_ci_list, dtype = int)
for e in columns:
extra = e.upper()
if extra in ['GRID', 'STAT']:
continue # todo: other non-numeric columns may need to be added to this list
pk = 'continuous'
uom = 'Euc'
if extra in ['ANGLA', 'ANGLV']:
uom = 'dega'
# neither azimuth nor dip are correct property kinds; todo: create local property kinds
pk = 'azimuth' if extra == 'ANGLA' else 'inclination'
elif extra in ['LENGTH', 'MD', 'X', 'Y', 'DEPTH', 'RADW']:
if length_uom is None or length_uom == 'Euc':
if extra in ['LENGTH', 'MD']:
uom = self.trajectory.md_uom
elif extra in ['X', 'Y', 'RADW']:
uom = self.grid_list[0].xy_units()
else:
uom = self.grid_list[0].z_units()
else:
uom = length_uom
if extra == 'DEPTH':
pk = 'depth'
else:
pk = 'length'
elif extra == 'KH':
uom = 'mD.' + length_uom
pk = 'permeability length'
elif extra == 'PPERF':
uom = length_uom + '/' + length_uom
else:
uom = 'Euc'
# 'SKIN': use defaults for now; todo: create local property kind for skin
expanded = np.full(self.cell_count, np.NaN)
expanded[ci_map] = df[extra]
extra_pc.add_cached_array_to_imported_list(expanded,
'blocked well dataframe',
extra,
discrete = False,
uom = uom,
property_kind = pk,
local_property_kind_uuid = None,
facet_type = None,
facet = None,
realization = None,
indexable_element = 'cells',
count = 1)
extra_pc.write_hdf5_for_imported_list()
extra_pc.create_xml_for_imported_list_and_add_parts_to_model()
def static_kh(self,
ntg_uuid = None,
perm_i_uuid = None,
perm_j_uuid = None,
perm_k_uuid = None,
satw_uuid = None,
sato_uuid = None,
satg_uuid = None,
region_uuid = None,
active_only = False,
min_k0 = None,
max_k0 = None,
k0_list = None,
min_length = None,
min_kh = None,
max_depth = None,
max_satw = None,
min_sato = None,
max_satg = None,
perforation_list = None,
region_list = None,
set_k_face_intervals_vertical = False,
anglv_ref = 'gravity',
angla_plane_ref = None,
length_mode = 'MD',
length_uom = None,
use_face_centres = False,
preferential_perforation = True):
"""Returns the total static K.H (permeability x height); length units are those of trajectory md_uom unless
length_upm is set.
note:
see doc string for dataframe() method for argument descriptions; perm_i_uuid required
"""
df = self.dataframe(i_col = 'I',
j_col = 'J',
k_col = 'K',
one_based = False,
extra_columns_list = ['KH'],
ntg_uuid = ntg_uuid,
perm_i_uuid = perm_i_uuid,
perm_j_uuid = perm_j_uuid,
perm_k_uuid = perm_k_uuid,
satw_uuid = satw_uuid,
sato_uuid = sato_uuid,
satg_uuid = satg_uuid,
region_uuid = region_uuid,
active_only = active_only,
min_k0 = min_k0,
max_k0 = max_k0,
k0_list = k0_list,
min_length = min_length,
min_kh = min_kh,
max_depth = max_depth,
max_satw = max_satw,
min_sato = min_sato,
max_satg = max_satg,
perforation_list = perforation_list,
region_list = region_list,
set_k_face_intervals_vertical = set_k_face_intervals_vertical,
anglv_ref = anglv_ref,
angla_plane_ref = angla_plane_ref,
length_mode = length_mode,
length_uom = length_uom,
use_face_centres = use_face_centres,
preferential_perforation = preferential_perforation)
return sum(df['KH'])
def write_wellspec(self,
wellspec_file,
well_name = None,
mode = 'a',
extra_columns_list = [],
ntg_uuid = None,
perm_i_uuid = None,
perm_j_uuid = None,
perm_k_uuid = None,
satw_uuid = None,
sato_uuid = None,
satg_uuid = None,
region_uuid = None,
radw = None,
skin = None,
stat = None,
active_only = False,
min_k0 = None,
max_k0 = None,
k0_list = None,
min_length = None,
min_kh = None,
max_depth = None,
max_satw = None,
min_sato = None,
max_satg = None,
perforation_list = None,
region_list = None,
set_k_face_intervals_vertical = False,
depth_inc_down = True,
anglv_ref = 'gravity',
angla_plane_ref = None,
length_mode = 'MD',
length_uom = None,
preferential_perforation = True,
space_instead_of_tab_separator = True,
align_columns = True,
preceeding_blank_lines = 0,
trailing_blank_lines = 0,
length_uom_comment = False,
write_nexus_units = True,
float_format = '5.3'):
"""Writes Nexus WELLSPEC keyword to an ascii file.
returns:
pandas DataFrame containing data that has been written to the wellspec file
note:
see doc string for dataframe() method for most of the argument descriptions;
align_columns and float_format arguments are deprecated and no longer used
"""
def tidy_well_name(well_name):
nexus_friendly = ''
previous_underscore = False
for ch in well_name:
if not 32 <= ord(ch) < 128 or ch in ' ,!*#':
ch = '_'
if not (previous_underscore and ch == '_'):
nexus_friendly += ch
previous_underscore = (ch == '_')
if not nexus_friendly:
well_name = 'WELL_X'
return nexus_friendly
def is_float_column(col_name):
if col_name.upper() in ['ANGLA', 'ANGLV', 'LENGTH', 'KH', 'DEPTH', 'MD', 'X', 'Y', 'SKIN', 'RADW', 'PPERF']:
return True
return False
def is_int_column(col_name):
if col_name.upper() in ['IW', 'JW', 'L']:
return True
return False
assert wellspec_file, 'no output file specified to write WELLSPEC to'
col_width_dict = {
'IW': 4,
'JW': 4,
'L': 4,
'ANGLA': 8,
'ANGLV': 8,
'LENGTH': 8,
'KH': 10,
'DEPTH': 10,
'MD': 10,
'X': 8,
'Y': 12,
'SKIN': 7,
'RADW': 5,
'PPERF': 5
}
if not well_name:
if self.well_name:
well_name = self.well_name
elif self.root is not None:
well_name = rqet.citation_title_for_node(self.root)
elif self.wellbore_interpretation is not None:
well_name = self.wellbore_interpretation.title
elif self.trajectory is not None:
well_name = self.trajectory.title
else:
log.warning('no well name identified for use in WELLSPEC')
well_name = 'WELLNAME'
well_name = tidy_well_name(well_name)
df = self.dataframe(one_based = True,
extra_columns_list = extra_columns_list,
ntg_uuid = ntg_uuid,
perm_i_uuid = perm_i_uuid,
perm_j_uuid = perm_j_uuid,
perm_k_uuid = perm_k_uuid,
satw_uuid = satw_uuid,
sato_uuid = sato_uuid,
satg_uuid = satg_uuid,
region_uuid = region_uuid,
radw = radw,
skin = skin,
stat = stat,
active_only = active_only,
min_k0 = min_k0,
max_k0 = max_k0,
k0_list = k0_list,
min_length = min_length,
min_kh = min_kh,
max_depth = max_depth,
max_satw = max_satw,
min_sato = min_sato,
max_satg = max_satg,
perforation_list = perforation_list,
region_list = region_list,
depth_inc_down = depth_inc_down,
set_k_face_intervals_vertical = set_k_face_intervals_vertical,
anglv_ref = anglv_ref,
angla_plane_ref = angla_plane_ref,
length_mode = length_mode,
length_uom = length_uom,
preferential_perforation = preferential_perforation)
sep = ' ' if space_instead_of_tab_separator else '\t'
with open(wellspec_file, mode = mode) as fp:
for _ in range(preceeding_blank_lines):
fp.write('\n')
if write_nexus_units:
if length_uom == 'm':
fp.write('METRIC\n\n')
elif length_uom == 'ft':
fp.write('ENGLISH\n\n')
if length_uom_comment and self.trajectory is not None and ('LENGTH' in extra_columns_list or
'MD' in extra_columns_list or
'KH' in extra_columns_list):
fp.write(
f'! Length units along wellbore: {self.trajectory.md_uom if length_uom is None else length_uom}\n')
fp.write('WELLSPEC ' + str(well_name) + '\n')
for col_name in df.columns:
if col_name in col_width_dict:
width = col_width_dict[col_name]
else:
width = 10
form = '{0:>' + str(width) + '}'
fp.write(sep + form.format(col_name))
fp.write('\n')
for row_info in df.iterrows():
row = row_info[1]
for col_name in df.columns:
try:
if col_name in col_width_dict:
width = col_width_dict[col_name]
else:
width = 10
if is_float_column(col_name):
form = '{0:>' + str(width) + '.3f}'
fp.write(sep + form.format(float(row[col_name])))
else:
form = '{0:>' + str(width) + '}'
if is_int_column(col_name):
fp.write(sep + form.format(int(row[col_name])))
else:
fp.write(sep + form.format(str(row[col_name])))
except Exception:
fp.write(sep + str(row[col_name]))
fp.write('\n')
for _ in range(trailing_blank_lines):
fp.write('\n')
return df
def kji0_marker(self, active_only = True):
"""Convenience method returning (k0, j0, i0), grid_uuid of first blocked interval."""
cells, grids = self.cell_indices_and_grid_list()
if cells is None or grids is None or len(grids) == 0:
return None, None, None, None
return cells[0], grids[0].uuid
def xyz_marker(self, active_only = True):
"""Convenience method returning (x, y, z), crs_uuid of perforation in first blocked interval.
notes:
active_only argument not yet in use;
returns None, None if no blocked interval found
"""
cells, grids = self.cell_indices_and_grid_list()
if cells is None or grids is None or len(grids) == 0:
return None, None
node_index = 0
while node_index < self.node_count - 1 and self.grid_indices[node_index] == -1:
node_index += 1
if node_index >= self.node_count - 1:
return None, None
md = 0.5 * (self.node_mds[node_index] + self.node_mds[node_index + 1])
xyz = self.trajectory.xyz_for_md(md)
return xyz, rqet.uuid_for_part_root(self.trajectory.crs_root)
def create_feature_and_interpretation(self, shared_interpretation = True):
"""Instantiate new empty WellboreFeature and WellboreInterpretation objects.
Uses the Blocked well citation title as the well name
"""
if self.trajectory is not None:
traj_interp_uuid = self.model.uuid(obj_type = 'WellboreInterpretation', related_uuid = self.trajectory.uuid)
if traj_interp_uuid is not None:
if shared_interpretation:
self.wellbore_interpretation = rqo.WellboreInterpretation(parent_model = self.model,
uuid = traj_interp_uuid)
traj_feature_uuid = self.model.uuid(obj_type = 'WellboreFeature', related_uuid = traj_interp_uuid)
if traj_feature_uuid is not None:
self.wellbore_feature = rqo.WellboreFeature(parent_model = self.model, uuid = traj_feature_uuid)
if self.wellbore_feature is None:
self.wellbore_feature = rqo.WellboreFeature(parent_model = self.model, feature_name = self.trajectory.title)
self.feature_to_be_written = True
if self.wellbore_interpretation is None:
self.wellbore_interpretation = rqo.WellboreInterpretation(parent_model = self.model,
wellbore_feature = self.wellbore_feature)
if self.trajectory.wellbore_interpretation is None and shared_interpretation:
self.trajectory.wellbore_interpretation = self.wellbore_interpretation
self.interpretation_to_be_written = True
def create_md_datum_and_trajectory(self,
grid,
trajectory_mds,
trajectory_points,
length_uom,
well_name,
set_depth_zero = False,
set_tangent_vectors = False,
create_feature_and_interp = True):
"""Creates an Md Datum object and a (simulation) Trajectory object for this blocked well.
note:
not usually called directly; used by import methods
"""
# create md datum node for synthetic trajectory, using crs for grid
datum_location = trajectory_points[0].copy()
if set_depth_zero:
datum_location[2] = 0.0
datum = MdDatum(self.model,
crs_uuid = grid.crs_uuid,
location = datum_location,
md_reference = 'mean sea level')
# create synthetic trajectory object, using crs for grid
trajectory_mds_array = np.array(trajectory_mds)
trajectory_xyz_array = np.array(trajectory_points)
trajectory_df = pd.DataFrame({
'MD': trajectory_mds_array,
'X': trajectory_xyz_array[..., 0],
'Y': trajectory_xyz_array[..., 1],
'Z': trajectory_xyz_array[..., 2]
})
self.trajectory = Trajectory(self.model,
md_datum = datum,
data_frame = trajectory_df,
length_uom = length_uom,
well_name = well_name,
set_tangent_vectors = set_tangent_vectors)
self.trajectory_to_be_written = True
if create_feature_and_interp:
self.create_feature_and_interpretation()
def create_xml(self,
ext_uuid = None,
create_for_trajectory_if_needed = True,
add_as_part = True,
add_relationships = True,
title = None,
originator = None):
"""Create a blocked wellbore representation node from this BlockedWell object, optionally add as part.
note:
trajectory xml node must be in place before calling this function;
witsml log reference, interval stratigraphic units, and cell fluid phase units not yet supported
:meta common:
"""
assert self.trajectory is not None, 'trajectory object missing'
if ext_uuid is None:
ext_uuid = self.model.h5_uuid()
if title:
self.title = title
if not self.title:
self.title = 'blocked well'
if self.feature_to_be_written:
if self.wellbore_feature is None:
self.create_feature_and_interpretation()
self.wellbore_feature.create_xml(add_as_part = add_as_part, originator = originator)
if self.interpretation_to_be_written:
if self.wellbore_interpretation is None:
self.create_feature_and_interpretation()
self.wellbore_interpretation.create_xml(add_as_part = add_as_part,
title_suffix = None,
add_relationships = add_relationships,
originator = originator)
if create_for_trajectory_if_needed and self.trajectory_to_be_written and self.trajectory.root is None:
md_datum_root = self.trajectory.md_datum.create_xml(add_as_part = add_as_part,
add_relationships = add_relationships,
title = str(self.title),
originator = originator)
self.trajectory.create_xml(ext_uuid,
md_datum_root = md_datum_root,
add_as_part = add_as_part,
add_relationships = add_relationships,
title = title,
originator = originator)
assert self.trajectory.root is not None, 'trajectory xml not established'
bw_node = super().create_xml(title = title, originator = originator, add_as_part = False)
# wellbore frame elements
nc_node = rqet.SubElement(bw_node, ns['resqml2'] + 'NodeCount')
nc_node.set(ns['xsi'] + 'type', ns['xsd'] + 'positiveInteger')
nc_node.text = str(self.node_count)
mds_node = rqet.SubElement(bw_node, ns['resqml2'] + 'NodeMd')
mds_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'DoubleHdf5Array')
mds_node.text = rqet.null_xml_text
mds_values_node = rqet.SubElement(mds_node, ns['resqml2'] + 'Values')
mds_values_node.set(ns['xsi'] + 'type', ns['eml'] + 'Hdf5Dataset')
mds_values_node.text = rqet.null_xml_text
self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'NodeMd', root = mds_values_node)
traj_root = self.trajectory.root
self.model.create_ref_node('Trajectory',
rqet.find_nested_tags_text(traj_root, ['Citation', 'Title']),
bu.uuid_from_string(traj_root.attrib['uuid']),
content_type = 'obj_WellboreTrajectoryRepresentation',
root = bw_node)
# remaining blocked wellbore elements
cc_node = rqet.SubElement(bw_node, ns['resqml2'] + 'CellCount')
cc_node.set(ns['xsi'] + 'type', ns['xsd'] + 'nonNegativeInteger')
cc_node.text = str(self.cell_count)
cis_node = rqet.SubElement(bw_node, ns['resqml2'] + 'CellIndices')
cis_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'IntegerHdf5Array')
cis_node.text = rqet.null_xml_text
cnull_node = rqet.SubElement(cis_node, ns['resqml2'] + 'NullValue')
cnull_node.set(ns['xsi'] + 'type', ns['xsd'] + 'integer')
cnull_node.text = str(self.cellind_null)
cis_values_node = rqet.SubElement(cis_node, ns['resqml2'] + 'Values')
cis_values_node.set(ns['xsi'] + 'type', ns['eml'] + 'Hdf5Dataset')
cis_values_node.text = rqet.null_xml_text
self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'CellIndices', root = cis_values_node)
gis_node = rqet.SubElement(bw_node, ns['resqml2'] + 'GridIndices')
gis_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'IntegerHdf5Array')
gis_node.text = rqet.null_xml_text
gnull_node = rqet.SubElement(gis_node, ns['resqml2'] + 'NullValue')
gnull_node.set(ns['xsi'] + 'type', ns['xsd'] + 'integer')
gnull_node.text = str(self.gridind_null)
gis_values_node = rqet.SubElement(gis_node, ns['resqml2'] + 'Values')
gis_values_node.set(ns['xsi'] + 'type', ns['eml'] + 'Hdf5Dataset')
gis_values_node.text = rqet.null_xml_text
self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'GridIndices', root = gis_values_node)
fis_node = rqet.SubElement(bw_node, ns['resqml2'] + 'LocalFacePairPerCellIndices')
fis_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'IntegerHdf5Array')
fis_node.text = rqet.null_xml_text
fnull_node = rqet.SubElement(fis_node, ns['resqml2'] + 'NullValue')
fnull_node.set(ns['xsi'] + 'type', ns['xsd'] + 'integer')
fnull_node.text = str(self.facepair_null)
fis_values_node = rqet.SubElement(fis_node, ns['resqml2'] + 'Values')
fis_values_node.set(ns['xsi'] + 'type', ns['eml'] + 'Hdf5Dataset')
fis_values_node.text = rqet.null_xml_text
self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'LocalFacePairPerCellIndices', root = fis_values_node)
for grid in self.grid_list:
grid_root = grid.root
self.model.create_ref_node('Grid',
rqet.find_nested_tags_text(grid_root, ['Citation', 'Title']),
bu.uuid_from_string(grid_root.attrib['uuid']),
content_type = 'obj_IjkGridRepresentation',
root = bw_node)
interp_root = None
if self.wellbore_interpretation is not None:
interp_root = self.wellbore_interpretation.root
self.model.create_ref_node('RepresentedInterpretation',
rqet.find_nested_tags_text(interp_root, ['Citation', 'Title']),
bu.uuid_from_string(interp_root.attrib['uuid']),
content_type = 'obj_WellboreInterpretation',
root = bw_node)
if add_as_part:
self.model.add_part('obj_BlockedWellboreRepresentation', self.uuid, bw_node)
if add_relationships:
self.model.create_reciprocal_relationship(bw_node, 'destinationObject', self.trajectory.root,
'sourceObject')
for grid in self.grid_list:
self.model.create_reciprocal_relationship(bw_node, 'destinationObject', grid.root, 'sourceObject')
if interp_root is not None:
self.model.create_reciprocal_relationship(bw_node, 'destinationObject', interp_root, 'sourceObject')
ext_part = rqet.part_name_for_object('obj_EpcExternalPartReference', ext_uuid, prefixed = False)
ext_node = self.model.root_for_part(ext_part)
self.model.create_reciprocal_relationship(bw_node, 'mlToExternalPartProxy', ext_node,
'externalPartProxyToMl')
return bw_node
def write_hdf5(self, file_name = None, mode = 'a', create_for_trajectory_if_needed = True):
"""Create or append to an hdf5 file, writing datasets for the measured depths, grid, cell & face indices.
:meta common:
"""
# NB: array data must all have been set up prior to calling this function
if self.uuid is None:
self.uuid = bu.new_uuid()
h5_reg = rwh5.H5Register(self.model)
if create_for_trajectory_if_needed and self.trajectory_to_be_written:
self.trajectory.write_hdf5(file_name, mode = mode)
mode = 'a'
h5_reg.register_dataset(self.uuid, 'NodeMd', self.node_mds)
h5_reg.register_dataset(self.uuid, 'CellIndices', self.cell_indices) # could use int32?
h5_reg.register_dataset(self.uuid, 'GridIndices', self.grid_indices) # could use int32?
# convert face index pairs from [axis, polarity] back to strange local face numbering
mask = (self.face_pair_indices.flatten() == -1).reshape((-1, 2)) # 2nd axis is (axis, polarity)
masked_face_indices = np.where(mask, 0, self.face_pair_indices.reshape((-1, 2))) # 2nd axis is (axis, polarity)
# using flat array for raw_face_indices array
# other resqml writing code might use an array with one int per entry point and one per exit point, with 2nd axis as (entry, exit)
raw_face_indices = np.where(mask[:, 0], -1, self.face_index_map[masked_face_indices[:, 0],
masked_face_indices[:,
1]].flatten()).reshape(-1)
h5_reg.register_dataset(self.uuid, 'LocalFacePairPerCellIndices', raw_face_indices) # could use uint8?
h5_reg.write(file = file_name, mode = mode)
class WellboreMarkerFrame(BaseResqpy):
"""Class to handle RESQML WellBoreMarkerFrameRepresentation objects.
note:
measured depth data must be in same crs as those for the related trajectory
"""
resqml_type = 'WellboreMarkerFrameRepresentation'
def __init__(self,
parent_model,
wellbore_marker_frame_root = None,
uuid = None,
trajectory = None,
title = None,
originator = None,
extra_metadata = None):
"""Creates a new wellbore marker object and optionally loads it from xml, or trajectory, or Nexus wellspec file.
arguments:
parent_model (model.Model object): the model which the new blocked well belongs to
wellbore_marker_root (DEPRECATED): the root node of an xml tree representing the wellbore marker;
trajectory (optional, Trajectory object): the trajectory of the well, to be intersected with the grid;
not used if wellbore_marker_root is not None;
title (str, optional): the citation title to use for a new wellbore marker frame;
ignored if uuid or wellbore_marker_frame_root is not None
originator (str, optional): the name of the person creating the wellbore marker frame, defaults to login id;
ignored if uuid or wellbore_marker_frame_root is not None
extra_metadata (dict, optional): string key, value pairs to add as extra metadata for the wellbore marker frame;
ignored if uuid or wellbore_marker_frame_root is not None
returns:
the newly created wellbore framework marker object
"""
self.trajectory = None
self.node_count = None # number of measured depth nodes, each being for a marker
self.node_mds = None # node_count measured depths (in same units and datum as trajectory) of markers
self.wellbore_marker_list = [
] # list of markers, each: (marker UUID, geologic boundary, marker citation title, interp. object)
if self.trajectory is not None:
self.trajectory = trajectory
super().__init__(model = parent_model,
uuid = uuid,
title = title,
originator = originator,
extra_metadata = extra_metadata,
root_node = wellbore_marker_frame_root)
def get_trajectory_obj(self, trajectory_uuid):
"""Returns a trajectory object.
arguments:
trajectory_uuid (string or uuid.UUID): the uuid of the trajectory for which a Trajectory object is required
returns:
well.Trajectory object
note:
this method is not usually called directly
"""
if trajectory_uuid is None:
log.error('no trajectory was found')
return None
else:
# create new trajectory object
trajectory_root_node = self.model.root_for_uuid(trajectory_uuid)
assert trajectory_root_node is not None, 'referenced wellbore trajectory missing from model'
return Trajectory(self.model, trajectory_root = trajectory_root_node)
def get_interpretation_obj(self, interpretation_uuid, interp_type = None):
"""Creates an interpretation object; returns a horizon or fault interpretation object.
arguments:
interpretation_uiud (string or uuid.UUID): the uuid of the required interpretation object
interp_type (string, optional): 'HorizonInterpretation' or 'FaultInterpretation' (optionally
prefixed with `obj_`); if None, the type is inferred from the xml for the given uuid
returns:
organization.HorizonInterpretation or organization.FaultInterpretation object
note:
this method is not usually called directly
"""
assert interpretation_uuid is not None, 'interpretation uuid argument missing'
interpretation_root_node = self.model.root_for_uuid(interpretation_uuid)
if not interp_type:
interp_type = rqet.node_type(interpretation_root_node)
if not interp_type.startswith('obj_'):
interp_type = 'obj_' + interp_type
if interp_type == 'obj_HorizonInterpretation':
# create new horizon interpretation object
return rqo.HorizonInterpretation(self.model, root_node = interpretation_root_node)
elif interp_type == 'obj_FaultInterpretation':
# create new fault interpretation object
return rqo.FaultInterpretation(self.model, root_node = interpretation_root_node)
elif interp_type == 'obj_GeobodyInterpretation':
# create new geobody interpretation object
return rqo.GeobodyInterpretation(self.model, root_node = interpretation_root_node)
else:
# No interpretation for the marker
return None
# log.error('interpretation type not recognized: ' + str(interp_type))
def _load_from_xml(self):
"""Loads the wellbore marker frame object from an xml node (and associated hdf5 data).
note:
this method is not usually called directly
"""
wellbore_marker_frame_root = self.root
assert wellbore_marker_frame_root is not None
if self.trajectory is None:
self.trajectory = self.get_trajectory_obj(
rqet.find_nested_tags_text(wellbore_marker_frame_root, ['Trajectory', 'UUID']))
# list of Wellbore markers, each: (marker UUID, geologic boundary, marker citation title, interp. object)
self.wellbore_marker_list = []
for tag in rqet.list_of_tag(wellbore_marker_frame_root, 'WellboreMarker'):
interp_tag = rqet.content_type(rqet.find_nested_tags_text(tag, ['Interpretation', 'ContentType']))
if interp_tag is not None:
interp_obj = self.get_interpretation_obj(rqet.find_nested_tags_text(tag, ['Interpretation', 'UUID']),
interp_tag)
else:
interp_obj = None
self.wellbore_marker_list.append(
(str(rqet.uuid_for_part_root(tag)), rqet.find_tag_text(tag, 'GeologicBoundaryKind'),
rqet.find_nested_tags_text(tag, ['Citation', 'Title']), interp_obj))
self.node_count = rqet.find_tag_int(wellbore_marker_frame_root, 'NodeCount')
load_hdf5_array(self, rqet.find_tag(wellbore_marker_frame_root, 'NodeMd'), "node_mds", tag = 'Values')
if self.node_count != len(self.node_mds):
log.error('node count does not match hdf5 array')
if len(self.wellbore_marker_list) != self.node_count:
log.error('wellbore marker list does not contain correct node count')
def dataframe(self):
"""Returns a pandas dataframe with columns X, Y, Z, MD, Type, Surface, Well."""
# todo: handle fractures and geobody boundaries as well as horizons and faults
xyz = np.empty((self.node_count, 3))
type_list = []
surface_list = []
well_list = []
for i in range(self.node_count):
_, boundary_kind, title, interp = self.wellbore_marker_list[i]
if interp:
if boundary_kind == 'horizon':
feature_name = rqo.GeneticBoundaryFeature(self.model, root_node = interp.feature_root).feature_name
elif boundary_kind == 'fault':
feature_name = rqo.TectonicBoundaryFeature(self.model, root_node = interp.feature_root).feature_name
elif boundary_kind == 'geobody':
feature_name = rqo.GeneticBoundaryFeature(self.model, root_node = interp.feature_root).feature_name
else:
assert False, 'unexpected boundary kind'
else:
feature_name = title
boundary_kind = boundary_kind[0].upper() + boundary_kind[1:]
feature_name = '"' + feature_name + '"'
xyz[i] = self.trajectory.xyz_for_md(self.node_mds[i])
type_list.append(boundary_kind)
surface_list.append(feature_name)
if self.trajectory.wellbore_interpretation is None:
well_name = '"' + self.trajectory.title + '"' # todo: trace through wellbore interp to wellbore feature name
else:
well_name = '"' + self.trajectory.wellbore_interpretation.title + '"' # use wellbore_interpretation title instead, RMS exports have feature_name as "Wellbore feature"
# well_name = '"' + self.trajectory.wellbore_interpretation.wellbore_feature.feature_name + '"'
well_list.append(well_name)
return pd.DataFrame({
'X': xyz[:, 0],
'Y': xyz[:, 1],
'Z': xyz[:, 2],
'MD': self.node_mds,
'Type': type_list,
'Surface': surface_list,
'Well': well_list
})
def create_xml(self,
ext_uuid = None,
add_as_part = True,
add_relationships = True,
wellbore_marker_list = None,
title = 'wellbore marker framework',
originator = None):
assert type(add_as_part) is bool
if ext_uuid is None:
ext_uuid = self.model.h5_uuid()
wbm_node = super().create_xml(originator = originator, add_as_part = False)
nodeCount = rqet.SubElement(wbm_node, ns['resqml2'] + 'NodeCount')
nodeCount.set(ns['xsi'] + 'type', ns['xsd'] + 'positiveInteger')
nodeCount.text = str(self.node_count)
nodeMd = rqet.SubElement(wbm_node, ns['resqml2'] + 'NodeMd')
nodeMd.set(ns['xsi'] + 'type', ns['resqml2'] + 'DoubleHdf5Array')
nodeMd.text = rqet.null_xml_text
md_values_node = rqet.SubElement(nodeMd, ns['resqml2'] + 'Values')
md_values_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'Hdf5Dataset')
md_values_node.text = rqet.null_xml_text
self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'mds', root = md_values_node)
if self.trajectory is not None:
traj_root = self.trajectory.root
self.model.create_ref_node('Trajectory',
rqet.find_tag(rqet.find_tag(traj_root, 'Citation'), 'Title').text,
bu.uuid_from_string(traj_root.attrib['uuid']),
content_type = 'obj_WellboreTrajectoryRepresentation',
root = wbm_node)
else:
log.error('trajectory object is missing and must be included')
# fill wellbore marker
for marker in self.wellbore_marker_list:
wbm_node_obj = self.model.new_obj_node('WellboreMarker', is_top_lvl_obj = False)
wbm_node_obj.set('uuid', marker[0])
wbm_node.append(wbm_node_obj)
wbm_gb_node = rqet.SubElement(wbm_node_obj, ns['resqml2'] + 'GeologicBoundaryKind')
wbm_gb_node.set(ns['xsi'] + 'type', ns['xsd'] + 'string')
wbm_gb_node.text = str(marker[1])
interp = marker[3]
if interp is not None:
interp_root = marker[3].root
if 'HorizonInterpretation' in str(type(marker[3])):
self.model.create_ref_node('Interpretation',
rqet.find_tag(rqet.find_tag(interp_root, 'Citation'), 'Title').text,
bu.uuid_from_string(interp_root.attrib['uuid']),
content_type = 'obj_HorizonInterpretation',
root = wbm_node_obj)
elif 'FaultInterpretation' in str(type(marker[3])):
self.model.create_ref_node('Interpretation',
rqet.find_tag(rqet.find_tag(interp_root, 'Citation'), 'Title').text,
bu.uuid_from_string(interp_root.attrib['uuid']),
content_type = 'obj_FaultInterpretation',
root = wbm_node_obj)
# add as part
if add_as_part:
self.model.add_part('obj_WellboreMarkerFrameRepresentation', self.uuid, wbm_node)
if add_relationships:
self.model.create_reciprocal_relationship(wbm_node, 'destinationObject', self.trajectory.root,
'sourceObject')
ext_part = rqet.part_name_for_object('obj_EpcExternalPartReference', ext_uuid, prefixed = False)
ext_node = self.model.root_for_part(ext_part)
self.model.create_reciprocal_relationship(wbm_node, 'mlToExternalPartProxy', ext_node,
'externalPartProxyToMl')
for marker in self.wellbore_marker_list:
self.model.create_reciprocal_relationship(wbm_node, 'destinationObject', marker[3].root,
'sourceObject')
return wbm_node
def write_hdf5(self, file_name = None, mode = 'a'):
"""Writes the hdf5 array associated with this object (the measured depth data).
arguments:
file_name (string): the name of the hdf5 file, or None, in which case the model's default will be used
mode (string, default 'a'): the write mode for the hdf5, either 'w' or 'a'
"""
h5_reg = rwh5.H5Register(self.model)
h5_reg.register_dataset(self.uuid, 'Mds', self.node_mds)
h5_reg.write(file = file_name, mode = mode)
def find_marker_from_interp(self, interpetation_obj = None, uuid = None):
"""Find wellbore marker by interpretation; can pass object or uuid.
arguments:
interpretation_obj (organize.HorizonInterpretation or organize.FaultInterpretation object, optional):
if present, the first (smallest md) marker relating to this interpretation object is returned
uuid (string or uuid.UUID): if present, the uuid of the interpretation object of interest; ignored if
interpretation_obj is not None
returns:
tuple, list of tuples or None; tuple is (marker UUID, geologic boundary, marker citation title, interp. object)
note:
if no arguments are passed, then a list of wellbore markers is returned;
if no marker is found for the interpretation object, None is returned
"""
if interpetation_obj is None and uuid is None:
return self.wellbore_marker_list
if interpetation_obj is not None:
uuid = interpetation_obj.uuid
for marker in self.wellbore_marker_list:
if bu.matching_uuids(marker[3].uuid, uuid):
return marker
return None
def get_marker_count(self):
"""Retruns number of wellbore markers."""
return len(self.wellbore_marker_list)
def find_marker_from_index(self, idx):
"""Returns wellbore marker by index."""
return self.wellbore_marker_list[idx - 1]
def add_las_to_trajectory(las: lasio.LASFile, trajectory, realization = None, check_well_name = False):
"""Creates a WellLogCollection and WellboreFrame from a LAS file.
Note:
In this current implementation, the first curve in the las object must be
Measured Depths, not e.g. TVDSS.
Arguments:
las: an lasio.LASFile object
trajectory: an instance of :class:`resqpy.well.Trajectory` .
realization (integer): if present, the single realisation (within an ensemble)
that this collection is for
check_well_name (bool): if True, raise warning if LAS well name does not match
existing wellborefeature citation title
Returns:
collection, well_frame: instances of :class:`resqpy.property.WellLogCollection`
and :class:`resqpy.well.WellboreFrame`
"""
# Lookup relevant related resqml parts
model = trajectory.model
well_interp = trajectory.wellbore_interpretation
well_title = well_interp.title
if check_well_name and well_title != las.well.WELL.value:
warnings.warn(f'LAS well title {las.well.WELL.value} does not match resqml tite {well_title}')
# Create a new wellbore frame, using depth data from first curve in las file
depth_values = np.array(las.index).copy()
assert isinstance(depth_values, np.ndarray)
las_depth_uom = bwam.rq_length_unit(las.curves[0].unit)
# Ensure depth units are correct
bwam.convert_lengths(depth_values, from_units = las_depth_uom, to_units = trajectory.md_uom)
assert len(depth_values) > 0
well_frame = WellboreFrame(
parent_model = model,
trajectory = trajectory,
mds = depth_values,
represented_interp = well_interp,
)
well_frame.write_hdf5()
well_frame.create_xml()
# Create a WellLogCollection in which to put logs
collection = rqp.WellLogCollection(frame = well_frame, realization = realization)
# Read in data from each curve in turn (skipping first curve which has depths)
for curve in las.curves[1:]:
collection.add_log(
title = curve.mnemonic,
data = curve.data,
unit = curve.unit,
realization = realization,
write = False,
)
collection.write_hdf5_for_imported_list()
collection.create_xml_for_imported_list_and_add_parts_to_model()
return collection, well_frame
def add_logs_from_cellio(blockedwell, cellio):
"""Creates a WellIntervalPropertyCollection for a given BlockedWell, using a given cell I/O file.
Arguments:
blockedwell: a resqml blockedwell object
cellio: an ascii file exported from RMS containing blocked well geometry and logs. Must contain columns i_index, j_index and k_index, plus additional columns for logs to be imported.
"""
# Get the initial variables from the blocked well
assert isinstance(blockedwell, BlockedWell), 'Not a blocked wellbore object'
collection = rqp.WellIntervalPropertyCollection(frame = blockedwell)
well_name = blockedwell.trajectory.title.split(" ")[0]
grid = blockedwell.model.grid()
# Read the cell I/O file to get the available columns (cols) and the data (data), and write into a dataframe
with open(cellio, 'r') as fp:
wellfound = False
cols, data = [], []
for line in fp.readlines():
if line == "\n":
wellfound = False # Blankline signifies end of well data
words = line.split()
if wellfound:
if len(words) > 2 and not words[0].isdigit():
cols.append(line)
else:
if len(words) > 9:
assert len(cols) == len(words), 'Number of columns found should match header of file'
data.append(words)
if len(words) == 3:
if words[0].upper() == well_name.upper():
wellfound = True
assert len(data) > 0 and len(cols) > 3, f"No data for well {well_name} found in file"
df = pd.DataFrame(data = data, columns = [x.split()[0] for x in cols])
df = df.apply(pd.to_numeric)
# Get the cell_indices from the grid for the given i/j/k
df['cell_indices'] = grid.natural_cell_indices(
np.array((df['k_index'] - 1, df['j_index'] - 1, df['i_index'] - 1), dtype = int).T)
df = df.drop(['i_index', 'j_index', 'k_index', 'x_in', 'y_in', 'z_in', 'x_out', 'y_out', 'z_out'], axis = 1)
assert (df['cell_indices'] == blockedwell.cell_indices
).all(), 'Cell indices do not match between blocked well and log inputs'
# Work out if the data columns are continuous, categorical or discrete
type_dict = {}
lookup_dict = {}
for col in cols:
words = col.split()
if words[0] not in ['i_index', 'j_index', 'k_index', 'x_in', 'y_in', 'z_in', 'x_out', 'y_out', 'z_out']:
if words[1] == 'unit1':
type_dict[words[0]] = 'continuous'
elif words[1] == 'DISC' and not words[0] == 'ZONES':
type_dict[words[0]] = 'categorical'
lookup_dict[words[0]] = lookup_from_cellio(col, blockedwell.model)
elif words[1] == 'param' or words[0] == 'ZONES':
type_dict[words[0]] = 'discrete'
else:
raise TypeError(f'unrecognised data type for {col}')
# Loop over the columns, adding them to the blockedwell property collection
for log in df.columns:
if log not in ['cell_indices']:
data_type = type_dict[log]
if log == 'ZONES':
data_type, dtype, null, discrete = 'discrete', int, -1, True
elif data_type == 'continuous':
dtype, null, discrete = float, np.nan, False
else:
dtype, null, discrete = int, -1, True
if data_type == 'categorical':
lookup_uuid = lookup_dict[log] # For categorical data, find or generate a StringLookupTable
else:
lookup_uuid = None
array_list = np.zeros((np.shape(blockedwell.grid_indices)), dtype = dtype)
vals = list(df[log])
for i, index in enumerate(blockedwell.cell_grid_link):
if index == -1:
assert blockedwell.grid_indices[i] == -1
array_list[i] = null
else:
if blockedwell.cell_indices[index] == list(df['cell_indices'])[index]:
array_list[i] = vals[index]
collection.add_cached_array_to_imported_list(
cached_array = array_list,
source_info = '',
keyword = f"{os.path.basename(cellio).split(".")[0]}.{blockedwell.trajectory.title}.{log}",
discrete = discrete,
uom = None,
property_kind = None,
facet = None,
null_value = null,
facet_type = None,
realization = None)
collection.write_hdf5_for_imported_list()
collection.create_xml_for_imported_list_and_add_parts_to_model(string_lookup_uuid = lookup_uuid)
def lookup_from_cellio(line, model):
"""Create a StringLookup Object from a cell I/O row containing a categorical column name and details.
Arguments:
line: a string from a cell I/O file, containing the column (log) name, type and categorical information
model: the model to add the StringTableLookup to
Returns:
uuid: the uuid of a StringTableLookup, either for a newly created table, or for an existing table if an identical one exists
"""
lookup_dict = {}
value, string = None, None
# Generate a dictionary of values and strings
for i, word in enumerate(line.split()):
if i == 0:
title = word
elif not i < 2:
if value is not None and string is not None:
lookup_dict[value] = string
value, string = None, None
if value is None:
value = int(word)
else:
if i == len(line.split()) - 1:
lookup_dict[value] = word
else:
string = word
# Check if a StringLookupTable already exists in the model, with the same name and values
for existing in model.parts_list_of_type('obj_StringTableLookup'):
table = rqp.StringLookup(parent_model = model, root_node = model.root_for_part(existing))
if table.title == title:
if table.str_dict == lookup_dict:
return table.uuid # If the exact table exists, reuse it by returning the uuid
# If no matching StringLookupTable exists, make a new one and return the uuid
lookup = rqp.StringLookup(parent_model = model, int_to_str_dict = lookup_dict, title = title)
lookup.create_xml(add_as_part = True)
return lookup.uuid
def add_wells_from_ascii_file(model,
crs_uuid,
trajectory_file,
comment_character = '#',
space_separated_instead_of_csv = False,
well_col = 'WELL',
md_col = 'MD',
x_col = 'X',
y_col = 'Y',
z_col = 'Z',
length_uom = 'm',
md_domain = None,
drilled = False):
"""Creates new md datum, trajectory, interpretation and feature objects for each well in an ascii file.
arguments:
crs_uuid (uuid.UUID): the unique identifier of the coordinate reference system applicable to the x,y,z data;
if None, a default crs will be created, making use of the length_uom and z_inc_down arguments
trajectory_file (string): the path of the ascii file holding the well trajectory data to be loaded
comment_character (string, default '#'): character deemed to introduce a comment in the trajectory file
space_separated_instead_of_csv (boolean, default False): if True, the columns in the trajectory file are space
separated; if False, comma separated
well_col (string, default 'WELL'): the heading for the column containing well names
md_col (string, default 'MD'): the heading for the column containing measured depths
x_col (string, default 'X'): the heading for the column containing X (usually easting) data
y_col (string, default 'Y'): the heading for the column containing Y (usually northing) data
z_col (string, default 'Z'): the heading for the column containing Z (depth or elevation) data
length_uom (string, default 'm'): the units of measure for the measured depths; should be 'm' or 'ft'
md_domain (string, optional): the source of the original deviation data; may be 'logger' or 'driller'
drilled (boolean, default False): True should be used for wells that have been drilled; False otherwise (planned,
proposed, or a location being studied)
z_inc_down (boolean, default True): indicates whether z values increase with depth; only used in the creation
of a default coordinate reference system; ignored if crs_uuid is not None
returns:
tuple of lists of objects: (feature_list, interpretation_list, trajectory_list, md_datum_list),
notes:
ascii file must be table with first line being column headers, with columns for WELL, MD, X, Y & Z;
actual column names can be set with optional arguments;
all the objects are added to the model, with array data being written to the hdf5 file for the trajectories;
the md_domain and drilled values are stored in the RESQML metadata but are only for human information and do not
generally affect computations
"""
assert md_col and x_col and y_col and z_col
md_col = str(md_col)
x_col = str(x_col)
y_col = str(y_col)
z_col = str(z_col)
if crs_uuid is None:
crs_uuid = model.crs_uuid
assert crs_uuid is not None, 'coordinate reference system not found when trying to add wells'
try:
df = pd.read_csv(trajectory_file,
comment = comment_character,
delim_whitespace = space_separated_instead_of_csv)
if df is None:
raise Exception
except Exception:
log.error('failed to read ascii deviation survey file: ' + str(trajectory_file))
raise
if well_col and well_col not in df.columns:
log.warning('well column ' + str(well_col) + ' not found in ascii trajectory file: ' + str(trajectory_file))
well_col = None
if well_col is None:
for col in df.columns:
if str(col).upper().startswith('WELL'):
well_col = str(col)
break
else:
well_col = str(well_col)
assert well_col
unique_wells = set(df[well_col])
if len(unique_wells) == 0:
log.warning('no well data found in ascii trajectory file: ' + str(trajectory_file))
# note: empty lists will be returned, below
feature_list = []
interpretation_list = []
trajectory_list = []
md_datum_list = []
for well_name in unique_wells:
log.debug('importing well: ' + str(well_name))
# create single well data frame (assumes measured depths increasing)
well_df = df[df[well_col] == well_name]
# create a measured depth datum for the well and add as part
first_row = well_df.iloc[0]
if first_row[md_col] == 0.0:
md_datum = MdDatum(model,
crs_uuid = crs_uuid,
location = (first_row[x_col], first_row[y_col], first_row[z_col]))
else:
md_datum = MdDatum(model, crs_uuid = crs_uuid,
location = (first_row[x_col], first_row[y_col], 0.0)) # sea level datum
md_datum.create_xml(title = str(well_name))
md_datum_list.append(md_datum)
# create a well feature and add as part
feature = rqo.WellboreFeature(model, feature_name = well_name)
feature.create_xml()
feature_list.append(feature)
# create interpretation and add as part
interpretation = rqo.WellboreInterpretation(model, is_drilled = drilled, wellbore_feature = feature)
interpretation.create_xml(title_suffix = None)
interpretation_list.append(interpretation)
# create trajectory, write arrays to hdf5 and add as part
trajectory = Trajectory(model,
md_datum = md_datum,
data_frame = well_df,
length_uom = length_uom,
md_domain = md_domain,
represented_interp = interpretation,
well_name = well_name)
trajectory.write_hdf5()
trajectory.create_xml(title = well_name)
trajectory_list.append(trajectory)
return (feature_list, interpretation_list, trajectory_list, md_datum_list)
def well_name(well_object, model = None):
"""Returns the 'best' citation title from the object or related well objects.
arguments:
well_object (object, uuid or root): Object for which a well name is required. Can be a
Trajectory, WellboreInterpretation, WellboreFeature, BlockedWell, WellboreMarkerFrame,
WellboreFrame, DeviationSurvey or MdDatum object
model (model.Model, optional): required if passing a uuid or root; not recommended otherwise
returns:
string being the 'best' citation title to serve as a well name, form the object or some related objects
note:
xml and relationships must be established for this function to work
"""
def better_root(model, root_a, root_b):
a = rqet.citation_title_for_node(root_a)
b = rqet.citation_title_for_node(root_b)
if a is None or len(a) == 0:
return root_b
if b is None or len(b) == 0:
return root_a
parts_like_a = model.parts(title = a)
parts_like_b = model.parts(title = b)
if len(parts_like_a) > 1 and len(parts_like_b) == 1:
return root_b
elif len(parts_like_b) > 1 and len(parts_like_a) == 1:
return root_a
a_digits = 0
for c in a:
if c.isdigit():
a_digits += 1
b_digits = 0
for c in b:
if c.isdigit():
b_digits += 1
if a_digits < b_digits:
return root_b
return root_a
def best_root(model, roots_list):
if len(roots_list) == 0:
return None
if len(roots_list) == 1:
return roots_list[0]
if len(roots_list) == 2:
return better_root(model, roots_list[0], roots_list[1])
return better_root(model, roots_list[0], best_root(model, roots_list[1:]))
def best_root_for_object(well_object, model = None):
if well_object is None:
return None
if model is None:
model = well_object.model
root_list = []
obj_root = None
obj_uuid = None
obj_type = None
traj_root = None
if isinstance(well_object, str):
obj_uuid = bu.uuid_from_string(well_object)
assert obj_uuid is not None, 'well_name string argument could not be interpreted as uuid'
well_object = obj_uuid
if isinstance(well_object, bu.uuid.UUID):
obj_uuid = well_object
obj_root = model.root_for_uuid(obj_uuid)
assert obj_root is not None, 'uuid not found in model when looking for well name'
obj_type = rqet.node_type(obj_root)
elif rqet.is_node(well_object):
obj_root = well_object
obj_type = rqet.node_type(obj_root)
obj_uuid = rqet.uuid_for_part_root(obj_root)
elif isinstance(well_object, Trajectory):
obj_type = 'WellboreTrajectoryRepresentation'
traj_root = well_object.root
elif isinstance(well_object, rqo.WellboreFeature):
obj_type = 'WellboreFeature'
elif isinstance(well_object, rqo.WellboreInterpretation):
obj_type = 'WellboreInterpretation'
elif isinstance(well_object, BlockedWell):
obj_type = 'BlockedWellboreRepresentation'
if well_object.trajectory is not None:
traj_root = well_object.trajectory.root
elif isinstance(well_object, WellboreMarkerFrame): # note: trajectory might be None
obj_type = 'WellboreMarkerFrameRepresentation'
if well_object.trajectory is not None:
traj_root = well_object.trajectory.root
elif isinstance(well_object, WellboreFrame): # note: trajectory might be None
obj_type = 'WellboreFrameRepresentation'
if well_object.trajectory is not None:
traj_root = well_object.trajectory.root
elif isinstance(well_object, DeviationSurvey):
obj_type = 'DeviationSurveyRepresentation'
elif isinstance(well_object, MdDatum):
obj_type = 'MdDatum'
assert obj_type is not None, 'argument type not recognized for well_name'
if obj_type.startswith('obj_'):
obj_type = obj_type[4:]
if obj_uuid is None:
obj_uuid = well_object.uuid
obj_root = model.root_for_uuid(obj_uuid)
if obj_type == 'WellboreFeature':
interp_parts = model.parts(obj_type = 'WellboreInterpretation')
interp_parts = model.parts_list_filtered_by_related_uuid(interp_parts, obj_uuid)
all_parts = interp_parts
all_traj_parts = model.parts(obj_type = 'WellboreTrajectoryRepresentation')
if interp_parts is not None:
for part in interp_parts:
traj_parts = model.parts_list_filtered_by_related_uuid(all_traj_parts, model.uuid_for_part(part))
all_parts += traj_parts
if all_parts is not None:
root_list = [model.root_for_part(part) for part in all_parts]
elif obj_type == 'WellboreInterpretation':
feat_roots = model.roots(obj_type = 'WellboreFeature', related_uuid = obj_uuid) # should return one root
traj_roots = model.roots(obj_type = 'WellboreTrajectoryRepresentation', related_uuid = obj_uuid)
root_list = feat_roots + traj_roots
elif obj_type == 'WellboreTrajectoryRepresentation':
interp_parts = model.parts(obj_type = 'WellboreInterpretation')
interp_parts = model.parts_list_filtered_by_related_uuid(interp_parts, obj_uuid)
all_parts = interp_parts
all_feat_parts = model.parts(obj_type = 'WellboreFeature')
if interp_parts is not None:
for part in interp_parts:
feat_parts = model.parts_list_filtered_by_related_uuid(all_feat_parts, model.uuid_for_part(part))
all_parts += feat_parts
if all_parts is not None:
root_list = [model.root_for_part(part) for part in all_parts]
elif obj_type in [
'BlockedWellboreRepresentation', 'WellboreMarkerFrameRepresentation', 'WellboreFrameRepresentation'
]:
if traj_root is None:
traj_root = model.root(obj_type = 'WellboreTrajectoryRepresentation', related_uuid = obj_uuid)
root_list = [best_root_for_object(traj_root, model = model)]
elif obj_type == 'DeviationSurveyRepresentation':
root_list = [best_root_for_object(model.root(obj_type = 'MdDatum', related_uuid = obj_uuid), model = model)]
elif obj_type == 'MdDatum':
pass
root_list.append(obj_root)
return best_root(model, root_list)
return rqet.citation_title_for_node(best_root_for_object(well_object, model = model))
def add_blocked_wells_from_wellspec(model, grid, wellspec_file):
"""Add a blocked well for each well in a Nexus WELLSPEC file.
arguments:
model (model.Model object): model to which blocked wells are added
grid (grid.Grid object): grid against which wellspec data will be interpreted
wellspec_file (string): path of ascii file holding Nexus WELLSPEC keyword and data
returns:
int: count of number of blocked wells created
notes:
this function appends to the hdf5 file and creates xml for the blocked wells (but does not store epc);
'simulation' trajectory and measured depth datum objects will also be created
"""
well_list_dict = wsk.load_wellspecs(wellspec_file, column_list = None)
count = 0
for well in well_list_dict:
log.info('processing well: ' + str(well))
bw = BlockedWell(model,
grid = grid,
wellspec_file = wellspec_file,
well_name = well,
check_grid_name = True,
use_face_centres = True)
if not bw.node_count: # failed to load from wellspec, eg. because of no perforations in grid
log.warning('no wellspec data loaded for well: ' + str(well))
continue
bw.write_hdf5(model.h5_file_name(), mode = 'a', create_for_trajectory_if_needed = True)
bw.create_xml(model.h5_uuid(), title = well)
count += 1
log.info(f'{count} blocked wells created based on wellspec file: {wellspec_file}')
def extract_xyz(xyz_node):
"""Extracts an x,y,z coordinate from a solitary point xml node.
argument:
xyz_node: the xml node representing the solitary point (in 3D space)
returns:
triple float: (x, y, z) coordinates as a tuple
"""
if xyz_node is None:
return None
xyz = np.zeros(3)
for axis in range(3):
xyz[axis] = rqet.find_tag_float(xyz_node, 'Coordinate' + str(axis + 1), must_exist = True)
return tuple(xyz)
def well_names_in_cellio_file(cellio_file):
"""Returns a list of well names as found in the RMS blocked well export cell I/O file."""
well_list = []
with open(cellio_file, 'r') as fp:
while True:
kf.skip_blank_lines_and_comments(fp)
line = fp.readline() # file format version number?
if line == '':
break # end of file
fp.readline() # 'Undefined'
words = fp.readline().split()
assert len(words), 'missing header info (well name) in cell I/O file'
well_list.append(words[0])
while not kf.blank_line(fp):
fp.readline() # skip to block of data for next well
return well_list
# 'private' functions
def load_hdf5_array(object, node, array_attribute, tag = 'Values', dtype = 'float', model = None):
"""Loads the property array data as an attribute of object, from the hdf5 referenced in xml node.
:meta private:
"""
assert (rqet.node_type(node) in ['DoubleHdf5Array', 'IntegerHdf5Array', 'Point3dHdf5Array'])
if model is None:
model = object.model
h5_key_pair = model.h5_uuid_and_path_for_node(node, tag = tag)
if h5_key_pair is None:
return None
return model.h5_array_element(h5_key_pair,
index = None,
cache_array = True,
dtype = dtype,
object = object,
array_attribute = array_attribute)
def find_entry_and_exit(cp, entry_vector, exit_vector, well_name):
"""Returns (entry_axis, entry_polarity, entry_xyz, exit_axis, exit_polarity, exit_xyz).
:meta private:
"""
cell_centre = np.mean(cp, axis = (0, 1, 2))
face_triangles = gf.triangles_for_cell_faces(cp).reshape(-1, 3, 3) # flattened first index 4 values per face
entry_points = intersect.line_triangles_intersects(cell_centre, entry_vector, face_triangles, line_segment = True)
entry_axis = entry_polarity = entry_xyz = exit_xyz = None
for t in range(24):
if not np.any(np.isnan(entry_points[t])):
entry_xyz = entry_points[t]
entry_axis = t // 8
entry_polarity = (t - 8 * entry_axis) // 4
break
assert entry_axis is not None, 'failed to find entry face for a perforation in well ' + str(well_name)
exit_points = intersect.line_triangles_intersects(cell_centre, exit_vector, face_triangles, line_segment = True)
exit_axis = exit_polarity = None
for t in range(24):
if not np.any(np.isnan(exit_points[t])):
exit_xyz = entry_points[t]
exit_axis = t // 8
exit_polarity = (t - 8 * exit_axis) // 4
break
assert exit_axis is not None, 'failed to find exit face for a perforation in well ' + str(well_name)
return (entry_axis, entry_polarity, entry_xyz, exit_axis, exit_polarity, exit_xyz)
def _as_optional_array(arr):
"""If not None, cast as numpy array.
Casting directly to an array can be problematic: np.array(None) creates an unsized array, which is potentially
confusing.
"""
if arr is None:
return None
else:
return np.array(arr)
def _pl(i, e = False):
return '' if i == 1 else 'es' if e else 's'
| """well.py: resqpy well module providing trajectory, deviation survey, blocked well, wellbore frame and marker frame and md datum classes.
Example::
# Wellbore interpretations
for well in model.iter_wellbore_interpretations():
print(well.title)
for trajectory in well.iter_trajectories():
print(trajectory.title)
for frame in trajectory.iter_wellbore_frames():
print(frame.title)
# Measured depths
mds = frame.node_mds
# Logs
log_collection = frame.logs
for log in log_collection:
values = log.values()
"""
# todo: create a trajectory from a deviation survey, assuming minimum curvature
version = '20th October 2021'
# Nexus is a registered trademark of the Halliburton Company
# RMS and ROXAR are registered trademarks of Roxar Software Solutions AS, an Emerson company
import logging
log = logging.getLogger(__name__)
log.debug('well.py version ' + version)
import math as maths
import os
import warnings
import lasio
import numpy as np
import pandas as pd
import resqpy.crs as crs
import resqpy.lines as rql
import resqpy.olio.grid_functions as gf
import resqpy.olio.intersection as intersect
import resqpy.olio.keyword_files as kf
import resqpy.olio.uuid as bu
import resqpy.olio.vector_utilities as vec
import resqpy.olio.wellspec_keywords as wsk
import resqpy.olio.write_hdf5 as rwh5
import resqpy.olio.xml_et as rqet
import resqpy.organize as rqo
import resqpy.property as rqp
import resqpy.weights_and_measures as bwam
from resqpy.olio.base import BaseResqpy
from resqpy.olio.xml_namespaces import curly_namespace as ns
valid_md_reference_list = [
"ground level", "kelly bushing", "mean sea level", "derrick floor", "casing flange", "arbitrary point",
"crown valve", "rotary bushing", "rotary table", "sea floor", "lowest astronomical tide", "mean higher high water",
"mean high water", "mean lower low water", "mean low water", "mean tide level", "kickoff point"
]
# todo: could require/maintain DeviationSurvey mds in same units as md datum object's crs vertical units?
class MdDatum(BaseResqpy):
"""Class for RESQML measured depth datum."""
resqml_type = 'MdDatum'
def __init__(
self,
parent_model,
uuid = None,
md_datum_root = None,
crs_uuid = None,
crs_root = None, # deprecated
location = None,
md_reference = 'mean sea level',
title = None,
originator = None,
extra_metadata = None):
"""Initialises a new MdDatum object.
arguments:
parent_model (model.Model object): the model which the new md datum belongs to
uuid: If not None, load from existing object. Else, create new.
md_datum_root (optional): DEPRECATED: the root node of the xml tree representing the md datum;
if not None, the new md datum object is initialised based on data in the tree;
if None, the new object is initialised from the remaining arguments
crs_uuid (uuid.UUID): required if initialising from values
crs_root: DEPRECATED, use crs_uuid instead; the root node of the coordinate reference system
xml tree; ignored if uuid or md_datum_root is not None or crs_uuid is not None
location: (triple float): the x, y, z location of the new measured depth datum;
ignored if uuid or md_datum_root is not None
md_reference (string): human readable resqml standard string indicating the real
world nature of the datum, eg. 'kelly bushing'; the full list of options is
available as the global variable valid_md_reference_list in this module;
ignored if uuid or md_datum_root is not None
title (str, optional): the citation title to use for a new datum;
ignored if uuid or md_datum_root is not None
originator (str, optional): the name of the person creating the datum, defaults to login id;
ignored if uuid or md_datum_root is not None
extra_metadata (dict, optional): string key, value pairs to add as extra metadata for the datum;
ignored if uuid or md_datum_root is not None
returns:
the newly instantiated measured depth datum object
note:
this function does not create an xml node for the md datum; call the create_xml() method afterwards
if initialising from data other than an existing RESQML object
"""
if crs_root is not None:
warnings.warn("Attribute 'crs_root' is deprecated. Use 'crs_uuid'", DeprecationWarning)
# TODO: remove crs_root argument
self.location = location
self.md_reference = md_reference
self.crs_uuid = crs_uuid
super().__init__(model = parent_model,
uuid = uuid,
title = title,
originator = originator,
extra_metadata = extra_metadata,
root_node = md_datum_root)
# temporary code to sort out crs reference, till crs_root arg is retired
if self.crs_uuid is None and crs_root is not None:
self.crs_uuid = rqet.uuid_for_part_root(crs_root)
assert self.crs_uuid is not None
if self.root is None and (location is not None or md_reference):
assert location is not None and md_reference
assert md_reference in valid_md_reference_list
assert len(location) == 3
def _load_from_xml(self):
md_datum_root = self.root
assert md_datum_root is not None
location_node = rqet.find_tag(md_datum_root, 'Location')
self.location = (rqet.find_tag_float(location_node,
'Coordinate1'), rqet.find_tag_float(location_node, 'Coordinate2'),
rqet.find_tag_float(location_node, 'Coordinate3'))
self.md_reference = rqet.node_text(rqet.find_tag(md_datum_root, 'MdReference')).strip().lower()
assert self.md_reference in valid_md_reference_list
self.crs_uuid = self.extract_crs_uuid()
@property
def crs_root(self):
"""XML node corresponding to self.crs_uuid."""
return self.model.root_for_uuid(self.crs_uuid)
# todo: the following function is almost identical to one in the grid module: it should be made common and put in model.py
def extract_crs_uuid(self):
"""Returns uuid for coordinate reference system, as stored in reference node of this md datum's xml tree."""
if self.crs_uuid is not None:
return self.crs_uuid
crs_root = rqet.find_tag(self.root, 'LocalCrs')
uuid_str = rqet.find_tag(crs_root, 'UUID').text
self.crs_uuid = bu.uuid_from_string(uuid_str)
return self.crs_uuid
def extract_crs_root(self):
"""Returns root in parent model xml parts forest of coordinate reference system used by this md datum."""
if self.crs_uuid is None:
self.extract_crs_uuid()
return self.crs_root
def create_part(self):
"""Creates xml for this md datum object and adds to parent model as a part; returns root node for part."""
# note: deprecated, call create_xml() directly
assert self.root is None
assert self.location is not None
self.create_xml(add_as_part = True)
def create_xml(self, add_as_part = True, add_relationships = True, title = None, originator = None):
"""Creates xml for a measured depth datum element; crs node must already exist; optionally adds as part.
arguments:
add_as_part (boolean, default True): if True, the newly created xml node is added as a part
in the model
add_relationships (boolean, default True): if True, a relationship xml part is created relating the
new md datum part to the crs
title (string): used as the citation Title text for the new md datum node
originator (string, optional): the name of the human being who created the md datum part;
default is to use the login name
returns:
the newly created measured depth datum xml node
"""
md_reference = self.md_reference.lower()
assert md_reference in valid_md_reference_list, 'invalid measured depth reference: ' + md_reference
if title:
self.title = title
if not self.title:
self.title = 'measured depth datum'
crs_uuid = self.crs_uuid
assert crs_uuid is not None
datum = super().create_xml(add_as_part = False, originator = originator)
self.model.create_solitary_point3d('Location', datum, self.location)
md_ref = rqet.SubElement(datum, ns['resqml2'] + 'MdReference')
md_ref.set(ns['xsi'] + 'type', ns['resqml2'] + 'MdReference')
md_ref.text = md_reference
self.model.create_crs_reference(crs_uuid = crs_uuid, root = datum)
if add_as_part:
self.model.add_part('obj_MdDatum', self.uuid, datum)
if add_relationships:
self.model.create_reciprocal_relationship(datum, 'destinationObject', self.crs_root, 'sourceObject')
return datum
def is_equivalent(self, other):
"""Implements equals operator, comparing metadata items deemed significant."""
if not isinstance(other, self.__class__):
return False
if self.md_reference != other.md_reference or not np.allclose(self.location, other.location):
return False
return bu.matching_uuids(self.crs_uuid, other.crs_uuid)
class DeviationSurvey(BaseResqpy):
"""Class for RESQML wellbore deviation survey.
RESQML documentation:
Specifies the station data from a deviation survey.
The deviation survey does not provide a complete specification of the
geometry of a wellbore trajectory. Although a minimum-curvature
algorithm is used in most cases, the implementation varies sufficiently
that no single algorithmic specification is available as a data transfer
standard.
Instead, the geometry of a RESQML wellbore trajectory is represented by
a parametric line, parameterized by the MD.
CRS and units of measure do not need to be consistent with the CRS and
units of measure for wellbore trajectory representation.
"""
resqml_type = 'DeviationSurveyRepresentation'
def __init__(self,
parent_model,
uuid = None,
title = None,
deviation_survey_root = None,
represented_interp = None,
md_datum = None,
md_uom = 'm',
angle_uom = 'dega',
measured_depths = None,
azimuths = None,
inclinations = None,
station_count = None,
first_station = None,
is_final = False,
originator = None,
extra_metadata = None):
"""Load or create a DeviationSurvey object.
If uuid is given, loads from XML. Else, create new. If loading from disk, other
parameters will be overwritten.
Args:
parent_model (model.Model): the model which the new survey belongs to
uuid (uuid.UUID): If given, loads from disk. Else, creates new.
title (str): Citation title
deviation_survey_root: DEPCRECATED. If given, load from disk.
represented_interp (wellbore interpretation): if present, is noted as the wellbore
interpretation object which this deviation survey relates to
md_datum (MdDatum): the datum that the depths for this survey are measured from
md_uom (string, default 'm'): a resqml length unit of measure applicable to the
measured depths; should be 'm' or 'ft'
angle_uom (string): a resqml angle unit; should be 'dega' or 'rad'
measured_depths (np.array): 1d array
azimuths (np.array): 1d array
inclindations (np.array): 1d array
station_count (int): length of measured_depths, azimuths & inclinations
first_station (tuple): (x, y, z) of first point in survey, in crs for md datum
is_final (bool): whether survey is a finalised deviation survey
originator (str): name of author
extra_metadata (dict, optional): extra metadata key, value pairs
Returns:
DeviationSurvey
Notes:
this method does not create an xml node, nor write hdf5 arrays
"""
self.is_final = is_final
self.md_uom = bwam.rq_length_unit(md_uom)
self.angles_in_degrees = angle_uom.strip().lower().startswith('deg')
"""boolean: True for degrees, False for radians (nothing else supported). Should be 'dega' or 'rad'"""
# Array data
self.measured_depths = _as_optional_array(measured_depths)
self.azimuths = _as_optional_array(azimuths)
self.inclinations = _as_optional_array(inclinations)
if station_count is None and measured_depths is not None:
station_count = len(measured_depths)
self.station_count = station_count
self.first_station = first_station
# Referenced objects
self.md_datum = md_datum # md datum is an object in its own right, with a related crs!
self.wellbore_interpretation = represented_interp
# TODO: remove deviation_survey_root, use just uuid
super().__init__(model = parent_model,
uuid = uuid,
title = title,
originator = originator,
extra_metadata = extra_metadata,
root_node = deviation_survey_root)
@classmethod
def from_data_frame(cls,
parent_model,
data_frame,
md_datum = None,
md_col = 'MD',
azimuth_col = 'AZIM_GN',
inclination_col = 'INCL',
x_col = 'X',
y_col = 'Y',
z_col = 'Z',
md_uom = 'm',
angle_uom = 'dega'):
"""Load MD, aximuth & inclination data from a pandas data frame.
Args:
parent_model (model.Model): the parent resqml model
data_frame: a pandas dataframe holding the deviation survey data
md_datum (MdDatum object): the datum that the depths for this survey are measured from
md_col (string, default 'MD'): the name of the column holding measured depth values
azimuth_col (string, default 'AZIM_GN'): the name of the column holding azimuth values relative
to the north direction (+ve y axis) of the coordinate reference system
inclination_col (string, default 'INCL'): the name of the column holding inclination values
x_col (string, default 'X'): the name of the column holding an x value in the first row
y_col (string, default 'Y'): the name of the column holding an Y value in the first row
z_col (string, default 'Z'): the name of the column holding an z value in the first row
md_uom (string, default 'm'): a resqml length unit of measure applicable to the
measured depths; should be 'm' or 'ft'
angle_uom (string, default 'dega'): a resqml angle unit of measure applicable to both
the azimuth and inclination data
Returns:
DeviationSurvey
Note:
The X, Y & Z columns are only used to set the first station location (from the first row)
"""
for col in [md_col, azimuth_col, inclination_col, x_col, y_col, z_col]:
assert col in data_frame.columns
station_count = len(data_frame)
assert station_count >= 2 # vertical well could be hamdled by allowing a single station in survey?
# self.md_uom = bwam.p_length_unit(md_uom)
start = data_frame.iloc[0]
return cls(parent_model = parent_model,
station_count = station_count,
md_datum = md_datum,
md_uom = md_uom,
angle_uom = angle_uom,
first_station = (start[x_col], start[y_col], start[z_col]),
measured_depths = data_frame[md_col].values,
azimuths = data_frame[azimuth_col].values,
inclinations = data_frame[inclination_col].values,
is_final = True) # assume this is a finalised deviation survey
@classmethod
def from_ascii_file(cls,
parent_model,
deviation_survey_file,
comment_character = '#',
space_separated_instead_of_csv = False,
md_col = 'MD',
azimuth_col = 'AZIM_GN',
inclination_col = 'INCL',
x_col = 'X',
y_col = 'Y',
z_col = 'Z',
md_uom = 'm',
angle_uom = 'dega',
md_datum = None):
"""Load MD, aximuth & inclination data from an ascii deviation survey file.
Arguments:
parent_model (model.Model): the parent resqml model
deviation_survey_file (string): the filename of an ascii file holding the deviation survey data
comment_character (string): the character to be treated as introducing comments
space_separated_instead_of_csv (boolea, default False): if False, csv format expected;
if True, columns are expected to be seperated by white space
md_col (string, default 'MD'): the name of the column holding measured depth values
azimuth_col (string, default 'AZIM_GN'): the name of the column holding azimuth values relative
to the north direction (+ve y axis) of the coordinate reference system
inclination_col (string, default 'INCL'): the name of the column holding inclination values
x_col (string, default 'X'): the name of the column holding an x value in the first row
y_col (string, default 'Y'): the name of the column holding an Y value in the first row
z_col (string, default 'Z'): the name of the column holding an z value in the first row
md_uom (string, default 'm'): a resqml length unit of measure applicable to the
measured depths; should be 'm' or 'ft'
angle_uom (string, default 'dega'): a resqml angle unit of measure applicable to both
the azimuth and inclination data
md_datum (MdDatum object): the datum that the depths for this survey are measured from
Returns:
DeviationSurvey
Note:
The X, Y & Z columns are only used to set the first station location (from the first row)
"""
try:
df = pd.read_csv(deviation_survey_file,
comment = comment_character,
delim_whitespace = space_separated_instead_of_csv)
if df is None:
raise Exception
except Exception:
log.error('failed to read ascii deviation survey file ' + deviation_survey_file)
raise
return cls.from_data_frame(parent_model,
df,
md_col = md_col,
azimuth_col = azimuth_col,
inclination_col = inclination_col,
x_col = x_col,
y_col = y_col,
z_col = z_col,
md_uom = md_uom,
angle_uom = angle_uom,
md_datum = md_datum)
def _load_from_xml(self):
"""Load attributes from xml and associated hdf5 data.
This is invoked as part of the init method when an existing uuid is given.
Returns:
[bool]: True if sucessful
"""
# Get node from self.uuid
node = self.root
assert node is not None
# Load XML data
self.md_uom = rqet.length_units_from_node(rqet.find_tag(node, 'MdUom', must_exist = True))
self.angle_uom = rqet.find_tag_text(node, 'AngleUom', must_exist = True)
self.station_count = rqet.find_tag_int(node, 'StationCount', must_exist = True)
self.first_station = extract_xyz(rqet.find_tag(node, 'FirstStationLocation', must_exist = True))
self.is_final = rqet.find_tag_bool(node, 'IsFinal')
# Load HDF5 data
mds_node = rqet.find_tag(node, 'Mds', must_exist = True)
load_hdf5_array(self, mds_node, 'measured_depths')
azimuths_node = rqet.find_tag(node, 'Azimuths', must_exist = True)
load_hdf5_array(self, azimuths_node, 'azimuths')
inclinations_node = rqet.find_tag(node, 'Inclinations', must_exist = True)
load_hdf5_array(self, inclinations_node, 'inclinations')
# Set related objects
self.md_datum = self._load_related_datum()
self.represented_interp = self._load_related_wellbore_interp()
# Validate
assert self.measured_depths is not None
assert len(self.measured_depths) > 0
return True
def create_xml(self,
ext_uuid = None,
md_datum_root = None,
md_datum_xyz = None,
add_as_part = True,
add_relationships = True,
title = None,
originator = None):
"""Creates a deviation survey representation xml element from this DeviationSurvey object.
arguments:
ext_uuid (uuid.UUID): the uuid of the hdf5 external part holding the deviation survey arrays
md_datum_root: the root xml node for the measured depth datum that the deviation survey depths
are based on
md_datum_xyz: TODO: document this
add_as_part (boolean, default True): if True, the newly created xml node is added as a part
in the model
add_relationships (boolean, default True): if True, a relationship xml part is created relating the
new deviation survey part to the measured depth datum part
title (string): used as the citation Title text; should usually refer to the well name in a
human readable way
originator (string, optional): the name of the human being who created the deviation survey part;
default is to use the login name
returns:
the newly created deviation survey xml node
"""
assert self.station_count > 0
if ext_uuid is None:
ext_uuid = self.model.h5_uuid()
if md_datum_root is None:
if self.md_datum is None:
if md_datum_xyz is None:
raise ValueError("Must provide a MD Datum for the DeviationSurvey")
self.md_datum = MdDatum(self.model, location = md_datum_xyz)
if self.md_datum.root is None:
md_datum_root = self.md_datum.create_xml()
else:
md_datum_root = self.md_datum.root
assert md_datum_root is not None
# Create root node, write citation block
ds_node = super().create_xml(title = title, originator = originator, add_as_part = False)
if_node = rqet.SubElement(ds_node, ns['resqml2'] + 'IsFinal')
if_node.set(ns['xsi'] + 'type', ns['xsd'] + 'boolean')
if_node.text = str(self.is_final).lower()
sc_node = rqet.SubElement(ds_node, ns['resqml2'] + 'StationCount')
sc_node.set(ns['xsi'] + 'type', ns['xsd'] + 'positiveInteger')
sc_node.text = str(self.station_count)
md_uom = rqet.SubElement(ds_node, ns['resqml2'] + 'MdUom')
md_uom.set(ns['xsi'] + 'type', ns['eml'] + 'LengthUom')
md_uom.text = bwam.rq_length_unit(self.md_uom)
self.model.create_md_datum_reference(md_datum_root, root = ds_node)
self.model.create_solitary_point3d('FirstStationLocation', ds_node, self.first_station)
angle_uom = rqet.SubElement(ds_node, ns['resqml2'] + 'AngleUom')
angle_uom.set(ns['xsi'] + 'type', ns['eml'] + 'PlaneAngleUom')
if self.angles_in_degrees:
angle_uom.text = 'dega'
else:
angle_uom.text = 'rad'
mds = rqet.SubElement(ds_node, ns['resqml2'] + 'Mds')
mds.set(ns['xsi'] + 'type', ns['resqml2'] + 'DoubleHdf5Array')
mds.text = rqet.null_xml_text
mds_values_node = rqet.SubElement(mds, ns['resqml2'] + 'Values')
mds_values_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'Hdf5Dataset')
mds_values_node.text = rqet.null_xml_text
self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'Mds', root = mds_values_node)
azimuths = rqet.SubElement(ds_node, ns['resqml2'] + 'Azimuths')
azimuths.set(ns['xsi'] + 'type', ns['resqml2'] + 'DoubleHdf5Array')
azimuths.text = rqet.null_xml_text
azimuths_values_node = rqet.SubElement(azimuths, ns['resqml2'] + 'Values')
azimuths_values_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'Hdf5Dataset')
azimuths_values_node.text = rqet.null_xml_text
self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'Azimuths', root = azimuths_values_node)
inclinations = rqet.SubElement(ds_node, ns['resqml2'] + 'Inclinations')
inclinations.set(ns['xsi'] + 'type', ns['resqml2'] + 'DoubleHdf5Array')
inclinations.text = rqet.null_xml_text
inclinations_values_node = rqet.SubElement(inclinations, ns['resqml2'] + 'Values')
inclinations_values_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'Hdf5Dataset')
inclinations_values_node.text = rqet.null_xml_text
self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'Inclinations', root = inclinations_values_node)
interp_root = None
if self.wellbore_interpretation is not None:
interp_root = self.wellbore_interpretation.root
self.model.create_ref_node('RepresentedInterpretation',
rqet.find_nested_tags_text(interp_root, ['Citation', 'Title']),
bu.uuid_from_string(interp_root.attrib['uuid']),
content_type = 'obj_WellboreInterpretation',
root = ds_node)
if add_as_part:
self.model.add_part('obj_DeviationSurveyRepresentation', self.uuid, ds_node)
if add_relationships:
# todo: check following relationship
self.model.create_reciprocal_relationship(ds_node, 'destinationObject', md_datum_root, 'sourceObject')
if interp_root is not None:
self.model.create_reciprocal_relationship(ds_node, 'destinationObject', interp_root, 'sourceObject')
ext_part = rqet.part_name_for_object('obj_EpcExternalPartReference', ext_uuid, prefixed = False)
ext_node = self.model.root_for_part(ext_part)
self.model.create_reciprocal_relationship(ds_node, 'mlToExternalPartProxy', ext_node,
'externalPartProxyToMl')
return ds_node
def write_hdf5(self, file_name = None, mode = 'a'):
"""Create or append to an hdf5 file, writing datasets for the measured depths, azimuths, and inclinations."""
# NB: array data must all have been set up prior to calling this function
h5_reg = rwh5.H5Register(self.model)
h5_reg.register_dataset(self.uuid, 'Mds', self.measured_depths, dtype = float)
h5_reg.register_dataset(self.uuid, 'Azimuths', self.azimuths, dtype = float)
h5_reg.register_dataset(self.uuid, 'Inclinations', self.inclinations, dtype = float)
h5_reg.write(file = file_name, mode = mode)
def _load_related_datum(self):
"""Return related MdDatum object from XML if present."""
md_datum_uuid = bu.uuid_from_string(rqet.find_tag(rqet.find_tag(self.root, 'MdDatum'), 'UUID'))
if md_datum_uuid is not None:
md_datum_part = 'obj_MdDatum_' + str(md_datum_uuid) + '.xml'
md_datum = MdDatum(self.model, md_datum_root = self.model.root_for_part(md_datum_part, is_rels = False))
else:
md_datum = None
return md_datum
def _load_related_wellbore_interp(self):
"""Return related wellbore interp object from XML if present."""
interp_uuid = rqet.find_nested_tags_text(self.root, ['RepresentedInterpretation', 'UUID'])
if interp_uuid is None:
represented_interp = None
else:
represented_interp = rqo.WellboreInterpretation(self.model, uuid = interp_uuid)
return represented_interp
class Trajectory(BaseResqpy):
"""Class for RESQML Wellbore Trajectory Representation (Geometry).
note:
resqml allows trajectory to have different crs to the measured depth datum crs;
however, this code requires the trajectory to be in the same crs as the md datum
"""
resqml_type = 'WellboreTrajectoryRepresentation'
well_name = rqo._alias_for_attribute("title")
def __init__(
self,
parent_model,
trajectory_root = None, # deprecated
uuid = None,
md_datum = None,
deviation_survey = None,
data_frame = None,
grid = None,
cell_kji0_list = None,
wellspec_file = None,
spline_mode = 'cube',
deviation_survey_file = None,
survey_file_space_separated = False,
length_uom = None,
md_domain = None,
represented_interp = None,
well_name = None,
set_tangent_vectors = False,
hdf5_source_model = None,
originator = None,
extra_metadata = None):
"""Creates a new trajectory object and optionally loads it from xml, deviation survey, pandas dataframe, or
ascii file.
arguments:
parent_model (model.Model object): the model which the new trajectory belongs to
trajectory_root (DEPRECATED): use uuid instead; the root node of an xml tree representing the trajectory;
if not None, the new trajectory object is initialised based on the data in the tree;
if None, one of the other arguments is used
md_datum (MdDatum object): the datum that the depths for this trajectory are measured from;
not used if uuid or trajectory_root is not None
deviation_survey (DeviationSurvey object, optional): if present and uuid and trajectory_root are None
then the trajectory is derived from the deviation survey based on minimum curvature
data_frame (optional): a pandas dataframe with columns 'MD', 'X', 'Y' and 'Z', holding
the measured depths, and corresponding node locations; ignored if uuid or trajectory_root is not None
grid (grid.Grid object, optional): only required if initialising from a list of cell indices;
ignored otherwise
cell_kji0_list (numpy int array of shape (N, 3)): ordered list of cell indices to be visited by
the trajectory; ignored if uuid or trajectory_root is not None
wellspec_file (string, optional): name of an ascii file containing Nexus WELLSPEC data; well_name
and length_uom arguments must be passed
spline_mode (string, default 'cube'): one of 'none', 'linear', 'square', or 'cube'; affects spline
tangent generation; only relevant if initialising from list of cells
deviation_survey_file (string): filename of an ascii file holding the trajectory
in a tabular form; ignored if uuid or trajectory_root is not None
survey_file_space_separated (boolean, default False): if True, deviation survey file is
space separated; if False, comma separated (csv); ignored unless loading from survey file
length_uom (string, default 'm'): a resqml length unit of measure applicable to the
measured depths; should be 'm' or 'ft'
md_domain (string, optional): if present, must be 'logger' or 'driller'; the source of the original
deviation data; ignored if uuid or trajectory_root is not None
represented_interp (wellbore interpretation object, optional): if present, is noted as the wellbore
interpretation object which this trajectory relates to; ignored if uuid or trajectory_root is not None
well_name (string, optional): used as citation title
set_tangent_vectors (boolean, default False): if True and tangent vectors are not loaded then they will
be computed from the control points
hdf5_source_model (model.Model, optional): if present this model is used to determine the hdf5 file
name from which to load the trajectory's array data; if None, the parent_model is used as usual
originator (str, optional): the name of the person creating the trajectory, defaults to login id;
ignored if uuid or trajectory_root is not None
extra_metadata (dict, optional): string key, value pairs to add as extra metadata for the trajectory;
ignored if uuid or trajectory_root is not None
returns:
the newly created wellbore trajectory object
notes:
if starting from a deviation survey file, there are two routes: create a deviation survey object first,
using the azimuth and inclination data, then generate a trajectory from that based on minimum curvature;
or, create a trajectory directly using X, Y, Z data from the deviation survey file (ie. minimum
curvature or other algorithm already applied externally);
if not loading from xml, then the crs is set to that used by the measured depth datum, or if that is not
available then the default crs for the model
:meta common:
"""
self.crs_uuid = None
self.title = well_name
self.start_md = None
self.finish_md = None
self.md_uom = length_uom
self.md_domain = md_domain
self.md_datum = md_datum # md datum is an object in its own right, with a related crs!
# parametric line geometry elements
self.knot_count = None
self.line_kind_index = None
# 0 for vertical
# 1 for linear spline
# 2 for natural cubic spline
# 3 for cubic spline
# 4 for z linear cubic spline
# 5 for minimum-curvature spline # in practice this is the value actually used in datasets
# (-1) for null: no line
self.measured_depths = None # known as control point parameters in the parametric line geometry
self.control_points = None # xyz array of shape (knot_count, 3)
self.tangent_vectors = None # optional xyz tangent vector array, if present has same shape as control points)
self.deviation_survey = deviation_survey # optional related deviation survey
self.wellbore_interpretation = represented_interp
self.wellbore_feature = None
self.feature_and_interpretation_to_be_written = False
# todo: parent intersection for multi-lateral wells
# todo: witsml trajectory reference (optional)
super().__init__(model = parent_model,
uuid = uuid,
title = well_name,
originator = originator,
extra_metadata = extra_metadata,
root_node = trajectory_root)
if self.root is not None:
return
if set_tangent_vectors and self.knot_count > 1 and self.tangent_vectors is None:
self.set_tangents()
elif self.deviation_survey is not None:
self.compute_from_deviation_survey(method = 'minimum curvature', set_tangent_vectors = set_tangent_vectors)
elif data_frame is not None:
self.load_from_data_frame(data_frame,
md_uom = length_uom,
md_datum = md_datum,
set_tangent_vectors = set_tangent_vectors)
elif cell_kji0_list is not None:
self.load_from_cell_list(grid, cell_kji0_list, spline_mode, length_uom)
elif wellspec_file:
self.load_from_wellspec(grid, wellspec_file, well_name, spline_mode, length_uom)
elif deviation_survey_file:
self.load_from_ascii_file(deviation_survey_file,
space_separated_instead_of_csv = survey_file_space_separated,
md_uom = length_uom,
md_datum = md_datum,
title = well_name,
set_tangent_vectors = set_tangent_vectors)
# todo: create from already loaded deviation_survey node (ie. derive xyz points)
if self.crs_uuid is None:
if self.md_datum is not None:
self.crs_uuid = self.md_datum.crs_uuid
else:
self.crs_uuid = self.model.crs_uuid
if not self.title:
self.title = 'well trajectory'
if self.md_datum is None and self.control_points is not None:
self.md_datum = MdDatum(self.model, crs_uuid = self.crs_uuid, location = self.control_points[0])
@property
def crs_root(self):
"""XML node corresponding to self.crs_uuid."""
return self.model.root_for_uuid(self.crs_uuid)
def iter_wellbore_frames(self):
"""Iterable of all WellboreFrames associated with a trajectory.
Yields:
frame: instance of :class:`resqpy.organize.WellboreFrame`
:meta common:
"""
uuids = self.model.uuids(obj_type = "WellboreFrameRepresentation", related_uuid = self.uuid)
for uuid in uuids:
yield WellboreFrame(self.model, uuid = uuid)
def _load_from_xml(self):
"""Loads the trajectory object from an xml node (and associated hdf5 data)."""
node = self.root
assert node is not None
self.start_md = float(rqet.node_text(rqet.find_tag(node, 'StartMd')).strip())
self.finish_md = float(rqet.node_text(rqet.find_tag(node, 'FinishMd')).strip())
self.md_uom = rqet.length_units_from_node(rqet.find_tag(node, 'MdUom'))
self.md_domain = rqet.node_text(rqet.find_tag(node, 'MdDomain'))
geometry_node = rqet.find_tag(node, 'Geometry')
self.crs_uuid = bu.uuid_from_string(rqet.find_nested_tags_text(geometry_node, ['LocalCrs', 'UUID']))
self.knot_count = int(rqet.node_text(rqet.find_tag(geometry_node, 'KnotCount')).strip())
self.line_kind_index = int(rqet.node_text(rqet.find_tag(geometry_node, 'LineKindIndex')).strip())
mds_node = rqet.find_tag(geometry_node, 'ControlPointParameters')
if mds_node is not None: # not required for vertical or z linear cubic spline
load_hdf5_array(self, mds_node, 'measured_depths')
control_points_node = rqet.find_tag(geometry_node, 'ControlPoints')
load_hdf5_array(self, control_points_node, 'control_points', tag = 'Coordinates')
tangents_node = rqet.find_tag(geometry_node, 'TangentVectors')
if tangents_node is not None:
load_hdf5_array(self, tangents_node, 'tangent_vectors', tag = 'Coordinates')
relatives_model = self.model # if hdf5_source_model is None else hdf5_source_model
# md_datum - separate part, referred to in this tree
md_datum_uuid = bu.uuid_from_string(rqet.find_nested_tags_text(node, ['MdDatum', 'UUID']))
assert md_datum_uuid is not None, 'failed to fetch uuid of md datum for trajectory'
md_datum_part = relatives_model.part_for_uuid(md_datum_uuid)
assert md_datum_part, 'md datum part not found in model'
self.md_datum = MdDatum(self.model, uuid = relatives_model.uuid_for_part(md_datum_part))
ds_uuid = bu.uuid_from_string(rqet.find_nested_tags_text(node, ['DeviationSurvey', 'UUID']))
if ds_uuid is not None: # this will probably not work when relatives model is different from self.model
ds_part = rqet.part_name_for_object('obj_DeviationSurveyRepresentation_', ds_uuid)
self.deviation_survey = DeviationSurvey(self.model,
uuid = relatives_model.uuid_for_part(ds_part, is_rels = False),
md_datum = self.md_datum)
interp_uuid = rqet.find_nested_tags_text(node, ['RepresentedInterpretation', 'UUID'])
if interp_uuid is None:
self.wellbore_interpretation = None
else:
self.wellbore_interpretation = rqo.WellboreInterpretation(self.model, uuid = interp_uuid)
def compute_from_deviation_survey(self,
survey = None,
method = 'minimum curvature',
md_domain = None,
set_tangent_vectors = True):
"""Derive wellbore trajectory from deviation survey azimuth and inclination data."""
if survey is None:
assert self.deviation_survey is not None
survey = self.deviation_survey
else:
self.deviation_survey = survey
assert method in ['minimum curvature'] # if adding other methods, set line_kind_index appropriately
self.knot_count = survey.station_count
assert self.knot_count >= 2 # vertical well could be hamdled by allowing a single station in survey?
self.line_kind_index = 5 # minimum curvature spline
self.measured_depths = survey.measured_depths.copy()
self.md_uom = survey.md_uom
if not self.title:
self.title = rqet.find_nested_tags_text(survey.root_node, ['Citation', 'Title'])
self.start_md = self.measured_depths[0]
self.finish_md = self.measured_depths[-1]
if md_domain is not None:
self.md_domain = md_domain
self.control_points = np.empty((self.knot_count, 3))
self.control_points[0, :] = survey.first_station
for sp in range(1, self.knot_count):
i1 = survey.inclinations[sp - 1]
i2 = survey.inclinations[sp]
az1 = survey.azimuths[sp - 1]
az2 = survey.azimuths[sp]
delta_md = survey.measured_depths[sp] - survey.measured_depths[sp - 1]
assert delta_md > 0.0
if i1 == i2 and az1 == az2:
matrix = vec.rotation_3d_matrix((180.0 - i1, -az1, 0.0)) # TODO: check sign of az1
delta_v = vec.rotate_vector(matrix, np.array([0.0, delta_md, 0.0]))
else:
i1 = maths.radians(i1)
i2 = maths.radians(i2)
az1 = maths.radians(az1)
az2 = maths.radians(az2)
sin_i1 = maths.sin(i1)
sin_i2 = maths.sin(i2)
cos_theta = min(max(maths.cos(i2 - i1) - sin_i1 * sin_i2 * (1.0 - maths.cos(az2 - az1)), -1.0), 1.0)
theta = maths.acos(cos_theta)
# theta = maths.acos(sin_i1 * sin_i2 * maths.cos(az2 - az1) + (maths.cos(i1) * maths.cos(i2)))
assert theta != 0.0 # shouldn't happen as covered by if clause above
half_rf = maths.tan(0.5 * theta) / theta
delta_y = delta_md * half_rf * ((sin_i1 * maths.cos(az1)) + (sin_i2 * maths.cos(az2)))
delta_x = delta_md * half_rf * ((sin_i1 * maths.sin(az1)) + (sin_i2 * maths.sin(az2)))
delta_z = delta_md * half_rf * (maths.cos(i1) + maths.cos(i2))
delta_v = np.array((delta_x, delta_y, delta_z))
self.control_points[sp] = self.control_points[sp - 1] + delta_v
self.tangent_vectors = None
if set_tangent_vectors:
self.set_tangents()
self.md_datum = survey.md_datum
def load_from_data_frame(
self,
data_frame,
md_col = 'MD',
x_col = 'X',
y_col = 'Y',
z_col = 'Z',
md_uom = 'm',
md_domain = None,
md_datum = None, # MdDatum object
title = None,
set_tangent_vectors = True):
"""Load MD and control points (xyz) data from a pandas data frame."""
try:
for col in [md_col, x_col, y_col, z_col]:
assert col in data_frame.columns
self.knot_count = len(data_frame)
assert self.knot_count >= 2 # vertical well could be hamdled by allowing a single station in survey?
self.line_kind_index = 5 # assume minimum curvature spline
# self.md_uom = bwam.p_length_unit(md_uom)
self.md_uom = bwam.rq_length_unit(md_uom)
start = data_frame.iloc[0]
finish = data_frame.iloc[-1]
if title:
self.title = title
self.start_md = start[md_col]
self.finish_md = finish[md_col]
if md_domain is not None:
self.md_domain = md_domain
self.measured_depths = np.empty(self.knot_count)
self.measured_depths[:] = data_frame[md_col]
self.control_points = np.empty((self.knot_count, 3))
self.control_points[:, 0] = data_frame[x_col]
self.control_points[:, 1] = data_frame[y_col]
self.control_points[:, 2] = data_frame[z_col]
self.tangent_vectors = None
if set_tangent_vectors:
self.set_tangents()
self.md_datum = md_datum
except Exception:
log.exception('failed to load trajectory object from data frame')
def load_from_cell_list(self, grid, cell_kji0_list, spline_mode = 'cube', md_uom = 'm'):
"""Loads the trajectory object based on the centre points of a list of cells."""
assert grid is not None, 'grid argument missing for trajectory initislisation from cell list'
cell_kji0_list = np.array(cell_kji0_list, dtype = int)
assert cell_kji0_list.ndim == 2 and cell_kji0_list.shape[1] == 3
assert spline_mode in ['none', 'linear', 'square', 'cube']
cell_centres = grid.centre_point_list(cell_kji0_list)
knot_count = len(cell_kji0_list) + 2
self.line_kind_index = 5 # 5 means minimum curvature spline; todo: set to cubic spline value?
self.md_uom = bwam.rq_length_unit(md_uom)
self.start_md = 0.0
points = np.empty((knot_count, 3))
points[1:-1] = cell_centres
points[0] = points[1]
points[0, 2] = 0.0
points[-1] = points[-2]
points[-1, 2] *= 1.05
if spline_mode == 'none':
self.knot_count = knot_count
self.control_points = points
else:
self.control_points = rql.spline(points, tangent_weight = spline_mode, min_subdivisions = 3)
self.knot_count = len(self.control_points)
self.set_measured_depths()
def load_from_wellspec(self, grid, wellspec_file, well_name, spline_mode = 'cube', md_uom = 'm'):
col_list = ['IW', 'JW', 'L']
wellspec_dict = wsk.load_wellspecs(wellspec_file, well = well_name, column_list = col_list)
assert len(wellspec_dict) == 1, 'no wellspec data found in file ' + wellspec_file + ' for well ' + well_name
df = wellspec_dict[well_name]
assert len(df) > 0, 'no rows of perforation data found in wellspec for well ' + well_name
cell_kji0_list = np.empty((len(df), 3), dtype = int)
cell_kji0_list[:, 0] = df['L']
cell_kji0_list[:, 1] = df['JW']
cell_kji0_list[:, 2] = df['IW']
self.load_from_cell_list(grid, cell_kji0_list, spline_mode, md_uom)
def load_from_ascii_file(self,
trajectory_file,
comment_character = '#',
space_separated_instead_of_csv = False,
md_col = 'MD',
x_col = 'X',
y_col = 'Y',
z_col = 'Z',
md_uom = 'm',
md_domain = None,
md_datum = None,
well_col = None,
title = None,
set_tangent_vectors = True):
"""Loads the trajectory object from an ascii file with columns for MD, X, Y & Z (and optionally WELL)."""
if not title and not self.title:
self.title = 'well trajectory'
try:
df = pd.read_csv(trajectory_file,
comment = comment_character,
delim_whitespace = space_separated_instead_of_csv)
if df is None:
raise Exception
except Exception:
log.error('failed to read ascii deviation survey file ' + str(trajectory_file))
raise
if well_col and well_col not in df.columns:
log.warning('well column ' + str(well_col) + ' not found in ascii trajectory file ' + str(trajectory_file))
well_col = None
if well_col is None:
for col in df.columns:
if str(col).upper().startswith('WELL'):
well_col = col
break
if title: # filter data frame by well name
if well_col:
df = df[df[well_col] == title]
if len(df) == 0:
log.error('no data found for well ' + str(title) + ' in file ' + str(trajectory_file))
elif well_col is not None:
if len(set(df[well_col])) > 1:
raise Exception(
'attempt to set trajectory for unidentified well from ascii file holding data for multiple wells')
self.load_from_data_frame(df,
md_col = md_col,
x_col = x_col,
y_col = y_col,
z_col = z_col,
md_uom = md_uom,
md_domain = md_domain,
md_datum = md_datum,
title = title,
set_tangent_vectors = set_tangent_vectors)
def set_tangents(self, force = False, write_hdf5 = False, weight = 'cube'):
"""Calculates tangent vectors based on control points.
arguments:
force (boolean, default False): if False and tangent vectors already exist then the existing ones are used;
if True or no tangents vectors exist then they are computed
write_hdf5 (boolean, default False): if True and new tangent vectors are computed then the array is also written
directly to the hdf5 file
weight (string, default 'linear'): one of 'linear', 'square', 'cube'; if linear, each tangent is the mean of the
direction vectors of the two trjectory segments which meet at the knot; the square and cube options give
increased weight to the direction vector of shorter segments (usually better)
returns:
numpy float array of shape (knot_count, 3) being the tangents in xyz, 'pointing' in the direction of increased
knot index; the tangents are also stored as an attribute of the object
note:
the write_hdf5() method writes all the array data for the trajectory, including the tangent vectors; only set
the write_hdf5 argument to this method to True if the other arrays for the trajectory already exist in the hdf5 file
"""
if self.tangent_vectors is not None and not force:
return self.tangent_vectors
assert self.knot_count is not None and self.knot_count >= 2
assert self.control_points is not None and len(self.control_points) == self.knot_count
self.tangent_vectors = rql.tangents(self.control_points, weight = weight)
if write_hdf5:
h5_reg = rwh5.H5Register(self.model)
h5_reg.register_dataset(self.uuid, 'tangentVectors', self.tangent_vectors)
h5_reg.write(file = self.model.h5_filename(), mode = 'a')
return self.tangent_vectors
def dataframe(self, md_col = 'MD', x_col = 'X', y_col = 'Y', z_col = 'Z'):
"""Returns a pandas data frame containing MD and control points (xyz) data.
note:
set md_col to None for a dataframe containing only X, Y & Z data
:meta common:
"""
if md_col:
column_list = [md_col, x_col, y_col, z_col]
else:
column_list = [x_col, y_col, z_col]
data_frame = pd.DataFrame(columns = column_list)
if md_col:
data_frame[md_col] = self.measured_depths
data_frame[x_col] = self.control_points[:, 0]
data_frame[y_col] = self.control_points[:, 1]
data_frame[z_col] = self.control_points[:, 2]
return data_frame
def write_to_ascii_file(self,
trajectory_file,
mode = 'w',
space_separated_instead_of_csv = False,
md_col = 'MD',
x_col = 'X',
y_col = 'Y',
z_col = 'Z'):
"""Writes trajectory to an ascii file.
note:
set md_col to None for a dataframe containing only X, Y & Z data
"""
df = self.dataframe(md_col = md_col, x_col = x_col, y_col = y_col, z_col = z_col)
sep = ' ' if space_separated_instead_of_csv else ','
df.to_csv(trajectory_file, sep = sep, index = False, mode = mode)
def xyz_for_md(self, md):
"""Returns an xyz triplet corresponding to the given measured depth; uses simple linear interpolation between
knots.
args:
md (float): measured depth for which xyz location is required; units must be those of self.md_uom
returns:
triple float being x, y, z coordinates of point on trajectory corresponding to given measured depth
note:
the algorithm uses a simple linear interpolation between neighbouring knots (control points) on the trajectory;
if the measured depth is less than zero or greater than the finish md, a single None is returned; if the md is
less than the start md then a linear interpolation between the md datum location and the first knot is returned
:meta common:
"""
def interpolate(p1, p2, f):
return f * p2 + (1.0 - f) * p1
def search(md, i1, i2):
if i2 - i1 <= 1:
if md == self.measured_depths[i1]:
return self.control_points[i1]
return interpolate(self.control_points[i1], self.control_points[i1 + 1],
(md - self.measured_depths[i1]) /
(self.measured_depths[i1 + 1] - self.measured_depths[i1]))
im = i1 + (i2 - i1) // 2
if self.measured_depths[im] >= md:
return search(md, i1, im)
return search(md, im, i2)
if md < 0.0 or md > self.finish_md or md > self.measured_depths[-1]:
return None
if md <= self.start_md:
if self.start_md == 0.0:
return self.md_datum.location
return interpolate(np.array(self.md_datum.location), self.control_points[0], md / self.start_md)
return search(md, 0, self.knot_count - 1)
def splined_trajectory(self,
well_name,
min_subdivisions = 1,
max_segment_length = None,
max_degrees_per_knot = 5.0,
use_tangents_if_present = True,
store_tangents_if_calculated = True):
"""Creates and returns a new Trajectory derived as a cubic spline of this trajectory.
arguments:
well_name (string): the name to use as the citation title for the new trajectory
min_subdivisions (+ve integer, default 1): the minimum number of segments in the trajectory for each
segment in this trajectory
max_segment_length (float, optional): if present, each segment of this trajectory is subdivided so
that the naive subdivided length is not greater than the specified length
max_degrees_per_knot (float, default 5.0): the maximum number of degrees
use_tangents_if_present (boolean, default False): if True, any tangent vectors in this trajectory
are used during splining
store_tangents_if_calculated (boolean, default True): if True any tangents calculated by the method
are stored in the object (causing any previous tangents to be discarded); however, the new tangents
are not written to the hdf5 file by this method
returns:
Trajectory object with control points lying on a cubic spline of the points of this trajectory
notes:
this method is typically used to smoothe an artificial or simulator trajectory;
measured depths are re-calculated and will differ from those in this trajectory;
unexpected behaviour may occur if the z units are different from the xy units in the crs;
if tangent vectors for neighbouring points in this trajectory are pointing in opposite directions,
the resulting spline is likely to be bad;
the max_segment_length is applied when deciding how many subdivisions to make for a segment in this
trajectory, based on the stright line segment length; segments in the resulting spline may exceed this
length;
similarly max_degrees_per_knot assumes a simply bend between neighbouring knots; if the position of the
control points results in a loop, the value may be exceeded in the spline;
the hdf5 data for the splined trajectory is not written by this method, neither is the xml created;
no interpretation object is created by this method
NB: direction of tangent vectors affects results, set use_tangents_if_present = False to
ensure locally calculated tangent vectors are used
"""
assert self.knot_count > 1 and self.control_points is not None
assert min_subdivisions >= 1
assert max_segment_length is None or max_segment_length > 0.0
assert max_degrees_per_knot is None or max_degrees_per_knot > 0.0
if not well_name:
well_name = self.title
tangent_vectors = self.tangent_vectors
if tangent_vectors is None or not use_tangents_if_present:
tangent_vectors = rql.tangents(self.control_points, weight = 'square')
if store_tangents_if_calculated:
self.tangent_vectors = tangent_vectors
spline_traj = Trajectory(self.model,
well_name = well_name,
md_datum = self.md_datum,
length_uom = self.md_uom,
md_domain = self.md_domain)
spline_traj.line_kind_index = self.line_kind_index # not sure how we should really be setting this
spline_traj.crs_uuid = self.crs_uuid
spline_traj.start_md = self.start_md
spline_traj.deviation_survey = self.deviation_survey
spline_traj.control_points = rql.spline(self.control_points,
tangent_vectors = tangent_vectors,
min_subdivisions = min_subdivisions,
max_segment_length = max_segment_length,
max_degrees_per_knot = max_degrees_per_knot)
spline_traj.knot_count = len(spline_traj.control_points)
spline_traj.set_measured_depths()
return spline_traj
def set_measured_depths(self):
"""Sets the measured depths from the start_md value and the control points."""
self.measured_depths = np.empty(self.knot_count)
self.measured_depths[0] = self.start_md
for sk in range(1, self.knot_count):
self.measured_depths[sk] = (self.measured_depths[sk - 1] +
vec.naive_length(self.control_points[sk] - self.control_points[sk - 1]))
self.finish_md = self.measured_depths[-1]
return self.measured_depths
def create_feature_and_interpretation(self):
"""Instantiate new empty WellboreFeature and WellboreInterpretation objects, if a wellboreinterpretation does
not already exist.
Uses the trajectory citation title as the well name
"""
log.debug("Creating a new WellboreInterpretation..")
log.debug(f"WellboreFeature exists: {self.wellbore_feature is not None}")
log.debug(f"WellboreInterpretation exists: {self.wellbore_interpretation is not None}")
if self.wellbore_interpretation is None:
log.info(f"Creating WellboreInterpretation and WellboreFeature with name {self.title}")
self.wellbore_feature = rqo.WellboreFeature(parent_model = self.model, feature_name = self.title)
self.wellbore_interpretation = rqo.WellboreInterpretation(parent_model = self.model,
wellbore_feature = self.wellbore_feature)
self.feature_and_interpretation_to_be_written = True
else:
raise ValueError("Cannot add WellboreFeature, trajectory already has an associated WellboreInterpretation")
def create_xml(self,
ext_uuid = None,
wbt_uuid = None,
md_datum_root = None,
md_datum_xyz = None,
add_as_part = True,
add_relationships = True,
title = None,
originator = None):
"""Create a wellbore trajectory representation node from a Trajectory object, optionally add as part.
notes:
measured depth datum xml node must be in place before calling this function;
branching well structures (multi-laterals) are supported by the resqml standard but not yet by
this code;
optional witsml trajectory reference not yet supported here
:meta common:
"""
if title:
self.title = title
if not self.title:
self.title = 'wellbore trajectory'
if ext_uuid is None:
ext_uuid = self.model.h5_uuid()
if self.feature_and_interpretation_to_be_written:
if self.wellbore_interpretation is None:
self.create_feature_and_interpretation()
if self.wellbore_feature is not None:
self.wellbore_feature.create_xml(add_as_part = add_as_part, originator = originator)
self.wellbore_interpretation.create_xml(add_as_part = add_as_part,
add_relationships = add_relationships,
originator = originator)
if md_datum_root is None:
if self.md_datum is None:
assert md_datum_xyz is not None
self.md_datum = MdDatum(self.model, location = md_datum_xyz)
if self.md_datum.root is None:
md_datum_root = self.md_datum.create_xml()
else:
md_datum_root = self.md_datum.root
wbt_node = super().create_xml(originator = originator, add_as_part = False)
start_node = rqet.SubElement(wbt_node, ns['resqml2'] + 'StartMd')
start_node.set(ns['xsi'] + 'type', ns['xsd'] + 'double')
start_node.text = str(self.start_md)
finish_node = rqet.SubElement(wbt_node, ns['resqml2'] + 'FinishMd')
finish_node.set(ns['xsi'] + 'type', ns['xsd'] + 'double')
finish_node.text = str(self.finish_md)
md_uom = rqet.SubElement(wbt_node, ns['resqml2'] + 'MdUom')
md_uom.set(ns['xsi'] + 'type', ns['eml'] + 'LengthUom')
md_uom.text = bwam.rq_length_unit(self.md_uom)
self.model.create_md_datum_reference(self.md_datum.root, root = wbt_node)
if self.line_kind_index != 0: # 0 means vertical well, which doesn't need a geometry
# todo: check geometry elements for parametric curve flavours other than minimum curvature
geom = rqet.SubElement(wbt_node, ns['resqml2'] + 'Geometry')
geom.set(ns['xsi'] + 'type', ns['resqml2'] + 'ParametricLineGeometry')
geom.text = '\n'
# note: resqml standard allows trajectory to be in different crs to md datum
# however, this module often uses the md datum crs, if the trajectory has been imported
if self.crs_uuid is None:
self.crs_uuid = self.md_datum.crs_uuid
assert self.crs_uuid is not None
self.model.create_crs_reference(crs_uuid = self.crs_uuid, root = geom)
kc_node = rqet.SubElement(geom, ns['resqml2'] + 'KnotCount')
kc_node.set(ns['xsi'] + 'type', ns['xsd'] + 'positiveInteger')
kc_node.text = str(self.knot_count)
lki_node = rqet.SubElement(geom, ns['resqml2'] + 'LineKindIndex')
lki_node.set(ns['xsi'] + 'type', ns['xsd'] + 'integer')
lki_node.text = str(self.line_kind_index)
cpp_node = rqet.SubElement(geom, ns['resqml2'] + 'ControlPointParameters')
cpp_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'DoubleHdf5Array')
cpp_node.text = rqet.null_xml_text
cpp_values_node = rqet.SubElement(cpp_node, ns['resqml2'] + 'Values')
cpp_values_node.set(ns['xsi'] + 'type', ns['eml'] + 'Hdf5Dataset')
cpp_values_node.text = rqet.null_xml_text
self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'controlPointParameters', root = cpp_values_node)
cp_node = rqet.SubElement(geom, ns['resqml2'] + 'ControlPoints')
cp_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'Point3dHdf5Array')
cp_node.text = rqet.null_xml_text
cp_coords_node = rqet.SubElement(cp_node, ns['resqml2'] + 'Coordinates')
cp_coords_node.set(ns['xsi'] + 'type', ns['eml'] + 'Hdf5Dataset')
cp_coords_node.text = rqet.null_xml_text
self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'controlPoints', root = cp_coords_node)
if self.tangent_vectors is not None:
tv_node = rqet.SubElement(geom, ns['resqml2'] + 'TangentVectors')
tv_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'Point3dHdf5Array')
tv_node.text = rqet.null_xml_text
tv_coords_node = rqet.SubElement(tv_node, ns['resqml2'] + 'Coordinates')
tv_coords_node.set(ns['xsi'] + 'type', ns['eml'] + 'Hdf5Dataset')
tv_coords_node.text = rqet.null_xml_text
self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'tangentVectors', root = tv_coords_node)
if self.md_domain:
domain_node = rqet.SubElement(wbt_node, ns['resqml2'] + 'MdDomain')
domain_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'MdDomain')
domain_node.text = self.md_domain
if self.deviation_survey is not None:
ds_root = self.deviation_survey.root_node
self.model.create_ref_node('DeviationSurvey',
rqet.find_tag(rqet.find_tag(ds_root, 'Citation'), 'Title').text,
bu.uuid_from_string(ds_root.attrib['uuid']),
content_type = 'obj_DeviationSurveyRepresentation',
root = wbt_node)
interp_root = None
if self.wellbore_interpretation is not None:
interp_root = self.wellbore_interpretation.root
self.model.create_ref_node('RepresentedInterpretation',
rqet.find_nested_tags_text(interp_root, ['Citation', 'Title']),
bu.uuid_from_string(interp_root.attrib['uuid']),
content_type = 'obj_WellboreInterpretation',
root = wbt_node)
if add_as_part:
self.model.add_part('obj_WellboreTrajectoryRepresentation', self.uuid, wbt_node)
if add_relationships:
crs_root = self.crs_root
self.model.create_reciprocal_relationship(wbt_node, 'destinationObject', crs_root, 'sourceObject')
self.model.create_reciprocal_relationship(wbt_node, 'destinationObject', self.md_datum.root,
'sourceObject')
if self.deviation_survey is not None:
self.model.create_reciprocal_relationship(wbt_node, 'destinationObject',
self.deviation_survey.root_node, 'sourceObject')
if interp_root is not None:
self.model.create_reciprocal_relationship(wbt_node, 'destinationObject', interp_root,
'sourceObject')
ext_part = rqet.part_name_for_object('obj_EpcExternalPartReference', ext_uuid, prefixed = False)
ext_node = self.model.root_for_part(ext_part)
self.model.create_reciprocal_relationship(wbt_node, 'mlToExternalPartProxy', ext_node,
'externalPartProxyToMl')
return wbt_node
def write_hdf5(self, file_name = None, mode = 'a'):
"""Create or append to an hdf5 file, writing datasets for the measured depths, control points and tangent
vectors.
:meta common:
"""
# NB: array data must all have been set up prior to calling this function
if self.uuid is None:
self.uuid = bu.new_uuid()
h5_reg = rwh5.H5Register(self.model)
h5_reg.register_dataset(self.uuid, 'controlPointParameters', self.measured_depths)
h5_reg.register_dataset(self.uuid, 'controlPoints', self.control_points)
if self.tangent_vectors is not None:
h5_reg.register_dataset(self.uuid, 'tangentVectors', self.tangent_vectors)
h5_reg.write(file = file_name, mode = mode)
def __eq__(self, other):
"""Implements equals operator.
Compares class type and uuid
"""
# TODO: more detailed equality comparison
other_uuid = getattr(other, "uuid", None)
return isinstance(other, self.__class__) and bu.matching_uuids(self.uuid, other_uuid)
class WellboreFrame(BaseResqpy):
"""Class for RESQML WellboreFrameRepresentation objects (supporting well log Properties)
RESQML documentation:
Representation of a wellbore that is organized along a wellbore trajectory by its MD values.
RESQML uses MD values to associate properties on points and to organize association of
properties on intervals between MD points.
Roughly equivalent to a Techlog "dataset" object with a given depth reference.
The `logs` attribute is a :class:`resqpy.property.WellLogCollection` of all logs in the frame.
"""
resqml_type = 'WellboreFrameRepresentation'
def __init__(self,
parent_model,
frame_root = None,
uuid = None,
trajectory = None,
mds = None,
represented_interp = None,
title = None,
originator = None,
extra_metadata = None):
"""Creates a new wellbore frame object and optionally loads it from xml or list of measured depths.
arguments:
parent_model (model.Model object): the model which the new wellbore frame belongs to
frame_root (optional): DEPRECATED. the root node of an xml tree representing the wellbore frame;
if not None, the new wellbore frame object is initialised based on the data in the tree;
if None, an empty wellbore frame object is returned
trajectory (Trajectory object, optional): the trajectory of the well; required if loading from
list of measured depths
mds (optional numpy 1D array, tuple or list of floats): ordered list of measured depths which
will constitute the frame; ignored if frame_root is not None
represented_interp (wellbore interpretation object, optional): if present, is noted as the wellbore
interpretation object which this frame relates to; ignored if frame_root is not None
title (str, optional): the citation title to use for a new wellbore frame;
ignored if uuid or frame_root is not None
originator (str, optional): the name of the person creating the wellbore frame, defaults to login id;
ignored if uuid or frame_root is not None
extra_metadata (dict, optional): string key, value pairs to add as extra metadata for the wellbore frame;
ignored if uuid or frame_root is not None
returns:
the newly created wellbore frame object
note:
if initialising from a list of measured depths, the wellbore trajectory object must already exist
"""
#: Associated wellbore trajectory, an instance of :class:`resqpy.well.Trajectory`.
self.trajectory = trajectory
self.trajectory_uuid = None if trajectory is None else trajectory.uuid
#: Instance of :class:`resqpy.organize.WellboreInterpretation`
self.wellbore_interpretation = represented_interp
self.wellbore_feature = None
self.feature_and_interpretation_to_be_written = False
#: number of measured depth nodes, each being an entry or exit point of trajectory with a cell
self.node_count = None
#: node_count measured depths (in same units and datum as trajectory) of cell entry and/or exit points
self.node_mds = None
#: All logs associated with the wellbore frame; an instance of :class:`resqpy.property.WellLogCollection`
self.logs = None
super().__init__(model = parent_model,
uuid = uuid,
title = title,
originator = originator,
extra_metadata = extra_metadata,
root_node = frame_root)
if self.root is None and trajectory is not None and mds is not None and len(mds) > 1:
self.node_count = len(mds)
self.node_mds = np.array(mds)
assert self.node_mds is not None and self.node_mds.ndim == 1
# UUID needs to have been created before LogCollection can be made
# TODO: Figure out when this should be created, and how it is kept in sync when new logs are created
self.logs = rqp.WellLogCollection(frame = self)
def _load_from_xml(self):
"""Loads the wellbore frame object from an xml node (and associated hdf5 data)."""
# NB: node is the root level xml node, not a node in the md list!
node = self.root
assert node is not None
trajectory_uuid = bu.uuid_from_string(rqet.find_nested_tags_text(node, ['Trajectory', 'UUID']))
assert trajectory_uuid is not None, 'wellbore frame trajectory reference not found in xml'
if self.trajectory is None:
self.trajectory = Trajectory(self.model, uuid = trajectory_uuid)
else:
assert bu.matching_uuids(self.trajectory.uuid, trajectory_uuid), 'wellbore frame trajectory uuid mismatch'
self.node_count = rqet.find_tag_int(node, 'NodeCount')
assert self.node_count is not None, 'node count not found in xml for wellbore frame'
assert self.node_count > 1, 'fewer than 2 nodes for wellbore frame'
mds_node = rqet.find_tag(node, 'NodeMd')
assert mds_node is not None, 'wellbore frame measured depths hdf5 reference not found in xml'
load_hdf5_array(self, mds_node, 'node_mds')
assert self.node_mds is not None and self.node_mds.ndim == 1 and self.node_mds.size == self.node_count
interp_uuid = rqet.find_nested_tags_text(node, ['RepresentedInterpretation', 'UUID'])
if interp_uuid is None:
self.wellbore_interpretation = None
else:
self.wellbore_interpretation = rqo.WellboreInterpretation(self.model, uuid = interp_uuid)
# Create well log collection of all log data
self.logs = rqp.WellLogCollection(frame = self)
def extract_crs_root(self):
"""Returns the xml root node of the coordinate reference system used by the related trajectory."""
if self.trajectory is None:
return None
return self.trajectory.crs_root
def create_feature_and_interpretation(self):
"""Instantiate new empty WellboreFeature and WellboreInterpretation objects, if a wellboreinterpretation does
not already exist.
Uses the wellboreframe citation title as the well name
"""
if self.wellbore_interpretation is not None:
log.info(f"Creating WellboreInterpretation and WellboreFeature with name {self.title}")
self.wellbore_feature = rqo.WellboreFeature(parent_model = self.model, feature_name = self.title)
self.wellbore_interpretation = rqo.WellboreInterpretation(parent_model = self.model,
wellbore_feature = self.wellbore_feature)
self.feature_and_interpretation_to_be_written = True
else:
log.info("WellboreInterpretation already exists")
def write_hdf5(self, file_name = None, mode = 'a'):
"""Create or append to an hdf5 file, writing datasets for the measured depths."""
# NB: array data must have been set up prior to calling this function
if self.uuid is None:
self.uuid = bu.new_uuid()
h5_reg = rwh5.H5Register(self.model)
h5_reg.register_dataset(self.uuid, 'NodeMd', self.node_mds)
h5_reg.write(file = file_name, mode = mode)
def create_xml(self,
ext_uuid = None,
add_as_part = True,
add_relationships = True,
title = None,
originator = None):
"""Create a wellbore frame representation node from this WellboreFrame object, optionally add as part.
note:
trajectory xml node must be in place before calling this function
"""
assert self.trajectory is not None, 'trajectory object missing'
assert self.trajectory.root is not None, 'trajectory xml not established'
if self.feature_and_interpretation_to_be_written:
if self.wellbore_interpretation is None:
self.create_feature_and_interpretation()
if self.wellbore_feature is not None:
self.wellbore_feature.create_xml(add_as_part = add_as_part, originator = originator)
self.wellbore_interpretation.create_xml(add_as_part = add_as_part,
add_relationships = add_relationships,
originator = originator)
if ext_uuid is None:
ext_uuid = self.model.h5_uuid()
if title:
self.title = title
if not self.title:
self.title = 'wellbore frame'
wf_node = super().create_xml(originator = originator, add_as_part = False)
# wellbore frame elements
nc_node = rqet.SubElement(wf_node, ns['resqml2'] + 'NodeCount')
nc_node.set(ns['xsi'] + 'type', ns['xsd'] + 'positiveInteger')
nc_node.text = str(self.node_count)
mds_node = rqet.SubElement(wf_node, ns['resqml2'] + 'NodeMd')
mds_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'DoubleHdf5Array')
mds_node.text = rqet.null_xml_text
mds_values_node = rqet.SubElement(mds_node, ns['resqml2'] + 'Values')
mds_values_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'Hdf5Dataset')
mds_values_node.text = rqet.null_xml_text
self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'NodeMd', root = mds_values_node)
traj_root = self.trajectory.root
self.model.create_ref_node('Trajectory',
rqet.find_nested_tags_text(traj_root, ['Citation', 'Title']),
bu.uuid_from_string(traj_root.attrib['uuid']),
content_type = 'obj_WellboreTrajectoryRepresentation',
root = wf_node)
if self.wellbore_interpretation is not None:
interp_root = self.wellbore_interpretation.root
self.model.create_ref_node('RepresentedInterpretation',
rqet.find_nested_tags_text(interp_root, ['Citation', 'Title']),
bu.uuid_from_string(interp_root.attrib['uuid']),
content_type = 'obj_WellboreInterpretation',
root = wf_node)
if add_as_part:
self.model.add_part('obj_WellboreFrameRepresentation', self.uuid, wf_node)
if add_relationships:
self.model.create_reciprocal_relationship(wf_node, 'destinationObject', self.trajectory.root,
'sourceObject')
ext_part = rqet.part_name_for_object('obj_EpcExternalPartReference', ext_uuid, prefixed = False)
ext_node = self.model.root_for_part(ext_part)
self.model.create_reciprocal_relationship(wf_node, 'mlToExternalPartProxy', ext_node,
'externalPartProxyToMl')
if self.wellbore_interpretation is not None:
interp_root = self.wellbore_interpretation.root
self.model.create_reciprocal_relationship(wf_node, 'destinationObject', interp_root, 'sourceObject')
return wf_node
class BlockedWell(BaseResqpy):
"""Class for RESQML Blocked Wellbore Representation (Wells), ie cells visited by wellbore.
RESQML documentation:
The information that allows you to locate, on one or several grids (existing or planned),
the intersection of volume (cells) and surface (faces) elements with a wellbore trajectory
(existing or planned).
note:
measured depth data must be in same crs as those for the related trajectory
"""
resqml_type = 'BlockedWellboreRepresentation'
well_name = rqo._alias_for_attribute("title")
def __init__(self,
parent_model,
blocked_well_root = None,
uuid = None,
grid = None,
trajectory = None,
wellspec_file = None,
cellio_file = None,
column_ji0 = None,
well_name = None,
check_grid_name = False,
use_face_centres = False,
represented_interp = None,
originator = None,
extra_metadata = None,
add_wellspec_properties = False):
"""Creates a new blocked well object and optionally loads it from xml, or trajectory, or Nexus wellspec file.
arguments:
parent_model (model.Model object): the model which the new blocked well belongs to
blocked_well_root (DEPRECATED): the root node of an xml tree representing the blocked well;
if not None, the new blocked well object is initialised based on the data in the tree;
if None, the other arguments are used
grid (optional, grid.Grid object): required if intialising from a trajectory or wellspec file;
not used if blocked_well_root is not None
trajectory (optional, Trajectory object): the trajectory of the well, to be intersected with the grid;
not used if blocked_well_root is not None
wellspec_file (optional, string): filename of an ascii file holding the Nexus wellspec data;
ignored if blocked_well_root is not None or trajectory is not None
cellio_file (optional, string): filename of an ascii file holding the RMS exported blocked well data;
ignored if blocked_well_root is not None or trajectory is not None or wellspec_file is not None
column_ji0 (optional, pair of ints): column indices (j0, i0) for a 'vertical' well; ignored if
blocked_well_root is not None or trajectory is not None or wellspec_file is not None or
cellio_file is not None
well_name (string): the well name as given in the wellspec or cellio file; required if loading from
one of those files; or the name to be used as citation title for a column well
check_grid_name (boolean, default False): if True, the GRID column of the wellspec data will be checked
for a match with the citation title of the grid object; perforations for other grids will be skipped;
if False, all wellspec data is assumed to relate to the grid; only relevant when loading from wellspec
use_face_centres (boolean, default False): if True, cell face centre points are used for the entry and
exit points when constructing the simulation trajectory; if False and ANGLA & ANGLV data are available
then entry and exit points are constructed based on a straight line at those angles passing through
the centre of the cell; only relevant when loading from wellspec
represented_interp (wellbore interpretation object, optional): if present, is noted as the wellbore
interpretation object which this frame relates to; ignored if blocked_well_root is not None
originator (str, optional): the name of the person creating the blocked well, defaults to login id;
ignored if uuid or blocked_well_root is not None
extra_metadata (dict, optional): string key, value pairs to add as extra metadata for the blocked well;
ignored if uuid or blocked_well_root is not None
add_wellspec_properties (boolean or list of str, default False): if not False, and initialising from
a wellspec file, the blocked well has its hdf5 data written and xml created and properties are
fully created; if a list is provided the elements must be numerical wellspec column names;
if True, all numerical columns other than the cell indices are added as properties
returns:
the newly created blocked well object
notes:
if starting from a wellspec file or column indices, a 'simulation' trajectory and md datum objects are
constructed to go with the blocked well;
column wells might not be truly vertical - the trajectory will consist of linear segments joining the
centres of the k faces in the column;
optional RESQML attributes are not handled by this code (WITSML log reference, interval stratigraphic units,
cell fluid phase units);
mysterious RESQML WellboreFrameIndexableElements is not used in any other RESQML classes and is therefore
not used here
:meta common:
"""
self.trajectory = trajectory #: trajectory object associated with the wellbore
self.trajectory_to_be_written = False
self.feature_to_be_written = False
self.interpretation_to_be_written = False
self.node_count = None #: number of measured depth nodes, each being an entry or exit point of trajectory with a cell
self.node_mds = None #: node_count measured depths (in same units and datum as trajectory) of cell entry and/or exit points
self.cell_count = None #: number of blocked intervals (<= node_count - 1)
self.cell_indices = None #: cell_count natural cell indices, paired with non-null grid_indices
self.grid_indices = None #: node_count-1 indices into grid list for each interval in node_mds; -1 for unblocked interval
self.face_pair_indices = None #: entry, exit face per cell indices, -1 for Target Depth termination within a cell
self.grid_list = [
] #: list of grid objects indexed by grid_indices; for now only handles 1 grid unless loading from xml
self.wellbore_interpretation = None #: associated wellbore interpretation object
self.wellbore_feature = None #: associated wellbore feature object
#: All logs associated with the blockedwellbore; an instance of :class:`resqpy.property.WellIntervalPropertyCollection`
self.logs = None
self.cellind_null = None
self.gridind_null = None
self.facepair_null = None
# face_index_map maps from (axis, p01) to face index value in range 0..5
# this is the default as indicated on page 139 (but not p. 180) of the RESQML Usage Gude v2.0.1
# also assumes K is generally increasing downwards
# see DevOps backlog item 269001 discussion for more information
# self.face_index_map = np.array([[0, 1], [4, 2], [5, 3]], dtype = int)
self.face_index_map = np.array([[0, 1], [2, 4], [5, 3]], dtype = int) # order: top, base, J-, I+, J+, I-
# and the inverse, maps from 0..5 to (axis, p01)
# self.face_index_inverse_map = np.array([[0, 0], [0, 1], [1, 1], [2, 1], [1, 0], [2, 0]], dtype = int)
self.face_index_inverse_map = np.array([[0, 0], [0, 1], [1, 0], [2, 1], [1, 1], [2, 0]], dtype = int)
# note: the rework_face_pairs() method, below, overwrites the face indices based on I, J cell indices
super().__init__(model = parent_model,
uuid = uuid,
title = well_name,
originator = originator,
extra_metadata = extra_metadata,
root_node = blocked_well_root)
if self.root is None:
self.wellbore_interpretation = represented_interp
if grid is None and (self.trajectory is not None or wellspec_file is not None or cellio_file is not None or
column_ji0 is not None):
grid = self.model.grid()
if self.trajectory is not None:
self.compute_from_trajectory(self.trajectory, grid)
elif wellspec_file is not None:
okay = self.derive_from_wellspec(wellspec_file,
well_name,
grid,
check_grid_name = check_grid_name,
use_face_centres = use_face_centres,
add_properties = add_wellspec_properties)
elif cellio_file is not None:
okay = self.import_from_rms_cellio(cellio_file, well_name, grid)
if not okay:
self.node_count = 0
elif column_ji0 is not None:
okay = self.set_for_column(well_name, grid, column_ji0)
self.gridind_null = -1
self.facepair_null = -1
self.cellind_null = -1
# else an empty object is returned
def _load_from_xml(self):
"""Loads the blocked wellbore object from an xml node (and associated hdf5 data)."""
node = self.root
assert node is not None
trajectory_uuid = bu.uuid_from_string(rqet.find_nested_tags_text(node, ['Trajectory', 'UUID']))
assert trajectory_uuid is not None, 'blocked well trajectory reference not found in xml'
if self.trajectory is None:
self.trajectory = Trajectory(self.model, uuid = trajectory_uuid)
else:
assert bu.matching_uuids(self.trajectory.uuid, trajectory_uuid), 'blocked well trajectory uuid mismatch'
self.node_count = rqet.find_tag_int(node, 'NodeCount')
assert self.node_count is not None and self.node_count >= 2, 'problem with blocked well node count'
mds_node = rqet.find_tag(node, 'NodeMd')
assert mds_node is not None, 'blocked well node measured depths hdf5 reference not found in xml'
load_hdf5_array(self, mds_node, 'node_mds')
# Statement below has no effect, is this a bug?
self.node_mds is not None and self.node_mds.ndim == 1 and self.node_mds.size == self.node_count
self.cell_count = rqet.find_tag_int(node, 'CellCount')
assert self.cell_count is not None and self.cell_count > 0
# TODO: remove this if block once RMS export issue resolved
if self.cell_count == self.node_count:
extended_mds = np.empty((self.node_mds.size + 1,))
extended_mds[:-1] = self.node_mds
extended_mds[-1] = self.node_mds[-1] + 1.0
self.node_mds = extended_mds
self.node_count += 1
assert self.cell_count < self.node_count
ci_node = rqet.find_tag(node, 'CellIndices')
assert ci_node is not None, 'blocked well cell indices hdf5 reference not found in xml'
load_hdf5_array(self, ci_node, 'cell_indices', dtype = int)
assert (self.cell_indices is not None and self.cell_indices.ndim == 1 and
self.cell_indices.size == self.cell_count), 'mismatch in number of cell indices for blocked well'
self.cellind_null = rqet.find_tag_int(ci_node, 'NullValue')
if self.cellind_null is None:
self.cellind_null = -1 # if no Null found assume -1 default
fi_node = rqet.find_tag(node, 'LocalFacePairPerCellIndices')
assert fi_node is not None, 'blocked well face indices hdf5 reference not found in xml'
load_hdf5_array(self, fi_node, 'raw_face_indices', dtype = 'int')
assert self.raw_face_indices is not None, 'failed to load face indices for blocked well'
assert self.raw_face_indices.size == 2 * self.cell_count, 'mismatch in number of cell faces for blocked well'
if self.raw_face_indices.ndim > 1:
self.raw_face_indices = self.raw_face_indices.reshape((self.raw_face_indices.size,))
mask = np.where(self.raw_face_indices == -1)
self.raw_face_indices[mask] = 0
self.face_pair_indices = self.face_index_inverse_map[self.raw_face_indices]
self.face_pair_indices[mask] = (-1, -1)
self.face_pair_indices = self.face_pair_indices.reshape((-1, 2, 2))
del self.raw_face_indices
self.facepair_null = rqet.find_tag_int(fi_node, 'NullValue')
if self.facepair_null is None:
self.facepair_null = -1
gi_node = rqet.find_tag(node, 'GridIndices')
assert gi_node is not None, 'blocked well grid indices hdf5 reference not found in xml'
load_hdf5_array(self, gi_node, 'grid_indices', dtype = 'int')
assert self.grid_indices is not None and self.grid_indices.ndim == 1 and self.grid_indices.size == self.node_count - 1
unique_grid_indices = np.unique(self.grid_indices) # sorted list of unique values
self.gridind_null = rqet.find_tag_int(gi_node, 'NullValue')
if self.gridind_null is None:
self.gridind_null = -1 # if no Null found assume -1 default
grid_node_list = rqet.list_of_tag(node, 'Grid')
assert len(grid_node_list) > 0, 'blocked well grid reference(s) not found in xml'
assert unique_grid_indices[0] >= -1 and unique_grid_indices[-1] < len(
grid_node_list), 'blocked well grid index out of range'
assert np.count_nonzero(
self.grid_indices >= 0) == self.cell_count, 'mismatch in number of blocked well intervals'
self.grid_list = []
for grid_ref_node in grid_node_list:
grid_node = self.model.referenced_node(grid_ref_node)
assert grid_node is not None, 'grid referenced in blocked well xml is not present in model'
grid_uuid = rqet.uuid_for_part_root(grid_node)
grid_obj = self.model.grid(uuid = grid_uuid, find_properties = False)
self.grid_list.append(grid_obj)
interp_uuid = rqet.find_nested_tags_text(node, ['RepresentedInterpretation', 'UUID'])
if interp_uuid is None:
self.wellbore_interpretation = None
else:
self.wellbore_interpretation = rqo.WellboreInterpretation(self.model, uuid = interp_uuid)
# Create blocked well log collection of all log data
self.logs = rqp.WellIntervalPropertyCollection(frame = self)
# Set up matches between cell_indices and grid_indices
self.cell_grid_link = self.map_cell_and_grid_indices()
def map_cell_and_grid_indices(self):
"""Returns a list of index values linking the grid_indices to cell_indices.
note:
length will match grid_indices, and will show -1 where cell is unblocked
"""
indexmap = []
j = 0
for i in self.grid_indices:
if i == -1:
indexmap.append(-1)
else:
indexmap.append(j)
j += 1
return indexmap
def compressed_grid_indices(self):
"""Returns a list of grid indices excluding the -1 elements (unblocked intervals).
note:
length will match that of cell_indices
"""
compressed = []
for i in self.grid_indices:
if i >= 0:
compressed.append(i)
assert len(compressed) == self.cell_count
return compressed
def number_of_grids(self):
"""Returns the number of grids referenced by the blocked well object."""
if self.grid_list is None:
return 0
return len(self.grid_list)
def single_grid(self):
"""Asserts that exactly one grid is being referenced and returns a grid object for that grid."""
assert len(self.grid_list) == 1, 'blocked well is not referring to exactly one grid'
return self.grid_list[0]
def grid_uuid_list(self):
"""Returns a list of the uuids of the grids referenced by the blocked well object.
:meta common:
"""
uuid_list = []
if self.grid_list is None:
return uuid_list
for g in self.grid_list:
uuid_list.append(g.uuid)
return uuid_list
def cell_indices_kji0(self):
"""Returns a numpy int array of shape (N, 3) of cells visited by well, for a single grid situation.
:meta common:
"""
grid = self.single_grid()
return grid.denaturalized_cell_indices(self.cell_indices)
def cell_indices_and_grid_list(self):
"""Returns a numpy int array of shape (N, 3) of cells visited by well, and a list of grid objects of length N.
:meta common:
"""
grid_for_cell_list = []
grid_indices = self.compressed_grid_indices()
assert len(grid_indices) == self.cell_count
cell_indices = np.empty((self.cell_count, 3), dtype = int)
for cell_number in range(self.cell_count):
grid = self.grid_list[grid_indices[cell_number]]
grid_for_cell_list.append(grid)
cell_indices[cell_number] = grid.denaturalized_cell_index(self.cell_indices[cell_number])
return cell_indices, grid_for_cell_list
def cell_indices_for_grid_uuid(self, grid_uuid):
"""Returns a numpy int array of shape (N, 3) of cells visited by well in specified grid.
:meta common:
"""
if isinstance(grid_uuid, str):
grid_uuid = bu.uuid_from_string(grid_uuid)
ci_list, grid_list = self.cell_indices_and_grid_list()
mask = np.zeros((len(ci_list),), dtype = bool)
for cell_number in range(len(ci_list)):
mask[cell_number] = bu.matching_uuids(grid_list[cell_number].uuid, grid_uuid)
ci_selected = ci_list[mask]
return ci_selected
def box(self, grid_uuid = None):
"""Returns the KJI box containing the cells visited by the well, for single grid if grid_uuid is None."""
if grid_uuid is None:
cells_kji0 = self.cell_indices_kji0()
else:
cells_kji0 = self.cell_indices_for_grid_uuid(grid_uuid)
if cells_kji0 is None or len(cells_kji0) == 0:
return None
well_box = np.empty((2, 3), dtype = int)
well_box[0] = np.min(cells_kji0, axis = 0)
well_box[1] = np.max(cells_kji0, axis = 0)
return well_box
def face_pair_array(self):
"""Returns numpy int array of shape (N, 2, 2) being pairs of face (axis, polarity) pairs, to go with
cell_kji0_array().
note:
each of the N rows in the returned array is of the form:
((entry_face_axis, entry_face_polarity), (exit_face_axis, exit_face_polarity))
where the axis values are in the range 0 to 2 for k, j & i respectively, and
the polarity values are zero for the 'negative' face and 1 for the 'positive' face;
exit values may be -1 to indicate TD within the cell (ie. no exit point)
"""
return self.face_pair_indices
def compute_from_trajectory(self,
trajectory,
grid,
active_only = False,
quad_triangles = True,
use_single_layer_tactics = True):
"""Populate this blocked wellbore object based on intersection of trajectory with cells of grid.
arguments:
trajectory (Trajectory object): the trajectory to intersect with the grid; control_points and crs_root attributes must
be populated
grid (grid.Grid object): the grid with which to intersect the trajectory
active_only (boolean, default False): if True, only active cells are included as blocked intervals
quad_triangles (boolean, default True): if True, 4 triangles per cell face are used for the intersection calculations;
if False, only 2 triangles per face are used
use_single_layer_tactics (boolean, default True): if True and the grid does not have k gaps, initial intersection
calculations with fault planes or the outer IK & JK skin of the grid are calculated as if the grid is a single
layer (and only after an intersection is thus found is the actual layer identified); this significantly speeds up
computation but may cause failure in the presence of significantly non-straight pillars and could (rarely) cause
problems where a fault plane is significantly skewed (non-planar) even if individual pillars are straight
note:
this method is computationally intensive and might take ~30 seconds for a tyipical grid and trajectory; large grids,
grids with k gaps, or setting use_single_layer_tactics False will typically result in significantly longer processing time
"""
import resqpy.grid_surface as rgs # was causing circular import issue when at global level
# note: see also extract_box_for_well code
assert trajectory is not None and grid is not None
if np.any(np.isnan(grid.points_ref(masked = False))):
log.warning('grid does not have geometry defined everywhere: attempting fill')
import resqpy.derived_model as rqdm
fill_grid = rqdm.copy_grid(grid)
fill_grid.set_geometry_is_defined(nullify_partial_pillars = True, complete_all = True)
# note: may need to write hdf5 and create xml for fill_grid, depending on use in populate_blocked_well_from_trajectory()
# fill_grid.write_hdf_from_caches()
# fill_grid.create_xml
grid = fill_grid
assert trajectory.control_points is not None and trajectory.crs_root is not None and grid.crs_root is not None
assert len(trajectory.control_points)
self.trajectory = trajectory
if not self.well_name:
self.well_name = trajectory.title
bw = rgs.populate_blocked_well_from_trajectory(self,
grid,
active_only = active_only,
quad_triangles = quad_triangles,
lazy = False,
use_single_layer_tactics = use_single_layer_tactics)
if bw is None:
raise Exception('failed to generate blocked well from trajectory with uuid: ' + str(trajectory.uuid))
assert bw is self
def set_for_column(self, well_name, grid, col_ji0, skip_inactive = True):
"""Populates empty blocked well for a 'vertical' well in given column; creates simulation trajectory and md
datum."""
if well_name:
self.well_name = well_name
col_list = ['IW', 'JW', 'L', 'ANGLA', 'ANGLV'] # NB: L is Layer, ie. k
df = pd.DataFrame(columns = col_list)
pinch_col = grid.pinched_out(cache_cp_array = True, cache_pinchout_array = True)[:, col_ji0[0], col_ji0[1]]
if skip_inactive and grid.inactive is not None:
inactive_col = grid.inactive[:, col_ji0[0], col_ji0[1]]
else:
inactive_col = np.zeros(grid.nk, dtype = bool)
for k0 in range(grid.nk):
if pinch_col[k0] or inactive_col[k0]:
continue
# note: leaving ANGLA & ANGLV columns as NA will cause K face centres to be used when deriving from dataframe
row_dict = {'IW': col_ji0[1] + 1, 'JW': col_ji0[0] + 1, 'L': k0 + 1}
df = df.append(row_dict, ignore_index = True)
return self.derive_from_dataframe(df, self.well_name, grid, use_face_centres = True)
def derive_from_wellspec(self,
wellspec_file,
well_name,
grid,
check_grid_name = False,
use_face_centres = False,
add_properties = True):
"""Populates empty blocked well from Nexus WELLSPEC data; creates simulation trajectory and md datum.
args:
wellspec_file (string): path of Nexus ascii file holding WELLSPEC keyword
well_name (string): the name of the well as used in the wellspec data
grid (grid.Grid object): the grid object which the cell indices in the wellspec data relate to
check_grid_name (boolean, default False): if True, the GRID column of the wellspec data will be checked
for a match with the citation title of the grid object; perforations for other grids will be skipped;
if False, all wellspec data is assumed to relate to the grid
use_face_centres (boolean, default False): if True, cell face centre points are used for the entry and
exit points when constructing the simulation trajectory; if False and ANGLA & ANGLV data are available
then entry and exit points are constructed based on a straight line at those angles passing through
the centre of the cell
add_properties (bool or list of str, default True): if True, WELLSPEC columns (other than IW, JW, L & GRID)
are added as property parts for the blocked well; if a list is passed, it must contain a subset of the
columns in the WELLSPEC data
returns:
self if successful; None otherwise
note:
if add_properties is True or present as a list, this method will write the hdf5, create the xml and add
parts to the model for this blocked well and the properties
"""
if well_name:
self.well_name = well_name
else:
well_name = self.well_name
if add_properties:
if isinstance(add_properties, list):
col_list = ['IW', 'JW', 'L'] + [col.upper() for col in add_properties if col not in ['IW', 'JW', 'L']]
else:
col_list = []
else:
col_list = ['IW', 'JW', 'L', 'ANGLA', 'ANGLV']
if check_grid_name:
grid_name = rqet.citation_title_for_node(grid.root).upper()
if not grid_name:
check_grid_name = False
else:
col_list.append('GRID')
wellspec_dict = wsk.load_wellspecs(wellspec_file, well = well_name, column_list = col_list)
assert len(wellspec_dict) == 1, 'no wellspec data found in file ' + wellspec_file + ' for well ' + well_name
df = wellspec_dict[well_name]
assert len(df) > 0, 'no rows of perforation data found in wellspec for well ' + well_name
name_for_check = grid_name if check_grid_name else None
return self.derive_from_dataframe(df,
well_name,
grid,
grid_name_to_check = name_for_check,
use_face_centres = use_face_centres,
add_as_properties = add_properties)
def derive_from_cell_list(self, cell_kji0_list, well_name, grid):
"""Populate empty blocked well from numpy int array of shape (N, 3) being list of cells."""
df = pd.DataFrame(columns = ['IW', 'JW', 'L'])
df['IW'] = cell_kji0_list[:, 2] + 1
df['JW'] = cell_kji0_list[:, 1] + 1
df['L'] = cell_kji0_list[:, 0] + 1
return self.derive_from_dataframe(df, well_name, grid, use_face_centres = True)
def derive_from_dataframe(self,
df,
well_name,
grid,
grid_name_to_check = None,
use_face_centres = True,
add_as_properties = False):
"""Populate empty blocked well from WELLSPEC-like dataframe; first columns must be IW, JW, L (i, j, k).
note:
if add_as_properties is True or present as a list of wellspec column names, both the blocked well and
the properties will have their hdf5 data written, xml created and be added as parts to the model
"""
def cell_kji0_from_df(df, df_row):
row = df.iloc[df_row]
if pd.isna(row[0]) or pd.isna(row[1]) or pd.isna(row[2]):
return None
cell_kji0 = np.empty((3,), dtype = int)
cell_kji0[:] = row[2], row[1], row[0]
cell_kji0[:] -= 1
return cell_kji0
if well_name:
self.well_name = well_name
else:
well_name = self.well_name
assert len(df) > 0, 'empty dataframe for blocked well ' + str(well_name)
length_uom = grid.z_units()
assert grid.xy_units() == length_uom, 'mixed length units in grid crs'
previous_xyz = None
trajectory_mds = []
trajectory_points = [] # entries paired with trajectory_mds
blocked_intervals = [
] # will have one fewer entries than trajectory nodes; 0 = blocked, -1 = not blocked (for grid indices)
blocked_cells_kji0 = [] # will have length equal to number of 0's in blocked intervals
blocked_face_pairs = [
] # same length as blocked_cells_kji0; each is ((entry axis, entry polarity), (exit axis, exit polarity))
log.debug('wellspec dataframe for well ' + str(well_name) + ' has ' + str(len(df)) + ' row' + _pl(len(df)))
skipped_warning_grid = None
angles_present = ('ANGLV' in df.columns and 'ANGLA' in df.columns and not pd.isnull(df.iloc[0]['ANGLV']) and
not pd.isnull(df.iloc[0]['ANGLA']))
# TODO: remove these temporary overrides
angles_present = False
use_face_centres = True
if not angles_present and not use_face_centres:
log.warning(f'ANGLV and/or ANGLA data unavailable for well {well_name}: using face centres')
use_face_centres = True
for i in range(len(df)): # for each row in the dataframe for this well
cell_kji0 = cell_kji0_from_df(df, i)
if cell_kji0 is None:
log.error('missing cell index in wellspec data for well ' + str(well_name) + ' row ' + str(i + 1))
continue
row = df.iloc[i]
if grid_name_to_check and pd.notna(row['GRID']) and grid_name_to_check != str(row['GRID']).upper():
other_grid = str(row['GRID'])
if skipped_warning_grid != other_grid:
log.warning('skipping perforation(s) in grid ' + other_grid + ' for well ' + str(well_name))
skipped_warning_grid = other_grid
continue
cp = grid.corner_points(cell_kji0 = cell_kji0, cache_resqml_array = False)
assert not np.any(np.isnan(cp)), 'missing geometry for perforation cell for well ' + str(well_name)
if angles_present:
log.debug('row ' + str(i) + ': using angles')
angla = row['ANGLA']
inclination = row['ANGLV']
if inclination < 0.1:
azimuth = 0.0
else:
i_vector = np.sum(cp[:, :, 1] - cp[:, :, 0], axis = (0, 1))
azimuth = vec.azimuth(i_vector) - angla # see Nexus keyword reference doc
well_vector = vec.unit_vector_from_azimuth_and_inclination(azimuth, inclination) * 10000.0
# todo: the following might be producing NaN's when vector passes precisely through an edge
(entry_axis, entry_polarity, entry_xyz, exit_axis, exit_polarity,
exit_xyz) = find_entry_and_exit(cp, -well_vector, well_vector, well_name)
else:
# fabricate entry and exit axes and polarities based on indices alone
# note: could use geometry but here a cheap rough-and-ready approach is used
log.debug('row ' + str(i) + ': using cell moves')
if i == 0:
entry_axis, entry_polarity = 0, 0 # K-
else:
entry_move = cell_kji0 - blocked_cells_kji0[-1]
log.debug(f'entry move: {entry_move}')
if entry_move[1] == 0 and entry_move[2] == 0: # K move
entry_axis = 0
entry_polarity = 0 if entry_move[0] >= 0 else 1
elif abs(entry_move[1]) > abs(entry_move[2]): # J dominant move
entry_axis = 1
entry_polarity = 0 if entry_move[1] >= 0 else 1
else: # I dominant move
entry_axis = 2
entry_polarity = 0 if entry_move[2] >= 0 else 1
if i == len(df) - 1:
exit_axis, exit_polarity = entry_axis, 1 - entry_polarity
else:
next_cell_kji0 = cell_kji0_from_df(df, i + 1)
if next_cell_kji0 is None:
exit_axis, exit_polarity = entry_axis, 1 - entry_polarity
else:
exit_move = next_cell_kji0 - cell_kji0
log.debug(f'exit move: {exit_move}')
if exit_move[1] == 0 and exit_move[2] == 0: # K move
exit_axis = 0
exit_polarity = 1 if exit_move[0] >= 0 else 0
elif abs(exit_move[1]) > abs(exit_move[2]): # J dominant move
exit_axis = 1
exit_polarity = 1 if exit_move[1] >= 0 else 0
else: # I dominant move
exit_axis = 2
exit_polarity = 1 if exit_move[2] >= 0 else 0
if use_face_centres: # override the vector based xyz entry and exit points with face centres
if entry_axis == 0:
entry_xyz = np.mean(cp[entry_polarity, :, :], axis = (0, 1))
elif entry_axis == 1:
entry_xyz = np.mean(cp[:, entry_polarity, :], axis = (0, 1))
else:
entry_xyz = np.mean(cp[:, :, entry_polarity], axis = (0, 1)) # entry_axis == 2, ie. I
if exit_axis == 0:
exit_xyz = np.mean(cp[exit_polarity, :, :], axis = (0, 1))
elif exit_axis == 1:
exit_xyz = np.mean(cp[:, exit_polarity, :], axis = (0, 1))
else:
exit_xyz = np.mean(cp[:, :, exit_polarity], axis = (0, 1)) # exit_axis == 2, ie. I
log.debug(
f'cell: {cell_kji0}; entry axis: {entry_axis}; polarity {entry_polarity}; exit axis: {exit_axis}; polarity {exit_polarity}'
)
if previous_xyz is None: # first entry
log.debug('adding mean sea level trajectory start')
previous_xyz = entry_xyz.copy()
previous_xyz[2] = 0.0 # use depth zero as md datum
trajectory_mds.append(0.0)
trajectory_points.append(previous_xyz)
if not vec.isclose(previous_xyz, entry_xyz, tolerance = 0.05): # add an unblocked interval
log.debug('adding unblocked interval')
trajectory_points.append(entry_xyz)
new_md = trajectory_mds[-1] + vec.naive_length(
entry_xyz - previous_xyz) # assumes x, y & z units are same
trajectory_mds.append(new_md)
blocked_intervals.append(-1) # unblocked interval
previous_xyz = entry_xyz
log.debug('adding blocked interval for cell kji0: ' + str(cell_kji0))
trajectory_points.append(exit_xyz)
new_md = trajectory_mds[-1] + vec.naive_length(exit_xyz - previous_xyz) # assumes x, y & z units are same
trajectory_mds.append(new_md)
blocked_intervals.append(0) # blocked interval
previous_xyz = exit_xyz
blocked_cells_kji0.append(cell_kji0)
blocked_face_pairs.append(((entry_axis, entry_polarity), (exit_axis, exit_polarity)))
blocked_count = len(blocked_cells_kji0)
if blocked_count == 0:
log.warning('no intervals blocked for well ' + str(well_name))
return None
else:
log.info(str(blocked_count) + ' interval' + _pl(blocked_count) + ' blocked for well ' + str(well_name))
self.node_count = len(trajectory_mds)
self.node_mds = np.array(trajectory_mds)
self.cell_count = len(blocked_cells_kji0)
self.grid_indices = np.array(blocked_intervals, dtype = int) # NB. only supporting one grid at the moment
self.cell_indices = grid.natural_cell_indices(np.array(blocked_cells_kji0))
self.face_pair_indices = np.array(blocked_face_pairs, dtype = int)
self.grid_list = [grid]
# if last segment terminates at bottom face in bottom layer, add a tail to trajectory
if blocked_count > 0 and exit_axis == 0 and exit_polarity == 1 and cell_kji0[
0] == grid.nk - 1 and grid.k_direction_is_down:
tail_length = 10.0 # metres or feet
tail_xyz = trajectory_points[-1].copy()
tail_xyz[2] += tail_length * (1.0 if grid.z_inc_down() else -1.0)
trajectory_points.append(tail_xyz)
new_md = trajectory_mds[-1] + tail_length
trajectory_mds.append(new_md)
self.create_md_datum_and_trajectory(grid, trajectory_mds, trajectory_points, length_uom, well_name)
if add_as_properties and len(df.columns) > 3:
# NB: atypical writing of hdf5 data and xml creation in order to support related properties
self.write_hdf5()
self.create_xml()
if isinstance(add_as_properties, list):
for col in add_as_properties:
assert col in df.columns[3:] # could just skip missing columns
property_columns = add_as_properties
else:
property_columns = df.columns[3:]
self._add_df_properties(df, property_columns, length_uom = length_uom)
return self
def import_from_rms_cellio(self, cellio_file, well_name, grid, include_overburden_unblocked_interval = False):
"""Populates empty blocked well from RMS cell I/O data; creates simulation trajectory and md datum.
args:
cellio_file (string): path of RMS ascii export file holding blocked well cell I/O data; cell entry and
exit points are expected
well_name (string): the name of the well as used in the cell I/O file
grid (grid.Grid object): the grid object which the cell indices in the cell I/O data relate to
returns:
self if successful; None otherwise
"""
if well_name:
self.well_name = well_name
else:
well_name = self.well_name
grid_name = rqet.citation_title_for_node(grid.root)
length_uom = grid.z_units()
grid_z_inc_down = crs.Crs(grid.model, uuid = grid.crs_uuid).z_inc_down
log.debug('grid z increasing downwards: ' + str(grid_z_inc_down) + '(type: ' + str(type(grid_z_inc_down)) + ')')
cellio_z_inc_down = None
try:
assert ' ' not in well_name, 'cannot import for well name containing spaces'
with open(cellio_file, 'r') as fp:
while True:
kf.skip_blank_lines_and_comments(fp)
line = fp.readline() # file format version number?
assert line, 'well ' + str(well_name) + ' not found in file ' + str(cellio_file)
fp.readline() # 'Undefined'
words = fp.readline().split()
assert len(words), 'missing header info in cell I/O file'
if words[0].upper() == well_name.upper():
break
while not kf.blank_line(fp):
fp.readline() # skip to block of data for next well
header_lines = int(fp.readline().strip())
for _ in range(header_lines):
fp.readline()
previous_xyz = None
trajectory_mds = []
trajectory_points = [] # entries paired with trajectory_mds
blocked_intervals = [
] # will have one fewer entries than trajectory nodes; 0 = blocked, -1 = not blocked (for grid indices)
blocked_cells_kji0 = [] # will have length equal to number of 0's in blocked intervals
blocked_face_pairs = [
] # same length as blocked_cells_kji0; each is ((entry axis, entry polarity), (exit axis, exit polarity))
while not kf.blank_line(fp):
line = fp.readline()
words = line.split()
assert len(words) >= 9, 'not enough items on data line in cell I/O file, minimum 9 expected'
i1, j1, k1 = int(words[0]), int(words[1]), int(words[2])
cell_kji0 = np.array((k1 - 1, j1 - 1, i1 - 1), dtype = int)
assert np.all(0 <= cell_kji0) and np.all(
cell_kji0 < grid.extent_kji), 'cell I/O cell index not within grid extent'
entry_xyz = np.array((float(words[3]), float(words[4]), float(words[5])))
exit_xyz = np.array((float(words[6]), float(words[7]), float(words[8])))
if cellio_z_inc_down is None:
cellio_z_inc_down = bool(entry_xyz[2] + exit_xyz[2] > 0.0)
if cellio_z_inc_down != grid_z_inc_down:
entry_xyz[2] = -entry_xyz[2]
exit_xyz[2] = -exit_xyz[2]
cp = grid.corner_points(cell_kji0 = cell_kji0, cache_resqml_array = False)
assert not np.any(np.isnan(cp)), 'missing geometry for perforation cell(kji0) ' + str(
cell_kji0) + ' for well ' + str(well_name)
cell_centre = np.mean(cp, axis = (0, 1, 2))
# let's hope everything is in the same coordinate reference system!
entry_vector = 100.0 * (entry_xyz - cell_centre)
exit_vector = 100.0 * (exit_xyz - cell_centre)
(entry_axis, entry_polarity, facial_entry_xyz, exit_axis, exit_polarity,
facial_exit_xyz) = find_entry_and_exit(cp, entry_vector, exit_vector, well_name)
if previous_xyz is None: # first entry
previous_xyz = entry_xyz.copy()
if include_overburden_unblocked_interval:
log.debug('adding mean sea level trajectory start')
previous_xyz[2] = 0.0 # use depth zero as md datum
trajectory_mds.append(previous_xyz[2])
trajectory_points.append(previous_xyz)
if not vec.isclose(previous_xyz, entry_xyz, tolerance = 0.05): # add an unblocked interval
log.debug('adding unblocked interval')
trajectory_points.append(entry_xyz)
new_md = trajectory_mds[-1] + vec.naive_length(
entry_xyz - previous_xyz) # assumes x, y & z units are same
trajectory_mds.append(new_md)
blocked_intervals.append(-1) # unblocked interval
previous_xyz = entry_xyz
log.debug('adding blocked interval for cell kji0: ' + str(cell_kji0))
trajectory_points.append(exit_xyz)
new_md = trajectory_mds[-1] + vec.naive_length(
exit_xyz - previous_xyz) # assumes x, y & z units are same
trajectory_mds.append(new_md)
blocked_intervals.append(0) # blocked interval
previous_xyz = exit_xyz
blocked_cells_kji0.append(cell_kji0)
blocked_face_pairs.append(((entry_axis, entry_polarity), (exit_axis, exit_polarity)))
blocked_count = len(blocked_cells_kji0)
if blocked_count == 0:
log.warning('no intervals blocked for well ' + well_name + ' in grid ' + str(grid_name))
return None
else:
log.info(
str(blocked_count) + ' interval' + _pl(blocked_count) + ' blocked for well ' + well_name +
' in grid ' + str(grid_name))
self.create_md_datum_and_trajectory(grid,
trajectory_mds,
trajectory_points,
length_uom,
well_name,
set_depth_zero = True,
set_tangent_vectors = True)
self.node_count = len(trajectory_mds)
self.node_mds = np.array(trajectory_mds)
self.cell_count = len(blocked_cells_kji0)
self.grid_indices = np.array(blocked_intervals,
dtype = int) # NB. only supporting one grid at the moment
self.cell_indices = grid.natural_cell_indices(np.array(blocked_cells_kji0))
self.face_pair_indices = np.array(blocked_face_pairs)
self.grid_list = [grid]
except Exception:
log.exception('failed to import info for blocked well ' + str(well_name) + ' from cell I/O file ' +
str(cellio_file))
return None
return self
def dataframe(self,
i_col = 'IW',
j_col = 'JW',
k_col = 'L',
one_based = True,
extra_columns_list = [],
ntg_uuid = None,
perm_i_uuid = None,
perm_j_uuid = None,
perm_k_uuid = None,
satw_uuid = None,
sato_uuid = None,
satg_uuid = None,
region_uuid = None,
radw = None,
skin = None,
stat = None,
active_only = False,
min_k0 = None,
max_k0 = None,
k0_list = None,
min_length = None,
min_kh = None,
max_depth = None,
max_satw = None,
min_sato = None,
max_satg = None,
perforation_list = None,
region_list = None,
depth_inc_down = None,
set_k_face_intervals_vertical = False,
anglv_ref = 'normal ij down',
angla_plane_ref = None,
length_mode = 'MD',
length_uom = None,
use_face_centres = False,
preferential_perforation = True,
add_as_properties = False,
use_properties = False):
"""Returns a pandas data frame containing WELLSPEC style data.
arguments:
i_col (string, default 'IW'): the column name to use for cell I index values
j_col (string, default 'JW'): the column name to use for cell J index values
k_col (string, default 'L'): the column name to use for cell K index values
one_based (boolean, default True): if True, simulator protocol i, j & k values are placed in I, J & K columns;
if False, resqml zero based values; this does not affect the interpretation of min_k0 & max_k0 arguments
extra_columns_list (list of string, optional): list of WELLSPEC column names to include in the dataframe, from currently
recognised values: 'GRID', 'ANGLA', 'ANGLV', 'LENGTH', 'KH', 'DEPTH', 'MD', 'X', 'Y', 'RADW', 'SKIN', 'PPERF', 'RADB', 'WI', 'WBC'
ntg_uuid (uuid.UUID, optional): the uuid of the net to gross ratio property; if present is used to downgrade the i & j
permeabilities in the calculation of KH; ignored if 'KH' not in the extra column list and min_kh is not specified;
the argument may also be a dictionary mapping from grid uuid to ntg uuid; if no net to gross data is provided, it
is effectively assumed to be one (or, equivalently, the I & J permeability data is applicable to the gross rock); see
also preferential_perforation argument which can cause adjustment of effective ntg in partially perforated cells
perm_i_uuid (uuid.UUID or dictionary, optional): the uuid of the permeability property in the I direction;
required if 'KH' is included in the extra columns list and min_kh is not specified; ignored otherwise;
the argument may also be a dictionary mapping from grid uuid to perm I uuid
perm_j_uuid (uuid.UUID, optional): the uuid (or dict) of the permeability property in the J direction;
defaults to perm_i_uuid
perm_k_uuid (uuid.UUID, optional): the uuid (or dict) of the permeability property in the K direction;
defaults to perm_i_uuid
satw_uuid (uuid.UUID, optional): the uuid of a water saturation property; required if max_satw is specified; may also
be a dictionary mapping from grid uuid to satw uuid; ignored if max_satw is None
sato_uuid (uuid.UUID, optional): the uuid of an oil saturation property; required if min_sato is specified; may also
be a dictionary mapping from grid uuid to sato uuid; ignored if min_sato is None
satg_uuid (uuid.UUID, optional): the uuid of a gas saturation property; required if max_satg is specified; may also
be a dictionary mapping from grid uuid to satg uuid; ignored if max_satg is None
region_uuid (uuid.UUID, optional): the uuid of a discrete or categorical property, required if region_list is not None;
may also be a dictionary mapping from grid uuid to region uuid; ignored if region_list is None
radw (float, optional): if present, the wellbore radius used for all perforations; must be in correct units for intended
use of the WELLSPEC style dataframe; will default to 0.25 if 'RADW' is included in the extra column list
skin (float, optional): if present, a skin column is included with values set to this constant
stat (string, optional): if present, should be 'ON' or 'OFF' and is used for all perforations; will default to 'ON' if
'STAT' is included in the extra column list
active_only (boolean, default False): if True, only cells that are flagged in the grid object as active are included;
if False, cells are included whether active or not
min_k0 (int, optional): if present, perforations in layers above this are excluded (layer number will be applied
naively to all grids – not recommended when working with more than one grid with different layering)
max_k0 (int, optional): if present, perforations in layers below this are excluded (layer number will be applied
naively to all grids – not recommended when working with more than one grid with different layering)
k0_list (list of int, optional): if present, only perforations in cells in these layers are included (layer numbers
will be applied naively to all grids – not recommended when working with more than one grid with different layering)
min_length (float, optional): if present, a minimum length for an individual perforation interval to be included;
units are the length units of the trajectory object unless length_uom argument is set
min_kh (float, optional): if present, the minimum permeability x length value for which an individual interval is
included; permeabilty uuid(s) must be supplied for the kh calculation; units of the length component are those
of the trajectory object unless length_uom argument is set
max_depth (float, optional): if present, rows are excluded for cells with a centre point depth greater than this value;
max_depth should be positive downwards, with units of measure those of the grid z coordinates
max_satw (float, optional): if present, perforations in cells where the water saturation exceeds this value will
be excluded; satw_uuid must be supplied if this argument is present
min_sato (float, optional): if present, perforations in cells where the oil saturation is less than this value will
be excluded; sato_uuid must be supplied if this argument is present
max_satg (float, optional): if present, perforations in cells where the gas saturation exceeds this value will
be excluded; satg_uuid must be supplied if this argument is present
perforation_list (list of (float, float), optional): if present, a list of perforated intervals; each entry is the
start and end measured depths for a perforation; these do not need to align with cell boundaries
region_list (list of int, optional): if present, a list of region numbers for which rows are to be included; the
property holding the region data is identified by the region_uuid argument
depth_inc_down (boolean, optional): if present and True, the depth values will increase with depth; if False or None,
the direction of the depth values will be determined by the z increasing downwards indicator in the trajectory crs
set_k_face_intervals_vertical (boolean, default False): if True, intervals with entry through K- and exit through K+
will have angla and anglv set to 0.0 (vertical); if False angles will be computed depending on geometry
anglv_ref (string, default 'normal ij down'): either 'gravity', 'z down' (same as gravity), 'z+', 'k down', 'k+',
'normal ij', or 'normal ij down';
the ANGLV angles are relative to a local (per cell) reference vector selected by this keyword
angla_plane_ref (string, optional): string indicating normal vector defining plane onto which trajectory and I axis are
projected for the calculation of ANGLA; options as for anglv_ref, or 'normal well i+' which results in no projection;
defaults to the same as anglv_ref
length_mode (string, default 'MD'): 'MD' or 'straight' indicating which length to use; 'md' takes measured depth
difference between exit and entry; 'straight' uses a naive straight line length between entry and exit;
this will affect values for LENGTH, KH, DEPTH, X & Y
length_uom (string, optional): if present, either 'm' or 'ft': the length units to use for the LENGTH, KH, MD, DEPTH,
X & Y columns if they are present in extra_columns_list; also used to interpret min_length and min_kh; if None, the
length units of the trajectory attribute are used LENGTH, KH & MD and those of the grid are used for DEPTH, X & Y;
RADW value, if present, is assumed to be in the correct units and is not changed; also used implicitly to determine
conversion constant used in calculation of wellbore constant (WBC)
use_face_centres (boolean, default False): if True, the centre points of the entry and exit faces will determine the
vector used as the basis of ANGLA and ANGLV calculations; if False, the trajectory locations for the entry and exit
measured depths will be used
preferential_perforation (boolean, default True): if perforation_list is given, and KH is requested or a min_kh given,
the perforated intervals are assumed to penetrate pay rock preferentially: an effective ntg weighting is computed
to account for any residual non-pay perforated interval; ignored if perforation_list is None or kh values are not
being computed
add_as_properties (boolean or list of str, default False): if True, each column in the extra_columns_list (excluding
GRID and STAT) is added as a property with the blocked well as supporting representation and 'cells' as the
indexable element; any cell that is excluded from the dataframe will have corresponding entries of NaN in all the
properties; if a list is provided it must be a subset of extra_columns_list
use_properties (boolean or list of str, default False): if True, each column in the extra_columns_list (excluding
GRID and STAT) is populated from a property with citation title matching the column name, if it exists
notes:
units of length along wellbore will be those of the trajectory's length_uom (also applies to K.H values) unless
the length_uom argument is used;
the constraints are applied independently for each row and a row is excluded if it fails any constraint;
the min_k0 and max_k0 arguments do not stop later rows within the layer range from being included;
the min_length and min_kh limits apply to individual cell intervals and thus depend on cell size;
the water and oil saturation limits are for saturations at a single time and affect whether the interval
is included in the dataframe – there is no functionality to support turning perforations off and on over time;
the saturation limits do not stop deeper intervals with qualifying saturations from being included;
the k0_list, perforation_list and region_list arguments should be set to None to disable the corresponding functionality,
if set to an empty list, no rows will be included in the dataframe;
if add_as_properties is True, the blocked well must already have been added as a part to the model;
at add_as_properties and use_properties cannot both be True;
add_as_properties and use_properties are only currently functional for single grid blocked wells;
at present, unit conversion is not handled when using properties
:meta common:
"""
def prop_array(uuid_or_dict, grid):
assert uuid_or_dict is not None and grid is not None
if isinstance(uuid_or_dict, dict):
prop_uuid = uuid_or_dict[grid.uuid]
else:
prop_uuid = uuid_or_dict # uuid either in form of string or uuid.UUID
return grid.property_collection.single_array_ref(uuid = prop_uuid)
def get_ref_vector(grid, grid_crs, cell_kji0, mode):
# gravity = np.array((0.0, 0.0, 1.0))
if mode == 'normal well i+':
return None # ANGLA only: option for no projection onto a plane
ref_vector = None
# options for anglv or angla reference: 'z down', 'z+', 'k down', 'k+', 'normal ij', 'normal ij down'
cell_axial_vectors = None
if not mode.startswith('z'):
cell_axial_vectors = grid.interface_vectors_kji(cell_kji0)
if mode == 'z+':
ref_vector = np.array((0.0, 0.0, 1.0))
elif mode == 'z down':
if grid_crs.z_inc_down:
ref_vector = np.array((0.0, 0.0, 1.0))
else:
ref_vector = np.array((0.0, 0.0, -1.0))
elif mode in ['k+', 'k down']:
ref_vector = vec.unit_vector(cell_axial_vectors[0])
if mode == 'k down' and not grid.k_direction_is_down:
ref_vector = -ref_vector
else: # normal to plane of ij axes
ref_vector = vec.unit_vector(vec.cross_product(cell_axial_vectors[1], cell_axial_vectors[2]))
if mode == 'normal ij down':
if grid_crs.z_inc_down:
if ref_vector[2] < 0.0:
ref_vector = -ref_vector
else:
if ref_vector[2] > 0.0:
ref_vector = -ref_vector
if ref_vector is None or ref_vector[2] == 0.0:
if grid_crs.z_inc_down:
ref_vector = np.array((0.0, 0.0, 1.0))
else:
ref_vector = np.array((0.0, 0.0, -1.0))
return ref_vector
assert length_mode in ['MD', 'straight']
assert length_uom is None or length_uom in ['m', 'ft']
assert anglv_ref in ['gravity', 'z down', 'z+', 'k down', 'k+', 'normal ij', 'normal ij down']
if anglv_ref == 'gravity':
anglv_ref = 'z down'
if angla_plane_ref is None:
angla_plane_ref = anglv_ref
assert angla_plane_ref in [
'gravity', 'z down', 'z+', 'k down', 'k+', 'normal ij', 'normal ij down', 'normal well i+'
]
if angla_plane_ref == 'gravity':
angla_plane_ref = 'z down'
column_list = [i_col, j_col, k_col]
if extra_columns_list:
for extra in extra_columns_list:
assert extra.upper() in [
'GRID', 'ANGLA', 'ANGLV', 'LENGTH', 'KH', 'DEPTH', 'MD', 'X', 'Y', 'SKIN', 'RADW', 'PPERF', 'RADB',
'WI', 'WBC'
]
column_list.append(extra.upper())
else:
add_as_properties = use_properties = False
assert not (add_as_properties and use_properties)
pc = rqp.PropertyCollection(support = self) if use_properties else None
pc_titles = [] if pc is None else pc.titles()
isotropic_perm = None
if min_length is not None and min_length <= 0.0:
min_length = None
if min_kh is not None and min_kh <= 0.0:
min_kh = None
if max_satw is not None and max_satw >= 1.0:
max_satw = None
if min_sato is not None and min_sato <= 0.0:
min_sato = None
if max_satg is not None and max_satg >= 1.0:
max_satg = None
doing_kh = False
if ('KH' in column_list or min_kh is not None) and 'KH' not in pc_titles:
assert perm_i_uuid is not None, 'KH requested (or minimum specified) without I direction permeabilty being specified'
doing_kh = True
if 'WBC' in column_list and 'WBC' not in pc_titles:
assert perm_i_uuid is not None, 'WBC requested without I direction permeabilty being specified'
doing_kh = True
do_well_inflow = (('WI' in column_list and 'WI' not in pc_titles) or
('WBC' in column_list and 'WBC' not in pc_titles) or
('RADB' in column_list and 'RADB' not in pc_titles))
if do_well_inflow:
assert perm_i_uuid is not None, 'WI, RADB or WBC requested without I direction permeabilty being specified'
if doing_kh or do_well_inflow:
if perm_j_uuid is None and perm_k_uuid is None:
isotropic_perm = True
else:
if perm_j_uuid is None:
perm_j_uuid = perm_i_uuid
if perm_k_uuid is None:
perm_k_uuid = perm_i_uuid
# following line assumes arguments are passed in same form; if not, some unnecessary maths might be done
isotropic_perm = (bu.matching_uuids(perm_i_uuid, perm_j_uuid) and
bu.matching_uuids(perm_i_uuid, perm_k_uuid))
if max_satw is not None:
assert satw_uuid is not None, 'water saturation limit specified without saturation property array'
if min_sato is not None:
assert sato_uuid is not None, 'oil saturation limit specified without saturation property array'
if max_satg is not None:
assert satg_uuid is not None, 'gas saturation limit specified without saturation property array'
if region_list is not None:
assert region_uuid is not None, 'region list specified without region property array'
if radw is not None and 'RADW' not in column_list:
column_list.append('RADW')
if radw is None:
radw = 0.25
if skin is not None and 'SKIN' not in column_list:
column_list.append('SKIN')
if skin is None:
skin = 0.0
if stat is not None:
assert str(stat).upper() in ['ON', 'OFF']
stat = str(stat).upper()
if 'STAT' not in column_list:
column_list.append('STAT')
else:
stat = 'ON'
if 'GRID' not in column_list and self.number_of_grids() > 1:
log.error('creating blocked well dataframe without GRID column for well that intersects more than one grid')
if 'LENGTH' in column_list and 'PPERF' in column_list and 'KH' not in column_list and perforation_list is not None:
log.warning(
'both LENGTH and PPERF will include effects of partial perforation; only one should be used in WELLSPEC'
)
elif (perforation_list is not None and 'LENGTH' not in column_list and 'PPERF' not in column_list and
'KH' not in column_list and 'WBC' not in column_list):
log.warning('perforation list supplied but no use of LENGTH, KH, PPERF nor WBC')
if min_k0 is None:
min_k0 = 0
else:
assert min_k0 >= 0
if max_k0 is not None:
assert min_k0 <= max_k0
if k0_list is not None and len(k0_list) == 0:
log.warning('no layers included for blocked well dataframe: no rows will be included')
if perforation_list is not None and len(perforation_list) == 0:
log.warning('empty perforation list specified for blocked well dataframe: no rows will be included')
doing_angles = (('ANGLA' in column_list and 'ANGLA' not in pc_titles) or
('ANGLV' in column_list and 'ANGLV' not in pc_titles) or doing_kh or do_well_inflow)
doing_xyz = (('X' in column_list and 'X' not in pc_titles) or ('Y' in column_list and 'Y' not in pc_titles) or
('DEPTH' in column_list and 'DEPTH' not in pc_titles))
doing_entry_exit = doing_angles or ('LENGTH' in column_list and 'LENGTH' not in pc_titles and
length_mode == 'straight')
grid_crs_list = []
for grid in self.grid_list:
grid_crs = crs.Crs(self.model, uuid = grid.crs_uuid)
grid_crs_list.append(grid_crs)
if grid_crs.z_units != grid_crs.xy_units and (len(column_list) > 1 or
(len(column_list) == 1 and
column_list[0] != 'GRID')) is not None:
log.error('grid ' + str(rqet.citation_title_for_node(grid.root_node)) +
' has z units different to xy units: some WELLSPEC data likely to be wrong')
k_face_check = np.zeros((2, 2), dtype = int)
k_face_check[1, 1] = 1 # now represents entry, exit of K-, K+
k_face_check_end = k_face_check.copy()
k_face_check_end[1] = -1 # entry through K-, terminating (TD) within cell
if self.trajectory is None or self.trajectory.crs_root is None:
traj_crs = None
traj_z_inc_down = None
else:
traj_crs = crs.Crs(self.trajectory.model, uuid = self.trajectory.crs_uuid)
assert traj_crs.xy_units == traj_crs.z_units
traj_z_inc_down = traj_crs.z_inc_down
df = pd.DataFrame(columns = column_list)
df = df.astype({i_col: int, j_col: int, k_col: int})
ci = -1
row_ci_list = []
if self.node_count is None or self.node_count < 2:
interval_count = 0
else:
interval_count = self.node_count - 1
for interval in range(interval_count):
if self.grid_indices[interval] < 0:
continue # unblocked interval
ci += 1
row_dict = {}
grid = self.grid_list[self.grid_indices[interval]]
grid_crs = grid_crs_list[self.grid_indices[interval]]
grid_name = rqet.citation_title_for_node(grid.root).replace(' ', '_')
natural_cell = self.cell_indices[ci]
cell_kji0 = grid.denaturalized_cell_index(natural_cell)
tuple_kji0 = tuple(cell_kji0)
if max_depth is not None:
cell_depth = grid.centre_point(cell_kji0)[2]
if not grid_crs.z_inc_down:
cell_depth = -cell_depth
if cell_depth > max_depth:
continue
if active_only and grid.inactive is not None and grid.inactive[tuple_kji0]:
continue
if (min_k0 is not None and cell_kji0[0] < min_k0) or (max_k0 is not None and cell_kji0[0] > max_k0):
continue
if k0_list is not None and cell_kji0[0] not in k0_list:
continue
if region_list is not None and prop_array(region_uuid, grid)[tuple_kji0] not in region_list:
continue
if max_satw is not None and prop_array(satw_uuid, grid)[tuple_kji0] > max_satw:
continue
if min_sato is not None and prop_array(sato_uuid, grid)[tuple_kji0] < min_sato:
continue
if max_satg is not None and prop_array(satg_uuid, grid)[tuple_kji0] > max_satg:
continue
if 'PPERF' in pc_titles:
part_perf_fraction = pc.single_array_ref(citation_title = 'PPERF')[ci]
else:
part_perf_fraction = 1.0
if perforation_list is not None:
perf_length = 0.0
for perf_start, perf_end in perforation_list:
if perf_end <= self.node_mds[interval] or perf_start >= self.node_mds[interval + 1]:
continue
if perf_start <= self.node_mds[interval]:
if perf_end >= self.node_mds[interval + 1]:
perf_length += self.node_mds[interval + 1] - self.node_mds[interval]
break
else:
perf_length += perf_end - self.node_mds[interval]
else:
if perf_end >= self.node_mds[interval + 1]:
perf_length += self.node_mds[interval + 1] - perf_start
else:
perf_length += perf_end - perf_start
if perf_length == 0.0:
continue
part_perf_fraction = min(1.0, perf_length / (self.node_mds[interval + 1] - self.node_mds[interval]))
# log.debug('kji0: ' + str(cell_kji0))
entry_xyz = None
exit_xyz = None
if doing_entry_exit:
assert self.trajectory is not None
if use_face_centres:
entry_xyz = grid.face_centre(cell_kji0, self.face_pair_indices[interval, 0, 0],
self.face_pair_indices[interval, 0, 1])
if self.face_pair_indices[interval, 1, 0] >= 0:
exit_xyz = grid.face_centre(cell_kji0, self.face_pair_indices[interval, 1, 0],
self.face_pair_indices[interval, 1, 1])
else:
exit_xyz = grid.face_centre(cell_kji0, self.face_pair_indices[interval, 0, 0],
1 - self.face_pair_indices[interval, 0, 1])
ee_crs = grid_crs
else:
entry_xyz = self.trajectory.xyz_for_md(self.node_mds[interval])
exit_xyz = self.trajectory.xyz_for_md(self.node_mds[interval + 1])
ee_crs = traj_crs
if length_mode == 'MD':
length = self.node_mds[interval + 1] - self.node_mds[interval]
if length_uom is not None and self.trajectory is not None and length_uom != self.trajectory.md_uom:
length = bwam.convert_lengths(length, self.trajectory.md_uom, length_uom)
else: # use straight line length between entry and exit
length = vec.naive_length(np.array(exit_xyz) -
np.array(entry_xyz)) # trajectory crs, unless use_face_centres!
if length_uom is not None:
length = bwam.convert_lengths(length, ee_crs.z_units, length_uom)
elif self.trajectory is not None:
length = bwam.convert_lengths(length, ee_crs.z_units, self.trajectory.md_uom)
if perforation_list is not None:
length *= part_perf_fraction
if min_length is not None and length < min_length:
continue
sine_anglv = sine_angla = 0.0
cosine_anglv = cosine_angla = 1.0
xyz = (np.NaN, np.NaN, np.NaN)
md = 0.5 * (self.node_mds[interval + 1] + self.node_mds[interval])
anglv = pc.single_array_ref(citation_title = 'ANGLV')[ci] if 'ANGLV' in pc_titles else None
angla = pc.single_array_ref(citation_title = 'ANGLA')[ci] if 'ANGLA' in pc_titles else None
if doing_angles and not (set_k_face_intervals_vertical and
(np.all(self.face_pair_indices[ci] == k_face_check) or
np.all(self.face_pair_indices[ci] == k_face_check_end))):
vector = vec.unit_vector(np.array(exit_xyz) -
np.array(entry_xyz)) # nominal wellbore vector for interval
if traj_z_inc_down is not None and traj_z_inc_down != grid_crs.z_inc_down:
vector[2] = -vector[2]
v_ref_vector = get_ref_vector(grid, grid_crs, cell_kji0, anglv_ref)
# log.debug('v ref vector: ' + str(v_ref_vector))
if angla_plane_ref == anglv_ref:
a_ref_vector = v_ref_vector
else:
a_ref_vector = get_ref_vector(grid, grid_crs, cell_kji0, angla_plane_ref)
# log.debug('a ref vector: ' + str(a_ref_vector))
if anglv is not None:
anglv_rad = vec.radians_from_degrees(anglv)
cosine_anglv = maths.cos(anglv_rad)
sine_anglv = maths.sin(anglv_rad)
else:
cosine_anglv = min(max(vec.dot_product(vector, v_ref_vector), -1.0), 1.0)
anglv_rad = maths.acos(cosine_anglv)
sine_anglv = maths.sin(anglv_rad)
anglv = vec.degrees_from_radians(anglv_rad)
# log.debug('anglv: ' + str(anglv))
if anglv != 0.0:
# project well vector and i-axis vector onto plane defined by normal vector a_ref_vector
i_axis = grid.interface_vector(cell_kji0, 2)
i_axis = vec.unit_vector(i_axis)
if a_ref_vector is not None: # project vector and i axis onto a plane
vector -= vec.dot_product(vector, a_ref_vector) * a_ref_vector
vector = vec.unit_vector(vector)
# log.debug('i axis unit vector: ' + str(i_axis))
i_axis -= vec.dot_product(i_axis, a_ref_vector) * a_ref_vector
i_axis = vec.unit_vector(i_axis)
# log.debug('i axis unit vector in reference plane: ' + str(i_axis))
if angla is not None:
angla_rad = vec.radians_from_degrees(angla)
cosine_angla = maths.cos(angla_rad)
sine_angla = maths.sin(angla_rad)
else:
cosine_angla = min(max(vec.dot_product(vector, i_axis), -1.0), 1.0)
angla_rad = maths.acos(cosine_angla)
# negate angla if vector is 'clockwise from' i_axis when viewed from above, projected in the xy plane
# todo: have discussion around angla sign under different ijk handedness (and z inc direction?)
sine_angla = maths.sin(angla_rad)
angla = vec.degrees_from_radians(angla_rad)
if vec.clockwise((0.0, 0.0), i_axis, vector) > 0.0:
angla = -angla
angle_rad = -angla_rad
sine_angla = -sine_angla
# log.debug('angla: ' + str(angla))
else:
if angla is None:
angla = 0.0
if anglv is None:
anglv = 0.0
if doing_kh or do_well_inflow:
if ntg_uuid is None:
ntg = 1.0
ntg_is_one = True
else:
ntg = prop_array(ntg_uuid, grid)[tuple_kji0]
ntg_is_one = maths.isclose(ntg, 1.0, rel_tol = 0.001)
if isotropic_perm and ntg_is_one:
k_i = k_j = k_k = prop_array(perm_i_uuid, grid)[tuple_kji0]
else:
if preferential_perforation and not ntg_is_one:
if part_perf_fraction <= ntg:
ntg = 1.0 # effective ntg when perforated intervals are in pay
else:
ntg /= part_perf_fraction # adjusted ntg when some perforations in non-pay
# todo: check netgross facet type in property perm i & j parts: if set to gross then don't multiply by ntg below
k_i = prop_array(perm_i_uuid, grid)[tuple_kji0] * ntg
k_j = prop_array(perm_j_uuid, grid)[tuple_kji0] * ntg
k_k = prop_array(perm_k_uuid, grid)[tuple_kji0]
if doing_kh:
if isotropic_perm and ntg_is_one:
kh = length * prop_array(perm_i_uuid, grid)[tuple_kji0]
else:
if np.isnan(k_i) or np.isnan(k_j):
kh = 0.0
elif anglv == 0.0:
kh = length * maths.sqrt(k_i * k_j)
elif np.isnan(k_k):
kh = 0.0
else:
k_e = maths.pow(k_i * k_j * k_k, 1.0 / 3.0)
if k_e == 0.0:
kh = 0.0
else:
l_i = length * maths.sqrt(k_e / k_i) * sine_anglv * cosine_angla
l_j = length * maths.sqrt(k_e / k_j) * sine_anglv * sine_angla
l_k = length * maths.sqrt(k_e / k_k) * cosine_anglv
l_p = maths.sqrt(l_i * l_i + l_j * l_j + l_k * l_k)
kh = k_e * l_p
if min_kh is not None and kh < min_kh:
continue
elif 'KH' in pc_titles:
kh = pc.single_array_ref(citation_title = 'KH')[ci]
else:
kh = None
if 'LENGTH' in pc_titles:
length = pc.single_array_ref(citation_title = 'LENGTH')[ci]
if 'RADW' in pc_titles:
radw = pc.single_array_ref(citation_title = 'RADW')[ci]
assert radw > 0.0
if 'SKIN' in pc_titles:
skin = pc.single_array_ref(citation_title = 'SKIN')[ci]
radb = wi = wbc = None
if 'RADB' in pc_titles:
radb = pc.single_array_ref(citation_title = 'RADB')[ci]
if 'WI' in pc_titles:
wi = pc.single_array_ref(citation_title = 'WI')[ci]
if 'WBC' in pc_titles:
wbc = pc.single_array_ref(citation_title = 'WBC')[ci]
if do_well_inflow:
if isotropic_perm and ntg_is_one:
k_ei = k_ej = k_ek = k_i
radw_e = radw
else:
k_ei = maths.sqrt(k_j * k_k)
k_ej = maths.sqrt(k_i * k_k)
k_ek = maths.sqrt(k_i * k_j)
r_wi = 0.0 if k_ei == 0.0 else 0.5 * radw * (maths.sqrt(k_ei / k_j) + maths.sqrt(k_ei / k_k))
r_wj = 0.0 if k_ej == 0.0 else 0.5 * radw * (maths.sqrt(k_ej / k_i) + maths.sqrt(k_ej / k_k))
r_wk = 0.0 if k_ek == 0.0 else 0.5 * radw * (maths.sqrt(k_ek / k_i) + maths.sqrt(k_ek / k_j))
rwi = r_wi * sine_anglv * cosine_angla
rwj = r_wj * sine_anglv * sine_angla
rwk = r_wk * cosine_anglv
radw_e = maths.sqrt(rwi * rwi + rwj * rwj + rwk * rwk)
if radw_e == 0.0:
radw_e = radw # no permeability in this situation anyway
cell_axial_vectors = grid.interface_vectors_kji(cell_kji0)
d2 = np.empty(3)
for axis in range(3):
d2[axis] = np.sum(cell_axial_vectors[axis] * cell_axial_vectors[axis])
r_bi = 0.0 if k_ei == 0.0 else 0.14 * maths.sqrt(k_ei * (d2[1] / k_j + d2[0] / k_k))
r_bj = 0.0 if k_ej == 0.0 else 0.14 * maths.sqrt(k_ej * (d2[2] / k_i + d2[0] / k_k))
r_bk = 0.0 if k_ek == 0.0 else 0.14 * maths.sqrt(k_ek * (d2[2] / k_i + d2[1] / k_j))
rbi = r_bi * sine_anglv * cosine_angla
rbj = r_bj * sine_anglv * sine_angla
rbk = r_bk * cosine_anglv
radb_e = maths.sqrt(rbi * rbi + rbj * rbj + rbk * rbk)
if radb is None:
radb = radw * radb_e / radw_e
if wi is None:
wi = 0.0 if radb <= 0.0 else 2.0 * maths.pi / (maths.log(radb / radw) + skin)
if 'WBC' in column_list and wbc is None:
conversion_constant = 8.5270171e-5 if length_uom == 'm' else 0.006328286
wbc = conversion_constant * kh * wi # note: pperf aleady accounted for in kh
if doing_xyz:
if length_mode == 'MD' and self.trajectory is not None:
xyz = self.trajectory.xyz_for_md(md)
if length_uom is not None and length_uom != self.trajectory.md_uom:
bwam.convert_lengths(xyz, traj_crs.z_units, length_uom)
if depth_inc_down and traj_z_inc_down is False:
xyz[2] = -xyz[2]
else:
xyz = 0.5 * (np.array(exit_xyz) + np.array(entry_xyz))
if length_uom is not None and length_uom != ee_crs.z_units:
bwam.convert_lengths(xyz, ee_crs.z_units, length_uom)
if depth_inc_down and ee_crs.z_inc_down is False:
xyz[2] = -xyz[2]
xyz = np.array(xyz)
if 'X' in pc_titles:
xyz[0] = pc.single_array_ref(citation_title = 'X')[ci]
if 'Y' in pc_titles:
xyz[1] = pc.single_array_ref(citation_title = 'Y')[ci]
if 'DEPTH' in pc_titles:
xyz[2] = pc.single_array_ref(citation_title = 'DEPTH')[ci]
if length_uom is not None and self.trajectory is not None and length_uom != self.trajectory.md_uom:
md = bwam.convert_lengths(md, self.trajectory.md_uom, length_uom)
if 'MD' in pc_titles:
md = pc.single_array_ref(citation_title = 'MD')[ci]
for col_index in range(len(column_list)):
column = column_list[col_index]
if col_index < 3:
if one_based:
row_dict[column] = cell_kji0[2 - col_index] + 1
else:
row_dict[column] = cell_kji0[2 - col_index]
elif column == 'GRID':
row_dict['GRID'] = grid_name # todo: worry about spaces and quotes
elif column == 'RADW':
row_dict['RADW'] = radw
elif column == 'SKIN':
row_dict['SKIN'] = skin
elif column == 'ANGLA':
row_dict['ANGLA'] = angla
elif column == 'ANGLV':
row_dict['ANGLV'] = anglv
elif column == 'LENGTH':
# note: length units are those of trajectory length uom if length mode is MD and length_uom is None
row_dict['LENGTH'] = length
elif column == 'KH':
row_dict['KH'] = kh
elif column == 'DEPTH':
row_dict['DEPTH'] = xyz[2]
elif column == 'MD':
row_dict['MD'] = md
elif column == 'X':
row_dict['X'] = xyz[0]
elif column == 'Y':
row_dict['Y'] = xyz[1]
elif column == 'STAT':
row_dict['STAT'] = stat
elif column == 'PPERF':
row_dict['PPERF'] = part_perf_fraction
elif column == 'RADB':
row_dict['RADB'] = radb
elif column == 'WI':
row_dict['WI'] = wi
elif column == 'WBC': # note: not a valid WELLSPEC column name
row_dict['WBC'] = wbc
df = df.append(row_dict, ignore_index = True)
row_ci_list.append(ci)
if add_as_properties:
if isinstance(add_as_properties, list):
for col in add_as_properties:
assert col in extra_columns_list
property_columns = add_as_properties
else:
property_columns = extra_columns_list
self._add_df_properties(df, property_columns, row_ci_list = row_ci_list, length_uom = length_uom)
return df
def _add_df_properties(self, df, columns, row_ci_list = None, length_uom = None):
# creates a property part for each named column, based on the dataframe values
# column name used as the citation title
# self must already exist as a part in the model
# currently only handles single grid situations
# todo: rewrite to add separate property objects for each grid references by the blocked well
log.debug('_add_df_props: df:')
log.debug(f'\n{df}')
log.debug(f'columns: {columns}')
assert len(self.grid_list) == 1
if columns is None or len(columns) == 0 or len(df) == 0:
return
if row_ci_list is None:
row_ci_list = np.arange(self.cell_count)
assert len(row_ci_list) == len(df)
if length_uom is None:
length_uom = self.trajectory.md_uom
extra_pc = rqp.PropertyCollection()
extra_pc.set_support(support = self)
ci_map = np.array(row_ci_list, dtype = int)
for e in columns:
extra = e.upper()
if extra in ['GRID', 'STAT']:
continue # todo: other non-numeric columns may need to be added to this list
pk = 'continuous'
uom = 'Euc'
if extra in ['ANGLA', 'ANGLV']:
uom = 'dega'
# neither azimuth nor dip are correct property kinds; todo: create local property kinds
pk = 'azimuth' if extra == 'ANGLA' else 'inclination'
elif extra in ['LENGTH', 'MD', 'X', 'Y', 'DEPTH', 'RADW']:
if length_uom is None or length_uom == 'Euc':
if extra in ['LENGTH', 'MD']:
uom = self.trajectory.md_uom
elif extra in ['X', 'Y', 'RADW']:
uom = self.grid_list[0].xy_units()
else:
uom = self.grid_list[0].z_units()
else:
uom = length_uom
if extra == 'DEPTH':
pk = 'depth'
else:
pk = 'length'
elif extra == 'KH':
uom = 'mD.' + length_uom
pk = 'permeability length'
elif extra == 'PPERF':
uom = length_uom + '/' + length_uom
else:
uom = 'Euc'
# 'SKIN': use defaults for now; todo: create local property kind for skin
expanded = np.full(self.cell_count, np.NaN)
expanded[ci_map] = df[extra]
extra_pc.add_cached_array_to_imported_list(expanded,
'blocked well dataframe',
extra,
discrete = False,
uom = uom,
property_kind = pk,
local_property_kind_uuid = None,
facet_type = None,
facet = None,
realization = None,
indexable_element = 'cells',
count = 1)
extra_pc.write_hdf5_for_imported_list()
extra_pc.create_xml_for_imported_list_and_add_parts_to_model()
def static_kh(self,
ntg_uuid = None,
perm_i_uuid = None,
perm_j_uuid = None,
perm_k_uuid = None,
satw_uuid = None,
sato_uuid = None,
satg_uuid = None,
region_uuid = None,
active_only = False,
min_k0 = None,
max_k0 = None,
k0_list = None,
min_length = None,
min_kh = None,
max_depth = None,
max_satw = None,
min_sato = None,
max_satg = None,
perforation_list = None,
region_list = None,
set_k_face_intervals_vertical = False,
anglv_ref = 'gravity',
angla_plane_ref = None,
length_mode = 'MD',
length_uom = None,
use_face_centres = False,
preferential_perforation = True):
"""Returns the total static K.H (permeability x height); length units are those of trajectory md_uom unless
length_upm is set.
note:
see doc string for dataframe() method for argument descriptions; perm_i_uuid required
"""
df = self.dataframe(i_col = 'I',
j_col = 'J',
k_col = 'K',
one_based = False,
extra_columns_list = ['KH'],
ntg_uuid = ntg_uuid,
perm_i_uuid = perm_i_uuid,
perm_j_uuid = perm_j_uuid,
perm_k_uuid = perm_k_uuid,
satw_uuid = satw_uuid,
sato_uuid = sato_uuid,
satg_uuid = satg_uuid,
region_uuid = region_uuid,
active_only = active_only,
min_k0 = min_k0,
max_k0 = max_k0,
k0_list = k0_list,
min_length = min_length,
min_kh = min_kh,
max_depth = max_depth,
max_satw = max_satw,
min_sato = min_sato,
max_satg = max_satg,
perforation_list = perforation_list,
region_list = region_list,
set_k_face_intervals_vertical = set_k_face_intervals_vertical,
anglv_ref = anglv_ref,
angla_plane_ref = angla_plane_ref,
length_mode = length_mode,
length_uom = length_uom,
use_face_centres = use_face_centres,
preferential_perforation = preferential_perforation)
return sum(df['KH'])
def write_wellspec(self,
wellspec_file,
well_name = None,
mode = 'a',
extra_columns_list = [],
ntg_uuid = None,
perm_i_uuid = None,
perm_j_uuid = None,
perm_k_uuid = None,
satw_uuid = None,
sato_uuid = None,
satg_uuid = None,
region_uuid = None,
radw = None,
skin = None,
stat = None,
active_only = False,
min_k0 = None,
max_k0 = None,
k0_list = None,
min_length = None,
min_kh = None,
max_depth = None,
max_satw = None,
min_sato = None,
max_satg = None,
perforation_list = None,
region_list = None,
set_k_face_intervals_vertical = False,
depth_inc_down = True,
anglv_ref = 'gravity',
angla_plane_ref = None,
length_mode = 'MD',
length_uom = None,
preferential_perforation = True,
space_instead_of_tab_separator = True,
align_columns = True,
preceeding_blank_lines = 0,
trailing_blank_lines = 0,
length_uom_comment = False,
write_nexus_units = True,
float_format = '5.3'):
"""Writes Nexus WELLSPEC keyword to an ascii file.
returns:
pandas DataFrame containing data that has been written to the wellspec file
note:
see doc string for dataframe() method for most of the argument descriptions;
align_columns and float_format arguments are deprecated and no longer used
"""
def tidy_well_name(well_name):
nexus_friendly = ''
previous_underscore = False
for ch in well_name:
if not 32 <= ord(ch) < 128 or ch in ' ,!*#':
ch = '_'
if not (previous_underscore and ch == '_'):
nexus_friendly += ch
previous_underscore = (ch == '_')
if not nexus_friendly:
well_name = 'WELL_X'
return nexus_friendly
def is_float_column(col_name):
if col_name.upper() in ['ANGLA', 'ANGLV', 'LENGTH', 'KH', 'DEPTH', 'MD', 'X', 'Y', 'SKIN', 'RADW', 'PPERF']:
return True
return False
def is_int_column(col_name):
if col_name.upper() in ['IW', 'JW', 'L']:
return True
return False
assert wellspec_file, 'no output file specified to write WELLSPEC to'
col_width_dict = {
'IW': 4,
'JW': 4,
'L': 4,
'ANGLA': 8,
'ANGLV': 8,
'LENGTH': 8,
'KH': 10,
'DEPTH': 10,
'MD': 10,
'X': 8,
'Y': 12,
'SKIN': 7,
'RADW': 5,
'PPERF': 5
}
if not well_name:
if self.well_name:
well_name = self.well_name
elif self.root is not None:
well_name = rqet.citation_title_for_node(self.root)
elif self.wellbore_interpretation is not None:
well_name = self.wellbore_interpretation.title
elif self.trajectory is not None:
well_name = self.trajectory.title
else:
log.warning('no well name identified for use in WELLSPEC')
well_name = 'WELLNAME'
well_name = tidy_well_name(well_name)
df = self.dataframe(one_based = True,
extra_columns_list = extra_columns_list,
ntg_uuid = ntg_uuid,
perm_i_uuid = perm_i_uuid,
perm_j_uuid = perm_j_uuid,
perm_k_uuid = perm_k_uuid,
satw_uuid = satw_uuid,
sato_uuid = sato_uuid,
satg_uuid = satg_uuid,
region_uuid = region_uuid,
radw = radw,
skin = skin,
stat = stat,
active_only = active_only,
min_k0 = min_k0,
max_k0 = max_k0,
k0_list = k0_list,
min_length = min_length,
min_kh = min_kh,
max_depth = max_depth,
max_satw = max_satw,
min_sato = min_sato,
max_satg = max_satg,
perforation_list = perforation_list,
region_list = region_list,
depth_inc_down = depth_inc_down,
set_k_face_intervals_vertical = set_k_face_intervals_vertical,
anglv_ref = anglv_ref,
angla_plane_ref = angla_plane_ref,
length_mode = length_mode,
length_uom = length_uom,
preferential_perforation = preferential_perforation)
sep = ' ' if space_instead_of_tab_separator else '\t'
with open(wellspec_file, mode = mode) as fp:
for _ in range(preceeding_blank_lines):
fp.write('\n')
if write_nexus_units:
if length_uom == 'm':
fp.write('METRIC\n\n')
elif length_uom == 'ft':
fp.write('ENGLISH\n\n')
if length_uom_comment and self.trajectory is not None and ('LENGTH' in extra_columns_list or
'MD' in extra_columns_list or
'KH' in extra_columns_list):
fp.write(
f'! Length units along wellbore: {self.trajectory.md_uom if length_uom is None else length_uom}\n')
fp.write('WELLSPEC ' + str(well_name) + '\n')
for col_name in df.columns:
if col_name in col_width_dict:
width = col_width_dict[col_name]
else:
width = 10
form = '{0:>' + str(width) + '}'
fp.write(sep + form.format(col_name))
fp.write('\n')
for row_info in df.iterrows():
row = row_info[1]
for col_name in df.columns:
try:
if col_name in col_width_dict:
width = col_width_dict[col_name]
else:
width = 10
if is_float_column(col_name):
form = '{0:>' + str(width) + '.3f}'
fp.write(sep + form.format(float(row[col_name])))
else:
form = '{0:>' + str(width) + '}'
if is_int_column(col_name):
fp.write(sep + form.format(int(row[col_name])))
else:
fp.write(sep + form.format(str(row[col_name])))
except Exception:
fp.write(sep + str(row[col_name]))
fp.write('\n')
for _ in range(trailing_blank_lines):
fp.write('\n')
return df
def kji0_marker(self, active_only = True):
"""Convenience method returning (k0, j0, i0), grid_uuid of first blocked interval."""
cells, grids = self.cell_indices_and_grid_list()
if cells is None or grids is None or len(grids) == 0:
return None, None, None, None
return cells[0], grids[0].uuid
def xyz_marker(self, active_only = True):
"""Convenience method returning (x, y, z), crs_uuid of perforation in first blocked interval.
notes:
active_only argument not yet in use;
returns None, None if no blocked interval found
"""
cells, grids = self.cell_indices_and_grid_list()
if cells is None or grids is None or len(grids) == 0:
return None, None
node_index = 0
while node_index < self.node_count - 1 and self.grid_indices[node_index] == -1:
node_index += 1
if node_index >= self.node_count - 1:
return None, None
md = 0.5 * (self.node_mds[node_index] + self.node_mds[node_index + 1])
xyz = self.trajectory.xyz_for_md(md)
return xyz, rqet.uuid_for_part_root(self.trajectory.crs_root)
def create_feature_and_interpretation(self, shared_interpretation = True):
"""Instantiate new empty WellboreFeature and WellboreInterpretation objects.
Uses the Blocked well citation title as the well name
"""
if self.trajectory is not None:
traj_interp_uuid = self.model.uuid(obj_type = 'WellboreInterpretation', related_uuid = self.trajectory.uuid)
if traj_interp_uuid is not None:
if shared_interpretation:
self.wellbore_interpretation = rqo.WellboreInterpretation(parent_model = self.model,
uuid = traj_interp_uuid)
traj_feature_uuid = self.model.uuid(obj_type = 'WellboreFeature', related_uuid = traj_interp_uuid)
if traj_feature_uuid is not None:
self.wellbore_feature = rqo.WellboreFeature(parent_model = self.model, uuid = traj_feature_uuid)
if self.wellbore_feature is None:
self.wellbore_feature = rqo.WellboreFeature(parent_model = self.model, feature_name = self.trajectory.title)
self.feature_to_be_written = True
if self.wellbore_interpretation is None:
self.wellbore_interpretation = rqo.WellboreInterpretation(parent_model = self.model,
wellbore_feature = self.wellbore_feature)
if self.trajectory.wellbore_interpretation is None and shared_interpretation:
self.trajectory.wellbore_interpretation = self.wellbore_interpretation
self.interpretation_to_be_written = True
def create_md_datum_and_trajectory(self,
grid,
trajectory_mds,
trajectory_points,
length_uom,
well_name,
set_depth_zero = False,
set_tangent_vectors = False,
create_feature_and_interp = True):
"""Creates an Md Datum object and a (simulation) Trajectory object for this blocked well.
note:
not usually called directly; used by import methods
"""
# create md datum node for synthetic trajectory, using crs for grid
datum_location = trajectory_points[0].copy()
if set_depth_zero:
datum_location[2] = 0.0
datum = MdDatum(self.model,
crs_uuid = grid.crs_uuid,
location = datum_location,
md_reference = 'mean sea level')
# create synthetic trajectory object, using crs for grid
trajectory_mds_array = np.array(trajectory_mds)
trajectory_xyz_array = np.array(trajectory_points)
trajectory_df = pd.DataFrame({
'MD': trajectory_mds_array,
'X': trajectory_xyz_array[..., 0],
'Y': trajectory_xyz_array[..., 1],
'Z': trajectory_xyz_array[..., 2]
})
self.trajectory = Trajectory(self.model,
md_datum = datum,
data_frame = trajectory_df,
length_uom = length_uom,
well_name = well_name,
set_tangent_vectors = set_tangent_vectors)
self.trajectory_to_be_written = True
if create_feature_and_interp:
self.create_feature_and_interpretation()
def create_xml(self,
ext_uuid = None,
create_for_trajectory_if_needed = True,
add_as_part = True,
add_relationships = True,
title = None,
originator = None):
"""Create a blocked wellbore representation node from this BlockedWell object, optionally add as part.
note:
trajectory xml node must be in place before calling this function;
witsml log reference, interval stratigraphic units, and cell fluid phase units not yet supported
:meta common:
"""
assert self.trajectory is not None, 'trajectory object missing'
if ext_uuid is None:
ext_uuid = self.model.h5_uuid()
if title:
self.title = title
if not self.title:
self.title = 'blocked well'
if self.feature_to_be_written:
if self.wellbore_feature is None:
self.create_feature_and_interpretation()
self.wellbore_feature.create_xml(add_as_part = add_as_part, originator = originator)
if self.interpretation_to_be_written:
if self.wellbore_interpretation is None:
self.create_feature_and_interpretation()
self.wellbore_interpretation.create_xml(add_as_part = add_as_part,
title_suffix = None,
add_relationships = add_relationships,
originator = originator)
if create_for_trajectory_if_needed and self.trajectory_to_be_written and self.trajectory.root is None:
md_datum_root = self.trajectory.md_datum.create_xml(add_as_part = add_as_part,
add_relationships = add_relationships,
title = str(self.title),
originator = originator)
self.trajectory.create_xml(ext_uuid,
md_datum_root = md_datum_root,
add_as_part = add_as_part,
add_relationships = add_relationships,
title = title,
originator = originator)
assert self.trajectory.root is not None, 'trajectory xml not established'
bw_node = super().create_xml(title = title, originator = originator, add_as_part = False)
# wellbore frame elements
nc_node = rqet.SubElement(bw_node, ns['resqml2'] + 'NodeCount')
nc_node.set(ns['xsi'] + 'type', ns['xsd'] + 'positiveInteger')
nc_node.text = str(self.node_count)
mds_node = rqet.SubElement(bw_node, ns['resqml2'] + 'NodeMd')
mds_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'DoubleHdf5Array')
mds_node.text = rqet.null_xml_text
mds_values_node = rqet.SubElement(mds_node, ns['resqml2'] + 'Values')
mds_values_node.set(ns['xsi'] + 'type', ns['eml'] + 'Hdf5Dataset')
mds_values_node.text = rqet.null_xml_text
self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'NodeMd', root = mds_values_node)
traj_root = self.trajectory.root
self.model.create_ref_node('Trajectory',
rqet.find_nested_tags_text(traj_root, ['Citation', 'Title']),
bu.uuid_from_string(traj_root.attrib['uuid']),
content_type = 'obj_WellboreTrajectoryRepresentation',
root = bw_node)
# remaining blocked wellbore elements
cc_node = rqet.SubElement(bw_node, ns['resqml2'] + 'CellCount')
cc_node.set(ns['xsi'] + 'type', ns['xsd'] + 'nonNegativeInteger')
cc_node.text = str(self.cell_count)
cis_node = rqet.SubElement(bw_node, ns['resqml2'] + 'CellIndices')
cis_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'IntegerHdf5Array')
cis_node.text = rqet.null_xml_text
cnull_node = rqet.SubElement(cis_node, ns['resqml2'] + 'NullValue')
cnull_node.set(ns['xsi'] + 'type', ns['xsd'] + 'integer')
cnull_node.text = str(self.cellind_null)
cis_values_node = rqet.SubElement(cis_node, ns['resqml2'] + 'Values')
cis_values_node.set(ns['xsi'] + 'type', ns['eml'] + 'Hdf5Dataset')
cis_values_node.text = rqet.null_xml_text
self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'CellIndices', root = cis_values_node)
gis_node = rqet.SubElement(bw_node, ns['resqml2'] + 'GridIndices')
gis_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'IntegerHdf5Array')
gis_node.text = rqet.null_xml_text
gnull_node = rqet.SubElement(gis_node, ns['resqml2'] + 'NullValue')
gnull_node.set(ns['xsi'] + 'type', ns['xsd'] + 'integer')
gnull_node.text = str(self.gridind_null)
gis_values_node = rqet.SubElement(gis_node, ns['resqml2'] + 'Values')
gis_values_node.set(ns['xsi'] + 'type', ns['eml'] + 'Hdf5Dataset')
gis_values_node.text = rqet.null_xml_text
self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'GridIndices', root = gis_values_node)
fis_node = rqet.SubElement(bw_node, ns['resqml2'] + 'LocalFacePairPerCellIndices')
fis_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'IntegerHdf5Array')
fis_node.text = rqet.null_xml_text
fnull_node = rqet.SubElement(fis_node, ns['resqml2'] + 'NullValue')
fnull_node.set(ns['xsi'] + 'type', ns['xsd'] + 'integer')
fnull_node.text = str(self.facepair_null)
fis_values_node = rqet.SubElement(fis_node, ns['resqml2'] + 'Values')
fis_values_node.set(ns['xsi'] + 'type', ns['eml'] + 'Hdf5Dataset')
fis_values_node.text = rqet.null_xml_text
self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'LocalFacePairPerCellIndices', root = fis_values_node)
for grid in self.grid_list:
grid_root = grid.root
self.model.create_ref_node('Grid',
rqet.find_nested_tags_text(grid_root, ['Citation', 'Title']),
bu.uuid_from_string(grid_root.attrib['uuid']),
content_type = 'obj_IjkGridRepresentation',
root = bw_node)
interp_root = None
if self.wellbore_interpretation is not None:
interp_root = self.wellbore_interpretation.root
self.model.create_ref_node('RepresentedInterpretation',
rqet.find_nested_tags_text(interp_root, ['Citation', 'Title']),
bu.uuid_from_string(interp_root.attrib['uuid']),
content_type = 'obj_WellboreInterpretation',
root = bw_node)
if add_as_part:
self.model.add_part('obj_BlockedWellboreRepresentation', self.uuid, bw_node)
if add_relationships:
self.model.create_reciprocal_relationship(bw_node, 'destinationObject', self.trajectory.root,
'sourceObject')
for grid in self.grid_list:
self.model.create_reciprocal_relationship(bw_node, 'destinationObject', grid.root, 'sourceObject')
if interp_root is not None:
self.model.create_reciprocal_relationship(bw_node, 'destinationObject', interp_root, 'sourceObject')
ext_part = rqet.part_name_for_object('obj_EpcExternalPartReference', ext_uuid, prefixed = False)
ext_node = self.model.root_for_part(ext_part)
self.model.create_reciprocal_relationship(bw_node, 'mlToExternalPartProxy', ext_node,
'externalPartProxyToMl')
return bw_node
def write_hdf5(self, file_name = None, mode = 'a', create_for_trajectory_if_needed = True):
"""Create or append to an hdf5 file, writing datasets for the measured depths, grid, cell & face indices.
:meta common:
"""
# NB: array data must all have been set up prior to calling this function
if self.uuid is None:
self.uuid = bu.new_uuid()
h5_reg = rwh5.H5Register(self.model)
if create_for_trajectory_if_needed and self.trajectory_to_be_written:
self.trajectory.write_hdf5(file_name, mode = mode)
mode = 'a'
h5_reg.register_dataset(self.uuid, 'NodeMd', self.node_mds)
h5_reg.register_dataset(self.uuid, 'CellIndices', self.cell_indices) # could use int32?
h5_reg.register_dataset(self.uuid, 'GridIndices', self.grid_indices) # could use int32?
# convert face index pairs from [axis, polarity] back to strange local face numbering
mask = (self.face_pair_indices.flatten() == -1).reshape((-1, 2)) # 2nd axis is (axis, polarity)
masked_face_indices = np.where(mask, 0, self.face_pair_indices.reshape((-1, 2))) # 2nd axis is (axis, polarity)
# using flat array for raw_face_indices array
# other resqml writing code might use an array with one int per entry point and one per exit point, with 2nd axis as (entry, exit)
raw_face_indices = np.where(mask[:, 0], -1, self.face_index_map[masked_face_indices[:, 0],
masked_face_indices[:,
1]].flatten()).reshape(-1)
h5_reg.register_dataset(self.uuid, 'LocalFacePairPerCellIndices', raw_face_indices) # could use uint8?
h5_reg.write(file = file_name, mode = mode)
class WellboreMarkerFrame(BaseResqpy):
"""Class to handle RESQML WellBoreMarkerFrameRepresentation objects.
note:
measured depth data must be in same crs as those for the related trajectory
"""
resqml_type = 'WellboreMarkerFrameRepresentation'
def __init__(self,
parent_model,
wellbore_marker_frame_root = None,
uuid = None,
trajectory = None,
title = None,
originator = None,
extra_metadata = None):
"""Creates a new wellbore marker object and optionally loads it from xml, or trajectory, or Nexus wellspec file.
arguments:
parent_model (model.Model object): the model which the new blocked well belongs to
wellbore_marker_root (DEPRECATED): the root node of an xml tree representing the wellbore marker;
trajectory (optional, Trajectory object): the trajectory of the well, to be intersected with the grid;
not used if wellbore_marker_root is not None;
title (str, optional): the citation title to use for a new wellbore marker frame;
ignored if uuid or wellbore_marker_frame_root is not None
originator (str, optional): the name of the person creating the wellbore marker frame, defaults to login id;
ignored if uuid or wellbore_marker_frame_root is not None
extra_metadata (dict, optional): string key, value pairs to add as extra metadata for the wellbore marker frame;
ignored if uuid or wellbore_marker_frame_root is not None
returns:
the newly created wellbore framework marker object
"""
self.trajectory = None
self.node_count = None # number of measured depth nodes, each being for a marker
self.node_mds = None # node_count measured depths (in same units and datum as trajectory) of markers
self.wellbore_marker_list = [
] # list of markers, each: (marker UUID, geologic boundary, marker citation title, interp. object)
if self.trajectory is not None:
self.trajectory = trajectory
super().__init__(model = parent_model,
uuid = uuid,
title = title,
originator = originator,
extra_metadata = extra_metadata,
root_node = wellbore_marker_frame_root)
def get_trajectory_obj(self, trajectory_uuid):
"""Returns a trajectory object.
arguments:
trajectory_uuid (string or uuid.UUID): the uuid of the trajectory for which a Trajectory object is required
returns:
well.Trajectory object
note:
this method is not usually called directly
"""
if trajectory_uuid is None:
log.error('no trajectory was found')
return None
else:
# create new trajectory object
trajectory_root_node = self.model.root_for_uuid(trajectory_uuid)
assert trajectory_root_node is not None, 'referenced wellbore trajectory missing from model'
return Trajectory(self.model, trajectory_root = trajectory_root_node)
def get_interpretation_obj(self, interpretation_uuid, interp_type = None):
"""Creates an interpretation object; returns a horizon or fault interpretation object.
arguments:
interpretation_uiud (string or uuid.UUID): the uuid of the required interpretation object
interp_type (string, optional): 'HorizonInterpretation' or 'FaultInterpretation' (optionally
prefixed with `obj_`); if None, the type is inferred from the xml for the given uuid
returns:
organization.HorizonInterpretation or organization.FaultInterpretation object
note:
this method is not usually called directly
"""
assert interpretation_uuid is not None, 'interpretation uuid argument missing'
interpretation_root_node = self.model.root_for_uuid(interpretation_uuid)
if not interp_type:
interp_type = rqet.node_type(interpretation_root_node)
if not interp_type.startswith('obj_'):
interp_type = 'obj_' + interp_type
if interp_type == 'obj_HorizonInterpretation':
# create new horizon interpretation object
return rqo.HorizonInterpretation(self.model, root_node = interpretation_root_node)
elif interp_type == 'obj_FaultInterpretation':
# create new fault interpretation object
return rqo.FaultInterpretation(self.model, root_node = interpretation_root_node)
elif interp_type == 'obj_GeobodyInterpretation':
# create new geobody interpretation object
return rqo.GeobodyInterpretation(self.model, root_node = interpretation_root_node)
else:
# No interpretation for the marker
return None
# log.error('interpretation type not recognized: ' + str(interp_type))
def _load_from_xml(self):
"""Loads the wellbore marker frame object from an xml node (and associated hdf5 data).
note:
this method is not usually called directly
"""
wellbore_marker_frame_root = self.root
assert wellbore_marker_frame_root is not None
if self.trajectory is None:
self.trajectory = self.get_trajectory_obj(
rqet.find_nested_tags_text(wellbore_marker_frame_root, ['Trajectory', 'UUID']))
# list of Wellbore markers, each: (marker UUID, geologic boundary, marker citation title, interp. object)
self.wellbore_marker_list = []
for tag in rqet.list_of_tag(wellbore_marker_frame_root, 'WellboreMarker'):
interp_tag = rqet.content_type(rqet.find_nested_tags_text(tag, ['Interpretation', 'ContentType']))
if interp_tag is not None:
interp_obj = self.get_interpretation_obj(rqet.find_nested_tags_text(tag, ['Interpretation', 'UUID']),
interp_tag)
else:
interp_obj = None
self.wellbore_marker_list.append(
(str(rqet.uuid_for_part_root(tag)), rqet.find_tag_text(tag, 'GeologicBoundaryKind'),
rqet.find_nested_tags_text(tag, ['Citation', 'Title']), interp_obj))
self.node_count = rqet.find_tag_int(wellbore_marker_frame_root, 'NodeCount')
load_hdf5_array(self, rqet.find_tag(wellbore_marker_frame_root, 'NodeMd'), "node_mds", tag = 'Values')
if self.node_count != len(self.node_mds):
log.error('node count does not match hdf5 array')
if len(self.wellbore_marker_list) != self.node_count:
log.error('wellbore marker list does not contain correct node count')
def dataframe(self):
"""Returns a pandas dataframe with columns X, Y, Z, MD, Type, Surface, Well."""
# todo: handle fractures and geobody boundaries as well as horizons and faults
xyz = np.empty((self.node_count, 3))
type_list = []
surface_list = []
well_list = []
for i in range(self.node_count):
_, boundary_kind, title, interp = self.wellbore_marker_list[i]
if interp:
if boundary_kind == 'horizon':
feature_name = rqo.GeneticBoundaryFeature(self.model, root_node = interp.feature_root).feature_name
elif boundary_kind == 'fault':
feature_name = rqo.TectonicBoundaryFeature(self.model, root_node = interp.feature_root).feature_name
elif boundary_kind == 'geobody':
feature_name = rqo.GeneticBoundaryFeature(self.model, root_node = interp.feature_root).feature_name
else:
assert False, 'unexpected boundary kind'
else:
feature_name = title
boundary_kind = boundary_kind[0].upper() + boundary_kind[1:]
feature_name = '"' + feature_name + '"'
xyz[i] = self.trajectory.xyz_for_md(self.node_mds[i])
type_list.append(boundary_kind)
surface_list.append(feature_name)
if self.trajectory.wellbore_interpretation is None:
well_name = '"' + self.trajectory.title + '"' # todo: trace through wellbore interp to wellbore feature name
else:
well_name = '"' + self.trajectory.wellbore_interpretation.title + '"' # use wellbore_interpretation title instead, RMS exports have feature_name as "Wellbore feature"
# well_name = '"' + self.trajectory.wellbore_interpretation.wellbore_feature.feature_name + '"'
well_list.append(well_name)
return pd.DataFrame({
'X': xyz[:, 0],
'Y': xyz[:, 1],
'Z': xyz[:, 2],
'MD': self.node_mds,
'Type': type_list,
'Surface': surface_list,
'Well': well_list
})
def create_xml(self,
ext_uuid = None,
add_as_part = True,
add_relationships = True,
wellbore_marker_list = None,
title = 'wellbore marker framework',
originator = None):
assert type(add_as_part) is bool
if ext_uuid is None:
ext_uuid = self.model.h5_uuid()
wbm_node = super().create_xml(originator = originator, add_as_part = False)
nodeCount = rqet.SubElement(wbm_node, ns['resqml2'] + 'NodeCount')
nodeCount.set(ns['xsi'] + 'type', ns['xsd'] + 'positiveInteger')
nodeCount.text = str(self.node_count)
nodeMd = rqet.SubElement(wbm_node, ns['resqml2'] + 'NodeMd')
nodeMd.set(ns['xsi'] + 'type', ns['resqml2'] + 'DoubleHdf5Array')
nodeMd.text = rqet.null_xml_text
md_values_node = rqet.SubElement(nodeMd, ns['resqml2'] + 'Values')
md_values_node.set(ns['xsi'] + 'type', ns['resqml2'] + 'Hdf5Dataset')
md_values_node.text = rqet.null_xml_text
self.model.create_hdf5_dataset_ref(ext_uuid, self.uuid, 'mds', root = md_values_node)
if self.trajectory is not None:
traj_root = self.trajectory.root
self.model.create_ref_node('Trajectory',
rqet.find_tag(rqet.find_tag(traj_root, 'Citation'), 'Title').text,
bu.uuid_from_string(traj_root.attrib['uuid']),
content_type = 'obj_WellboreTrajectoryRepresentation',
root = wbm_node)
else:
log.error('trajectory object is missing and must be included')
# fill wellbore marker
for marker in self.wellbore_marker_list:
wbm_node_obj = self.model.new_obj_node('WellboreMarker', is_top_lvl_obj = False)
wbm_node_obj.set('uuid', marker[0])
wbm_node.append(wbm_node_obj)
wbm_gb_node = rqet.SubElement(wbm_node_obj, ns['resqml2'] + 'GeologicBoundaryKind')
wbm_gb_node.set(ns['xsi'] + 'type', ns['xsd'] + 'string')
wbm_gb_node.text = str(marker[1])
interp = marker[3]
if interp is not None:
interp_root = marker[3].root
if 'HorizonInterpretation' in str(type(marker[3])):
self.model.create_ref_node('Interpretation',
rqet.find_tag(rqet.find_tag(interp_root, 'Citation'), 'Title').text,
bu.uuid_from_string(interp_root.attrib['uuid']),
content_type = 'obj_HorizonInterpretation',
root = wbm_node_obj)
elif 'FaultInterpretation' in str(type(marker[3])):
self.model.create_ref_node('Interpretation',
rqet.find_tag(rqet.find_tag(interp_root, 'Citation'), 'Title').text,
bu.uuid_from_string(interp_root.attrib['uuid']),
content_type = 'obj_FaultInterpretation',
root = wbm_node_obj)
# add as part
if add_as_part:
self.model.add_part('obj_WellboreMarkerFrameRepresentation', self.uuid, wbm_node)
if add_relationships:
self.model.create_reciprocal_relationship(wbm_node, 'destinationObject', self.trajectory.root,
'sourceObject')
ext_part = rqet.part_name_for_object('obj_EpcExternalPartReference', ext_uuid, prefixed = False)
ext_node = self.model.root_for_part(ext_part)
self.model.create_reciprocal_relationship(wbm_node, 'mlToExternalPartProxy', ext_node,
'externalPartProxyToMl')
for marker in self.wellbore_marker_list:
self.model.create_reciprocal_relationship(wbm_node, 'destinationObject', marker[3].root,
'sourceObject')
return wbm_node
def write_hdf5(self, file_name = None, mode = 'a'):
"""Writes the hdf5 array associated with this object (the measured depth data).
arguments:
file_name (string): the name of the hdf5 file, or None, in which case the model's default will be used
mode (string, default 'a'): the write mode for the hdf5, either 'w' or 'a'
"""
h5_reg = rwh5.H5Register(self.model)
h5_reg.register_dataset(self.uuid, 'Mds', self.node_mds)
h5_reg.write(file = file_name, mode = mode)
def find_marker_from_interp(self, interpetation_obj = None, uuid = None):
"""Find wellbore marker by interpretation; can pass object or uuid.
arguments:
interpretation_obj (organize.HorizonInterpretation or organize.FaultInterpretation object, optional):
if present, the first (smallest md) marker relating to this interpretation object is returned
uuid (string or uuid.UUID): if present, the uuid of the interpretation object of interest; ignored if
interpretation_obj is not None
returns:
tuple, list of tuples or None; tuple is (marker UUID, geologic boundary, marker citation title, interp. object)
note:
if no arguments are passed, then a list of wellbore markers is returned;
if no marker is found for the interpretation object, None is returned
"""
if interpetation_obj is None and uuid is None:
return self.wellbore_marker_list
if interpetation_obj is not None:
uuid = interpetation_obj.uuid
for marker in self.wellbore_marker_list:
if bu.matching_uuids(marker[3].uuid, uuid):
return marker
return None
def get_marker_count(self):
"""Retruns number of wellbore markers."""
return len(self.wellbore_marker_list)
def find_marker_from_index(self, idx):
"""Returns wellbore marker by index."""
return self.wellbore_marker_list[idx - 1]
def add_las_to_trajectory(las: lasio.LASFile, trajectory, realization = None, check_well_name = False):
"""Creates a WellLogCollection and WellboreFrame from a LAS file.
Note:
In this current implementation, the first curve in the las object must be
Measured Depths, not e.g. TVDSS.
Arguments:
las: an lasio.LASFile object
trajectory: an instance of :class:`resqpy.well.Trajectory` .
realization (integer): if present, the single realisation (within an ensemble)
that this collection is for
check_well_name (bool): if True, raise warning if LAS well name does not match
existing wellborefeature citation title
Returns:
collection, well_frame: instances of :class:`resqpy.property.WellLogCollection`
and :class:`resqpy.well.WellboreFrame`
"""
# Lookup relevant related resqml parts
model = trajectory.model
well_interp = trajectory.wellbore_interpretation
well_title = well_interp.title
if check_well_name and well_title != las.well.WELL.value:
warnings.warn(f'LAS well title {las.well.WELL.value} does not match resqml tite {well_title}')
# Create a new wellbore frame, using depth data from first curve in las file
depth_values = np.array(las.index).copy()
assert isinstance(depth_values, np.ndarray)
las_depth_uom = bwam.rq_length_unit(las.curves[0].unit)
# Ensure depth units are correct
bwam.convert_lengths(depth_values, from_units = las_depth_uom, to_units = trajectory.md_uom)
assert len(depth_values) > 0
well_frame = WellboreFrame(
parent_model = model,
trajectory = trajectory,
mds = depth_values,
represented_interp = well_interp,
)
well_frame.write_hdf5()
well_frame.create_xml()
# Create a WellLogCollection in which to put logs
collection = rqp.WellLogCollection(frame = well_frame, realization = realization)
# Read in data from each curve in turn (skipping first curve which has depths)
for curve in las.curves[1:]:
collection.add_log(
title = curve.mnemonic,
data = curve.data,
unit = curve.unit,
realization = realization,
write = False,
)
collection.write_hdf5_for_imported_list()
collection.create_xml_for_imported_list_and_add_parts_to_model()
return collection, well_frame
def add_logs_from_cellio(blockedwell, cellio):
"""Creates a WellIntervalPropertyCollection for a given BlockedWell, using a given cell I/O file.
Arguments:
blockedwell: a resqml blockedwell object
cellio: an ascii file exported from RMS containing blocked well geometry and logs. Must contain columns i_index, j_index and k_index, plus additional columns for logs to be imported.
"""
# Get the initial variables from the blocked well
assert isinstance(blockedwell, BlockedWell), 'Not a blocked wellbore object'
collection = rqp.WellIntervalPropertyCollection(frame = blockedwell)
well_name = blockedwell.trajectory.title.split(" ")[0]
grid = blockedwell.model.grid()
# Read the cell I/O file to get the available columns (cols) and the data (data), and write into a dataframe
with open(cellio, 'r') as fp:
wellfound = False
cols, data = [], []
for line in fp.readlines():
if line == "\n":
wellfound = False # Blankline signifies end of well data
words = line.split()
if wellfound:
if len(words) > 2 and not words[0].isdigit():
cols.append(line)
else:
if len(words) > 9:
assert len(cols) == len(words), 'Number of columns found should match header of file'
data.append(words)
if len(words) == 3:
if words[0].upper() == well_name.upper():
wellfound = True
assert len(data) > 0 and len(cols) > 3, f"No data for well {well_name} found in file"
df = pd.DataFrame(data = data, columns = [x.split()[0] for x in cols])
df = df.apply(pd.to_numeric)
# Get the cell_indices from the grid for the given i/j/k
df['cell_indices'] = grid.natural_cell_indices(
np.array((df['k_index'] - 1, df['j_index'] - 1, df['i_index'] - 1), dtype = int).T)
df = df.drop(['i_index', 'j_index', 'k_index', 'x_in', 'y_in', 'z_in', 'x_out', 'y_out', 'z_out'], axis = 1)
assert (df['cell_indices'] == blockedwell.cell_indices
).all(), 'Cell indices do not match between blocked well and log inputs'
# Work out if the data columns are continuous, categorical or discrete
type_dict = {}
lookup_dict = {}
for col in cols:
words = col.split()
if words[0] not in ['i_index', 'j_index', 'k_index', 'x_in', 'y_in', 'z_in', 'x_out', 'y_out', 'z_out']:
if words[1] == 'unit1':
type_dict[words[0]] = 'continuous'
elif words[1] == 'DISC' and not words[0] == 'ZONES':
type_dict[words[0]] = 'categorical'
lookup_dict[words[0]] = lookup_from_cellio(col, blockedwell.model)
elif words[1] == 'param' or words[0] == 'ZONES':
type_dict[words[0]] = 'discrete'
else:
raise TypeError(f'unrecognised data type for {col}')
# Loop over the columns, adding them to the blockedwell property collection
for log in df.columns:
if log not in ['cell_indices']:
data_type = type_dict[log]
if log == 'ZONES':
data_type, dtype, null, discrete = 'discrete', int, -1, True
elif data_type == 'continuous':
dtype, null, discrete = float, np.nan, False
else:
dtype, null, discrete = int, -1, True
if data_type == 'categorical':
lookup_uuid = lookup_dict[log] # For categorical data, find or generate a StringLookupTable
else:
lookup_uuid = None
array_list = np.zeros((np.shape(blockedwell.grid_indices)), dtype = dtype)
vals = list(df[log])
for i, index in enumerate(blockedwell.cell_grid_link):
if index == -1:
assert blockedwell.grid_indices[i] == -1
array_list[i] = null
else:
if blockedwell.cell_indices[index] == list(df['cell_indices'])[index]:
array_list[i] = vals[index]
collection.add_cached_array_to_imported_list(
cached_array = array_list,
source_info = '',
keyword = f"{os.path.basename(cellio).split('.')[0]}.{blockedwell.trajectory.title}.{log}",
discrete = discrete,
uom = None,
property_kind = None,
facet = None,
null_value = null,
facet_type = None,
realization = None)
collection.write_hdf5_for_imported_list()
collection.create_xml_for_imported_list_and_add_parts_to_model(string_lookup_uuid = lookup_uuid)
def lookup_from_cellio(line, model):
"""Create a StringLookup Object from a cell I/O row containing a categorical column name and details.
Arguments:
line: a string from a cell I/O file, containing the column (log) name, type and categorical information
model: the model to add the StringTableLookup to
Returns:
uuid: the uuid of a StringTableLookup, either for a newly created table, or for an existing table if an identical one exists
"""
lookup_dict = {}
value, string = None, None
# Generate a dictionary of values and strings
for i, word in enumerate(line.split()):
if i == 0:
title = word
elif not i < 2:
if value is not None and string is not None:
lookup_dict[value] = string
value, string = None, None
if value is None:
value = int(word)
else:
if i == len(line.split()) - 1:
lookup_dict[value] = word
else:
string = word
# Check if a StringLookupTable already exists in the model, with the same name and values
for existing in model.parts_list_of_type('obj_StringTableLookup'):
table = rqp.StringLookup(parent_model = model, root_node = model.root_for_part(existing))
if table.title == title:
if table.str_dict == lookup_dict:
return table.uuid # If the exact table exists, reuse it by returning the uuid
# If no matching StringLookupTable exists, make a new one and return the uuid
lookup = rqp.StringLookup(parent_model = model, int_to_str_dict = lookup_dict, title = title)
lookup.create_xml(add_as_part = True)
return lookup.uuid
def add_wells_from_ascii_file(model,
crs_uuid,
trajectory_file,
comment_character = '#',
space_separated_instead_of_csv = False,
well_col = 'WELL',
md_col = 'MD',
x_col = 'X',
y_col = 'Y',
z_col = 'Z',
length_uom = 'm',
md_domain = None,
drilled = False):
"""Creates new md datum, trajectory, interpretation and feature objects for each well in an ascii file.
arguments:
crs_uuid (uuid.UUID): the unique identifier of the coordinate reference system applicable to the x,y,z data;
if None, a default crs will be created, making use of the length_uom and z_inc_down arguments
trajectory_file (string): the path of the ascii file holding the well trajectory data to be loaded
comment_character (string, default '#'): character deemed to introduce a comment in the trajectory file
space_separated_instead_of_csv (boolean, default False): if True, the columns in the trajectory file are space
separated; if False, comma separated
well_col (string, default 'WELL'): the heading for the column containing well names
md_col (string, default 'MD'): the heading for the column containing measured depths
x_col (string, default 'X'): the heading for the column containing X (usually easting) data
y_col (string, default 'Y'): the heading for the column containing Y (usually northing) data
z_col (string, default 'Z'): the heading for the column containing Z (depth or elevation) data
length_uom (string, default 'm'): the units of measure for the measured depths; should be 'm' or 'ft'
md_domain (string, optional): the source of the original deviation data; may be 'logger' or 'driller'
drilled (boolean, default False): True should be used for wells that have been drilled; False otherwise (planned,
proposed, or a location being studied)
z_inc_down (boolean, default True): indicates whether z values increase with depth; only used in the creation
of a default coordinate reference system; ignored if crs_uuid is not None
returns:
tuple of lists of objects: (feature_list, interpretation_list, trajectory_list, md_datum_list),
notes:
ascii file must be table with first line being column headers, with columns for WELL, MD, X, Y & Z;
actual column names can be set with optional arguments;
all the objects are added to the model, with array data being written to the hdf5 file for the trajectories;
the md_domain and drilled values are stored in the RESQML metadata but are only for human information and do not
generally affect computations
"""
assert md_col and x_col and y_col and z_col
md_col = str(md_col)
x_col = str(x_col)
y_col = str(y_col)
z_col = str(z_col)
if crs_uuid is None:
crs_uuid = model.crs_uuid
assert crs_uuid is not None, 'coordinate reference system not found when trying to add wells'
try:
df = pd.read_csv(trajectory_file,
comment = comment_character,
delim_whitespace = space_separated_instead_of_csv)
if df is None:
raise Exception
except Exception:
log.error('failed to read ascii deviation survey file: ' + str(trajectory_file))
raise
if well_col and well_col not in df.columns:
log.warning('well column ' + str(well_col) + ' not found in ascii trajectory file: ' + str(trajectory_file))
well_col = None
if well_col is None:
for col in df.columns:
if str(col).upper().startswith('WELL'):
well_col = str(col)
break
else:
well_col = str(well_col)
assert well_col
unique_wells = set(df[well_col])
if len(unique_wells) == 0:
log.warning('no well data found in ascii trajectory file: ' + str(trajectory_file))
# note: empty lists will be returned, below
feature_list = []
interpretation_list = []
trajectory_list = []
md_datum_list = []
for well_name in unique_wells:
log.debug('importing well: ' + str(well_name))
# create single well data frame (assumes measured depths increasing)
well_df = df[df[well_col] == well_name]
# create a measured depth datum for the well and add as part
first_row = well_df.iloc[0]
if first_row[md_col] == 0.0:
md_datum = MdDatum(model,
crs_uuid = crs_uuid,
location = (first_row[x_col], first_row[y_col], first_row[z_col]))
else:
md_datum = MdDatum(model, crs_uuid = crs_uuid,
location = (first_row[x_col], first_row[y_col], 0.0)) # sea level datum
md_datum.create_xml(title = str(well_name))
md_datum_list.append(md_datum)
# create a well feature and add as part
feature = rqo.WellboreFeature(model, feature_name = well_name)
feature.create_xml()
feature_list.append(feature)
# create interpretation and add as part
interpretation = rqo.WellboreInterpretation(model, is_drilled = drilled, wellbore_feature = feature)
interpretation.create_xml(title_suffix = None)
interpretation_list.append(interpretation)
# create trajectory, write arrays to hdf5 and add as part
trajectory = Trajectory(model,
md_datum = md_datum,
data_frame = well_df,
length_uom = length_uom,
md_domain = md_domain,
represented_interp = interpretation,
well_name = well_name)
trajectory.write_hdf5()
trajectory.create_xml(title = well_name)
trajectory_list.append(trajectory)
return (feature_list, interpretation_list, trajectory_list, md_datum_list)
def well_name(well_object, model = None):
"""Returns the 'best' citation title from the object or related well objects.
arguments:
well_object (object, uuid or root): Object for which a well name is required. Can be a
Trajectory, WellboreInterpretation, WellboreFeature, BlockedWell, WellboreMarkerFrame,
WellboreFrame, DeviationSurvey or MdDatum object
model (model.Model, optional): required if passing a uuid or root; not recommended otherwise
returns:
string being the 'best' citation title to serve as a well name, form the object or some related objects
note:
xml and relationships must be established for this function to work
"""
def better_root(model, root_a, root_b):
a = rqet.citation_title_for_node(root_a)
b = rqet.citation_title_for_node(root_b)
if a is None or len(a) == 0:
return root_b
if b is None or len(b) == 0:
return root_a
parts_like_a = model.parts(title = a)
parts_like_b = model.parts(title = b)
if len(parts_like_a) > 1 and len(parts_like_b) == 1:
return root_b
elif len(parts_like_b) > 1 and len(parts_like_a) == 1:
return root_a
a_digits = 0
for c in a:
if c.isdigit():
a_digits += 1
b_digits = 0
for c in b:
if c.isdigit():
b_digits += 1
if a_digits < b_digits:
return root_b
return root_a
def best_root(model, roots_list):
if len(roots_list) == 0:
return None
if len(roots_list) == 1:
return roots_list[0]
if len(roots_list) == 2:
return better_root(model, roots_list[0], roots_list[1])
return better_root(model, roots_list[0], best_root(model, roots_list[1:]))
def best_root_for_object(well_object, model = None):
if well_object is None:
return None
if model is None:
model = well_object.model
root_list = []
obj_root = None
obj_uuid = None
obj_type = None
traj_root = None
if isinstance(well_object, str):
obj_uuid = bu.uuid_from_string(well_object)
assert obj_uuid is not None, 'well_name string argument could not be interpreted as uuid'
well_object = obj_uuid
if isinstance(well_object, bu.uuid.UUID):
obj_uuid = well_object
obj_root = model.root_for_uuid(obj_uuid)
assert obj_root is not None, 'uuid not found in model when looking for well name'
obj_type = rqet.node_type(obj_root)
elif rqet.is_node(well_object):
obj_root = well_object
obj_type = rqet.node_type(obj_root)
obj_uuid = rqet.uuid_for_part_root(obj_root)
elif isinstance(well_object, Trajectory):
obj_type = 'WellboreTrajectoryRepresentation'
traj_root = well_object.root
elif isinstance(well_object, rqo.WellboreFeature):
obj_type = 'WellboreFeature'
elif isinstance(well_object, rqo.WellboreInterpretation):
obj_type = 'WellboreInterpretation'
elif isinstance(well_object, BlockedWell):
obj_type = 'BlockedWellboreRepresentation'
if well_object.trajectory is not None:
traj_root = well_object.trajectory.root
elif isinstance(well_object, WellboreMarkerFrame): # note: trajectory might be None
obj_type = 'WellboreMarkerFrameRepresentation'
if well_object.trajectory is not None:
traj_root = well_object.trajectory.root
elif isinstance(well_object, WellboreFrame): # note: trajectory might be None
obj_type = 'WellboreFrameRepresentation'
if well_object.trajectory is not None:
traj_root = well_object.trajectory.root
elif isinstance(well_object, DeviationSurvey):
obj_type = 'DeviationSurveyRepresentation'
elif isinstance(well_object, MdDatum):
obj_type = 'MdDatum'
assert obj_type is not None, 'argument type not recognized for well_name'
if obj_type.startswith('obj_'):
obj_type = obj_type[4:]
if obj_uuid is None:
obj_uuid = well_object.uuid
obj_root = model.root_for_uuid(obj_uuid)
if obj_type == 'WellboreFeature':
interp_parts = model.parts(obj_type = 'WellboreInterpretation')
interp_parts = model.parts_list_filtered_by_related_uuid(interp_parts, obj_uuid)
all_parts = interp_parts
all_traj_parts = model.parts(obj_type = 'WellboreTrajectoryRepresentation')
if interp_parts is not None:
for part in interp_parts:
traj_parts = model.parts_list_filtered_by_related_uuid(all_traj_parts, model.uuid_for_part(part))
all_parts += traj_parts
if all_parts is not None:
root_list = [model.root_for_part(part) for part in all_parts]
elif obj_type == 'WellboreInterpretation':
feat_roots = model.roots(obj_type = 'WellboreFeature', related_uuid = obj_uuid) # should return one root
traj_roots = model.roots(obj_type = 'WellboreTrajectoryRepresentation', related_uuid = obj_uuid)
root_list = feat_roots + traj_roots
elif obj_type == 'WellboreTrajectoryRepresentation':
interp_parts = model.parts(obj_type = 'WellboreInterpretation')
interp_parts = model.parts_list_filtered_by_related_uuid(interp_parts, obj_uuid)
all_parts = interp_parts
all_feat_parts = model.parts(obj_type = 'WellboreFeature')
if interp_parts is not None:
for part in interp_parts:
feat_parts = model.parts_list_filtered_by_related_uuid(all_feat_parts, model.uuid_for_part(part))
all_parts += feat_parts
if all_parts is not None:
root_list = [model.root_for_part(part) for part in all_parts]
elif obj_type in [
'BlockedWellboreRepresentation', 'WellboreMarkerFrameRepresentation', 'WellboreFrameRepresentation'
]:
if traj_root is None:
traj_root = model.root(obj_type = 'WellboreTrajectoryRepresentation', related_uuid = obj_uuid)
root_list = [best_root_for_object(traj_root, model = model)]
elif obj_type == 'DeviationSurveyRepresentation':
root_list = [best_root_for_object(model.root(obj_type = 'MdDatum', related_uuid = obj_uuid), model = model)]
elif obj_type == 'MdDatum':
pass
root_list.append(obj_root)
return best_root(model, root_list)
return rqet.citation_title_for_node(best_root_for_object(well_object, model = model))
def add_blocked_wells_from_wellspec(model, grid, wellspec_file):
"""Add a blocked well for each well in a Nexus WELLSPEC file.
arguments:
model (model.Model object): model to which blocked wells are added
grid (grid.Grid object): grid against which wellspec data will be interpreted
wellspec_file (string): path of ascii file holding Nexus WELLSPEC keyword and data
returns:
int: count of number of blocked wells created
notes:
this function appends to the hdf5 file and creates xml for the blocked wells (but does not store epc);
'simulation' trajectory and measured depth datum objects will also be created
"""
well_list_dict = wsk.load_wellspecs(wellspec_file, column_list = None)
count = 0
for well in well_list_dict:
log.info('processing well: ' + str(well))
bw = BlockedWell(model,
grid = grid,
wellspec_file = wellspec_file,
well_name = well,
check_grid_name = True,
use_face_centres = True)
if not bw.node_count: # failed to load from wellspec, eg. because of no perforations in grid
log.warning('no wellspec data loaded for well: ' + str(well))
continue
bw.write_hdf5(model.h5_file_name(), mode = 'a', create_for_trajectory_if_needed = True)
bw.create_xml(model.h5_uuid(), title = well)
count += 1
log.info(f'{count} blocked wells created based on wellspec file: {wellspec_file}')
def extract_xyz(xyz_node):
"""Extracts an x,y,z coordinate from a solitary point xml node.
argument:
xyz_node: the xml node representing the solitary point (in 3D space)
returns:
triple float: (x, y, z) coordinates as a tuple
"""
if xyz_node is None:
return None
xyz = np.zeros(3)
for axis in range(3):
xyz[axis] = rqet.find_tag_float(xyz_node, 'Coordinate' + str(axis + 1), must_exist = True)
return tuple(xyz)
def well_names_in_cellio_file(cellio_file):
"""Returns a list of well names as found in the RMS blocked well export cell I/O file."""
well_list = []
with open(cellio_file, 'r') as fp:
while True:
kf.skip_blank_lines_and_comments(fp)
line = fp.readline() # file format version number?
if line == '':
break # end of file
fp.readline() # 'Undefined'
words = fp.readline().split()
assert len(words), 'missing header info (well name) in cell I/O file'
well_list.append(words[0])
while not kf.blank_line(fp):
fp.readline() # skip to block of data for next well
return well_list
# 'private' functions
def load_hdf5_array(object, node, array_attribute, tag = 'Values', dtype = 'float', model = None):
"""Loads the property array data as an attribute of object, from the hdf5 referenced in xml node.
:meta private:
"""
assert (rqet.node_type(node) in ['DoubleHdf5Array', 'IntegerHdf5Array', 'Point3dHdf5Array'])
if model is None:
model = object.model
h5_key_pair = model.h5_uuid_and_path_for_node(node, tag = tag)
if h5_key_pair is None:
return None
return model.h5_array_element(h5_key_pair,
index = None,
cache_array = True,
dtype = dtype,
object = object,
array_attribute = array_attribute)
def find_entry_and_exit(cp, entry_vector, exit_vector, well_name):
"""Returns (entry_axis, entry_polarity, entry_xyz, exit_axis, exit_polarity, exit_xyz).
:meta private:
"""
cell_centre = np.mean(cp, axis = (0, 1, 2))
face_triangles = gf.triangles_for_cell_faces(cp).reshape(-1, 3, 3) # flattened first index 4 values per face
entry_points = intersect.line_triangles_intersects(cell_centre, entry_vector, face_triangles, line_segment = True)
entry_axis = entry_polarity = entry_xyz = exit_xyz = None
for t in range(24):
if not np.any(np.isnan(entry_points[t])):
entry_xyz = entry_points[t]
entry_axis = t // 8
entry_polarity = (t - 8 * entry_axis) // 4
break
assert entry_axis is not None, 'failed to find entry face for a perforation in well ' + str(well_name)
exit_points = intersect.line_triangles_intersects(cell_centre, exit_vector, face_triangles, line_segment = True)
exit_axis = exit_polarity = None
for t in range(24):
if not np.any(np.isnan(exit_points[t])):
exit_xyz = entry_points[t]
exit_axis = t // 8
exit_polarity = (t - 8 * exit_axis) // 4
break
assert exit_axis is not None, 'failed to find exit face for a perforation in well ' + str(well_name)
return (entry_axis, entry_polarity, entry_xyz, exit_axis, exit_polarity, exit_xyz)
def _as_optional_array(arr):
"""If not None, cast as numpy array.
Casting directly to an array can be problematic: np.array(None) creates an unsized array, which is potentially
confusing.
"""
if arr is None:
return None
else:
return np.array(arr)
def _pl(i, e = False):
return '' if i == 1 else 'es' if e else 's'
|
#!/usr/bin/env python3
"""
Defines the SeEpub class, the master class for representing and operating on
Standard Ebooks epub3 files.
"""
import base64
import datetime
import os
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Union
from sys import getsizeof
import git
from lxml import etree
from natsort import natsorted
import regex
import se
import se.easy_xml
import se.formatting
import se.images
class GitCommit:
"""
Object used to represent the last Git commit.
"""
short_sha = ""
timestamp = None
def __init__(self, short_sha: str, timestamp: datetime.datetime):
self.short_sha = short_sha
self.timestamp = timestamp
class Endnote:
"""
Class to hold information on endnotes
"""
def __init__(self):
self.node = None
self.number = 0
self.anchor = ""
self.contents = [] # The strings and tags inside an <li> element
self.back_link = ""
self.source_file = ""
self.matched = False
class SeEpub:
"""
An object representing an SE epub file.
An SE epub can have various operations performed on it, including recomposing and linting.
"""
path: Path = Path() # The path to the base of the ebook repo, i.e., a folder containing ./images/ and ./src/
epub_root_path = Path() # The path to the epub source root, i.e. self.path / src
content_path: Path = Path() # The path to the epub content base, i.e. self.epub_root_path / epub
metadata_file_path: Path = Path() # The path to the metadata file, i.e. self.content_path / content.opf
toc_path: Path = Path() # The path to the metadata file, i.e. self.content_path / toc.xhtml
local_css = ""
is_se_ebook = True
_file_cache: Dict[str, str] = {}
_dom_cache: Dict[str, se.easy_xml.EasyXmlTree] = {}
_generated_identifier = None
_generated_github_repo_url = None
_repo = None # git.Repo object
_last_commit = None # GitCommit object
_endnotes: Optional[List[Endnote]] = None # List of Endnote objects
_endnotes_path = None
_cover_path = None
_spine_file_paths: Optional[List[Path]] = None # List of Path objects
def __init__(self, epub_root_directory: Union[str, Path]):
try:
self.path = Path(epub_root_directory).resolve()
if not self.path.is_dir():
raise Exception
except Exception as ex:
raise se.InvalidSeEbookException(f"Not a directory: [path][link=file://{self.path}]{self.path}[/][/].") from ex
# Decide if this is an SE epub, or a white-label epub
# SE epubs have a ./src dir and the identifier looks like an SE identifier
if (self.path / "src" / "META-INF" / "container.xml").is_file():
self.epub_root_path = self.path / "src"
else:
self.epub_root_path = self.path
self.is_se_ebook = False
try:
container_tree = self.get_dom(self.epub_root_path / "META-INF" / "container.xml")
self.metadata_file_path = self.epub_root_path / container_tree.xpath("/container/rootfiles/rootfile[@media-type=\"application/oebps-package+xml\"]/@full-path")[0]
except Exception as ex:
raise se.InvalidSeEbookException("Target doesn’t appear to be an epub: no [path]container.xml[/] or no metadata file.") from ex
self.content_path = self.metadata_file_path.parent
try:
self.metadata_dom = self.get_dom(self.metadata_file_path)
except Exception as ex:
raise se.InvalidXmlException(f"Couldn’t parse [path][link=file://{self.metadata_file_path}]{self.metadata_file_path}[/][/]. Exception: {ex}") from ex
toc_href = self.metadata_dom.xpath("/package/manifest/item[contains(@properties, 'nav')]/@href", True)
if toc_href:
self.toc_path = self.content_path / toc_href
else:
raise se.InvalidSeEbookException("Couldn’t find table of contents.")
# If our identifier isn't SE-style, we're not an SE ebook
identifier = self.metadata_dom.xpath("/package/metadata/dc:identifier/text()", True)
if not identifier or not identifier.startswith("url:https://standardebooks.org/ebooks/"):
self.is_se_ebook = False
@property
def cover_path(self):
"""
Accessor
"""
if not self._cover_path:
for file_href in self.metadata_dom.xpath("/package/manifest/item[contains(@properties, 'cover-image')]/@href"):
self._cover_path = self.content_path / file_href
return self._cover_path
@property
def endnotes_path(self):
"""
Accessor
"""
if not self._endnotes_path:
for file_path in self.content_path.glob("**/*.xhtml"):
dom = self.get_dom(file_path)
if dom.xpath("/html/body/section[contains(@epub:type, 'endnotes')]"):
self._endnotes_path = file_path
break
return self._endnotes_path
@property
def repo(self) -> git.Repo:
"""
Accessor
"""
if not self._repo:
try:
self._repo = git.Repo(self.path)
except Exception as ex:
raise se.InvalidSeEbookException("Couldn’t access this ebook’s Git repository.") from ex
return self._repo
@property
def last_commit(self) -> Optional[GitCommit]:
"""
Accessor
"""
if not self._last_commit:
# We use git command instead of using gitpython's commit object because we want the short hash
try:
# We have to clear this environmental variable or else GitPython will think the repo is "." instead
# of the dir we actually pass, if we're called from a git hook (like post-receive).
# See https://stackoverflow.com/questions/42328426/gitpython-not-working-from-git-hook
if "GIT_DIR" in os.environ:
del os.environ["GIT_DIR"]
git_command = git.cmd.Git(self.path)
output = git_command.show("-s", "--format=%h %ct", "HEAD").split()
self._last_commit = GitCommit(output[0], datetime.datetime.fromtimestamp(int(output[1]), datetime.timezone.utc))
except Exception:
self._last_commit = None
return self._last_commit
@property
def generated_identifier(self) -> str:
"""
Accessor
Generate an SE identifer based on the metadata in the metadata file.
"""
if not self._generated_identifier:
identifier = "url:https://standardebooks.org/ebooks/"
if not self.is_se_ebook:
identifier = ""
for publisher in self.metadata_dom.xpath("/package/metadata/dc:publisher"):
identifier += se.formatting.make_url_safe(publisher.text) + "_"
# Add authors
authors = []
for author in self.metadata_dom.xpath("/package/metadata/dc:creator"):
authors.append(author.text)
identifier += se.formatting.make_url_safe(author.text) + "_"
identifier = identifier.strip("_") + "/"
# Add title
for title in self.metadata_dom.xpath("/package/metadata/dc:title[@id=\"title\"]"):
identifier += se.formatting.make_url_safe(title.text) + "/"
# For contributors, we add both translators and illustrators.
# However, we may not include specific translators or illustrators in certain cases, namely
# if *some* contributors have a `display-seq` property, and others do not.
# According to the epub spec, if that is the case, we should only add those that *do* have the attribute.
# By SE convention, any contributor with `display-seq == 0` will be excluded from the identifier string.
translators = []
illustrators = []
translators_have_display_seq = False
illustrators_have_display_seq = False
for role in self.metadata_dom.xpath("/package/metadata/meta[@property='role' or @property='se:role']"):
contributor_id = role.get_attr("refines").lstrip("#")
contributor_element = self.metadata_dom.xpath("/package/metadata/dc:contributor[@id=\"" + contributor_id + "\"]")
if contributor_element:
contributor = {"name": contributor_element[0].text, "include": True, "display_seq": None}
display_seq = self.metadata_dom.xpath("/package/metadata/meta[@property=\"display-seq\"][@refines=\"#" + contributor_id + "\"]")
if display_seq and int(display_seq[0].text) == 0:
contributor["include"] = False
display_seq = []
if role.text == "trl":
if display_seq:
contributor["display_seq"] = display_seq[0]
translators_have_display_seq = True
translators.append(contributor)
if role.text == "ill":
if display_seq:
contributor["display_seq"] = display_seq[0]
illustrators_have_display_seq = True
illustrators.append(contributor)
for translator in translators:
if (not translators_have_display_seq and translator["include"]) or translator["display_seq"]:
identifier += se.formatting.make_url_safe(translator["name"]) + "_"
if translators:
identifier = identifier.strip("_") + "/"
for illustrator in illustrators:
include_illustrator = True
# If the translator is also the illustrator, don't include them twice
for translator in translators:
if illustrator["name"] == translator["name"]:
include_illustrator = False
break
if (include_illustrator and not illustrators_have_display_seq and illustrator["include"]) or illustrator["display_seq"]:
identifier += se.formatting.make_url_safe(illustrator["name"]) + "_"
identifier = identifier.strip("_/")
self._generated_identifier = identifier
return self._generated_identifier
@property
def generated_github_repo_url(self) -> str:
"""
Accessor
Generate a GitHub repository URL based on the *generated* SE identifier,
*not* the SE identifier in the metadata file.
INPUTS
None
OUTPUTS
A string representing the GitHub repository URL (capped at maximum 100 characters).
"""
if not self._generated_github_repo_url:
self._generated_github_repo_url = "https://github.com/standardebooks/" + self.generated_identifier.replace("url:https://standardebooks.org/ebooks/", "").replace("/", "_")[0:100]
return self._generated_github_repo_url
@property
def endnotes(self) -> list:
"""
Accessor
Return a list of Endnote objects representing the endnotes file for this ebook.
INPUTS
None
OUTPUTS
A list of Endnote objects representing the endnotes file for this ebook.
"""
if not self._endnotes:
self._endnotes = []
dom = self.get_dom(self.endnotes_path)
for node in dom.xpath("/html/body/section[contains(@epub:type, 'endnotes')]/ol/li[contains(@epub:type, 'endnote')]"):
note = Endnote()
note.node = node
try:
note.number = int(node.get_attr("id").replace("note-", ""))
except ValueError:
note.number = 0
note.contents = node.xpath("./*")
note.anchor = node.get_attr("id") or ""
for back_link in node.xpath(".//a[contains(@epub:type, 'backlink')]/@href"):
note.back_link = back_link
if not note.back_link:
raise se.InvalidInputException(f"No backlink found in note {note.anchor} in existing endnotes file.")
self._endnotes.append(note)
return self._endnotes
@property
def spine_file_paths(self) -> List[Path]:
"""
Reads the spine from the metadata file to obtain a list of content files, in the order wanted for the ToC.
It assumes this has already been manually ordered by the producer.
INPUTS:
None
OUTPUTS:
list of content files paths in the order given in the spine in the metadata file
"""
if not self._spine_file_paths:
self._spine_file_paths = []
for idref in self.metadata_dom.xpath("/package/spine/itemref/@idref"):
try:
self._spine_file_paths.append(self.content_path / self.metadata_dom.xpath(f"/package/manifest/item[@id='{idref}']/@href", True))
except Exception as ex:
raise se.InvalidSeEbookException(f"Couldn’t find spine item: {idref}") from ex
return self._spine_file_paths
def get_file(self, file_path: Path) -> str:
"""
Get raw file contents of a file in the epub.
Contents are cached so that we don't hit the disk repeatedly
INPUTS
file_path: A Path pointing to the file
OUTPUTS
A string representing the file contents
"""
file_path_str = str(file_path)
if file_path_str not in self._file_cache:
with open(file_path, "r", encoding="utf-8") as file:
file_contents = file.read()
self._file_cache[file_path_str] = file_contents
return self._file_cache[file_path_str]
def flush_dom_cache_entry(self, file_path: Path) -> None:
"""
Remove a dom cache entry for the given file, regardless of whether comments were removed.
INPUTS
file_path: A Path pointing to the file
"""
keys_to_delete = []
for key in self._dom_cache:
if key.startswith(str(file_path)):
keys_to_delete.append(key)
for key in keys_to_delete:
del self._dom_cache[key]
try:
del self._file_cache[str(file_path)]
except:
pass
# Cache dom objects so we don't have to create them multiple times
def get_dom(self, file_path: Path, remove_comments=False) -> se.easy_xml.EasyXmlTree:
"""
Get an EasyXmlTree DOM object for a given file.
Contents are cached so that we don't hit the disk or re-parse DOMs repeatedly
INPUTS
file_path: A Path pointing to the file
OUTPUTS
A string representing the file contents
"""
file_path_str = str(file_path) + "_" + str(remove_comments)
if file_path_str not in self._dom_cache:
file_contents = self.get_file(file_path)
try:
self._dom_cache[file_path_str] = se.easy_xml.EasyXmlTree(file_contents)
# Remove comments
if remove_comments:
for node in self._dom_cache[file_path_str].xpath("//comment()"):
node.remove()
except etree.XMLSyntaxError as ex:
raise se.InvalidXhtmlException(f"Couldn’t parse XML in [path][link=file://{file_path.resolve()}]{file_path}[/][/]. Exception: {ex}") from ex
except FileNotFoundError as ex:
raise ex
except se.InvalidXmlException as ex:
raise se.InvalidXhtmlException(f"Couldn’t parse XML in [path][link=file://{file_path.resolve()}]{file_path}[/][/]. Exception: {ex.__cause__}") from ex
except Exception as ex:
raise se.InvalidXhtmlException(f"Couldn’t parse XML in [path][link=file://{file_path.resolve()}]{file_path}[/][/].") from ex
return self._dom_cache[file_path_str]
def _recompose_xhtml(self, section: se.easy_xml.EasyXmlElement, output_dom: se.easy_xml.EasyXmlTree) -> None:
"""
Helper function used in self.recompose()
Recursive function for recomposing a series of XHTML files into a single XHTML file.
INPUTS
section: An EasyXmlElement to inspect
output_dom: A EasyXmlTree representing the entire output dom
OUTPUTS
None
"""
# Quick sanity check before we begin
if not section.get_attr("id") or (section.parent.tag.lower() != "body" and not section.parent.get_attr("id")):
raise se.InvalidXhtmlException("Section without [attr]id[/] attribute.")
if section.parent.tag.lower() == "body":
section.set_attr("epub:type", f"{section.get_attr("epub:type")} {section.parent.get_attr("epub:type")}".strip())
# Try to find our parent tag in the output, by ID.
# If it's not in the output, then append it to the tag's closest parent by ID (or <body>), then iterate over its children and do the same.
existing_section = output_dom.xpath(f"//*[@id='{section.get_attr("id")}']")
if not existing_section:
if section.parent.tag.lower() == "body":
output_dom.xpath("/html/body")[0].append(section)
else:
output_dom.xpath(f"//*[@id='{section.parent.get_attr("id")}']")[0].append(section)
existing_section = output_dom.xpath(f"//*[@id='{section.get_attr("id")}']")
# Convert all <img> references to inline base64
# We even convert SVGs instead of inlining them, because CSS won't allow us to style inlined SVGs
# (for example if we want to apply max-width or filter: invert())
for img in section.xpath("//img[starts-with(@src, '../images/')]"):
src = img.get_attr("src").replace("../", "")
with open(self.content_path / src, "rb") as binary_file:
image_contents_base64 = base64.b64encode(binary_file.read()).decode()
if src.endswith(".svg"):
img.set_attr("src", f"data:image/svg+xml;base64, {image_contents_base64}")
if src.endswith(".jpg"):
img.set_attr("src", f"data:image/jpg;base64, {image_contents_base64}")
if src.endswith(".png"):
img.set_attr("src", f"data:image/png;base64, {image_contents_base64}")
for child in section.xpath("./*"):
if child.tag in ("section", "article"):
self._recompose_xhtml(child, output_dom)
else:
existing_section.append(child)
def recompose(self, output_xhtml5: bool, extra_css_file: Path = None) -> str:
"""
Iterate over the XHTML files in this epub and "recompose" them into a single XHTML string representing this ebook.
INPUTS
output_xhtml5: true to output XHTML5 instead of HTML5
OUTPUTS
A string of HTML5 representing the entire recomposed ebook.
"""
# Get some header data: title, core and local css
title = self.metadata_dom.xpath("/package/metadata/dc:title/text()")[0]
language = self.metadata_dom.xpath("/package/metadata/dc:language/text()")[0]
css = ""
namespaces: List[str] = []
css_filenames = ["core.css", "se.css", "local.css"]
if extra_css_file:
css_filenames.append(str(extra_css_file))
for filename in css_filenames:
filepath = self.content_path / "css" / filename
file_css = self.get_file(filepath)
namespaces = namespaces + regex.findall(r"@namespace.+?;", file_css)
file_css = regex.sub(r"\s*@(charset|namespace).+?;\s*", "\n", file_css).strip()
css = css + f"\n\n\n/* {filepath.name} */\n" + file_css
css = css.strip()
namespaces = list(set(namespaces))
if namespaces:
css = "\n" + css
for namespace in namespaces:
css = namespace + "\n" + css
css = "\t\t\t".join(css.splitlines(True)) + "\n"
# Remove min-height from CSS since it doesn't really apply to the single page format.
# It occurs at least in se.css
css = regex.sub(r"\s*min-height: [^;]+?;", "", css)
# Remove -epub-* CSS as it's invalid in a browser context
css = regex.sub(r"\s*\-epub\-[^;]+?;", "", css)
output_xhtml = f"<?xml version=\"1.0\" encoding=\"utf-8\"?><html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\" epub:prefix=\"z3998: http://www.daisy.org/z3998/2012/vocab/structure/, se: https://standardebooks.org/vocab/1.0\" xml:lang=\"{language}\"><head><meta charset=\"utf-8\"/><title>{title}</title><style/></head><body></body></html>"
output_dom = se.formatting.EasyXmlTree(output_xhtml)
output_dom.is_css_applied = True # We will apply CSS recursively to nodes that will be attached to output_dom, so set the bit here
# Iterate over spine items in order and recompose them into our output
needs_wrapper_css = False
for file_path in self.spine_file_paths:
dom = self.get_dom(file_path)
# Apply the stylesheet to see if we have `position: absolute` on any items. If so, apply `position: relative` to its closest <section> ancestor
# See https://standardebooks.org/ebooks/jean-toomer/cane for an example of this in action
dom.apply_css(css)
# Select deepest sections or articles with id attributes that have ONLY figure or img children, and one of those children has position: absolute
for node in dom.xpath("/html/body//*[@id and (name() = 'section' or name = 'article') and not(.//*[(name() = 'section' or name() = 'article') and not(preceding-sibling::* or following-sibling::*)]) and count(./*[(name() = 'figure' or name() = 'img')]) = count(./*) and .//*[(name() = 'figure' or name() = 'img') and @data-css-position = 'absolute']]"):
needs_wrapper_css = True
# Wrap the sections in a div that we style later
wrapper_element = etree.SubElement(node.lxml_element, "div")
wrapper_element.set("class", "positioning-wrapper")
for child in node.xpath("./*[(name() = 'figure' or name() = 'img')]"):
wrapper_element.append(child.lxml_element) # .append() will *move* the element to the end of wrapper_element
# Now, recompose the children
for node in dom.xpath("/html/body/*"):
try:
self._recompose_xhtml(node, output_dom)
except se.SeException as ex:
raise se.SeException(f"[path][link=file://{file_path}]{file_path}[/][/]: {ex}") from ex
# Did we add wrappers? If so add the CSS
# We also have to give the wrapper a height, because it may have siblings that were recomposed in from other files
if needs_wrapper_css:
css = css + "\n\t\t\t.positioning-wrapper{\n\t\t\t\tposition: relative; height: 100vh;\n\t\t\t}\n"
# Add the ToC after the titlepage
toc_dom = self.get_dom(self.toc_path)
titlepage_node = output_dom.xpath("//*[contains(concat(' ', @epub:type, ' '), ' titlepage ')]")[0]
for node in toc_dom.xpath("//nav[1]"):
titlepage_node.lxml_element.addnext(node.lxml_element)
# Replace all <a href> links with internal links
for link in output_dom.xpath("//a[not(re:test(@href, '^https?://')) and contains(@href, '#')]"):
link.set_attr("href", regex.sub(r".+(#.+)$", r"\1", link.get_attr("href")))
# Replace all <a href> links to entire files
for link in output_dom.xpath("//a[not(re:test(@href, '^https?://')) and not(contains(@href, '#'))]"):
href = link.get_attr("href")
href = regex.sub(r".+/([^/]+)$", r"#\1", href)
href = regex.sub(r"\.xhtml$", "", href)
link.set_attr("href", href)
for node in output_dom.xpath("/html/body//a[re:test(@href, '^(\\.\\./)?text/(.+?)\\.xhtml$')]"):
node.set_attr("href", regex.sub(r"(\.\./)?text/(.+?)\.xhtml", r"#\2", node.get_attr("href")))
for node in output_dom.xpath("/html/body//a[re:test(@href, '^(\\.\\./)?text/.+?\\.xhtml#(.+?)$')]"):
node.set_attr("href", regex.sub(r"(\.\./)?text/.+?\.xhtml#(.+?)", r"#\2", node.get_attr("href")))
# Make some compatibility adjustments
if output_xhtml5:
for node in output_dom.xpath("/html/head/meta[@charset]"):
node.remove()
for node in output_dom.xpath("//*[@xml:lang]"):
node.set_attr("lang", node.get_attr("xml:lang"))
else:
for node in output_dom.xpath("/html[@epub:prefix]"):
node.remove_attr("epub:prefix")
for node in output_dom.xpath("//*[@xml:lang]"):
node.set_attr("lang", node.get_attr("xml:lang"))
node.remove_attr("xml:lang")
for node in output_dom.xpath("//*[@epub:type]"):
node.set_attr("data-epub-type", node.get_attr("epub:type"))
node.remove_attr("epub:type")
# Get the output XHTML as a string
output_xhtml = output_dom.to_string()
# All done, clean the output
# Very large files like Ulysses S. Grant's memoirs or Through the Looking Glass will crash lxml due to their size.
# The inlined SVGs get too big.
# So, if the byte size of the XHTML string is larger than an arbitrary size, don't pretty print the output.
# Pepys is about 20,000,000 bytes
if getsizeof(output_xhtml) < 100000000:
output_xhtml = se.formatting.format_xhtml(output_xhtml)
# Insert our CSS. We do this after `clean` because `clean` will escape > in the CSS
output_xhtml = regex.sub(r"<style/>", "<style><![CDATA[\n\t\t\t" + css + "\t\t]]></style>", output_xhtml)
if output_xhtml5:
output_xhtml = output_xhtml.replace("\t\t<style/>\n", "")
# Re-add a doctype
output_xhtml = output_xhtml.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE html>")
else:
# Remove xml declaration and re-add the doctype
output_xhtml = regex.sub(r"<\?xml.+?\?>", "<!doctype html>", output_xhtml)
# Remove CDATA
output_xhtml = output_xhtml.replace("<![CDATA[", "")
output_xhtml = output_xhtml.replace("]]>", "")
# Make some replacements for HTML5 compatibility
output_xhtml = output_xhtml.replace("epub|type", "data-epub-type")
output_xhtml = regex.sub(r" xmlns.+?=\".+?\"", "", output_xhtml)
return output_xhtml
def generate_titlepage_svg(self) -> None:
"""
Generate a distributable titlepage SVG in ./src/epub/images/ based on the titlepage file in ./images/
INPUTS
None
OUTPUTS
None.
"""
source_images_directory = self.path / "images"
source_titlepage_svg_filename = source_images_directory / "titlepage.svg"
dest_images_directory = self.content_path / "images"
dest_titlepage_svg_filename = dest_images_directory / "titlepage.svg"
if source_titlepage_svg_filename.is_file():
# Convert text to paths
se.images.svg_text_to_paths(source_titlepage_svg_filename, dest_titlepage_svg_filename)
def generate_cover_svg(self) -> None:
"""
Generate a distributable cover SVG in ./src/epub/images/ based on the cover file in ./images/
INPUTS
None
OUTPUTS
None.
"""
source_images_directory = self.path / "images"
source_cover_jpg_filename = source_images_directory / "cover.jpg"
source_cover_svg_filename = source_images_directory / "cover.svg"
dest_images_directory = self.content_path / "images"
dest_cover_svg_filename = self.cover_path
# Create output directory if it doesn't exist
dest_images_directory.mkdir(parents=True, exist_ok=True)
if source_cover_jpg_filename.is_file() and source_cover_svg_filename.is_file():
# base64 encode cover.jpg
with open(source_cover_jpg_filename, "rb") as binary_file:
source_cover_jpg_base64 = base64.b64encode(binary_file.read()).decode()
# Convert text to paths
if source_cover_svg_filename.is_file():
se.images.svg_text_to_paths(source_cover_svg_filename, dest_cover_svg_filename, remove_style=False)
# Embed cover.jpg
dom = self.get_dom(dest_cover_svg_filename)
# Embed the file
for node in dom.xpath("//*[re:test(@xlink:href, 'cover\\.jpg$')]"):
node.set_attr("xlink:href", "data:image/jpeg;base64," + source_cover_jpg_base64)
# For the cover we want to keep the path.title-box style, and add an additional
# style to color our new paths white
for node in dom.xpath("/svg/style"):
node.set_text("\n\t\tpath{\n\t\t\tfill: #fff;\n\t\t}\n\n\t\t.title-box{\n\t\t\tfill: #000;\n\t\t\tfill-opacity: .75;\n\t\t}\n\t")
with open(dest_cover_svg_filename, "w", encoding="utf-8") as file:
file.write(dom.to_string())
def shift_endnotes(self, target_endnote_number: int, step: int = 1) -> None:
"""
Shift endnotes starting at target_endnote_number.
INPUTS:
target_endnote_number: The endnote to start shifting at
step: 1 to increment or -1 to decrement
OUTPUTS:
None.
"""
increment = step > 0
endnote_count = 0
if step == 0:
return
dom = self.get_dom(self.endnotes_path)
endnote_count = len(dom.xpath("//li[contains(@epub:type, 'endnote')]"))
if increment:
# Range is from COUNT -> target_endnote_number
note_range = range(endnote_count, target_endnote_number - 1, -1)
else:
# Range is from target_endnote_number -> COUNT
note_range = range(target_endnote_number, endnote_count + 1, 1)
for endnote_number in note_range:
new_endnote_number = endnote_number + step
# Update all the actual endnotes in the endnotes file
for node in dom.xpath(f"/html/body//li[contains(@epub:type, 'endnote') and @id='note-{endnote_number}']"):
node.set_attr("id", f"note-{new_endnote_number}")
# Update all backlinks in the endnotes file
for node in dom.xpath(f"/html/body//a[re:test(@href, '#noteref-{endnote_number}$')]"):
node.set_attr("href", node.get_attr("href").replace(f"#noteref-{endnote_number}", f"#noteref-{new_endnote_number}"))
# Write the endnotes file
try:
with open(self.endnotes_path, "w", encoding="utf-8") as file:
file.write(dom.to_string())
except Exception as ex:
raise se.InvalidSeEbookException(f"Couldn’t open endnotes file: [path][link=file://{self.endnotes_path}]{self.endnotes_path}[/][/].") from ex
# Now update endnotes in all other files. We also do a pass over the endnotes file itself.
# again just in case there are endnotes within endnotes.
for file_path in self.content_path.glob("**/*.xhtml"):
dom = self.get_dom(file_path)
for endnote_number in note_range:
new_endnote_number = endnote_number + step
# We don't use an xpath matching epub:type="noteref" because we can have hrefs that are not noterefs pointing to endnotes (like "see here")
for node in dom.xpath(f"/html/body//a[re:test(@href, '(endnotes\\.xhtml)?#note-{endnote_number}$')]"):
# Update the `id` attribute of the link, if we have one (sometimes hrefs point to endnotes but they are not noterefs themselves)
if node.get_attr("id"):
# Use a regex instead of just replacing the entire ID so that we don't mess up IDs that do not fit this pattern
node.set_attr("id", regex.sub(r"noteref-\d+$", f"noteref-{new_endnote_number}", node.get_attr("id")))
node.set_attr("href", regex.sub(fr"#note-{endnote_number}$", f"#note-{new_endnote_number}", node.get_attr("href")))
node.set_text(regex.sub(fr"\b{endnote_number}\b", f"{new_endnote_number}", node.text))
with open(file_path, "w", encoding="utf-8") as file:
file.write(dom.to_string())
def set_release_timestamp(self) -> None:
"""
If this ebook has not yet been released, set the first release timestamp in the metadata file.
"""
if self.metadata_dom.xpath("/package/metadata/dc:date[text() = '1900-01-01T00:00:00Z']"):
now = datetime.datetime.utcnow()
now_iso = regex.sub(r"\.[0-9]+$", "", now.isoformat()) + "Z"
now_iso = regex.sub(r"\+.+?Z$", "Z", now_iso)
now_friendly = f"{now:%B %e, %Y, %l:%M <abbr class=\"eoc\">%p</abbr>}"
now_friendly = regex.sub(r"\s+", " ", now_friendly).replace("AM", "a.m.").replace("PM", "p.m.").replace(" <abbr", " <abbr")
for node in self.metadata_dom.xpath("/package/metadata/dc:date"):
node.set_text(now_iso)
for node in self.metadata_dom.xpath("/package/metadata/meta[@property='dcterms:modified']"):
node.set_text(now_iso)
with open(self.metadata_file_path, "w", encoding="utf-8") as file:
file.write(self.metadata_dom.to_string())
for file_path in self.content_path.glob("**/*.xhtml"):
dom = self.get_dom(file_path)
if dom.xpath("/html/body/section[contains(@epub:type, 'colophon')]"):
for node in dom.xpath("/html/body/section[contains(@epub:type, 'colophon')]//b[contains(text(), 'January 1, 1900')]"):
node.replace_with(se.easy_xml.EasyXmlElement(etree.fromstring(str.encode("<b>" + now_friendly + "</b>"))))
with open(file_path, "w", encoding="utf-8") as file:
file.write(dom.to_string())
def update_flesch_reading_ease(self) -> None:
"""
Calculate a new reading ease for this ebook and update the metadata file.
Ignores SE boilerplate files like the imprint.
INPUTS
None
OUTPUTS
None.
"""
text = ""
for filename in se.get_target_filenames([self.path], ".xhtml"):
xhtml = self.get_file(filename)
is_ignored, _ = se.get_dom_if_not_ignored(xhtml, ["colophon", "titlepage", "imprint", "copyright-page", "halftitlepage", "toc", "loi"])
if not is_ignored:
text += xhtml
for node in self.metadata_dom.xpath("/package/metadata/meta[@property='se:reading-ease.flesch']"):
node.set_text(str(se.formatting.get_flesch_reading_ease(text)))
with open(self.metadata_file_path, "w", encoding="utf-8") as file:
file.write(self.metadata_dom.to_string())
def get_word_count(self) -> int:
"""
Calculate the word count of this ebook.
Ignores SE boilerplate files like the imprint, as well as any endnotes.
INPUTS
None
OUTPUTS
The number of words in the ebook.
"""
word_count = 0
for filename in se.get_target_filenames([self.path], ".xhtml"):
xhtml = self.get_file(filename)
is_ignored, _ = se.get_dom_if_not_ignored(xhtml, ["colophon", "titlepage", "imprint", "copyright-page", "halftitlepage", "toc", "loi", "endnotes"])
if not is_ignored:
word_count += se.formatting.get_word_count(xhtml)
return word_count
def update_word_count(self) -> None:
"""
Calculate a new word count for this ebook and update the metadata file.
Ignores SE boilerplate files like the imprint, as well as any endnotes.
INPUTS
None
OUTPUTS
None.
"""
for node in self.metadata_dom.xpath("/package/metadata/meta[@property='se:word-count']"):
node.set_text(str(self.get_word_count()))
with open(self.metadata_file_path, "r+", encoding="utf-8") as file:
file.seek(0)
file.write(self.metadata_dom.to_string())
file.truncate()
def generate_manifest(self) -> se.easy_xml.EasyXmlElement:
"""
Return the <manifest> element for this ebook as an EasyXmlElement.
INPUTS
None
OUTPUTS
An EasyXmlElement representing the manifest.
"""
manifest = []
for file_path in self.content_path.glob("**/*"):
if file_path.name == self.metadata_file_path.name:
# Don't add the metadata file to the manifest
continue
if file_path.stem.startswith("."):
# Skip dotfiles
continue
mime_type = None
properties = []
if file_path.suffix == ".css":
mime_type="text/css"
if file_path.suffix in (".ttf", ".otf", ".woff", ".woff2"):
mime_type="application/vnd.ms-opentype"
if file_path.suffix == ".svg":
mime_type = "image/svg+xml"
if file_path.suffix == ".png":
mime_type = "image/png"
if file_path.suffix == ".jpg":
mime_type = "image/jpeg"
if file_path.stem == "cover":
properties.append("cover-image")
if file_path.suffix == ".xhtml":
dom = self.get_dom(file_path)
mime_type = "application/xhtml+xml"
# the `glossary` semantic may also appear in the ToC landmarks, so specifically exclude that
if dom.xpath("//*[contains(@epub:type, 'glossary') and not(ancestor-or-self::nav)]"):
properties.append("glossary")
#if dom.xpath("/html/body//*[namespace-uri()='http://www.w3.org/1998/Math/MathML']"):
if dom.xpath("/html[namespace::*='http://www.w3.org/1998/Math/MathML']"):
properties.append("mathml")
if dom.xpath("//img[re:test(@src, '\\.svg$')]"):
properties.append("svg")
if dom.xpath("//nav[contains(@epub:type, 'toc')]"):
properties.append("nav")
if file_path.suffix == ".xml":
dom = self.get_dom(file_path)
# Do we have a glossary search key map?
if dom.xpath("/search-key-map"):
mime_type = "application/vnd.epub.search-key-map+xml"
properties.append("glossary")
properties.append("search-key-map")
if mime_type:
# Put together any properties we have
properties_attr = ""
for prop in properties:
properties_attr += prop + " "
properties_attr = properties_attr.strip()
if properties_attr:
properties_attr = f" properties=\"{properties_attr}\""
# Add the manifest item
# Replace the path separator because if run on Windows we will get the wrong slash direction from pathlib
manifest.append(f"""<item href="{str(file_path.relative_to(self.content_path)).replace(os.sep, "/")}" id="{file_path.name}" media-type="{mime_type}"{properties_attr}/>""")
manifest = natsorted(manifest)
# Assemble the manifest XML string
manifest_xml = "<manifest>\n"
for line in manifest:
manifest_xml = manifest_xml + "\t" + line + "\n"
manifest_xml = manifest_xml + "</manifest>"
return se.easy_xml.EasyXmlElement(etree.fromstring(str.encode(manifest_xml)))
def __add_to_spine(self, spine: List[str], items: List[Path], semantic: str) -> Tuple[List[str], List[Path]]:
"""
Given a spine and a list of items, add the item to the spine if it contains the specified semantic.
If an item is added to the spine, remove it from the original list.
Returns an updated spine and item list.
"""
filtered_items = []
spine_additions = []
for file_path in items:
dom = self.get_dom(file_path)
# Match against \b because we might have `titlepage` and `halftitlepage`
if dom.xpath(f"/html/body//section[re:test(@epub:type, '\\b{semantic}\\b')]"):
spine_additions.append(file_path.name)
else:
filtered_items.append(file_path)
# Sort the additions, for example if we have more than one dedication or introduction
spine_additions = natsorted(spine_additions)
return (spine + spine_additions, filtered_items)
def generate_spine(self) -> se.easy_xml.EasyXmlElement:
"""
Return the <spine> element of this ebook as an EasyXmlElement, with a best guess as to the correct order. Manual review is required.
INPUTS
None
OUTPUTS
An EasyXmlElement representing the spine.
"""
spine: List[str] = []
frontmatter = []
bodymatter = []
backmatter = []
for file_path in self.content_path.glob("**/*.xhtml"):
dom = self.get_dom(file_path)
# Exclude the ToC from the spine
if dom.xpath("/html/body//nav[contains(@epub:type, 'toc')]"):
continue
if dom.xpath("/html/*[contains(@epub:type, 'frontmatter')]"):
frontmatter.append(file_path)
elif dom.xpath("/html/*[contains(@epub:type, 'backmatter')]"):
backmatter.append(file_path)
else:
bodymatter.append(file_path)
# Add frontmatter
spine, frontmatter = self.__add_to_spine(spine, frontmatter, "titlepage")
spine, frontmatter = self.__add_to_spine(spine, frontmatter, "imprint")
spine, frontmatter = self.__add_to_spine(spine, frontmatter, "dedication")
spine, frontmatter = self.__add_to_spine(spine, frontmatter, "preamble")
spine, frontmatter = self.__add_to_spine(spine, frontmatter, "introduction")
spine, frontmatter = self.__add_to_spine(spine, frontmatter, "foreword")
spine, frontmatter = self.__add_to_spine(spine, frontmatter, "preface")
spine, frontmatter = self.__add_to_spine(spine, frontmatter, "epigraph")
spine, frontmatter = self.__add_to_spine(spine, frontmatter, "z3998:dramatis-personae")
spine, frontmatter = self.__add_to_spine(spine, frontmatter, "halftitlepage")
# Add any remaining frontmatter
spine = spine + natsorted([file_path.name for file_path in frontmatter])
# Add bodymatter
spine, bodymatter = self.__add_to_spine(spine, bodymatter, "prologue")
spine = spine + natsorted([file_path.name for file_path in bodymatter])
# Add backmatter
spine, backmatter = self.__add_to_spine(spine, backmatter, "afterword")
spine, backmatter = self.__add_to_spine(spine, backmatter, "appendix")
spine, backmatter = self.__add_to_spine(spine, backmatter, "glossary")
spine, backmatter = self.__add_to_spine(spine, backmatter, "endnotes")
spine, backmatter = self.__add_to_spine(spine, backmatter, "loi")
spine, backmatter = self.__add_to_spine(spine, backmatter, "colophon")
spine, backmatter = self.__add_to_spine(spine, backmatter, "copyright-page")
# Add any remaining backmatter
spine = spine + natsorted([file_path.name for file_path in backmatter])
# Now build the spine output
spine_xml = "<spine>\n"
for filename in spine:
spine_xml = spine_xml + f"""\t<itemref idref="{filename}"/>\n"""
spine_xml = spine_xml + "</spine>"
return se.easy_xml.EasyXmlElement(etree.fromstring(str.encode(spine_xml)))
def get_work_type(self) -> str:
"""
Returns either "fiction" or "non-fiction", based on analysis of se:subjects in the metadata file
INPUTS:
None
OUTPUTS:
The fiction or non-fiction type
"""
worktype = "fiction" # default
subjects = self.metadata_dom.xpath("/package/metadata/meta[@property='se:subject']/text()")
if not subjects:
return worktype
# Unfortunately, some works are tagged "Philosophy" but are nevertheless fiction, so we have to double-check
if "Nonfiction" in subjects:
return "non-fiction"
nonfiction_types = ["Autobiography", "Memoir", "Philosophy", "Spirituality", "Travel"]
for nonfiction_type in nonfiction_types:
if nonfiction_type in subjects:
worktype = "non-fiction"
fiction_types = ["Fantasy", "Fiction", "Horror", "Mystery", "Science Fiction"]
for fiction_type in fiction_types:
if fiction_type in subjects:
worktype = "fiction"
return worktype
def get_work_title(self) -> str:
"""
Returns the title of the book from the metadata file, which we assume has already been correctly completed.
INPUTS:
None
OUTPUTS:
Either the title of the book or the default WORKING_TITLE
"""
return self.metadata_dom.xpath("/package/metadata/dc:title/text()", True) or "WORK_TITLE"
def lint(self, skip_lint_ignore: bool, allowed_messages: List[str] = None) -> list:
"""
The lint() function is very big so for readability and maintainability
it's broken out to a separate file. Strictly speaking that file can be inlined
into this class.
"""
from se.se_epub_lint import lint # pylint: disable=import-outside-toplevel
return lint(self, skip_lint_ignore, allowed_messages)
def build(self, run_epubcheck: bool, check_only: bool, build_kobo: bool, build_kindle: bool, output_directory: Path, proof: bool) -> None:
"""
The build() function is very big so for readability and maintainability
it's broken out to a separate file. Strictly speaking that file can be inlined
into this class.
"""
from se.se_epub_build import build # pylint: disable=import-outside-toplevel
build(self, run_epubcheck, check_only, build_kobo, build_kindle, output_directory, proof)
def generate_toc(self) -> str:
"""
The generate_toc() function is very big so for readability and maintainability
it's broken out to a separate file. Strictly speaking that file can be inlined
into this class.
"""
from se.se_epub_generate_toc import generate_toc # pylint: disable=import-outside-toplevel
toc_xhtml = generate_toc(self)
# Word joiners and nbsp don't go in the ToC
toc_xhtml = toc_xhtml.replace(se.WORD_JOINER, "")
toc_xhtml = toc_xhtml.replace(se.NO_BREAK_SPACE, " ")
return toc_xhtml
def _check_endnotes(self) -> list:
"""
Initial check to see if all note references in the body have matching endnotes
in endnotes.xhtml and no duplicates.
Returns string of failures if any. If these are empty, all was well.
"""
missing = []
duplicates = []
orphans = []
references = []
response = []
for file_path in self.spine_file_paths:
dom = self.get_dom(file_path)
for link in dom.xpath("/html/body//a[contains(@epub:type, 'noteref')]"):
anchor = ""
href = link.get_attr("href") or ""
if href:
# Extract just the anchor from a URL (ie, what follows a hash symbol)
hash_position = href.find("#") + 1 # we want the characters AFTER the hash
if hash_position > 0:
anchor = href[hash_position:]
references.append(anchor) # keep these for later reverse check
# Now try to find anchor in endnotes
match_anchor = lambda x, old=anchor: x.anchor == old
matches = list(filter(match_anchor, self.endnotes))
if not matches:
missing.append(anchor)
if len(matches) > 1:
duplicates.append(anchor)
for miss in missing:
response.append(f"Missing endnote with anchor: {miss}")
for dupe in duplicates:
response.append(f"Duplicate endnotes with anchor: {dupe}")
# reverse check: look for orphaned endnotes
for note in self.endnotes:
# try to find it in our references collection
if note.anchor not in references:
orphans.append(note.anchor)
for orphan in orphans:
response.append(f"Orphan endnote with anchor: {orphan}")
return response
def recreate_endnotes(self) -> None:
"""
Renumber all noterefs starting from 1, and renumber all endnotes starting from 1.
Does not perform any sanity checks or do any rearranging; may result in more noterefs than endnotes, or more endnotes than noterefs.
Changes are written to disk.
"""
noteref_locations = {}
current_note_number = 1
# Renumber all noterefs starting from 1
for file_path in self.spine_file_paths:
dom = self.get_dom(file_path)
for node in dom.xpath("/html/body//a[contains(@epub:type, 'noteref')]"):
node.set_attr("href", f"endnotes.xhtml#note-{current_note_number}")
node.set_attr("id", f"noteref-{current_note_number}")
node.set_text(str(current_note_number))
noteref_locations[current_note_number] = file_path
current_note_number += 1
with open(file_path, "w") as file:
file.write(dom.to_string())
# Renumber all endnotes starting from 1
current_note_number = 1
endnotes_dom = self.get_dom(self.endnotes_path)
for node in endnotes_dom.xpath("/html/body//li[contains(@epub:type, 'endnote')]"):
node.set_attr("id", f"note-{current_note_number}")
for backlink in node.xpath(".//a[contains(@epub:type, 'backlink')]"):
filename = noteref_locations[current_note_number].name if current_note_number in noteref_locations else ""
backlink.set_attr("href", f"{filename}#noteref-{current_note_number}")
current_note_number += 1
with open(self.endnotes_path, "w") as file:
file.write(endnotes_dom.to_string())
def generate_endnotes(self) -> Tuple[int, int]:
"""
Read the epub spine to regenerate all endnotes in order of appearance, starting from 1.
Changes are written to disk.
Returns a tuple of (found_endnote_count, changed_endnote_count)
"""
# Do a safety check first, throw exception if it failed
results = self._check_endnotes()
if results:
report = "\n".join(results)
raise se.InvalidInputException(f"Endnote error(s) found: {report}.")
# If we get here, it's safe to proceed
processed = 0
current_note_number = 1
notes_changed = 0
change_list: List[str] = []
for file_path in self.spine_file_paths:
dom = self.get_dom(file_path)
# Skip the actual endnotes file, we'll handle that later
if dom.xpath("/html/body//*[contains(@epub:type, 'endnotes')]"):
continue
processed += 1
needs_rewrite = False
for link in dom.xpath("/html/body//a[contains(@epub:type, 'noteref')]"):
needs_rewrite, notes_changed = self.__process_link(change_list, current_note_number, file_path.name, link, needs_rewrite, notes_changed)
current_note_number += 1
# If we need to write back the body text file
if needs_rewrite:
with open(file_path, "w") as file:
file.write(se.formatting.format_xhtml(dom.to_string()))
# Now process any endnotes WITHIN the endnotes
for source_note in self.endnotes:
node = source_note.node
needs_rewrite = False
for link in node.xpath(".//a[contains(@epub:type, 'noteref')]"):
needs_rewrite, notes_changed = self.__process_link(change_list, current_note_number, self.endnotes_path.name, link, needs_rewrite, notes_changed)
current_note_number += 1
if processed == 0:
raise se.InvalidInputException("No files processed. Did you update the manifest and order the spine?")
if notes_changed > 0:
# Now we need to recreate the endnotes file
endnotes_dom = self.get_dom(self.endnotes_path)
for ol_node in endnotes_dom.xpath("/html/body/section[contains(@epub:type, 'endnotes')]/ol[1]"):
for node in ol_node.xpath("./li[contains(@epub:type, 'endnote')]"):
node.remove()
self.endnotes.sort(key=lambda endnote: endnote.number)
for endnote in self.endnotes:
if endnote.matched:
endnote.node.set_attr("id", f"note-{endnote.number}")
for node in endnote.node.xpath(".//a[contains(@epub:type, 'backlink')]"):
node.set_attr("href", f"{endnote.source_file}#noteref-{endnote.number}")
ol_node.append(endnote.node)
with open(self.endnotes_path, "w") as file:
file.write(se.formatting.format_xhtml(endnotes_dom.to_string()))
return current_note_number - 1, notes_changed
def __process_link(self, change_list, current_note_number, file_name, link, needs_rewrite, notes_changed) -> Tuple[bool, int]:
"""
Checks each endnote link to see if the existing anchor needs to be updated with a new number
Returns a tuple of needs_write (whether object needs to be re-written), and the number of notes_changed
"""
old_anchor = ""
href = link.get_attr("href") or ""
if href:
# Extract just the anchor from a URL (ie, what follows a hash symbol)
hash_position = href.find("#") + 1 # we want the characters AFTER the hash
if hash_position > 0:
old_anchor = href[hash_position:]
new_anchor = f"note-{current_note_number:d}"
if new_anchor != old_anchor:
change_list.append(f"Changed {old_anchor} to {new_anchor} in {file_name}")
notes_changed += 1
# Update the link in the dom
link.set_attr("href", f"{self.endnotes_path.name}#{new_anchor}")
link.set_attr("id", f"noteref-{current_note_number:d}")
link.lxml_element.text = str(current_note_number)
needs_rewrite = True
# Now try to find this in endnotes
match_old = lambda x, old=old_anchor: x.anchor == old
matches = list(filter(match_old, self.endnotes))
if not matches:
raise se.InvalidInputException(f"Couldn’t find endnote with anchor [attr]{old_anchor}[/].")
if len(matches) > 1:
raise se.InvalidInputException(f"Duplicate anchors in endnotes file for anchor [attr]{old_anchor}[/].")
# Found a single match, which is what we want
endnote = matches[0]
endnote.number = current_note_number
endnote.matched = True
# We don't change the anchor or the back ref just yet
endnote.source_file = file_name
return needs_rewrite, notes_changed
| #!/usr/bin/env python3
"""
Defines the SeEpub class, the master class for representing and operating on
Standard Ebooks epub3 files.
"""
import base64
import datetime
import os
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Union
from sys import getsizeof
import git
from lxml import etree
from natsort import natsorted
import regex
import se
import se.easy_xml
import se.formatting
import se.images
class GitCommit:
"""
Object used to represent the last Git commit.
"""
short_sha = ""
timestamp = None
def __init__(self, short_sha: str, timestamp: datetime.datetime):
self.short_sha = short_sha
self.timestamp = timestamp
class Endnote:
"""
Class to hold information on endnotes
"""
def __init__(self):
self.node = None
self.number = 0
self.anchor = ""
self.contents = [] # The strings and tags inside an <li> element
self.back_link = ""
self.source_file = ""
self.matched = False
class SeEpub:
"""
An object representing an SE epub file.
An SE epub can have various operations performed on it, including recomposing and linting.
"""
path: Path = Path() # The path to the base of the ebook repo, i.e., a folder containing ./images/ and ./src/
epub_root_path = Path() # The path to the epub source root, i.e. self.path / src
content_path: Path = Path() # The path to the epub content base, i.e. self.epub_root_path / epub
metadata_file_path: Path = Path() # The path to the metadata file, i.e. self.content_path / content.opf
toc_path: Path = Path() # The path to the metadata file, i.e. self.content_path / toc.xhtml
local_css = ""
is_se_ebook = True
_file_cache: Dict[str, str] = {}
_dom_cache: Dict[str, se.easy_xml.EasyXmlTree] = {}
_generated_identifier = None
_generated_github_repo_url = None
_repo = None # git.Repo object
_last_commit = None # GitCommit object
_endnotes: Optional[List[Endnote]] = None # List of Endnote objects
_endnotes_path = None
_cover_path = None
_spine_file_paths: Optional[List[Path]] = None # List of Path objects
def __init__(self, epub_root_directory: Union[str, Path]):
try:
self.path = Path(epub_root_directory).resolve()
if not self.path.is_dir():
raise Exception
except Exception as ex:
raise se.InvalidSeEbookException(f"Not a directory: [path][link=file://{self.path}]{self.path}[/][/].") from ex
# Decide if this is an SE epub, or a white-label epub
# SE epubs have a ./src dir and the identifier looks like an SE identifier
if (self.path / "src" / "META-INF" / "container.xml").is_file():
self.epub_root_path = self.path / "src"
else:
self.epub_root_path = self.path
self.is_se_ebook = False
try:
container_tree = self.get_dom(self.epub_root_path / "META-INF" / "container.xml")
self.metadata_file_path = self.epub_root_path / container_tree.xpath("/container/rootfiles/rootfile[@media-type=\"application/oebps-package+xml\"]/@full-path")[0]
except Exception as ex:
raise se.InvalidSeEbookException("Target doesn’t appear to be an epub: no [path]container.xml[/] or no metadata file.") from ex
self.content_path = self.metadata_file_path.parent
try:
self.metadata_dom = self.get_dom(self.metadata_file_path)
except Exception as ex:
raise se.InvalidXmlException(f"Couldn’t parse [path][link=file://{self.metadata_file_path}]{self.metadata_file_path}[/][/]. Exception: {ex}") from ex
toc_href = self.metadata_dom.xpath("/package/manifest/item[contains(@properties, 'nav')]/@href", True)
if toc_href:
self.toc_path = self.content_path / toc_href
else:
raise se.InvalidSeEbookException("Couldn’t find table of contents.")
# If our identifier isn't SE-style, we're not an SE ebook
identifier = self.metadata_dom.xpath("/package/metadata/dc:identifier/text()", True)
if not identifier or not identifier.startswith("url:https://standardebooks.org/ebooks/"):
self.is_se_ebook = False
@property
def cover_path(self):
"""
Accessor
"""
if not self._cover_path:
for file_href in self.metadata_dom.xpath("/package/manifest/item[contains(@properties, 'cover-image')]/@href"):
self._cover_path = self.content_path / file_href
return self._cover_path
@property
def endnotes_path(self):
"""
Accessor
"""
if not self._endnotes_path:
for file_path in self.content_path.glob("**/*.xhtml"):
dom = self.get_dom(file_path)
if dom.xpath("/html/body/section[contains(@epub:type, 'endnotes')]"):
self._endnotes_path = file_path
break
return self._endnotes_path
@property
def repo(self) -> git.Repo:
"""
Accessor
"""
if not self._repo:
try:
self._repo = git.Repo(self.path)
except Exception as ex:
raise se.InvalidSeEbookException("Couldn’t access this ebook’s Git repository.") from ex
return self._repo
@property
def last_commit(self) -> Optional[GitCommit]:
"""
Accessor
"""
if not self._last_commit:
# We use git command instead of using gitpython's commit object because we want the short hash
try:
# We have to clear this environmental variable or else GitPython will think the repo is "." instead
# of the dir we actually pass, if we're called from a git hook (like post-receive).
# See https://stackoverflow.com/questions/42328426/gitpython-not-working-from-git-hook
if "GIT_DIR" in os.environ:
del os.environ["GIT_DIR"]
git_command = git.cmd.Git(self.path)
output = git_command.show("-s", "--format=%h %ct", "HEAD").split()
self._last_commit = GitCommit(output[0], datetime.datetime.fromtimestamp(int(output[1]), datetime.timezone.utc))
except Exception:
self._last_commit = None
return self._last_commit
@property
def generated_identifier(self) -> str:
"""
Accessor
Generate an SE identifer based on the metadata in the metadata file.
"""
if not self._generated_identifier:
identifier = "url:https://standardebooks.org/ebooks/"
if not self.is_se_ebook:
identifier = ""
for publisher in self.metadata_dom.xpath("/package/metadata/dc:publisher"):
identifier += se.formatting.make_url_safe(publisher.text) + "_"
# Add authors
authors = []
for author in self.metadata_dom.xpath("/package/metadata/dc:creator"):
authors.append(author.text)
identifier += se.formatting.make_url_safe(author.text) + "_"
identifier = identifier.strip("_") + "/"
# Add title
for title in self.metadata_dom.xpath("/package/metadata/dc:title[@id=\"title\"]"):
identifier += se.formatting.make_url_safe(title.text) + "/"
# For contributors, we add both translators and illustrators.
# However, we may not include specific translators or illustrators in certain cases, namely
# if *some* contributors have a `display-seq` property, and others do not.
# According to the epub spec, if that is the case, we should only add those that *do* have the attribute.
# By SE convention, any contributor with `display-seq == 0` will be excluded from the identifier string.
translators = []
illustrators = []
translators_have_display_seq = False
illustrators_have_display_seq = False
for role in self.metadata_dom.xpath("/package/metadata/meta[@property='role' or @property='se:role']"):
contributor_id = role.get_attr("refines").lstrip("#")
contributor_element = self.metadata_dom.xpath("/package/metadata/dc:contributor[@id=\"" + contributor_id + "\"]")
if contributor_element:
contributor = {"name": contributor_element[0].text, "include": True, "display_seq": None}
display_seq = self.metadata_dom.xpath("/package/metadata/meta[@property=\"display-seq\"][@refines=\"#" + contributor_id + "\"]")
if display_seq and int(display_seq[0].text) == 0:
contributor["include"] = False
display_seq = []
if role.text == "trl":
if display_seq:
contributor["display_seq"] = display_seq[0]
translators_have_display_seq = True
translators.append(contributor)
if role.text == "ill":
if display_seq:
contributor["display_seq"] = display_seq[0]
illustrators_have_display_seq = True
illustrators.append(contributor)
for translator in translators:
if (not translators_have_display_seq and translator["include"]) or translator["display_seq"]:
identifier += se.formatting.make_url_safe(translator["name"]) + "_"
if translators:
identifier = identifier.strip("_") + "/"
for illustrator in illustrators:
include_illustrator = True
# If the translator is also the illustrator, don't include them twice
for translator in translators:
if illustrator["name"] == translator["name"]:
include_illustrator = False
break
if (include_illustrator and not illustrators_have_display_seq and illustrator["include"]) or illustrator["display_seq"]:
identifier += se.formatting.make_url_safe(illustrator["name"]) + "_"
identifier = identifier.strip("_/")
self._generated_identifier = identifier
return self._generated_identifier
@property
def generated_github_repo_url(self) -> str:
"""
Accessor
Generate a GitHub repository URL based on the *generated* SE identifier,
*not* the SE identifier in the metadata file.
INPUTS
None
OUTPUTS
A string representing the GitHub repository URL (capped at maximum 100 characters).
"""
if not self._generated_github_repo_url:
self._generated_github_repo_url = "https://github.com/standardebooks/" + self.generated_identifier.replace("url:https://standardebooks.org/ebooks/", "").replace("/", "_")[0:100]
return self._generated_github_repo_url
@property
def endnotes(self) -> list:
"""
Accessor
Return a list of Endnote objects representing the endnotes file for this ebook.
INPUTS
None
OUTPUTS
A list of Endnote objects representing the endnotes file for this ebook.
"""
if not self._endnotes:
self._endnotes = []
dom = self.get_dom(self.endnotes_path)
for node in dom.xpath("/html/body/section[contains(@epub:type, 'endnotes')]/ol/li[contains(@epub:type, 'endnote')]"):
note = Endnote()
note.node = node
try:
note.number = int(node.get_attr("id").replace("note-", ""))
except ValueError:
note.number = 0
note.contents = node.xpath("./*")
note.anchor = node.get_attr("id") or ""
for back_link in node.xpath(".//a[contains(@epub:type, 'backlink')]/@href"):
note.back_link = back_link
if not note.back_link:
raise se.InvalidInputException(f"No backlink found in note {note.anchor} in existing endnotes file.")
self._endnotes.append(note)
return self._endnotes
@property
def spine_file_paths(self) -> List[Path]:
"""
Reads the spine from the metadata file to obtain a list of content files, in the order wanted for the ToC.
It assumes this has already been manually ordered by the producer.
INPUTS:
None
OUTPUTS:
list of content files paths in the order given in the spine in the metadata file
"""
if not self._spine_file_paths:
self._spine_file_paths = []
for idref in self.metadata_dom.xpath("/package/spine/itemref/@idref"):
try:
self._spine_file_paths.append(self.content_path / self.metadata_dom.xpath(f"/package/manifest/item[@id='{idref}']/@href", True))
except Exception as ex:
raise se.InvalidSeEbookException(f"Couldn’t find spine item: {idref}") from ex
return self._spine_file_paths
def get_file(self, file_path: Path) -> str:
"""
Get raw file contents of a file in the epub.
Contents are cached so that we don't hit the disk repeatedly
INPUTS
file_path: A Path pointing to the file
OUTPUTS
A string representing the file contents
"""
file_path_str = str(file_path)
if file_path_str not in self._file_cache:
with open(file_path, "r", encoding="utf-8") as file:
file_contents = file.read()
self._file_cache[file_path_str] = file_contents
return self._file_cache[file_path_str]
def flush_dom_cache_entry(self, file_path: Path) -> None:
"""
Remove a dom cache entry for the given file, regardless of whether comments were removed.
INPUTS
file_path: A Path pointing to the file
"""
keys_to_delete = []
for key in self._dom_cache:
if key.startswith(str(file_path)):
keys_to_delete.append(key)
for key in keys_to_delete:
del self._dom_cache[key]
try:
del self._file_cache[str(file_path)]
except:
pass
# Cache dom objects so we don't have to create them multiple times
def get_dom(self, file_path: Path, remove_comments=False) -> se.easy_xml.EasyXmlTree:
"""
Get an EasyXmlTree DOM object for a given file.
Contents are cached so that we don't hit the disk or re-parse DOMs repeatedly
INPUTS
file_path: A Path pointing to the file
OUTPUTS
A string representing the file contents
"""
file_path_str = str(file_path) + "_" + str(remove_comments)
if file_path_str not in self._dom_cache:
file_contents = self.get_file(file_path)
try:
self._dom_cache[file_path_str] = se.easy_xml.EasyXmlTree(file_contents)
# Remove comments
if remove_comments:
for node in self._dom_cache[file_path_str].xpath("//comment()"):
node.remove()
except etree.XMLSyntaxError as ex:
raise se.InvalidXhtmlException(f"Couldn’t parse XML in [path][link=file://{file_path.resolve()}]{file_path}[/][/]. Exception: {ex}") from ex
except FileNotFoundError as ex:
raise ex
except se.InvalidXmlException as ex:
raise se.InvalidXhtmlException(f"Couldn’t parse XML in [path][link=file://{file_path.resolve()}]{file_path}[/][/]. Exception: {ex.__cause__}") from ex
except Exception as ex:
raise se.InvalidXhtmlException(f"Couldn’t parse XML in [path][link=file://{file_path.resolve()}]{file_path}[/][/].") from ex
return self._dom_cache[file_path_str]
def _recompose_xhtml(self, section: se.easy_xml.EasyXmlElement, output_dom: se.easy_xml.EasyXmlTree) -> None:
"""
Helper function used in self.recompose()
Recursive function for recomposing a series of XHTML files into a single XHTML file.
INPUTS
section: An EasyXmlElement to inspect
output_dom: A EasyXmlTree representing the entire output dom
OUTPUTS
None
"""
# Quick sanity check before we begin
if not section.get_attr("id") or (section.parent.tag.lower() != "body" and not section.parent.get_attr("id")):
raise se.InvalidXhtmlException("Section without [attr]id[/] attribute.")
if section.parent.tag.lower() == "body":
section.set_attr("epub:type", f"{section.get_attr('epub:type')} {section.parent.get_attr('epub:type')}".strip())
# Try to find our parent tag in the output, by ID.
# If it's not in the output, then append it to the tag's closest parent by ID (or <body>), then iterate over its children and do the same.
existing_section = output_dom.xpath(f"//*[@id='{section.get_attr('id')}']")
if not existing_section:
if section.parent.tag.lower() == "body":
output_dom.xpath("/html/body")[0].append(section)
else:
output_dom.xpath(f"//*[@id='{section.parent.get_attr('id')}']")[0].append(section)
existing_section = output_dom.xpath(f"//*[@id='{section.get_attr('id')}']")
# Convert all <img> references to inline base64
# We even convert SVGs instead of inlining them, because CSS won't allow us to style inlined SVGs
# (for example if we want to apply max-width or filter: invert())
for img in section.xpath("//img[starts-with(@src, '../images/')]"):
src = img.get_attr("src").replace("../", "")
with open(self.content_path / src, "rb") as binary_file:
image_contents_base64 = base64.b64encode(binary_file.read()).decode()
if src.endswith(".svg"):
img.set_attr("src", f"data:image/svg+xml;base64, {image_contents_base64}")
if src.endswith(".jpg"):
img.set_attr("src", f"data:image/jpg;base64, {image_contents_base64}")
if src.endswith(".png"):
img.set_attr("src", f"data:image/png;base64, {image_contents_base64}")
for child in section.xpath("./*"):
if child.tag in ("section", "article"):
self._recompose_xhtml(child, output_dom)
else:
existing_section.append(child)
def recompose(self, output_xhtml5: bool, extra_css_file: Path = None) -> str:
"""
Iterate over the XHTML files in this epub and "recompose" them into a single XHTML string representing this ebook.
INPUTS
output_xhtml5: true to output XHTML5 instead of HTML5
OUTPUTS
A string of HTML5 representing the entire recomposed ebook.
"""
# Get some header data: title, core and local css
title = self.metadata_dom.xpath("/package/metadata/dc:title/text()")[0]
language = self.metadata_dom.xpath("/package/metadata/dc:language/text()")[0]
css = ""
namespaces: List[str] = []
css_filenames = ["core.css", "se.css", "local.css"]
if extra_css_file:
css_filenames.append(str(extra_css_file))
for filename in css_filenames:
filepath = self.content_path / "css" / filename
file_css = self.get_file(filepath)
namespaces = namespaces + regex.findall(r"@namespace.+?;", file_css)
file_css = regex.sub(r"\s*@(charset|namespace).+?;\s*", "\n", file_css).strip()
css = css + f"\n\n\n/* {filepath.name} */\n" + file_css
css = css.strip()
namespaces = list(set(namespaces))
if namespaces:
css = "\n" + css
for namespace in namespaces:
css = namespace + "\n" + css
css = "\t\t\t".join(css.splitlines(True)) + "\n"
# Remove min-height from CSS since it doesn't really apply to the single page format.
# It occurs at least in se.css
css = regex.sub(r"\s*min-height: [^;]+?;", "", css)
# Remove -epub-* CSS as it's invalid in a browser context
css = regex.sub(r"\s*\-epub\-[^;]+?;", "", css)
output_xhtml = f"<?xml version=\"1.0\" encoding=\"utf-8\"?><html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\" epub:prefix=\"z3998: http://www.daisy.org/z3998/2012/vocab/structure/, se: https://standardebooks.org/vocab/1.0\" xml:lang=\"{language}\"><head><meta charset=\"utf-8\"/><title>{title}</title><style/></head><body></body></html>"
output_dom = se.formatting.EasyXmlTree(output_xhtml)
output_dom.is_css_applied = True # We will apply CSS recursively to nodes that will be attached to output_dom, so set the bit here
# Iterate over spine items in order and recompose them into our output
needs_wrapper_css = False
for file_path in self.spine_file_paths:
dom = self.get_dom(file_path)
# Apply the stylesheet to see if we have `position: absolute` on any items. If so, apply `position: relative` to its closest <section> ancestor
# See https://standardebooks.org/ebooks/jean-toomer/cane for an example of this in action
dom.apply_css(css)
# Select deepest sections or articles with id attributes that have ONLY figure or img children, and one of those children has position: absolute
for node in dom.xpath("/html/body//*[@id and (name() = 'section' or name = 'article') and not(.//*[(name() = 'section' or name() = 'article') and not(preceding-sibling::* or following-sibling::*)]) and count(./*[(name() = 'figure' or name() = 'img')]) = count(./*) and .//*[(name() = 'figure' or name() = 'img') and @data-css-position = 'absolute']]"):
needs_wrapper_css = True
# Wrap the sections in a div that we style later
wrapper_element = etree.SubElement(node.lxml_element, "div")
wrapper_element.set("class", "positioning-wrapper")
for child in node.xpath("./*[(name() = 'figure' or name() = 'img')]"):
wrapper_element.append(child.lxml_element) # .append() will *move* the element to the end of wrapper_element
# Now, recompose the children
for node in dom.xpath("/html/body/*"):
try:
self._recompose_xhtml(node, output_dom)
except se.SeException as ex:
raise se.SeException(f"[path][link=file://{file_path}]{file_path}[/][/]: {ex}") from ex
# Did we add wrappers? If so add the CSS
# We also have to give the wrapper a height, because it may have siblings that were recomposed in from other files
if needs_wrapper_css:
css = css + "\n\t\t\t.positioning-wrapper{\n\t\t\t\tposition: relative; height: 100vh;\n\t\t\t}\n"
# Add the ToC after the titlepage
toc_dom = self.get_dom(self.toc_path)
titlepage_node = output_dom.xpath("//*[contains(concat(' ', @epub:type, ' '), ' titlepage ')]")[0]
for node in toc_dom.xpath("//nav[1]"):
titlepage_node.lxml_element.addnext(node.lxml_element)
# Replace all <a href> links with internal links
for link in output_dom.xpath("//a[not(re:test(@href, '^https?://')) and contains(@href, '#')]"):
link.set_attr("href", regex.sub(r".+(#.+)$", r"\1", link.get_attr("href")))
# Replace all <a href> links to entire files
for link in output_dom.xpath("//a[not(re:test(@href, '^https?://')) and not(contains(@href, '#'))]"):
href = link.get_attr("href")
href = regex.sub(r".+/([^/]+)$", r"#\1", href)
href = regex.sub(r"\.xhtml$", "", href)
link.set_attr("href", href)
for node in output_dom.xpath("/html/body//a[re:test(@href, '^(\\.\\./)?text/(.+?)\\.xhtml$')]"):
node.set_attr("href", regex.sub(r"(\.\./)?text/(.+?)\.xhtml", r"#\2", node.get_attr("href")))
for node in output_dom.xpath("/html/body//a[re:test(@href, '^(\\.\\./)?text/.+?\\.xhtml#(.+?)$')]"):
node.set_attr("href", regex.sub(r"(\.\./)?text/.+?\.xhtml#(.+?)", r"#\2", node.get_attr("href")))
# Make some compatibility adjustments
if output_xhtml5:
for node in output_dom.xpath("/html/head/meta[@charset]"):
node.remove()
for node in output_dom.xpath("//*[@xml:lang]"):
node.set_attr("lang", node.get_attr("xml:lang"))
else:
for node in output_dom.xpath("/html[@epub:prefix]"):
node.remove_attr("epub:prefix")
for node in output_dom.xpath("//*[@xml:lang]"):
node.set_attr("lang", node.get_attr("xml:lang"))
node.remove_attr("xml:lang")
for node in output_dom.xpath("//*[@epub:type]"):
node.set_attr("data-epub-type", node.get_attr("epub:type"))
node.remove_attr("epub:type")
# Get the output XHTML as a string
output_xhtml = output_dom.to_string()
# All done, clean the output
# Very large files like Ulysses S. Grant's memoirs or Through the Looking Glass will crash lxml due to their size.
# The inlined SVGs get too big.
# So, if the byte size of the XHTML string is larger than an arbitrary size, don't pretty print the output.
# Pepys is about 20,000,000 bytes
if getsizeof(output_xhtml) < 100000000:
output_xhtml = se.formatting.format_xhtml(output_xhtml)
# Insert our CSS. We do this after `clean` because `clean` will escape > in the CSS
output_xhtml = regex.sub(r"<style/>", "<style><![CDATA[\n\t\t\t" + css + "\t\t]]></style>", output_xhtml)
if output_xhtml5:
output_xhtml = output_xhtml.replace("\t\t<style/>\n", "")
# Re-add a doctype
output_xhtml = output_xhtml.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE html>")
else:
# Remove xml declaration and re-add the doctype
output_xhtml = regex.sub(r"<\?xml.+?\?>", "<!doctype html>", output_xhtml)
# Remove CDATA
output_xhtml = output_xhtml.replace("<![CDATA[", "")
output_xhtml = output_xhtml.replace("]]>", "")
# Make some replacements for HTML5 compatibility
output_xhtml = output_xhtml.replace("epub|type", "data-epub-type")
output_xhtml = regex.sub(r" xmlns.+?=\".+?\"", "", output_xhtml)
return output_xhtml
def generate_titlepage_svg(self) -> None:
"""
Generate a distributable titlepage SVG in ./src/epub/images/ based on the titlepage file in ./images/
INPUTS
None
OUTPUTS
None.
"""
source_images_directory = self.path / "images"
source_titlepage_svg_filename = source_images_directory / "titlepage.svg"
dest_images_directory = self.content_path / "images"
dest_titlepage_svg_filename = dest_images_directory / "titlepage.svg"
if source_titlepage_svg_filename.is_file():
# Convert text to paths
se.images.svg_text_to_paths(source_titlepage_svg_filename, dest_titlepage_svg_filename)
def generate_cover_svg(self) -> None:
"""
Generate a distributable cover SVG in ./src/epub/images/ based on the cover file in ./images/
INPUTS
None
OUTPUTS
None.
"""
source_images_directory = self.path / "images"
source_cover_jpg_filename = source_images_directory / "cover.jpg"
source_cover_svg_filename = source_images_directory / "cover.svg"
dest_images_directory = self.content_path / "images"
dest_cover_svg_filename = self.cover_path
# Create output directory if it doesn't exist
dest_images_directory.mkdir(parents=True, exist_ok=True)
if source_cover_jpg_filename.is_file() and source_cover_svg_filename.is_file():
# base64 encode cover.jpg
with open(source_cover_jpg_filename, "rb") as binary_file:
source_cover_jpg_base64 = base64.b64encode(binary_file.read()).decode()
# Convert text to paths
if source_cover_svg_filename.is_file():
se.images.svg_text_to_paths(source_cover_svg_filename, dest_cover_svg_filename, remove_style=False)
# Embed cover.jpg
dom = self.get_dom(dest_cover_svg_filename)
# Embed the file
for node in dom.xpath("//*[re:test(@xlink:href, 'cover\\.jpg$')]"):
node.set_attr("xlink:href", "data:image/jpeg;base64," + source_cover_jpg_base64)
# For the cover we want to keep the path.title-box style, and add an additional
# style to color our new paths white
for node in dom.xpath("/svg/style"):
node.set_text("\n\t\tpath{\n\t\t\tfill: #fff;\n\t\t}\n\n\t\t.title-box{\n\t\t\tfill: #000;\n\t\t\tfill-opacity: .75;\n\t\t}\n\t")
with open(dest_cover_svg_filename, "w", encoding="utf-8") as file:
file.write(dom.to_string())
def shift_endnotes(self, target_endnote_number: int, step: int = 1) -> None:
"""
Shift endnotes starting at target_endnote_number.
INPUTS:
target_endnote_number: The endnote to start shifting at
step: 1 to increment or -1 to decrement
OUTPUTS:
None.
"""
increment = step > 0
endnote_count = 0
if step == 0:
return
dom = self.get_dom(self.endnotes_path)
endnote_count = len(dom.xpath("//li[contains(@epub:type, 'endnote')]"))
if increment:
# Range is from COUNT -> target_endnote_number
note_range = range(endnote_count, target_endnote_number - 1, -1)
else:
# Range is from target_endnote_number -> COUNT
note_range = range(target_endnote_number, endnote_count + 1, 1)
for endnote_number in note_range:
new_endnote_number = endnote_number + step
# Update all the actual endnotes in the endnotes file
for node in dom.xpath(f"/html/body//li[contains(@epub:type, 'endnote') and @id='note-{endnote_number}']"):
node.set_attr("id", f"note-{new_endnote_number}")
# Update all backlinks in the endnotes file
for node in dom.xpath(f"/html/body//a[re:test(@href, '#noteref-{endnote_number}$')]"):
node.set_attr("href", node.get_attr("href").replace(f"#noteref-{endnote_number}", f"#noteref-{new_endnote_number}"))
# Write the endnotes file
try:
with open(self.endnotes_path, "w", encoding="utf-8") as file:
file.write(dom.to_string())
except Exception as ex:
raise se.InvalidSeEbookException(f"Couldn’t open endnotes file: [path][link=file://{self.endnotes_path}]{self.endnotes_path}[/][/].") from ex
# Now update endnotes in all other files. We also do a pass over the endnotes file itself.
# again just in case there are endnotes within endnotes.
for file_path in self.content_path.glob("**/*.xhtml"):
dom = self.get_dom(file_path)
for endnote_number in note_range:
new_endnote_number = endnote_number + step
# We don't use an xpath matching epub:type="noteref" because we can have hrefs that are not noterefs pointing to endnotes (like "see here")
for node in dom.xpath(f"/html/body//a[re:test(@href, '(endnotes\\.xhtml)?#note-{endnote_number}$')]"):
# Update the `id` attribute of the link, if we have one (sometimes hrefs point to endnotes but they are not noterefs themselves)
if node.get_attr("id"):
# Use a regex instead of just replacing the entire ID so that we don't mess up IDs that do not fit this pattern
node.set_attr("id", regex.sub(r"noteref-\d+$", f"noteref-{new_endnote_number}", node.get_attr("id")))
node.set_attr("href", regex.sub(fr"#note-{endnote_number}$", f"#note-{new_endnote_number}", node.get_attr("href")))
node.set_text(regex.sub(fr"\b{endnote_number}\b", f"{new_endnote_number}", node.text))
with open(file_path, "w", encoding="utf-8") as file:
file.write(dom.to_string())
def set_release_timestamp(self) -> None:
"""
If this ebook has not yet been released, set the first release timestamp in the metadata file.
"""
if self.metadata_dom.xpath("/package/metadata/dc:date[text() = '1900-01-01T00:00:00Z']"):
now = datetime.datetime.utcnow()
now_iso = regex.sub(r"\.[0-9]+$", "", now.isoformat()) + "Z"
now_iso = regex.sub(r"\+.+?Z$", "Z", now_iso)
now_friendly = f"{now:%B %e, %Y, %l:%M <abbr class=\"eoc\">%p</abbr>}"
now_friendly = regex.sub(r"\s+", " ", now_friendly).replace("AM", "a.m.").replace("PM", "p.m.").replace(" <abbr", " <abbr")
for node in self.metadata_dom.xpath("/package/metadata/dc:date"):
node.set_text(now_iso)
for node in self.metadata_dom.xpath("/package/metadata/meta[@property='dcterms:modified']"):
node.set_text(now_iso)
with open(self.metadata_file_path, "w", encoding="utf-8") as file:
file.write(self.metadata_dom.to_string())
for file_path in self.content_path.glob("**/*.xhtml"):
dom = self.get_dom(file_path)
if dom.xpath("/html/body/section[contains(@epub:type, 'colophon')]"):
for node in dom.xpath("/html/body/section[contains(@epub:type, 'colophon')]//b[contains(text(), 'January 1, 1900')]"):
node.replace_with(se.easy_xml.EasyXmlElement(etree.fromstring(str.encode("<b>" + now_friendly + "</b>"))))
with open(file_path, "w", encoding="utf-8") as file:
file.write(dom.to_string())
def update_flesch_reading_ease(self) -> None:
"""
Calculate a new reading ease for this ebook and update the metadata file.
Ignores SE boilerplate files like the imprint.
INPUTS
None
OUTPUTS
None.
"""
text = ""
for filename in se.get_target_filenames([self.path], ".xhtml"):
xhtml = self.get_file(filename)
is_ignored, _ = se.get_dom_if_not_ignored(xhtml, ["colophon", "titlepage", "imprint", "copyright-page", "halftitlepage", "toc", "loi"])
if not is_ignored:
text += xhtml
for node in self.metadata_dom.xpath("/package/metadata/meta[@property='se:reading-ease.flesch']"):
node.set_text(str(se.formatting.get_flesch_reading_ease(text)))
with open(self.metadata_file_path, "w", encoding="utf-8") as file:
file.write(self.metadata_dom.to_string())
def get_word_count(self) -> int:
"""
Calculate the word count of this ebook.
Ignores SE boilerplate files like the imprint, as well as any endnotes.
INPUTS
None
OUTPUTS
The number of words in the ebook.
"""
word_count = 0
for filename in se.get_target_filenames([self.path], ".xhtml"):
xhtml = self.get_file(filename)
is_ignored, _ = se.get_dom_if_not_ignored(xhtml, ["colophon", "titlepage", "imprint", "copyright-page", "halftitlepage", "toc", "loi", "endnotes"])
if not is_ignored:
word_count += se.formatting.get_word_count(xhtml)
return word_count
def update_word_count(self) -> None:
"""
Calculate a new word count for this ebook and update the metadata file.
Ignores SE boilerplate files like the imprint, as well as any endnotes.
INPUTS
None
OUTPUTS
None.
"""
for node in self.metadata_dom.xpath("/package/metadata/meta[@property='se:word-count']"):
node.set_text(str(self.get_word_count()))
with open(self.metadata_file_path, "r+", encoding="utf-8") as file:
file.seek(0)
file.write(self.metadata_dom.to_string())
file.truncate()
def generate_manifest(self) -> se.easy_xml.EasyXmlElement:
"""
Return the <manifest> element for this ebook as an EasyXmlElement.
INPUTS
None
OUTPUTS
An EasyXmlElement representing the manifest.
"""
manifest = []
for file_path in self.content_path.glob("**/*"):
if file_path.name == self.metadata_file_path.name:
# Don't add the metadata file to the manifest
continue
if file_path.stem.startswith("."):
# Skip dotfiles
continue
mime_type = None
properties = []
if file_path.suffix == ".css":
mime_type="text/css"
if file_path.suffix in (".ttf", ".otf", ".woff", ".woff2"):
mime_type="application/vnd.ms-opentype"
if file_path.suffix == ".svg":
mime_type = "image/svg+xml"
if file_path.suffix == ".png":
mime_type = "image/png"
if file_path.suffix == ".jpg":
mime_type = "image/jpeg"
if file_path.stem == "cover":
properties.append("cover-image")
if file_path.suffix == ".xhtml":
dom = self.get_dom(file_path)
mime_type = "application/xhtml+xml"
# the `glossary` semantic may also appear in the ToC landmarks, so specifically exclude that
if dom.xpath("//*[contains(@epub:type, 'glossary') and not(ancestor-or-self::nav)]"):
properties.append("glossary")
#if dom.xpath("/html/body//*[namespace-uri()='http://www.w3.org/1998/Math/MathML']"):
if dom.xpath("/html[namespace::*='http://www.w3.org/1998/Math/MathML']"):
properties.append("mathml")
if dom.xpath("//img[re:test(@src, '\\.svg$')]"):
properties.append("svg")
if dom.xpath("//nav[contains(@epub:type, 'toc')]"):
properties.append("nav")
if file_path.suffix == ".xml":
dom = self.get_dom(file_path)
# Do we have a glossary search key map?
if dom.xpath("/search-key-map"):
mime_type = "application/vnd.epub.search-key-map+xml"
properties.append("glossary")
properties.append("search-key-map")
if mime_type:
# Put together any properties we have
properties_attr = ""
for prop in properties:
properties_attr += prop + " "
properties_attr = properties_attr.strip()
if properties_attr:
properties_attr = f" properties=\"{properties_attr}\""
# Add the manifest item
# Replace the path separator because if run on Windows we will get the wrong slash direction from pathlib
manifest.append(f"""<item href="{str(file_path.relative_to(self.content_path)).replace(os.sep, "/")}" id="{file_path.name}" media-type="{mime_type}"{properties_attr}/>""")
manifest = natsorted(manifest)
# Assemble the manifest XML string
manifest_xml = "<manifest>\n"
for line in manifest:
manifest_xml = manifest_xml + "\t" + line + "\n"
manifest_xml = manifest_xml + "</manifest>"
return se.easy_xml.EasyXmlElement(etree.fromstring(str.encode(manifest_xml)))
def __add_to_spine(self, spine: List[str], items: List[Path], semantic: str) -> Tuple[List[str], List[Path]]:
"""
Given a spine and a list of items, add the item to the spine if it contains the specified semantic.
If an item is added to the spine, remove it from the original list.
Returns an updated spine and item list.
"""
filtered_items = []
spine_additions = []
for file_path in items:
dom = self.get_dom(file_path)
# Match against \b because we might have `titlepage` and `halftitlepage`
if dom.xpath(f"/html/body//section[re:test(@epub:type, '\\b{semantic}\\b')]"):
spine_additions.append(file_path.name)
else:
filtered_items.append(file_path)
# Sort the additions, for example if we have more than one dedication or introduction
spine_additions = natsorted(spine_additions)
return (spine + spine_additions, filtered_items)
def generate_spine(self) -> se.easy_xml.EasyXmlElement:
"""
Return the <spine> element of this ebook as an EasyXmlElement, with a best guess as to the correct order. Manual review is required.
INPUTS
None
OUTPUTS
An EasyXmlElement representing the spine.
"""
spine: List[str] = []
frontmatter = []
bodymatter = []
backmatter = []
for file_path in self.content_path.glob("**/*.xhtml"):
dom = self.get_dom(file_path)
# Exclude the ToC from the spine
if dom.xpath("/html/body//nav[contains(@epub:type, 'toc')]"):
continue
if dom.xpath("/html/*[contains(@epub:type, 'frontmatter')]"):
frontmatter.append(file_path)
elif dom.xpath("/html/*[contains(@epub:type, 'backmatter')]"):
backmatter.append(file_path)
else:
bodymatter.append(file_path)
# Add frontmatter
spine, frontmatter = self.__add_to_spine(spine, frontmatter, "titlepage")
spine, frontmatter = self.__add_to_spine(spine, frontmatter, "imprint")
spine, frontmatter = self.__add_to_spine(spine, frontmatter, "dedication")
spine, frontmatter = self.__add_to_spine(spine, frontmatter, "preamble")
spine, frontmatter = self.__add_to_spine(spine, frontmatter, "introduction")
spine, frontmatter = self.__add_to_spine(spine, frontmatter, "foreword")
spine, frontmatter = self.__add_to_spine(spine, frontmatter, "preface")
spine, frontmatter = self.__add_to_spine(spine, frontmatter, "epigraph")
spine, frontmatter = self.__add_to_spine(spine, frontmatter, "z3998:dramatis-personae")
spine, frontmatter = self.__add_to_spine(spine, frontmatter, "halftitlepage")
# Add any remaining frontmatter
spine = spine + natsorted([file_path.name for file_path in frontmatter])
# Add bodymatter
spine, bodymatter = self.__add_to_spine(spine, bodymatter, "prologue")
spine = spine + natsorted([file_path.name for file_path in bodymatter])
# Add backmatter
spine, backmatter = self.__add_to_spine(spine, backmatter, "afterword")
spine, backmatter = self.__add_to_spine(spine, backmatter, "appendix")
spine, backmatter = self.__add_to_spine(spine, backmatter, "glossary")
spine, backmatter = self.__add_to_spine(spine, backmatter, "endnotes")
spine, backmatter = self.__add_to_spine(spine, backmatter, "loi")
spine, backmatter = self.__add_to_spine(spine, backmatter, "colophon")
spine, backmatter = self.__add_to_spine(spine, backmatter, "copyright-page")
# Add any remaining backmatter
spine = spine + natsorted([file_path.name for file_path in backmatter])
# Now build the spine output
spine_xml = "<spine>\n"
for filename in spine:
spine_xml = spine_xml + f"""\t<itemref idref="{filename}"/>\n"""
spine_xml = spine_xml + "</spine>"
return se.easy_xml.EasyXmlElement(etree.fromstring(str.encode(spine_xml)))
def get_work_type(self) -> str:
"""
Returns either "fiction" or "non-fiction", based on analysis of se:subjects in the metadata file
INPUTS:
None
OUTPUTS:
The fiction or non-fiction type
"""
worktype = "fiction" # default
subjects = self.metadata_dom.xpath("/package/metadata/meta[@property='se:subject']/text()")
if not subjects:
return worktype
# Unfortunately, some works are tagged "Philosophy" but are nevertheless fiction, so we have to double-check
if "Nonfiction" in subjects:
return "non-fiction"
nonfiction_types = ["Autobiography", "Memoir", "Philosophy", "Spirituality", "Travel"]
for nonfiction_type in nonfiction_types:
if nonfiction_type in subjects:
worktype = "non-fiction"
fiction_types = ["Fantasy", "Fiction", "Horror", "Mystery", "Science Fiction"]
for fiction_type in fiction_types:
if fiction_type in subjects:
worktype = "fiction"
return worktype
def get_work_title(self) -> str:
"""
Returns the title of the book from the metadata file, which we assume has already been correctly completed.
INPUTS:
None
OUTPUTS:
Either the title of the book or the default WORKING_TITLE
"""
return self.metadata_dom.xpath("/package/metadata/dc:title/text()", True) or "WORK_TITLE"
def lint(self, skip_lint_ignore: bool, allowed_messages: List[str] = None) -> list:
"""
The lint() function is very big so for readability and maintainability
it's broken out to a separate file. Strictly speaking that file can be inlined
into this class.
"""
from se.se_epub_lint import lint # pylint: disable=import-outside-toplevel
return lint(self, skip_lint_ignore, allowed_messages)
def build(self, run_epubcheck: bool, check_only: bool, build_kobo: bool, build_kindle: bool, output_directory: Path, proof: bool) -> None:
"""
The build() function is very big so for readability and maintainability
it's broken out to a separate file. Strictly speaking that file can be inlined
into this class.
"""
from se.se_epub_build import build # pylint: disable=import-outside-toplevel
build(self, run_epubcheck, check_only, build_kobo, build_kindle, output_directory, proof)
def generate_toc(self) -> str:
"""
The generate_toc() function is very big so for readability and maintainability
it's broken out to a separate file. Strictly speaking that file can be inlined
into this class.
"""
from se.se_epub_generate_toc import generate_toc # pylint: disable=import-outside-toplevel
toc_xhtml = generate_toc(self)
# Word joiners and nbsp don't go in the ToC
toc_xhtml = toc_xhtml.replace(se.WORD_JOINER, "")
toc_xhtml = toc_xhtml.replace(se.NO_BREAK_SPACE, " ")
return toc_xhtml
def _check_endnotes(self) -> list:
"""
Initial check to see if all note references in the body have matching endnotes
in endnotes.xhtml and no duplicates.
Returns string of failures if any. If these are empty, all was well.
"""
missing = []
duplicates = []
orphans = []
references = []
response = []
for file_path in self.spine_file_paths:
dom = self.get_dom(file_path)
for link in dom.xpath("/html/body//a[contains(@epub:type, 'noteref')]"):
anchor = ""
href = link.get_attr("href") or ""
if href:
# Extract just the anchor from a URL (ie, what follows a hash symbol)
hash_position = href.find("#") + 1 # we want the characters AFTER the hash
if hash_position > 0:
anchor = href[hash_position:]
references.append(anchor) # keep these for later reverse check
# Now try to find anchor in endnotes
match_anchor = lambda x, old=anchor: x.anchor == old
matches = list(filter(match_anchor, self.endnotes))
if not matches:
missing.append(anchor)
if len(matches) > 1:
duplicates.append(anchor)
for miss in missing:
response.append(f"Missing endnote with anchor: {miss}")
for dupe in duplicates:
response.append(f"Duplicate endnotes with anchor: {dupe}")
# reverse check: look for orphaned endnotes
for note in self.endnotes:
# try to find it in our references collection
if note.anchor not in references:
orphans.append(note.anchor)
for orphan in orphans:
response.append(f"Orphan endnote with anchor: {orphan}")
return response
def recreate_endnotes(self) -> None:
"""
Renumber all noterefs starting from 1, and renumber all endnotes starting from 1.
Does not perform any sanity checks or do any rearranging; may result in more noterefs than endnotes, or more endnotes than noterefs.
Changes are written to disk.
"""
noteref_locations = {}
current_note_number = 1
# Renumber all noterefs starting from 1
for file_path in self.spine_file_paths:
dom = self.get_dom(file_path)
for node in dom.xpath("/html/body//a[contains(@epub:type, 'noteref')]"):
node.set_attr("href", f"endnotes.xhtml#note-{current_note_number}")
node.set_attr("id", f"noteref-{current_note_number}")
node.set_text(str(current_note_number))
noteref_locations[current_note_number] = file_path
current_note_number += 1
with open(file_path, "w") as file:
file.write(dom.to_string())
# Renumber all endnotes starting from 1
current_note_number = 1
endnotes_dom = self.get_dom(self.endnotes_path)
for node in endnotes_dom.xpath("/html/body//li[contains(@epub:type, 'endnote')]"):
node.set_attr("id", f"note-{current_note_number}")
for backlink in node.xpath(".//a[contains(@epub:type, 'backlink')]"):
filename = noteref_locations[current_note_number].name if current_note_number in noteref_locations else ""
backlink.set_attr("href", f"{filename}#noteref-{current_note_number}")
current_note_number += 1
with open(self.endnotes_path, "w") as file:
file.write(endnotes_dom.to_string())
def generate_endnotes(self) -> Tuple[int, int]:
"""
Read the epub spine to regenerate all endnotes in order of appearance, starting from 1.
Changes are written to disk.
Returns a tuple of (found_endnote_count, changed_endnote_count)
"""
# Do a safety check first, throw exception if it failed
results = self._check_endnotes()
if results:
report = "\n".join(results)
raise se.InvalidInputException(f"Endnote error(s) found: {report}.")
# If we get here, it's safe to proceed
processed = 0
current_note_number = 1
notes_changed = 0
change_list: List[str] = []
for file_path in self.spine_file_paths:
dom = self.get_dom(file_path)
# Skip the actual endnotes file, we'll handle that later
if dom.xpath("/html/body//*[contains(@epub:type, 'endnotes')]"):
continue
processed += 1
needs_rewrite = False
for link in dom.xpath("/html/body//a[contains(@epub:type, 'noteref')]"):
needs_rewrite, notes_changed = self.__process_link(change_list, current_note_number, file_path.name, link, needs_rewrite, notes_changed)
current_note_number += 1
# If we need to write back the body text file
if needs_rewrite:
with open(file_path, "w") as file:
file.write(se.formatting.format_xhtml(dom.to_string()))
# Now process any endnotes WITHIN the endnotes
for source_note in self.endnotes:
node = source_note.node
needs_rewrite = False
for link in node.xpath(".//a[contains(@epub:type, 'noteref')]"):
needs_rewrite, notes_changed = self.__process_link(change_list, current_note_number, self.endnotes_path.name, link, needs_rewrite, notes_changed)
current_note_number += 1
if processed == 0:
raise se.InvalidInputException("No files processed. Did you update the manifest and order the spine?")
if notes_changed > 0:
# Now we need to recreate the endnotes file
endnotes_dom = self.get_dom(self.endnotes_path)
for ol_node in endnotes_dom.xpath("/html/body/section[contains(@epub:type, 'endnotes')]/ol[1]"):
for node in ol_node.xpath("./li[contains(@epub:type, 'endnote')]"):
node.remove()
self.endnotes.sort(key=lambda endnote: endnote.number)
for endnote in self.endnotes:
if endnote.matched:
endnote.node.set_attr("id", f"note-{endnote.number}")
for node in endnote.node.xpath(".//a[contains(@epub:type, 'backlink')]"):
node.set_attr("href", f"{endnote.source_file}#noteref-{endnote.number}")
ol_node.append(endnote.node)
with open(self.endnotes_path, "w") as file:
file.write(se.formatting.format_xhtml(endnotes_dom.to_string()))
return current_note_number - 1, notes_changed
def __process_link(self, change_list, current_note_number, file_name, link, needs_rewrite, notes_changed) -> Tuple[bool, int]:
"""
Checks each endnote link to see if the existing anchor needs to be updated with a new number
Returns a tuple of needs_write (whether object needs to be re-written), and the number of notes_changed
"""
old_anchor = ""
href = link.get_attr("href") or ""
if href:
# Extract just the anchor from a URL (ie, what follows a hash symbol)
hash_position = href.find("#") + 1 # we want the characters AFTER the hash
if hash_position > 0:
old_anchor = href[hash_position:]
new_anchor = f"note-{current_note_number:d}"
if new_anchor != old_anchor:
change_list.append(f"Changed {old_anchor} to {new_anchor} in {file_name}")
notes_changed += 1
# Update the link in the dom
link.set_attr("href", f"{self.endnotes_path.name}#{new_anchor}")
link.set_attr("id", f"noteref-{current_note_number:d}")
link.lxml_element.text = str(current_note_number)
needs_rewrite = True
# Now try to find this in endnotes
match_old = lambda x, old=old_anchor: x.anchor == old
matches = list(filter(match_old, self.endnotes))
if not matches:
raise se.InvalidInputException(f"Couldn’t find endnote with anchor [attr]{old_anchor}[/].")
if len(matches) > 1:
raise se.InvalidInputException(f"Duplicate anchors in endnotes file for anchor [attr]{old_anchor}[/].")
# Found a single match, which is what we want
endnote = matches[0]
endnote.number = current_note_number
endnote.matched = True
# We don't change the anchor or the back ref just yet
endnote.source_file = file_name
return needs_rewrite, notes_changed
|
from abc import ABC, abstractmethod
from collections import abc as cabc
from typing import Union, Optional, Type, ClassVar, TypeVar # Special types
from typing import Iterator, Mapping, Sequence # ABCs
from typing import Tuple, List, Dict # Generic base types
import numpy as np
import pandas as pd
from scipy.sparse import spmatrix
from ..utils import deprecated, ensure_df_homogeneous
from . import raw, anndata
from .views import as_view, ViewArgs
from .index import _subset
OneDIdx = Union[Sequence[int], Sequence[bool], slice]
TwoDIdx = Tuple[OneDIdx, OneDIdx]
I = TypeVar("I", OneDIdx, TwoDIdx, covariant=True)
# TODO: pd.DataFrame only allowed in AxisArrays?
V = Union[pd.DataFrame, spmatrix, np.ndarray]
class AlignedMapping(cabc.MutableMapping, ABC):
"""\
An abstract base class for Mappings containing array-like values aligned
to either one or both AnnData axes.
"""
_allow_df: ClassVar[bool]
"""If this mapping supports heterogeneous DataFrames"""
_view_class: ClassVar[Type["AlignedViewMixin"]]
"""The view class for this aligned mapping."""
_actual_class: ClassVar[Type["AlignedActualMixin"]]
"""The actual class (which has it’s own data) for this aligned mapping."""
def __repr__(self):
return f"{type(self).__name__} with keys: {", ".join(self.keys())}"
def _ipython_key_completions_(self) -> List[str]:
return list(self.keys())
def _validate_value(self, val: V, key: str) -> V:
"""Raises an error if value is invalid"""
for i, axis in enumerate(self.axes):
if self.parent.shape[axis] != val.shape[i]:
right_shape = tuple(self.parent.shape[a] for a in self.axes)
raise ValueError(
f"Value passed for key {key!r} is of incorrect shape. "
f"Values of {self.attrname} must match dimensions "
f"{self.axes} of parent. Value had shape {val.shape} while "
f"it should have had {right_shape}."
)
if not self._allow_df and isinstance(val, pd.DataFrame):
name = self.attrname.title().rstrip("s")
val = ensure_df_homogeneous(val, f"{name} {key!r}")
return val
@property
@abstractmethod
def attrname(self) -> str:
"""What attr for the AnnData is this?"""
pass
@property
@abstractmethod
def axes(self) -> Tuple[int, ...]:
"""Which axes of the parent is this aligned to?"""
pass
@property
@abstractmethod
def is_view(self) -> bool:
pass
@property
def parent(self) -> Union["anndata.AnnData", "raw.Raw"]:
return self._parent
def copy(self):
d = self._actual_class(self.parent, self._axis)
for k, v in self.items():
d[k] = v.copy()
return d
def _view(self, parent: "anndata.AnnData", subset_idx: I):
"""Returns a subset copy-on-write view of the object."""
return self._view_class(self, parent, subset_idx)
@deprecated("dict(obj)")
def as_dict(self) -> dict:
return dict(self)
class AlignedViewMixin:
parent: "anndata.AnnData"
"""Reference to parent AnnData view"""
attrname: str
"""What attribute in the parent is this?"""
parent_mapping: Mapping[str, V]
"""The object this is a view of."""
is_view = True
def __getitem__(self, key: str) -> V:
return as_view(
_subset(self.parent_mapping[key], self.subset_idx),
ViewArgs(self.parent, self.attrname, (key,)),
)
def __setitem__(self, key: str, value: V):
value = self._validate_value(value, key) # Validate before mutating
adata = self.parent.copy()
new_mapping = getattr(adata, self.attrname)
new_mapping[key] = value
self.parent._init_as_actual(adata)
def __delitem__(self, key: str):
self[key] # Make sure it exists before bothering with a copy
adata = self.parent.copy()
new_mapping = getattr(adata, self.attrname)
del new_mapping[key]
self.parent._init_as_actual(adata)
def __contains__(self, key: str) -> bool:
return key in self.parent_mapping
def __iter__(self) -> Iterator[str]:
return iter(self.parent_mapping)
def __len__(self) -> int:
return len(self.parent_mapping)
class AlignedActualMixin:
_data: Dict[str, V]
"""Underlying mapping to the data"""
is_view = False
def __getitem__(self, key: str) -> V:
return self._data[key]
def __setitem__(self, key: str, value: V):
value = self._validate_value(value, key)
self._data[key] = value
def __contains__(self, key: str) -> bool:
return key in self._data
def __delitem__(self, key: str):
del self._data[key]
def __iter__(self) -> Iterator[str]:
return iter(self._data)
def __len__(self) -> int:
return len(self._data)
class AxisArraysBase(AlignedMapping):
"""\
Mapping of key→array-like,
where array-like is aligned to an axis of parent AnnData.
"""
_allow_df = True
_dimnames = ("obs", "var")
@property
def attrname(self) -> str:
return f"{self.dim}m"
@property
def axes(self) -> Tuple[int]:
"""Axes of the parent this is aligned to"""
return (self._axis,)
@property
def dim(self) -> str:
"""Name of the dimension this aligned to."""
return self._dimnames[self._axis]
def flipped(self) -> "AxisArraysBase":
"""Transpose."""
new = self.copy()
new.dimension = abs(self._axis - 1)
return new
def to_df(self) -> pd.DataFrame:
"""Convert to pandas dataframe."""
df = pd.DataFrame(index=self.dim_names)
for key in self.keys():
value = self[key]
for icolumn, column in enumerate(value.T):
df[f"{key}{icolumn + 1}"] = column
return df
def _validate_value(self, val: V, key: str) -> V:
if (
hasattr(val, "index")
and isinstance(val.index, cabc.Collection)
and not (val.index == self.dim_names).all()
):
# Could probably also re-order index if it’s contained
raise ValueError(
f"value.index does not match parent’s axis {self.axes[0]} names"
)
return super()._validate_value(val, key)
class AxisArrays(AlignedActualMixin, AxisArraysBase):
def __init__(
self,
parent: Union["anndata.AnnData", "raw.Raw"],
axis: int,
vals: Union[Mapping, AxisArraysBase, None] = None,
):
self._parent = parent
if axis not in (0, 1):
raise ValueError()
self._axis = axis
self.dim_names = (parent.obs_names, parent.var_names)[self._axis]
self._data = dict()
if vals is not None:
self.update(vals)
class AxisArraysView(AlignedViewMixin, AxisArraysBase):
def __init__(
self,
parent_mapping: AxisArraysBase,
parent_view: "anndata.AnnData",
subset_idx: OneDIdx,
):
self.parent_mapping = parent_mapping
self._parent = parent_view
self.subset_idx = subset_idx
self._axis = parent_mapping._axis
self.dim_names = parent_mapping.dim_names[subset_idx]
AxisArraysBase._view_class = AxisArraysView
AxisArraysBase._actual_class = AxisArrays
class LayersBase(AlignedMapping):
"""\
Mapping of key: array-like, where array-like is aligned to both axes of the
parent anndata.
"""
_allow_df = False
attrname = "layers"
axes = (0, 1)
# TODO: I thought I had a more elegant solution to overiding this...
def copy(self) -> "Layers":
d = self._actual_class(self.parent)
for k, v in self.items():
d[k] = v.copy()
return d
class Layers(AlignedActualMixin, LayersBase):
def __init__(self, parent: "anndata.AnnData", vals: Optional[Mapping] = None):
self._parent = parent
self._data = dict()
if vals is not None:
self.update(vals)
class LayersView(AlignedViewMixin, LayersBase):
def __init__(
self,
parent_mapping: LayersBase,
parent_view: "anndata.AnnData",
subset_idx: TwoDIdx,
):
self.parent_mapping = parent_mapping
self._parent = parent_view
self.subset_idx = subset_idx
LayersBase._view_class = LayersView
LayersBase._actual_class = Layers
class PairwiseArraysBase(AlignedMapping):
"""\
Mapping of key: array-like, where both axes of array-like are aligned to
one axis of the parent anndata.
"""
_allow_df = False
_dimnames = ("obs", "var")
@property
def attrname(self) -> str:
return f"{self.dim}p"
@property
def axes(self) -> Tuple[int, int]:
"""Axes of the parent this is aligned to"""
return self._axis, self._axis
@property
def dim(self) -> str:
"""Name of the dimension this aligned to."""
return self._dimnames[self._axis]
class PairwiseArrays(AlignedActualMixin, PairwiseArraysBase):
def __init__(
self, parent: "anndata.AnnData", axis: int, vals: Optional[Mapping] = None,
):
self._parent = parent
if axis not in (0, 1):
raise ValueError()
self._axis = axis
self._data = dict()
if vals is not None:
self.update(vals)
class PairwiseArraysView(AlignedViewMixin, PairwiseArraysBase):
def __init__(
self,
parent_mapping: PairwiseArraysBase,
parent_view: "anndata.AnnData",
subset_idx: OneDIdx,
):
self.parent_mapping = parent_mapping
self._parent = parent_view
self.subset_idx = (subset_idx, subset_idx)
self._axis = parent_mapping._axis
PairwiseArraysBase._view_class = PairwiseArraysView
PairwiseArraysBase._actual_class = PairwiseArrays
| from abc import ABC, abstractmethod
from collections import abc as cabc
from typing import Union, Optional, Type, ClassVar, TypeVar # Special types
from typing import Iterator, Mapping, Sequence # ABCs
from typing import Tuple, List, Dict # Generic base types
import numpy as np
import pandas as pd
from scipy.sparse import spmatrix
from ..utils import deprecated, ensure_df_homogeneous
from . import raw, anndata
from .views import as_view, ViewArgs
from .index import _subset
OneDIdx = Union[Sequence[int], Sequence[bool], slice]
TwoDIdx = Tuple[OneDIdx, OneDIdx]
I = TypeVar("I", OneDIdx, TwoDIdx, covariant=True)
# TODO: pd.DataFrame only allowed in AxisArrays?
V = Union[pd.DataFrame, spmatrix, np.ndarray]
class AlignedMapping(cabc.MutableMapping, ABC):
"""\
An abstract base class for Mappings containing array-like values aligned
to either one or both AnnData axes.
"""
_allow_df: ClassVar[bool]
"""If this mapping supports heterogeneous DataFrames"""
_view_class: ClassVar[Type["AlignedViewMixin"]]
"""The view class for this aligned mapping."""
_actual_class: ClassVar[Type["AlignedActualMixin"]]
"""The actual class (which has it’s own data) for this aligned mapping."""
def __repr__(self):
return f"{type(self).__name__} with keys: {', '.join(self.keys())}"
def _ipython_key_completions_(self) -> List[str]:
return list(self.keys())
def _validate_value(self, val: V, key: str) -> V:
"""Raises an error if value is invalid"""
for i, axis in enumerate(self.axes):
if self.parent.shape[axis] != val.shape[i]:
right_shape = tuple(self.parent.shape[a] for a in self.axes)
raise ValueError(
f"Value passed for key {key!r} is of incorrect shape. "
f"Values of {self.attrname} must match dimensions "
f"{self.axes} of parent. Value had shape {val.shape} while "
f"it should have had {right_shape}."
)
if not self._allow_df and isinstance(val, pd.DataFrame):
name = self.attrname.title().rstrip("s")
val = ensure_df_homogeneous(val, f"{name} {key!r}")
return val
@property
@abstractmethod
def attrname(self) -> str:
"""What attr for the AnnData is this?"""
pass
@property
@abstractmethod
def axes(self) -> Tuple[int, ...]:
"""Which axes of the parent is this aligned to?"""
pass
@property
@abstractmethod
def is_view(self) -> bool:
pass
@property
def parent(self) -> Union["anndata.AnnData", "raw.Raw"]:
return self._parent
def copy(self):
d = self._actual_class(self.parent, self._axis)
for k, v in self.items():
d[k] = v.copy()
return d
def _view(self, parent: "anndata.AnnData", subset_idx: I):
"""Returns a subset copy-on-write view of the object."""
return self._view_class(self, parent, subset_idx)
@deprecated("dict(obj)")
def as_dict(self) -> dict:
return dict(self)
class AlignedViewMixin:
parent: "anndata.AnnData"
"""Reference to parent AnnData view"""
attrname: str
"""What attribute in the parent is this?"""
parent_mapping: Mapping[str, V]
"""The object this is a view of."""
is_view = True
def __getitem__(self, key: str) -> V:
return as_view(
_subset(self.parent_mapping[key], self.subset_idx),
ViewArgs(self.parent, self.attrname, (key,)),
)
def __setitem__(self, key: str, value: V):
value = self._validate_value(value, key) # Validate before mutating
adata = self.parent.copy()
new_mapping = getattr(adata, self.attrname)
new_mapping[key] = value
self.parent._init_as_actual(adata)
def __delitem__(self, key: str):
self[key] # Make sure it exists before bothering with a copy
adata = self.parent.copy()
new_mapping = getattr(adata, self.attrname)
del new_mapping[key]
self.parent._init_as_actual(adata)
def __contains__(self, key: str) -> bool:
return key in self.parent_mapping
def __iter__(self) -> Iterator[str]:
return iter(self.parent_mapping)
def __len__(self) -> int:
return len(self.parent_mapping)
class AlignedActualMixin:
_data: Dict[str, V]
"""Underlying mapping to the data"""
is_view = False
def __getitem__(self, key: str) -> V:
return self._data[key]
def __setitem__(self, key: str, value: V):
value = self._validate_value(value, key)
self._data[key] = value
def __contains__(self, key: str) -> bool:
return key in self._data
def __delitem__(self, key: str):
del self._data[key]
def __iter__(self) -> Iterator[str]:
return iter(self._data)
def __len__(self) -> int:
return len(self._data)
class AxisArraysBase(AlignedMapping):
"""\
Mapping of key→array-like,
where array-like is aligned to an axis of parent AnnData.
"""
_allow_df = True
_dimnames = ("obs", "var")
@property
def attrname(self) -> str:
return f"{self.dim}m"
@property
def axes(self) -> Tuple[int]:
"""Axes of the parent this is aligned to"""
return (self._axis,)
@property
def dim(self) -> str:
"""Name of the dimension this aligned to."""
return self._dimnames[self._axis]
def flipped(self) -> "AxisArraysBase":
"""Transpose."""
new = self.copy()
new.dimension = abs(self._axis - 1)
return new
def to_df(self) -> pd.DataFrame:
"""Convert to pandas dataframe."""
df = pd.DataFrame(index=self.dim_names)
for key in self.keys():
value = self[key]
for icolumn, column in enumerate(value.T):
df[f"{key}{icolumn + 1}"] = column
return df
def _validate_value(self, val: V, key: str) -> V:
if (
hasattr(val, "index")
and isinstance(val.index, cabc.Collection)
and not (val.index == self.dim_names).all()
):
# Could probably also re-order index if it’s contained
raise ValueError(
f"value.index does not match parent’s axis {self.axes[0]} names"
)
return super()._validate_value(val, key)
class AxisArrays(AlignedActualMixin, AxisArraysBase):
def __init__(
self,
parent: Union["anndata.AnnData", "raw.Raw"],
axis: int,
vals: Union[Mapping, AxisArraysBase, None] = None,
):
self._parent = parent
if axis not in (0, 1):
raise ValueError()
self._axis = axis
self.dim_names = (parent.obs_names, parent.var_names)[self._axis]
self._data = dict()
if vals is not None:
self.update(vals)
class AxisArraysView(AlignedViewMixin, AxisArraysBase):
def __init__(
self,
parent_mapping: AxisArraysBase,
parent_view: "anndata.AnnData",
subset_idx: OneDIdx,
):
self.parent_mapping = parent_mapping
self._parent = parent_view
self.subset_idx = subset_idx
self._axis = parent_mapping._axis
self.dim_names = parent_mapping.dim_names[subset_idx]
AxisArraysBase._view_class = AxisArraysView
AxisArraysBase._actual_class = AxisArrays
class LayersBase(AlignedMapping):
"""\
Mapping of key: array-like, where array-like is aligned to both axes of the
parent anndata.
"""
_allow_df = False
attrname = "layers"
axes = (0, 1)
# TODO: I thought I had a more elegant solution to overiding this...
def copy(self) -> "Layers":
d = self._actual_class(self.parent)
for k, v in self.items():
d[k] = v.copy()
return d
class Layers(AlignedActualMixin, LayersBase):
def __init__(self, parent: "anndata.AnnData", vals: Optional[Mapping] = None):
self._parent = parent
self._data = dict()
if vals is not None:
self.update(vals)
class LayersView(AlignedViewMixin, LayersBase):
def __init__(
self,
parent_mapping: LayersBase,
parent_view: "anndata.AnnData",
subset_idx: TwoDIdx,
):
self.parent_mapping = parent_mapping
self._parent = parent_view
self.subset_idx = subset_idx
LayersBase._view_class = LayersView
LayersBase._actual_class = Layers
class PairwiseArraysBase(AlignedMapping):
"""\
Mapping of key: array-like, where both axes of array-like are aligned to
one axis of the parent anndata.
"""
_allow_df = False
_dimnames = ("obs", "var")
@property
def attrname(self) -> str:
return f"{self.dim}p"
@property
def axes(self) -> Tuple[int, int]:
"""Axes of the parent this is aligned to"""
return self._axis, self._axis
@property
def dim(self) -> str:
"""Name of the dimension this aligned to."""
return self._dimnames[self._axis]
class PairwiseArrays(AlignedActualMixin, PairwiseArraysBase):
def __init__(
self, parent: "anndata.AnnData", axis: int, vals: Optional[Mapping] = None,
):
self._parent = parent
if axis not in (0, 1):
raise ValueError()
self._axis = axis
self._data = dict()
if vals is not None:
self.update(vals)
class PairwiseArraysView(AlignedViewMixin, PairwiseArraysBase):
def __init__(
self,
parent_mapping: PairwiseArraysBase,
parent_view: "anndata.AnnData",
subset_idx: OneDIdx,
):
self.parent_mapping = parent_mapping
self._parent = parent_view
self.subset_idx = (subset_idx, subset_idx)
self._axis = parent_mapping._axis
PairwiseArraysBase._view_class = PairwiseArraysView
PairwiseArraysBase._actual_class = PairwiseArrays
|
import asyncio
from datetime import datetime
from typing import Callable
import discord
from discord.ext import commands
class AoiTask:
def __init__(self, task: asyncio.Task, ctx: commands.Context, status: Callable[[], str]):
self.task = task
self.ctx = ctx
self._status = status
self.time = datetime.now()
self.ctx.bot.logger.info(f"Creating task for {ctx.author.id} {ctx.message.content}")
def __del__(self):
self.ctx.bot.logger.info(f"Deleting task for {self.ctx.author.id} {self.ctx.message.content}")
def __str__(self) -> str:
return f"{self.member.mention} {self.time.strftime("%x %X")} [Jump]({self.message.jump_url})\n" \
+ (self.status + "\n" or "") + \
f"{self.message.content}\n"
@property
def status(self) -> str:
return self._status()
@property
def message(self) -> discord.Message:
return self.ctx.message
@property
def member(self) -> discord.Member:
return self.ctx.author
def guild(self) -> discord.Guild:
return self.ctx.guild
| import asyncio
from datetime import datetime
from typing import Callable
import discord
from discord.ext import commands
class AoiTask:
def __init__(self, task: asyncio.Task, ctx: commands.Context, status: Callable[[], str]):
self.task = task
self.ctx = ctx
self._status = status
self.time = datetime.now()
self.ctx.bot.logger.info(f"Creating task for {ctx.author.id} {ctx.message.content}")
def __del__(self):
self.ctx.bot.logger.info(f"Deleting task for {self.ctx.author.id} {self.ctx.message.content}")
def __str__(self) -> str:
return f"{self.member.mention} {self.time.strftime('%x %X')} [Jump]({self.message.jump_url})\n" \
+ (self.status + "\n" or "") + \
f"{self.message.content}\n"
@property
def status(self) -> str:
return self._status()
@property
def message(self) -> discord.Message:
return self.ctx.message
@property
def member(self) -> discord.Member:
return self.ctx.author
def guild(self) -> discord.Guild:
return self.ctx.guild
|
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
""" Userbot module for having some fun with people. """
from asyncio import sleep
from random import choice, getrandbits, randint
from re import sub
import time
from collections import deque
import requests
from cowpy import cow
from userbot import CMD_HELP
from userbot.events import register
from userbot.modules.admin import get_user_from_event
# ================= CONSTANT =================
METOOSTR = [
"Me too thanks",
"Haha yes, me too",
"Same lol",
"Me irl",
"Same here",
"Haha yes",
"Me rn",
]
ZALG_LIST = [[
"̖",
" ̗",
" ̘",
" ̙",
" ̜",
" ̝",
" ̞",
" ̟",
" ̠",
" ̤",
" ̥",
" ̦",
" ̩",
" ̪",
" ̫",
" ̬",
" ̭",
" ̮",
" ̯",
" ̰",
" ̱",
" ̲",
" ̳",
" ̹",
" ̺",
" ̻",
" ̼",
" ͅ",
" ͇",
" ͈",
" ͉",
" ͍",
" ͎",
" ͓",
" ͔",
" ͕",
" ͖",
" ͙",
" ͚",
" ",
],
[
" ̍",
" ̎",
" ̄",
" ̅",
" ̿",
" ̑",
" ̆",
" ̐",
" ͒",
" ͗",
" ͑",
" ̇",
" ̈",
" ̊",
" ͂",
" ̓",
" ̈́",
" ͊",
" ͋",
" ͌",
" ̃",
" ̂",
" ̌",
" ͐",
" ́",
" ̋",
" ̏",
" ̽",
" ̉",
" ͣ",
" ͤ",
" ͥ",
" ͦ",
" ͧ",
" ͨ",
" ͩ",
" ͪ",
" ͫ",
" ͬ",
" ͭ",
" ͮ",
" ͯ",
" ̾",
" ͛",
" ͆",
" ̚",
],
[
" ̕",
" ̛",
" ̀",
" ́",
" ͘",
" ̡",
" ̢",
" ̧",
" ̨",
" ̴",
" ̵",
" ̶",
" ͜",
" ͝",
" ͞",
" ͟",
" ͠",
" ͢",
" ̸",
" ̷",
" ͡",
]]
EMOJIS = [
"😂",
"😂",
"👌",
"✌",
"💞",
"👍",
"👌",
"💯",
"🎶",
"👀",
"😂",
"👓",
"👏",
"👐",
"🍕",
"💥",
"🍴",
"💦",
"💦",
"🍑",
"🍆",
"😩",
"😏",
"👉👌",
"👀",
"👅",
"😩",
"🚰",
]
INSULT_STRINGS = [
"Owww ... Such a stupid idiot.",
"Don't drink and type.",
"I think you should go home or better a mental asylum.",
"Command not found. Just like your brain.",
"Do you realize you are making a fool of yourself? Apparently not.",
"You can type better than that.",
"Bot rule 544 section 9 prevents me from replying to stupid humans like you.",
"Sorry, we do not sell brains.",
"Believe me you are not normal.",
"I bet your brain feels as good as new, seeing that you never use it.",
"If I wanted to kill myself I'd climb your ego and jump to your IQ.",
"Zombies eat brains... you're safe.",
"You didn't evolve from apes, they evolved from you.",
"Come back and talk to me when your I.Q. exceeds your age.",
"I'm not saying you're stupid, I'm just saying you've got bad luck when it comes to thinking.",
"What language are you speaking? Cause it sounds like bullshit.",
"Stupidity is not a crime so you are free to go.",
"You are proof that evolution CAN go in reverse.",
"I would ask you how old you are but I know you can't count that high.",
"As an outsider, what do you think of the human race?",
"Brains aren't everything. In your case they're nothing.",
"Ordinarily people live and learn. You just live.",
"I don't know what makes you so stupid, but it really works.",
"Keep talking, someday you'll say something intelligent! (I doubt it though)",
"Shock me, say something intelligent.",
"Your IQ's lower than your shoe size.",
"Alas! Your neurotransmitters are no more working.",
"Are you crazy you fool.",
"Everyone has the right to be stupid but you are abusing the privilege.",
"I'm sorry I hurt your feelings when I called you stupid. I thought you already knew that.",
"You should try tasting cyanide.",
"Your enzymes are meant to digest rat poison.",
"You should try sleeping forever.",
"Pick up a gun and shoot yourself.",
"You could make a world record by jumping from a plane without parachute.",
"Stop talking BS and jump in front of a running bullet train.",
"Try bathing with Hydrochloric Acid instead of water.",
"Try this: if you hold your breath underwater for an hour, you can then hold it forever.",
"Go Green! Stop inhaling Oxygen.",
"God was searching for you. You should leave to meet him.",
"give your 100%. Now, go donate blood.",
"Try jumping from a hundred story building but you can do it only once.",
"You should donate your brain seeing that you never used it.",
"Volunteer for target in an firing range.",
"Head shots are fun. Get yourself one.",
"You should try swimming with great white sharks.",
"You should paint yourself red and run in a bull marathon.",
"You can stay underwater for the rest of your life without coming back up.",
"How about you stop breathing for like 1 day? That'll be great.",
"Try provoking a tiger while you both are in a cage.",
"Have you tried shooting yourself as high as 100m using a canon.",
"You should try holding TNT in your mouth and igniting it.",
"Try playing catch and throw with RDX its fun.",
"I heard phogine is poisonous but i guess you wont mind inhaling it for fun.",
"Launch yourself into outer space while forgetting oxygen on Earth.",
"You should try playing snake and ladders, with real snakes and no ladders.",
"Dance naked on a couple of HT wires.",
"Active Volcano is the best swimming pool for you.",
"You should try hot bath in a volcano.",
"Try to spend one day in a coffin and it will be yours forever.",
"Hit Uranium with a slow moving neutron in your presence. It will be a worthwhile experience.",
"You can be the first person to step on sun. Have a try.",
]
UWUS = [
"(・`ω´・)",
";;w;;",
"owo",
"UwU",
">w<",
"^w^",
r"\(^o\) (/o^)/",
"( ^ _ ^)∠☆",
"(ô_ô)",
"~:o",
";-;",
"(*^*)",
"(>_",
"(♥_♥)",
"*(^O^)*",
"((+_+))",
]
FACEREACTS = [
"ʘ‿ʘ",
"ヾ(-_- )ゞ",
"(っ˘ڡ˘ς)",
"(´ж`ς)",
"( ಠ ʖ̯ ಠ)",
"(° ͜ʖ͡°)╭∩╮",
"(ᵟຶ︵ ᵟຶ)",
"(งツ)ว",
"ʚ(•`",
"(っ▀¯▀)つ",
"(◠﹏◠)",
"( ͡ಠ ʖ̯ ͡ಠ)",
"( ఠ ͟ʖ ఠ)",
"(∩`-´)⊃━☆゚.*・。゚",
"(⊃。•́‿•̀。)⊃",
"(._.)",
"{•̃_•̃}",
"(ᵔᴥᵔ)",
"♨_♨",
"⥀.⥀",
"ح˚௰˚づ ",
"(҂◡_◡)",
"ƪ(ړײ)ƪ",
"(っ•́。•́)♪♬",
"◖ᵔᴥᵔ◗ ♪ ♫ ",
"(☞゚ヮ゚)☞",
"[¬º-°]¬",
"(Ծ‸ Ծ)",
"(•̀ᴗ•́)و ̑̑",
"ヾ(´〇`)ノ♪♪♪",
"(ง'̀-'́)ง",
"ლ(•́•́ლ)",
"ʕ •́؈•̀ ₎",
"♪♪ ヽ(ˇ∀ˇ )ゞ",
"щ(゚Д゚щ)",
"( ˇ෴ˇ )",
"눈_눈",
"(๑•́ ₃ •̀๑) ",
"( ˘ ³˘)♥ ",
"ԅ(≖‿≖ԅ)",
"♥‿♥",
"◔_◔",
"⁽⁽ଘ( ˊᵕˋ )ଓ⁾⁾",
"乁( ◔ ౪◔)「 ┑( ̄Д  ̄)┍",
"( ఠൠఠ )ノ",
"٩(๏_๏)۶",
"┌(ㆆ㉨ㆆ)ʃ",
"ఠ_ఠ",
"(づ。◕‿‿◕。)づ",
"(ノಠ ∩ಠ)ノ彡( \\o°o)\\",
"“ヽ(´▽`)ノ”",
"༼ ༎ຶ ෴ ༎ຶ༽",
"。゚( ゚இ‸இ゚)゚。",
"(づ ̄ ³ ̄)づ",
"(⊙.☉)7",
"ᕕ( ᐛ )ᕗ",
"t(-_-t)",
"(ಥ⌣ಥ)",
"ヽ༼ ಠ益ಠ ༽ノ",
"༼∵༽ ༼⍨༽ ༼⍢༽ ༼⍤༽",
"ミ●﹏☉ミ",
"(⊙_◎)",
"¿ⓧ_ⓧﮌ",
"ಠ_ಠ",
"(´・_・`)",
"ᕦ(ò_óˇ)ᕤ",
"⊙﹏⊙",
"(╯°□°)╯︵ ┻━┻",
r"¯\_(⊙︿⊙)_/¯",
"٩◔̯◔۶",
"°‿‿°",
"ᕙ(⇀‸↼‶)ᕗ",
"⊂(◉‿◉)つ",
"V•ᴥ•V",
"q(❂‿❂)p",
"ಥ_ಥ",
"ฅ^•ﻌ•^ฅ",
"ಥ﹏ಥ",
"( ^_^)o自自o(^_^ )",
"ಠ‿ಠ",
"ヽ(´▽`)/",
"ᵒᴥᵒ#",
"( ͡° ͜ʖ ͡°)",
"┬─┬ ノ( ゜-゜ノ)",
"ヽ(´ー`)ノ",
"☜(⌒▽⌒)☞",
"ε=ε=ε=┌(;*´Д`)ノ",
"(╬ ಠ益ಠ)",
"┬─┬⃰͡ (ᵔᵕᵔ͜ )",
"┻━┻ ︵ヽ(`Д´)ノ︵ ┻━┻",
r"¯\_(ツ)_/¯",
"ʕᵔᴥᵔʔ",
"(`・ω・´)",
"ʕ•ᴥ•ʔ",
"ლ(`ー´ლ)",
"ʕʘ̅͜ʘ̅ʔ",
"( ゚Д゚)",
r"¯\(°_o)/¯",
"(。◕‿◕。)",
]
RUNS_STR = [
"Runs to Thanos..",
"Runs far, far away from earth..",
"Running faster than Bolt coz i'mma userbot !!",
"Runs to Marie..",
"This Group is too cancerous to deal with.",
"Cya bois",
"Kys",
"I go away",
"I am just walking off, coz me is too fat.",
"I Fugged off!",
"Will run for chocolate.",
"I run because I really like food.",
"Running...\nbecause dieting is not an option.",
"Wicked fast runnah",
"If you wanna catch me, you got to be fast...\nIf you wanna stay with me, you got to be good...\nBut if you wanna pass me...\nYou've got to be kidding.",
"Anyone can run a hundred meters, it's the next forty-two thousand and two hundred that count.",
"Why are all these people following me?",
"Are the kids still chasing me?",
"Running a marathon...there's an app for that.",
]
CHASE_STR = [
"Where do you think you're going?",
"Huh? what? did they get away?",
"ZZzzZZzz... Huh? what? oh, just them again, nevermind.",
"Get back here!",
"Not so fast...",
"Look out for the wall!",
"Don't leave me alone with them!!",
"You run, you die.",
"Jokes on you, I'm everywhere",
"You're gonna regret that...",
"You could also try /kickme, I hear that's fun.",
"Go bother someone else, no-one here cares.",
"You can run, but you can't hide.",
"Is that all you've got?",
"I'm behind you...",
"You've got company!",
"We can do this the easy way, or the hard way.",
"You just don't get it, do you?",
"Yeah, you better run!",
"Please, remind me how much I care?",
"I'd run faster if I were you.",
"That's definitely the droid we're looking for.",
"May the odds be ever in your favour.",
"Famous last words.",
"And they disappeared forever, never to be seen again.",
"\"Oh, look at me! I'm so cool, I can run from a bot!\" - this person",
"Yeah yeah, just tap /kickme already.",
"Here, take this ring and head to Mordor while you're at it.",
"Legend has it, they're still running...",
"Unlike Harry Potter, your parents can't protect you from me.",
"Fear leads to anger. Anger leads to hate. Hate leads to suffering. If you keep running in fear, you might "
"be the next Vader.",
"Multiple calculations later, I have decided my interest in your shenanigans is exactly 0.",
"Legend has it, they're still running.",
"Keep it up, not sure we want you here anyway.",
"You're a wiza- Oh. Wait. You're not Harry, keep moving.",
"NO RUNNING IN THE HALLWAYS!",
"Hasta la vista, baby.",
"Who let the dogs out?",
"It's funny, because no one cares.",
"Ah, what a waste. I liked that one.",
"Frankly, my dear, I don't give a damn.",
"My milkshake brings all the boys to yard... So run faster!",
"You can't HANDLE the truth!",
"A long time ago, in a galaxy far far away... Someone would've cared about that. Not anymore though.",
"Hey, look at them! They're running from the inevitable banhammer... Cute.",
"Han shot first. So will I.",
"What are you running after, a white rabbit?",
"As The Doctor would say... RUN!",
]
HELLOSTR = [
"Hi !",
"‘Ello, gov'nor!",
"What’s crackin’?",
"‘Sup, homeslice?",
"Howdy, howdy ,howdy!",
"Hello, who's there, I'm talking.",
"You know who this is.",
"Yo!",
"Whaddup.",
"Greetings and salutations!",
"Hello, sunshine!",
"Hey, howdy, hi!",
"What’s kickin’, little chicken?",
"Peek-a-boo!",
"Howdy-doody!",
"Hey there, freshman!",
"I come in peace!",
"Ahoy, matey!",
"Hiya!",
]
SHGS = [
"┐(´д`)┌",
"┐(´~`)┌",
"┐(´ー`)┌",
"┐( ̄ヘ ̄)┌",
"╮(╯∀╰)╭",
"╮(╯_╰)╭",
"┐(´д`)┌",
"┐(´∀`)┌",
"ʅ(́◡◝)ʃ",
"┐(゚~゚)┌",
"┐('д')┌",
"┐(‘~`;)┌",
"ヘ(´-`;)ヘ",
"┐( -“-)┌",
"ʅ(´◔౪◔)ʃ",
"ヽ(゜~゜o)ノ",
"ヽ(~~~ )ノ",
"┐(~ー~;)┌",
"┐(-。ー;)┌",
r"¯\_(ツ)_/¯",
r"¯\_(⊙_ʖ⊙)_/¯",
r"¯\_༼ ಥ ‿ ಥ ༽_/¯",
"乁( ⁰͡ Ĺ̯ ⁰͡ ) ㄏ",
]
CRI = [
"أ‿أ",
"╥﹏╥",
"(;﹏;)",
"(ToT)",
"(┳Д┳)",
"(ಥ﹏ಥ)",
"(;へ:)",
"(T_T)",
"(πーπ)",
"(T▽T)",
"(⋟﹏⋞)",
"(iДi)",
"(´Д⊂ヽ",
"(;Д;)",
"(>﹏<)",
"(TдT)",
"(つ﹏⊂)",
"༼☯﹏☯༽",
"(ノ﹏ヽ)",
"(ノAヽ)",
"(╥_╥)",
"(T⌓T)",
"(༎ຶ⌑༎ຶ)",
"(☍﹏⁰)。",
"(ಥ_ʖಥ)",
"(つд⊂)",
"(≖͞_≖̥)",
"(இ﹏இ`。)",
"༼ಢ_ಢ༽",
"༼ ༎ຶ ෴ ༎ຶ༽",
]
SLAP_TEMPLATES = [
"{hits} {victim} with a {item}.",
"{hits} {victim} in the face with a {item}.",
"{hits} {victim} around a bit with a {item}.",
"{throws} a {item} at {victim}.",
"grabs a {item} and {throws} it at {victim}'s face.",
"{hits} a {item} at {victim}.", "{throws} a few {item} at {victim}.",
"grabs a {item} and {throws} it in {victim}'s face.",
"launches a {item} in {victim}'s general direction.",
"sits on {victim}'s face while slamming a {item} {where}.",
"starts slapping {victim} silly with a {item}.",
"pins {victim} down and repeatedly {hits} them with a {item}.",
"grabs up a {item} and {hits} {victim} with it.",
"starts slapping {victim} silly with a {item}.",
"holds {victim} down and repeatedly {hits} them with a {item}.",
"prods {victim} with a {item}.",
"picks up a {item} and {hits} {victim} with it.",
"ties {victim} to a chair and {throws} a {item} at them.",
"{hits} {victim} {where} with a {item}.",
"ties {victim} to a pole and whips them {where} with a {item}."
"gave a friendly push to help {victim} learn to swim in lava.",
"sent {victim} to /dev/null.", "sent {victim} down the memory hole.",
"beheaded {victim}.", "threw {victim} off a building.",
"replaced all of {victim}'s music with Nickelback.",
"spammed {victim}'s email.", "made {victim} a knuckle sandwich.",
"slapped {victim} with pure nothing.",
"hit {victim} with a small, interstellar spaceship.",
"quickscoped {victim}.", "put {victim} in check-mate.",
"RSA-encrypted {victim} and deleted the private key.",
"put {victim} in the friendzone.",
"slaps {victim} with a DMCA takedown request!"
]
ITEMS = [
"cast iron skillet",
"large trout",
"baseball bat",
"cricket bat",
"wooden cane",
"nail",
"printer",
"shovel",
"pair of trousers",
"CRT monitor",
"diamond sword",
"baguette",
"physics textbook",
"toaster",
"portrait of Richard Stallman",
"television",
"mau5head",
"five ton truck",
"roll of duct tape",
"book",
"laptop",
"old television",
"sack of rocks",
"rainbow trout",
"cobblestone block",
"lava bucket",
"rubber chicken",
"spiked bat",
"gold block",
"fire extinguisher",
"heavy rock",
"chunk of dirt",
"beehive",
"piece of rotten meat",
"bear",
"ton of bricks",
]
THROW = [
"throws",
"flings",
"chucks",
"hurls",
]
HIT = [
"hits",
"whacks",
"slaps",
"smacks",
"bashes",
]
ABUSEHARD_STRING = [
"`Madarchod Randi ke bacche.Oye bosdike madarchod bhen ke lode tere gand me lohe ka danda garam karke dalu randwe tujhetho gali ke kutte gand pe chut rakh ke katenge me bata raha hu tere lode pe madhu makkhi Katelode ke ando pe Road roller chale tu kab bathroom me muthne Jaye tho Tera loda ghir Jaye fir tere ando me se lizard ke bacche nikle teko kidnap Kare aur childporn banaye maa ke chuttad ke lode tere saat Johnny sins rape Kare aur jab wo teko anal de tab loda andar fas Jaye bkl tere jhaat pe waxing karunga me dhek lio fir jab tu chillayega na tab tere muh me Mai gai ka gobar dalunga sale tere gand ke balo pe tel laga ke jala du me teko Anaconda leke gand me dalu tho muh se nikle maa ke lode hamesha chutiyo jaisa bartav kartha he tu maa ke Dai chawal drugs tere gand Me dalunga thi tatti nahi nikle maa darchod kabhi teko Marne ka mouka mil gaya na tho bas I'll do my best to get that tatti outof you aur tere jaise chutio ko is duniya me jagaha bhi nahi maa ke lode bandarchod tere gand me chitiya Kate wo bhi bullet ants maadarchod samj nahi aaraha tere baap NE teko kya khake paida kiya Tha kesa chutiya he tu rand ke bacche teko shadi me khana khane na mile teko gand pe 4 thappad mare sab log aur blade se likhe I want anal madarchod bosdike maccharki tatte ke baal chutiye maa ke chut pe ghode ka Lund tere gand me jaltha hu koila Dale bhen ke lode MAA KI CHUT MAI TALWAR DUNGA BC CHUT FAT JAEGI AUR USME SE ITNA KHOON NIKLEGA MZA AJAEGA DEKHNE KA SALE MAA KE BHOSDE SE BAHR AJA FIR BAAP SE ZUBAN DA TERI MAA KI CHUT CHOD CHOD KE BHOSDABNADU MADARCHOD AUR USKE UPAR CENENT LAGADU KI TERE JESA GANDU INSAAN KABHI BAHR NA A SKE ESI GANDI CHUT MAI SE LODA LASUN MADRCHOD TERI MAA KI CHUT GASTI AMA KA CHUTIA BACHA TERI MAA KO CHOD CHOD K PAGAL KAR DUNGA MAA K LODY KISI SASTIII RANDII K BACHY TERI MAA KI CHOOT MAIN TEER MAARUN GANDU HARAMI TERI COLLEGE JATI BAJI KA ROAD PEY RAPE KARONGANDU KI OLAAD HARAM KI NASAL PAPA HUN TERA BHEN PESH KAR AB PAPA KO TERI MAA KKALE KUSS MAIN KIS`",
"`Main roz teri behno ki banjar chut me apna lawda daalke andar haryali lata tha magar aaj unke ke baare me sunke mujhe bhut afsos huwa..ki unko ab bada loudha chahye..ab mera balatkaaari lawda lagataar 4 ghante tk apne muh me kon rakhega..vo teri behne hi thi jo apni kaali magar rasilli chut mere saamne khol deti aur zameen pe naagin ki tarah rengne lgti thi jaise ki kisine unki chut pe naariyal tod diya ho vo b bada wala mumbai ka naariyal..apni chennal maa ko b nhi bhej rahe mere paas to main kaixe tum logo se vaada karu ki main teri maa chodd dungaw..ab agar tun sach me chahta hai ki main tum dono k mc ki chut me dhammal karu to mera lawda apne muh me rakho aur kaho Sameer hamare sage papa hain... Aur agar tb b the apni maa ki kaali chut mere saamne nahi rakhi to tumhare ghar me ghuske tumhari maa ka balatkaar kar dungaw jaixe delhi me huwa tha...ab teri chudi hui kuttiyo ki tarah apni gaand hilaate hue mere aage kalapna mt ni to tumhari fatti bhoxdi me 100 ched karunga`",
]
ABUSE_STRINGS = [
"`Madharchod hai kya tu lavde ?`",
"`Gaandu paida liya tha kya chutiya`",
"`Lavde teri gand mardunga`",
"`Abee Ja be Gaandu`",
"`Teri Ma ka Bhodsa madharchod`",
"`mu meh leta hai kya sab ka tu madarchod`",
"`Jyada gand na fulaao maa chod dengi tumhari bsdk....`",
"`Muh Me Lega Bhosdike ?`"
]
GEY_STRINGS = [
"`you gey bsdk`",
"`you gey`",
"`Nikal na gey bc`",
"`you chakka`",
"`you gey gey gey gey gey gey gey gey`",
"`you gey go away`",
]
RAPE_STRINGS = [
"`Dekho Bhaiyya esa hai! Izzat bachailo apni warna Gaand maar lenge tumhari`",
"`Relax your Rear, ders nothing to fear,The Rape train is finally here`",
"`Lodu Andha hai kya Yaha tera rape ho raha hai aur tu abhi tak yahi gaand mara raha hai lulz`",
]
WHERE = ["in the chest", "on the head", "on the butt", "on the crotch"]
# ===========================================
@register(outgoing=True, pattern=r"^.(\w+)say (.*)")
async def univsaye(cowmsg):
""" For .cowsay module, userbot wrapper for cow which says things. """
arg = cowmsg.pattern_match.group(1).lower()
text = cowmsg.pattern_match.group(2)
if arg == "cow":
arg = "default"
if arg not in cow.COWACTERS:
return
cheese = cow.get_cow(arg)
cheese = cheese()
await cowmsg.edit(f"`{cheese.milk(text).replace("`", "´")}`")
@register(outgoing=True, pattern="^:/$", ignore_unsafe=True)
async def kek(keks):
""" Check yourself ;)"""
uio = ["/", "\\"]
for i in range(1, 15):
time.sleep(0.3)
await keks.edit(":" + uio[i % 2])
@register(outgoing=True, pattern=r"^.coinflip (.*)")
async def coin(event):
r = choice(["heads", "tails"])
input_str = event.pattern_match.group(1)
if input_str:
input_str = input_str.lower()
if r == "heads":
if input_str == "heads":
await event.edit(
"The coin landed on: **Heads**.\nYou were correct.")
elif input_str == "tails":
await event.edit(
"The coin landed on: **Heads**.\nYou weren't correct, try again ..."
)
else:
await event.edit("The coin landed on: **Heads**.")
elif r == "tails":
if input_str == "tails":
await event.edit(
"The coin landed on: **Tails**.\nYou were correct.")
elif input_str == "heads":
await event.edit(
"The coin landed on: **Tails**.\nYou weren't correct, try again ..."
)
else:
await event.edit("The coin landed on: **Tails**.")
@register(pattern="^.slap(?: |$)(.*)", outgoing=True)
async def who(event):
""" slaps a user, or get slapped if not a reply. """
replied_user = await get_user_from_event(event)
if replied_user:
replied_user = replied_user[0]
else:
return
caption = await slap(replied_user, event)
try:
await event.edit(caption)
except BaseException:
await event.edit(
"`Can't slap this person, need to fetch some sticks and stones !!`"
)
async def slap(replied_user, event):
""" Construct a funny slap sentence !! """
user_id = replied_user.id
first_name = replied_user.first_name
username = replied_user.username
if username:
slapped = "@{}".format(username)
else:
slapped = f"[{first_name}](tg://user?id={user_id})"
temp = choice(SLAP_TEMPLATES)
item = choice(ITEMS)
hit = choice(HIT)
throw = choice(THROW)
where = choice(WHERE)
caption = "..." + temp.format(
victim=slapped, item=item, hits=hit, throws=throw, where=where)
return caption
@register(outgoing=True, pattern="^-_-$", ignore_unsafe=True)
async def lol(lel):
""" Ok... """
okay = "-_-"
for i in range(10):
okay = okay[:-1] + "_-"
await lel.edit(okay)
@register(outgoing=True, pattern="^.(yes|no|maybe|decide)$")
async def decide(event):
decision = event.pattern_match.group(1).lower()
message_id = event.reply_to_msg_id if event.reply_to_msg_id else None
if decision != "decide":
r = requests.get(f"https://yesno.wtf/api?force={decision}").json()
else:
r = requests.get(f"https://yesno.wtf/api").json()
await event.delete()
await event.client.send_message(event.chat_id,
str(r["answer"]).upper(),
reply_to=message_id,
file=r["image"])
@register(outgoing=True, pattern="^;_;$", ignore_unsafe=True)
async def fun(e):
t = ";_;"
for j in range(10):
t = t[:-1] + "_;"
await e.edit(t)
@register(outgoing=True, pattern="^.fp$")
async def facepalm(e):
""" Facepalm 🤦♂ """
await e.edit("🤦♂")
@register(outgoing=True, pattern="^.cry$")
async def cry(e):
""" y u du dis, i cry everytime !! """
await e.edit(choice(CRI))
@register(outgoing=True, pattern="^.insult$")
async def insult(e):
""" I make you cry !! """
await e.edit(choice(INSULT_STRINGS))
@register(outgoing=True, pattern="^.cp(?: |$)(.*)")
async def copypasta(cp_e):
""" Copypasta the famous meme """
textx = await cp_e.get_reply_message()
message = cp_e.pattern_match.group(1)
if message:
pass
elif textx:
message = textx.text
else:
await cp_e.edit("`😂🅱️IvE👐sOME👅text👅for✌️Me👌tO👐MAkE👀iT💞funNy!💦`")
return
reply_text = choice(EMOJIS)
# choose a random character in the message to be substituted with 🅱️
b_char = choice(message).lower()
for owo in message:
if owo == " ":
reply_text += choice(EMOJIS)
elif owo in EMOJIS:
reply_text += owo
reply_text += choice(EMOJIS)
elif owo.lower() == b_char:
reply_text += "🅱️"
else:
if bool(getrandbits(1)):
reply_text += owo.upper()
else:
reply_text += owo.lower()
reply_text += choice(EMOJIS)
await cp_e.edit(reply_text)
@register(outgoing=True, pattern="^.vapor(?: |$)(.*)")
async def vapor(vpr):
""" Vaporize everything! """
reply_text = list()
textx = await vpr.get_reply_message()
message = vpr.pattern_match.group(1)
if message:
pass
elif textx:
message = textx.text
else:
await vpr.edit("`Give some text for vapor!`")
return
for charac in message:
if 0x21 <= ord(charac) <= 0x7F:
reply_text.append(chr(ord(charac) + 0xFEE0))
elif ord(charac) == 0x20:
reply_text.append(chr(0x3000))
else:
reply_text.append(charac)
await vpr.edit("".join(reply_text))
@register(outgoing=True, pattern="^.str(?: |$)(.*)")
async def stretch(stret):
""" Stretch it."""
textx = await stret.get_reply_message()
message = stret.text
message = stret.pattern_match.group(1)
if message:
pass
elif textx:
message = textx.text
else:
await stret.edit("`GiiiiiiiB sooooooomeeeeeee teeeeeeext!`")
return
count = randint(3, 10)
reply_text = sub(r"([aeiouAEIOUaeiouAEIOUаеиоуюяыэё])", (r"\1" * count),
message)
await stret.edit(reply_text)
@register(outgoing=True, pattern="^.zal(?: |$)(.*)")
async def zal(zgfy):
""" Invoke the feeling of chaos. """
reply_text = list()
textx = await zgfy.get_reply_message()
message = zgfy.pattern_match.group(1)
if message:
pass
elif textx:
message = textx.text
else:
await zgfy.edit(
"`gͫ ̆ i̛ ̺ v͇̆ ȅͅ a̢ͦ s̴̪ c̸̢ ä̸ rͩͣ y͖͞ t̨͚ é̠ x̢͖ t͔͛`"
)
return
for charac in message:
if not charac.isalpha():
reply_text.append(charac)
continue
for _ in range(0, 3):
randint = randint(0, 2)
if randint == 0:
charac = charac.strip() + \
choice(ZALG_LIST[0]).strip()
elif randint == 1:
charac = charac.strip() + \
choice(ZALG_LIST[1]).strip()
else:
charac = charac.strip() + \
choice(ZALG_LIST[2]).strip()
reply_text.append(charac)
await zgfy.edit("".join(reply_text))
@register(outgoing=True, pattern="^.hi$")
async def hoi(hello):
""" Greet everyone! """
await hello.edit(choice(HELLOSTR))
@register(outgoing=True, pattern="^.owo(?: |$)(.*)")
async def faces(owo):
""" UwU """
textx = await owo.get_reply_message()
message = owo.pattern_match.group(1)
if message:
pass
elif textx:
message = textx.text
else:
await owo.edit("` UwU no text given! `")
return
reply_text = sub(r"(r|l)", "w", message)
reply_text = sub(r"(R|L)", "W", reply_text)
reply_text = sub(r"n([aeiou])", r"ny\1", reply_text)
reply_text = sub(r"N([aeiouAEIOU])", r"Ny\1", reply_text)
reply_text = sub(r"\!+", " " + choice(UWUS), reply_text)
reply_text = reply_text.replace("ove", "uv")
reply_text += " " + choice(UWUS)
await owo.edit(reply_text)
@register(outgoing=True, pattern="^.react$")
async def react_meme(react):
""" Make your userbot react to everything. """
await react.edit(choice(FACEREACTS))
@register(outgoing=True, pattern="^.shg$")
async def shrugger(shg):
r""" ¯\_(ツ)_/¯ """
await shg.edit(choice(SHGS))
@register(outgoing=True, pattern="^.chase$")
async def police(chase):
""" Run boi run, i'm gonna catch you !! """
await chase.edit(choice(CHASE_STR))
@register(outgoing=True, pattern="^.run$")
async def runner_lol(run):
""" Run, run, RUNNN! """
await run.edit(choice(RUNS_STR))
@register(outgoing=True, pattern="^.metoo$")
async def metoo(hahayes):
""" Haha yes """
await hahayes.edit(choice(METOOSTR))
@register(outgoing=True, pattern="^Oof$")
async def Oof(e):
t = "Oof"
for j in range(15):
t = t[:-1] + "of"
await e.edit(t)
@register(outgoing=True, pattern="^.10iq$")
async def iqless(e):
await e.edit("♿")
@register(outgoing=True, pattern="^.moon$")
async def moon(event):
deq = deque(list("🌗🌘🌑🌒🌓🌔🌕🌖"))
try:
for x in range(32):
await sleep(0.1)
await event.edit("".join(deq))
deq.rotate(1)
except BaseException:
return
@register(outgoing=True, pattern="^.clock$")
async def clock(event):
deq = deque(list("🕙🕘🕗🕖🕕🕔🕓🕒🕑🕐🕛"))
try:
for x in range(32):
await sleep(0.1)
await event.edit("".join(deq))
deq.rotate(1)
except BaseException:
return
@register(outgoing=True, pattern="^.mock(?: |$)(.*)")
async def spongemocktext(mock):
""" Do it and find the real fun. """
reply_text = list()
textx = await mock.get_reply_message()
message = mock.pattern_match.group(1)
if message:
pass
elif textx:
message = textx.text
else:
await mock.edit("`gIvE sOMEtHInG tO MoCk!`")
return
for charac in message:
if charac.isalpha() and randint(0, 1):
to_app = charac.upper() if charac.islower() else charac.lower()
reply_text.append(to_app)
else:
reply_text.append(charac)
await mock.edit("".join(reply_text))
@register(outgoing=True, pattern="^.clap(?: |$)(.*)")
async def claptext(memereview):
""" Praise people! """
textx = await memereview.get_reply_message()
message = memereview.pattern_match.group(1)
if message:
pass
elif textx:
message = textx.text
else:
await memereview.edit("`Hah, I don't clap pointlessly!`")
return
reply_text = "👏 "
reply_text += message.replace(" ", " 👏 ")
reply_text += " 👏"
await memereview.edit(reply_text)
@register(outgoing=True, pattern="^.bt$")
async def bluetext(bt_e):
""" Believe me, you will find this useful. """
if await bt_e.get_reply_message() and bt_e.is_group:
await bt_e.edit(
"/BLUETEXT /MUST /CLICK.\n"
"/ARE /YOU /A /STUPID /ANIMAL /WHICH /IS /ATTRACTED /TO /COLOURS?")
@register(outgoing=True, pattern=r"^.f (.*)")
async def payf(event):
paytext = event.pattern_match.group(1)
pay = "{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}".format(
paytext * 8, paytext * 8, paytext * 2, paytext * 2, paytext * 2,
paytext * 6, paytext * 6, paytext * 2, paytext * 2, paytext * 2,
paytext * 2, paytext * 2)
await event.edit(pay)
@register(outgoing=True, pattern="^.googleit (.*)")
async def let_me_google_that_for_you(lmgtfy_q):
textx = await lmgtfy_q.get_reply_message()
qry = lmgtfy_q.pattern_match.group(1)
if qry:
query = str(qry)
elif textx:
query = textx
query = query.message
query_encoded = query.replace(" ", "+")
lfy_url = f"http://lmgtfy.com/?s=g&iie=1&q={query_encoded}"
payload = {'format': 'json', 'url': lfy_url}
r = requests.get('http://is.gd/create.php', params=payload)
await lmgtfy_q.edit(f"Here you are, help yourself.\
\n[{query}]({r.json()['shorturl']})")
@register(pattern=r".scam(?: |$)(.*)", outgoing=True)
async def scam(event):
""" Just a small command to fake chat actions for fun !! """
options = [
'typing', 'contact', 'game', 'location', 'voice', 'round', 'video',
'photo', 'document', 'cancel'
]
input_str = event.pattern_match.group(1)
args = input_str.split()
if len(args) is 0: # Let bot decide action and time
scam_action = choice(options)
scam_time = randint(30, 60)
elif len(args) is 1: # User decides time/action, bot decides the other.
try:
scam_action = str(args[0]).lower()
scam_time = randint(30, 60)
except ValueError:
scam_action = choice(options)
scam_time = int(args[0])
elif len(args) is 2: # User decides both action and time
scam_action = str(args[0]).lower()
scam_time = int(args[1])
else:
await event.edit("`Invalid Syntax !!`")
return
try:
if (scam_time > 0):
await event.delete()
async with event.client.action(event.chat_id, scam_action):
await sleep(scam_time)
except BaseException:
return
@register(outgoing=True, pattern="^.abusehard$")
async def fuckedd (abusehard):
""" Use with caution """
if not abusehard.text[0].isalpha() and abusehard.text[0] not in ("/", "#", "@", "!"):
index = random.randint(0, len(ABUSEHARD_STRING) - 1)
reply_text = ABUSEHARD_STRING[index]
await abusehard.edit(reply_text)
@register(outgoing=True, pattern="^.rape$")
async def raping (raped):
""" -,- """
if not raped.text[0].isalpha() and raped.text[0] not in ("/", "#", "@", "!"):
index = random.randint(0, len(RAPE_STRINGS) - 1)
reply_text = RAPE_STRINGS[index]
await raped.edit(reply_text)
@register(outgoing=True, pattern="^.gey$")
async def geys (geyed):
""" :/ """
if not geyed.text[0].isalpha() and geyed.text[0] not in ("/", "#", "@", "!"):
index = random.randint(0, len(GEY_STRINGS) - 1)
reply_text = GEY_STRINGS[index]
await geyed.edit(reply_text)
@register(outgoing=True, pattern="^.abuse$")
async def abusing (abused):
""" Ez Abuse """
if not abused.text[0].isalpha() and abused.text[0] not in ("/", "#", "@", "!"):
index = random.randint(0, len(ABUSE_STRINGS) - 1)
reply_text = ABUSE_STRINGS[index]
await abused.edit(reply_text)
@register(outgoing=True, pattern="^.reep$")
async def restinpeace (rest):
""" Ezio Auditore R.I.P """
if not rest.text[0].isalpha() and rest.text[0] not in ("/", "#", "@", "!"):
if await rest.get_reply_message():
await rest.edit(
"`Requiescat In Pace ☠️`\n"
)
@register(pattern=r".type(?: |$)(.*)", outgoing=True)
async def typewriter(typew):
""" Just a small command to make your keyboard become a typewriter! """
textx = await typew.get_reply_message()
message = typew.pattern_match.group(1)
if message:
pass
elif textx:
message = textx.text
else:
await typew.edit("`Give a text to type!`")
return
sleep_time = 0.03
typing_symbol = "|"
old_text = ""
await typew.edit(typing_symbol)
await sleep(sleep_time)
for character in message:
old_text = old_text + "" + character
typing_text = old_text + "" + typing_symbol
await typew.edit(typing_text)
await sleep(sleep_time)
await typew.edit(old_text)
await sleep(sleep_time)
CMD_HELP.update({
"memes":
".cowsay\
\nUsage: cow which says things.\
\n\n:/\
\nUsage: Check yourself ;)\
\n\n-_-\
\nUsage: Ok...\
\n\n;_;\
\nUsage: Like `-_-` but crying.\
\n\n.cp\
\nUsage: Copypasta the famous meme\
\n\n.vapor\
\nUsage: Vaporize everything!\
\n\n.str\
\nUsage: Stretch it.\
\n\n.10iq\
\nUsage: You retard !!\
\n\n.zal\
\nUsage: Invoke the feeling of chaos.\
\n\nOof\
\nUsage: Ooooof\
\n\n.fp\
\nUsage: Facepalm :P\
\n\n.moon\
\nUsage: kensar moon animation.\
\n\n.clock\
\nUsage: kensar clock animation.\
\n\n.hi\
\nUsage: Greet everyone!\
\n\n.coinflip <heads/tails>\
\nUsage: Flip a coin !!\
\n\n.owo\
\nUsage: UwU\
\n\n.react\
\nUsage: Make your userbot react to everything.\
\n\n.slap\
\nUsage: reply to slap them with random objects !!\
\n\n.cry\
\nUsage: y u du dis, i cri.\
\n\n.shg\
\nUsage: Shrug at it !!\
\n\n.run\
\nUsage: Let Me Run, run, RUNNN!\
\n\n.chase\
\nUsage: You better start running\
\n\n.metoo\
\nUsage: Haha yes\
\n\n.mock\
\nUsage: Do it and find the real fun.\
\n\n.clap\
\nUsage: Praise people!\
\n\n.f <emoji/character>\
\nUsage: Pay Respects.\
\n\n.bt\
\nUsage: Believe me, you will find this useful.\
\n\n.type\
\nUsage: Just a small command to make your keyboard become a typewriter!\
\n\n.googleit <query>\
\nUsage: Let me Google that for you real quick !!\
\n\n.decide [Alternates: (.yes, .no, .maybe)]\
\nUsage: Make a quick decision.\
\n\n.scam <action> <time>\
\n[Available Actions: (typing, contact, game, location, voice, round, video, photo, document, cancel)]\
\nUsage: Create fake chat actions, for fun. (Default action: typing)\
\n\n\nThanks to 🅱️ottom🅱️ext🅱️ot (@NotAMemeBot) for some of these."
})
| # Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
""" Userbot module for having some fun with people. """
from asyncio import sleep
from random import choice, getrandbits, randint
from re import sub
import time
from collections import deque
import requests
from cowpy import cow
from userbot import CMD_HELP
from userbot.events import register
from userbot.modules.admin import get_user_from_event
# ================= CONSTANT =================
METOOSTR = [
"Me too thanks",
"Haha yes, me too",
"Same lol",
"Me irl",
"Same here",
"Haha yes",
"Me rn",
]
ZALG_LIST = [[
"̖",
" ̗",
" ̘",
" ̙",
" ̜",
" ̝",
" ̞",
" ̟",
" ̠",
" ̤",
" ̥",
" ̦",
" ̩",
" ̪",
" ̫",
" ̬",
" ̭",
" ̮",
" ̯",
" ̰",
" ̱",
" ̲",
" ̳",
" ̹",
" ̺",
" ̻",
" ̼",
" ͅ",
" ͇",
" ͈",
" ͉",
" ͍",
" ͎",
" ͓",
" ͔",
" ͕",
" ͖",
" ͙",
" ͚",
" ",
],
[
" ̍",
" ̎",
" ̄",
" ̅",
" ̿",
" ̑",
" ̆",
" ̐",
" ͒",
" ͗",
" ͑",
" ̇",
" ̈",
" ̊",
" ͂",
" ̓",
" ̈́",
" ͊",
" ͋",
" ͌",
" ̃",
" ̂",
" ̌",
" ͐",
" ́",
" ̋",
" ̏",
" ̽",
" ̉",
" ͣ",
" ͤ",
" ͥ",
" ͦ",
" ͧ",
" ͨ",
" ͩ",
" ͪ",
" ͫ",
" ͬ",
" ͭ",
" ͮ",
" ͯ",
" ̾",
" ͛",
" ͆",
" ̚",
],
[
" ̕",
" ̛",
" ̀",
" ́",
" ͘",
" ̡",
" ̢",
" ̧",
" ̨",
" ̴",
" ̵",
" ̶",
" ͜",
" ͝",
" ͞",
" ͟",
" ͠",
" ͢",
" ̸",
" ̷",
" ͡",
]]
EMOJIS = [
"😂",
"😂",
"👌",
"✌",
"💞",
"👍",
"👌",
"💯",
"🎶",
"👀",
"😂",
"👓",
"👏",
"👐",
"🍕",
"💥",
"🍴",
"💦",
"💦",
"🍑",
"🍆",
"😩",
"😏",
"👉👌",
"👀",
"👅",
"😩",
"🚰",
]
INSULT_STRINGS = [
"Owww ... Such a stupid idiot.",
"Don't drink and type.",
"I think you should go home or better a mental asylum.",
"Command not found. Just like your brain.",
"Do you realize you are making a fool of yourself? Apparently not.",
"You can type better than that.",
"Bot rule 544 section 9 prevents me from replying to stupid humans like you.",
"Sorry, we do not sell brains.",
"Believe me you are not normal.",
"I bet your brain feels as good as new, seeing that you never use it.",
"If I wanted to kill myself I'd climb your ego and jump to your IQ.",
"Zombies eat brains... you're safe.",
"You didn't evolve from apes, they evolved from you.",
"Come back and talk to me when your I.Q. exceeds your age.",
"I'm not saying you're stupid, I'm just saying you've got bad luck when it comes to thinking.",
"What language are you speaking? Cause it sounds like bullshit.",
"Stupidity is not a crime so you are free to go.",
"You are proof that evolution CAN go in reverse.",
"I would ask you how old you are but I know you can't count that high.",
"As an outsider, what do you think of the human race?",
"Brains aren't everything. In your case they're nothing.",
"Ordinarily people live and learn. You just live.",
"I don't know what makes you so stupid, but it really works.",
"Keep talking, someday you'll say something intelligent! (I doubt it though)",
"Shock me, say something intelligent.",
"Your IQ's lower than your shoe size.",
"Alas! Your neurotransmitters are no more working.",
"Are you crazy you fool.",
"Everyone has the right to be stupid but you are abusing the privilege.",
"I'm sorry I hurt your feelings when I called you stupid. I thought you already knew that.",
"You should try tasting cyanide.",
"Your enzymes are meant to digest rat poison.",
"You should try sleeping forever.",
"Pick up a gun and shoot yourself.",
"You could make a world record by jumping from a plane without parachute.",
"Stop talking BS and jump in front of a running bullet train.",
"Try bathing with Hydrochloric Acid instead of water.",
"Try this: if you hold your breath underwater for an hour, you can then hold it forever.",
"Go Green! Stop inhaling Oxygen.",
"God was searching for you. You should leave to meet him.",
"give your 100%. Now, go donate blood.",
"Try jumping from a hundred story building but you can do it only once.",
"You should donate your brain seeing that you never used it.",
"Volunteer for target in an firing range.",
"Head shots are fun. Get yourself one.",
"You should try swimming with great white sharks.",
"You should paint yourself red and run in a bull marathon.",
"You can stay underwater for the rest of your life without coming back up.",
"How about you stop breathing for like 1 day? That'll be great.",
"Try provoking a tiger while you both are in a cage.",
"Have you tried shooting yourself as high as 100m using a canon.",
"You should try holding TNT in your mouth and igniting it.",
"Try playing catch and throw with RDX its fun.",
"I heard phogine is poisonous but i guess you wont mind inhaling it for fun.",
"Launch yourself into outer space while forgetting oxygen on Earth.",
"You should try playing snake and ladders, with real snakes and no ladders.",
"Dance naked on a couple of HT wires.",
"Active Volcano is the best swimming pool for you.",
"You should try hot bath in a volcano.",
"Try to spend one day in a coffin and it will be yours forever.",
"Hit Uranium with a slow moving neutron in your presence. It will be a worthwhile experience.",
"You can be the first person to step on sun. Have a try.",
]
UWUS = [
"(・`ω´・)",
";;w;;",
"owo",
"UwU",
">w<",
"^w^",
r"\(^o\) (/o^)/",
"( ^ _ ^)∠☆",
"(ô_ô)",
"~:o",
";-;",
"(*^*)",
"(>_",
"(♥_♥)",
"*(^O^)*",
"((+_+))",
]
FACEREACTS = [
"ʘ‿ʘ",
"ヾ(-_- )ゞ",
"(っ˘ڡ˘ς)",
"(´ж`ς)",
"( ಠ ʖ̯ ಠ)",
"(° ͜ʖ͡°)╭∩╮",
"(ᵟຶ︵ ᵟຶ)",
"(งツ)ว",
"ʚ(•`",
"(っ▀¯▀)つ",
"(◠﹏◠)",
"( ͡ಠ ʖ̯ ͡ಠ)",
"( ఠ ͟ʖ ఠ)",
"(∩`-´)⊃━☆゚.*・。゚",
"(⊃。•́‿•̀。)⊃",
"(._.)",
"{•̃_•̃}",
"(ᵔᴥᵔ)",
"♨_♨",
"⥀.⥀",
"ح˚௰˚づ ",
"(҂◡_◡)",
"ƪ(ړײ)ƪ",
"(っ•́。•́)♪♬",
"◖ᵔᴥᵔ◗ ♪ ♫ ",
"(☞゚ヮ゚)☞",
"[¬º-°]¬",
"(Ծ‸ Ծ)",
"(•̀ᴗ•́)و ̑̑",
"ヾ(´〇`)ノ♪♪♪",
"(ง'̀-'́)ง",
"ლ(•́•́ლ)",
"ʕ •́؈•̀ ₎",
"♪♪ ヽ(ˇ∀ˇ )ゞ",
"щ(゚Д゚щ)",
"( ˇ෴ˇ )",
"눈_눈",
"(๑•́ ₃ •̀๑) ",
"( ˘ ³˘)♥ ",
"ԅ(≖‿≖ԅ)",
"♥‿♥",
"◔_◔",
"⁽⁽ଘ( ˊᵕˋ )ଓ⁾⁾",
"乁( ◔ ౪◔)「 ┑( ̄Д  ̄)┍",
"( ఠൠఠ )ノ",
"٩(๏_๏)۶",
"┌(ㆆ㉨ㆆ)ʃ",
"ఠ_ఠ",
"(づ。◕‿‿◕。)づ",
"(ノಠ ∩ಠ)ノ彡( \\o°o)\\",
"“ヽ(´▽`)ノ”",
"༼ ༎ຶ ෴ ༎ຶ༽",
"。゚( ゚இ‸இ゚)゚。",
"(づ ̄ ³ ̄)づ",
"(⊙.☉)7",
"ᕕ( ᐛ )ᕗ",
"t(-_-t)",
"(ಥ⌣ಥ)",
"ヽ༼ ಠ益ಠ ༽ノ",
"༼∵༽ ༼⍨༽ ༼⍢༽ ༼⍤༽",
"ミ●﹏☉ミ",
"(⊙_◎)",
"¿ⓧ_ⓧﮌ",
"ಠ_ಠ",
"(´・_・`)",
"ᕦ(ò_óˇ)ᕤ",
"⊙﹏⊙",
"(╯°□°)╯︵ ┻━┻",
r"¯\_(⊙︿⊙)_/¯",
"٩◔̯◔۶",
"°‿‿°",
"ᕙ(⇀‸↼‶)ᕗ",
"⊂(◉‿◉)つ",
"V•ᴥ•V",
"q(❂‿❂)p",
"ಥ_ಥ",
"ฅ^•ﻌ•^ฅ",
"ಥ﹏ಥ",
"( ^_^)o自自o(^_^ )",
"ಠ‿ಠ",
"ヽ(´▽`)/",
"ᵒᴥᵒ#",
"( ͡° ͜ʖ ͡°)",
"┬─┬ ノ( ゜-゜ノ)",
"ヽ(´ー`)ノ",
"☜(⌒▽⌒)☞",
"ε=ε=ε=┌(;*´Д`)ノ",
"(╬ ಠ益ಠ)",
"┬─┬⃰͡ (ᵔᵕᵔ͜ )",
"┻━┻ ︵ヽ(`Д´)ノ︵ ┻━┻",
r"¯\_(ツ)_/¯",
"ʕᵔᴥᵔʔ",
"(`・ω・´)",
"ʕ•ᴥ•ʔ",
"ლ(`ー´ლ)",
"ʕʘ̅͜ʘ̅ʔ",
"( ゚Д゚)",
r"¯\(°_o)/¯",
"(。◕‿◕。)",
]
RUNS_STR = [
"Runs to Thanos..",
"Runs far, far away from earth..",
"Running faster than Bolt coz i'mma userbot !!",
"Runs to Marie..",
"This Group is too cancerous to deal with.",
"Cya bois",
"Kys",
"I go away",
"I am just walking off, coz me is too fat.",
"I Fugged off!",
"Will run for chocolate.",
"I run because I really like food.",
"Running...\nbecause dieting is not an option.",
"Wicked fast runnah",
"If you wanna catch me, you got to be fast...\nIf you wanna stay with me, you got to be good...\nBut if you wanna pass me...\nYou've got to be kidding.",
"Anyone can run a hundred meters, it's the next forty-two thousand and two hundred that count.",
"Why are all these people following me?",
"Are the kids still chasing me?",
"Running a marathon...there's an app for that.",
]
CHASE_STR = [
"Where do you think you're going?",
"Huh? what? did they get away?",
"ZZzzZZzz... Huh? what? oh, just them again, nevermind.",
"Get back here!",
"Not so fast...",
"Look out for the wall!",
"Don't leave me alone with them!!",
"You run, you die.",
"Jokes on you, I'm everywhere",
"You're gonna regret that...",
"You could also try /kickme, I hear that's fun.",
"Go bother someone else, no-one here cares.",
"You can run, but you can't hide.",
"Is that all you've got?",
"I'm behind you...",
"You've got company!",
"We can do this the easy way, or the hard way.",
"You just don't get it, do you?",
"Yeah, you better run!",
"Please, remind me how much I care?",
"I'd run faster if I were you.",
"That's definitely the droid we're looking for.",
"May the odds be ever in your favour.",
"Famous last words.",
"And they disappeared forever, never to be seen again.",
"\"Oh, look at me! I'm so cool, I can run from a bot!\" - this person",
"Yeah yeah, just tap /kickme already.",
"Here, take this ring and head to Mordor while you're at it.",
"Legend has it, they're still running...",
"Unlike Harry Potter, your parents can't protect you from me.",
"Fear leads to anger. Anger leads to hate. Hate leads to suffering. If you keep running in fear, you might "
"be the next Vader.",
"Multiple calculations later, I have decided my interest in your shenanigans is exactly 0.",
"Legend has it, they're still running.",
"Keep it up, not sure we want you here anyway.",
"You're a wiza- Oh. Wait. You're not Harry, keep moving.",
"NO RUNNING IN THE HALLWAYS!",
"Hasta la vista, baby.",
"Who let the dogs out?",
"It's funny, because no one cares.",
"Ah, what a waste. I liked that one.",
"Frankly, my dear, I don't give a damn.",
"My milkshake brings all the boys to yard... So run faster!",
"You can't HANDLE the truth!",
"A long time ago, in a galaxy far far away... Someone would've cared about that. Not anymore though.",
"Hey, look at them! They're running from the inevitable banhammer... Cute.",
"Han shot first. So will I.",
"What are you running after, a white rabbit?",
"As The Doctor would say... RUN!",
]
HELLOSTR = [
"Hi !",
"‘Ello, gov'nor!",
"What’s crackin’?",
"‘Sup, homeslice?",
"Howdy, howdy ,howdy!",
"Hello, who's there, I'm talking.",
"You know who this is.",
"Yo!",
"Whaddup.",
"Greetings and salutations!",
"Hello, sunshine!",
"Hey, howdy, hi!",
"What’s kickin’, little chicken?",
"Peek-a-boo!",
"Howdy-doody!",
"Hey there, freshman!",
"I come in peace!",
"Ahoy, matey!",
"Hiya!",
]
SHGS = [
"┐(´д`)┌",
"┐(´~`)┌",
"┐(´ー`)┌",
"┐( ̄ヘ ̄)┌",
"╮(╯∀╰)╭",
"╮(╯_╰)╭",
"┐(´д`)┌",
"┐(´∀`)┌",
"ʅ(́◡◝)ʃ",
"┐(゚~゚)┌",
"┐('д')┌",
"┐(‘~`;)┌",
"ヘ(´-`;)ヘ",
"┐( -“-)┌",
"ʅ(´◔౪◔)ʃ",
"ヽ(゜~゜o)ノ",
"ヽ(~~~ )ノ",
"┐(~ー~;)┌",
"┐(-。ー;)┌",
r"¯\_(ツ)_/¯",
r"¯\_(⊙_ʖ⊙)_/¯",
r"¯\_༼ ಥ ‿ ಥ ༽_/¯",
"乁( ⁰͡ Ĺ̯ ⁰͡ ) ㄏ",
]
CRI = [
"أ‿أ",
"╥﹏╥",
"(;﹏;)",
"(ToT)",
"(┳Д┳)",
"(ಥ﹏ಥ)",
"(;へ:)",
"(T_T)",
"(πーπ)",
"(T▽T)",
"(⋟﹏⋞)",
"(iДi)",
"(´Д⊂ヽ",
"(;Д;)",
"(>﹏<)",
"(TдT)",
"(つ﹏⊂)",
"༼☯﹏☯༽",
"(ノ﹏ヽ)",
"(ノAヽ)",
"(╥_╥)",
"(T⌓T)",
"(༎ຶ⌑༎ຶ)",
"(☍﹏⁰)。",
"(ಥ_ʖಥ)",
"(つд⊂)",
"(≖͞_≖̥)",
"(இ﹏இ`。)",
"༼ಢ_ಢ༽",
"༼ ༎ຶ ෴ ༎ຶ༽",
]
SLAP_TEMPLATES = [
"{hits} {victim} with a {item}.",
"{hits} {victim} in the face with a {item}.",
"{hits} {victim} around a bit with a {item}.",
"{throws} a {item} at {victim}.",
"grabs a {item} and {throws} it at {victim}'s face.",
"{hits} a {item} at {victim}.", "{throws} a few {item} at {victim}.",
"grabs a {item} and {throws} it in {victim}'s face.",
"launches a {item} in {victim}'s general direction.",
"sits on {victim}'s face while slamming a {item} {where}.",
"starts slapping {victim} silly with a {item}.",
"pins {victim} down and repeatedly {hits} them with a {item}.",
"grabs up a {item} and {hits} {victim} with it.",
"starts slapping {victim} silly with a {item}.",
"holds {victim} down and repeatedly {hits} them with a {item}.",
"prods {victim} with a {item}.",
"picks up a {item} and {hits} {victim} with it.",
"ties {victim} to a chair and {throws} a {item} at them.",
"{hits} {victim} {where} with a {item}.",
"ties {victim} to a pole and whips them {where} with a {item}."
"gave a friendly push to help {victim} learn to swim in lava.",
"sent {victim} to /dev/null.", "sent {victim} down the memory hole.",
"beheaded {victim}.", "threw {victim} off a building.",
"replaced all of {victim}'s music with Nickelback.",
"spammed {victim}'s email.", "made {victim} a knuckle sandwich.",
"slapped {victim} with pure nothing.",
"hit {victim} with a small, interstellar spaceship.",
"quickscoped {victim}.", "put {victim} in check-mate.",
"RSA-encrypted {victim} and deleted the private key.",
"put {victim} in the friendzone.",
"slaps {victim} with a DMCA takedown request!"
]
ITEMS = [
"cast iron skillet",
"large trout",
"baseball bat",
"cricket bat",
"wooden cane",
"nail",
"printer",
"shovel",
"pair of trousers",
"CRT monitor",
"diamond sword",
"baguette",
"physics textbook",
"toaster",
"portrait of Richard Stallman",
"television",
"mau5head",
"five ton truck",
"roll of duct tape",
"book",
"laptop",
"old television",
"sack of rocks",
"rainbow trout",
"cobblestone block",
"lava bucket",
"rubber chicken",
"spiked bat",
"gold block",
"fire extinguisher",
"heavy rock",
"chunk of dirt",
"beehive",
"piece of rotten meat",
"bear",
"ton of bricks",
]
THROW = [
"throws",
"flings",
"chucks",
"hurls",
]
HIT = [
"hits",
"whacks",
"slaps",
"smacks",
"bashes",
]
ABUSEHARD_STRING = [
"`Madarchod Randi ke bacche.Oye bosdike madarchod bhen ke lode tere gand me lohe ka danda garam karke dalu randwe tujhetho gali ke kutte gand pe chut rakh ke katenge me bata raha hu tere lode pe madhu makkhi Katelode ke ando pe Road roller chale tu kab bathroom me muthne Jaye tho Tera loda ghir Jaye fir tere ando me se lizard ke bacche nikle teko kidnap Kare aur childporn banaye maa ke chuttad ke lode tere saat Johnny sins rape Kare aur jab wo teko anal de tab loda andar fas Jaye bkl tere jhaat pe waxing karunga me dhek lio fir jab tu chillayega na tab tere muh me Mai gai ka gobar dalunga sale tere gand ke balo pe tel laga ke jala du me teko Anaconda leke gand me dalu tho muh se nikle maa ke lode hamesha chutiyo jaisa bartav kartha he tu maa ke Dai chawal drugs tere gand Me dalunga thi tatti nahi nikle maa darchod kabhi teko Marne ka mouka mil gaya na tho bas I'll do my best to get that tatti outof you aur tere jaise chutio ko is duniya me jagaha bhi nahi maa ke lode bandarchod tere gand me chitiya Kate wo bhi bullet ants maadarchod samj nahi aaraha tere baap NE teko kya khake paida kiya Tha kesa chutiya he tu rand ke bacche teko shadi me khana khane na mile teko gand pe 4 thappad mare sab log aur blade se likhe I want anal madarchod bosdike maccharki tatte ke baal chutiye maa ke chut pe ghode ka Lund tere gand me jaltha hu koila Dale bhen ke lode MAA KI CHUT MAI TALWAR DUNGA BC CHUT FAT JAEGI AUR USME SE ITNA KHOON NIKLEGA MZA AJAEGA DEKHNE KA SALE MAA KE BHOSDE SE BAHR AJA FIR BAAP SE ZUBAN DA TERI MAA KI CHUT CHOD CHOD KE BHOSDABNADU MADARCHOD AUR USKE UPAR CENENT LAGADU KI TERE JESA GANDU INSAAN KABHI BAHR NA A SKE ESI GANDI CHUT MAI SE LODA LASUN MADRCHOD TERI MAA KI CHUT GASTI AMA KA CHUTIA BACHA TERI MAA KO CHOD CHOD K PAGAL KAR DUNGA MAA K LODY KISI SASTIII RANDII K BACHY TERI MAA KI CHOOT MAIN TEER MAARUN GANDU HARAMI TERI COLLEGE JATI BAJI KA ROAD PEY RAPE KARONGANDU KI OLAAD HARAM KI NASAL PAPA HUN TERA BHEN PESH KAR AB PAPA KO TERI MAA KKALE KUSS MAIN KIS`",
"`Main roz teri behno ki banjar chut me apna lawda daalke andar haryali lata tha magar aaj unke ke baare me sunke mujhe bhut afsos huwa..ki unko ab bada loudha chahye..ab mera balatkaaari lawda lagataar 4 ghante tk apne muh me kon rakhega..vo teri behne hi thi jo apni kaali magar rasilli chut mere saamne khol deti aur zameen pe naagin ki tarah rengne lgti thi jaise ki kisine unki chut pe naariyal tod diya ho vo b bada wala mumbai ka naariyal..apni chennal maa ko b nhi bhej rahe mere paas to main kaixe tum logo se vaada karu ki main teri maa chodd dungaw..ab agar tun sach me chahta hai ki main tum dono k mc ki chut me dhammal karu to mera lawda apne muh me rakho aur kaho Sameer hamare sage papa hain... Aur agar tb b the apni maa ki kaali chut mere saamne nahi rakhi to tumhare ghar me ghuske tumhari maa ka balatkaar kar dungaw jaixe delhi me huwa tha...ab teri chudi hui kuttiyo ki tarah apni gaand hilaate hue mere aage kalapna mt ni to tumhari fatti bhoxdi me 100 ched karunga`",
]
ABUSE_STRINGS = [
"`Madharchod hai kya tu lavde ?`",
"`Gaandu paida liya tha kya chutiya`",
"`Lavde teri gand mardunga`",
"`Abee Ja be Gaandu`",
"`Teri Ma ka Bhodsa madharchod`",
"`mu meh leta hai kya sab ka tu madarchod`",
"`Jyada gand na fulaao maa chod dengi tumhari bsdk....`",
"`Muh Me Lega Bhosdike ?`"
]
GEY_STRINGS = [
"`you gey bsdk`",
"`you gey`",
"`Nikal na gey bc`",
"`you chakka`",
"`you gey gey gey gey gey gey gey gey`",
"`you gey go away`",
]
RAPE_STRINGS = [
"`Dekho Bhaiyya esa hai! Izzat bachailo apni warna Gaand maar lenge tumhari`",
"`Relax your Rear, ders nothing to fear,The Rape train is finally here`",
"`Lodu Andha hai kya Yaha tera rape ho raha hai aur tu abhi tak yahi gaand mara raha hai lulz`",
]
WHERE = ["in the chest", "on the head", "on the butt", "on the crotch"]
# ===========================================
@register(outgoing=True, pattern=r"^.(\w+)say (.*)")
async def univsaye(cowmsg):
""" For .cowsay module, userbot wrapper for cow which says things. """
arg = cowmsg.pattern_match.group(1).lower()
text = cowmsg.pattern_match.group(2)
if arg == "cow":
arg = "default"
if arg not in cow.COWACTERS:
return
cheese = cow.get_cow(arg)
cheese = cheese()
await cowmsg.edit(f"`{cheese.milk(text).replace('`', '´')}`")
@register(outgoing=True, pattern="^:/$", ignore_unsafe=True)
async def kek(keks):
""" Check yourself ;)"""
uio = ["/", "\\"]
for i in range(1, 15):
time.sleep(0.3)
await keks.edit(":" + uio[i % 2])
@register(outgoing=True, pattern=r"^.coinflip (.*)")
async def coin(event):
r = choice(["heads", "tails"])
input_str = event.pattern_match.group(1)
if input_str:
input_str = input_str.lower()
if r == "heads":
if input_str == "heads":
await event.edit(
"The coin landed on: **Heads**.\nYou were correct.")
elif input_str == "tails":
await event.edit(
"The coin landed on: **Heads**.\nYou weren't correct, try again ..."
)
else:
await event.edit("The coin landed on: **Heads**.")
elif r == "tails":
if input_str == "tails":
await event.edit(
"The coin landed on: **Tails**.\nYou were correct.")
elif input_str == "heads":
await event.edit(
"The coin landed on: **Tails**.\nYou weren't correct, try again ..."
)
else:
await event.edit("The coin landed on: **Tails**.")
@register(pattern="^.slap(?: |$)(.*)", outgoing=True)
async def who(event):
""" slaps a user, or get slapped if not a reply. """
replied_user = await get_user_from_event(event)
if replied_user:
replied_user = replied_user[0]
else:
return
caption = await slap(replied_user, event)
try:
await event.edit(caption)
except BaseException:
await event.edit(
"`Can't slap this person, need to fetch some sticks and stones !!`"
)
async def slap(replied_user, event):
""" Construct a funny slap sentence !! """
user_id = replied_user.id
first_name = replied_user.first_name
username = replied_user.username
if username:
slapped = "@{}".format(username)
else:
slapped = f"[{first_name}](tg://user?id={user_id})"
temp = choice(SLAP_TEMPLATES)
item = choice(ITEMS)
hit = choice(HIT)
throw = choice(THROW)
where = choice(WHERE)
caption = "..." + temp.format(
victim=slapped, item=item, hits=hit, throws=throw, where=where)
return caption
@register(outgoing=True, pattern="^-_-$", ignore_unsafe=True)
async def lol(lel):
""" Ok... """
okay = "-_-"
for i in range(10):
okay = okay[:-1] + "_-"
await lel.edit(okay)
@register(outgoing=True, pattern="^.(yes|no|maybe|decide)$")
async def decide(event):
decision = event.pattern_match.group(1).lower()
message_id = event.reply_to_msg_id if event.reply_to_msg_id else None
if decision != "decide":
r = requests.get(f"https://yesno.wtf/api?force={decision}").json()
else:
r = requests.get(f"https://yesno.wtf/api").json()
await event.delete()
await event.client.send_message(event.chat_id,
str(r["answer"]).upper(),
reply_to=message_id,
file=r["image"])
@register(outgoing=True, pattern="^;_;$", ignore_unsafe=True)
async def fun(e):
t = ";_;"
for j in range(10):
t = t[:-1] + "_;"
await e.edit(t)
@register(outgoing=True, pattern="^.fp$")
async def facepalm(e):
""" Facepalm 🤦♂ """
await e.edit("🤦♂")
@register(outgoing=True, pattern="^.cry$")
async def cry(e):
""" y u du dis, i cry everytime !! """
await e.edit(choice(CRI))
@register(outgoing=True, pattern="^.insult$")
async def insult(e):
""" I make you cry !! """
await e.edit(choice(INSULT_STRINGS))
@register(outgoing=True, pattern="^.cp(?: |$)(.*)")
async def copypasta(cp_e):
""" Copypasta the famous meme """
textx = await cp_e.get_reply_message()
message = cp_e.pattern_match.group(1)
if message:
pass
elif textx:
message = textx.text
else:
await cp_e.edit("`😂🅱️IvE👐sOME👅text👅for✌️Me👌tO👐MAkE👀iT💞funNy!💦`")
return
reply_text = choice(EMOJIS)
# choose a random character in the message to be substituted with 🅱️
b_char = choice(message).lower()
for owo in message:
if owo == " ":
reply_text += choice(EMOJIS)
elif owo in EMOJIS:
reply_text += owo
reply_text += choice(EMOJIS)
elif owo.lower() == b_char:
reply_text += "🅱️"
else:
if bool(getrandbits(1)):
reply_text += owo.upper()
else:
reply_text += owo.lower()
reply_text += choice(EMOJIS)
await cp_e.edit(reply_text)
@register(outgoing=True, pattern="^.vapor(?: |$)(.*)")
async def vapor(vpr):
""" Vaporize everything! """
reply_text = list()
textx = await vpr.get_reply_message()
message = vpr.pattern_match.group(1)
if message:
pass
elif textx:
message = textx.text
else:
await vpr.edit("`Give some text for vapor!`")
return
for charac in message:
if 0x21 <= ord(charac) <= 0x7F:
reply_text.append(chr(ord(charac) + 0xFEE0))
elif ord(charac) == 0x20:
reply_text.append(chr(0x3000))
else:
reply_text.append(charac)
await vpr.edit("".join(reply_text))
@register(outgoing=True, pattern="^.str(?: |$)(.*)")
async def stretch(stret):
""" Stretch it."""
textx = await stret.get_reply_message()
message = stret.text
message = stret.pattern_match.group(1)
if message:
pass
elif textx:
message = textx.text
else:
await stret.edit("`GiiiiiiiB sooooooomeeeeeee teeeeeeext!`")
return
count = randint(3, 10)
reply_text = sub(r"([aeiouAEIOUaeiouAEIOUаеиоуюяыэё])", (r"\1" * count),
message)
await stret.edit(reply_text)
@register(outgoing=True, pattern="^.zal(?: |$)(.*)")
async def zal(zgfy):
""" Invoke the feeling of chaos. """
reply_text = list()
textx = await zgfy.get_reply_message()
message = zgfy.pattern_match.group(1)
if message:
pass
elif textx:
message = textx.text
else:
await zgfy.edit(
"`gͫ ̆ i̛ ̺ v͇̆ ȅͅ a̢ͦ s̴̪ c̸̢ ä̸ rͩͣ y͖͞ t̨͚ é̠ x̢͖ t͔͛`"
)
return
for charac in message:
if not charac.isalpha():
reply_text.append(charac)
continue
for _ in range(0, 3):
randint = randint(0, 2)
if randint == 0:
charac = charac.strip() + \
choice(ZALG_LIST[0]).strip()
elif randint == 1:
charac = charac.strip() + \
choice(ZALG_LIST[1]).strip()
else:
charac = charac.strip() + \
choice(ZALG_LIST[2]).strip()
reply_text.append(charac)
await zgfy.edit("".join(reply_text))
@register(outgoing=True, pattern="^.hi$")
async def hoi(hello):
""" Greet everyone! """
await hello.edit(choice(HELLOSTR))
@register(outgoing=True, pattern="^.owo(?: |$)(.*)")
async def faces(owo):
""" UwU """
textx = await owo.get_reply_message()
message = owo.pattern_match.group(1)
if message:
pass
elif textx:
message = textx.text
else:
await owo.edit("` UwU no text given! `")
return
reply_text = sub(r"(r|l)", "w", message)
reply_text = sub(r"(R|L)", "W", reply_text)
reply_text = sub(r"n([aeiou])", r"ny\1", reply_text)
reply_text = sub(r"N([aeiouAEIOU])", r"Ny\1", reply_text)
reply_text = sub(r"\!+", " " + choice(UWUS), reply_text)
reply_text = reply_text.replace("ove", "uv")
reply_text += " " + choice(UWUS)
await owo.edit(reply_text)
@register(outgoing=True, pattern="^.react$")
async def react_meme(react):
""" Make your userbot react to everything. """
await react.edit(choice(FACEREACTS))
@register(outgoing=True, pattern="^.shg$")
async def shrugger(shg):
r""" ¯\_(ツ)_/¯ """
await shg.edit(choice(SHGS))
@register(outgoing=True, pattern="^.chase$")
async def police(chase):
""" Run boi run, i'm gonna catch you !! """
await chase.edit(choice(CHASE_STR))
@register(outgoing=True, pattern="^.run$")
async def runner_lol(run):
""" Run, run, RUNNN! """
await run.edit(choice(RUNS_STR))
@register(outgoing=True, pattern="^.metoo$")
async def metoo(hahayes):
""" Haha yes """
await hahayes.edit(choice(METOOSTR))
@register(outgoing=True, pattern="^Oof$")
async def Oof(e):
t = "Oof"
for j in range(15):
t = t[:-1] + "of"
await e.edit(t)
@register(outgoing=True, pattern="^.10iq$")
async def iqless(e):
await e.edit("♿")
@register(outgoing=True, pattern="^.moon$")
async def moon(event):
deq = deque(list("🌗🌘🌑🌒🌓🌔🌕🌖"))
try:
for x in range(32):
await sleep(0.1)
await event.edit("".join(deq))
deq.rotate(1)
except BaseException:
return
@register(outgoing=True, pattern="^.clock$")
async def clock(event):
deq = deque(list("🕙🕘🕗🕖🕕🕔🕓🕒🕑🕐🕛"))
try:
for x in range(32):
await sleep(0.1)
await event.edit("".join(deq))
deq.rotate(1)
except BaseException:
return
@register(outgoing=True, pattern="^.mock(?: |$)(.*)")
async def spongemocktext(mock):
""" Do it and find the real fun. """
reply_text = list()
textx = await mock.get_reply_message()
message = mock.pattern_match.group(1)
if message:
pass
elif textx:
message = textx.text
else:
await mock.edit("`gIvE sOMEtHInG tO MoCk!`")
return
for charac in message:
if charac.isalpha() and randint(0, 1):
to_app = charac.upper() if charac.islower() else charac.lower()
reply_text.append(to_app)
else:
reply_text.append(charac)
await mock.edit("".join(reply_text))
@register(outgoing=True, pattern="^.clap(?: |$)(.*)")
async def claptext(memereview):
""" Praise people! """
textx = await memereview.get_reply_message()
message = memereview.pattern_match.group(1)
if message:
pass
elif textx:
message = textx.text
else:
await memereview.edit("`Hah, I don't clap pointlessly!`")
return
reply_text = "👏 "
reply_text += message.replace(" ", " 👏 ")
reply_text += " 👏"
await memereview.edit(reply_text)
@register(outgoing=True, pattern="^.bt$")
async def bluetext(bt_e):
""" Believe me, you will find this useful. """
if await bt_e.get_reply_message() and bt_e.is_group:
await bt_e.edit(
"/BLUETEXT /MUST /CLICK.\n"
"/ARE /YOU /A /STUPID /ANIMAL /WHICH /IS /ATTRACTED /TO /COLOURS?")
@register(outgoing=True, pattern=r"^.f (.*)")
async def payf(event):
paytext = event.pattern_match.group(1)
pay = "{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}".format(
paytext * 8, paytext * 8, paytext * 2, paytext * 2, paytext * 2,
paytext * 6, paytext * 6, paytext * 2, paytext * 2, paytext * 2,
paytext * 2, paytext * 2)
await event.edit(pay)
@register(outgoing=True, pattern="^.googleit (.*)")
async def let_me_google_that_for_you(lmgtfy_q):
textx = await lmgtfy_q.get_reply_message()
qry = lmgtfy_q.pattern_match.group(1)
if qry:
query = str(qry)
elif textx:
query = textx
query = query.message
query_encoded = query.replace(" ", "+")
lfy_url = f"http://lmgtfy.com/?s=g&iie=1&q={query_encoded}"
payload = {'format': 'json', 'url': lfy_url}
r = requests.get('http://is.gd/create.php', params=payload)
await lmgtfy_q.edit(f"Here you are, help yourself.\
\n[{query}]({r.json()['shorturl']})")
@register(pattern=r".scam(?: |$)(.*)", outgoing=True)
async def scam(event):
""" Just a small command to fake chat actions for fun !! """
options = [
'typing', 'contact', 'game', 'location', 'voice', 'round', 'video',
'photo', 'document', 'cancel'
]
input_str = event.pattern_match.group(1)
args = input_str.split()
if len(args) is 0: # Let bot decide action and time
scam_action = choice(options)
scam_time = randint(30, 60)
elif len(args) is 1: # User decides time/action, bot decides the other.
try:
scam_action = str(args[0]).lower()
scam_time = randint(30, 60)
except ValueError:
scam_action = choice(options)
scam_time = int(args[0])
elif len(args) is 2: # User decides both action and time
scam_action = str(args[0]).lower()
scam_time = int(args[1])
else:
await event.edit("`Invalid Syntax !!`")
return
try:
if (scam_time > 0):
await event.delete()
async with event.client.action(event.chat_id, scam_action):
await sleep(scam_time)
except BaseException:
return
@register(outgoing=True, pattern="^.abusehard$")
async def fuckedd (abusehard):
""" Use with caution """
if not abusehard.text[0].isalpha() and abusehard.text[0] not in ("/", "#", "@", "!"):
index = random.randint(0, len(ABUSEHARD_STRING) - 1)
reply_text = ABUSEHARD_STRING[index]
await abusehard.edit(reply_text)
@register(outgoing=True, pattern="^.rape$")
async def raping (raped):
""" -,- """
if not raped.text[0].isalpha() and raped.text[0] not in ("/", "#", "@", "!"):
index = random.randint(0, len(RAPE_STRINGS) - 1)
reply_text = RAPE_STRINGS[index]
await raped.edit(reply_text)
@register(outgoing=True, pattern="^.gey$")
async def geys (geyed):
""" :/ """
if not geyed.text[0].isalpha() and geyed.text[0] not in ("/", "#", "@", "!"):
index = random.randint(0, len(GEY_STRINGS) - 1)
reply_text = GEY_STRINGS[index]
await geyed.edit(reply_text)
@register(outgoing=True, pattern="^.abuse$")
async def abusing (abused):
""" Ez Abuse """
if not abused.text[0].isalpha() and abused.text[0] not in ("/", "#", "@", "!"):
index = random.randint(0, len(ABUSE_STRINGS) - 1)
reply_text = ABUSE_STRINGS[index]
await abused.edit(reply_text)
@register(outgoing=True, pattern="^.reep$")
async def restinpeace (rest):
""" Ezio Auditore R.I.P """
if not rest.text[0].isalpha() and rest.text[0] not in ("/", "#", "@", "!"):
if await rest.get_reply_message():
await rest.edit(
"`Requiescat In Pace ☠️`\n"
)
@register(pattern=r".type(?: |$)(.*)", outgoing=True)
async def typewriter(typew):
""" Just a small command to make your keyboard become a typewriter! """
textx = await typew.get_reply_message()
message = typew.pattern_match.group(1)
if message:
pass
elif textx:
message = textx.text
else:
await typew.edit("`Give a text to type!`")
return
sleep_time = 0.03
typing_symbol = "|"
old_text = ""
await typew.edit(typing_symbol)
await sleep(sleep_time)
for character in message:
old_text = old_text + "" + character
typing_text = old_text + "" + typing_symbol
await typew.edit(typing_text)
await sleep(sleep_time)
await typew.edit(old_text)
await sleep(sleep_time)
CMD_HELP.update({
"memes":
".cowsay\
\nUsage: cow which says things.\
\n\n:/\
\nUsage: Check yourself ;)\
\n\n-_-\
\nUsage: Ok...\
\n\n;_;\
\nUsage: Like `-_-` but crying.\
\n\n.cp\
\nUsage: Copypasta the famous meme\
\n\n.vapor\
\nUsage: Vaporize everything!\
\n\n.str\
\nUsage: Stretch it.\
\n\n.10iq\
\nUsage: You retard !!\
\n\n.zal\
\nUsage: Invoke the feeling of chaos.\
\n\nOof\
\nUsage: Ooooof\
\n\n.fp\
\nUsage: Facepalm :P\
\n\n.moon\
\nUsage: kensar moon animation.\
\n\n.clock\
\nUsage: kensar clock animation.\
\n\n.hi\
\nUsage: Greet everyone!\
\n\n.coinflip <heads/tails>\
\nUsage: Flip a coin !!\
\n\n.owo\
\nUsage: UwU\
\n\n.react\
\nUsage: Make your userbot react to everything.\
\n\n.slap\
\nUsage: reply to slap them with random objects !!\
\n\n.cry\
\nUsage: y u du dis, i cri.\
\n\n.shg\
\nUsage: Shrug at it !!\
\n\n.run\
\nUsage: Let Me Run, run, RUNNN!\
\n\n.chase\
\nUsage: You better start running\
\n\n.metoo\
\nUsage: Haha yes\
\n\n.mock\
\nUsage: Do it and find the real fun.\
\n\n.clap\
\nUsage: Praise people!\
\n\n.f <emoji/character>\
\nUsage: Pay Respects.\
\n\n.bt\
\nUsage: Believe me, you will find this useful.\
\n\n.type\
\nUsage: Just a small command to make your keyboard become a typewriter!\
\n\n.googleit <query>\
\nUsage: Let me Google that for you real quick !!\
\n\n.decide [Alternates: (.yes, .no, .maybe)]\
\nUsage: Make a quick decision.\
\n\n.scam <action> <time>\
\n[Available Actions: (typing, contact, game, location, voice, round, video, photo, document, cancel)]\
\nUsage: Create fake chat actions, for fun. (Default action: typing)\
\n\n\nThanks to 🅱️ottom🅱️ext🅱️ot (@NotAMemeBot) for some of these."
})
|
import jk_pypiorgapi
from datetime import datetime
import re
import requests
import time
from pprint import pprint
import json
import pickle
from multiprocessing import Pool
# set up autentification github
username = 'edigeze'
# token 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
token = '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'
repos_url = 'https://api.github.com/user/repos'
# create a re-usable session object with the user creds in-built
gh_session = requests.Session()
gh_session.auth = (username, token)
# list all pypi package
api = jk_pypiorgapi.PyPiOrgAPI()
list_packages = api.listAllPackages()
n=len(list_packages)
print("Number of packages on pypi.org:", n)
start_time = time.time()
package_info={}
index = 0
linked_package = 0
github_repo_check = 0
for package in list_packages:
index+=1
jData = api.getPackageInfoJSON(package[1])
# size of the doc assuming that the doc size is big meaning that the package is important
doc_size = len(str(jData))
try:
last_update = datetime.strptime("1900-01-01T01:01:01", "%Y-%m-%dT%H:%M:%S")
amount_of_releases = len(jData["releases"])
for rkey, rvalue in jData["releases"].items():
datetime_object = datetime.strptime(rvalue[0]["upload_time"], "%Y-%m-%dT%H:%M:%S")
if datetime_object > last_update: last_update = datetime_object
except:
pass
#print(f"impossible to fetch releases on {package[1]}")
try:
url = None
if "github" in jData["info"]["home_page"] or "gitlab" in jData["info"]["home_page"]:
url=jData["info"]["home_page"]
linked_package += 1
elif "github" in jData["info"]["download_url"] or "gitlab" in jData["info"]["download_url"]:
url=jData["info"]["download_url"]
linked_package += 1
# elif "https://git"in jData["info"]["description"]: # looking for git to include github and gitlab
# url=re.search("(?P<url>https?://github.com/[^\s]+)", jData["info"]["description"]).group("url")
# linked_package += 1
# elif "https://git"in jData["info"]["description"]:
# url=re.search("(?P<url>https?://github.com/[^\s]+)", str(jData)).group("url")
# print("la tu deconnes")
# linked_package += 1
except:
pass
#print(f"impossible to fetch info of {package[1]}")
#compute score
score = 0 if url==None else 20
delta = datetime.now() - last_update
score+=max(0,20-delta.days/50)
score+=min(20, doc_size/1000)
score+=min(amount_of_releases, 20)
# connect to stats:
github_stars=-1 # -1 mean didn't find any repo
github_last_commit=None
github_api_timeout = None
while github_api_timeout is None:
try:
if "github" in url and delta.days<700: # we check the repo if it's github and if the last release is less than 2 years old
url_github = f"https://api.github.com/repos/{url.split("/")[3]}/{url.split("/")[4]}"
user_data = gh_session.get(url_github).json()
github_stars=user_data['stargazers_count']
github_last_commit=user_data['pushed_at']
github_repo_check += 1
github_api_timeout = True
except KeyError:
if 'message' in user_data:
github_api_timeout = True
else:
print("wait for API github timeout finished")
time.sleep(60)
except:
github_api_timeout = True
pass
info = {"url": url,
"Last_update": last_update,
"Amount_of_releases": amount_of_releases,
"Doc_size":doc_size,
"score": score,
"github_stars":github_stars,
"github_last_commit": github_last_commit
}
package_info[package[1]] = info
if index%1000==0:
print(f'packages parsed : {index} time : {(time.time() - start_time)} repo_check : {github_repo_check}')
start_time = time.time()
package_info = {k: v for k, v in sorted(package_info.items(), key=lambda item: item[1]["github_stars"])}
for name, info in package_info.items():
print(name, info)
print(linked_package, len(package_info), github_repo_check)
with open('saved_dictionary.pkl', 'wb') as f:
pickle.dump(package_info, f)
# with open('saved_dictionary.pkl', 'rb') as f:
# loaded_dict = pickle.load(f)
# check the important packages without github
# for name, info in package_info.items():
# if info["Doc_size"]> 10000 and info["url"]==None:
# print(name)
| import jk_pypiorgapi
from datetime import datetime
import re
import requests
import time
from pprint import pprint
import json
import pickle
from multiprocessing import Pool
# set up autentification github
username = 'edigeze'
# token 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
token = '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'
repos_url = 'https://api.github.com/user/repos'
# create a re-usable session object with the user creds in-built
gh_session = requests.Session()
gh_session.auth = (username, token)
# list all pypi package
api = jk_pypiorgapi.PyPiOrgAPI()
list_packages = api.listAllPackages()
n=len(list_packages)
print("Number of packages on pypi.org:", n)
start_time = time.time()
package_info={}
index = 0
linked_package = 0
github_repo_check = 0
for package in list_packages:
index+=1
jData = api.getPackageInfoJSON(package[1])
# size of the doc assuming that the doc size is big meaning that the package is important
doc_size = len(str(jData))
try:
last_update = datetime.strptime("1900-01-01T01:01:01", "%Y-%m-%dT%H:%M:%S")
amount_of_releases = len(jData["releases"])
for rkey, rvalue in jData["releases"].items():
datetime_object = datetime.strptime(rvalue[0]["upload_time"], "%Y-%m-%dT%H:%M:%S")
if datetime_object > last_update: last_update = datetime_object
except:
pass
#print(f"impossible to fetch releases on {package[1]}")
try:
url = None
if "github" in jData["info"]["home_page"] or "gitlab" in jData["info"]["home_page"]:
url=jData["info"]["home_page"]
linked_package += 1
elif "github" in jData["info"]["download_url"] or "gitlab" in jData["info"]["download_url"]:
url=jData["info"]["download_url"]
linked_package += 1
# elif "https://git"in jData["info"]["description"]: # looking for git to include github and gitlab
# url=re.search("(?P<url>https?://github.com/[^\s]+)", jData["info"]["description"]).group("url")
# linked_package += 1
# elif "https://git"in jData["info"]["description"]:
# url=re.search("(?P<url>https?://github.com/[^\s]+)", str(jData)).group("url")
# print("la tu deconnes")
# linked_package += 1
except:
pass
#print(f"impossible to fetch info of {package[1]}")
#compute score
score = 0 if url==None else 20
delta = datetime.now() - last_update
score+=max(0,20-delta.days/50)
score+=min(20, doc_size/1000)
score+=min(amount_of_releases, 20)
# connect to stats:
github_stars=-1 # -1 mean didn't find any repo
github_last_commit=None
github_api_timeout = None
while github_api_timeout is None:
try:
if "github" in url and delta.days<700: # we check the repo if it's github and if the last release is less than 2 years old
url_github = f"https://api.github.com/repos/{url.split('/')[3]}/{url.split('/')[4]}"
user_data = gh_session.get(url_github).json()
github_stars=user_data['stargazers_count']
github_last_commit=user_data['pushed_at']
github_repo_check += 1
github_api_timeout = True
except KeyError:
if 'message' in user_data:
github_api_timeout = True
else:
print("wait for API github timeout finished")
time.sleep(60)
except:
github_api_timeout = True
pass
info = {"url": url,
"Last_update": last_update,
"Amount_of_releases": amount_of_releases,
"Doc_size":doc_size,
"score": score,
"github_stars":github_stars,
"github_last_commit": github_last_commit
}
package_info[package[1]] = info
if index%1000==0:
print(f'packages parsed : {index} time : {(time.time() - start_time)} repo_check : {github_repo_check}')
start_time = time.time()
package_info = {k: v for k, v in sorted(package_info.items(), key=lambda item: item[1]["github_stars"])}
for name, info in package_info.items():
print(name, info)
print(linked_package, len(package_info), github_repo_check)
with open('saved_dictionary.pkl', 'wb') as f:
pickle.dump(package_info, f)
# with open('saved_dictionary.pkl', 'rb') as f:
# loaded_dict = pickle.load(f)
# check the important packages without github
# for name, info in package_info.items():
# if info["Doc_size"]> 10000 and info["url"]==None:
# print(name)
|
from http import HTTPStatus
from api import app, database
from flask import jsonify, request, abort, make_response
def check_and_insert(company):
"""
Inserts the supplied company record if it doesnt already exists
"""
# Get the companies collection from the database
company_collection = database()
# Check if a company document already exists with the id provided and throw HTTP error if so
company_in_db = company_collection.find_one({'_id': company['_id']}, {'_id': 0})
if company_in_db:
conflict_msg = f"Company with id '{company["_id"]}' already exists in the database."
abort(make_response(jsonify(message=conflict_msg), HTTPStatus.CONFLICT))
# Insert the posted company json body as a document in the database
company_collection.insert_one(company)
@app.route('/companies', methods=['POST'])
def create_company():
"""
Creates a new company
"""
# Get the posted data
companies_json = request.get_json()
# Check if the json only contains a single company document
if '_id' in companies_json:
check_and_insert(companies_json)
# Iterate and insert each company document if there are multiple documents
else:
for company in companies_json:
check_and_insert(company)
# Return the created company as JSON
return jsonify(companies_json), HTTPStatus.CREATED
| from http import HTTPStatus
from api import app, database
from flask import jsonify, request, abort, make_response
def check_and_insert(company):
"""
Inserts the supplied company record if it doesnt already exists
"""
# Get the companies collection from the database
company_collection = database()
# Check if a company document already exists with the id provided and throw HTTP error if so
company_in_db = company_collection.find_one({'_id': company['_id']}, {'_id': 0})
if company_in_db:
conflict_msg = f"Company with id '{company['_id']}' already exists in the database."
abort(make_response(jsonify(message=conflict_msg), HTTPStatus.CONFLICT))
# Insert the posted company json body as a document in the database
company_collection.insert_one(company)
@app.route('/companies', methods=['POST'])
def create_company():
"""
Creates a new company
"""
# Get the posted data
companies_json = request.get_json()
# Check if the json only contains a single company document
if '_id' in companies_json:
check_and_insert(companies_json)
# Iterate and insert each company document if there are multiple documents
else:
for company in companies_json:
check_and_insert(company)
# Return the created company as JSON
return jsonify(companies_json), HTTPStatus.CREATED
|
import os
import platform
from pathlib import Path
from torchaudio.datasets import tedlium
from torchaudio_unittest.common_utils import (
get_whitenoise,
save_wav,
skipIfNoSox,
TempDirMixin,
TorchaudioTestCase,
)
# Used to generate a unique utterance for each dummy audio file
_UTTERANCES = [
"AaronHuey_2010X 1 AaronHuey_2010X 0.0 2.0 <o,f0,female> script1\n",
"AaronHuey_2010X 1 AaronHuey_2010X 2.0 4.0 <o,f0,female> script2\n",
"AaronHuey_2010X 1 AaronHuey_2010X 4.0 6.0 <o,f0,female> script3\n",
"AaronHuey_2010X 1 AaronHuey_2010X 6.0 8.0 <o,f0,female> script4\n",
"AaronHuey_2010X 1 AaronHuey_2010X 8.0 10.0 <o,f0,female> script5\n",
]
_PHONEME = [
"a AH",
"a(2) EY",
"aachen AA K AH N",
"aad AE D",
"aaden EY D AH N",
"aadmi AE D M IY",
"aae EY EY",
]
def get_mock_dataset(dataset_dir):
"""
dataset_dir: directory of the mocked dataset
"""
mocked_samples = {}
os.makedirs(dataset_dir, exist_ok=True)
sample_rate = 16000 # 16kHz
seed = 0
for release in ["release1", "release2", "release3"]:
data = get_whitenoise(sample_rate=sample_rate, duration=10.00, n_channels=1, dtype="float32", seed=seed)
if release in ["release1", "release2"]:
release_dir = os.path.join(
dataset_dir,
tedlium._RELEASE_CONFIGS[release]["folder_in_archive"],
tedlium._RELEASE_CONFIGS[release]["subset"],
)
else:
release_dir = os.path.join(
dataset_dir,
tedlium._RELEASE_CONFIGS[release]["folder_in_archive"],
tedlium._RELEASE_CONFIGS[release]["data_path"],
)
os.makedirs(release_dir, exist_ok=True)
os.makedirs(os.path.join(release_dir, "stm"), exist_ok=True) # Subfolder for transcripts
os.makedirs(os.path.join(release_dir, "sph"), exist_ok=True) # Subfolder for audio files
filename = f"{release}.sph"
path = os.path.join(os.path.join(release_dir, "sph"), filename)
save_wav(path, data, sample_rate)
trans_filename = f"{release}.stm"
trans_path = os.path.join(os.path.join(release_dir, "stm"), trans_filename)
with open(trans_path, "w") as f:
f.write("".join(_UTTERANCES))
dict_filename = f"{release}.dic"
dict_path = os.path.join(release_dir, dict_filename)
with open(dict_path, "w") as f:
f.write("\n".join(_PHONEME))
# Create a samples list to compare with
mocked_samples[release] = []
for utterance in _UTTERANCES:
talk_id, _, speaker_id, start_time, end_time, identifier, transcript = utterance.split(" ", 6)
start_time = int(float(start_time)) * sample_rate
end_time = int(float(end_time)) * sample_rate
sample = (
data[:, start_time:end_time],
sample_rate,
transcript,
talk_id,
speaker_id,
identifier,
)
mocked_samples[release].append(sample)
seed += 1
return mocked_samples
class Tedlium(TempDirMixin):
root_dir = None
samples = {}
@classmethod
def setUpClass(cls):
cls.root_dir = cls.get_base_temp_dir()
cls.root_dir = dataset_dir = os.path.join(cls.root_dir, "tedlium")
cls.samples = get_mock_dataset(dataset_dir)
def _test_tedlium(self, dataset, release):
num_samples = 0
for i, (data, sample_rate, transcript, talk_id, speaker_id, identifier) in enumerate(dataset):
self.assertEqual(data, self.samples[release][i][0], atol=5e-5, rtol=1e-8)
assert sample_rate == self.samples[release][i][1]
assert transcript == self.samples[release][i][2]
assert talk_id == self.samples[release][i][3]
assert speaker_id == self.samples[release][i][4]
assert identifier == self.samples[release][i][5]
num_samples += 1
assert num_samples == len(self.samples[release])
dataset._dict_path = os.path.join(dataset._path, f"{release}.dic")
phoneme_dict = dataset.phoneme_dict
phoenemes = [f"{key} {" ".join(value)}" for key, value in phoneme_dict.items()]
assert phoenemes == _PHONEME
def test_tedlium_release1_str(self):
release = "release1"
dataset = tedlium.TEDLIUM(self.root_dir, release=release)
self._test_tedlium(dataset, release)
def test_tedlium_release1_path(self):
release = "release1"
dataset = tedlium.TEDLIUM(Path(self.root_dir), release=release)
self._test_tedlium(dataset, release)
def test_tedlium_release2(self):
release = "release2"
dataset = tedlium.TEDLIUM(self.root_dir, release=release)
self._test_tedlium(dataset, release)
def test_tedlium_release3(self):
release = "release3"
dataset = tedlium.TEDLIUM(self.root_dir, release=release)
self._test_tedlium(dataset, release)
class TestTedliumSoundfile(Tedlium, TorchaudioTestCase):
backend = "soundfile"
if platform.system() != "Windows":
@skipIfNoSox
class TestTedliumSoxIO(Tedlium, TorchaudioTestCase):
backend = "sox_io"
| import os
import platform
from pathlib import Path
from torchaudio.datasets import tedlium
from torchaudio_unittest.common_utils import (
get_whitenoise,
save_wav,
skipIfNoSox,
TempDirMixin,
TorchaudioTestCase,
)
# Used to generate a unique utterance for each dummy audio file
_UTTERANCES = [
"AaronHuey_2010X 1 AaronHuey_2010X 0.0 2.0 <o,f0,female> script1\n",
"AaronHuey_2010X 1 AaronHuey_2010X 2.0 4.0 <o,f0,female> script2\n",
"AaronHuey_2010X 1 AaronHuey_2010X 4.0 6.0 <o,f0,female> script3\n",
"AaronHuey_2010X 1 AaronHuey_2010X 6.0 8.0 <o,f0,female> script4\n",
"AaronHuey_2010X 1 AaronHuey_2010X 8.0 10.0 <o,f0,female> script5\n",
]
_PHONEME = [
"a AH",
"a(2) EY",
"aachen AA K AH N",
"aad AE D",
"aaden EY D AH N",
"aadmi AE D M IY",
"aae EY EY",
]
def get_mock_dataset(dataset_dir):
"""
dataset_dir: directory of the mocked dataset
"""
mocked_samples = {}
os.makedirs(dataset_dir, exist_ok=True)
sample_rate = 16000 # 16kHz
seed = 0
for release in ["release1", "release2", "release3"]:
data = get_whitenoise(sample_rate=sample_rate, duration=10.00, n_channels=1, dtype="float32", seed=seed)
if release in ["release1", "release2"]:
release_dir = os.path.join(
dataset_dir,
tedlium._RELEASE_CONFIGS[release]["folder_in_archive"],
tedlium._RELEASE_CONFIGS[release]["subset"],
)
else:
release_dir = os.path.join(
dataset_dir,
tedlium._RELEASE_CONFIGS[release]["folder_in_archive"],
tedlium._RELEASE_CONFIGS[release]["data_path"],
)
os.makedirs(release_dir, exist_ok=True)
os.makedirs(os.path.join(release_dir, "stm"), exist_ok=True) # Subfolder for transcripts
os.makedirs(os.path.join(release_dir, "sph"), exist_ok=True) # Subfolder for audio files
filename = f"{release}.sph"
path = os.path.join(os.path.join(release_dir, "sph"), filename)
save_wav(path, data, sample_rate)
trans_filename = f"{release}.stm"
trans_path = os.path.join(os.path.join(release_dir, "stm"), trans_filename)
with open(trans_path, "w") as f:
f.write("".join(_UTTERANCES))
dict_filename = f"{release}.dic"
dict_path = os.path.join(release_dir, dict_filename)
with open(dict_path, "w") as f:
f.write("\n".join(_PHONEME))
# Create a samples list to compare with
mocked_samples[release] = []
for utterance in _UTTERANCES:
talk_id, _, speaker_id, start_time, end_time, identifier, transcript = utterance.split(" ", 6)
start_time = int(float(start_time)) * sample_rate
end_time = int(float(end_time)) * sample_rate
sample = (
data[:, start_time:end_time],
sample_rate,
transcript,
talk_id,
speaker_id,
identifier,
)
mocked_samples[release].append(sample)
seed += 1
return mocked_samples
class Tedlium(TempDirMixin):
root_dir = None
samples = {}
@classmethod
def setUpClass(cls):
cls.root_dir = cls.get_base_temp_dir()
cls.root_dir = dataset_dir = os.path.join(cls.root_dir, "tedlium")
cls.samples = get_mock_dataset(dataset_dir)
def _test_tedlium(self, dataset, release):
num_samples = 0
for i, (data, sample_rate, transcript, talk_id, speaker_id, identifier) in enumerate(dataset):
self.assertEqual(data, self.samples[release][i][0], atol=5e-5, rtol=1e-8)
assert sample_rate == self.samples[release][i][1]
assert transcript == self.samples[release][i][2]
assert talk_id == self.samples[release][i][3]
assert speaker_id == self.samples[release][i][4]
assert identifier == self.samples[release][i][5]
num_samples += 1
assert num_samples == len(self.samples[release])
dataset._dict_path = os.path.join(dataset._path, f"{release}.dic")
phoneme_dict = dataset.phoneme_dict
phoenemes = [f"{key} {' '.join(value)}" for key, value in phoneme_dict.items()]
assert phoenemes == _PHONEME
def test_tedlium_release1_str(self):
release = "release1"
dataset = tedlium.TEDLIUM(self.root_dir, release=release)
self._test_tedlium(dataset, release)
def test_tedlium_release1_path(self):
release = "release1"
dataset = tedlium.TEDLIUM(Path(self.root_dir), release=release)
self._test_tedlium(dataset, release)
def test_tedlium_release2(self):
release = "release2"
dataset = tedlium.TEDLIUM(self.root_dir, release=release)
self._test_tedlium(dataset, release)
def test_tedlium_release3(self):
release = "release3"
dataset = tedlium.TEDLIUM(self.root_dir, release=release)
self._test_tedlium(dataset, release)
class TestTedliumSoundfile(Tedlium, TorchaudioTestCase):
backend = "soundfile"
if platform.system() != "Windows":
@skipIfNoSox
class TestTedliumSoxIO(Tedlium, TorchaudioTestCase):
backend = "sox_io"
|
#!/usr/bin/python3
# coding=utf-8
# pylint: disable=I0011,E0401,W0702,W0703
# Copyright 2019 getcarrier.io
#
# 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.
"""
Scanner: java
"""
from dusty.tools import log
from dusty.models.module import DependentModuleModel
from dusty.models.scanner import ScannerModel
class Scanner(DependentModuleModel, ScannerModel):
""" Scanner class """
def __init__(self, context):
""" Initialize scanner instance """
super().__init__()
self.context = context
self.config = \
self.context.config["scanners"][__name__.split(".")[-3]][__name__.split(".")[-2]]
self.set_meta("meta_scanner", True)
def prepare(self):
""" Prepare scanner """
scanners = ["spotbugs"]
if self.config.get("composition_analysis", False):
scanners.append("dependencycheck")
self.config["comp_path"] = self.config.get("scan_path", self.config.get("code"))
self.config["comp_opts"] = self.config.get("scan_opts", "")
for scanner in scanners:
log.info("Adding %s scanner", scanner)
self.context.performers["scanning"].schedule_scanner("sast", scanner, self.config)
@staticmethod
def fill_config(data_obj):
""" Make sample config """
data_obj.insert(len(data_obj), "code", "/path/to/code", comment="scan target")
data_obj.insert(
len(data_obj), "composition_analysis", False, comment="enable composition analysis"
)
data_obj.insert(
len(data_obj), "scan_path", "/path/to/code",
comment="(composition analysis) (optional) path to code for analysis"
)
data_obj.insert(
len(data_obj), "scan_opts", "",
comment="(composition analysis) (optional) additional options"
)
data_obj.insert(
len(data_obj), "save_intermediates_to", "/data/intermediates/dast",
comment="(optional) Save scan intermediates (raw results, logs, ...)"
)
@staticmethod
def validate_config(config):
""" Validate config """
required = ["code"]
not_set = [item for item in required if item not in config]
if not_set:
error = f"Required configuration options not set: {", ".join(not_set)}"
log.error(error)
raise ValueError(error)
@staticmethod
def get_name():
""" Module name """
return "java"
@staticmethod
def get_description():
""" Module description or help message """
return "SAST scanner"
| #!/usr/bin/python3
# coding=utf-8
# pylint: disable=I0011,E0401,W0702,W0703
# Copyright 2019 getcarrier.io
#
# 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.
"""
Scanner: java
"""
from dusty.tools import log
from dusty.models.module import DependentModuleModel
from dusty.models.scanner import ScannerModel
class Scanner(DependentModuleModel, ScannerModel):
""" Scanner class """
def __init__(self, context):
""" Initialize scanner instance """
super().__init__()
self.context = context
self.config = \
self.context.config["scanners"][__name__.split(".")[-3]][__name__.split(".")[-2]]
self.set_meta("meta_scanner", True)
def prepare(self):
""" Prepare scanner """
scanners = ["spotbugs"]
if self.config.get("composition_analysis", False):
scanners.append("dependencycheck")
self.config["comp_path"] = self.config.get("scan_path", self.config.get("code"))
self.config["comp_opts"] = self.config.get("scan_opts", "")
for scanner in scanners:
log.info("Adding %s scanner", scanner)
self.context.performers["scanning"].schedule_scanner("sast", scanner, self.config)
@staticmethod
def fill_config(data_obj):
""" Make sample config """
data_obj.insert(len(data_obj), "code", "/path/to/code", comment="scan target")
data_obj.insert(
len(data_obj), "composition_analysis", False, comment="enable composition analysis"
)
data_obj.insert(
len(data_obj), "scan_path", "/path/to/code",
comment="(composition analysis) (optional) path to code for analysis"
)
data_obj.insert(
len(data_obj), "scan_opts", "",
comment="(composition analysis) (optional) additional options"
)
data_obj.insert(
len(data_obj), "save_intermediates_to", "/data/intermediates/dast",
comment="(optional) Save scan intermediates (raw results, logs, ...)"
)
@staticmethod
def validate_config(config):
""" Validate config """
required = ["code"]
not_set = [item for item in required if item not in config]
if not_set:
error = f"Required configuration options not set: {', '.join(not_set)}"
log.error(error)
raise ValueError(error)
@staticmethod
def get_name():
""" Module name """
return "java"
@staticmethod
def get_description():
""" Module description or help message """
return "SAST scanner"
|
#!/usr/bin/env python
# coding: utf-8
"""Controllers for HebPhonics."""
# native
import os
from inspect import cleandoc
# lib
from flask import jsonify, render_template, request
from sqlalchemy.sql import and_, or_
from sqlalchemy.sql.expression import desc, false, func
from markdown import markdown
# pkg
from .. import app, tokens as T, rules, __version__, __pubdate__
from ..grammar import ItemList, Cluster, Parser
from ..models import Book, Word, Freq
from .jsend import JSend
VERSION = __version__ if not __pubdate__ else f"{__version__} ({__pubdate__})"
GOOGLE_ANALYTICS_ID = os.getenv("GOOGLE_ANALYTICS_ID")
def get_color(count):
"""Simple color scale."""
color = ""
if count == 0:
color = "is-danger"
elif count < 20:
color = "is-warning"
elif count < 300:
color = "is-primary"
elif count < 1000:
color = "is-success"
else:
color = "is-black"
return color
@app.route("/")
def index():
"""Home page."""
return render_template(
"index.html",
books=[b.name for b in Book.query.order_by(Book.id).all()],
symbols=[x for x in list(T.SYMBOLS) if x not in ["dagesh", "holam"]],
rules=rules.RULES,
version=VERSION,
GOOGLE_ANALYTICS_ID=GOOGLE_ANALYTICS_ID,
)
@app.route("/rules")
def list_rules():
"""Get rules list from the database."""
all_rules = {}
all_symbols = {}
see_also = rules.__doc__[rules.__doc__.find("See also:") + 10 :]
for rule, fn in rules.RULES.items():
count = (
Word.query.filter(Word.rules.like(f"%'{rule}'%"))
.with_entities(func.count())
.scalar()
)
parts = cleandoc(fn.__doc__ or "").split("\n")
stmt = f"- **Rule**: {parts[0]}"
rest = (
"\n".join(parts[1:])
.replace("Example:", "- **Example**:")
.replace("Examples:", "- **Examples**:")
.replace("Requires:", "- **Requires**:")
.replace("See also:", "- **See also**:")
.replace("Source:", "- **Source**:")
.replace("Sources:", "- **Sources**:")
)
doc = markdown(f"{rest}\n\n{stmt}\n\n{see_also}")
all_rules[rule] = dict(doc=doc, count=f"{count:,}", color=get_color(count))
for symbol in T.SYMBOLS:
count = (
Word.query.filter(Word.parsed.like(f"%'{symbol}'%"))
.with_entities(func.count())
.scalar()
)
all_symbols[symbol] = dict(count=f"{count:,}", color=get_color(count))
return render_template(
"rules.html",
rules=all_rules,
symbols=all_symbols,
version=VERSION,
GOOGLE_ANALYTICS_ID=GOOGLE_ANALYTICS_ID,
)
@app.route("/words", methods=["GET", "POST"])
def list_word():
"""Search database."""
args = request.json
query = search(**args)
words = [{"h": w.hebrew, "f": w.freq, "r": w.ref} for w in query.all()]
sql = str(query.statement.compile(compile_kwargs={"literal_binds": True}))
return jsonify(JSend(data=words, query=sql))
def _block_letter(base, bclasses, btool, full, fclasses, ftool, dtool, rules_=""):
if rules_:
rules_ = f"[{rules_}]"
tool = "\n".join([x for x in [btool, dtool, ftool, rules_] if x]).strip()
if tool:
tool = f' data-tooltip="{tool}"'
return f"""
<span class="letter">
<span class="base {' '.join(bclasses)} has-tooltip-left"{tool}>{base}</span>
<span class="full {' '.join(fclasses)}">{full}</span>
</span>"""
@app.route("/display", methods=["POST"])
def display_word():
"""Typographical hints for words."""
word = request.json["word"]
query = Word.query.filter(Word.hebrew == word).first()
if query:
syls = ItemList([ItemList([Cluster(**t) for t in s]) for s in query.syls])
else:
parser = Parser()
parsed = parser.parse(word)
syls = parser.syl(parsed)
result = ""
for num, syl in enumerate(syls):
if num > 0:
result += _block_letter(" | ", ["syllable"], "", "", ["syllable"], "", "")
for sym in syl:
lett = f"{T.SYMBOLS.get(sym.letter, "")}{T.SYMBOLS.get(sym.dagesh, "")}"
vow = T.SYMBOLS.get(sym.vowel, "")
if sym.vowel in [T.NAME_HOLAM_MALE_VAV, T.NAME_SHURUQ]:
vow = ""
lett_show = [T.POINT_HOLAM, T.LETTER_FINAL_KAF]
lett_hide = [T.LETTER_AYIN]
result += _block_letter(
lett,
[f"letter-{sym.letter}", sym.dagesh],
sym.letter,
f"{lett if (lett in lett_show or vow in lett_show) and not (lett in lett_hide or vow in lett_hide) else " "}{vow}",
[f"vowel-{sym.vowel}"],
sym.vowel,
sym.dagesh,
", ".join(sym.rules),
)
if sym.vowel in [T.NAME_HOLAM_MALE_VAV, T.NAME_SHURUQ]:
lett = T.SYMBOLS.get("vav", "")
vow = T.SYMBOLS.get(sym.vowel, "")
result += _block_letter(
lett,
["letter-vav"],
"",
vow,
[f"vowel-{sym.vowel}"],
sym.vowel,
sym.dagesh,
", ".join(sym.rules),
)
return jsonify(
JSend(
display=f'<div class="hebrew" dir="rtl">{result}</div>',
syllables=str([x.flat() for x in syls]),
rules=str(syls.rules.flat()),
)
)
def _list(key: str, vals: dict) -> list:
"""Get a key from a dictionary of values and ensure it is a list."""
result = vals.get(key, [])
if not isinstance(result, list):
result = [result]
return result
def search(limit=1000, shemot=False, **kwargs):
"""Return a list of Words that match the search criteria.
Kwargs:
books (list): names of the books to search
shemot (bool): if True, allow shemot to be displayed (default: False)
limit (int): maximum number of results (default: 1000)
Character Filters:
- find_any (list): at least one of these characters must appear
- find_all (list): all of these characters must appear
- find_none (list): none of these character must apepar
- find_seq (list): all of these characters in this relative order must
appear in each word
- find_pat (list): all of these characters in this precise order must
appear in each word
Integer Filters:
- gematria (list[int]): only include words equal to these values
- syllen (list[int]): only include words with these syllable lengths
- frequency (list[int]): only include words with these frequencies
(0=rare, 5=extremely common)
Returns:
list<Word>. Words that match the criteria.
"""
# pylint: disable=too-many-locals, too-many-branches, too-many-statements
query = Word.query.join(Freq)
if not shemot:
query = query.filter(Word.shemot == false())
# Books
books_all = _list("books_all", kwargs)
if books_all:
query = query.join(Book).filter(Book.name.in_(books_all))
# Symbols
find_any = _list("find_any", kwargs)
find_all = _list("find_all", kwargs)
find_none = _list("find_none", kwargs)
find_seq = _list("find_seq", kwargs)
find_pat = _list("find_pat", kwargs)
if find_any:
condition = [Word.parsed.like(f"%'{letter}'%") for letter in find_any]
query = query.filter(or_(*condition))
if find_all:
condition = [Word.parsed.like(f"%'{letter}'%") for letter in find_all]
query = query.filter(and_(*condition))
if find_none:
condition = [~Word.parsed.like(f"%'{letter}'%") for letter in find_none]
query = query.filter(and_(*condition))
if find_seq:
quoted = [f"'{x}'" for x in find_seq]
condition = f"%{"%".join(quoted)}%"
query = query.filter(Word.parsed.like(condition))
if find_pat:
quoted = [f"'{x}'" for x in find_pat]
condition = ", ".join(quoted)
query = query.filter(Word.parsed.like(f"%{condition}%"))
# Rules
rule_any = _list("rule_any", kwargs)
rule_all = _list("rule_all", kwargs)
rule_none = _list("rule_none", kwargs)
if rule_any:
condition = [Word.rules.like(f"%'{rule}'%") for rule in rule_any]
query = query.filter(or_(*condition))
if rule_all:
condition = [Word.rules.like(f"%'{rule}'%") for rule in rule_all]
query = query.filter(and_(*condition))
if rule_none:
condition = [~Word.rules.like(f"%'{rule}'%") for rule in rule_none]
query = query.filter(and_(*condition))
# Filters
gematria = _list("gematria", kwargs)
syllen = _list("syllen", kwargs)
freq = _list("freq", kwargs)
if gematria:
query = query.filter(Word.gematria.in_(gematria))
if syllen:
query = query.filter(Word.syllen.in_(syllen))
freq_col = func.sum(Freq.freq).label("freq")
if freq:
condition = [freq_col.between(5 ** n, 5 ** (n + 1)) for n in freq]
query = query.having(or_(*condition))
# Order
order = kwargs.get("order", "alpha")
if order == "random":
query = query.order_by(func.random())
elif order == "freq":
query = query.order_by(desc("freq"), Freq.book_id, Word.id)
elif order == "alpha":
query = query.order_by(Word.hebrew, Freq.book_id, Word.id)
elif order == "source":
query = query.order_by(Freq.book_id, Word.id)
query = query.add_columns(
# Word.id, Word.hebrew, Word.parsed, Word.rules, freq_col, Freq.ref
Word.id,
Word.hebrew,
freq_col,
Freq.ref,
).group_by(Word.hebrew)
# Limits
if limit:
query = query.limit(limit)
return query
| #!/usr/bin/env python
# coding: utf-8
"""Controllers for HebPhonics."""
# native
import os
from inspect import cleandoc
# lib
from flask import jsonify, render_template, request
from sqlalchemy.sql import and_, or_
from sqlalchemy.sql.expression import desc, false, func
from markdown import markdown
# pkg
from .. import app, tokens as T, rules, __version__, __pubdate__
from ..grammar import ItemList, Cluster, Parser
from ..models import Book, Word, Freq
from .jsend import JSend
VERSION = __version__ if not __pubdate__ else f"{__version__} ({__pubdate__})"
GOOGLE_ANALYTICS_ID = os.getenv("GOOGLE_ANALYTICS_ID")
def get_color(count):
"""Simple color scale."""
color = ""
if count == 0:
color = "is-danger"
elif count < 20:
color = "is-warning"
elif count < 300:
color = "is-primary"
elif count < 1000:
color = "is-success"
else:
color = "is-black"
return color
@app.route("/")
def index():
"""Home page."""
return render_template(
"index.html",
books=[b.name for b in Book.query.order_by(Book.id).all()],
symbols=[x for x in list(T.SYMBOLS) if x not in ["dagesh", "holam"]],
rules=rules.RULES,
version=VERSION,
GOOGLE_ANALYTICS_ID=GOOGLE_ANALYTICS_ID,
)
@app.route("/rules")
def list_rules():
"""Get rules list from the database."""
all_rules = {}
all_symbols = {}
see_also = rules.__doc__[rules.__doc__.find("See also:") + 10 :]
for rule, fn in rules.RULES.items():
count = (
Word.query.filter(Word.rules.like(f"%'{rule}'%"))
.with_entities(func.count())
.scalar()
)
parts = cleandoc(fn.__doc__ or "").split("\n")
stmt = f"- **Rule**: {parts[0]}"
rest = (
"\n".join(parts[1:])
.replace("Example:", "- **Example**:")
.replace("Examples:", "- **Examples**:")
.replace("Requires:", "- **Requires**:")
.replace("See also:", "- **See also**:")
.replace("Source:", "- **Source**:")
.replace("Sources:", "- **Sources**:")
)
doc = markdown(f"{rest}\n\n{stmt}\n\n{see_also}")
all_rules[rule] = dict(doc=doc, count=f"{count:,}", color=get_color(count))
for symbol in T.SYMBOLS:
count = (
Word.query.filter(Word.parsed.like(f"%'{symbol}'%"))
.with_entities(func.count())
.scalar()
)
all_symbols[symbol] = dict(count=f"{count:,}", color=get_color(count))
return render_template(
"rules.html",
rules=all_rules,
symbols=all_symbols,
version=VERSION,
GOOGLE_ANALYTICS_ID=GOOGLE_ANALYTICS_ID,
)
@app.route("/words", methods=["GET", "POST"])
def list_word():
"""Search database."""
args = request.json
query = search(**args)
words = [{"h": w.hebrew, "f": w.freq, "r": w.ref} for w in query.all()]
sql = str(query.statement.compile(compile_kwargs={"literal_binds": True}))
return jsonify(JSend(data=words, query=sql))
def _block_letter(base, bclasses, btool, full, fclasses, ftool, dtool, rules_=""):
if rules_:
rules_ = f"[{rules_}]"
tool = "\n".join([x for x in [btool, dtool, ftool, rules_] if x]).strip()
if tool:
tool = f' data-tooltip="{tool}"'
return f"""
<span class="letter">
<span class="base {' '.join(bclasses)} has-tooltip-left"{tool}>{base}</span>
<span class="full {' '.join(fclasses)}">{full}</span>
</span>"""
@app.route("/display", methods=["POST"])
def display_word():
"""Typographical hints for words."""
word = request.json["word"]
query = Word.query.filter(Word.hebrew == word).first()
if query:
syls = ItemList([ItemList([Cluster(**t) for t in s]) for s in query.syls])
else:
parser = Parser()
parsed = parser.parse(word)
syls = parser.syl(parsed)
result = ""
for num, syl in enumerate(syls):
if num > 0:
result += _block_letter(" | ", ["syllable"], "", "", ["syllable"], "", "")
for sym in syl:
lett = f"{T.SYMBOLS.get(sym.letter, '')}{T.SYMBOLS.get(sym.dagesh, '')}"
vow = T.SYMBOLS.get(sym.vowel, "")
if sym.vowel in [T.NAME_HOLAM_MALE_VAV, T.NAME_SHURUQ]:
vow = ""
lett_show = [T.POINT_HOLAM, T.LETTER_FINAL_KAF]
lett_hide = [T.LETTER_AYIN]
result += _block_letter(
lett,
[f"letter-{sym.letter}", sym.dagesh],
sym.letter,
f"{lett if (lett in lett_show or vow in lett_show) and not (lett in lett_hide or vow in lett_hide) else ' '}{vow}",
[f"vowel-{sym.vowel}"],
sym.vowel,
sym.dagesh,
", ".join(sym.rules),
)
if sym.vowel in [T.NAME_HOLAM_MALE_VAV, T.NAME_SHURUQ]:
lett = T.SYMBOLS.get("vav", "")
vow = T.SYMBOLS.get(sym.vowel, "")
result += _block_letter(
lett,
["letter-vav"],
"",
vow,
[f"vowel-{sym.vowel}"],
sym.vowel,
sym.dagesh,
", ".join(sym.rules),
)
return jsonify(
JSend(
display=f'<div class="hebrew" dir="rtl">{result}</div>',
syllables=str([x.flat() for x in syls]),
rules=str(syls.rules.flat()),
)
)
def _list(key: str, vals: dict) -> list:
"""Get a key from a dictionary of values and ensure it is a list."""
result = vals.get(key, [])
if not isinstance(result, list):
result = [result]
return result
def search(limit=1000, shemot=False, **kwargs):
"""Return a list of Words that match the search criteria.
Kwargs:
books (list): names of the books to search
shemot (bool): if True, allow shemot to be displayed (default: False)
limit (int): maximum number of results (default: 1000)
Character Filters:
- find_any (list): at least one of these characters must appear
- find_all (list): all of these characters must appear
- find_none (list): none of these character must apepar
- find_seq (list): all of these characters in this relative order must
appear in each word
- find_pat (list): all of these characters in this precise order must
appear in each word
Integer Filters:
- gematria (list[int]): only include words equal to these values
- syllen (list[int]): only include words with these syllable lengths
- frequency (list[int]): only include words with these frequencies
(0=rare, 5=extremely common)
Returns:
list<Word>. Words that match the criteria.
"""
# pylint: disable=too-many-locals, too-many-branches, too-many-statements
query = Word.query.join(Freq)
if not shemot:
query = query.filter(Word.shemot == false())
# Books
books_all = _list("books_all", kwargs)
if books_all:
query = query.join(Book).filter(Book.name.in_(books_all))
# Symbols
find_any = _list("find_any", kwargs)
find_all = _list("find_all", kwargs)
find_none = _list("find_none", kwargs)
find_seq = _list("find_seq", kwargs)
find_pat = _list("find_pat", kwargs)
if find_any:
condition = [Word.parsed.like(f"%'{letter}'%") for letter in find_any]
query = query.filter(or_(*condition))
if find_all:
condition = [Word.parsed.like(f"%'{letter}'%") for letter in find_all]
query = query.filter(and_(*condition))
if find_none:
condition = [~Word.parsed.like(f"%'{letter}'%") for letter in find_none]
query = query.filter(and_(*condition))
if find_seq:
quoted = [f"'{x}'" for x in find_seq]
condition = f"%{'%'.join(quoted)}%"
query = query.filter(Word.parsed.like(condition))
if find_pat:
quoted = [f"'{x}'" for x in find_pat]
condition = ", ".join(quoted)
query = query.filter(Word.parsed.like(f"%{condition}%"))
# Rules
rule_any = _list("rule_any", kwargs)
rule_all = _list("rule_all", kwargs)
rule_none = _list("rule_none", kwargs)
if rule_any:
condition = [Word.rules.like(f"%'{rule}'%") for rule in rule_any]
query = query.filter(or_(*condition))
if rule_all:
condition = [Word.rules.like(f"%'{rule}'%") for rule in rule_all]
query = query.filter(and_(*condition))
if rule_none:
condition = [~Word.rules.like(f"%'{rule}'%") for rule in rule_none]
query = query.filter(and_(*condition))
# Filters
gematria = _list("gematria", kwargs)
syllen = _list("syllen", kwargs)
freq = _list("freq", kwargs)
if gematria:
query = query.filter(Word.gematria.in_(gematria))
if syllen:
query = query.filter(Word.syllen.in_(syllen))
freq_col = func.sum(Freq.freq).label("freq")
if freq:
condition = [freq_col.between(5 ** n, 5 ** (n + 1)) for n in freq]
query = query.having(or_(*condition))
# Order
order = kwargs.get("order", "alpha")
if order == "random":
query = query.order_by(func.random())
elif order == "freq":
query = query.order_by(desc("freq"), Freq.book_id, Word.id)
elif order == "alpha":
query = query.order_by(Word.hebrew, Freq.book_id, Word.id)
elif order == "source":
query = query.order_by(Freq.book_id, Word.id)
query = query.add_columns(
# Word.id, Word.hebrew, Word.parsed, Word.rules, freq_col, Freq.ref
Word.id,
Word.hebrew,
freq_col,
Freq.ref,
).group_by(Word.hebrew)
# Limits
if limit:
query = query.limit(limit)
return query
|
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
# with the License. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "LICENSE.txt" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and
# limitations under the License.
from datetime import datetime
from aws_cdk import aws_batch as batch
from aws_cdk import aws_cloudformation as cfn
from aws_cdk import aws_codebuild as codebuild
from aws_cdk import aws_ec2 as ec2
from aws_cdk import aws_ecr as ecr
from aws_cdk import aws_events as events
from aws_cdk import aws_iam as iam
from aws_cdk import aws_lambda as awslambda
from aws_cdk import aws_logs as logs
from aws_cdk.aws_ec2 import CfnSecurityGroup
from aws_cdk.core import CfnOutput, CfnResource, Construct, Fn, Stack
from pcluster.config.cluster_config import AwsBatchClusterConfig, CapacityType, SharedStorageType
from pcluster.constants import AWSBATCH_CLI_REQUIREMENTS, CW_LOG_GROUP_NAME_PREFIX, IAM_ROLE_PATH
from pcluster.models.s3_bucket import S3Bucket
from pcluster.templates.cdk_builder_utils import (
PclusterLambdaConstruct,
add_lambda_cfn_role,
get_assume_role_policy_document,
get_cloud_watch_logs_policy_statement,
get_cloud_watch_logs_retention_days,
get_custom_tags,
get_default_instance_tags,
get_log_group_deletion_policy,
get_mount_dirs_by_type,
get_queue_security_groups_full,
get_shared_storage_ids_by_type,
)
class AwsBatchConstruct(Construct):
"""Create the resources required when using AWS Batch as a scheduler."""
def __init__(
self,
scope: Construct,
id: str,
cluster_config: AwsBatchClusterConfig,
stack_name: str,
bucket: S3Bucket,
create_lambda_roles: bool,
compute_security_group: CfnSecurityGroup,
shared_storage_mappings: dict,
shared_storage_options: dict,
head_node_instance: ec2.CfnInstance,
managed_head_node_instance_role: iam.CfnRole,
):
super().__init__(scope, id)
self.stack_name = stack_name
self.stack_scope = scope
self.config = cluster_config
self.bucket = bucket
self.create_lambda_roles = create_lambda_roles
self.compute_security_group = compute_security_group
self.shared_storage_mappings = shared_storage_mappings
self.shared_storage_options = shared_storage_options
self.head_node_instance = head_node_instance
self.head_node_instance_role = managed_head_node_instance_role
# Currently AWS batch integration supports a single queue and a single compute resource
self.queue = self.config.scheduling.queues[0]
self.compute_resource = self.queue.compute_resources[0]
self._add_resources()
self._add_outputs()
# -- Utility methods --------------------------------------------------------------------------------------------- #
@property
def _stack_account(self):
return Stack.of(self).account
@property
def _stack_region(self):
return Stack.of(self).region
@property
def _url_suffix(self):
return Stack.of(self).url_suffix
def _stack_unique_id(self):
return Fn.select(2, Fn.split("/", Stack.of(self).stack_id))
def _format_arn(self, **kwargs):
return Stack.of(self).format_arn(**kwargs)
def _stack_id(self):
return Stack.of(self).stack_id
def _get_compute_env_prefix(self):
return Fn.select(1, Fn.split("compute-environment/", self._compute_env.ref))
def _cluster_scoped_iam_path(self):
"""Return a path to be associated IAM roles and instance profiles."""
return f"{IAM_ROLE_PATH}{self.stack_name}/"
# -- Resources --------------------------------------------------------------------------------------------------- #
def _add_resources(self):
# Augment head node instance profile with Batch-specific policies, only add policies to Role craeted by
# ParallelCluster
if self.head_node_instance_role:
self._add_batch_head_node_policies_to_role()
# Iam Roles
self._ecs_instance_role, self._iam_instance_profile = self._add_ecs_instance_role_and_profile()
# Spot Iam Role
self._spot_iam_fleet_role = None
if self.queue.capacity_type == CapacityType.SPOT:
self._spot_iam_fleet_role = self._add_spot_fleet_iam_role()
# Batch resources
self._compute_env = self._add_compute_env()
self._job_queue = self._add_job_queue()
self._job_role = self._add_job_role()
self._docker_images_repo = self._add_docker_images_repo()
self._job_definition_serial = self._add_job_definition_serial()
self._job_definition_mnp = self._add_job_definition_mnp()
self._batch_user_role = self._add_batch_user_role()
# Code build resources
self._code_build_role = self._add_code_build_role()
self._code_build_policy = self._add_code_build_policy()
self._docker_build_wait_condition_handle = self._add_docker_build_wait_condition_handle()
self._code_build_image_builder_project = self._add_code_build_docker_image_builder_project()
# Docker image management
self._manage_docker_images_lambda = self._add_manage_docker_images_lambda()
self._manage_docker_images_custom_resource = self._add_manage_docker_images_custom_resource()
self._docker_build_wait_condition = self._add_docker_build_wait_condition()
self._docker_build_wait_condition.add_depends_on(self._manage_docker_images_custom_resource)
# Code build notification
self._code_build_notification_lambda = self._add_code_build_notification_lambda()
self._code_build_notification_lambda.add_depends_on(self._docker_build_wait_condition_handle)
self._code_build_notification_rule = self._add_code_build_notification_rule()
self._manage_docker_images_custom_resource.add_depends_on(self._code_build_notification_rule)
def _add_compute_env(self):
return batch.CfnComputeEnvironment(
self.stack_scope,
"ComputeEnvironment",
type="MANAGED",
# service_role=self._batch_service_role.ref,
state="ENABLED",
compute_resources=batch.CfnComputeEnvironment.ComputeResourcesProperty(
type="SPOT" if self.queue.capacity_type == CapacityType.SPOT else "EC2",
minv_cpus=self.compute_resource.min_vcpus,
desiredv_cpus=self.compute_resource.desired_vcpus,
maxv_cpus=self.compute_resource.max_vcpus,
instance_types=self.compute_resource.instance_types,
subnets=self.queue.networking.subnet_ids,
security_group_ids=get_queue_security_groups_full(self.compute_security_group, self.queue),
instance_role=self._iam_instance_profile.ref,
bid_percentage=self.compute_resource.spot_bid_percentage,
spot_iam_fleet_role=self._spot_iam_fleet_role.attr_arn if self._spot_iam_fleet_role else None,
tags={
**get_default_instance_tags(
self.stack_name,
self.config,
self.compute_resource,
"Compute",
self.shared_storage_mappings,
raw_dict=True,
),
**get_custom_tags(self.config, raw_dict=True),
},
),
)
def _add_job_queue(self):
return batch.CfnJobQueue(
self.stack_scope,
"JobQueue",
priority=1,
compute_environment_order=[
batch.CfnJobQueue.ComputeEnvironmentOrderProperty(
compute_environment=self._compute_env.ref,
order=1,
)
],
)
def _add_ecs_instance_role_and_profile(self):
ecs_instance_role = iam.CfnRole(
self.stack_scope,
"EcsInstanceRole",
path=self._cluster_scoped_iam_path(),
managed_policy_arns=[
self._format_arn(
service="iam",
account="aws",
region="",
resource="policy/service-role/AmazonEC2ContainerServiceforEC2Role",
)
],
assume_role_policy_document=get_assume_role_policy_document(f"ec2.{self._url_suffix}"),
)
iam_instance_profile = iam.CfnInstanceProfile(
self.stack_scope, "IamInstanceProfile", path=self._cluster_scoped_iam_path(), roles=[ecs_instance_role.ref]
)
return ecs_instance_role, iam_instance_profile
def _add_job_role(self):
return iam.CfnRole(
self.stack_scope,
"JobRole",
path=self._cluster_scoped_iam_path(),
managed_policy_arns=[
self._format_arn(service="iam", account="aws", region="", resource="policy/AmazonS3ReadOnlyAccess"),
self._format_arn(
service="iam",
account="aws",
region="",
resource="policy/service-role/AmazonECSTaskExecutionRolePolicy",
),
],
assume_role_policy_document=get_assume_role_policy_document("ecs-tasks.amazonaws.com"),
policies=[
iam.CfnRole.PolicyProperty(
policy_name="s3PutObject",
policy_document=iam.PolicyDocument(
statements=[
iam.PolicyStatement(
actions=["s3:PutObject"],
effect=iam.Effect.ALLOW,
resources=[
self._format_arn(
service="s3",
resource=f"{self.bucket.name}/{self.bucket.artifact_directory}/batch/*",
region="",
account="",
),
],
sid="CloudWatchLogsPolicy",
),
],
),
),
iam.CfnRole.PolicyProperty(
policy_name="cfnDescribeStacks",
policy_document=iam.PolicyDocument(
statements=[
iam.PolicyStatement(
actions=["cloudformation:DescribeStacks"],
effect=iam.Effect.ALLOW,
resources=[
self._format_arn(
service="cloudformation",
resource=f"stack/{self.stack_name}/*",
),
self._format_arn(
# ToDo: This resource is for substack. Check if this is necessary for pcluster3
service="cloudformation",
resource=f"stack/{self.stack_name}-*/*",
),
],
sid="CloudWatchLogsPolicy",
),
],
),
),
],
)
def _add_docker_images_repo(self):
return ecr.CfnRepository(self.stack_scope, "ParallelClusterDockerImagesRepo")
def _add_job_definition_serial(self):
return batch.CfnJobDefinition(
self.stack_scope,
"JobDefinitionSerial",
type="container",
container_properties=self._get_container_properties(),
)
def _add_job_definition_mnp(self):
return batch.CfnJobDefinition(
self.stack_scope,
"JobDefinitionMNP",
type="multinode",
node_properties=batch.CfnJobDefinition.NodePropertiesProperty(
main_node=0,
num_nodes=1,
node_range_properties=[
batch.CfnJobDefinition.NodeRangePropertyProperty(
target_nodes="0:", container=self._get_container_properties()
)
],
),
)
def _add_batch_user_role(self):
batch_user_role_statement = iam.PolicyStatement(effect=iam.Effect.ALLOW, actions=["sts:AssumeRole"])
batch_user_role_statement.add_account_root_principal()
return iam.CfnRole(
self.stack_scope,
"PclusterBatchUserRole",
path=self._cluster_scoped_iam_path(),
max_session_duration=36000,
assume_role_policy_document=iam.PolicyDocument(statements=[batch_user_role_statement]),
policies=[
iam.CfnRole.PolicyProperty(
policy_name="BatchUserPolicy",
policy_document=iam.PolicyDocument(
statements=[
iam.PolicyStatement(
actions=[
"batch:SubmitJob",
"cloudformation:DescribeStacks",
"ecs:ListContainerInstances",
"ecs:DescribeContainerInstances",
"logs:GetLogEvents",
"logs:FilterLogEvents",
"s3:PutObject",
"s3:Get*",
"s3:DeleteObject",
"iam:PassRole",
],
effect=iam.Effect.ALLOW,
resources=[
self._job_definition_serial.ref,
self._job_definition_mnp.ref,
self._job_queue.ref,
self._job_role.attr_arn,
self._format_arn(service="cloudformation", resource=f"stack/{self.stack_name}/*"),
# ToDo: This resource is for substack. Check if this is necessary for pcluster3
self._format_arn(service="cloudformation", resource=f"stack/{self.stack_name}-*/*"),
self._format_arn(
service="s3",
resource=f"{self.bucket.name}/{self.bucket.artifact_directory}/batch/*",
region="",
account="",
),
self._format_arn(
service="ecs",
resource=f"cluster/{self._get_compute_env_prefix()}_Batch_*",
region=self._stack_region,
account=self._stack_account,
),
self._format_arn(
service="ecs",
resource="container-instance/*",
region=self._stack_region,
account=self._stack_account,
),
self._format_arn(
service="logs",
resource="log-group:/aws/batch/job:log-stream:*",
region=self._stack_region,
account=self._stack_account,
),
],
),
iam.PolicyStatement(
effect=iam.Effect.ALLOW,
actions=["s3:List*"],
resources=[
self._format_arn(service="s3", resource=self.bucket.name, region="", account=""),
],
),
iam.PolicyStatement(
effect=iam.Effect.ALLOW,
actions=[
"batch:DescribeJobQueues",
"batch:TerminateJob",
"batch:DescribeJobs",
"batch:CancelJob",
"batch:DescribeJobDefinitions",
"batch:ListJobs",
"batch:DescribeComputeEnvironments",
"ec2:DescribeInstances",
],
resources=["*"],
),
],
),
),
iam.CfnRole.PolicyProperty(
policy_name="cfnDescribeStacks",
policy_document=iam.PolicyDocument(
statements=[
iam.PolicyStatement(
actions=["cloudformation:DescribeStacks"],
effect=iam.Effect.ALLOW,
resources=[
self._format_arn(
service="cloudformation",
resource=f"stack/{self.stack_name}/*",
),
self._format_arn(
# ToDo: This resource is for substack. Check if this is necessary for pcluster3
service="cloudformation",
resource=f"stack/{self.stack_name}-*/*",
),
],
sid="CloudWatchLogsPolicy",
),
],
),
),
],
)
def _add_spot_fleet_iam_role(self):
return iam.CfnRole(
self.stack_scope,
"BatchSpotRole",
path=self._cluster_scoped_iam_path(),
managed_policy_arns=[
self._format_arn(
service="iam",
account="aws",
region="",
resource="policy/service-role/AmazonEC2SpotFleetTaggingRole",
)
],
assume_role_policy_document=get_assume_role_policy_document("spotfleet.amazonaws.com"),
)
def _get_container_properties(self):
return batch.CfnJobDefinition.ContainerPropertiesProperty(
job_role_arn=self._job_role.attr_arn,
image="{account}.dkr.ecr.{region}.{url_suffix}/{docker_images_repo}:{os}".format(
account=self._stack_account,
region=self._stack_region,
url_suffix=self._url_suffix,
docker_images_repo=self._docker_images_repo.ref,
os=self.config.image.os,
),
vcpus=1,
memory=512,
privileged=True,
environment=[
batch.CfnJobDefinition.EnvironmentProperty(name="PCLUSTER_AWS_REGION", value=self._stack_region),
batch.CfnJobDefinition.EnvironmentProperty(name="PCLUSTER_STACK_NAME", value=self.stack_name),
batch.CfnJobDefinition.EnvironmentProperty(
name="PCLUSTER_SHARED_DIRS",
value=get_mount_dirs_by_type(self.shared_storage_options, SharedStorageType.EBS),
),
batch.CfnJobDefinition.EnvironmentProperty(
name="PCLUSTER_EFS_SHARED_DIR",
value=get_mount_dirs_by_type(self.shared_storage_options, SharedStorageType.EFS),
),
batch.CfnJobDefinition.EnvironmentProperty(
name="PCLUSTER_EFS_FS_ID",
value=get_shared_storage_ids_by_type(self.shared_storage_mappings, SharedStorageType.EFS),
),
batch.CfnJobDefinition.EnvironmentProperty(
name="PCLUSTER_RAID_SHARED_DIR",
value=get_mount_dirs_by_type(self.shared_storage_options, SharedStorageType.RAID),
),
batch.CfnJobDefinition.EnvironmentProperty(
name="PCLUSTER_HEAD_NODE_IP", value=self.head_node_instance.attr_private_ip
),
],
)
def _add_code_build_role(self):
return iam.CfnRole(
self.stack_scope,
"CodeBuildRole",
path=self._cluster_scoped_iam_path(),
assume_role_policy_document=get_assume_role_policy_document("codebuild.amazonaws.com"),
)
def _add_code_build_policy(self):
return iam.CfnPolicy(
self.stack_scope,
"CodeBuildPolicy",
policy_name="CodeBuildPolicy",
policy_document=iam.PolicyDocument(
statements=[
iam.PolicyStatement(
sid="ECRRepoPolicy",
effect=iam.Effect.ALLOW,
actions=[
"ecr:BatchCheckLayerAvailability",
"ecr:CompleteLayerUpload",
"ecr:InitiateLayerUpload",
"ecr:PutImage",
"ecr:UploadLayerPart",
],
resources=[self._docker_images_repo.attr_arn],
),
iam.PolicyStatement(
sid="ECRPolicy", effect=iam.Effect.ALLOW, actions=["ecr:GetAuthorizationToken"], resources=["*"]
),
get_cloud_watch_logs_policy_statement(
resource=self._format_arn(service="logs", account="*", region="*", resource="*")
),
iam.PolicyStatement(
sid="S3GetObjectPolicy",
effect=iam.Effect.ALLOW,
actions=["s3:GetObject", "s3:GetObjectVersion"],
resources=[
self._format_arn(
service="s3",
region="",
resource=f"{self.bucket.name}/{self.bucket.artifact_directory}/*",
account="",
)
],
),
]
),
roles=[self._code_build_role.ref],
)
def _add_code_build_docker_image_builder_project(self):
timestamp = f"{datetime.utcnow().strftime("%Y%m%d%H%M")}"
log_group_name = (
f"{CW_LOG_GROUP_NAME_PREFIX}codebuild/{self.stack_name}-CodeBuildDockerImageBuilderProject-{timestamp}"
)
log_group = logs.CfnLogGroup(
self.stack_scope,
"CodeBuildLogGroup",
log_group_name=log_group_name,
retention_in_days=get_cloud_watch_logs_retention_days(self.config),
)
log_group.cfn_options.deletion_policy = get_log_group_deletion_policy(self.config)
return codebuild.CfnProject(
self.stack_scope,
"CodeBuildDockerImageBuilderProj",
artifacts=codebuild.CfnProject.ArtifactsProperty(type="NO_ARTIFACTS"),
environment=codebuild.CfnProject.EnvironmentProperty(
compute_type="BUILD_GENERAL1_LARGE"
if self._condition_use_arm_code_build_image()
else "BUILD_GENERAL1_SMALL",
environment_variables=[
codebuild.CfnProject.EnvironmentVariableProperty(
name="AWS_REGION",
value=self._stack_region,
),
codebuild.CfnProject.EnvironmentVariableProperty(
name="AWS_ACCOUNT_ID",
value=self._stack_account,
),
codebuild.CfnProject.EnvironmentVariableProperty(
name="IMAGE_REPO_NAME",
value=self._docker_images_repo.ref,
),
codebuild.CfnProject.EnvironmentVariableProperty(
name="IMAGE",
value=self.config.image.os,
),
codebuild.CfnProject.EnvironmentVariableProperty(
name="NOTIFICATION_URL",
value=self._docker_build_wait_condition_handle.ref,
),
],
image="aws/codebuild/amazonlinux2-aarch64-standard:1.0"
if self._condition_use_arm_code_build_image()
else "aws/codebuild/amazonlinux2-x86_64-standard:3.0",
type="ARM_CONTAINER" if self._condition_use_arm_code_build_image() else "LINUX_CONTAINER",
privileged_mode=True,
),
name=f"pcluster-{self.stack_name}-build-docker-images-project",
service_role=self._code_build_role.attr_arn,
source=codebuild.CfnProject.SourceProperty(
location=f"{self.bucket.name}/{self.bucket.artifact_directory}"
"/custom_resources/scheduler_resources.zip",
type="S3",
),
logs_config=codebuild.CfnProject.LogsConfigProperty(
cloud_watch_logs=codebuild.CfnProject.CloudWatchLogsConfigProperty(
group_name=log_group_name, status="ENABLED"
)
),
)
def _add_manage_docker_images_lambda(self):
manage_docker_images_lambda_execution_role = None
if self.create_lambda_roles:
manage_docker_images_lambda_execution_role = add_lambda_cfn_role(
scope=self.stack_scope,
function_id="ManageDockerImages",
statements=[
iam.PolicyStatement(
actions=["ecr:BatchDeleteImage", "ecr:ListImages"],
effect=iam.Effect.ALLOW,
resources=[self._docker_images_repo.attr_arn],
sid="ECRPolicy",
),
iam.PolicyStatement(
actions=["codebuild:BatchGetBuilds", "codebuild:StartBuild"],
effect=iam.Effect.ALLOW,
resources=[self._code_build_image_builder_project.attr_arn],
sid="CodeBuildPolicy",
),
get_cloud_watch_logs_policy_statement(
resource=self._format_arn(service="logs", account="*", region="*", resource="*")
),
],
)
return PclusterLambdaConstruct(
scope=self.stack_scope,
id="ManageDockerImagesFunctionConstruct",
function_id="ManageDockerImages",
bucket=self.bucket,
config=self.config,
execution_role=manage_docker_images_lambda_execution_role.attr_arn
if manage_docker_images_lambda_execution_role
else self.config.iam.roles.lambda_functions_role,
handler_func="manage_docker_images",
timeout=60,
).lambda_func
def _add_code_build_notification_rule(self):
code_build_notification_rule = events.CfnRule(
self.stack_scope,
"CodeBuildNotificationRule",
event_pattern={
"detail": {
"build-status": ["FAILED", "STOPPED", "SUCCEEDED"],
"project-name": [self._code_build_image_builder_project.ref],
},
"detail-type": ["CodeBuild Build State Change"],
"source": ["aws.codebuild"],
},
state="ENABLED",
targets=[
events.CfnRule.TargetProperty(
arn=self._code_build_notification_lambda.attr_arn,
id="BuildNotificationFunction",
)
],
)
awslambda.CfnPermission(
self.stack_scope,
"BuildNotificationFunctionInvokePermission",
action="lambda:InvokeFunction",
function_name=self._code_build_notification_lambda.attr_arn,
principal="events.amazonaws.com",
source_arn=code_build_notification_rule.attr_arn,
)
return code_build_notification_rule
def _add_code_build_notification_lambda(self):
build_notification_lambda_execution_role = None
if self.create_lambda_roles:
build_notification_lambda_execution_role = add_lambda_cfn_role(
scope=self.stack_scope,
function_id="BuildNotification",
statements=[
get_cloud_watch_logs_policy_statement(
resource=self._format_arn(service="logs", account="*", region="*", resource="*")
)
],
)
return PclusterLambdaConstruct(
scope=self.stack_scope,
id="BuildNotificationFunctionConstruct",
function_id="BuildNotification",
bucket=self.bucket,
config=self.config,
execution_role=build_notification_lambda_execution_role.attr_arn
if build_notification_lambda_execution_role
else self.config.iam.roles.lambda_functions_role,
handler_func="send_build_notification",
timeout=60,
).lambda_func
def _add_manage_docker_images_custom_resource(self):
return CfnResource(
self.stack_scope,
"ManageDockerImagesCustomResource",
type="AWS::CloudFormation::CustomResource",
properties={
"ServiceToken": self._manage_docker_images_lambda.attr_arn,
"CodeBuildProject": self._code_build_image_builder_project.ref,
"EcrRepository": self._docker_images_repo.ref,
},
)
def _add_docker_build_wait_condition_handle(self):
return cfn.CfnWaitConditionHandle(self.stack_scope, "DockerBuildWaitHandle")
def _add_docker_build_wait_condition(self):
return cfn.CfnWaitCondition(
self.stack_scope,
"DockerBuildWaitCondition",
handle=self._docker_build_wait_condition_handle.ref,
timeout="3600",
)
def _add_batch_head_node_policies_to_role(self):
iam.CfnPolicy(
self,
"ParallelClusterBatchPoliciesHeadNode",
policy_name="parallelcluster-awsbatch-head-node",
policy_document=iam.PolicyDocument(
statements=[
iam.PolicyStatement(
sid="BatchJobPassRole",
actions=["iam:PassRole"],
effect=iam.Effect.ALLOW,
resources=[
self._format_arn(
service="iam",
region="",
resource=f"role{self._cluster_scoped_iam_path()}*",
)
],
),
]
),
roles=[self.head_node_instance_role.ref],
)
# -- Conditions -------------------------------------------------------------------------------------------------- #
def _condition_use_arm_code_build_image(self):
return self.config.head_node.architecture == "arm64"
# -- Outputs ----------------------------------------------------------------------------------------------------- #
def _add_outputs(self):
CfnOutput(
scope=self.stack_scope,
id="BatchCliRequirements",
description="List of requirements for the ParallelCluster AWS Batch CLI.",
value=AWSBATCH_CLI_REQUIREMENTS,
)
CfnOutput(
self.stack_scope,
"BatchComputeEnvironmentArn",
description="Compute Environment created within the cluster.",
value=self._compute_env.ref,
)
CfnOutput(
self.stack_scope,
"BatchJobQueueArn",
description="Job Queue created within the cluster.",
value=self._job_queue.ref,
)
CfnOutput(
self.stack_scope,
"BatchJobDefinitionArn",
description="Job Definition for serial submission.",
value=self._job_definition_serial.ref,
)
CfnOutput(
self.stack_scope,
"ECRRepoName",
description="Name of the ECR repository where docker images used by AWS Batch are located.",
value=self._docker_images_repo.ref,
)
CfnOutput(
self.stack_scope,
"CodeBuildDockerImageBuilderProject",
description="CodeBuild project used to bake docker images.",
value=self._code_build_image_builder_project.ref,
)
CfnOutput(
self.stack_scope,
"BatchJobDefinitionMnpArn",
description="Job Definition for MNP submission.",
value=self._job_definition_mnp.ref,
)
CfnOutput(
self.stack_scope,
"BatchUserRole",
description="Role to be used to contact AWS Batch resources created within the cluster.",
value=self._batch_user_role.ref,
)
| # Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
# with the License. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "LICENSE.txt" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and
# limitations under the License.
from datetime import datetime
from aws_cdk import aws_batch as batch
from aws_cdk import aws_cloudformation as cfn
from aws_cdk import aws_codebuild as codebuild
from aws_cdk import aws_ec2 as ec2
from aws_cdk import aws_ecr as ecr
from aws_cdk import aws_events as events
from aws_cdk import aws_iam as iam
from aws_cdk import aws_lambda as awslambda
from aws_cdk import aws_logs as logs
from aws_cdk.aws_ec2 import CfnSecurityGroup
from aws_cdk.core import CfnOutput, CfnResource, Construct, Fn, Stack
from pcluster.config.cluster_config import AwsBatchClusterConfig, CapacityType, SharedStorageType
from pcluster.constants import AWSBATCH_CLI_REQUIREMENTS, CW_LOG_GROUP_NAME_PREFIX, IAM_ROLE_PATH
from pcluster.models.s3_bucket import S3Bucket
from pcluster.templates.cdk_builder_utils import (
PclusterLambdaConstruct,
add_lambda_cfn_role,
get_assume_role_policy_document,
get_cloud_watch_logs_policy_statement,
get_cloud_watch_logs_retention_days,
get_custom_tags,
get_default_instance_tags,
get_log_group_deletion_policy,
get_mount_dirs_by_type,
get_queue_security_groups_full,
get_shared_storage_ids_by_type,
)
class AwsBatchConstruct(Construct):
"""Create the resources required when using AWS Batch as a scheduler."""
def __init__(
self,
scope: Construct,
id: str,
cluster_config: AwsBatchClusterConfig,
stack_name: str,
bucket: S3Bucket,
create_lambda_roles: bool,
compute_security_group: CfnSecurityGroup,
shared_storage_mappings: dict,
shared_storage_options: dict,
head_node_instance: ec2.CfnInstance,
managed_head_node_instance_role: iam.CfnRole,
):
super().__init__(scope, id)
self.stack_name = stack_name
self.stack_scope = scope
self.config = cluster_config
self.bucket = bucket
self.create_lambda_roles = create_lambda_roles
self.compute_security_group = compute_security_group
self.shared_storage_mappings = shared_storage_mappings
self.shared_storage_options = shared_storage_options
self.head_node_instance = head_node_instance
self.head_node_instance_role = managed_head_node_instance_role
# Currently AWS batch integration supports a single queue and a single compute resource
self.queue = self.config.scheduling.queues[0]
self.compute_resource = self.queue.compute_resources[0]
self._add_resources()
self._add_outputs()
# -- Utility methods --------------------------------------------------------------------------------------------- #
@property
def _stack_account(self):
return Stack.of(self).account
@property
def _stack_region(self):
return Stack.of(self).region
@property
def _url_suffix(self):
return Stack.of(self).url_suffix
def _stack_unique_id(self):
return Fn.select(2, Fn.split("/", Stack.of(self).stack_id))
def _format_arn(self, **kwargs):
return Stack.of(self).format_arn(**kwargs)
def _stack_id(self):
return Stack.of(self).stack_id
def _get_compute_env_prefix(self):
return Fn.select(1, Fn.split("compute-environment/", self._compute_env.ref))
def _cluster_scoped_iam_path(self):
"""Return a path to be associated IAM roles and instance profiles."""
return f"{IAM_ROLE_PATH}{self.stack_name}/"
# -- Resources --------------------------------------------------------------------------------------------------- #
def _add_resources(self):
# Augment head node instance profile with Batch-specific policies, only add policies to Role craeted by
# ParallelCluster
if self.head_node_instance_role:
self._add_batch_head_node_policies_to_role()
# Iam Roles
self._ecs_instance_role, self._iam_instance_profile = self._add_ecs_instance_role_and_profile()
# Spot Iam Role
self._spot_iam_fleet_role = None
if self.queue.capacity_type == CapacityType.SPOT:
self._spot_iam_fleet_role = self._add_spot_fleet_iam_role()
# Batch resources
self._compute_env = self._add_compute_env()
self._job_queue = self._add_job_queue()
self._job_role = self._add_job_role()
self._docker_images_repo = self._add_docker_images_repo()
self._job_definition_serial = self._add_job_definition_serial()
self._job_definition_mnp = self._add_job_definition_mnp()
self._batch_user_role = self._add_batch_user_role()
# Code build resources
self._code_build_role = self._add_code_build_role()
self._code_build_policy = self._add_code_build_policy()
self._docker_build_wait_condition_handle = self._add_docker_build_wait_condition_handle()
self._code_build_image_builder_project = self._add_code_build_docker_image_builder_project()
# Docker image management
self._manage_docker_images_lambda = self._add_manage_docker_images_lambda()
self._manage_docker_images_custom_resource = self._add_manage_docker_images_custom_resource()
self._docker_build_wait_condition = self._add_docker_build_wait_condition()
self._docker_build_wait_condition.add_depends_on(self._manage_docker_images_custom_resource)
# Code build notification
self._code_build_notification_lambda = self._add_code_build_notification_lambda()
self._code_build_notification_lambda.add_depends_on(self._docker_build_wait_condition_handle)
self._code_build_notification_rule = self._add_code_build_notification_rule()
self._manage_docker_images_custom_resource.add_depends_on(self._code_build_notification_rule)
def _add_compute_env(self):
return batch.CfnComputeEnvironment(
self.stack_scope,
"ComputeEnvironment",
type="MANAGED",
# service_role=self._batch_service_role.ref,
state="ENABLED",
compute_resources=batch.CfnComputeEnvironment.ComputeResourcesProperty(
type="SPOT" if self.queue.capacity_type == CapacityType.SPOT else "EC2",
minv_cpus=self.compute_resource.min_vcpus,
desiredv_cpus=self.compute_resource.desired_vcpus,
maxv_cpus=self.compute_resource.max_vcpus,
instance_types=self.compute_resource.instance_types,
subnets=self.queue.networking.subnet_ids,
security_group_ids=get_queue_security_groups_full(self.compute_security_group, self.queue),
instance_role=self._iam_instance_profile.ref,
bid_percentage=self.compute_resource.spot_bid_percentage,
spot_iam_fleet_role=self._spot_iam_fleet_role.attr_arn if self._spot_iam_fleet_role else None,
tags={
**get_default_instance_tags(
self.stack_name,
self.config,
self.compute_resource,
"Compute",
self.shared_storage_mappings,
raw_dict=True,
),
**get_custom_tags(self.config, raw_dict=True),
},
),
)
def _add_job_queue(self):
return batch.CfnJobQueue(
self.stack_scope,
"JobQueue",
priority=1,
compute_environment_order=[
batch.CfnJobQueue.ComputeEnvironmentOrderProperty(
compute_environment=self._compute_env.ref,
order=1,
)
],
)
def _add_ecs_instance_role_and_profile(self):
ecs_instance_role = iam.CfnRole(
self.stack_scope,
"EcsInstanceRole",
path=self._cluster_scoped_iam_path(),
managed_policy_arns=[
self._format_arn(
service="iam",
account="aws",
region="",
resource="policy/service-role/AmazonEC2ContainerServiceforEC2Role",
)
],
assume_role_policy_document=get_assume_role_policy_document(f"ec2.{self._url_suffix}"),
)
iam_instance_profile = iam.CfnInstanceProfile(
self.stack_scope, "IamInstanceProfile", path=self._cluster_scoped_iam_path(), roles=[ecs_instance_role.ref]
)
return ecs_instance_role, iam_instance_profile
def _add_job_role(self):
return iam.CfnRole(
self.stack_scope,
"JobRole",
path=self._cluster_scoped_iam_path(),
managed_policy_arns=[
self._format_arn(service="iam", account="aws", region="", resource="policy/AmazonS3ReadOnlyAccess"),
self._format_arn(
service="iam",
account="aws",
region="",
resource="policy/service-role/AmazonECSTaskExecutionRolePolicy",
),
],
assume_role_policy_document=get_assume_role_policy_document("ecs-tasks.amazonaws.com"),
policies=[
iam.CfnRole.PolicyProperty(
policy_name="s3PutObject",
policy_document=iam.PolicyDocument(
statements=[
iam.PolicyStatement(
actions=["s3:PutObject"],
effect=iam.Effect.ALLOW,
resources=[
self._format_arn(
service="s3",
resource=f"{self.bucket.name}/{self.bucket.artifact_directory}/batch/*",
region="",
account="",
),
],
sid="CloudWatchLogsPolicy",
),
],
),
),
iam.CfnRole.PolicyProperty(
policy_name="cfnDescribeStacks",
policy_document=iam.PolicyDocument(
statements=[
iam.PolicyStatement(
actions=["cloudformation:DescribeStacks"],
effect=iam.Effect.ALLOW,
resources=[
self._format_arn(
service="cloudformation",
resource=f"stack/{self.stack_name}/*",
),
self._format_arn(
# ToDo: This resource is for substack. Check if this is necessary for pcluster3
service="cloudformation",
resource=f"stack/{self.stack_name}-*/*",
),
],
sid="CloudWatchLogsPolicy",
),
],
),
),
],
)
def _add_docker_images_repo(self):
return ecr.CfnRepository(self.stack_scope, "ParallelClusterDockerImagesRepo")
def _add_job_definition_serial(self):
return batch.CfnJobDefinition(
self.stack_scope,
"JobDefinitionSerial",
type="container",
container_properties=self._get_container_properties(),
)
def _add_job_definition_mnp(self):
return batch.CfnJobDefinition(
self.stack_scope,
"JobDefinitionMNP",
type="multinode",
node_properties=batch.CfnJobDefinition.NodePropertiesProperty(
main_node=0,
num_nodes=1,
node_range_properties=[
batch.CfnJobDefinition.NodeRangePropertyProperty(
target_nodes="0:", container=self._get_container_properties()
)
],
),
)
def _add_batch_user_role(self):
batch_user_role_statement = iam.PolicyStatement(effect=iam.Effect.ALLOW, actions=["sts:AssumeRole"])
batch_user_role_statement.add_account_root_principal()
return iam.CfnRole(
self.stack_scope,
"PclusterBatchUserRole",
path=self._cluster_scoped_iam_path(),
max_session_duration=36000,
assume_role_policy_document=iam.PolicyDocument(statements=[batch_user_role_statement]),
policies=[
iam.CfnRole.PolicyProperty(
policy_name="BatchUserPolicy",
policy_document=iam.PolicyDocument(
statements=[
iam.PolicyStatement(
actions=[
"batch:SubmitJob",
"cloudformation:DescribeStacks",
"ecs:ListContainerInstances",
"ecs:DescribeContainerInstances",
"logs:GetLogEvents",
"logs:FilterLogEvents",
"s3:PutObject",
"s3:Get*",
"s3:DeleteObject",
"iam:PassRole",
],
effect=iam.Effect.ALLOW,
resources=[
self._job_definition_serial.ref,
self._job_definition_mnp.ref,
self._job_queue.ref,
self._job_role.attr_arn,
self._format_arn(service="cloudformation", resource=f"stack/{self.stack_name}/*"),
# ToDo: This resource is for substack. Check if this is necessary for pcluster3
self._format_arn(service="cloudformation", resource=f"stack/{self.stack_name}-*/*"),
self._format_arn(
service="s3",
resource=f"{self.bucket.name}/{self.bucket.artifact_directory}/batch/*",
region="",
account="",
),
self._format_arn(
service="ecs",
resource=f"cluster/{self._get_compute_env_prefix()}_Batch_*",
region=self._stack_region,
account=self._stack_account,
),
self._format_arn(
service="ecs",
resource="container-instance/*",
region=self._stack_region,
account=self._stack_account,
),
self._format_arn(
service="logs",
resource="log-group:/aws/batch/job:log-stream:*",
region=self._stack_region,
account=self._stack_account,
),
],
),
iam.PolicyStatement(
effect=iam.Effect.ALLOW,
actions=["s3:List*"],
resources=[
self._format_arn(service="s3", resource=self.bucket.name, region="", account=""),
],
),
iam.PolicyStatement(
effect=iam.Effect.ALLOW,
actions=[
"batch:DescribeJobQueues",
"batch:TerminateJob",
"batch:DescribeJobs",
"batch:CancelJob",
"batch:DescribeJobDefinitions",
"batch:ListJobs",
"batch:DescribeComputeEnvironments",
"ec2:DescribeInstances",
],
resources=["*"],
),
],
),
),
iam.CfnRole.PolicyProperty(
policy_name="cfnDescribeStacks",
policy_document=iam.PolicyDocument(
statements=[
iam.PolicyStatement(
actions=["cloudformation:DescribeStacks"],
effect=iam.Effect.ALLOW,
resources=[
self._format_arn(
service="cloudformation",
resource=f"stack/{self.stack_name}/*",
),
self._format_arn(
# ToDo: This resource is for substack. Check if this is necessary for pcluster3
service="cloudformation",
resource=f"stack/{self.stack_name}-*/*",
),
],
sid="CloudWatchLogsPolicy",
),
],
),
),
],
)
def _add_spot_fleet_iam_role(self):
return iam.CfnRole(
self.stack_scope,
"BatchSpotRole",
path=self._cluster_scoped_iam_path(),
managed_policy_arns=[
self._format_arn(
service="iam",
account="aws",
region="",
resource="policy/service-role/AmazonEC2SpotFleetTaggingRole",
)
],
assume_role_policy_document=get_assume_role_policy_document("spotfleet.amazonaws.com"),
)
def _get_container_properties(self):
return batch.CfnJobDefinition.ContainerPropertiesProperty(
job_role_arn=self._job_role.attr_arn,
image="{account}.dkr.ecr.{region}.{url_suffix}/{docker_images_repo}:{os}".format(
account=self._stack_account,
region=self._stack_region,
url_suffix=self._url_suffix,
docker_images_repo=self._docker_images_repo.ref,
os=self.config.image.os,
),
vcpus=1,
memory=512,
privileged=True,
environment=[
batch.CfnJobDefinition.EnvironmentProperty(name="PCLUSTER_AWS_REGION", value=self._stack_region),
batch.CfnJobDefinition.EnvironmentProperty(name="PCLUSTER_STACK_NAME", value=self.stack_name),
batch.CfnJobDefinition.EnvironmentProperty(
name="PCLUSTER_SHARED_DIRS",
value=get_mount_dirs_by_type(self.shared_storage_options, SharedStorageType.EBS),
),
batch.CfnJobDefinition.EnvironmentProperty(
name="PCLUSTER_EFS_SHARED_DIR",
value=get_mount_dirs_by_type(self.shared_storage_options, SharedStorageType.EFS),
),
batch.CfnJobDefinition.EnvironmentProperty(
name="PCLUSTER_EFS_FS_ID",
value=get_shared_storage_ids_by_type(self.shared_storage_mappings, SharedStorageType.EFS),
),
batch.CfnJobDefinition.EnvironmentProperty(
name="PCLUSTER_RAID_SHARED_DIR",
value=get_mount_dirs_by_type(self.shared_storage_options, SharedStorageType.RAID),
),
batch.CfnJobDefinition.EnvironmentProperty(
name="PCLUSTER_HEAD_NODE_IP", value=self.head_node_instance.attr_private_ip
),
],
)
def _add_code_build_role(self):
return iam.CfnRole(
self.stack_scope,
"CodeBuildRole",
path=self._cluster_scoped_iam_path(),
assume_role_policy_document=get_assume_role_policy_document("codebuild.amazonaws.com"),
)
def _add_code_build_policy(self):
return iam.CfnPolicy(
self.stack_scope,
"CodeBuildPolicy",
policy_name="CodeBuildPolicy",
policy_document=iam.PolicyDocument(
statements=[
iam.PolicyStatement(
sid="ECRRepoPolicy",
effect=iam.Effect.ALLOW,
actions=[
"ecr:BatchCheckLayerAvailability",
"ecr:CompleteLayerUpload",
"ecr:InitiateLayerUpload",
"ecr:PutImage",
"ecr:UploadLayerPart",
],
resources=[self._docker_images_repo.attr_arn],
),
iam.PolicyStatement(
sid="ECRPolicy", effect=iam.Effect.ALLOW, actions=["ecr:GetAuthorizationToken"], resources=["*"]
),
get_cloud_watch_logs_policy_statement(
resource=self._format_arn(service="logs", account="*", region="*", resource="*")
),
iam.PolicyStatement(
sid="S3GetObjectPolicy",
effect=iam.Effect.ALLOW,
actions=["s3:GetObject", "s3:GetObjectVersion"],
resources=[
self._format_arn(
service="s3",
region="",
resource=f"{self.bucket.name}/{self.bucket.artifact_directory}/*",
account="",
)
],
),
]
),
roles=[self._code_build_role.ref],
)
def _add_code_build_docker_image_builder_project(self):
timestamp = f"{datetime.utcnow().strftime('%Y%m%d%H%M')}"
log_group_name = (
f"{CW_LOG_GROUP_NAME_PREFIX}codebuild/{self.stack_name}-CodeBuildDockerImageBuilderProject-{timestamp}"
)
log_group = logs.CfnLogGroup(
self.stack_scope,
"CodeBuildLogGroup",
log_group_name=log_group_name,
retention_in_days=get_cloud_watch_logs_retention_days(self.config),
)
log_group.cfn_options.deletion_policy = get_log_group_deletion_policy(self.config)
return codebuild.CfnProject(
self.stack_scope,
"CodeBuildDockerImageBuilderProj",
artifacts=codebuild.CfnProject.ArtifactsProperty(type="NO_ARTIFACTS"),
environment=codebuild.CfnProject.EnvironmentProperty(
compute_type="BUILD_GENERAL1_LARGE"
if self._condition_use_arm_code_build_image()
else "BUILD_GENERAL1_SMALL",
environment_variables=[
codebuild.CfnProject.EnvironmentVariableProperty(
name="AWS_REGION",
value=self._stack_region,
),
codebuild.CfnProject.EnvironmentVariableProperty(
name="AWS_ACCOUNT_ID",
value=self._stack_account,
),
codebuild.CfnProject.EnvironmentVariableProperty(
name="IMAGE_REPO_NAME",
value=self._docker_images_repo.ref,
),
codebuild.CfnProject.EnvironmentVariableProperty(
name="IMAGE",
value=self.config.image.os,
),
codebuild.CfnProject.EnvironmentVariableProperty(
name="NOTIFICATION_URL",
value=self._docker_build_wait_condition_handle.ref,
),
],
image="aws/codebuild/amazonlinux2-aarch64-standard:1.0"
if self._condition_use_arm_code_build_image()
else "aws/codebuild/amazonlinux2-x86_64-standard:3.0",
type="ARM_CONTAINER" if self._condition_use_arm_code_build_image() else "LINUX_CONTAINER",
privileged_mode=True,
),
name=f"pcluster-{self.stack_name}-build-docker-images-project",
service_role=self._code_build_role.attr_arn,
source=codebuild.CfnProject.SourceProperty(
location=f"{self.bucket.name}/{self.bucket.artifact_directory}"
"/custom_resources/scheduler_resources.zip",
type="S3",
),
logs_config=codebuild.CfnProject.LogsConfigProperty(
cloud_watch_logs=codebuild.CfnProject.CloudWatchLogsConfigProperty(
group_name=log_group_name, status="ENABLED"
)
),
)
def _add_manage_docker_images_lambda(self):
manage_docker_images_lambda_execution_role = None
if self.create_lambda_roles:
manage_docker_images_lambda_execution_role = add_lambda_cfn_role(
scope=self.stack_scope,
function_id="ManageDockerImages",
statements=[
iam.PolicyStatement(
actions=["ecr:BatchDeleteImage", "ecr:ListImages"],
effect=iam.Effect.ALLOW,
resources=[self._docker_images_repo.attr_arn],
sid="ECRPolicy",
),
iam.PolicyStatement(
actions=["codebuild:BatchGetBuilds", "codebuild:StartBuild"],
effect=iam.Effect.ALLOW,
resources=[self._code_build_image_builder_project.attr_arn],
sid="CodeBuildPolicy",
),
get_cloud_watch_logs_policy_statement(
resource=self._format_arn(service="logs", account="*", region="*", resource="*")
),
],
)
return PclusterLambdaConstruct(
scope=self.stack_scope,
id="ManageDockerImagesFunctionConstruct",
function_id="ManageDockerImages",
bucket=self.bucket,
config=self.config,
execution_role=manage_docker_images_lambda_execution_role.attr_arn
if manage_docker_images_lambda_execution_role
else self.config.iam.roles.lambda_functions_role,
handler_func="manage_docker_images",
timeout=60,
).lambda_func
def _add_code_build_notification_rule(self):
code_build_notification_rule = events.CfnRule(
self.stack_scope,
"CodeBuildNotificationRule",
event_pattern={
"detail": {
"build-status": ["FAILED", "STOPPED", "SUCCEEDED"],
"project-name": [self._code_build_image_builder_project.ref],
},
"detail-type": ["CodeBuild Build State Change"],
"source": ["aws.codebuild"],
},
state="ENABLED",
targets=[
events.CfnRule.TargetProperty(
arn=self._code_build_notification_lambda.attr_arn,
id="BuildNotificationFunction",
)
],
)
awslambda.CfnPermission(
self.stack_scope,
"BuildNotificationFunctionInvokePermission",
action="lambda:InvokeFunction",
function_name=self._code_build_notification_lambda.attr_arn,
principal="events.amazonaws.com",
source_arn=code_build_notification_rule.attr_arn,
)
return code_build_notification_rule
def _add_code_build_notification_lambda(self):
build_notification_lambda_execution_role = None
if self.create_lambda_roles:
build_notification_lambda_execution_role = add_lambda_cfn_role(
scope=self.stack_scope,
function_id="BuildNotification",
statements=[
get_cloud_watch_logs_policy_statement(
resource=self._format_arn(service="logs", account="*", region="*", resource="*")
)
],
)
return PclusterLambdaConstruct(
scope=self.stack_scope,
id="BuildNotificationFunctionConstruct",
function_id="BuildNotification",
bucket=self.bucket,
config=self.config,
execution_role=build_notification_lambda_execution_role.attr_arn
if build_notification_lambda_execution_role
else self.config.iam.roles.lambda_functions_role,
handler_func="send_build_notification",
timeout=60,
).lambda_func
def _add_manage_docker_images_custom_resource(self):
return CfnResource(
self.stack_scope,
"ManageDockerImagesCustomResource",
type="AWS::CloudFormation::CustomResource",
properties={
"ServiceToken": self._manage_docker_images_lambda.attr_arn,
"CodeBuildProject": self._code_build_image_builder_project.ref,
"EcrRepository": self._docker_images_repo.ref,
},
)
def _add_docker_build_wait_condition_handle(self):
return cfn.CfnWaitConditionHandle(self.stack_scope, "DockerBuildWaitHandle")
def _add_docker_build_wait_condition(self):
return cfn.CfnWaitCondition(
self.stack_scope,
"DockerBuildWaitCondition",
handle=self._docker_build_wait_condition_handle.ref,
timeout="3600",
)
def _add_batch_head_node_policies_to_role(self):
iam.CfnPolicy(
self,
"ParallelClusterBatchPoliciesHeadNode",
policy_name="parallelcluster-awsbatch-head-node",
policy_document=iam.PolicyDocument(
statements=[
iam.PolicyStatement(
sid="BatchJobPassRole",
actions=["iam:PassRole"],
effect=iam.Effect.ALLOW,
resources=[
self._format_arn(
service="iam",
region="",
resource=f"role{self._cluster_scoped_iam_path()}*",
)
],
),
]
),
roles=[self.head_node_instance_role.ref],
)
# -- Conditions -------------------------------------------------------------------------------------------------- #
def _condition_use_arm_code_build_image(self):
return self.config.head_node.architecture == "arm64"
# -- Outputs ----------------------------------------------------------------------------------------------------- #
def _add_outputs(self):
CfnOutput(
scope=self.stack_scope,
id="BatchCliRequirements",
description="List of requirements for the ParallelCluster AWS Batch CLI.",
value=AWSBATCH_CLI_REQUIREMENTS,
)
CfnOutput(
self.stack_scope,
"BatchComputeEnvironmentArn",
description="Compute Environment created within the cluster.",
value=self._compute_env.ref,
)
CfnOutput(
self.stack_scope,
"BatchJobQueueArn",
description="Job Queue created within the cluster.",
value=self._job_queue.ref,
)
CfnOutput(
self.stack_scope,
"BatchJobDefinitionArn",
description="Job Definition for serial submission.",
value=self._job_definition_serial.ref,
)
CfnOutput(
self.stack_scope,
"ECRRepoName",
description="Name of the ECR repository where docker images used by AWS Batch are located.",
value=self._docker_images_repo.ref,
)
CfnOutput(
self.stack_scope,
"CodeBuildDockerImageBuilderProject",
description="CodeBuild project used to bake docker images.",
value=self._code_build_image_builder_project.ref,
)
CfnOutput(
self.stack_scope,
"BatchJobDefinitionMnpArn",
description="Job Definition for MNP submission.",
value=self._job_definition_mnp.ref,
)
CfnOutput(
self.stack_scope,
"BatchUserRole",
description="Role to be used to contact AWS Batch resources created within the cluster.",
value=self._batch_user_role.ref,
)
|
"""
Functions to do with masks and mixing matrices.
"""
import copy
import time
import warnings
import healpy as hp
import matplotlib.cm
import matplotlib.pyplot as plt
import numpy as np
import pymaster as nmt
def generate_mask(wmap_mask_path, nside, target_fsky, mask_save_path):
"""
Generate a Stage-IV-like mask by manipulating the WMAP temperature mask and then adding random holes until the
target sky fraction is reached.
Args:
wmap_mask_path (str): Path to the WMAP temperature mask fits file.
nside (int): HEALPix resolution to use.
target_fsky (float): Sky fraction to achieve. Holes will be added at random to reach this value.
msk_save_path (str): Path to save the final mask as a fits file.
"""
print('Loading')
input_mask = hp.fitsfunc.read_map(wmap_mask_path, dtype=float, verbose=False)
assert input_mask.shape == (hp.pixelfunc.nside2npix(nside), )
assert np.amin(input_mask) == 0
assert np.amax(input_mask) == 1
print('Input mask fsky =', np.mean(input_mask))
print('Rotating')
rotated_mask = hp.rotator.Rotator(coord=['E', 'G']).rotate_map_alms(input_mask)
print('Rotated mask fsky =', np.mean(rotated_mask))
# Clip back to 0-1
rotated_mask = np.clip(rotated_mask, 0, 1)
assert np.amin(rotated_mask) == 0
assert np.amax(rotated_mask) == 1
print('Multiplying')
dual_mask = input_mask * rotated_mask
assert np.amin(dual_mask) == 0
assert np.amax(dual_mask) == 1
print('Dual mask fsky =', np.mean(dual_mask))
# Iteratively take out holes until the desired fsky is reached
mask = dual_mask
rng = np.random.default_rng()
npix = hp.pixelfunc.nside2npix(nside)
while np.mean(mask) > target_fsky:
# Select non-zero pixel as the centre of the hole
have_hole_centre = False
while not have_hole_centre:
hole_centre = rng.integers(npix)
if mask[hole_centre] > 0:
have_hole_centre = True
# Mask the centre
mask[hole_centre] = 0
# Mask the immediate neighbours, then their neighbours with a 50% chance, etc.
neighbours = hole_centre
hole_size = 0
while hole_size < 6: # max size
hole_size += 1
neighbours = hp.pixelfunc.get_all_neighbours(nside, neighbours)
mask[neighbours] = 0
if rng.integers(2) > 0:
break
print('fsky = ', np.mean(mask), end='\r')
print()
# Final checks
assert np.all(np.isfinite(mask))
assert np.amin(mask) == 0
assert np.amax(mask) == 1
# Plot
with warnings.catch_warnings():
warnings.simplefilter('ignore') # ignore mollview warnings
hp.visufunc.mollview(mask)
plt.show()
# Save to disk
hp.fitsfunc.write_map(mask_save_path, mask, dtype=float)
print('Saved ' + mask_save_path)
def plot_mask(mask_path, save_path=None):
"""
Plot Mollweide projection of a mask, with colour bar.
Args:
mask_path (str): Path to mask FITS file.
save_path (str, optional): Path to save plot to (default None). If None, plot is displayed.
"""
# Load mask
mask = hp.fitsfunc.read_map(mask_path, dtype=float, verbose=False)
# Calculate Mollweide projection
with warnings.catch_warnings():
warnings.simplefilter('ignore') # mollview's plotting code creates warnings
mask_proj = hp.visufunc.mollview(mask, return_projected_map=True)
plt.close()
# Plot
plt.rcParams.update({'font.size': 7})
cmap = copy.copy(matplotlib.cm.get_cmap('cividis'))
cmap.set_bad(color='white')
plt.imshow(mask_proj, origin='lower', cmap=cmap, interpolation='none')
plt.gca().axis('off')
plt.colorbar(shrink=0.4, aspect=10)
# Save or show
if save_path is not None:
plt.savefig(save_path, bbox_inches='tight')
print('Saved ' + save_path)
else:
plt.show()
def get_3x2pt_mixmats(mask_path, nside, lmin, lmax_mix, lmax_out, save_path):
"""
Calculate all 3x2pt mixing matrices from a mask using NaMaster, and save to disk in a single file.
Args:
mask_path (str): Path to mask FITS file. If None, full sky is assumed, in which case the mixing matrices should
be diagonal.
nside (int): HEALPix resolution to use.
lmin (int): Minimum l to include in mixing matrices.
lmax_mix (int): Maximum l to include in input to mixing matrices.
lmax_out (int): Maximum l to include in output from mixing matrices.
save_path (str): Path to save output, as a single numpy .npz file containing all mixing matrices.
"""
# Load and rescale mask, and calculate fsky
if mask_path is not None:
print('Loading and rescaling mask')
mask = hp.pixelfunc.ud_grade(hp.read_map(mask_path, dtype=float), nside)
assert np.amin(mask) == 0
assert np.amax(mask) == 1
else:
print('Full sky')
mask = np.ones(hp.pixelfunc.nside2npix(nside))
assert np.all(np.isfinite(mask))
fsky = np.mean(mask)
print(f'fsky = {fsky:.3f}')
# Create NaMaster binning scheme as individual Cls
print('Creating binning scheme')
bins = nmt.NmtBin.from_lmax_linear(lmax_mix, 1)
# Calculate mixing matrices for spin 0-0, 0-2 (equivalent to 2-0), and 2-2
field_spin0 = nmt.NmtField(mask, None, spin=0, lite=True)
field_spin2 = nmt.NmtField(mask, None, spin=2, lite=True)
workspace_spin00 = nmt.NmtWorkspace()
print(f'Calculating mixing matrix 1 / 3 at {time.strftime('%c')}')
workspace_spin00.compute_coupling_matrix(field_spin0, field_spin0, bins)
workspace_spin02 = nmt.NmtWorkspace()
print(f'Calculating mixing matrix 2 / 3 at {time.strftime('%c')}')
workspace_spin02.compute_coupling_matrix(field_spin0, field_spin2, bins)
workspace_spin22 = nmt.NmtWorkspace()
print(f'Calculating mixing matrix 3 / 3 at {time.strftime('%c')}')
workspace_spin22.compute_coupling_matrix(field_spin2, field_spin2, bins)
# Extract the relevant mixing matrices
print('Extracting mixing matrices')
# For 0-0 there is only a single mixing matrix
mixmats_spin00 = workspace_spin00.get_coupling_matrix()
mixmat_nn_to_nn = mixmats_spin00
# For 0-2 they are arranged NE->NE, NB->NE // NE->NB NB->NB, per l, so select every other row and column
mixmats_spin02 = workspace_spin02.get_coupling_matrix()
mixmat_ne_to_ne = mixmats_spin02[::2, ::2]
# For 2-2 there are 4x4 elements per l, ordered EE, EB, BE, BB. We only need EE->EE and BB->EE,
# so select every 4th row and the 1st and 4th columns from each block
mixmats_spin22 = workspace_spin22.get_coupling_matrix()
mixmat_ee_to_ee = mixmats_spin22[::4, ::4]
mixmat_bb_to_ee = mixmats_spin22[::4, 3::4]
# Check everything has the correct shape
mixmat_shape = (lmax_mix + 1, lmax_mix + 1)
assert mixmat_nn_to_nn.shape == mixmat_shape
assert mixmat_ne_to_ne.shape == mixmat_shape
assert mixmat_ee_to_ee.shape == mixmat_shape
assert mixmat_bb_to_ee.shape == mixmat_shape
# Trim to required output range
mixmat_nn_to_nn = mixmat_nn_to_nn[lmin:(lmax_out + 1), lmin:]
mixmat_ne_to_ne = mixmat_ne_to_ne[lmin:(lmax_out + 1), lmin:]
mixmat_ee_to_ee = mixmat_ee_to_ee[lmin:(lmax_out + 1), lmin:]
mixmat_bb_to_ee = mixmat_bb_to_ee[lmin:(lmax_out + 1), lmin:]
# Do some final checks
n_ell_out = lmax_out - lmin + 1
n_ell_in = lmax_mix - lmin + 1
mixmat_out_shape = (n_ell_out, n_ell_in)
assert mixmat_nn_to_nn.shape == mixmat_out_shape
assert mixmat_ne_to_ne.shape == mixmat_out_shape
assert mixmat_ee_to_ee.shape == mixmat_out_shape
assert mixmat_bb_to_ee.shape == mixmat_out_shape
assert np.all(np.isfinite(mixmat_nn_to_nn))
assert np.all(np.isfinite(mixmat_ne_to_ne))
assert np.all(np.isfinite(mixmat_ee_to_ee))
assert np.all(np.isfinite(mixmat_bb_to_ee))
# Save to disk
header = (f'Mixing matrices. Output from {__file__}.get_3x2pt_mixmats for mask_path = {mask_path}, '
f'nside = {nside}, lmin = {lmin}, lmax_mix = {lmax_mix}, lmax_out = {lmax_out}, at {time.strftime('%c')}')
np.savez_compressed(save_path, mixmat_nn_to_nn=mixmat_nn_to_nn, mixmat_ne_to_ne=mixmat_ne_to_ne,
mixmat_ee_to_ee=mixmat_ee_to_ee, mixmat_bb_to_ee=mixmat_bb_to_ee, header=header)
print('Saved ' + save_path)
| """
Functions to do with masks and mixing matrices.
"""
import copy
import time
import warnings
import healpy as hp
import matplotlib.cm
import matplotlib.pyplot as plt
import numpy as np
import pymaster as nmt
def generate_mask(wmap_mask_path, nside, target_fsky, mask_save_path):
"""
Generate a Stage-IV-like mask by manipulating the WMAP temperature mask and then adding random holes until the
target sky fraction is reached.
Args:
wmap_mask_path (str): Path to the WMAP temperature mask fits file.
nside (int): HEALPix resolution to use.
target_fsky (float): Sky fraction to achieve. Holes will be added at random to reach this value.
msk_save_path (str): Path to save the final mask as a fits file.
"""
print('Loading')
input_mask = hp.fitsfunc.read_map(wmap_mask_path, dtype=float, verbose=False)
assert input_mask.shape == (hp.pixelfunc.nside2npix(nside), )
assert np.amin(input_mask) == 0
assert np.amax(input_mask) == 1
print('Input mask fsky =', np.mean(input_mask))
print('Rotating')
rotated_mask = hp.rotator.Rotator(coord=['E', 'G']).rotate_map_alms(input_mask)
print('Rotated mask fsky =', np.mean(rotated_mask))
# Clip back to 0-1
rotated_mask = np.clip(rotated_mask, 0, 1)
assert np.amin(rotated_mask) == 0
assert np.amax(rotated_mask) == 1
print('Multiplying')
dual_mask = input_mask * rotated_mask
assert np.amin(dual_mask) == 0
assert np.amax(dual_mask) == 1
print('Dual mask fsky =', np.mean(dual_mask))
# Iteratively take out holes until the desired fsky is reached
mask = dual_mask
rng = np.random.default_rng()
npix = hp.pixelfunc.nside2npix(nside)
while np.mean(mask) > target_fsky:
# Select non-zero pixel as the centre of the hole
have_hole_centre = False
while not have_hole_centre:
hole_centre = rng.integers(npix)
if mask[hole_centre] > 0:
have_hole_centre = True
# Mask the centre
mask[hole_centre] = 0
# Mask the immediate neighbours, then their neighbours with a 50% chance, etc.
neighbours = hole_centre
hole_size = 0
while hole_size < 6: # max size
hole_size += 1
neighbours = hp.pixelfunc.get_all_neighbours(nside, neighbours)
mask[neighbours] = 0
if rng.integers(2) > 0:
break
print('fsky = ', np.mean(mask), end='\r')
print()
# Final checks
assert np.all(np.isfinite(mask))
assert np.amin(mask) == 0
assert np.amax(mask) == 1
# Plot
with warnings.catch_warnings():
warnings.simplefilter('ignore') # ignore mollview warnings
hp.visufunc.mollview(mask)
plt.show()
# Save to disk
hp.fitsfunc.write_map(mask_save_path, mask, dtype=float)
print('Saved ' + mask_save_path)
def plot_mask(mask_path, save_path=None):
"""
Plot Mollweide projection of a mask, with colour bar.
Args:
mask_path (str): Path to mask FITS file.
save_path (str, optional): Path to save plot to (default None). If None, plot is displayed.
"""
# Load mask
mask = hp.fitsfunc.read_map(mask_path, dtype=float, verbose=False)
# Calculate Mollweide projection
with warnings.catch_warnings():
warnings.simplefilter('ignore') # mollview's plotting code creates warnings
mask_proj = hp.visufunc.mollview(mask, return_projected_map=True)
plt.close()
# Plot
plt.rcParams.update({'font.size': 7})
cmap = copy.copy(matplotlib.cm.get_cmap('cividis'))
cmap.set_bad(color='white')
plt.imshow(mask_proj, origin='lower', cmap=cmap, interpolation='none')
plt.gca().axis('off')
plt.colorbar(shrink=0.4, aspect=10)
# Save or show
if save_path is not None:
plt.savefig(save_path, bbox_inches='tight')
print('Saved ' + save_path)
else:
plt.show()
def get_3x2pt_mixmats(mask_path, nside, lmin, lmax_mix, lmax_out, save_path):
"""
Calculate all 3x2pt mixing matrices from a mask using NaMaster, and save to disk in a single file.
Args:
mask_path (str): Path to mask FITS file. If None, full sky is assumed, in which case the mixing matrices should
be diagonal.
nside (int): HEALPix resolution to use.
lmin (int): Minimum l to include in mixing matrices.
lmax_mix (int): Maximum l to include in input to mixing matrices.
lmax_out (int): Maximum l to include in output from mixing matrices.
save_path (str): Path to save output, as a single numpy .npz file containing all mixing matrices.
"""
# Load and rescale mask, and calculate fsky
if mask_path is not None:
print('Loading and rescaling mask')
mask = hp.pixelfunc.ud_grade(hp.read_map(mask_path, dtype=float), nside)
assert np.amin(mask) == 0
assert np.amax(mask) == 1
else:
print('Full sky')
mask = np.ones(hp.pixelfunc.nside2npix(nside))
assert np.all(np.isfinite(mask))
fsky = np.mean(mask)
print(f'fsky = {fsky:.3f}')
# Create NaMaster binning scheme as individual Cls
print('Creating binning scheme')
bins = nmt.NmtBin.from_lmax_linear(lmax_mix, 1)
# Calculate mixing matrices for spin 0-0, 0-2 (equivalent to 2-0), and 2-2
field_spin0 = nmt.NmtField(mask, None, spin=0, lite=True)
field_spin2 = nmt.NmtField(mask, None, spin=2, lite=True)
workspace_spin00 = nmt.NmtWorkspace()
print(f'Calculating mixing matrix 1 / 3 at {time.strftime("%c")}')
workspace_spin00.compute_coupling_matrix(field_spin0, field_spin0, bins)
workspace_spin02 = nmt.NmtWorkspace()
print(f'Calculating mixing matrix 2 / 3 at {time.strftime("%c")}')
workspace_spin02.compute_coupling_matrix(field_spin0, field_spin2, bins)
workspace_spin22 = nmt.NmtWorkspace()
print(f'Calculating mixing matrix 3 / 3 at {time.strftime("%c")}')
workspace_spin22.compute_coupling_matrix(field_spin2, field_spin2, bins)
# Extract the relevant mixing matrices
print('Extracting mixing matrices')
# For 0-0 there is only a single mixing matrix
mixmats_spin00 = workspace_spin00.get_coupling_matrix()
mixmat_nn_to_nn = mixmats_spin00
# For 0-2 they are arranged NE->NE, NB->NE // NE->NB NB->NB, per l, so select every other row and column
mixmats_spin02 = workspace_spin02.get_coupling_matrix()
mixmat_ne_to_ne = mixmats_spin02[::2, ::2]
# For 2-2 there are 4x4 elements per l, ordered EE, EB, BE, BB. We only need EE->EE and BB->EE,
# so select every 4th row and the 1st and 4th columns from each block
mixmats_spin22 = workspace_spin22.get_coupling_matrix()
mixmat_ee_to_ee = mixmats_spin22[::4, ::4]
mixmat_bb_to_ee = mixmats_spin22[::4, 3::4]
# Check everything has the correct shape
mixmat_shape = (lmax_mix + 1, lmax_mix + 1)
assert mixmat_nn_to_nn.shape == mixmat_shape
assert mixmat_ne_to_ne.shape == mixmat_shape
assert mixmat_ee_to_ee.shape == mixmat_shape
assert mixmat_bb_to_ee.shape == mixmat_shape
# Trim to required output range
mixmat_nn_to_nn = mixmat_nn_to_nn[lmin:(lmax_out + 1), lmin:]
mixmat_ne_to_ne = mixmat_ne_to_ne[lmin:(lmax_out + 1), lmin:]
mixmat_ee_to_ee = mixmat_ee_to_ee[lmin:(lmax_out + 1), lmin:]
mixmat_bb_to_ee = mixmat_bb_to_ee[lmin:(lmax_out + 1), lmin:]
# Do some final checks
n_ell_out = lmax_out - lmin + 1
n_ell_in = lmax_mix - lmin + 1
mixmat_out_shape = (n_ell_out, n_ell_in)
assert mixmat_nn_to_nn.shape == mixmat_out_shape
assert mixmat_ne_to_ne.shape == mixmat_out_shape
assert mixmat_ee_to_ee.shape == mixmat_out_shape
assert mixmat_bb_to_ee.shape == mixmat_out_shape
assert np.all(np.isfinite(mixmat_nn_to_nn))
assert np.all(np.isfinite(mixmat_ne_to_ne))
assert np.all(np.isfinite(mixmat_ee_to_ee))
assert np.all(np.isfinite(mixmat_bb_to_ee))
# Save to disk
header = (f'Mixing matrices. Output from {__file__}.get_3x2pt_mixmats for mask_path = {mask_path}, '
f'nside = {nside}, lmin = {lmin}, lmax_mix = {lmax_mix}, lmax_out = {lmax_out}, at {time.strftime("%c")}')
np.savez_compressed(save_path, mixmat_nn_to_nn=mixmat_nn_to_nn, mixmat_ne_to_ne=mixmat_ne_to_ne,
mixmat_ee_to_ee=mixmat_ee_to_ee, mixmat_bb_to_ee=mixmat_bb_to_ee, header=header)
print('Saved ' + save_path)
|
import copy
import json
import os
import pytest
import tempfile
from contextlib import contextmanager
from pathlib import Path
from unittest import mock
from requests import HTTPError
from RPA.Robocorp.WorkItems import (
BaseAdapter,
EmptyQueue,
FileAdapter,
RobocorpAdapter,
State,
WorkItems,
)
from RPA.Robocorp.utils import RequestsHTTPError
VARIABLES_FIRST = {"username": "testguy", "address": "guy@company.com"}
VARIABLES_SECOND = {"username": "another", "address": "dude@company.com"}
VALID_DATA = {
"workitem-id-first": VARIABLES_FIRST,
"workitem-id-second": VARIABLES_SECOND,
"workitem-id-custom": [1, 2, 3],
}
VALID_FILES = {
"workitem-id-first": {
"file1.txt": b"data1",
"file2.txt": b"data2",
"file3.png": b"data3",
},
"workitem-id-second": {},
"workitem-id-custom": {},
}
ITEMS_JSON = [{"payload": {"a-key": "a-value"}, "files": {"a-file": "file.txt"}}]
@contextmanager
def temp_filename(content=None):
"""Create temporary file and return filename, delete file afterwards.
Needs to close file handle, since Windows won't allow multiple
open handles to the same file.
"""
with tempfile.NamedTemporaryFile(delete=False) as fd:
path = fd.name
if content:
fd.write(content)
try:
yield path
finally:
os.unlink(path)
def is_equal_files(lhs, rhs):
lhs = Path(lhs).resolve()
rhs = Path(rhs).resolve()
return lhs == rhs
class MockAdapter(BaseAdapter):
DATA = {}
FILES = {}
INDEX = 0
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._data_keys = []
self.releases = []
@classmethod
def validate(cls, item, key, val):
data = cls.DATA.get(item.id)
assert data is not None
assert data[key] == val
@property
def data_keys(self):
if not self._data_keys:
self._data_keys = list(self.DATA.keys())
return self._data_keys
def reserve_input(self) -> str:
if self.INDEX >= len(self.data_keys):
raise EmptyQueue("No work items in the input queue")
try:
return self.data_keys[self.INDEX]
finally:
self.INDEX += 1
def release_input(self, item_id: str, state: State):
self.releases.append((item_id, state)) # purely for testing purposes
def create_output(self, parent_id, payload=None) -> str:
raise NotImplementedError
def load_payload(self, item_id):
return self.DATA[item_id]
def save_payload(self, item_id, payload):
self.DATA[item_id] = payload
def list_files(self, item_id):
return self.FILES[item_id]
def get_file(self, item_id, name):
return self.FILES[item_id][name]
def add_file(self, item_id, name, *, original_name, content):
self.FILES[item_id][name] = content
def remove_file(self, item_id, name):
del self.FILES[item_id][name]
class TestLibrary:
@pytest.fixture
def adapter(self):
MockAdapter.DATA = copy.deepcopy(VALID_DATA)
MockAdapter.FILES = copy.deepcopy(VALID_FILES)
try:
yield MockAdapter
finally:
MockAdapter.DATA = {}
MockAdapter.FILES = {}
MockAdapter.INDEX = 0
@pytest.fixture
def library(self, adapter):
yield WorkItems(default_adapter=adapter)
def test_autoload(self, library):
# Called by Robot Framework listener
library._start_suite(None, None)
# Work item loaded using env variables
env = library.current
assert env is not None
assert env.payload == VARIABLES_FIRST
def test_autoload_disable(self, adapter):
library = WorkItems(default_adapter=adapter, autoload=False)
# Called by Robot Framework listener
library._start_suite(None, None)
assert library._current is None
def test_keyword_get_input_work_item(self, library):
first = library.get_input_work_item()
assert first.payload == VARIABLES_FIRST
assert first == library.current
second = library.get_input_work_item()
assert second.payload == VARIABLES_SECOND
assert second == library.current
def test_keyword_save_work_item(self, library):
item = library.get_input_work_item()
for key, value in VARIABLES_FIRST.items():
MockAdapter.validate(item, key, value)
modified = {"username": "changed", "address": "dude@company.com"}
item.payload = modified
library.save_work_item()
for key, value in modified.items():
MockAdapter.validate(item, key, value)
def test_no_active_item(self):
library = WorkItems(default_adapter=MockAdapter)
with pytest.raises(RuntimeError) as err:
library.save_work_item()
assert str(err.value) == "No active work item"
def test_list_variables(self, library):
library.get_input_work_item()
names = library.list_work_item_variables()
assert len(names) == 2
assert "username" in names
assert "address" in names
def test_get_variables(self, library):
library.get_input_work_item()
value = library.get_work_item_variable("username")
assert value == "testguy"
with pytest.raises(KeyError):
library.get_work_item_variable("notexist")
def test_get_variables_default(self, library):
library.get_input_work_item()
value = library.get_work_item_variable("username", default="doesntmatter")
assert value == "testguy"
value = library.get_work_item_variable("notexist", default="doesmatter")
assert value == "doesmatter"
def test_delete_variables(self, library):
library.get_input_work_item()
assert "username" in library.list_work_item_variables()
library.delete_work_item_variables("username")
assert "username" not in library.list_work_item_variables()
library.delete_work_item_variables("doesntexist")
with pytest.raises(KeyError):
library.delete_work_item_variables("doesntexist", force=False)
def test_delete_variables_multiple(self, library):
library.get_input_work_item()
assert "username" in library.list_work_item_variables()
assert len(library.current["variables"]) == 2
library.delete_work_item_variables("username")
assert "username" not in library.list_work_item_variables()
assert len(library.current["variables"]) == 1
def test_delete_variables_multiple(self, library):
library.get_input_work_item()
names = library.list_work_item_variables()
assert "username" in names
assert "address" in names
assert len(names) == 2
library.delete_work_item_variables("username", "address")
names = library.list_work_item_variables()
assert "username" not in names
assert "username" not in names
assert len(names) == 0
def test_delete_variables_unknown(self, library):
library.get_input_work_item()
assert len(library.list_work_item_variables()) == 2
library.delete_work_item_variables("unknown-variable")
assert len(library.list_work_item_variables()) == 2
with pytest.raises(KeyError):
library.delete_work_item_variables("unknown-variable", force=False)
assert len(library.list_work_item_variables()) == 2
def test_raw_payload(self, library):
_ = library.get_input_work_item()
_ = library.get_input_work_item()
item = library.get_input_work_item()
payload = library.get_work_item_payload()
assert payload == [1, 2, 3]
library.set_work_item_payload({"output": 0xBEEF})
library.save_work_item()
MockAdapter.validate(item, "output", 0xBEEF)
def test_list_files(self, library):
library.get_input_work_item()
files = library.list_work_item_files()
assert files == ["file1.txt", "file2.txt", "file3.png"]
def test_get_file(self, library):
library.get_input_work_item()
with temp_filename() as path:
result = library.get_work_item_file("file2.txt", path)
with open(result) as fd:
data = fd.read()
assert is_equal_files(result, path)
assert data == "data2"
def test_get_file_notexist(self, library):
library.get_input_work_item()
with pytest.raises(FileNotFoundError):
library.get_work_item_file("file5.txt")
def test_add_file(self, library):
item = library.get_input_work_item()
with temp_filename(b"some-input-content") as path:
library.add_work_item_file(path, "file4.txt")
files = library.list_work_item_files()
assert files == ["file1.txt", "file2.txt", "file3.png", "file4.txt"]
assert "file4.txt" not in MockAdapter.FILES[item.id]
library.save_work_item()
assert MockAdapter.FILES[item.id]["file4.txt"] == b"some-input-content"
def test_add_file_duplicate(self, library):
item = library.get_input_work_item()
def verify_files():
files = library.list_work_item_files()
assert files == ["file1.txt", "file2.txt", "file3.png", "file4.txt"]
with temp_filename(b"some-input-content") as path:
library.add_work_item_file(path, "file4.txt")
assert "file4.txt" not in MockAdapter.FILES[item.id]
verify_files()
# Add duplicate for unsaved item
library.add_work_item_file(path, "file4.txt")
assert "file4.txt" not in MockAdapter.FILES[item.id]
verify_files()
library.save_work_item()
assert MockAdapter.FILES[item.id]["file4.txt"] == b"some-input-content"
verify_files()
# Add duplicate for saved item
library.add_work_item_file(path, "file4.txt")
verify_files()
library.save_work_item()
verify_files()
def test_add_file_notexist(self, library):
library.get_input_work_item()
with pytest.raises(FileNotFoundError):
library.add_work_item_file("file5.txt", "doesnt-matter")
def test_remove_file(self, library):
item = library.get_input_work_item()
library.remove_work_item_file("file2.txt")
files = library.list_work_item_files()
assert files == ["file1.txt", "file3.png"]
assert "file2.txt" in MockAdapter.FILES[item.id]
library.save_work_item()
assert "file2.txt" not in MockAdapter.FILES[item.id]
def test_remove_file_notexist(self, library):
library.get_input_work_item()
library.remove_work_item_file("file5.txt")
with pytest.raises(FileNotFoundError):
library.remove_work_item_file("file5.txt", missing_ok=False)
def test_get_file_pattern(self, library):
library.get_input_work_item()
with tempfile.TemporaryDirectory() as outdir:
file1 = os.path.join(outdir, "file1.txt")
file2 = os.path.join(outdir, "file2.txt")
paths = library.get_work_item_files("*.txt", outdir)
assert is_equal_files(paths[0], file1)
assert is_equal_files(paths[1], file2)
assert os.path.exists(file1)
assert os.path.exists(file2)
def test_remove_file_pattern(self, library):
item = library.get_input_work_item()
library.remove_work_item_files("*.txt")
files = library.list_work_item_files()
assert files == ["file3.png"]
assert list(MockAdapter.FILES[item.id]) == [
"file1.txt",
"file2.txt",
"file3.png",
]
library.save_work_item()
files = library.list_work_item_files()
assert files == ["file3.png"]
assert list(MockAdapter.FILES[item.id]) == ["file3.png"]
def test_clear_work_item(self, library):
library.get_input_work_item()
library.clear_work_item()
library.save_work_item()
assert library.get_work_item_payload() == {}
assert library.list_work_item_files() == []
def test_get_file_unsaved(self, library):
library.get_input_work_item()
with temp_filename(b"some-input-content") as path:
library.add_work_item_file(path, "file4.txt")
files = library.list_work_item_files()
assert files == ["file1.txt", "file2.txt", "file3.png", "file4.txt"]
assert "file4.txt" not in MockAdapter.FILES
with tempfile.TemporaryDirectory() as outdir:
names = ["file1.txt", "file2.txt", "file4.txt"]
result = library.get_work_item_files("*.txt", outdir)
expected = [os.path.join(outdir, name) for name in names]
for lhs, rhs in zip(result, expected):
assert is_equal_files(lhs, rhs)
with open(result[-1]) as fd:
assert fd.read() == "some-input-content"
def test_get_file_unsaved_no_copy(self, library):
library.get_input_work_item()
with tempfile.TemporaryDirectory() as outdir:
path = os.path.join(outdir, "nomove.txt")
with open(path, "w") as fd:
fd.write("my content")
mtime = os.path.getmtime(path)
library.add_work_item_file(path)
files = library.list_work_item_files()
assert files == ["file1.txt", "file2.txt", "file3.png", "nomove.txt"]
paths = library.get_work_item_files("*.txt", outdir)
assert is_equal_files(paths[-1], path)
assert os.path.getmtime(path) == mtime
def test_get_file_unsaved_relative(self, library):
library.get_input_work_item()
with tempfile.TemporaryDirectory() as outdir:
curdir = os.getcwd()
try:
os.chdir(outdir)
with open("nomove.txt", "w") as fd:
fd.write("my content")
mtime = os.path.getmtime("nomove.txt")
library.add_work_item_file(os.path.join(outdir, "nomove.txt"))
files = library.list_work_item_files()
assert files == ["file1.txt", "file2.txt", "file3.png", "nomove.txt"]
paths = library.get_work_item_files("*.txt")
assert is_equal_files(paths[-1], os.path.join(outdir, "nomove.txt"))
assert os.path.getmtime("nomove.txt") == mtime
finally:
os.chdir(curdir)
def test_get_file_no_matches(self, library):
library.get_input_work_item()
with tempfile.TemporaryDirectory() as outdir:
paths = library.get_work_item_files("*.pdf", outdir)
assert len(paths) == 0
def test_create_output_work_item(self, library):
input_item = library.get_input_work_item()
output_item = library.create_output_work_item()
assert output_item.id is None
assert output_item.parent_id == input_item.id
def test_create_output_work_item_no_input(self, library):
with pytest.raises(RuntimeError):
library.create_output_work_item()
def test_custom_root(self, adapter):
library = WorkItems(default_adapter=adapter, root="vars")
item = library.get_input_work_item()
variables = library.get_work_item_variables()
assert variables == {}
library.set_work_item_variables(cool="beans", yeah="boi")
assert item.payload == {
**VARIABLES_FIRST,
"vars": {"cool": "beans", "yeah": "boi"},
}
@pytest.mark.parametrize("limit", [0, 1, 2, 3, 4]) # no, existing and over limit
def test_iter_work_items(self, library, limit):
usernames = []
def func(a, b, r=3):
assert a + b == r
# Collects the "username" variable from the payload if provided and returns
# True if found, False otherwise.
payload = library.get_work_item_payload()
if not isinstance(payload, dict):
return False
username = payload.get("username")
if username:
usernames.append(username)
return username is not None
library.get_input_work_item()
results = library.for_each_input_work_item(func, 1, 2, _limit=limit, r=3)
expected_usernames = ["testguy", "another"]
expected_results = [True, True, False]
if limit:
expected_usernames = expected_usernames[:limit]
expected_results = expected_results[:limit]
assert usernames == expected_usernames
assert results == expected_results
def test_release_work_item(self, library):
library.get_input_work_item()
library.release_input_work_item("FAILED") # intentionally provide a string
assert library.current.state == State.FAILED
assert library.adapter.releases == [("workitem-id-first", State.FAILED)]
def test_auto_release_work_item(self, library):
library.get_input_work_item()
library.get_input_work_item() # this automatically sets the state of the last
assert library.current.state is None # because the previous one has a state
assert library.adapter.releases == [("workitem-id-first", State.DONE)]
class TestFileAdapter:
"""Tests the local dev env `FileAdapter` on Work Items."""
@contextmanager
def _input_work_items(self):
with tempfile.TemporaryDirectory() as datadir:
items_in = os.path.join(datadir, "items.json")
with open(items_in, "w") as fd:
json.dump(ITEMS_JSON, fd)
with open(os.path.join(datadir, "file.txt"), "w") as fd:
fd.write("some mock content")
output_dir = os.path.join(datadir, "output_dir")
os.makedirs(output_dir)
items_out = os.path.join(output_dir, "items-out.json")
yield items_in, items_out
@pytest.fixture(
params=[
("RPA_WORKITEMS_PATH", "N/A"),
("RPA_INPUT_WORKITEM_PATH", "RPA_OUTPUT_WORKITEM_PATH"),
]
)
def adapter(self, monkeypatch, request):
with self._input_work_items() as (items_in, items_out):
monkeypatch.setenv(request.param[0], items_in)
monkeypatch.setenv(request.param[1], items_out)
yield FileAdapter()
@pytest.fixture
def empty_adapter(self):
# No work items i/o files nor envs set.
return FileAdapter()
def test_load_data(self, adapter):
item_id = adapter.reserve_input()
data = adapter.load_payload(item_id)
assert data == {"a-key": "a-value"}
def test_list_files(self, adapter):
item_id = adapter.reserve_input()
files = adapter.list_files(item_id)
assert files == ["a-file"]
def test_get_file(self, adapter):
item_id = adapter.reserve_input()
content = adapter.get_file(item_id, "a-file")
assert content == b"some mock content"
def test_add_file(self, adapter):
item_id = adapter.reserve_input()
adapter.add_file(
item_id,
"secondfile.txt",
original_name="secondfile2.txt",
content=b"somedata",
)
assert adapter.inputs[0]["files"]["secondfile.txt"] == "secondfile2.txt"
assert os.path.isfile(Path(adapter.input_path).parent / "secondfile2.txt")
def test_save_data_input(self, adapter):
item_id = adapter.reserve_input()
adapter.save_payload(item_id, {"key": "value"})
with open(adapter.input_path) as fd:
data = json.load(fd)
assert data == [
{"payload": {"key": "value"}, "files": {"a-file": "file.txt"}}
]
def test_save_data_output(self, adapter):
item_id = adapter.create_output("0", {})
adapter.save_payload(item_id, {"key": "value"})
output = os.getenv("RPA_OUTPUT_WORKITEM_PATH")
if output:
assert "output_dir" in output # checks automatic dir creation
else:
output = Path(adapter.input_path).with_suffix(".output.json")
assert os.path.isfile(output)
with open(output) as fd:
data = json.load(fd)
assert data == [{"payload": {"key": "value"}, "files": {}}]
def test_missing_file(self, monkeypatch):
monkeypatch.setenv("RPA_WORKITEMS_PATH", "not-exist.json")
adapter = FileAdapter()
assert adapter.inputs == [{"payload": {}}]
def test_empty_queue(self, monkeypatch):
with tempfile.TemporaryDirectory() as datadir:
items = os.path.join(datadir, "items.json")
with open(items, "w") as fd:
json.dump([], fd)
monkeypatch.setenv("RPA_WORKITEMS_PATH", items)
adapter = FileAdapter()
assert adapter.inputs == [{"payload": {}}]
def test_malformed_queue(self, monkeypatch):
with tempfile.TemporaryDirectory() as datadir:
items = os.path.join(datadir, "items.json")
with open(items, "w") as fd:
json.dump(["not-an-item"], fd)
monkeypatch.setenv("RPA_WORKITEMS_PATH", items)
adapter = FileAdapter()
assert adapter.inputs == [{"payload": {}}]
def test_without_items_paths(self, empty_adapter):
assert empty_adapter.inputs == [{"payload": {}}]
# Can't save inputs nor outputs since there's no path defined for them.
with pytest.raises(RuntimeError):
empty_adapter.save_payload("0", {"input": "value"})
with pytest.raises(RuntimeError):
_ = empty_adapter.output_path
with pytest.raises(RuntimeError):
empty_adapter.create_output("1", {"var": "some-value"})
class TestRobocorpAdapter:
"""Test control room API calls and retrying behaviour."""
ENV = {
"RC_WORKSPACE_ID": "1",
"RC_PROCESS_RUN_ID": "2",
"RC_ACTIVITY_RUN_ID": "3",
"RC_WORKITEM_ID": "4",
"RC_API_WORKITEM_HOST": "https://api.workitem.com",
"RC_API_WORKITEM_TOKEN": "workitem-token",
"RC_API_PROCESS_HOST": "https://api.process.com",
"RC_API_PROCESS_TOKEN": "process-token",
"RC_PROCESS_ID": "5",
}
HEADERS_WORKITEM = {
"Authorization": f"Bearer {ENV["RC_API_WORKITEM_TOKEN"]}",
"Content-Type": "application/json",
}
HEADERS_PROCESS = {
"Authorization": f"Bearer {ENV["RC_API_PROCESS_TOKEN"]}",
"Content-Type": "application/json",
}
@pytest.fixture
def adapter(self, monkeypatch):
for name, value in self.ENV.items():
monkeypatch.setenv(name, value)
with mock.patch("RPA.Robocorp.utils.requests.get") as mock_get, mock.patch(
"RPA.Robocorp.utils.requests.post"
) as mock_post, mock.patch(
"RPA.Robocorp.utils.requests.put"
) as mock_put, mock.patch(
"RPA.Robocorp.utils.requests.delete"
) as mock_delete, mock.patch(
"time.sleep", return_value=None
):
self.mock_get = mock_get
self.mock_post = mock_post
self.mock_put = mock_put
self.mock_delete = mock_delete
yield RobocorpAdapter()
def test_reserve_input(self, adapter):
initial_item_id = adapter.reserve_input()
assert initial_item_id == self.ENV["RC_WORKITEM_ID"]
self.mock_post.return_value.json.return_value = {"workItemId": "44"}
reserved_item_id = adapter.reserve_input()
assert reserved_item_id == "44"
url = "https://api.process.com/process-v1/workspaces/1/processes/5/runs/2/robotRuns/3/reserve-next-work-item"
self.mock_post.assert_called_once_with(url, headers=self.HEADERS_PROCESS)
def test_release_input(self, adapter):
item_id = "26"
adapter.release_input(item_id, State.FAILED)
url = "https://api.process.com/process-v1/workspaces/1/processes/5/runs/2/robotRuns/3/release-work-item"
body = {"workItemId": item_id, "state": State.FAILED.value}
self.mock_post.assert_called_once_with(
url, headers=self.HEADERS_PROCESS, json=body
)
def test_load_payload(self, adapter):
item_id = "4"
expected_payload = {"name": "value"}
self.mock_get.return_value.json.return_value = expected_payload
payload = adapter.load_payload(item_id)
assert payload == expected_payload
response = self.mock_get.return_value
response.ok = False
response.status_code = 404
payload = adapter.load_payload(item_id)
assert payload == {}
def test_save_payload(self, adapter):
item_id = "1993"
payload = {"Cosmin": "Poieana"}
adapter.save_payload(item_id, payload)
url = f"https://api.workitem.com/json-v1/workspaces/1/workitems/{item_id}/data"
self.mock_put.assert_called_once_with(
url, headers=self.HEADERS_WORKITEM, json=payload
)
def test_remove_file(self, adapter):
item_id = "44"
name = "procrastination.txt"
file_id = "88"
self.mock_get.return_value.json.return_value = [
{"fileName": name, "fileId": file_id}
]
adapter.remove_file(item_id, name)
url = f"https://api.workitem.com/json-v1/workspaces/1/workitems/{item_id}/files/{file_id}"
self.mock_delete.assert_called_once_with(url, headers=self.HEADERS_WORKITEM)
def test_list_files(self, adapter):
expected_files = ["just.py", "mark.robot", "it.txt"]
self.mock_get.return_value.json.return_value = [
{"fileName": expected_files[0], "fileId": "1"},
{"fileName": expected_files[1], "fileId": "2"},
{"fileName": expected_files[2], "fileId": "3"},
]
files = adapter.list_files("4")
assert files == expected_files
@staticmethod
def _failing_response(request):
resp = mock.MagicMock()
resp.ok = False
resp.json.return_value = request.param[0]
resp.raise_for_status.side_effect = request.param[1]
return resp
@pytest.fixture(
params=[
# Requests response attribute values for: `.json()`, `.raise_for_status()`
({}, None),
(None, HTTPError()),
]
)
def failing_response(self, request):
return self._failing_response(request)
@pytest.mark.parametrize(
"status_code,call_count",
[
# Retrying enabled:
(429, 5),
# Retrying disabled:
(400, 1),
(401, 1),
(403, 1),
(409, 1),
(500, 1),
],
)
def test_list_files_retrying(
self, adapter, failing_response, status_code, call_count
):
self.mock_get.return_value = failing_response
failing_response.status_code = status_code
with pytest.raises(RequestsHTTPError) as exc_info:
adapter.list_files("4")
assert exc_info.value.status_code == status_code
assert self.mock_get.call_count == call_count # tried once or 5 times in a row
@pytest.fixture(
params=[
# Requests response attribute values for: `.json()`, `.raise_for_status()`
({"error": {"code": "ERR_UNEXPECTED"}}, None), # normal response
('{"error": {"code": "ERR_UNEXPECTED"}}', None), # double serialized
(r'"{\"error\": {\"code\": \"ERR_UNEXPECTED\"}}"', None), # triple
('[{"some": "value"}]', HTTPError()), # double serialized list
]
)
def failing_deserializing_response(self, request):
return self._failing_response(request)
def test_bad_response_payload(self, adapter, failing_deserializing_response):
self.mock_get.return_value = failing_deserializing_response
failing_deserializing_response.status_code = 429
with pytest.raises(RequestsHTTPError) as exc_info:
adapter.list_files("4")
err = "ERR_UNEXPECTED"
call_count = 1
if err not in str(failing_deserializing_response.json.return_value):
err = "Error" # default error message in the absence of it
call_count = 5
assert exc_info.value.status_code == 429
assert exc_info.value.status_message == err
assert self.mock_get.call_count == call_count
| import copy
import json
import os
import pytest
import tempfile
from contextlib import contextmanager
from pathlib import Path
from unittest import mock
from requests import HTTPError
from RPA.Robocorp.WorkItems import (
BaseAdapter,
EmptyQueue,
FileAdapter,
RobocorpAdapter,
State,
WorkItems,
)
from RPA.Robocorp.utils import RequestsHTTPError
VARIABLES_FIRST = {"username": "testguy", "address": "guy@company.com"}
VARIABLES_SECOND = {"username": "another", "address": "dude@company.com"}
VALID_DATA = {
"workitem-id-first": VARIABLES_FIRST,
"workitem-id-second": VARIABLES_SECOND,
"workitem-id-custom": [1, 2, 3],
}
VALID_FILES = {
"workitem-id-first": {
"file1.txt": b"data1",
"file2.txt": b"data2",
"file3.png": b"data3",
},
"workitem-id-second": {},
"workitem-id-custom": {},
}
ITEMS_JSON = [{"payload": {"a-key": "a-value"}, "files": {"a-file": "file.txt"}}]
@contextmanager
def temp_filename(content=None):
"""Create temporary file and return filename, delete file afterwards.
Needs to close file handle, since Windows won't allow multiple
open handles to the same file.
"""
with tempfile.NamedTemporaryFile(delete=False) as fd:
path = fd.name
if content:
fd.write(content)
try:
yield path
finally:
os.unlink(path)
def is_equal_files(lhs, rhs):
lhs = Path(lhs).resolve()
rhs = Path(rhs).resolve()
return lhs == rhs
class MockAdapter(BaseAdapter):
DATA = {}
FILES = {}
INDEX = 0
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._data_keys = []
self.releases = []
@classmethod
def validate(cls, item, key, val):
data = cls.DATA.get(item.id)
assert data is not None
assert data[key] == val
@property
def data_keys(self):
if not self._data_keys:
self._data_keys = list(self.DATA.keys())
return self._data_keys
def reserve_input(self) -> str:
if self.INDEX >= len(self.data_keys):
raise EmptyQueue("No work items in the input queue")
try:
return self.data_keys[self.INDEX]
finally:
self.INDEX += 1
def release_input(self, item_id: str, state: State):
self.releases.append((item_id, state)) # purely for testing purposes
def create_output(self, parent_id, payload=None) -> str:
raise NotImplementedError
def load_payload(self, item_id):
return self.DATA[item_id]
def save_payload(self, item_id, payload):
self.DATA[item_id] = payload
def list_files(self, item_id):
return self.FILES[item_id]
def get_file(self, item_id, name):
return self.FILES[item_id][name]
def add_file(self, item_id, name, *, original_name, content):
self.FILES[item_id][name] = content
def remove_file(self, item_id, name):
del self.FILES[item_id][name]
class TestLibrary:
@pytest.fixture
def adapter(self):
MockAdapter.DATA = copy.deepcopy(VALID_DATA)
MockAdapter.FILES = copy.deepcopy(VALID_FILES)
try:
yield MockAdapter
finally:
MockAdapter.DATA = {}
MockAdapter.FILES = {}
MockAdapter.INDEX = 0
@pytest.fixture
def library(self, adapter):
yield WorkItems(default_adapter=adapter)
def test_autoload(self, library):
# Called by Robot Framework listener
library._start_suite(None, None)
# Work item loaded using env variables
env = library.current
assert env is not None
assert env.payload == VARIABLES_FIRST
def test_autoload_disable(self, adapter):
library = WorkItems(default_adapter=adapter, autoload=False)
# Called by Robot Framework listener
library._start_suite(None, None)
assert library._current is None
def test_keyword_get_input_work_item(self, library):
first = library.get_input_work_item()
assert first.payload == VARIABLES_FIRST
assert first == library.current
second = library.get_input_work_item()
assert second.payload == VARIABLES_SECOND
assert second == library.current
def test_keyword_save_work_item(self, library):
item = library.get_input_work_item()
for key, value in VARIABLES_FIRST.items():
MockAdapter.validate(item, key, value)
modified = {"username": "changed", "address": "dude@company.com"}
item.payload = modified
library.save_work_item()
for key, value in modified.items():
MockAdapter.validate(item, key, value)
def test_no_active_item(self):
library = WorkItems(default_adapter=MockAdapter)
with pytest.raises(RuntimeError) as err:
library.save_work_item()
assert str(err.value) == "No active work item"
def test_list_variables(self, library):
library.get_input_work_item()
names = library.list_work_item_variables()
assert len(names) == 2
assert "username" in names
assert "address" in names
def test_get_variables(self, library):
library.get_input_work_item()
value = library.get_work_item_variable("username")
assert value == "testguy"
with pytest.raises(KeyError):
library.get_work_item_variable("notexist")
def test_get_variables_default(self, library):
library.get_input_work_item()
value = library.get_work_item_variable("username", default="doesntmatter")
assert value == "testguy"
value = library.get_work_item_variable("notexist", default="doesmatter")
assert value == "doesmatter"
def test_delete_variables(self, library):
library.get_input_work_item()
assert "username" in library.list_work_item_variables()
library.delete_work_item_variables("username")
assert "username" not in library.list_work_item_variables()
library.delete_work_item_variables("doesntexist")
with pytest.raises(KeyError):
library.delete_work_item_variables("doesntexist", force=False)
def test_delete_variables_multiple(self, library):
library.get_input_work_item()
assert "username" in library.list_work_item_variables()
assert len(library.current["variables"]) == 2
library.delete_work_item_variables("username")
assert "username" not in library.list_work_item_variables()
assert len(library.current["variables"]) == 1
def test_delete_variables_multiple(self, library):
library.get_input_work_item()
names = library.list_work_item_variables()
assert "username" in names
assert "address" in names
assert len(names) == 2
library.delete_work_item_variables("username", "address")
names = library.list_work_item_variables()
assert "username" not in names
assert "username" not in names
assert len(names) == 0
def test_delete_variables_unknown(self, library):
library.get_input_work_item()
assert len(library.list_work_item_variables()) == 2
library.delete_work_item_variables("unknown-variable")
assert len(library.list_work_item_variables()) == 2
with pytest.raises(KeyError):
library.delete_work_item_variables("unknown-variable", force=False)
assert len(library.list_work_item_variables()) == 2
def test_raw_payload(self, library):
_ = library.get_input_work_item()
_ = library.get_input_work_item()
item = library.get_input_work_item()
payload = library.get_work_item_payload()
assert payload == [1, 2, 3]
library.set_work_item_payload({"output": 0xBEEF})
library.save_work_item()
MockAdapter.validate(item, "output", 0xBEEF)
def test_list_files(self, library):
library.get_input_work_item()
files = library.list_work_item_files()
assert files == ["file1.txt", "file2.txt", "file3.png"]
def test_get_file(self, library):
library.get_input_work_item()
with temp_filename() as path:
result = library.get_work_item_file("file2.txt", path)
with open(result) as fd:
data = fd.read()
assert is_equal_files(result, path)
assert data == "data2"
def test_get_file_notexist(self, library):
library.get_input_work_item()
with pytest.raises(FileNotFoundError):
library.get_work_item_file("file5.txt")
def test_add_file(self, library):
item = library.get_input_work_item()
with temp_filename(b"some-input-content") as path:
library.add_work_item_file(path, "file4.txt")
files = library.list_work_item_files()
assert files == ["file1.txt", "file2.txt", "file3.png", "file4.txt"]
assert "file4.txt" not in MockAdapter.FILES[item.id]
library.save_work_item()
assert MockAdapter.FILES[item.id]["file4.txt"] == b"some-input-content"
def test_add_file_duplicate(self, library):
item = library.get_input_work_item()
def verify_files():
files = library.list_work_item_files()
assert files == ["file1.txt", "file2.txt", "file3.png", "file4.txt"]
with temp_filename(b"some-input-content") as path:
library.add_work_item_file(path, "file4.txt")
assert "file4.txt" not in MockAdapter.FILES[item.id]
verify_files()
# Add duplicate for unsaved item
library.add_work_item_file(path, "file4.txt")
assert "file4.txt" not in MockAdapter.FILES[item.id]
verify_files()
library.save_work_item()
assert MockAdapter.FILES[item.id]["file4.txt"] == b"some-input-content"
verify_files()
# Add duplicate for saved item
library.add_work_item_file(path, "file4.txt")
verify_files()
library.save_work_item()
verify_files()
def test_add_file_notexist(self, library):
library.get_input_work_item()
with pytest.raises(FileNotFoundError):
library.add_work_item_file("file5.txt", "doesnt-matter")
def test_remove_file(self, library):
item = library.get_input_work_item()
library.remove_work_item_file("file2.txt")
files = library.list_work_item_files()
assert files == ["file1.txt", "file3.png"]
assert "file2.txt" in MockAdapter.FILES[item.id]
library.save_work_item()
assert "file2.txt" not in MockAdapter.FILES[item.id]
def test_remove_file_notexist(self, library):
library.get_input_work_item()
library.remove_work_item_file("file5.txt")
with pytest.raises(FileNotFoundError):
library.remove_work_item_file("file5.txt", missing_ok=False)
def test_get_file_pattern(self, library):
library.get_input_work_item()
with tempfile.TemporaryDirectory() as outdir:
file1 = os.path.join(outdir, "file1.txt")
file2 = os.path.join(outdir, "file2.txt")
paths = library.get_work_item_files("*.txt", outdir)
assert is_equal_files(paths[0], file1)
assert is_equal_files(paths[1], file2)
assert os.path.exists(file1)
assert os.path.exists(file2)
def test_remove_file_pattern(self, library):
item = library.get_input_work_item()
library.remove_work_item_files("*.txt")
files = library.list_work_item_files()
assert files == ["file3.png"]
assert list(MockAdapter.FILES[item.id]) == [
"file1.txt",
"file2.txt",
"file3.png",
]
library.save_work_item()
files = library.list_work_item_files()
assert files == ["file3.png"]
assert list(MockAdapter.FILES[item.id]) == ["file3.png"]
def test_clear_work_item(self, library):
library.get_input_work_item()
library.clear_work_item()
library.save_work_item()
assert library.get_work_item_payload() == {}
assert library.list_work_item_files() == []
def test_get_file_unsaved(self, library):
library.get_input_work_item()
with temp_filename(b"some-input-content") as path:
library.add_work_item_file(path, "file4.txt")
files = library.list_work_item_files()
assert files == ["file1.txt", "file2.txt", "file3.png", "file4.txt"]
assert "file4.txt" not in MockAdapter.FILES
with tempfile.TemporaryDirectory() as outdir:
names = ["file1.txt", "file2.txt", "file4.txt"]
result = library.get_work_item_files("*.txt", outdir)
expected = [os.path.join(outdir, name) for name in names]
for lhs, rhs in zip(result, expected):
assert is_equal_files(lhs, rhs)
with open(result[-1]) as fd:
assert fd.read() == "some-input-content"
def test_get_file_unsaved_no_copy(self, library):
library.get_input_work_item()
with tempfile.TemporaryDirectory() as outdir:
path = os.path.join(outdir, "nomove.txt")
with open(path, "w") as fd:
fd.write("my content")
mtime = os.path.getmtime(path)
library.add_work_item_file(path)
files = library.list_work_item_files()
assert files == ["file1.txt", "file2.txt", "file3.png", "nomove.txt"]
paths = library.get_work_item_files("*.txt", outdir)
assert is_equal_files(paths[-1], path)
assert os.path.getmtime(path) == mtime
def test_get_file_unsaved_relative(self, library):
library.get_input_work_item()
with tempfile.TemporaryDirectory() as outdir:
curdir = os.getcwd()
try:
os.chdir(outdir)
with open("nomove.txt", "w") as fd:
fd.write("my content")
mtime = os.path.getmtime("nomove.txt")
library.add_work_item_file(os.path.join(outdir, "nomove.txt"))
files = library.list_work_item_files()
assert files == ["file1.txt", "file2.txt", "file3.png", "nomove.txt"]
paths = library.get_work_item_files("*.txt")
assert is_equal_files(paths[-1], os.path.join(outdir, "nomove.txt"))
assert os.path.getmtime("nomove.txt") == mtime
finally:
os.chdir(curdir)
def test_get_file_no_matches(self, library):
library.get_input_work_item()
with tempfile.TemporaryDirectory() as outdir:
paths = library.get_work_item_files("*.pdf", outdir)
assert len(paths) == 0
def test_create_output_work_item(self, library):
input_item = library.get_input_work_item()
output_item = library.create_output_work_item()
assert output_item.id is None
assert output_item.parent_id == input_item.id
def test_create_output_work_item_no_input(self, library):
with pytest.raises(RuntimeError):
library.create_output_work_item()
def test_custom_root(self, adapter):
library = WorkItems(default_adapter=adapter, root="vars")
item = library.get_input_work_item()
variables = library.get_work_item_variables()
assert variables == {}
library.set_work_item_variables(cool="beans", yeah="boi")
assert item.payload == {
**VARIABLES_FIRST,
"vars": {"cool": "beans", "yeah": "boi"},
}
@pytest.mark.parametrize("limit", [0, 1, 2, 3, 4]) # no, existing and over limit
def test_iter_work_items(self, library, limit):
usernames = []
def func(a, b, r=3):
assert a + b == r
# Collects the "username" variable from the payload if provided and returns
# True if found, False otherwise.
payload = library.get_work_item_payload()
if not isinstance(payload, dict):
return False
username = payload.get("username")
if username:
usernames.append(username)
return username is not None
library.get_input_work_item()
results = library.for_each_input_work_item(func, 1, 2, _limit=limit, r=3)
expected_usernames = ["testguy", "another"]
expected_results = [True, True, False]
if limit:
expected_usernames = expected_usernames[:limit]
expected_results = expected_results[:limit]
assert usernames == expected_usernames
assert results == expected_results
def test_release_work_item(self, library):
library.get_input_work_item()
library.release_input_work_item("FAILED") # intentionally provide a string
assert library.current.state == State.FAILED
assert library.adapter.releases == [("workitem-id-first", State.FAILED)]
def test_auto_release_work_item(self, library):
library.get_input_work_item()
library.get_input_work_item() # this automatically sets the state of the last
assert library.current.state is None # because the previous one has a state
assert library.adapter.releases == [("workitem-id-first", State.DONE)]
class TestFileAdapter:
"""Tests the local dev env `FileAdapter` on Work Items."""
@contextmanager
def _input_work_items(self):
with tempfile.TemporaryDirectory() as datadir:
items_in = os.path.join(datadir, "items.json")
with open(items_in, "w") as fd:
json.dump(ITEMS_JSON, fd)
with open(os.path.join(datadir, "file.txt"), "w") as fd:
fd.write("some mock content")
output_dir = os.path.join(datadir, "output_dir")
os.makedirs(output_dir)
items_out = os.path.join(output_dir, "items-out.json")
yield items_in, items_out
@pytest.fixture(
params=[
("RPA_WORKITEMS_PATH", "N/A"),
("RPA_INPUT_WORKITEM_PATH", "RPA_OUTPUT_WORKITEM_PATH"),
]
)
def adapter(self, monkeypatch, request):
with self._input_work_items() as (items_in, items_out):
monkeypatch.setenv(request.param[0], items_in)
monkeypatch.setenv(request.param[1], items_out)
yield FileAdapter()
@pytest.fixture
def empty_adapter(self):
# No work items i/o files nor envs set.
return FileAdapter()
def test_load_data(self, adapter):
item_id = adapter.reserve_input()
data = adapter.load_payload(item_id)
assert data == {"a-key": "a-value"}
def test_list_files(self, adapter):
item_id = adapter.reserve_input()
files = adapter.list_files(item_id)
assert files == ["a-file"]
def test_get_file(self, adapter):
item_id = adapter.reserve_input()
content = adapter.get_file(item_id, "a-file")
assert content == b"some mock content"
def test_add_file(self, adapter):
item_id = adapter.reserve_input()
adapter.add_file(
item_id,
"secondfile.txt",
original_name="secondfile2.txt",
content=b"somedata",
)
assert adapter.inputs[0]["files"]["secondfile.txt"] == "secondfile2.txt"
assert os.path.isfile(Path(adapter.input_path).parent / "secondfile2.txt")
def test_save_data_input(self, adapter):
item_id = adapter.reserve_input()
adapter.save_payload(item_id, {"key": "value"})
with open(adapter.input_path) as fd:
data = json.load(fd)
assert data == [
{"payload": {"key": "value"}, "files": {"a-file": "file.txt"}}
]
def test_save_data_output(self, adapter):
item_id = adapter.create_output("0", {})
adapter.save_payload(item_id, {"key": "value"})
output = os.getenv("RPA_OUTPUT_WORKITEM_PATH")
if output:
assert "output_dir" in output # checks automatic dir creation
else:
output = Path(adapter.input_path).with_suffix(".output.json")
assert os.path.isfile(output)
with open(output) as fd:
data = json.load(fd)
assert data == [{"payload": {"key": "value"}, "files": {}}]
def test_missing_file(self, monkeypatch):
monkeypatch.setenv("RPA_WORKITEMS_PATH", "not-exist.json")
adapter = FileAdapter()
assert adapter.inputs == [{"payload": {}}]
def test_empty_queue(self, monkeypatch):
with tempfile.TemporaryDirectory() as datadir:
items = os.path.join(datadir, "items.json")
with open(items, "w") as fd:
json.dump([], fd)
monkeypatch.setenv("RPA_WORKITEMS_PATH", items)
adapter = FileAdapter()
assert adapter.inputs == [{"payload": {}}]
def test_malformed_queue(self, monkeypatch):
with tempfile.TemporaryDirectory() as datadir:
items = os.path.join(datadir, "items.json")
with open(items, "w") as fd:
json.dump(["not-an-item"], fd)
monkeypatch.setenv("RPA_WORKITEMS_PATH", items)
adapter = FileAdapter()
assert adapter.inputs == [{"payload": {}}]
def test_without_items_paths(self, empty_adapter):
assert empty_adapter.inputs == [{"payload": {}}]
# Can't save inputs nor outputs since there's no path defined for them.
with pytest.raises(RuntimeError):
empty_adapter.save_payload("0", {"input": "value"})
with pytest.raises(RuntimeError):
_ = empty_adapter.output_path
with pytest.raises(RuntimeError):
empty_adapter.create_output("1", {"var": "some-value"})
class TestRobocorpAdapter:
"""Test control room API calls and retrying behaviour."""
ENV = {
"RC_WORKSPACE_ID": "1",
"RC_PROCESS_RUN_ID": "2",
"RC_ACTIVITY_RUN_ID": "3",
"RC_WORKITEM_ID": "4",
"RC_API_WORKITEM_HOST": "https://api.workitem.com",
"RC_API_WORKITEM_TOKEN": "workitem-token",
"RC_API_PROCESS_HOST": "https://api.process.com",
"RC_API_PROCESS_TOKEN": "process-token",
"RC_PROCESS_ID": "5",
}
HEADERS_WORKITEM = {
"Authorization": f"Bearer {ENV['RC_API_WORKITEM_TOKEN']}",
"Content-Type": "application/json",
}
HEADERS_PROCESS = {
"Authorization": f"Bearer {ENV['RC_API_PROCESS_TOKEN']}",
"Content-Type": "application/json",
}
@pytest.fixture
def adapter(self, monkeypatch):
for name, value in self.ENV.items():
monkeypatch.setenv(name, value)
with mock.patch("RPA.Robocorp.utils.requests.get") as mock_get, mock.patch(
"RPA.Robocorp.utils.requests.post"
) as mock_post, mock.patch(
"RPA.Robocorp.utils.requests.put"
) as mock_put, mock.patch(
"RPA.Robocorp.utils.requests.delete"
) as mock_delete, mock.patch(
"time.sleep", return_value=None
):
self.mock_get = mock_get
self.mock_post = mock_post
self.mock_put = mock_put
self.mock_delete = mock_delete
yield RobocorpAdapter()
def test_reserve_input(self, adapter):
initial_item_id = adapter.reserve_input()
assert initial_item_id == self.ENV["RC_WORKITEM_ID"]
self.mock_post.return_value.json.return_value = {"workItemId": "44"}
reserved_item_id = adapter.reserve_input()
assert reserved_item_id == "44"
url = "https://api.process.com/process-v1/workspaces/1/processes/5/runs/2/robotRuns/3/reserve-next-work-item"
self.mock_post.assert_called_once_with(url, headers=self.HEADERS_PROCESS)
def test_release_input(self, adapter):
item_id = "26"
adapter.release_input(item_id, State.FAILED)
url = "https://api.process.com/process-v1/workspaces/1/processes/5/runs/2/robotRuns/3/release-work-item"
body = {"workItemId": item_id, "state": State.FAILED.value}
self.mock_post.assert_called_once_with(
url, headers=self.HEADERS_PROCESS, json=body
)
def test_load_payload(self, adapter):
item_id = "4"
expected_payload = {"name": "value"}
self.mock_get.return_value.json.return_value = expected_payload
payload = adapter.load_payload(item_id)
assert payload == expected_payload
response = self.mock_get.return_value
response.ok = False
response.status_code = 404
payload = adapter.load_payload(item_id)
assert payload == {}
def test_save_payload(self, adapter):
item_id = "1993"
payload = {"Cosmin": "Poieana"}
adapter.save_payload(item_id, payload)
url = f"https://api.workitem.com/json-v1/workspaces/1/workitems/{item_id}/data"
self.mock_put.assert_called_once_with(
url, headers=self.HEADERS_WORKITEM, json=payload
)
def test_remove_file(self, adapter):
item_id = "44"
name = "procrastination.txt"
file_id = "88"
self.mock_get.return_value.json.return_value = [
{"fileName": name, "fileId": file_id}
]
adapter.remove_file(item_id, name)
url = f"https://api.workitem.com/json-v1/workspaces/1/workitems/{item_id}/files/{file_id}"
self.mock_delete.assert_called_once_with(url, headers=self.HEADERS_WORKITEM)
def test_list_files(self, adapter):
expected_files = ["just.py", "mark.robot", "it.txt"]
self.mock_get.return_value.json.return_value = [
{"fileName": expected_files[0], "fileId": "1"},
{"fileName": expected_files[1], "fileId": "2"},
{"fileName": expected_files[2], "fileId": "3"},
]
files = adapter.list_files("4")
assert files == expected_files
@staticmethod
def _failing_response(request):
resp = mock.MagicMock()
resp.ok = False
resp.json.return_value = request.param[0]
resp.raise_for_status.side_effect = request.param[1]
return resp
@pytest.fixture(
params=[
# Requests response attribute values for: `.json()`, `.raise_for_status()`
({}, None),
(None, HTTPError()),
]
)
def failing_response(self, request):
return self._failing_response(request)
@pytest.mark.parametrize(
"status_code,call_count",
[
# Retrying enabled:
(429, 5),
# Retrying disabled:
(400, 1),
(401, 1),
(403, 1),
(409, 1),
(500, 1),
],
)
def test_list_files_retrying(
self, adapter, failing_response, status_code, call_count
):
self.mock_get.return_value = failing_response
failing_response.status_code = status_code
with pytest.raises(RequestsHTTPError) as exc_info:
adapter.list_files("4")
assert exc_info.value.status_code == status_code
assert self.mock_get.call_count == call_count # tried once or 5 times in a row
@pytest.fixture(
params=[
# Requests response attribute values for: `.json()`, `.raise_for_status()`
({"error": {"code": "ERR_UNEXPECTED"}}, None), # normal response
('{"error": {"code": "ERR_UNEXPECTED"}}', None), # double serialized
(r'"{\"error\": {\"code\": \"ERR_UNEXPECTED\"}}"', None), # triple
('[{"some": "value"}]', HTTPError()), # double serialized list
]
)
def failing_deserializing_response(self, request):
return self._failing_response(request)
def test_bad_response_payload(self, adapter, failing_deserializing_response):
self.mock_get.return_value = failing_deserializing_response
failing_deserializing_response.status_code = 429
with pytest.raises(RequestsHTTPError) as exc_info:
adapter.list_files("4")
err = "ERR_UNEXPECTED"
call_count = 1
if err not in str(failing_deserializing_response.json.return_value):
err = "Error" # default error message in the absence of it
call_count = 5
assert exc_info.value.status_code == 429
assert exc_info.value.status_message == err
assert self.mock_get.call_count == call_count
|
import functools
import io
import pickle
from pathlib import Path
import pytest
import torch
from builtin_dataset_mocks import parametrize_dataset_mocks, DATASET_MOCKS
from torch.testing._comparison import assert_equal, TensorLikePair, ObjectPair
from torch.utils.data.datapipes.iter.grouping import ShardingFilterIterDataPipe as ShardingFilter
from torch.utils.data.graph import traverse
from torchdata.datapipes.iter import IterDataPipe, Shuffler
from torchvision._utils import sequence_to_str
from torchvision.prototype import transforms, datasets
assert_samples_equal = functools.partial(
assert_equal, pair_types=(TensorLikePair, ObjectPair), rtol=0, atol=0, equal_nan=True
)
@pytest.fixture
def test_home(mocker, tmp_path):
mocker.patch("torchvision.prototype.datasets._api.home", return_value=str(tmp_path))
yield tmp_path
def test_coverage():
untested_datasets = set(datasets.list_datasets()) - DATASET_MOCKS.keys()
if untested_datasets:
raise AssertionError(
f"The dataset(s) {sequence_to_str(sorted(untested_datasets), separate_last="and ")} "
f"are exposed through `torchvision.prototype.datasets.load()`, but are not tested. "
f"Please add mock data to `test/builtin_dataset_mocks.py`."
)
class TestCommon:
@parametrize_dataset_mocks(DATASET_MOCKS)
def test_smoke(self, test_home, dataset_mock, config):
dataset_mock.prepare(test_home, config)
dataset = datasets.load(dataset_mock.name, **config)
if not isinstance(dataset, IterDataPipe):
raise AssertionError(f"Loading the dataset should return an IterDataPipe, but got {type(dataset)} instead.")
@parametrize_dataset_mocks(DATASET_MOCKS)
def test_sample(self, test_home, dataset_mock, config):
dataset_mock.prepare(test_home, config)
dataset = datasets.load(dataset_mock.name, **config)
try:
sample = next(iter(dataset))
except StopIteration:
raise AssertionError("Unable to draw any sample.") from None
except Exception as error:
raise AssertionError("Drawing a sample raised the error above.") from error
if not isinstance(sample, dict):
raise AssertionError(f"Samples should be dictionaries, but got {type(sample)} instead.")
if not sample:
raise AssertionError("Sample dictionary is empty.")
@parametrize_dataset_mocks(DATASET_MOCKS)
def test_num_samples(self, test_home, dataset_mock, config):
mock_info = dataset_mock.prepare(test_home, config)
dataset = datasets.load(dataset_mock.name, **config)
num_samples = 0
for _ in dataset:
num_samples += 1
assert num_samples == mock_info["num_samples"]
@parametrize_dataset_mocks(DATASET_MOCKS)
def test_decoding(self, test_home, dataset_mock, config):
dataset_mock.prepare(test_home, config)
dataset = datasets.load(dataset_mock.name, **config)
undecoded_features = {key for key, value in next(iter(dataset)).items() if isinstance(value, io.IOBase)}
if undecoded_features:
raise AssertionError(
f"The values of key(s) "
f"{sequence_to_str(sorted(undecoded_features), separate_last="and ")} were not decoded."
)
@parametrize_dataset_mocks(DATASET_MOCKS)
def test_no_vanilla_tensors(self, test_home, dataset_mock, config):
dataset_mock.prepare(test_home, config)
dataset = datasets.load(dataset_mock.name, **config)
vanilla_tensors = {key for key, value in next(iter(dataset)).items() if type(value) is torch.Tensor}
if vanilla_tensors:
raise AssertionError(
f"The values of key(s) "
f"{sequence_to_str(sorted(vanilla_tensors), separate_last="and ")} contained vanilla tensors."
)
@parametrize_dataset_mocks(DATASET_MOCKS)
def test_transformable(self, test_home, dataset_mock, config):
dataset_mock.prepare(test_home, config)
dataset = datasets.load(dataset_mock.name, **config)
next(iter(dataset.map(transforms.Identity())))
@parametrize_dataset_mocks(DATASET_MOCKS)
def test_serializable(self, test_home, dataset_mock, config):
dataset_mock.prepare(test_home, config)
dataset = datasets.load(dataset_mock.name, **config)
pickle.dumps(dataset)
@parametrize_dataset_mocks(DATASET_MOCKS)
@pytest.mark.parametrize("annotation_dp_type", (Shuffler, ShardingFilter))
def test_has_annotations(self, test_home, dataset_mock, config, annotation_dp_type):
def scan(graph):
for node, sub_graph in graph.items():
yield node
yield from scan(sub_graph)
dataset_mock.prepare(test_home, config)
dataset = datasets.load(dataset_mock.name, **config)
if not any(type(dp) is annotation_dp_type for dp in scan(traverse(dataset))):
raise AssertionError(f"The dataset doesn't contain a {annotation_dp_type.__name__}() datapipe.")
@parametrize_dataset_mocks(DATASET_MOCKS)
def test_save_load(self, test_home, dataset_mock, config):
dataset_mock.prepare(test_home, config)
dataset = datasets.load(dataset_mock.name, **config)
sample = next(iter(dataset))
with io.BytesIO() as buffer:
torch.save(sample, buffer)
buffer.seek(0)
assert_samples_equal(torch.load(buffer), sample)
@parametrize_dataset_mocks(DATASET_MOCKS["qmnist"])
class TestQMNIST:
def test_extra_label(self, test_home, dataset_mock, config):
dataset_mock.prepare(test_home, config)
dataset = datasets.load(dataset_mock.name, **config)
sample = next(iter(dataset))
for key, type in (
("nist_hsf_series", int),
("nist_writer_id", int),
("digit_index", int),
("nist_label", int),
("global_digit_index", int),
("duplicate", bool),
("unused", bool),
):
assert key in sample and isinstance(sample[key], type)
@parametrize_dataset_mocks(DATASET_MOCKS["gtsrb"])
class TestGTSRB:
def test_label_matches_path(self, test_home, dataset_mock, config):
# We read the labels from the csv files instead. But for the trainset, the labels are also part of the path.
# This test makes sure that they're both the same
if config.split != "train":
return
dataset_mock.prepare(test_home, config)
dataset = datasets.load(dataset_mock.name, **config)
for sample in dataset:
label_from_path = int(Path(sample["path"]).parent.name)
assert sample["label"] == label_from_path
| import functools
import io
import pickle
from pathlib import Path
import pytest
import torch
from builtin_dataset_mocks import parametrize_dataset_mocks, DATASET_MOCKS
from torch.testing._comparison import assert_equal, TensorLikePair, ObjectPair
from torch.utils.data.datapipes.iter.grouping import ShardingFilterIterDataPipe as ShardingFilter
from torch.utils.data.graph import traverse
from torchdata.datapipes.iter import IterDataPipe, Shuffler
from torchvision._utils import sequence_to_str
from torchvision.prototype import transforms, datasets
assert_samples_equal = functools.partial(
assert_equal, pair_types=(TensorLikePair, ObjectPair), rtol=0, atol=0, equal_nan=True
)
@pytest.fixture
def test_home(mocker, tmp_path):
mocker.patch("torchvision.prototype.datasets._api.home", return_value=str(tmp_path))
yield tmp_path
def test_coverage():
untested_datasets = set(datasets.list_datasets()) - DATASET_MOCKS.keys()
if untested_datasets:
raise AssertionError(
f"The dataset(s) {sequence_to_str(sorted(untested_datasets), separate_last='and ')} "
f"are exposed through `torchvision.prototype.datasets.load()`, but are not tested. "
f"Please add mock data to `test/builtin_dataset_mocks.py`."
)
class TestCommon:
@parametrize_dataset_mocks(DATASET_MOCKS)
def test_smoke(self, test_home, dataset_mock, config):
dataset_mock.prepare(test_home, config)
dataset = datasets.load(dataset_mock.name, **config)
if not isinstance(dataset, IterDataPipe):
raise AssertionError(f"Loading the dataset should return an IterDataPipe, but got {type(dataset)} instead.")
@parametrize_dataset_mocks(DATASET_MOCKS)
def test_sample(self, test_home, dataset_mock, config):
dataset_mock.prepare(test_home, config)
dataset = datasets.load(dataset_mock.name, **config)
try:
sample = next(iter(dataset))
except StopIteration:
raise AssertionError("Unable to draw any sample.") from None
except Exception as error:
raise AssertionError("Drawing a sample raised the error above.") from error
if not isinstance(sample, dict):
raise AssertionError(f"Samples should be dictionaries, but got {type(sample)} instead.")
if not sample:
raise AssertionError("Sample dictionary is empty.")
@parametrize_dataset_mocks(DATASET_MOCKS)
def test_num_samples(self, test_home, dataset_mock, config):
mock_info = dataset_mock.prepare(test_home, config)
dataset = datasets.load(dataset_mock.name, **config)
num_samples = 0
for _ in dataset:
num_samples += 1
assert num_samples == mock_info["num_samples"]
@parametrize_dataset_mocks(DATASET_MOCKS)
def test_decoding(self, test_home, dataset_mock, config):
dataset_mock.prepare(test_home, config)
dataset = datasets.load(dataset_mock.name, **config)
undecoded_features = {key for key, value in next(iter(dataset)).items() if isinstance(value, io.IOBase)}
if undecoded_features:
raise AssertionError(
f"The values of key(s) "
f"{sequence_to_str(sorted(undecoded_features), separate_last='and ')} were not decoded."
)
@parametrize_dataset_mocks(DATASET_MOCKS)
def test_no_vanilla_tensors(self, test_home, dataset_mock, config):
dataset_mock.prepare(test_home, config)
dataset = datasets.load(dataset_mock.name, **config)
vanilla_tensors = {key for key, value in next(iter(dataset)).items() if type(value) is torch.Tensor}
if vanilla_tensors:
raise AssertionError(
f"The values of key(s) "
f"{sequence_to_str(sorted(vanilla_tensors), separate_last='and ')} contained vanilla tensors."
)
@parametrize_dataset_mocks(DATASET_MOCKS)
def test_transformable(self, test_home, dataset_mock, config):
dataset_mock.prepare(test_home, config)
dataset = datasets.load(dataset_mock.name, **config)
next(iter(dataset.map(transforms.Identity())))
@parametrize_dataset_mocks(DATASET_MOCKS)
def test_serializable(self, test_home, dataset_mock, config):
dataset_mock.prepare(test_home, config)
dataset = datasets.load(dataset_mock.name, **config)
pickle.dumps(dataset)
@parametrize_dataset_mocks(DATASET_MOCKS)
@pytest.mark.parametrize("annotation_dp_type", (Shuffler, ShardingFilter))
def test_has_annotations(self, test_home, dataset_mock, config, annotation_dp_type):
def scan(graph):
for node, sub_graph in graph.items():
yield node
yield from scan(sub_graph)
dataset_mock.prepare(test_home, config)
dataset = datasets.load(dataset_mock.name, **config)
if not any(type(dp) is annotation_dp_type for dp in scan(traverse(dataset))):
raise AssertionError(f"The dataset doesn't contain a {annotation_dp_type.__name__}() datapipe.")
@parametrize_dataset_mocks(DATASET_MOCKS)
def test_save_load(self, test_home, dataset_mock, config):
dataset_mock.prepare(test_home, config)
dataset = datasets.load(dataset_mock.name, **config)
sample = next(iter(dataset))
with io.BytesIO() as buffer:
torch.save(sample, buffer)
buffer.seek(0)
assert_samples_equal(torch.load(buffer), sample)
@parametrize_dataset_mocks(DATASET_MOCKS["qmnist"])
class TestQMNIST:
def test_extra_label(self, test_home, dataset_mock, config):
dataset_mock.prepare(test_home, config)
dataset = datasets.load(dataset_mock.name, **config)
sample = next(iter(dataset))
for key, type in (
("nist_hsf_series", int),
("nist_writer_id", int),
("digit_index", int),
("nist_label", int),
("global_digit_index", int),
("duplicate", bool),
("unused", bool),
):
assert key in sample and isinstance(sample[key], type)
@parametrize_dataset_mocks(DATASET_MOCKS["gtsrb"])
class TestGTSRB:
def test_label_matches_path(self, test_home, dataset_mock, config):
# We read the labels from the csv files instead. But for the trainset, the labels are also part of the path.
# This test makes sure that they're both the same
if config.split != "train":
return
dataset_mock.prepare(test_home, config)
dataset = datasets.load(dataset_mock.name, **config)
for sample in dataset:
label_from_path = int(Path(sample["path"]).parent.name)
assert sample["label"] == label_from_path
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 Marcel Bollmann <marcel@bollmann.me>
#
# 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.
"""Usage: seed_meilisearch.py [options]
Options:
--importdir=DIR Directory to import XML files from. [default: {scriptdir}/../data/]
--json Don't connect to MeiliSearch, just dump JSON files instead.
--debug Output debug-level log messages.
-h, --help Display this helpful text.
"""
from docopt import docopt
from glob import glob
import json
import logging as log
from lxml import etree
import meilisearch
import os
import time
from anthology import Anthology
from anthology.utils import SeverityTracker
def prepare_meili_docs(anthology):
docs = []
for id_, paper in anthology.papers.items():
check_id(id_.replace(".", "_"))
author_ids = [
anthology.people.resolve_name(*author).get("id")
for author in paper.attrib.get("author", [])
]
docs.append(
{
"id": id_.replace(".", "_"),
"acl_id": id_,
"title": paper.get_title(form="plain"),
"abstract": paper.get_abstract(form="plain"),
"author": paper.attrib.get("author_string", "").replace(", ", " ||| "),
"author_ids": author_ids,
"year": int(paper.attrib.get("year")),
"venue": paper.get_booktitle(form="plain"),
"thumbnail": paper.attrib.get("thumbnail"),
"url": paper.attrib.get("url"),
"pdf": paper.attrib.get("pdf"),
}
)
return docs
def prepare_meili_authors(anthology):
docs = []
for id_ in anthology.people.personids():
check_id(id_)
docs.append(
{
"id": id_,
"name": anthology.people.id_to_canonical[id_].full,
"url": f"https://www.aclweb.org/anthology/people/{id_[0]}/{id_}",
"pubcount": len(anthology.people.id_to_papers[id_]["author"])
+ len(anthology.people.id_to_papers[id_]["editor"]),
}
)
return docs
def check_id(id_):
"""Checks if this is a valid MeiliSearch ID."""
if all(c.isalnum() or c in ("-", "_") for c in id_):
return True
log.error(f"Not a valid ID: '{id_}'")
return False
def client_has_index(client, uid):
for index in client.get_indexes():
if index.get("uid") == uid:
return True
return False
def perform_sync(action, index):
ret = action()
update_id = ret["updateId"]
duration = None
while True:
actions = index.get_update_status(update_id)
if actions.get("status") == "processed":
duration = float(actions.get("duration"))
break
elif actions.get("status") == "failed":
log.error(f"Action failed: {actions.get("error")}")
duration = float(actions.get("duration"))
break
elif actions.get("status") != "enqueued":
log.warning(f"Unknown status: {actions.get("status", "None")}")
time.sleep(1)
return duration
def main(anthology, dump=False):
if not dump:
log.info("Connecting to MeiliSearch...")
client = meilisearch.Client("http://127.0.0.1:7700")
log.info("Indexing papers...")
docs = prepare_meili_docs(anthology)
if dump:
with open("meili_papers.json", "w") as f:
json.dump(docs, f)
else:
if client_has_index(client, "papers"):
index = client.get_index("papers")
else:
index = client.create_index(uid="papers")
duration = perform_sync(lambda: index.add_documents(docs), index)
log.info(f"Done in {duration:.2f}s.")
log.info("Indexing authors...")
docs = prepare_meili_authors(anthology)
if dump:
with open("meili_people.json", "w") as f:
json.dump(docs, f)
else:
if client_has_index(client, "people"):
p_index = client.get_index("people")
else:
p_index = client.create_index(uid="people")
duration = perform_sync(lambda: p_index.add_documents(docs), p_index)
log.info(f"Done in {duration:.2f}s.")
if not dump:
log.info("Updating settings...")
order = ["title", "abstract", "author", "venue", "year"]
duration = perform_sync(
lambda: index.update_searchable_attributes(order), index
)
duration += perform_sync(
lambda: index.update_distinct_attribute("acl_id"), index
)
duration += perform_sync(
lambda: p_index.update_searchable_attributes(["name"]), p_index
)
log.info(f"Done in {duration:.2f}s.")
if __name__ == "__main__":
args = docopt(__doc__)
scriptdir = os.path.dirname(os.path.abspath(__file__))
if "{scriptdir}" in args["--importdir"]:
args["--importdir"] = os.path.abspath(
args["--importdir"].format(scriptdir=scriptdir)
)
log_level = log.DEBUG if args["--debug"] else log.INFO
log.basicConfig(format="%(levelname)-8s %(message)s", level=log_level)
tracker = SeverityTracker()
log.getLogger().addHandler(tracker)
log.info("Loading Anthology data...")
if not args["--debug"]:
log.getLogger().setLevel(log.ERROR)
anthology = Anthology(importdir=args["--importdir"])
log.getLogger().setLevel(log_level)
main(anthology, dump=bool(args["--json"]))
if tracker.highest >= log.ERROR:
exit(1)
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 Marcel Bollmann <marcel@bollmann.me>
#
# 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.
"""Usage: seed_meilisearch.py [options]
Options:
--importdir=DIR Directory to import XML files from. [default: {scriptdir}/../data/]
--json Don't connect to MeiliSearch, just dump JSON files instead.
--debug Output debug-level log messages.
-h, --help Display this helpful text.
"""
from docopt import docopt
from glob import glob
import json
import logging as log
from lxml import etree
import meilisearch
import os
import time
from anthology import Anthology
from anthology.utils import SeverityTracker
def prepare_meili_docs(anthology):
docs = []
for id_, paper in anthology.papers.items():
check_id(id_.replace(".", "_"))
author_ids = [
anthology.people.resolve_name(*author).get("id")
for author in paper.attrib.get("author", [])
]
docs.append(
{
"id": id_.replace(".", "_"),
"acl_id": id_,
"title": paper.get_title(form="plain"),
"abstract": paper.get_abstract(form="plain"),
"author": paper.attrib.get("author_string", "").replace(", ", " ||| "),
"author_ids": author_ids,
"year": int(paper.attrib.get("year")),
"venue": paper.get_booktitle(form="plain"),
"thumbnail": paper.attrib.get("thumbnail"),
"url": paper.attrib.get("url"),
"pdf": paper.attrib.get("pdf"),
}
)
return docs
def prepare_meili_authors(anthology):
docs = []
for id_ in anthology.people.personids():
check_id(id_)
docs.append(
{
"id": id_,
"name": anthology.people.id_to_canonical[id_].full,
"url": f"https://www.aclweb.org/anthology/people/{id_[0]}/{id_}",
"pubcount": len(anthology.people.id_to_papers[id_]["author"])
+ len(anthology.people.id_to_papers[id_]["editor"]),
}
)
return docs
def check_id(id_):
"""Checks if this is a valid MeiliSearch ID."""
if all(c.isalnum() or c in ("-", "_") for c in id_):
return True
log.error(f"Not a valid ID: '{id_}'")
return False
def client_has_index(client, uid):
for index in client.get_indexes():
if index.get("uid") == uid:
return True
return False
def perform_sync(action, index):
ret = action()
update_id = ret["updateId"]
duration = None
while True:
actions = index.get_update_status(update_id)
if actions.get("status") == "processed":
duration = float(actions.get("duration"))
break
elif actions.get("status") == "failed":
log.error(f"Action failed: {actions.get('error')}")
duration = float(actions.get("duration"))
break
elif actions.get("status") != "enqueued":
log.warning(f"Unknown status: {actions.get('status', 'None')}")
time.sleep(1)
return duration
def main(anthology, dump=False):
if not dump:
log.info("Connecting to MeiliSearch...")
client = meilisearch.Client("http://127.0.0.1:7700")
log.info("Indexing papers...")
docs = prepare_meili_docs(anthology)
if dump:
with open("meili_papers.json", "w") as f:
json.dump(docs, f)
else:
if client_has_index(client, "papers"):
index = client.get_index("papers")
else:
index = client.create_index(uid="papers")
duration = perform_sync(lambda: index.add_documents(docs), index)
log.info(f"Done in {duration:.2f}s.")
log.info("Indexing authors...")
docs = prepare_meili_authors(anthology)
if dump:
with open("meili_people.json", "w") as f:
json.dump(docs, f)
else:
if client_has_index(client, "people"):
p_index = client.get_index("people")
else:
p_index = client.create_index(uid="people")
duration = perform_sync(lambda: p_index.add_documents(docs), p_index)
log.info(f"Done in {duration:.2f}s.")
if not dump:
log.info("Updating settings...")
order = ["title", "abstract", "author", "venue", "year"]
duration = perform_sync(
lambda: index.update_searchable_attributes(order), index
)
duration += perform_sync(
lambda: index.update_distinct_attribute("acl_id"), index
)
duration += perform_sync(
lambda: p_index.update_searchable_attributes(["name"]), p_index
)
log.info(f"Done in {duration:.2f}s.")
if __name__ == "__main__":
args = docopt(__doc__)
scriptdir = os.path.dirname(os.path.abspath(__file__))
if "{scriptdir}" in args["--importdir"]:
args["--importdir"] = os.path.abspath(
args["--importdir"].format(scriptdir=scriptdir)
)
log_level = log.DEBUG if args["--debug"] else log.INFO
log.basicConfig(format="%(levelname)-8s %(message)s", level=log_level)
tracker = SeverityTracker()
log.getLogger().addHandler(tracker)
log.info("Loading Anthology data...")
if not args["--debug"]:
log.getLogger().setLevel(log.ERROR)
anthology = Anthology(importdir=args["--importdir"])
log.getLogger().setLevel(log_level)
main(anthology, dump=bool(args["--json"]))
if tracker.highest >= log.ERROR:
exit(1)
|
pessoas = {'nome': 'jonatan', 'sexo': 'M', 'idade': 39}
print('---'*15)
print(pessoas)
print(pessoas['idade'])
print(f'O {pessoas['nome']} tem {pessoas['idade']} anos')
print(pessoas.keys())
print(pessoas.values())
print(pessoas.items())
print('---'*15)
for k in pessoas.keys():
print(k)
print('---'*15)
for v in pessoas.values():
print(v)
print('---'*15)
for k, v in pessoas.items():
print(f'{k} = {v}')
print('---'*15)
del pessoas['sexo']
pessoas['nome'] = 'Augusto'
pessoas['peso'] = 85
for k, v in pessoas.items():
print(f'{k} = {v}') | pessoas = {'nome': 'jonatan', 'sexo': 'M', 'idade': 39}
print('---'*15)
print(pessoas)
print(pessoas['idade'])
print(f'O {pessoas["nome"]} tem {pessoas["idade"]} anos')
print(pessoas.keys())
print(pessoas.values())
print(pessoas.items())
print('---'*15)
for k in pessoas.keys():
print(k)
print('---'*15)
for v in pessoas.values():
print(v)
print('---'*15)
for k, v in pessoas.items():
print(f'{k} = {v}')
print('---'*15)
del pessoas['sexo']
pessoas['nome'] = 'Augusto'
pessoas['peso'] = 85
for k, v in pessoas.items():
print(f'{k} = {v}') |
import shutil
from glob import glob
from pathlib import Path
import pytest
_HERE = Path(__file__).parent
@pytest.fixture()
def test_data_folder():
return _HERE / 'data'
@pytest.fixture(scope='session')
def product_dir(tmp_path_factory):
prod = tmp_path_factory.mktemp('S1A_IW_20150621T120220_DVP_RTC10_G_saufem_F8E2', numbered=False)
product_files = glob(str(_HERE / 'data' / 'rtc*'))
for f in product_files:
shutil.copy(f, prod / f'{Path(f).name.replace('rtc', prod.name)}')
return prod
| import shutil
from glob import glob
from pathlib import Path
import pytest
_HERE = Path(__file__).parent
@pytest.fixture()
def test_data_folder():
return _HERE / 'data'
@pytest.fixture(scope='session')
def product_dir(tmp_path_factory):
prod = tmp_path_factory.mktemp('S1A_IW_20150621T120220_DVP_RTC10_G_saufem_F8E2', numbered=False)
product_files = glob(str(_HERE / 'data' / 'rtc*'))
for f in product_files:
shutil.copy(f, prod / f'{Path(f).name.replace("rtc", prod.name)}')
return prod
|
from fnmatch import fnmatch
from lxml.etree import Element
from Framework import Transform_Wrapper, Load_File, Load_Files, Plugin_Log
from .Support import Standardize_Match_Rules
from .Support import XML_Multiply_Int_Attribute
from .Support import XML_Multiply_Float_Attribute
__all__ = [
'Increase_AI_Script_Waits',
'Adjust_OOS_Damage',
'Disable_AI_Travel_Drive',
]
@Transform_Wrapper()
def Increase_AI_Script_Waits(
oos_multiplier = 2,
oos_seta_multiplier = 4,
oos_max_wait = 15,
iv_multiplier = 1,
iv_seta_multiplier = 1,
iv_max_wait = 5,
filter = '*',
include_extensions = False,
skip_combat_scripts = False,
skip_mining_scripts = True,
):
'''
Increases wait times in ai scripts, to reduce their background load
and improve performance. Separate modifiers are applied to "in-vision"
and "out-of-vision" parts of scripts. Expected to have high impact on fps,
at some cost of ai efficiency.
* oos_multiplier
- Float, how much to multiply OOS wait times by. Default is 2.
* oos_seta_multiplier
- Float, alternate OOS multiplier to apply if the player
is in SETA mode. Default is 4.
- Eg. if multiplier is 2 and seta_multiplier is 4, then waits will
be 2x longer when not in SETA, 4x longer when in SETA.
* oos_max_wait
- Float, optional, the longest OOS wait that this multiplier can achieve,
in seconds.
- Defaults to 15.
- If the original wait is longer than this, it will be unaffected.
* iv_multiplier
- As above, but for in-vision.
- Defaults to 1x, eg. no change.
* iv_seta_multiplier
- As above, but for in-vision.
- Defaults to 1x, eg. no change.
* iv_max_wait
- As above, but for in-vision.
- Defaults to 5.
* filter
- String, possibly with wildcards, matching names of ai scripts to
modify; default is plain '*' to match all aiscripts.
- Example: "*trade.*" to modify only trade scripts.
* include_extensions
- Bool, if True then aiscripts added by extensions are also modified.
- Defaults False.
* skip_combat_scripts
- Bool, if True then scripts which control OOS damage application
will not be modified. Otherwise, they are modified and their
attack strength per round is increased to match the longer wait times.
- Defaults False.
* skip_mining_scripts
- Bool, if True then scripts which control OOS mining rates will not
be modified. Currently has no extra code to adjust mining rates
when scaled.
- Defaults True.
- Note currently expected to signicantly matter with max_wait of 15s,
since OOS mining waits at least 16s between gathers.
'''
# Just ai scripts; md has no load.
aiscript_files = Load_Files(f"{"*" if include_extensions else ""}aiscripts/{filter}.xml")
# Combine oos/iv stuff into a dict for convenience.
vis_params = {
'iv': {
'multiplier' : iv_multiplier,
'seta_multiplier' : iv_seta_multiplier,
'max_wait' : iv_max_wait,
},
'oos': {
'multiplier' : oos_multiplier,
'seta_multiplier' : oos_seta_multiplier,
'max_wait' : oos_max_wait,
},
}
# Set up the string with the multiplication.
for entry in vis_params.values():
entry['mult_str'] = "(if player.timewarp.active then {} else {})".format(
entry['seta_multiplier'],
entry['multiplier'])
for game_file in aiscript_files:
xml_root = game_file.Get_Root()
file_name = game_file.name.replace('.xml','')
# Find any get_attack_strength nodes, used in OOS combat.
attack_strength_nodes = xml_root.xpath(".//get_attackstrength")
# If there are any, and not modifying combat scripts, skip.
if attack_strength_nodes and skip_combat_scripts:
continue
# Find any get_resource_gatherrate nodes, used in OOS mining.
gatherrate_nodes = xml_root.xpath(".//get_resource_gatherrate")
# If there are any, and not modifying mining scripts, skip.
if gatherrate_nodes and skip_mining_scripts:
continue
# Find all waits.
nodes = xml_root.xpath(".//wait")
if not nodes:
continue
# Find any waits under visible attention as well.
visible_waits = xml_root.xpath('.//attention[@min="visible"]//wait')
# Loop over iv, oos.
for mode, params in vis_params.items():
# Unpack for convenience.
multiplier = params['multiplier']
seta_multiplier = params['seta_multiplier']
max_wait = params['max_wait']
mult_str = params['mult_str']
# If the multipliers are just 1x or None, skip.
if multiplier in [1,None] and seta_multiplier in [1,None]:
continue
for node in nodes:
# Skip if visible in oos, or if not visible in iv.
if mode == 'oos' and node in visible_waits:
continue
if mode == 'iv' and node not in visible_waits:
continue
# TODO: figure out a good way to record the wait length
# for pre-atack_strength waits, to use in adjusting the
# applied damage more precisely (eg. avoid mis-estimate
# when play goes in/out of seta during the pre-attack wait.
for attr in ['min','max','exact']:
orig = node.get(attr)
if not orig:
continue
# This will get the orig value, the orig value multiplied
# with a ceiling, and take the max.
new = f'[{orig}, [{max_wait}s, ({orig})*{mult_str}].min].max'
node.set(attr, new)
# If this is in-vision mode, skip the oos attack_strength stuff.
if mode == 'iv':
continue
# Adjust attack strength to account for the timing change.
for node in attack_strength_nodes:
# For now, assume the waits were fully multiplied, and didn't
# cap out at max_wait. Combat scripts appear to use a 1s
# period (since attack_strength is dps), so this shouldn't
# be an issue.
# This can have up to 5 output values, that all need the
# same multiplication.
# A unified result is in a 'result' attribute.
# Specific damages (shield, hull, etc.) are in a 'result'
# subnode.
# Gather the names of capture vars.
out_vars = []
if node.get('result'):
out_vars.append(node.get('result'))
result_subnode = node.find('./result')
if result_subnode != None:
for attr in ['hullshield','hullonly','shieldonly','hullnoshield']:
varname = result_subnode.get(attr)
if varname:
out_vars.append(varname)
# Add in set_value nodes to multiply each of these.
for varname in out_vars:
new_node = Element('set_value',
name = varname,
exact = f'{varname} * {mult_str}')
node.addnext(new_node)
# lxml can mess up node id tails, so fix it.
if new_node.tail != None:
assert node.tail == None
node.tail = new_node.tail
new_node.tail = None
game_file.Update_Root(xml_root)
return
@Transform_Wrapper()
def Adjust_OOS_Damage(multiplier):
'''
Adjusts all out-of-vision damage-per-second by a multiplier. For instance,
if OOS combat seems to run too fast, it can be multiplied by 0.5 to
slow it down by half.
* multiplier
- Float, how much to multiply damage by.
'''
# The code for this is similar to what was done above, just split off.
# If the two transforms are used together, it's probably okay, will
# just have a few extra cheap script instructions.
aiscript_files = Load_Files(f"*aiscripts/*.xml")
for game_file in aiscript_files:
xml_root = game_file.Get_Root()
file_name = game_file.name.replace('.xml','')
# Find any get_attack_strength nodes, used in OOS combat.
nodes = xml_root.xpath(".//get_attackstrength")
if not nodes:
continue
for node in nodes:
# Gather the names of capture vars.
out_vars = []
if node.get('result'):
out_vars.append(node.get('result'))
result_subnode = node.find('./result')
if result_subnode != None:
for attr in ['hullshield','hullonly','shieldonly','hullnoshield']:
varname = result_subnode.get(attr)
if varname:
out_vars.append(varname)
# Add in set_value nodes to multiply each of these.
for varname in out_vars:
new_node = Element('set_value',
name = varname,
exact = f'{varname} * {multiplier}')
node.addnext(new_node)
# lxml can mess up node id tails, so fix it.
if new_node.tail != None:
assert node.tail == None
node.tail = new_node.tail
new_node.tail = None
game_file.Update_Root(xml_root)
return
@Transform_Wrapper()
def Disable_AI_Travel_Drive():
'''
Disables usage of travel drives for all ai scripts. When applied to
a save, existing move orders may continue to use travel drive
until they complete.
'''
# Travel drive is part of the move commands, as one of the arguments.
# Can set to false always, to disable use.
# (This appears to only apply to plain move_to?)
aiscript_files = Load_Files(f"*aiscripts/*.xml")
for game_file in aiscript_files:
xml_root = game_file.Get_Root()
file_name = game_file.name.replace('.xml','')
change_occurred = False
for tag in [
#'move_approach_path',
#'move_docking',
#'move_undocking',
#'move_gate',
#'move_navmesh',
#'move_strafe',
#'move_target_points',
#'move_waypoints',
'move_to',
]:
nodes = xml_root.xpath(".//{}".format(tag))
if not nodes:
continue
for node in nodes:
# Check if this uses the travel arg; if not, it defaults to
# false, so no change needed.
if node.get('travel') != None:
node.set('travel', 'false')
change_occurred = True
if change_occurred:
game_file.Update_Root(xml_root)
return
|
from fnmatch import fnmatch
from lxml.etree import Element
from Framework import Transform_Wrapper, Load_File, Load_Files, Plugin_Log
from .Support import Standardize_Match_Rules
from .Support import XML_Multiply_Int_Attribute
from .Support import XML_Multiply_Float_Attribute
__all__ = [
'Increase_AI_Script_Waits',
'Adjust_OOS_Damage',
'Disable_AI_Travel_Drive',
]
@Transform_Wrapper()
def Increase_AI_Script_Waits(
oos_multiplier = 2,
oos_seta_multiplier = 4,
oos_max_wait = 15,
iv_multiplier = 1,
iv_seta_multiplier = 1,
iv_max_wait = 5,
filter = '*',
include_extensions = False,
skip_combat_scripts = False,
skip_mining_scripts = True,
):
'''
Increases wait times in ai scripts, to reduce their background load
and improve performance. Separate modifiers are applied to "in-vision"
and "out-of-vision" parts of scripts. Expected to have high impact on fps,
at some cost of ai efficiency.
* oos_multiplier
- Float, how much to multiply OOS wait times by. Default is 2.
* oos_seta_multiplier
- Float, alternate OOS multiplier to apply if the player
is in SETA mode. Default is 4.
- Eg. if multiplier is 2 and seta_multiplier is 4, then waits will
be 2x longer when not in SETA, 4x longer when in SETA.
* oos_max_wait
- Float, optional, the longest OOS wait that this multiplier can achieve,
in seconds.
- Defaults to 15.
- If the original wait is longer than this, it will be unaffected.
* iv_multiplier
- As above, but for in-vision.
- Defaults to 1x, eg. no change.
* iv_seta_multiplier
- As above, but for in-vision.
- Defaults to 1x, eg. no change.
* iv_max_wait
- As above, but for in-vision.
- Defaults to 5.
* filter
- String, possibly with wildcards, matching names of ai scripts to
modify; default is plain '*' to match all aiscripts.
- Example: "*trade.*" to modify only trade scripts.
* include_extensions
- Bool, if True then aiscripts added by extensions are also modified.
- Defaults False.
* skip_combat_scripts
- Bool, if True then scripts which control OOS damage application
will not be modified. Otherwise, they are modified and their
attack strength per round is increased to match the longer wait times.
- Defaults False.
* skip_mining_scripts
- Bool, if True then scripts which control OOS mining rates will not
be modified. Currently has no extra code to adjust mining rates
when scaled.
- Defaults True.
- Note currently expected to signicantly matter with max_wait of 15s,
since OOS mining waits at least 16s between gathers.
'''
# Just ai scripts; md has no load.
aiscript_files = Load_Files(f"{'*' if include_extensions else ''}aiscripts/{filter}.xml")
# Combine oos/iv stuff into a dict for convenience.
vis_params = {
'iv': {
'multiplier' : iv_multiplier,
'seta_multiplier' : iv_seta_multiplier,
'max_wait' : iv_max_wait,
},
'oos': {
'multiplier' : oos_multiplier,
'seta_multiplier' : oos_seta_multiplier,
'max_wait' : oos_max_wait,
},
}
# Set up the string with the multiplication.
for entry in vis_params.values():
entry['mult_str'] = "(if player.timewarp.active then {} else {})".format(
entry['seta_multiplier'],
entry['multiplier'])
for game_file in aiscript_files:
xml_root = game_file.Get_Root()
file_name = game_file.name.replace('.xml','')
# Find any get_attack_strength nodes, used in OOS combat.
attack_strength_nodes = xml_root.xpath(".//get_attackstrength")
# If there are any, and not modifying combat scripts, skip.
if attack_strength_nodes and skip_combat_scripts:
continue
# Find any get_resource_gatherrate nodes, used in OOS mining.
gatherrate_nodes = xml_root.xpath(".//get_resource_gatherrate")
# If there are any, and not modifying mining scripts, skip.
if gatherrate_nodes and skip_mining_scripts:
continue
# Find all waits.
nodes = xml_root.xpath(".//wait")
if not nodes:
continue
# Find any waits under visible attention as well.
visible_waits = xml_root.xpath('.//attention[@min="visible"]//wait')
# Loop over iv, oos.
for mode, params in vis_params.items():
# Unpack for convenience.
multiplier = params['multiplier']
seta_multiplier = params['seta_multiplier']
max_wait = params['max_wait']
mult_str = params['mult_str']
# If the multipliers are just 1x or None, skip.
if multiplier in [1,None] and seta_multiplier in [1,None]:
continue
for node in nodes:
# Skip if visible in oos, or if not visible in iv.
if mode == 'oos' and node in visible_waits:
continue
if mode == 'iv' and node not in visible_waits:
continue
# TODO: figure out a good way to record the wait length
# for pre-atack_strength waits, to use in adjusting the
# applied damage more precisely (eg. avoid mis-estimate
# when play goes in/out of seta during the pre-attack wait.
for attr in ['min','max','exact']:
orig = node.get(attr)
if not orig:
continue
# This will get the orig value, the orig value multiplied
# with a ceiling, and take the max.
new = f'[{orig}, [{max_wait}s, ({orig})*{mult_str}].min].max'
node.set(attr, new)
# If this is in-vision mode, skip the oos attack_strength stuff.
if mode == 'iv':
continue
# Adjust attack strength to account for the timing change.
for node in attack_strength_nodes:
# For now, assume the waits were fully multiplied, and didn't
# cap out at max_wait. Combat scripts appear to use a 1s
# period (since attack_strength is dps), so this shouldn't
# be an issue.
# This can have up to 5 output values, that all need the
# same multiplication.
# A unified result is in a 'result' attribute.
# Specific damages (shield, hull, etc.) are in a 'result'
# subnode.
# Gather the names of capture vars.
out_vars = []
if node.get('result'):
out_vars.append(node.get('result'))
result_subnode = node.find('./result')
if result_subnode != None:
for attr in ['hullshield','hullonly','shieldonly','hullnoshield']:
varname = result_subnode.get(attr)
if varname:
out_vars.append(varname)
# Add in set_value nodes to multiply each of these.
for varname in out_vars:
new_node = Element('set_value',
name = varname,
exact = f'{varname} * {mult_str}')
node.addnext(new_node)
# lxml can mess up node id tails, so fix it.
if new_node.tail != None:
assert node.tail == None
node.tail = new_node.tail
new_node.tail = None
game_file.Update_Root(xml_root)
return
@Transform_Wrapper()
def Adjust_OOS_Damage(multiplier):
'''
Adjusts all out-of-vision damage-per-second by a multiplier. For instance,
if OOS combat seems to run too fast, it can be multiplied by 0.5 to
slow it down by half.
* multiplier
- Float, how much to multiply damage by.
'''
# The code for this is similar to what was done above, just split off.
# If the two transforms are used together, it's probably okay, will
# just have a few extra cheap script instructions.
aiscript_files = Load_Files(f"*aiscripts/*.xml")
for game_file in aiscript_files:
xml_root = game_file.Get_Root()
file_name = game_file.name.replace('.xml','')
# Find any get_attack_strength nodes, used in OOS combat.
nodes = xml_root.xpath(".//get_attackstrength")
if not nodes:
continue
for node in nodes:
# Gather the names of capture vars.
out_vars = []
if node.get('result'):
out_vars.append(node.get('result'))
result_subnode = node.find('./result')
if result_subnode != None:
for attr in ['hullshield','hullonly','shieldonly','hullnoshield']:
varname = result_subnode.get(attr)
if varname:
out_vars.append(varname)
# Add in set_value nodes to multiply each of these.
for varname in out_vars:
new_node = Element('set_value',
name = varname,
exact = f'{varname} * {multiplier}')
node.addnext(new_node)
# lxml can mess up node id tails, so fix it.
if new_node.tail != None:
assert node.tail == None
node.tail = new_node.tail
new_node.tail = None
game_file.Update_Root(xml_root)
return
@Transform_Wrapper()
def Disable_AI_Travel_Drive():
'''
Disables usage of travel drives for all ai scripts. When applied to
a save, existing move orders may continue to use travel drive
until they complete.
'''
# Travel drive is part of the move commands, as one of the arguments.
# Can set to false always, to disable use.
# (This appears to only apply to plain move_to?)
aiscript_files = Load_Files(f"*aiscripts/*.xml")
for game_file in aiscript_files:
xml_root = game_file.Get_Root()
file_name = game_file.name.replace('.xml','')
change_occurred = False
for tag in [
#'move_approach_path',
#'move_docking',
#'move_undocking',
#'move_gate',
#'move_navmesh',
#'move_strafe',
#'move_target_points',
#'move_waypoints',
'move_to',
]:
nodes = xml_root.xpath(".//{}".format(tag))
if not nodes:
continue
for node in nodes:
# Check if this uses the travel arg; if not, it defaults to
# false, so no change needed.
if node.get('travel') != None:
node.set('travel', 'false')
change_occurred = True
if change_occurred:
game_file.Update_Root(xml_root)
return
|
#!/usr/bin/env python3
import os
import shutil
import textwrap
from pathlib import Path
import pdoc.render_helpers
here = Path(__file__).parent
if os.environ.get("DOCS_ARCHIVE", False):
edit_url_map = {}
else:
edit_url_map = {
"mitmproxy": "https://github.com/mitmproxy/mitmproxy/blob/main/mitmproxy/",
}
pdoc.render.configure(
template_directory=here / "pdoc-template",
edit_url_map=edit_url_map,
)
# We can't configure Hugo, but we can configure pdoc.
pdoc.render_helpers.formatter.cssclass = "chroma"
modules = [
"mitmproxy.addonmanager",
"mitmproxy.certs",
"mitmproxy.connection",
"mitmproxy.coretypes.multidict",
"mitmproxy.flow",
"mitmproxy.http",
"mitmproxy.net.server_spec",
"mitmproxy.proxy.server_hooks",
"mitmproxy.tcp",
"mitmproxy.websocket",
here / ".." / "src" / "generated" / "events.py",
]
pdoc.pdoc(
*modules,
output_directory=here / ".." / "src" / "generated" / "api"
)
api_content = here / ".." / "src" / "content" / "api"
if api_content.exists():
shutil.rmtree(api_content)
api_content.mkdir()
for module in modules:
if isinstance(module, Path):
continue
filename = f"api/{module.replace(".", "/")}.html"
(api_content / f"{module}.md").write_text(textwrap.dedent(f"""
---
title: "{module}"
url: "{filename}"
menu:
addons:
parent: 'Event Hooks & API'
---
{{{{< readfile file="/generated/{filename}" >}}}}
"""))
(here / ".." / "src" / "content" / "addons-api.md").touch()
| #!/usr/bin/env python3
import os
import shutil
import textwrap
from pathlib import Path
import pdoc.render_helpers
here = Path(__file__).parent
if os.environ.get("DOCS_ARCHIVE", False):
edit_url_map = {}
else:
edit_url_map = {
"mitmproxy": "https://github.com/mitmproxy/mitmproxy/blob/main/mitmproxy/",
}
pdoc.render.configure(
template_directory=here / "pdoc-template",
edit_url_map=edit_url_map,
)
# We can't configure Hugo, but we can configure pdoc.
pdoc.render_helpers.formatter.cssclass = "chroma"
modules = [
"mitmproxy.addonmanager",
"mitmproxy.certs",
"mitmproxy.connection",
"mitmproxy.coretypes.multidict",
"mitmproxy.flow",
"mitmproxy.http",
"mitmproxy.net.server_spec",
"mitmproxy.proxy.server_hooks",
"mitmproxy.tcp",
"mitmproxy.websocket",
here / ".." / "src" / "generated" / "events.py",
]
pdoc.pdoc(
*modules,
output_directory=here / ".." / "src" / "generated" / "api"
)
api_content = here / ".." / "src" / "content" / "api"
if api_content.exists():
shutil.rmtree(api_content)
api_content.mkdir()
for module in modules:
if isinstance(module, Path):
continue
filename = f"api/{module.replace('.', '/')}.html"
(api_content / f"{module}.md").write_text(textwrap.dedent(f"""
---
title: "{module}"
url: "{filename}"
menu:
addons:
parent: 'Event Hooks & API'
---
{{{{< readfile file="/generated/{filename}" >}}}}
"""))
(here / ".." / "src" / "content" / "addons-api.md").touch()
|
import json
class Pdk(object):
def __init__(self):
"""Initialize empty container dict"""
self.pdk = {}
def __str__(self):
ret = ''
for key, value in self.pdk.items():
ret += f"{key}: {value}\n"
return ret
def __contains__(self, key):
return key in self.pdk
def __getitem__(self, key):
"""Act like a read-only dict"""
assert key in self.pdk, key
return self.pdk[key]
def items(self):
"""Manage iterators for read-only dict"""
return self.pdk.items()
def keys(self):
"""Manage iterators for read-only dict"""
return self.pdk.keys()
def values(self):
"""Manage iterators for read-only dict"""
return self.pdk.values()
def load(self, filename):
self.layerfile=filename.resolve()
with open(self.layerfile, "rt") as fp:
j = json.load(fp)
assert 'Abstraction' in j
for layer in j['Abstraction']:
assert layer['Layer'] not in self.pdk, f"Cannot have multiple {layer["Layer"]} layers with same name"
assert layer['Layer'][0].isupper(), f"Layer name {layer["Layer"]} must start with capitalized letter"
if layer['Layer'].startswith('M'):
self.addMetal(**layer)
elif layer['Layer'].startswith('V'):
self.addVia(**layer)
else:
self.add(**layer)
return self
@staticmethod
def _check(parameters, optional_parameters, **kwargs):
assert all( x in kwargs for x in parameters), f"Entry {kwargs} missing one or more of {parameters}"
assert all( (x in parameters) or (x in optional_parameters) for x in kwargs.keys()), f"Entry {kwargs} has one or more spurious entries (Needs only {parameters})"
def _add(self, parameters, **kwargs):
# Guarantee one is to one mapping between parameters & kwargs
layername = kwargs.pop('Layer')
self.pdk[layername] = {key: None if value == 'NA' else value for key, value in kwargs.items()}
def addMetal(self, **kwargs):
optional_params = ['AdjacentAttacker','Space','Stop_point','Stop_pitch','Stop_offset']
params = ['Layer',
'GdsLayerNo',
'GdsDatatype',
'Direction',
'Color',
'Pitch',
'Width',
'MinL',
'MaxL',
'EndToEnd',
'Offset',
'UnitC',
'UnitCC',
'UnitR']
self._check(params, optional_params, **kwargs)
# Attributes that need additional processing
# 0. Dimensions must be integers or None. Pitch & Width must be even.
assert all(all(isinstance(y, int) for y in kwargs[x] if y is not None) \
if isinstance(kwargs[x], list) else isinstance(kwargs[x], int) \
for x in params[5:10] if kwargs[x] is not None), \
f"One or more of {params[5:10]} not an integer in {kwargs}"
assert all(all(y is not None and y % 2 == 0 for y in kwargs[x]) \
if isinstance(kwargs[x], list) else kwargs[x] is not None and kwargs[x] % 2 == 0 \
for x in params[5:6] if kwargs[x] is not None), \
f"One or more of {params[4:6]} in {kwargs} not a multiple of two"
# # Disabled the check below as lists might be of different length for non-uniform metal templates
# # 1. Pitch, Width, MinL, MaxL, EndToEnd of type list
# list_params = ['Pitch', 'Width', 'MinL', 'MaxL', 'EndToEnd', 'UnitC', 'UnitCC', 'UnitR']
# ll = set()
# for param in list_params:
# if isinstance(kwargs[param], list):
# if len(kwargs[param]) == 1:
# kwargs[param] = kwargs[param][0]
# else:
# ll.add(len(kwargs[param]))
# assert len(ll) <= 1, f"All lists in {kwargs} must of be same length"
# if len(ll) == 1:
# ll = ll.pop()
# for param in list_params:
# if not isinstance(kwargs[param], list):
# kwargs[param] = [kwargs[param]] * ll
# 2. Cast direction must be lowercase & ensure it is either v or h
kwargs['Direction'] = kwargs['Direction'].lower()
assert kwargs['Direction'] in ('v', 'h'), f"Invalid Direction {kwargs["Direction"]} in {kwargs}"
self._add(params + optional_params, **kwargs)
def addVia(self, **kwargs):
optional_params = ['ViaCut', 'Pitch', 'Offset']
params = ['Layer',
'GdsLayerNo',
'GdsDatatype',
'Stack',
'SpaceX',
'SpaceY',
'WidthX',
'WidthY',
'VencA_L',
'VencA_H',
'VencP_L',
'VencP_H',
'R']
self._check(params, optional_params, **kwargs)
# Attributes that need additional processing
# 0. Dimensions
assert all(isinstance(kwargs[x], int) for x in params[4:7]), f"One or more of {params[3:7]} not an integer in {kwargs}"
assert all(kwargs[x] % 2 == 0 for x in params[4:7]), f"One or more of {params[4:7]} in {kwargs} not a multiple of two"
# 1. Metal Stack
assert isinstance(kwargs['Stack'], list) and len(kwargs['Stack']) == 2, f"Parameter 'Stack': {kwargs["Stack"]} must be a list of size 2"
assert all(x is None or x in self.pdk for x in kwargs['Stack']), f"One or more of metals {kwargs["Stack"]} not yet defined."
# 2. DesignRules
# TODO: Figure out if we should be specifying positives or negatives
# if isinstance(kwargs['DesignRules'], list):
# for rule in kwargs['DesignRules']:
# self._check(['Name', 'Present', 'Absent'], **rule)
self._add(params, **kwargs)
def add(self, **kwargs):
assert 'Layer' in kwargs, '"Layer" is required parameter for all layers in PDK abstraction'
self._add(None, **kwargs)
def get_via_stack(self):
layer_stack = []
for l, info in self.pdk.items():
if l.startswith('V'):
layer_stack.append( (l, tuple(info['Stack'])) )
return layer_stack
def get_lef_exclude(self):
return {x for x in self.pdk.keys() if (x.startswith('M') or x.startswith('V')) is False}
def get_gds_map(self):
return {x: self.pdk[x]['LayerNo'] for x in self.pdk.keys() if 'LayerNo' in self.pdk[x]}
def get_via_table(self):
def get_direction( m):
dir = self.pdk[m]['Direction'].upper()
assert dir == 'V' or dir == 'H', dir
return dir
def swap_enc( a, p, m):
return (a,p) if get_direction(m) == 'H' else (p,a)
via_table = {}
s = 40
hs = 40//2
for (x,e) in self.pdk.items():
if x.startswith('V') and x != 'V0':
lower = e['Stack'][0]
upper = e['Stack'][1]
(x0, y0) = (hs*e['WidthX'], hs*e['WidthY'])
(elx, ely) = swap_enc(s*e['VencA_L'], s*e['VencP_L'], lower)
(ehx, ehy) = swap_enc(s*e['VencA_H'], s*e['VencP_H'], upper)
via_table.update( {x:(x,
{x:[-x0,-y0, x0, y0],
lower:[-x0-elx,-y0-ely, x0+elx, y0+ely],
upper:[-x0-ehx,-y0-ehy, x0+ehx, y0+ehy]
})})
return via_table
| import json
class Pdk(object):
def __init__(self):
"""Initialize empty container dict"""
self.pdk = {}
def __str__(self):
ret = ''
for key, value in self.pdk.items():
ret += f"{key}: {value}\n"
return ret
def __contains__(self, key):
return key in self.pdk
def __getitem__(self, key):
"""Act like a read-only dict"""
assert key in self.pdk, key
return self.pdk[key]
def items(self):
"""Manage iterators for read-only dict"""
return self.pdk.items()
def keys(self):
"""Manage iterators for read-only dict"""
return self.pdk.keys()
def values(self):
"""Manage iterators for read-only dict"""
return self.pdk.values()
def load(self, filename):
self.layerfile=filename.resolve()
with open(self.layerfile, "rt") as fp:
j = json.load(fp)
assert 'Abstraction' in j
for layer in j['Abstraction']:
assert layer['Layer'] not in self.pdk, f"Cannot have multiple {layer['Layer']} layers with same name"
assert layer['Layer'][0].isupper(), f"Layer name {layer['Layer']} must start with capitalized letter"
if layer['Layer'].startswith('M'):
self.addMetal(**layer)
elif layer['Layer'].startswith('V'):
self.addVia(**layer)
else:
self.add(**layer)
return self
@staticmethod
def _check(parameters, optional_parameters, **kwargs):
assert all( x in kwargs for x in parameters), f"Entry {kwargs} missing one or more of {parameters}"
assert all( (x in parameters) or (x in optional_parameters) for x in kwargs.keys()), f"Entry {kwargs} has one or more spurious entries (Needs only {parameters})"
def _add(self, parameters, **kwargs):
# Guarantee one is to one mapping between parameters & kwargs
layername = kwargs.pop('Layer')
self.pdk[layername] = {key: None if value == 'NA' else value for key, value in kwargs.items()}
def addMetal(self, **kwargs):
optional_params = ['AdjacentAttacker','Space','Stop_point','Stop_pitch','Stop_offset']
params = ['Layer',
'GdsLayerNo',
'GdsDatatype',
'Direction',
'Color',
'Pitch',
'Width',
'MinL',
'MaxL',
'EndToEnd',
'Offset',
'UnitC',
'UnitCC',
'UnitR']
self._check(params, optional_params, **kwargs)
# Attributes that need additional processing
# 0. Dimensions must be integers or None. Pitch & Width must be even.
assert all(all(isinstance(y, int) for y in kwargs[x] if y is not None) \
if isinstance(kwargs[x], list) else isinstance(kwargs[x], int) \
for x in params[5:10] if kwargs[x] is not None), \
f"One or more of {params[5:10]} not an integer in {kwargs}"
assert all(all(y is not None and y % 2 == 0 for y in kwargs[x]) \
if isinstance(kwargs[x], list) else kwargs[x] is not None and kwargs[x] % 2 == 0 \
for x in params[5:6] if kwargs[x] is not None), \
f"One or more of {params[4:6]} in {kwargs} not a multiple of two"
# # Disabled the check below as lists might be of different length for non-uniform metal templates
# # 1. Pitch, Width, MinL, MaxL, EndToEnd of type list
# list_params = ['Pitch', 'Width', 'MinL', 'MaxL', 'EndToEnd', 'UnitC', 'UnitCC', 'UnitR']
# ll = set()
# for param in list_params:
# if isinstance(kwargs[param], list):
# if len(kwargs[param]) == 1:
# kwargs[param] = kwargs[param][0]
# else:
# ll.add(len(kwargs[param]))
# assert len(ll) <= 1, f"All lists in {kwargs} must of be same length"
# if len(ll) == 1:
# ll = ll.pop()
# for param in list_params:
# if not isinstance(kwargs[param], list):
# kwargs[param] = [kwargs[param]] * ll
# 2. Cast direction must be lowercase & ensure it is either v or h
kwargs['Direction'] = kwargs['Direction'].lower()
assert kwargs['Direction'] in ('v', 'h'), f"Invalid Direction {kwargs['Direction']} in {kwargs}"
self._add(params + optional_params, **kwargs)
def addVia(self, **kwargs):
optional_params = ['ViaCut', 'Pitch', 'Offset']
params = ['Layer',
'GdsLayerNo',
'GdsDatatype',
'Stack',
'SpaceX',
'SpaceY',
'WidthX',
'WidthY',
'VencA_L',
'VencA_H',
'VencP_L',
'VencP_H',
'R']
self._check(params, optional_params, **kwargs)
# Attributes that need additional processing
# 0. Dimensions
assert all(isinstance(kwargs[x], int) for x in params[4:7]), f"One or more of {params[3:7]} not an integer in {kwargs}"
assert all(kwargs[x] % 2 == 0 for x in params[4:7]), f"One or more of {params[4:7]} in {kwargs} not a multiple of two"
# 1. Metal Stack
assert isinstance(kwargs['Stack'], list) and len(kwargs['Stack']) == 2, f"Parameter 'Stack': {kwargs['Stack']} must be a list of size 2"
assert all(x is None or x in self.pdk for x in kwargs['Stack']), f"One or more of metals {kwargs['Stack']} not yet defined."
# 2. DesignRules
# TODO: Figure out if we should be specifying positives or negatives
# if isinstance(kwargs['DesignRules'], list):
# for rule in kwargs['DesignRules']:
# self._check(['Name', 'Present', 'Absent'], **rule)
self._add(params, **kwargs)
def add(self, **kwargs):
assert 'Layer' in kwargs, '"Layer" is required parameter for all layers in PDK abstraction'
self._add(None, **kwargs)
def get_via_stack(self):
layer_stack = []
for l, info in self.pdk.items():
if l.startswith('V'):
layer_stack.append( (l, tuple(info['Stack'])) )
return layer_stack
def get_lef_exclude(self):
return {x for x in self.pdk.keys() if (x.startswith('M') or x.startswith('V')) is False}
def get_gds_map(self):
return {x: self.pdk[x]['LayerNo'] for x in self.pdk.keys() if 'LayerNo' in self.pdk[x]}
def get_via_table(self):
def get_direction( m):
dir = self.pdk[m]['Direction'].upper()
assert dir == 'V' or dir == 'H', dir
return dir
def swap_enc( a, p, m):
return (a,p) if get_direction(m) == 'H' else (p,a)
via_table = {}
s = 40
hs = 40//2
for (x,e) in self.pdk.items():
if x.startswith('V') and x != 'V0':
lower = e['Stack'][0]
upper = e['Stack'][1]
(x0, y0) = (hs*e['WidthX'], hs*e['WidthY'])
(elx, ely) = swap_enc(s*e['VencA_L'], s*e['VencP_L'], lower)
(ehx, ehy) = swap_enc(s*e['VencA_H'], s*e['VencP_H'], upper)
via_table.update( {x:(x,
{x:[-x0,-y0, x0, y0],
lower:[-x0-elx,-y0-ely, x0+elx, y0+ely],
upper:[-x0-ehx,-y0-ehy, x0+ehx, y0+ehy]
})})
return via_table
|
import pandas as pd
import numpy as np
from .engineobj import SqPandasEngine
from suzieq.utils import build_query_str, humanize_timestamp
class BgpObj(SqPandasEngine):
@staticmethod
def table_name():
return 'bgp'
def get(self, **kwargs):
"""Replacing the original interface name in returned result"""
addnl_fields = kwargs.pop('addnl_fields', [])
columns = kwargs.get('columns', ['default'])
vrf = kwargs.pop('vrf', None)
peer = kwargs.pop('peer', None)
hostname = kwargs.pop('hostname', None)
user_query = kwargs.pop('query_str', None)
drop_cols = ['origPeer', 'peerHost']
addnl_fields.extend(['origPeer'])
sch = self.schema
fields = sch.get_display_fields(columns)
for col in ['peerIP', 'updateSource', 'state', 'namespace', 'vrf',
'peer', 'hostname']:
if col not in fields:
addnl_fields.append(col)
drop_cols.append(col)
try:
df = super().get(addnl_fields=addnl_fields, **kwargs)
except KeyError as ex:
if ('afi' in str(ex)) or ('safi' in str(ex)):
df = pd.DataFrame(
{'error':
['ERROR: Migrate BGP data first using sq-coalescer']})
return df
if df.empty:
return df
if 'afiSafi' in columns or (columns == ['*']):
df['afiSafi'] = df['afi'] + ' ' + df['safi']
query_str = build_query_str([], sch, vrf=vrf, peer=peer,
hostname=hostname,
ignore_regex=False)
if 'peer' in df.columns:
df['peer'] = np.where(df['origPeer'] != "",
df['origPeer'], df['peer'])
# Convert old data into new 2.0 data format
if 'peerHostname' in df.columns:
mdf = self._get_peer_matched_df(df)
drop_cols = [x for x in drop_cols if x in mdf.columns]
drop_cols.extend(list(mdf.filter(regex='_y')))
else:
mdf = df
mdf = self._handle_user_query_str(mdf, user_query)
if query_str:
return mdf.query(query_str).drop(columns=drop_cols,
errors='ignore')
else:
return mdf.drop(columns=drop_cols, errors='ignore')
def summarize(self, **kwargs) -> pd.DataFrame:
"""Summarize key information about BGP"""
self._init_summarize(self.iobj._table, **kwargs)
if self.summary_df.empty or ('error' in self.summary_df.columns):
return self.summary_df
self.summary_df['afiSafi'] = (
self.summary_df['afi'] + ' ' + self.summary_df['safi'])
afi_safi_count = self.summary_df.groupby(by=['namespace'])['afiSafi'] \
.nunique()
self.summary_df = self.summary_df \
.set_index(['namespace', 'hostname', 'vrf',
'peer']) \
.query('~index.duplicated(keep="last")') \
.reset_index()
self.ns = {i: {} for i in self.summary_df['namespace'].unique()}
self.nsgrp = self.summary_df.groupby(by=["namespace"],
observed=True)
self._summarize_on_add_field = [
('deviceCnt', 'hostname', 'nunique'),
('totalPeerCnt', 'peer', 'count'),
('uniqueAsnCnt', 'asn', 'nunique'),
('uniqueVrfsCnt', 'vrf', 'nunique')
]
self._summarize_on_add_with_query = [
('failedPeerCnt', 'state == "NotEstd"', 'peer'),
('iBGPPeerCnt', 'asn == peerAsn', 'peer'),
('eBGPPeerCnt', 'asn != peerAsn', 'peer'),
('rrClientPeerCnt', 'rrclient.str.lower() == "true"', 'peer',
'count'),
]
self._gen_summarize_data()
{self.ns[i].update({'activeAfiSafiCnt': afi_safi_count[i]})
for i in self.ns.keys()}
self.summary_row_order.append('activeAfiSafiCnt')
self.summary_df['estdTime'] = humanize_timestamp(
self.summary_df.estdTime,
self.cfg.get('analyzer', {}).get('timezone', None))
self.summary_df['estdTime'] = (
self.summary_df['timestamp'] - self.summary_df['estdTime'])
self.summary_df['estdTime'] = self.summary_df['estdTime'] \
.apply(lambda x: x.round('s'))
# Now come the BGP specific ones
established = self.summary_df.query("state == 'Established'") \
.groupby(by=['namespace'])
uptime = established["estdTime"]
rx_updates = established["updatesRx"]
tx_updates = established["updatesTx"]
self._add_stats_to_summary(uptime, 'upTimeStat')
self._add_stats_to_summary(rx_updates, 'updatesRxStat')
self._add_stats_to_summary(tx_updates, 'updatesTxStat')
self.summary_row_order.extend(['upTimeStat', 'updatesRxStat',
'updatesTxStat'])
self._post_summarize()
return self.ns_df.convert_dtypes()
def _get_peer_matched_df(self, df) -> pd.DataFrame:
"""Get a BGP dataframe that also contains a session's matching peer"""
if 'peerHostname' not in df.columns:
return df
# We have to separate out the Established and non Established entries
# for the merge. Otherwise we end up with a mess
df_1 = df[['namespace', 'hostname', 'vrf', 'peer', 'peerIP',
'updateSource']] \
.drop_duplicates() \
.reset_index(drop=True)
df_2 = df[['namespace', 'hostname', 'vrf', 'updateSource']] \
.drop_duplicates() \
.reset_index(drop=True)
mdf = df_1.merge(df_2,
left_on=['namespace', 'peerIP'],
right_on=['namespace', 'updateSource'],
suffixes=('', '_y')) \
.drop_duplicates(subset=['namespace', 'hostname', 'vrf',
'peerIP']) \
.rename(columns={'hostname_y': 'peerHost'}) \
.fillna(value={'peerHostname': '', 'peerHost': ''}) \
.reset_index(drop=True)
df = df.merge(mdf[['namespace', 'hostname', 'vrf', 'peer',
'peerHost']],
on=['namespace', 'hostname', 'vrf', 'peer'], how='left')
df['peerHostname'] = np.where((df['peerHostname'] == '') &
(df['state'] == "Established"),
df['peerHost'],
df['peerHostname'])
df = df.fillna(value={'peerHostname': ''}) \
.drop(columns=['peerHost'])
for i in df.select_dtypes(include='category'):
df[i].cat.add_categories('', inplace=True)
return df
def aver(self, **kwargs) -> pd.DataFrame:
"""BGP Assert"""
def _check_if_state(row, if_df):
if not if_df.empty:
thisif = if_df.query(f'namespace=="{row.namespace}" and '
f'hostname=="{row.hostname}" and '
f'ifname=="{row.ifname}"')
if not thisif.empty:
if thisif.adminState.unique()[0] != 'up':
return ['interface admin down']
elif thisif.state.unique()[0] != 'up':
return ['interface down']
else:
return []
return []
assert_cols = ["namespace", "hostname", "vrf", "peer", "peerHostname",
"afi", "safi", "asn", "state", "peerAsn", "bfdStatus",
"reason", "notificnReason", "afisAdvOnly", 'ifname',
"afisRcvOnly", "peerIP", "updateSource", "timestamp"]
kwargs.pop("columns", None) # Loose whatever's passed
status = kwargs.pop("status", 'all')
df = self.get(columns=assert_cols, state='!dynamic', **kwargs)
if 'error' in df:
return df
if df.empty:
if status != "pass":
df['assert'] = 'fail'
df['assertReason'] = 'No data'
return df
df = self._get_peer_matched_df(df)
if df.empty:
if status != "pass":
df['assert'] = 'fail'
df['assertReason'] = 'No data'
return df
# We can get rid of sessions with duplicate peer info since we're
# interested only in session info here
df = df.drop_duplicates(
subset=['namespace', 'hostname', 'vrf', 'peer'])
failed_df = df.query("state != 'Established'").reset_index(drop=True)
passed_df = df.query("state == 'Established'").reset_index(drop=True)
# Get the interface information
if_df = self._get_table_sqobj('interfaces').get(
namespace=failed_df.namespace.unique().tolist(),
hostname=failed_df.hostname.unique().tolist(),
ifname=failed_df.ifname.unique().tolist(),
columns=['namespace', 'hostname', 'ifname', 'state', 'adminState']
)
failed_df['assertReason'] = [[] for _ in range(len(failed_df))]
passed_df['assertReason'] = [[] for _ in range(len(passed_df))]
if not failed_df.empty:
# For not established entries, check if route/ARP entry exists
failed_df['assertReason'] += failed_df.apply(
lambda x, ifdf: _check_if_state(x, ifdf),
args=(if_df,), axis=1)
failed_df['assertReason'] += failed_df.apply(
lambda x: ["asn mismatch"]
if (x['peerHostname'] and ((x["asn"] != x["peerAsn_y"]) or
(x['asn_y'] != x['peerAsn'])))
else [], axis=1)
failed_df['assertReason'] += failed_df.apply(
lambda x: [f"{x["reason"]}:{x["notificnReason"]}"]
if ((x['reason'] and x['reason'] != 'None' and
x['reason'] != "No error"))
else [], axis=1)
# Get list of peer IP addresses for peer not in Established state
# Returning to performing checks even if we didn't get LLDP/Intf info
passed_df['assertReason'] += passed_df.apply(
lambda x: ['Not all Afi/Safis enabled']
if x['afisAdvOnly'].any() or x['afisRcvOnly'].any() else [],
axis=1)
df = pd.concat([failed_df, passed_df])
df['assert'] = df.apply(lambda x: 'pass'
if not len(x.assertReason) else 'fail',
axis=1)
result = df[['namespace', 'hostname', 'vrf', 'peer', 'asn',
'peerAsn', 'state', 'peerHostname', 'assert',
'assertReason', 'timestamp']] \
.explode(column="assertReason") \
.fillna({'assertReason': '-'})
if status == "fail":
return result.query('assertReason != "-"')
elif status == "pass":
return result.query('assertReason == "-"')
return result
| import pandas as pd
import numpy as np
from .engineobj import SqPandasEngine
from suzieq.utils import build_query_str, humanize_timestamp
class BgpObj(SqPandasEngine):
@staticmethod
def table_name():
return 'bgp'
def get(self, **kwargs):
"""Replacing the original interface name in returned result"""
addnl_fields = kwargs.pop('addnl_fields', [])
columns = kwargs.get('columns', ['default'])
vrf = kwargs.pop('vrf', None)
peer = kwargs.pop('peer', None)
hostname = kwargs.pop('hostname', None)
user_query = kwargs.pop('query_str', None)
drop_cols = ['origPeer', 'peerHost']
addnl_fields.extend(['origPeer'])
sch = self.schema
fields = sch.get_display_fields(columns)
for col in ['peerIP', 'updateSource', 'state', 'namespace', 'vrf',
'peer', 'hostname']:
if col not in fields:
addnl_fields.append(col)
drop_cols.append(col)
try:
df = super().get(addnl_fields=addnl_fields, **kwargs)
except KeyError as ex:
if ('afi' in str(ex)) or ('safi' in str(ex)):
df = pd.DataFrame(
{'error':
['ERROR: Migrate BGP data first using sq-coalescer']})
return df
if df.empty:
return df
if 'afiSafi' in columns or (columns == ['*']):
df['afiSafi'] = df['afi'] + ' ' + df['safi']
query_str = build_query_str([], sch, vrf=vrf, peer=peer,
hostname=hostname,
ignore_regex=False)
if 'peer' in df.columns:
df['peer'] = np.where(df['origPeer'] != "",
df['origPeer'], df['peer'])
# Convert old data into new 2.0 data format
if 'peerHostname' in df.columns:
mdf = self._get_peer_matched_df(df)
drop_cols = [x for x in drop_cols if x in mdf.columns]
drop_cols.extend(list(mdf.filter(regex='_y')))
else:
mdf = df
mdf = self._handle_user_query_str(mdf, user_query)
if query_str:
return mdf.query(query_str).drop(columns=drop_cols,
errors='ignore')
else:
return mdf.drop(columns=drop_cols, errors='ignore')
def summarize(self, **kwargs) -> pd.DataFrame:
"""Summarize key information about BGP"""
self._init_summarize(self.iobj._table, **kwargs)
if self.summary_df.empty or ('error' in self.summary_df.columns):
return self.summary_df
self.summary_df['afiSafi'] = (
self.summary_df['afi'] + ' ' + self.summary_df['safi'])
afi_safi_count = self.summary_df.groupby(by=['namespace'])['afiSafi'] \
.nunique()
self.summary_df = self.summary_df \
.set_index(['namespace', 'hostname', 'vrf',
'peer']) \
.query('~index.duplicated(keep="last")') \
.reset_index()
self.ns = {i: {} for i in self.summary_df['namespace'].unique()}
self.nsgrp = self.summary_df.groupby(by=["namespace"],
observed=True)
self._summarize_on_add_field = [
('deviceCnt', 'hostname', 'nunique'),
('totalPeerCnt', 'peer', 'count'),
('uniqueAsnCnt', 'asn', 'nunique'),
('uniqueVrfsCnt', 'vrf', 'nunique')
]
self._summarize_on_add_with_query = [
('failedPeerCnt', 'state == "NotEstd"', 'peer'),
('iBGPPeerCnt', 'asn == peerAsn', 'peer'),
('eBGPPeerCnt', 'asn != peerAsn', 'peer'),
('rrClientPeerCnt', 'rrclient.str.lower() == "true"', 'peer',
'count'),
]
self._gen_summarize_data()
{self.ns[i].update({'activeAfiSafiCnt': afi_safi_count[i]})
for i in self.ns.keys()}
self.summary_row_order.append('activeAfiSafiCnt')
self.summary_df['estdTime'] = humanize_timestamp(
self.summary_df.estdTime,
self.cfg.get('analyzer', {}).get('timezone', None))
self.summary_df['estdTime'] = (
self.summary_df['timestamp'] - self.summary_df['estdTime'])
self.summary_df['estdTime'] = self.summary_df['estdTime'] \
.apply(lambda x: x.round('s'))
# Now come the BGP specific ones
established = self.summary_df.query("state == 'Established'") \
.groupby(by=['namespace'])
uptime = established["estdTime"]
rx_updates = established["updatesRx"]
tx_updates = established["updatesTx"]
self._add_stats_to_summary(uptime, 'upTimeStat')
self._add_stats_to_summary(rx_updates, 'updatesRxStat')
self._add_stats_to_summary(tx_updates, 'updatesTxStat')
self.summary_row_order.extend(['upTimeStat', 'updatesRxStat',
'updatesTxStat'])
self._post_summarize()
return self.ns_df.convert_dtypes()
def _get_peer_matched_df(self, df) -> pd.DataFrame:
"""Get a BGP dataframe that also contains a session's matching peer"""
if 'peerHostname' not in df.columns:
return df
# We have to separate out the Established and non Established entries
# for the merge. Otherwise we end up with a mess
df_1 = df[['namespace', 'hostname', 'vrf', 'peer', 'peerIP',
'updateSource']] \
.drop_duplicates() \
.reset_index(drop=True)
df_2 = df[['namespace', 'hostname', 'vrf', 'updateSource']] \
.drop_duplicates() \
.reset_index(drop=True)
mdf = df_1.merge(df_2,
left_on=['namespace', 'peerIP'],
right_on=['namespace', 'updateSource'],
suffixes=('', '_y')) \
.drop_duplicates(subset=['namespace', 'hostname', 'vrf',
'peerIP']) \
.rename(columns={'hostname_y': 'peerHost'}) \
.fillna(value={'peerHostname': '', 'peerHost': ''}) \
.reset_index(drop=True)
df = df.merge(mdf[['namespace', 'hostname', 'vrf', 'peer',
'peerHost']],
on=['namespace', 'hostname', 'vrf', 'peer'], how='left')
df['peerHostname'] = np.where((df['peerHostname'] == '') &
(df['state'] == "Established"),
df['peerHost'],
df['peerHostname'])
df = df.fillna(value={'peerHostname': ''}) \
.drop(columns=['peerHost'])
for i in df.select_dtypes(include='category'):
df[i].cat.add_categories('', inplace=True)
return df
def aver(self, **kwargs) -> pd.DataFrame:
"""BGP Assert"""
def _check_if_state(row, if_df):
if not if_df.empty:
thisif = if_df.query(f'namespace=="{row.namespace}" and '
f'hostname=="{row.hostname}" and '
f'ifname=="{row.ifname}"')
if not thisif.empty:
if thisif.adminState.unique()[0] != 'up':
return ['interface admin down']
elif thisif.state.unique()[0] != 'up':
return ['interface down']
else:
return []
return []
assert_cols = ["namespace", "hostname", "vrf", "peer", "peerHostname",
"afi", "safi", "asn", "state", "peerAsn", "bfdStatus",
"reason", "notificnReason", "afisAdvOnly", 'ifname',
"afisRcvOnly", "peerIP", "updateSource", "timestamp"]
kwargs.pop("columns", None) # Loose whatever's passed
status = kwargs.pop("status", 'all')
df = self.get(columns=assert_cols, state='!dynamic', **kwargs)
if 'error' in df:
return df
if df.empty:
if status != "pass":
df['assert'] = 'fail'
df['assertReason'] = 'No data'
return df
df = self._get_peer_matched_df(df)
if df.empty:
if status != "pass":
df['assert'] = 'fail'
df['assertReason'] = 'No data'
return df
# We can get rid of sessions with duplicate peer info since we're
# interested only in session info here
df = df.drop_duplicates(
subset=['namespace', 'hostname', 'vrf', 'peer'])
failed_df = df.query("state != 'Established'").reset_index(drop=True)
passed_df = df.query("state == 'Established'").reset_index(drop=True)
# Get the interface information
if_df = self._get_table_sqobj('interfaces').get(
namespace=failed_df.namespace.unique().tolist(),
hostname=failed_df.hostname.unique().tolist(),
ifname=failed_df.ifname.unique().tolist(),
columns=['namespace', 'hostname', 'ifname', 'state', 'adminState']
)
failed_df['assertReason'] = [[] for _ in range(len(failed_df))]
passed_df['assertReason'] = [[] for _ in range(len(passed_df))]
if not failed_df.empty:
# For not established entries, check if route/ARP entry exists
failed_df['assertReason'] += failed_df.apply(
lambda x, ifdf: _check_if_state(x, ifdf),
args=(if_df,), axis=1)
failed_df['assertReason'] += failed_df.apply(
lambda x: ["asn mismatch"]
if (x['peerHostname'] and ((x["asn"] != x["peerAsn_y"]) or
(x['asn_y'] != x['peerAsn'])))
else [], axis=1)
failed_df['assertReason'] += failed_df.apply(
lambda x: [f"{x['reason']}:{x['notificnReason']}"]
if ((x['reason'] and x['reason'] != 'None' and
x['reason'] != "No error"))
else [], axis=1)
# Get list of peer IP addresses for peer not in Established state
# Returning to performing checks even if we didn't get LLDP/Intf info
passed_df['assertReason'] += passed_df.apply(
lambda x: ['Not all Afi/Safis enabled']
if x['afisAdvOnly'].any() or x['afisRcvOnly'].any() else [],
axis=1)
df = pd.concat([failed_df, passed_df])
df['assert'] = df.apply(lambda x: 'pass'
if not len(x.assertReason) else 'fail',
axis=1)
result = df[['namespace', 'hostname', 'vrf', 'peer', 'asn',
'peerAsn', 'state', 'peerHostname', 'assert',
'assertReason', 'timestamp']] \
.explode(column="assertReason") \
.fillna({'assertReason': '-'})
if status == "fail":
return result.query('assertReason != "-"')
elif status == "pass":
return result.query('assertReason == "-"')
return result
|
import os
import requests as r
def urs_authenticate():
# AUTHENTICATION CONFIGURATION
from netrc import netrc
from subprocess import Popen
from getpass import getpass
urs = 'urs.earthdata.nasa.gov' # Earthdata URL to call for authentication
prompts = ['Enter NASA Earthdata Login Username \n(or create an account at urs.earthdata.nasa.gov): ',
'Enter NASA Earthdata Login Password: ']
# Determine if netrc file exists, and if so, if it includes NASA Earthdata Login Credentials
try:
netrcDir = os.path.expanduser("~/.netrc")
netrc(netrcDir).authenticators(urs)[0]
del netrcDir
# Below, create a netrc file and prompt user for NASA Earthdata Login Username and Password
except FileNotFoundError:
homeDir = os.path.expanduser("~")
Popen('touch {0}.netrc | chmod og-rw {0}.netrc | echo machine {1} >> {0}.netrc'.format(homeDir + os.sep, urs), shell=True)
Popen('echo login {} >> {}.netrc'.format(getpass(prompt=prompts[0]), homeDir + os.sep), shell=True)
Popen('echo password {} >> {}.netrc'.format(getpass(prompt=prompts[1]), homeDir + os.sep), shell=True)
del homeDir
# Determine OS and edit netrc file if it exists but is not set up for NASA Earthdata Login
except TypeError:
homeDir = os.path.expanduser("~")
Popen('echo machine {1} >> {0}.netrc'.format(homeDir + os.sep, urs), shell=True)
Popen('echo login {} >> {}.netrc'.format(getpass(prompt=prompts[0]), homeDir + os.sep), shell=True)
Popen('echo password {} >> {}.netrc'.format(getpass(prompt=prompts[1]), homeDir + os.sep), shell=True)
del homeDir
del urs, prompts
def simple_hls_stac_search(bbox, date_time = "2020-10-01T00:00:00Z/2020-10-31T23:31:12Z"):
stac = 'https://cmr.earthdata.nasa.gov/stac/' # CMR-STAC API Endpoint
stac_response = r.get(stac).json() # Call the STAC API endpoint
stac_lp = [s for s in stac_response['links'] if 'LP' in s['title']]
lp_cloud = r.get([s for s in stac_lp if s['title'] == 'LPCLOUD'][0]['href']).json()
lp_links = lp_cloud['links']
lp_search = [l['href'] for l in lp_links if l['rel'] == 'search'][0] # Define the search endpoint
lim = 100
search_query = f"{lp_search}?&limit={lim}" # Add in a limit parameter to retrieve 100 items at a time.
search_query2 = f"{search_query}&bbox={bbox}" # Add bbox to query
#Sdate_time = "2020-10-01T00:00:00Z/2020-10-31T23:31:12Z" # Define start time period / end time period
search_query3 = f"{search_query2}&datetime={date_time}" # Add to query that already includes bounding_box
search_response = r.get(search_query3).json()
print(f"{len(search_response["features"])} items found!")
FEATURES = search_response['features']
return (FEATURES)
| import os
import requests as r
def urs_authenticate():
# AUTHENTICATION CONFIGURATION
from netrc import netrc
from subprocess import Popen
from getpass import getpass
urs = 'urs.earthdata.nasa.gov' # Earthdata URL to call for authentication
prompts = ['Enter NASA Earthdata Login Username \n(or create an account at urs.earthdata.nasa.gov): ',
'Enter NASA Earthdata Login Password: ']
# Determine if netrc file exists, and if so, if it includes NASA Earthdata Login Credentials
try:
netrcDir = os.path.expanduser("~/.netrc")
netrc(netrcDir).authenticators(urs)[0]
del netrcDir
# Below, create a netrc file and prompt user for NASA Earthdata Login Username and Password
except FileNotFoundError:
homeDir = os.path.expanduser("~")
Popen('touch {0}.netrc | chmod og-rw {0}.netrc | echo machine {1} >> {0}.netrc'.format(homeDir + os.sep, urs), shell=True)
Popen('echo login {} >> {}.netrc'.format(getpass(prompt=prompts[0]), homeDir + os.sep), shell=True)
Popen('echo password {} >> {}.netrc'.format(getpass(prompt=prompts[1]), homeDir + os.sep), shell=True)
del homeDir
# Determine OS and edit netrc file if it exists but is not set up for NASA Earthdata Login
except TypeError:
homeDir = os.path.expanduser("~")
Popen('echo machine {1} >> {0}.netrc'.format(homeDir + os.sep, urs), shell=True)
Popen('echo login {} >> {}.netrc'.format(getpass(prompt=prompts[0]), homeDir + os.sep), shell=True)
Popen('echo password {} >> {}.netrc'.format(getpass(prompt=prompts[1]), homeDir + os.sep), shell=True)
del homeDir
del urs, prompts
def simple_hls_stac_search(bbox, date_time = "2020-10-01T00:00:00Z/2020-10-31T23:31:12Z"):
stac = 'https://cmr.earthdata.nasa.gov/stac/' # CMR-STAC API Endpoint
stac_response = r.get(stac).json() # Call the STAC API endpoint
stac_lp = [s for s in stac_response['links'] if 'LP' in s['title']]
lp_cloud = r.get([s for s in stac_lp if s['title'] == 'LPCLOUD'][0]['href']).json()
lp_links = lp_cloud['links']
lp_search = [l['href'] for l in lp_links if l['rel'] == 'search'][0] # Define the search endpoint
lim = 100
search_query = f"{lp_search}?&limit={lim}" # Add in a limit parameter to retrieve 100 items at a time.
search_query2 = f"{search_query}&bbox={bbox}" # Add bbox to query
#Sdate_time = "2020-10-01T00:00:00Z/2020-10-31T23:31:12Z" # Define start time period / end time period
search_query3 = f"{search_query2}&datetime={date_time}" # Add to query that already includes bounding_box
search_response = r.get(search_query3).json()
print(f"{len(search_response['features'])} items found!")
FEATURES = search_response['features']
return (FEATURES)
|
import pandas as pd
import logging
from datetime import datetime
from datetime import timedelta
from typing import Union
def validate_name_dob(dict_id: dict, flight_manifest: pd.DataFrame) -> pd.DataFrame:
# get idx where name matches, if more than one, check dob
idx_name = flight_manifest.query(
f"name == '{(name := dict_id.get("full_name"))}'"
).index
# if idx_match none, raise error
if idx_name.empty:
logging.warning(f"Name {name} not found in flight manifest. Check name.")
return False
if len(idx_name) > 1:
logging.warning(f"Multiple names {name} found in flight manifest.")
# TODO: handle multiple matches
return False
# validate dob
elif len(idx_name) == 1:
if (
all(
(dob_manifest := flight_manifest.loc[idx_name].birthdate.dt.date)
== (dob := dict_id.get("dob"))
)
is True
):
logging.info(f"Validated: {name}, {dob}")
return True
else:
logging.warning(
f"{dob} does not match {name}'s dob in manifest, {dob_manifest}."
)
return False
else:
logging.warning(f"{name} not found in flight manifest.")
return False
def validate_boardingpass(
dict_boardingpass: dict, flight_manifest: pd.DataFrame
) -> bool:
# validate boarding pass
dict_reference = flight_manifest.query(
f"name == '{(dict_boardingpass.get("name"))}'"
).to_dict(orient="records")[0]
# name
valid_boarding_name = dict_reference["name"] == dict_boardingpass.get("name")
# seat
valid_boarding_seat = dict_reference["seat"] == dict_boardingpass.get("seat")
# flight id
valid_boarding_flight = dict_reference["flight_number"] == (
dict_boardingpass["airline"] + "-" + dict_boardingpass["flight_number"]
)
# origin
valid_boarding_origin = dict_reference["origin"] == dict_boardingpass.get("origin")
# destination
valid_boarding_destination = dict_reference["destination"] == dict_boardingpass.get(
"destination"
)
# flight date
valid_boarding_date = (
dict_reference["flight_date"].strftime("%d.%m") == dict_boardingpass["date"]
)
# flight time (boarding + 30 min)
dict_reference["flight_boarding"] = (
datetime.strptime(dict_reference["flight_time"], "%H:%M")
- timedelta(minutes=30)
).strftime("%H:%M")
valid_boarding_time = (
dict_reference["flight_boarding"] == dict_boardingpass["flight_boarding"]
)
if all(
[
valid_boarding_name,
valid_boarding_seat,
valid_boarding_flight,
valid_boarding_origin,
valid_boarding_destination,
valid_boarding_date,
valid_boarding_time,
]
):
logging.info("Boarding pass is valid.")
return True
else:
logging.warning(
f"One or more item from boarding pass is invalid: {dict_reference}, {dict_boardingpass}"
)
return False
def validate_face(dict_face: dict, confidence_min: float = 0.6) -> bool:
if (
dict_face.get("face_is_identical")
and dict_face.get("confidence") > confidence_min
):
logging.info("Person validated. Face from video matches with ID photo.")
return True
else:
return False
def has_no_lighter(result: dict, detect_threshold: float = 0.2) -> bool:
if (
probability := result.get("probabilities_topn").get("lighter")[0]
) > detect_threshold:
logging.info(f"Lighter detected with probability {probability}")
return False
else:
logging.info(f"No lighter detected with probability {probability}")
return True
def update_manifest(
flight_manifest: pd.DataFrame,
idx: pd.core.indexes.numeric.Int64Index,
column_update: Union[str, list],
) -> pd.DataFrame:
flight_manifest.loc[idx, column_update] = True
logging.info(f"Set {column_update} True.")
return flight_manifest
def pipeline_validate(
flight_manifest: pd.DataFrame,
dict_id: dict,
dict_boardingpass: dict,
dict_face: dict,
dict_lighter: dict,
):
"""Validation based on detection results"""
idx = flight_manifest.loc[flight_manifest.name == dict_id.get("full_name"), :].index
if len(idx) == 0:
logging.error(f"{dict_id.get("full_name")} not found in manifest.")
return None
if validate_name_dob(dict_id, flight_manifest):
update_manifest(flight_manifest, idx, ["valid_dob", "valid_name"])
if validate_boardingpass(dict_boardingpass, flight_manifest):
update_manifest(flight_manifest, idx, "valid_boardingpass")
if validate_face(dict_face):
update_manifest(flight_manifest, idx, "valid_person")
if has_no_lighter(dict_lighter):
update_manifest(flight_manifest, idx, "valid_luggage")
flight_manifest.loc[idx].to_csv(
filepath := f"data/validated/flight_manifest_{idx[0]}.csv", index=False
)
logging.info(
f"Saved validated manifest for {dict_id.get("full_name")} to {filepath}"
)
return flight_manifest.loc[idx]
def message_to_passenger(passenger_manifest) -> None:
df = passenger_manifest.iloc[0]
if (df.filter(like="valid") * 1).sum() >= 3:
logging.info("Flight manifest is valid.")
print(
f"""
Dear {df.loc['name']},
You are welcome to flight {df.loc['flight_number']} departing at {df.loc['flight_time']} from San Francisco to Chicago.
Your seat number is {df.loc['seat']}, and it is confirmed.
Your identity is verified so please board the plane.
"""
)
if (df.filter(like="valid") * 1).sum() < 3:
print(
"""
Dear Sir/Madam,
Some of the information in your boarding pass does not match the flight manifest data, so you cannot board the plane.
Please see a customer service representative.
"""
)
if not df.loc["valid_luggage"]:
print(
"""
CAUTION
We have found a prohibited item in your carry-on baggage, and it is flagged for removal. Please remove it.
"""
)
if not df.loc["valid_boardingpass"]:
print(
"""
Dear Sir/Madam,
Some of the information on your ID card does not match the flight manifest data, so you cannot board the plane.
Please see a customer service representative.
"""
)
| import pandas as pd
import logging
from datetime import datetime
from datetime import timedelta
from typing import Union
def validate_name_dob(dict_id: dict, flight_manifest: pd.DataFrame) -> pd.DataFrame:
# get idx where name matches, if more than one, check dob
idx_name = flight_manifest.query(
f"name == '{(name := dict_id.get('full_name'))}'"
).index
# if idx_match none, raise error
if idx_name.empty:
logging.warning(f"Name {name} not found in flight manifest. Check name.")
return False
if len(idx_name) > 1:
logging.warning(f"Multiple names {name} found in flight manifest.")
# TODO: handle multiple matches
return False
# validate dob
elif len(idx_name) == 1:
if (
all(
(dob_manifest := flight_manifest.loc[idx_name].birthdate.dt.date)
== (dob := dict_id.get("dob"))
)
is True
):
logging.info(f"Validated: {name}, {dob}")
return True
else:
logging.warning(
f"{dob} does not match {name}'s dob in manifest, {dob_manifest}."
)
return False
else:
logging.warning(f"{name} not found in flight manifest.")
return False
def validate_boardingpass(
dict_boardingpass: dict, flight_manifest: pd.DataFrame
) -> bool:
# validate boarding pass
dict_reference = flight_manifest.query(
f"name == '{(dict_boardingpass.get('name'))}'"
).to_dict(orient="records")[0]
# name
valid_boarding_name = dict_reference["name"] == dict_boardingpass.get("name")
# seat
valid_boarding_seat = dict_reference["seat"] == dict_boardingpass.get("seat")
# flight id
valid_boarding_flight = dict_reference["flight_number"] == (
dict_boardingpass["airline"] + "-" + dict_boardingpass["flight_number"]
)
# origin
valid_boarding_origin = dict_reference["origin"] == dict_boardingpass.get("origin")
# destination
valid_boarding_destination = dict_reference["destination"] == dict_boardingpass.get(
"destination"
)
# flight date
valid_boarding_date = (
dict_reference["flight_date"].strftime("%d.%m") == dict_boardingpass["date"]
)
# flight time (boarding + 30 min)
dict_reference["flight_boarding"] = (
datetime.strptime(dict_reference["flight_time"], "%H:%M")
- timedelta(minutes=30)
).strftime("%H:%M")
valid_boarding_time = (
dict_reference["flight_boarding"] == dict_boardingpass["flight_boarding"]
)
if all(
[
valid_boarding_name,
valid_boarding_seat,
valid_boarding_flight,
valid_boarding_origin,
valid_boarding_destination,
valid_boarding_date,
valid_boarding_time,
]
):
logging.info("Boarding pass is valid.")
return True
else:
logging.warning(
f"One or more item from boarding pass is invalid: {dict_reference}, {dict_boardingpass}"
)
return False
def validate_face(dict_face: dict, confidence_min: float = 0.6) -> bool:
if (
dict_face.get("face_is_identical")
and dict_face.get("confidence") > confidence_min
):
logging.info("Person validated. Face from video matches with ID photo.")
return True
else:
return False
def has_no_lighter(result: dict, detect_threshold: float = 0.2) -> bool:
if (
probability := result.get("probabilities_topn").get("lighter")[0]
) > detect_threshold:
logging.info(f"Lighter detected with probability {probability}")
return False
else:
logging.info(f"No lighter detected with probability {probability}")
return True
def update_manifest(
flight_manifest: pd.DataFrame,
idx: pd.core.indexes.numeric.Int64Index,
column_update: Union[str, list],
) -> pd.DataFrame:
flight_manifest.loc[idx, column_update] = True
logging.info(f"Set {column_update} True.")
return flight_manifest
def pipeline_validate(
flight_manifest: pd.DataFrame,
dict_id: dict,
dict_boardingpass: dict,
dict_face: dict,
dict_lighter: dict,
):
"""Validation based on detection results"""
idx = flight_manifest.loc[flight_manifest.name == dict_id.get("full_name"), :].index
if len(idx) == 0:
logging.error(f"{dict_id.get('full_name')} not found in manifest.")
return None
if validate_name_dob(dict_id, flight_manifest):
update_manifest(flight_manifest, idx, ["valid_dob", "valid_name"])
if validate_boardingpass(dict_boardingpass, flight_manifest):
update_manifest(flight_manifest, idx, "valid_boardingpass")
if validate_face(dict_face):
update_manifest(flight_manifest, idx, "valid_person")
if has_no_lighter(dict_lighter):
update_manifest(flight_manifest, idx, "valid_luggage")
flight_manifest.loc[idx].to_csv(
filepath := f"data/validated/flight_manifest_{idx[0]}.csv", index=False
)
logging.info(
f"Saved validated manifest for {dict_id.get('full_name')} to {filepath}"
)
return flight_manifest.loc[idx]
def message_to_passenger(passenger_manifest) -> None:
df = passenger_manifest.iloc[0]
if (df.filter(like="valid") * 1).sum() >= 3:
logging.info("Flight manifest is valid.")
print(
f"""
Dear {df.loc['name']},
You are welcome to flight {df.loc['flight_number']} departing at {df.loc['flight_time']} from San Francisco to Chicago.
Your seat number is {df.loc['seat']}, and it is confirmed.
Your identity is verified so please board the plane.
"""
)
if (df.filter(like="valid") * 1).sum() < 3:
print(
"""
Dear Sir/Madam,
Some of the information in your boarding pass does not match the flight manifest data, so you cannot board the plane.
Please see a customer service representative.
"""
)
if not df.loc["valid_luggage"]:
print(
"""
CAUTION
We have found a prohibited item in your carry-on baggage, and it is flagged for removal. Please remove it.
"""
)
if not df.loc["valid_boardingpass"]:
print(
"""
Dear Sir/Madam,
Some of the information on your ID card does not match the flight manifest data, so you cannot board the plane.
Please see a customer service representative.
"""
)
|
# Copyright 2017 Alethea Katherine Flowers
#
# 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 argparse
import ast
import collections.abc
import itertools
from collections import OrderedDict
from typing import (
Any,
Iterable,
Iterator,
List,
Mapping,
Optional,
Sequence,
Set,
Tuple,
Union,
)
from nox._decorators import Call, Func
from nox.sessions import Session, SessionRunner
WARN_PYTHONS_IGNORED = "python_ignored"
def _unique_list(*args: str) -> List[str]:
"""Return a list without duplicates, while preserving order."""
return list(OrderedDict.fromkeys(args))
class Manifest:
"""Session manifest.
The session manifest provides the source of truth for the sequence of
sessions that should be run by nox.
It is possible for this to be mutated during execution. This allows for
useful use cases, such as for one session to "notify" another or
"chain" to another.
Args:
session_functions (Mapping[str, function]): The registry of discovered
session functions.
global_config (.nox.main.GlobalConfig): The global configuration.
module_docstring (Optional[str]): The user noxfile.py docstring.
Defaults to `None`.
"""
def __init__(
self,
session_functions: Mapping[str, "Func"],
global_config: argparse.Namespace,
module_docstring: Optional[str] = None,
) -> None:
self._all_sessions = [] # type: List[SessionRunner]
self._queue = [] # type: List[SessionRunner]
self._consumed = [] # type: List[SessionRunner]
self._config = global_config # type: argparse.Namespace
self.module_docstring = module_docstring # type: Optional[str]
# Create the sessions based on the provided session functions.
for name, func in session_functions.items():
for session in self.make_session(name, func):
self.add_session(session)
def __contains__(self, needle: Union[str, SessionRunner]) -> bool:
if needle in self._queue or needle in self._consumed:
return True
for session in self._queue + self._consumed:
if session.name == needle or needle in session.signatures:
return True
return False
def __iter__(self) -> "Manifest":
return self
def __getitem__(self, key: str) -> SessionRunner:
for session in self._queue + self._consumed:
if session.name == key or key in session.signatures:
return session
raise KeyError(key)
def __next__(self) -> SessionRunner:
"""Return the next item in the queue.
Raises:
StopIteration: If the queue has been entirely consumed.
"""
if not len(self._queue):
raise StopIteration
session = self._queue.pop(0)
self._consumed.append(session)
return session
def __len__(self) -> int:
return len(self._queue) + len(self._consumed)
def list_all_sessions(self) -> Iterator[Tuple[SessionRunner, bool]]:
"""Yields all sessions and whether or not they're selected."""
for session in self._all_sessions:
yield session, session in self._queue
def add_session(self, session: SessionRunner) -> None:
"""Add the given session to the manifest.
Args:
session (~nox.sessions.Session): A session object, such as
one returned from ``make_session``.
"""
if session not in self._all_sessions:
self._all_sessions.append(session)
if session not in self._queue:
self._queue.append(session)
def filter_by_name(self, specified_sessions: Iterable[str]) -> None:
"""Filter sessions in the queue based on the user-specified names.
Args:
specified_sessions (Sequence[str]): A list of specified
session names.
Raises:
KeyError: If any explicitly listed sessions are not found.
"""
# Filter the sessions remaining in the queue based on
# whether they are individually specified.
queue = []
for session_name in specified_sessions:
for session in self._queue:
if _normalized_session_match(session_name, session):
queue.append(session)
self._queue = queue
# If a session was requested and was not found, complain loudly.
all_sessions = set(
map(
_normalize_arg,
(
itertools.chain(
[x.name for x in self._all_sessions if x.name],
*[x.signatures for x in self._all_sessions],
)
),
)
)
missing_sessions = [
session_name
for session_name in specified_sessions
if _normalize_arg(session_name) not in all_sessions
]
if missing_sessions:
raise KeyError(f"Sessions not found: {", ".join(missing_sessions)}")
def filter_by_python_interpreter(self, specified_pythons: Sequence[str]) -> None:
"""Filter sessions in the queue based on the user-specified
python interpreter versions.
Args:
specified_pythons (Sequence[str]): A list of specified
python interpreter versions.
"""
self._queue = [x for x in self._queue if x.func.python in specified_pythons]
def filter_by_keywords(self, keywords: str) -> None:
"""Filter sessions using pytest-like keyword expressions.
Args:
keywords (str): A Python expression of keywords which
session names are checked against.
"""
self._queue = [
x for x in self._queue if keyword_match(keywords, x.signatures + [x.name])
]
def make_session(
self, name: str, func: "Func", multi: bool = False
) -> List[SessionRunner]:
"""Create a session object from the session function.
Args:
name (str): The name of the session.
func (function): The session function.
multi (bool): Whether the function is a member of a set of sessions
with different interpreters.
Returns:
Sequence[~nox.session.Session]: A sequence of Session objects
bound to this manifest and configuration.
"""
sessions = []
# If the backend is "none", we won't parametrize `python`.
backend = (
self._config.force_venv_backend
or func.venv_backend
or self._config.default_venv_backend
)
if backend == "none" and isinstance(func.python, (list, tuple, set)):
# we can not log a warning here since the session is maybe deselected.
# instead let's set a flag, to warn later when session is actually run.
func.should_warn[WARN_PYTHONS_IGNORED] = func.python
func.python = False
if self._config.extra_pythons:
# If extra python is provided, expand the func.python list to
# include additional python interpreters
extra_pythons = self._config.extra_pythons # type: List[str]
if isinstance(func.python, (list, tuple, set)):
func.python = _unique_list(*func.python, *extra_pythons)
elif not multi and func.python:
# If this is multi, but there is only a single interpreter, it
# is the reentrant case. The extra_python interpreter shouldn't
# be added in that case. If func.python is False, the session
# has no backend; if None, it uses the same interpreter as Nox.
# Otherwise, add the extra specified python.
assert isinstance(func.python, str)
func.python = _unique_list(func.python, *extra_pythons)
# If the func has the python attribute set to a list, we'll need
# to expand them.
if isinstance(func.python, (list, tuple, set)):
for python in func.python:
single_func = func.copy()
single_func.python = python
sessions.extend(self.make_session(name, single_func, multi=True))
return sessions
# Simple case: If this function is not parametrized, then make
# a simple session.
if not hasattr(func, "parametrize"):
long_names = []
if not multi:
long_names.append(name)
if func.python:
long_names.append(f"{name}-{func.python}")
return [SessionRunner(name, long_names, func, self._config, self)]
# Since this function is parametrized, we need to add a distinct
# session for each permutation.
parametrize = func.parametrize # type: ignore
calls = Call.generate_calls(func, parametrize)
for call in calls:
long_names = []
if not multi:
long_names.append(f"{name}{call.session_signature}")
if func.python:
long_names.append(f"{name}-{func.python}{call.session_signature}")
# Ensure that specifying session-python will run all parameterizations.
long_names.append(f"{name}-{func.python}")
sessions.append(SessionRunner(name, long_names, call, self._config, self))
# Edge case: If the parameters made it such that there were no valid
# calls, add an empty, do-nothing session.
if not calls:
sessions.append(
SessionRunner(name, [], _null_session_func, self._config, self)
)
# Return the list of sessions.
return sessions
def next(self) -> SessionRunner:
return self.__next__()
def notify(
self, session: Union[str, SessionRunner], posargs: Optional[List[str]] = None
) -> bool:
"""Enqueue the specified session in the queue.
If the session is already in the queue, or has been run already,
then this is a no-op.
Args:
session (Union[str, ~nox.session.Session]): The session to be
enqueued.
posargs (Optional[List[str]]): If given, sets the positional
arguments *only* for the queued session. Otherwise, the
standard globally available positional arguments will be
used instead.
Returns:
bool: Whether the session was added to the queue.
Raises:
ValueError: If the session was not found.
"""
# Sanity check: If this session is already in the queue, this is
# a no-op.
if session in self:
return False
# Locate the session in the list of all sessions, and place it at
# the end of the queue.
for s in self._all_sessions:
if s == session or s.name == session or session in s.signatures:
if posargs is not None:
s.posargs = posargs
self._queue.append(s)
return True
# The session was not found in the list of sessions.
raise ValueError(f"Session {session} not found.")
class KeywordLocals(collections.abc.Mapping):
"""Eval locals using keywords.
When looking up a local variable the variable name is compared against
the set of keywords. If the local variable name matches any *substring* of
any keyword, then the name lookup returns True. Otherwise, the name lookup
returns False.
"""
def __init__(self, keywords: Set[str]) -> None:
self._keywords = keywords
def __getitem__(self, variable_name: str) -> bool:
for keyword in self._keywords:
if variable_name in keyword:
return True
return False
def __iter__(self) -> Iterator[str]:
return iter(self._keywords)
def __len__(self) -> int:
return len(self._keywords)
def keyword_match(expression: str, keywords: Iterable[str]) -> Any:
"""See if an expression matches the given set of keywords."""
locals = KeywordLocals(set(keywords))
return eval(expression, {}, locals)
def _null_session_func_(session: Session) -> None:
"""A no-op session for patemetrized sessions with no available params."""
session.skip("This session had no parameters available.")
def _normalized_session_match(session_name: str, session: SessionRunner) -> bool:
"""Checks if session_name matches session."""
if session_name == session.name or session_name in session.signatures:
return True
for name in session.signatures:
equal_rep = _normalize_arg(session_name) == _normalize_arg(name)
if equal_rep:
return True
# Exhausted
return False
def _normalize_arg(arg: str) -> Union[str]:
"""Normalize arg for comparison."""
try:
return str(ast.dump(ast.parse(arg)))
except (TypeError, SyntaxError):
return arg
_null_session_func = Func(_null_session_func_, python=False)
| # Copyright 2017 Alethea Katherine Flowers
#
# 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 argparse
import ast
import collections.abc
import itertools
from collections import OrderedDict
from typing import (
Any,
Iterable,
Iterator,
List,
Mapping,
Optional,
Sequence,
Set,
Tuple,
Union,
)
from nox._decorators import Call, Func
from nox.sessions import Session, SessionRunner
WARN_PYTHONS_IGNORED = "python_ignored"
def _unique_list(*args: str) -> List[str]:
"""Return a list without duplicates, while preserving order."""
return list(OrderedDict.fromkeys(args))
class Manifest:
"""Session manifest.
The session manifest provides the source of truth for the sequence of
sessions that should be run by nox.
It is possible for this to be mutated during execution. This allows for
useful use cases, such as for one session to "notify" another or
"chain" to another.
Args:
session_functions (Mapping[str, function]): The registry of discovered
session functions.
global_config (.nox.main.GlobalConfig): The global configuration.
module_docstring (Optional[str]): The user noxfile.py docstring.
Defaults to `None`.
"""
def __init__(
self,
session_functions: Mapping[str, "Func"],
global_config: argparse.Namespace,
module_docstring: Optional[str] = None,
) -> None:
self._all_sessions = [] # type: List[SessionRunner]
self._queue = [] # type: List[SessionRunner]
self._consumed = [] # type: List[SessionRunner]
self._config = global_config # type: argparse.Namespace
self.module_docstring = module_docstring # type: Optional[str]
# Create the sessions based on the provided session functions.
for name, func in session_functions.items():
for session in self.make_session(name, func):
self.add_session(session)
def __contains__(self, needle: Union[str, SessionRunner]) -> bool:
if needle in self._queue or needle in self._consumed:
return True
for session in self._queue + self._consumed:
if session.name == needle or needle in session.signatures:
return True
return False
def __iter__(self) -> "Manifest":
return self
def __getitem__(self, key: str) -> SessionRunner:
for session in self._queue + self._consumed:
if session.name == key or key in session.signatures:
return session
raise KeyError(key)
def __next__(self) -> SessionRunner:
"""Return the next item in the queue.
Raises:
StopIteration: If the queue has been entirely consumed.
"""
if not len(self._queue):
raise StopIteration
session = self._queue.pop(0)
self._consumed.append(session)
return session
def __len__(self) -> int:
return len(self._queue) + len(self._consumed)
def list_all_sessions(self) -> Iterator[Tuple[SessionRunner, bool]]:
"""Yields all sessions and whether or not they're selected."""
for session in self._all_sessions:
yield session, session in self._queue
def add_session(self, session: SessionRunner) -> None:
"""Add the given session to the manifest.
Args:
session (~nox.sessions.Session): A session object, such as
one returned from ``make_session``.
"""
if session not in self._all_sessions:
self._all_sessions.append(session)
if session not in self._queue:
self._queue.append(session)
def filter_by_name(self, specified_sessions: Iterable[str]) -> None:
"""Filter sessions in the queue based on the user-specified names.
Args:
specified_sessions (Sequence[str]): A list of specified
session names.
Raises:
KeyError: If any explicitly listed sessions are not found.
"""
# Filter the sessions remaining in the queue based on
# whether they are individually specified.
queue = []
for session_name in specified_sessions:
for session in self._queue:
if _normalized_session_match(session_name, session):
queue.append(session)
self._queue = queue
# If a session was requested and was not found, complain loudly.
all_sessions = set(
map(
_normalize_arg,
(
itertools.chain(
[x.name for x in self._all_sessions if x.name],
*[x.signatures for x in self._all_sessions],
)
),
)
)
missing_sessions = [
session_name
for session_name in specified_sessions
if _normalize_arg(session_name) not in all_sessions
]
if missing_sessions:
raise KeyError(f"Sessions not found: {', '.join(missing_sessions)}")
def filter_by_python_interpreter(self, specified_pythons: Sequence[str]) -> None:
"""Filter sessions in the queue based on the user-specified
python interpreter versions.
Args:
specified_pythons (Sequence[str]): A list of specified
python interpreter versions.
"""
self._queue = [x for x in self._queue if x.func.python in specified_pythons]
def filter_by_keywords(self, keywords: str) -> None:
"""Filter sessions using pytest-like keyword expressions.
Args:
keywords (str): A Python expression of keywords which
session names are checked against.
"""
self._queue = [
x for x in self._queue if keyword_match(keywords, x.signatures + [x.name])
]
def make_session(
self, name: str, func: "Func", multi: bool = False
) -> List[SessionRunner]:
"""Create a session object from the session function.
Args:
name (str): The name of the session.
func (function): The session function.
multi (bool): Whether the function is a member of a set of sessions
with different interpreters.
Returns:
Sequence[~nox.session.Session]: A sequence of Session objects
bound to this manifest and configuration.
"""
sessions = []
# If the backend is "none", we won't parametrize `python`.
backend = (
self._config.force_venv_backend
or func.venv_backend
or self._config.default_venv_backend
)
if backend == "none" and isinstance(func.python, (list, tuple, set)):
# we can not log a warning here since the session is maybe deselected.
# instead let's set a flag, to warn later when session is actually run.
func.should_warn[WARN_PYTHONS_IGNORED] = func.python
func.python = False
if self._config.extra_pythons:
# If extra python is provided, expand the func.python list to
# include additional python interpreters
extra_pythons = self._config.extra_pythons # type: List[str]
if isinstance(func.python, (list, tuple, set)):
func.python = _unique_list(*func.python, *extra_pythons)
elif not multi and func.python:
# If this is multi, but there is only a single interpreter, it
# is the reentrant case. The extra_python interpreter shouldn't
# be added in that case. If func.python is False, the session
# has no backend; if None, it uses the same interpreter as Nox.
# Otherwise, add the extra specified python.
assert isinstance(func.python, str)
func.python = _unique_list(func.python, *extra_pythons)
# If the func has the python attribute set to a list, we'll need
# to expand them.
if isinstance(func.python, (list, tuple, set)):
for python in func.python:
single_func = func.copy()
single_func.python = python
sessions.extend(self.make_session(name, single_func, multi=True))
return sessions
# Simple case: If this function is not parametrized, then make
# a simple session.
if not hasattr(func, "parametrize"):
long_names = []
if not multi:
long_names.append(name)
if func.python:
long_names.append(f"{name}-{func.python}")
return [SessionRunner(name, long_names, func, self._config, self)]
# Since this function is parametrized, we need to add a distinct
# session for each permutation.
parametrize = func.parametrize # type: ignore
calls = Call.generate_calls(func, parametrize)
for call in calls:
long_names = []
if not multi:
long_names.append(f"{name}{call.session_signature}")
if func.python:
long_names.append(f"{name}-{func.python}{call.session_signature}")
# Ensure that specifying session-python will run all parameterizations.
long_names.append(f"{name}-{func.python}")
sessions.append(SessionRunner(name, long_names, call, self._config, self))
# Edge case: If the parameters made it such that there were no valid
# calls, add an empty, do-nothing session.
if not calls:
sessions.append(
SessionRunner(name, [], _null_session_func, self._config, self)
)
# Return the list of sessions.
return sessions
def next(self) -> SessionRunner:
return self.__next__()
def notify(
self, session: Union[str, SessionRunner], posargs: Optional[List[str]] = None
) -> bool:
"""Enqueue the specified session in the queue.
If the session is already in the queue, or has been run already,
then this is a no-op.
Args:
session (Union[str, ~nox.session.Session]): The session to be
enqueued.
posargs (Optional[List[str]]): If given, sets the positional
arguments *only* for the queued session. Otherwise, the
standard globally available positional arguments will be
used instead.
Returns:
bool: Whether the session was added to the queue.
Raises:
ValueError: If the session was not found.
"""
# Sanity check: If this session is already in the queue, this is
# a no-op.
if session in self:
return False
# Locate the session in the list of all sessions, and place it at
# the end of the queue.
for s in self._all_sessions:
if s == session or s.name == session or session in s.signatures:
if posargs is not None:
s.posargs = posargs
self._queue.append(s)
return True
# The session was not found in the list of sessions.
raise ValueError(f"Session {session} not found.")
class KeywordLocals(collections.abc.Mapping):
"""Eval locals using keywords.
When looking up a local variable the variable name is compared against
the set of keywords. If the local variable name matches any *substring* of
any keyword, then the name lookup returns True. Otherwise, the name lookup
returns False.
"""
def __init__(self, keywords: Set[str]) -> None:
self._keywords = keywords
def __getitem__(self, variable_name: str) -> bool:
for keyword in self._keywords:
if variable_name in keyword:
return True
return False
def __iter__(self) -> Iterator[str]:
return iter(self._keywords)
def __len__(self) -> int:
return len(self._keywords)
def keyword_match(expression: str, keywords: Iterable[str]) -> Any:
"""See if an expression matches the given set of keywords."""
locals = KeywordLocals(set(keywords))
return eval(expression, {}, locals)
def _null_session_func_(session: Session) -> None:
"""A no-op session for patemetrized sessions with no available params."""
session.skip("This session had no parameters available.")
def _normalized_session_match(session_name: str, session: SessionRunner) -> bool:
"""Checks if session_name matches session."""
if session_name == session.name or session_name in session.signatures:
return True
for name in session.signatures:
equal_rep = _normalize_arg(session_name) == _normalize_arg(name)
if equal_rep:
return True
# Exhausted
return False
def _normalize_arg(arg: str) -> Union[str]:
"""Normalize arg for comparison."""
try:
return str(ast.dump(ast.parse(arg)))
except (TypeError, SyntaxError):
return arg
_null_session_func = Func(_null_session_func_, python=False)
|
from py_imessage import imessage
from time import sleep
phone = "+66818726755"
if not imessage.check_compatibility(phone):
print("Not an iPhone.")
else:
print("Yes, he use iPhone.")
# guid = imessage.send(phone, "Hello World!")
#
# # Let the recipient read the message
# sleep(5)
# resp = imessage.status(guid)
#
# print(f'Message was read at {resp.get('date_read')}') | from py_imessage import imessage
from time import sleep
phone = "+66818726755"
if not imessage.check_compatibility(phone):
print("Not an iPhone.")
else:
print("Yes, he use iPhone.")
# guid = imessage.send(phone, "Hello World!")
#
# # Let the recipient read the message
# sleep(5)
# resp = imessage.status(guid)
#
# print(f'Message was read at {resp.get("date_read")}') |
# -*- coding: utf-8 -*-
import asyncio
import os
import signal
import asyncpg
from .App import App, AppData
from .AppConfig import AppConfig, KEY_EXPOSE, KEY_FORWARDS
from .Config import Config
from .Containers import Containers
from .DeploymentLock import DeploymentLock
from .Exceptions import StoryscriptError, TooManyActiveApps, TooManyServices, \
TooManyVolumes
from .GraphQLAPI import GraphQLAPI
from .Logger import Logger
from .ServiceUsage import ServiceUsage
from .constants.Events import APP_DEPLOYED, APP_DEPLOY_FAILED, \
APP_DEPLOY_INITIATED, APP_INSTANCE_DESTROYED, \
APP_INSTANCE_DESTROY_ERROR, APP_RELOAD_FAILED
from .constants.ReleaseConstants import ReleaseConstants
from .constants.ServiceConstants import ServiceConstants
from .db.Database import Database
from .entities.Release import Release
from .enums.AppEnvironment import AppEnvironment
from .enums.ReleaseState import ReleaseState
from .reporting.Reporter import Reporter
from .reporting.ReportingAgent import ReportingEvent
from .utils.Dict import Dict
MAX_VOLUMES_BETA = 15
MAX_SERVICES_BETA = 15
MAX_ACTIVE_APPS = 5
DEPLOYMENT_BATCH_SIZE = 100
class Apps:
"""
Globals used: glogger - the global logger (used for the engine)
"""
release_listener_db_con = None
internal_services = ['http', 'log', 'crontab', 'file', 'event']
deployment_lock = DeploymentLock()
apps = {}
"""
Keeps a reference to all apps. Keyed by their app_id,
with their value being asyncy.App
"""
@classmethod
def get_app_config(cls, raw):
return AppConfig(raw)
@classmethod
async def deploy_release(cls, config: Config, release: Release):
app_id = release.app_uuid
stories = release.stories
logger = cls.make_logger_for_app(config, app_id, release.version)
logger.info(f'Deploying app {app_id}@{release.version}')
re = ReportingEvent.from_release(release, APP_DEPLOY_INITIATED)
Reporter.capture_evt(re)
if release.maintenance:
logger.warn(f'Not updating deployment, app put in maintenance'
f'({app_id}@{release.version})')
return
if release.deleted:
await Database.update_release_state(logger, config, app_id,
release.version,
ReleaseState.NO_DEPLOY)
logger.warn(f'Deployment halted {app_id}@{release.version}; '
f'deleted={release.deleted}; '
f'maintenance={release.maintenance}')
logger.warn(f'State changed to NO_DEPLOY for {app_id}@'
f'{release.version}')
return
await Database.update_release_state(logger, config, app_id,
release.version,
ReleaseState.DEPLOYING)
try:
# Check for the currently active apps by the same owner.
# Note: This is a super inefficient method, but is OK
# since it'll last only during beta.
active_apps = 0
for app in cls.apps.values():
if app is not None and app.owner_uuid == release.owner_uuid:
active_apps += 1
if active_apps >= MAX_ACTIVE_APPS:
raise TooManyActiveApps(active_apps, MAX_ACTIVE_APPS)
services_count = len(stories.get('services', []))
if services_count > MAX_SERVICES_BETA:
raise TooManyServices(services_count, MAX_SERVICES_BETA)
services = await cls.get_services(
stories.get('yaml', {}), logger, stories)
volume_count = 0
for service in services.keys():
omg = services[service][ServiceConstants.config]
volume_count += len(omg.get('volumes', {}).keys())
if volume_count > MAX_VOLUMES_BETA:
raise TooManyVolumes(volume_count, MAX_VOLUMES_BETA)
app_config = cls.get_app_config(raw=stories.get('yaml', {}))
app = App(
app_data=AppData(
app_config=app_config,
config=config,
logger=logger,
services=services,
release=release
)
)
cls.apps[app_id] = app
await Containers.clean_app(app)
await Containers.init(app)
await app.bootstrap()
await Database.update_release_state(logger, config, app_id,
release.version,
ReleaseState.DEPLOYED)
logger.info(f'Successfully deployed app {app_id}@'
f'{release.version}')
re = ReportingEvent.from_release(release, APP_DEPLOYED)
Reporter.capture_evt(re)
except BaseException as e:
if isinstance(e, StoryscriptError):
await Database.update_release_state(
logger, config, app_id, release.version,
ReleaseState.FAILED
)
logger.error(str(e))
else:
logger.error(f'Failed to bootstrap app ({e})', exc=e)
await Database.update_release_state(
logger, config, app_id, release.version,
ReleaseState.TEMP_DEPLOYMENT_FAILURE
)
re = ReportingEvent.from_release(
release, APP_DEPLOY_FAILED, exc_info=e)
Reporter.capture_evt(re)
@classmethod
def make_logger_for_app(cls, config, app_id, version):
logger = Logger(config)
logger.start()
logger.adapt(app_id, version)
return logger
@classmethod
async def reload_apps(cls, config, glogger):
"""
Split apps in batches, where all apps in a batch
are deployed together in parallel
and subsequent batches are deployed sequentially
"""
apps = await Database.get_all_app_uuids_for_deployment(config)
for i in range(0, len(apps), DEPLOYMENT_BATCH_SIZE):
current_batch = apps[i: i + DEPLOYMENT_BATCH_SIZE]
await asyncio.gather(*[
cls.reload_app(config, glogger, app['uuid'])
for app in current_batch
])
@classmethod
async def init_all(cls, config: Config, glogger: Logger):
# We must start listening for releases straight away,
# before an app is even deployed.
# If we start listening after all the apps are deployed,
# then we might miss some notifications about releases.
loop = asyncio.get_event_loop()
asyncio.create_task(
cls.start_release_listener(config, glogger, loop)
)
if config.APP_ENVIRONMENT == AppEnvironment.PRODUCTION:
# Only record service resource usage metrics in production
asyncio.create_task(
ServiceUsage.start_metrics_recorder(config, glogger)
)
await cls.reload_apps(config, glogger)
@classmethod
def get(cls, app_id: str):
return cls.apps[app_id]
@classmethod
async def get_services(cls, asyncy_yaml, glogger: Logger,
stories: dict):
services = {}
all_services = stories.get('services', [])
expose = asyncy_yaml.get(KEY_FORWARDS, asyncy_yaml.get(KEY_EXPOSE, {}))
for expose_conf in expose:
all_services.append(expose_conf['service'])
for service in all_services:
conf = Dict.find(asyncy_yaml, f'services.{service}', {})
# query the Hub for the OMG
tag = conf.get('tag', 'latest')
if '/' in service:
uuid, pull_url, omg = await GraphQLAPI.get_by_slug(
glogger, service, tag)
else:
uuid, pull_url, omg = await GraphQLAPI.get_by_alias(
glogger, service, tag)
if conf.get('image') is not None:
image = f'{conf.get('image')}:{tag}'
else:
image = f'{pull_url}:{tag}'
omg.update({
'uuid': uuid,
'image': image
})
services[service] = {
'tag': tag,
'configuration': omg
}
return services
@classmethod
async def destroy_app(cls, app: App, silent=False,
update_db_state=False):
app.logger.info(f'Destroying app {app.app_id}')
try:
if update_db_state:
await Database.update_release_state(app.logger, app.config,
app.app_id, app.version,
ReleaseState.TERMINATING)
await app.destroy()
await Containers.clean_app(app)
except BaseException as e:
if not silent:
raise e
app.logger.error(
f'Failed to destroy app {app.app_id}@{app.version}; '
f'will eat exception (silent=True)',
exc=e)
re = ReportingEvent.from_release(
app.release, APP_INSTANCE_DESTROY_ERROR, exc_info=e)
Reporter.capture_evt(re)
finally:
if update_db_state:
await Database.update_release_state(app.logger, app.config,
app.app_id, app.version,
ReleaseState.TERMINATED)
app.logger.info(f'Completed destroying app {app.app_id}')
Reporter.capture_evt(ReportingEvent.from_release(
app.release, APP_INSTANCE_DESTROYED))
cls.apps[app.app_id] = None
@classmethod
async def reload_app(cls, config: Config, glogger: Logger, app_id: str):
glogger.info(f'Reloading app {app_id}')
if cls.apps.get(app_id) is not None:
await cls.destroy_app(cls.apps[app_id], silent=True,
update_db_state=True)
can_deploy = False
release = None
try:
can_deploy = await cls.deployment_lock.try_acquire(app_id)
if not can_deploy:
glogger.warn(f'Another deployment for app {app_id} is in '
f'progress. Will not reload.')
return
release = await Database.get_release_for_deployment(config, app_id)
# At boot up, there won't be environment mismatches. However,
# since there's just one release notification from the DB, they'll
# might make it through.
if release.app_environment != config.APP_ENVIRONMENT:
glogger.info(
f'Not deploying app {app_id} '
f'(environment mismatch - '
f'expected {config.APP_ENVIRONMENT}, '
f'but got {release.app_environment})')
return
if release.state == ReleaseState.FAILED.value:
glogger.warn(f'Cowardly refusing to deploy app '
f'{app_id}@{release.version} as it\'s '
f'last state is FAILED')
return
if release.stories is None:
glogger.info(f'No story found for deployment for '
f'app {app_id}@{release.version}. '
f'Halting deployment.')
return
await asyncio.wait_for(
cls.deploy_release(
config=config,
release=release
),
timeout=5 * 60)
glogger.info(f'Reloaded app {app_id}@{release.version}')
except BaseException as e:
glogger.error(
f'Failed to reload app {app_id}', exc=e)
if release is not None:
re = ReportingEvent.from_release(release, APP_RELOAD_FAILED,
exc_info=e)
else:
re = ReportingEvent.from_exc(e)
Reporter.capture_evt(re)
if isinstance(e, asyncio.TimeoutError):
logger = cls.make_logger_for_app(config, app_id,
release.version)
await Database.update_release_state(logger, config, app_id,
release.version,
ReleaseState.TIMED_OUT)
finally:
if can_deploy:
# If we did acquire the lock, then we must release it.
await cls.deployment_lock.release(app_id)
@classmethod
async def destroy_all(cls):
copy = cls.apps.copy()
for app in copy.values():
try:
await cls.destroy_app(app)
except BaseException as e:
re = ReportingEvent.from_release(
app.release, 'App Destroy Failed', exc_info=e)
Reporter.capture_evt(re)
@classmethod
async def listen_to_releases(cls, config: Config, glogger: Logger, loop):
if cls.release_listener_db_con:
asyncio.create_task(cls.release_listener_db_con.close())
try:
con = await Database.new_con(config)
await con.add_listener(
ReleaseConstants.table,
lambda _conn, _pid, _channel, payload:
asyncio.run_coroutine_threadsafe(
cls.reload_app(config, glogger, payload),
loop
)
)
cls.release_listener_db_con = con
glogger.info('Listening for new releases...')
except (OSError, asyncpg.exceptions.InterfaceError,
asyncpg.exceptions.InternalClientError):
glogger.error('Failed to connect to database.')
# kill the server if the database listener is not listening
os.kill(os.getpid(), signal.SIGINT)
@classmethod
async def start_release_listener(cls, config, glogger, loop):
while True:
con = cls.release_listener_db_con
# con: connection object
# not con._con: underlying connection broken
# not in con._listeners: notify listener lost in space
if not con or not con._con or \
ReleaseConstants.table not in con._listeners:
await cls.listen_to_releases(config, glogger, loop)
await asyncio.sleep(1)
| # -*- coding: utf-8 -*-
import asyncio
import os
import signal
import asyncpg
from .App import App, AppData
from .AppConfig import AppConfig, KEY_EXPOSE, KEY_FORWARDS
from .Config import Config
from .Containers import Containers
from .DeploymentLock import DeploymentLock
from .Exceptions import StoryscriptError, TooManyActiveApps, TooManyServices, \
TooManyVolumes
from .GraphQLAPI import GraphQLAPI
from .Logger import Logger
from .ServiceUsage import ServiceUsage
from .constants.Events import APP_DEPLOYED, APP_DEPLOY_FAILED, \
APP_DEPLOY_INITIATED, APP_INSTANCE_DESTROYED, \
APP_INSTANCE_DESTROY_ERROR, APP_RELOAD_FAILED
from .constants.ReleaseConstants import ReleaseConstants
from .constants.ServiceConstants import ServiceConstants
from .db.Database import Database
from .entities.Release import Release
from .enums.AppEnvironment import AppEnvironment
from .enums.ReleaseState import ReleaseState
from .reporting.Reporter import Reporter
from .reporting.ReportingAgent import ReportingEvent
from .utils.Dict import Dict
MAX_VOLUMES_BETA = 15
MAX_SERVICES_BETA = 15
MAX_ACTIVE_APPS = 5
DEPLOYMENT_BATCH_SIZE = 100
class Apps:
"""
Globals used: glogger - the global logger (used for the engine)
"""
release_listener_db_con = None
internal_services = ['http', 'log', 'crontab', 'file', 'event']
deployment_lock = DeploymentLock()
apps = {}
"""
Keeps a reference to all apps. Keyed by their app_id,
with their value being asyncy.App
"""
@classmethod
def get_app_config(cls, raw):
return AppConfig(raw)
@classmethod
async def deploy_release(cls, config: Config, release: Release):
app_id = release.app_uuid
stories = release.stories
logger = cls.make_logger_for_app(config, app_id, release.version)
logger.info(f'Deploying app {app_id}@{release.version}')
re = ReportingEvent.from_release(release, APP_DEPLOY_INITIATED)
Reporter.capture_evt(re)
if release.maintenance:
logger.warn(f'Not updating deployment, app put in maintenance'
f'({app_id}@{release.version})')
return
if release.deleted:
await Database.update_release_state(logger, config, app_id,
release.version,
ReleaseState.NO_DEPLOY)
logger.warn(f'Deployment halted {app_id}@{release.version}; '
f'deleted={release.deleted}; '
f'maintenance={release.maintenance}')
logger.warn(f'State changed to NO_DEPLOY for {app_id}@'
f'{release.version}')
return
await Database.update_release_state(logger, config, app_id,
release.version,
ReleaseState.DEPLOYING)
try:
# Check for the currently active apps by the same owner.
# Note: This is a super inefficient method, but is OK
# since it'll last only during beta.
active_apps = 0
for app in cls.apps.values():
if app is not None and app.owner_uuid == release.owner_uuid:
active_apps += 1
if active_apps >= MAX_ACTIVE_APPS:
raise TooManyActiveApps(active_apps, MAX_ACTIVE_APPS)
services_count = len(stories.get('services', []))
if services_count > MAX_SERVICES_BETA:
raise TooManyServices(services_count, MAX_SERVICES_BETA)
services = await cls.get_services(
stories.get('yaml', {}), logger, stories)
volume_count = 0
for service in services.keys():
omg = services[service][ServiceConstants.config]
volume_count += len(omg.get('volumes', {}).keys())
if volume_count > MAX_VOLUMES_BETA:
raise TooManyVolumes(volume_count, MAX_VOLUMES_BETA)
app_config = cls.get_app_config(raw=stories.get('yaml', {}))
app = App(
app_data=AppData(
app_config=app_config,
config=config,
logger=logger,
services=services,
release=release
)
)
cls.apps[app_id] = app
await Containers.clean_app(app)
await Containers.init(app)
await app.bootstrap()
await Database.update_release_state(logger, config, app_id,
release.version,
ReleaseState.DEPLOYED)
logger.info(f'Successfully deployed app {app_id}@'
f'{release.version}')
re = ReportingEvent.from_release(release, APP_DEPLOYED)
Reporter.capture_evt(re)
except BaseException as e:
if isinstance(e, StoryscriptError):
await Database.update_release_state(
logger, config, app_id, release.version,
ReleaseState.FAILED
)
logger.error(str(e))
else:
logger.error(f'Failed to bootstrap app ({e})', exc=e)
await Database.update_release_state(
logger, config, app_id, release.version,
ReleaseState.TEMP_DEPLOYMENT_FAILURE
)
re = ReportingEvent.from_release(
release, APP_DEPLOY_FAILED, exc_info=e)
Reporter.capture_evt(re)
@classmethod
def make_logger_for_app(cls, config, app_id, version):
logger = Logger(config)
logger.start()
logger.adapt(app_id, version)
return logger
@classmethod
async def reload_apps(cls, config, glogger):
"""
Split apps in batches, where all apps in a batch
are deployed together in parallel
and subsequent batches are deployed sequentially
"""
apps = await Database.get_all_app_uuids_for_deployment(config)
for i in range(0, len(apps), DEPLOYMENT_BATCH_SIZE):
current_batch = apps[i: i + DEPLOYMENT_BATCH_SIZE]
await asyncio.gather(*[
cls.reload_app(config, glogger, app['uuid'])
for app in current_batch
])
@classmethod
async def init_all(cls, config: Config, glogger: Logger):
# We must start listening for releases straight away,
# before an app is even deployed.
# If we start listening after all the apps are deployed,
# then we might miss some notifications about releases.
loop = asyncio.get_event_loop()
asyncio.create_task(
cls.start_release_listener(config, glogger, loop)
)
if config.APP_ENVIRONMENT == AppEnvironment.PRODUCTION:
# Only record service resource usage metrics in production
asyncio.create_task(
ServiceUsage.start_metrics_recorder(config, glogger)
)
await cls.reload_apps(config, glogger)
@classmethod
def get(cls, app_id: str):
return cls.apps[app_id]
@classmethod
async def get_services(cls, asyncy_yaml, glogger: Logger,
stories: dict):
services = {}
all_services = stories.get('services', [])
expose = asyncy_yaml.get(KEY_FORWARDS, asyncy_yaml.get(KEY_EXPOSE, {}))
for expose_conf in expose:
all_services.append(expose_conf['service'])
for service in all_services:
conf = Dict.find(asyncy_yaml, f'services.{service}', {})
# query the Hub for the OMG
tag = conf.get('tag', 'latest')
if '/' in service:
uuid, pull_url, omg = await GraphQLAPI.get_by_slug(
glogger, service, tag)
else:
uuid, pull_url, omg = await GraphQLAPI.get_by_alias(
glogger, service, tag)
if conf.get('image') is not None:
image = f'{conf.get("image")}:{tag}'
else:
image = f'{pull_url}:{tag}'
omg.update({
'uuid': uuid,
'image': image
})
services[service] = {
'tag': tag,
'configuration': omg
}
return services
@classmethod
async def destroy_app(cls, app: App, silent=False,
update_db_state=False):
app.logger.info(f'Destroying app {app.app_id}')
try:
if update_db_state:
await Database.update_release_state(app.logger, app.config,
app.app_id, app.version,
ReleaseState.TERMINATING)
await app.destroy()
await Containers.clean_app(app)
except BaseException as e:
if not silent:
raise e
app.logger.error(
f'Failed to destroy app {app.app_id}@{app.version}; '
f'will eat exception (silent=True)',
exc=e)
re = ReportingEvent.from_release(
app.release, APP_INSTANCE_DESTROY_ERROR, exc_info=e)
Reporter.capture_evt(re)
finally:
if update_db_state:
await Database.update_release_state(app.logger, app.config,
app.app_id, app.version,
ReleaseState.TERMINATED)
app.logger.info(f'Completed destroying app {app.app_id}')
Reporter.capture_evt(ReportingEvent.from_release(
app.release, APP_INSTANCE_DESTROYED))
cls.apps[app.app_id] = None
@classmethod
async def reload_app(cls, config: Config, glogger: Logger, app_id: str):
glogger.info(f'Reloading app {app_id}')
if cls.apps.get(app_id) is not None:
await cls.destroy_app(cls.apps[app_id], silent=True,
update_db_state=True)
can_deploy = False
release = None
try:
can_deploy = await cls.deployment_lock.try_acquire(app_id)
if not can_deploy:
glogger.warn(f'Another deployment for app {app_id} is in '
f'progress. Will not reload.')
return
release = await Database.get_release_for_deployment(config, app_id)
# At boot up, there won't be environment mismatches. However,
# since there's just one release notification from the DB, they'll
# might make it through.
if release.app_environment != config.APP_ENVIRONMENT:
glogger.info(
f'Not deploying app {app_id} '
f'(environment mismatch - '
f'expected {config.APP_ENVIRONMENT}, '
f'but got {release.app_environment})')
return
if release.state == ReleaseState.FAILED.value:
glogger.warn(f'Cowardly refusing to deploy app '
f'{app_id}@{release.version} as it\'s '
f'last state is FAILED')
return
if release.stories is None:
glogger.info(f'No story found for deployment for '
f'app {app_id}@{release.version}. '
f'Halting deployment.')
return
await asyncio.wait_for(
cls.deploy_release(
config=config,
release=release
),
timeout=5 * 60)
glogger.info(f'Reloaded app {app_id}@{release.version}')
except BaseException as e:
glogger.error(
f'Failed to reload app {app_id}', exc=e)
if release is not None:
re = ReportingEvent.from_release(release, APP_RELOAD_FAILED,
exc_info=e)
else:
re = ReportingEvent.from_exc(e)
Reporter.capture_evt(re)
if isinstance(e, asyncio.TimeoutError):
logger = cls.make_logger_for_app(config, app_id,
release.version)
await Database.update_release_state(logger, config, app_id,
release.version,
ReleaseState.TIMED_OUT)
finally:
if can_deploy:
# If we did acquire the lock, then we must release it.
await cls.deployment_lock.release(app_id)
@classmethod
async def destroy_all(cls):
copy = cls.apps.copy()
for app in copy.values():
try:
await cls.destroy_app(app)
except BaseException as e:
re = ReportingEvent.from_release(
app.release, 'App Destroy Failed', exc_info=e)
Reporter.capture_evt(re)
@classmethod
async def listen_to_releases(cls, config: Config, glogger: Logger, loop):
if cls.release_listener_db_con:
asyncio.create_task(cls.release_listener_db_con.close())
try:
con = await Database.new_con(config)
await con.add_listener(
ReleaseConstants.table,
lambda _conn, _pid, _channel, payload:
asyncio.run_coroutine_threadsafe(
cls.reload_app(config, glogger, payload),
loop
)
)
cls.release_listener_db_con = con
glogger.info('Listening for new releases...')
except (OSError, asyncpg.exceptions.InterfaceError,
asyncpg.exceptions.InternalClientError):
glogger.error('Failed to connect to database.')
# kill the server if the database listener is not listening
os.kill(os.getpid(), signal.SIGINT)
@classmethod
async def start_release_listener(cls, config, glogger, loop):
while True:
con = cls.release_listener_db_con
# con: connection object
# not con._con: underlying connection broken
# not in con._listeners: notify listener lost in space
if not con or not con._con or \
ReleaseConstants.table not in con._listeners:
await cls.listen_to_releases(config, glogger, loop)
await asyncio.sleep(1)
|
import asyncio
import base64
import hashlib
import json
import math
import os
import sys
import time
from dataclasses import asdict, dataclass, field, InitVar
from json import JSONDecodeError
from os.path import splitext, basename
from typing import Union, Any
from urllib import parse
from urllib.parse import quote
import aiohttp
import requests.utils
import rsa
import urllib3.exceptions
from requests.adapters import HTTPAdapter, Retry
from biliup import config
from ..engine import Plugin
from ..engine.upload import UploadBase, logger
@Plugin.upload(platform="bili_web")
class BiliWeb(UploadBase):
def __init__(self, principal, data, user, submit_api=None, copyright=2, postprocessor=None,
lines='AUTO', threads=3, tid=122, tags=None, cover_path=None, description=''):
super().__init__(principal, data, persistence_path='bili.cookie', postprocessor=postprocessor)
if tags is None:
tags = []
self.user = user
self.lines = lines
self.submit_api = submit_api
self.threads = threads
self.tid = tid
self.tags = tags
self.cover_path = cover_path
self.desc = description
self.copyright = copyright
def upload(self, file_list):
video = Data()
with BiliBili(video) as bili:
bili.app_key = self.user.get('app_key')
bili.appsec = self.user.get('appsec')
bili.login(self.persistence_path, self.user)
for file in file_list:
video_part = bili.upload_file(file, self.lines, self.threads) # 上传视频
video.append(video_part) # 添加已经上传的视频
video.title = self.data["format_title"]
video.desc = self.desc + '''
Powered By biliup
Github:https://github.com/ForgQi/biliup'''
video.copyright = self.copyright
if self.copyright == 2:
video.source = self.data["url"] # 添加转载地址说明
# 设置视频分区,默认为174 生活,其他分区
video.tid = self.tid
video.set_tag(self.tags)
if self.cover_path:
video.cover = bili.cover_up(self.cover_path).replace('http:', '')
ret = bili.submit(self.submit_api) # 提交视频
logger.info(f"上传成功: {ret}")
return file_list
class BiliBili:
def __init__(self, video: 'Data'):
self.app_key = None
self.appsec = None
if self.app_key is None or self.appsec is None:
self.app_key = 'ae57252b0c09105d'
self.appsec = 'c75875c596a69eb55bd119e74b07cfe3'
self.__session = requests.Session()
self.video = video
self.__session.mount('https://', HTTPAdapter(max_retries=Retry(total=5, method_whitelist=False)))
self.__session.headers.update({
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/63.0.3239.108",
"Referer": "https://www.bilibili.com/", 'Connection': 'keep-alive'
})
self.cookies = None
self.access_token = None
self.refresh_token = None
self.account = None
self.__bili_jct = None
self._auto_os = None
self.persistence_path = 'engine/bili.cookie'
def login(self, persistence_path, user):
self.persistence_path = persistence_path
if os.path.isfile(persistence_path):
print('使用持久化内容上传')
self.load()
if not self.cookies and user.get('cookies'):
self.cookies = user['cookies']
if not self.access_token and user.get('access_token'):
self.access_token = user['access_token']
if not self.account and user.get('account'):
self.account = user['account']
if self.cookies:
try:
self.login_by_cookies(self.cookies)
except:
logger.exception('login error')
self.login_by_password(**self.account)
else:
self.login_by_password(**self.account)
self.store()
def load(self):
try:
with open(self.persistence_path) as f:
self.cookies = json.load(f)
self.access_token = self.cookies['access_token']
except (JSONDecodeError, KeyError):
logger.exception('加载cookie出错')
def store(self):
with open(self.persistence_path, "w") as f:
json.dump({**self.cookies,
'access_token': self.access_token,
'refresh_token': self.refresh_token
}, f)
def login_by_password(self, username, password):
print('使用账号上传')
key_hash, pub_key = self.get_key()
encrypt_password = base64.b64encode(rsa.encrypt(f'{key_hash}{password}'.encode(), pub_key))
payload = {
"actionKey": 'appkey',
"appkey": self.app_key,
"build": 6270200,
"captcha": '',
"challenge": '',
"channel": 'bili',
"device": 'phone',
"mobi_app": 'android',
"password": encrypt_password,
"permission": 'ALL',
"platform": 'android',
"seccode": "",
"subid": 1,
"ts": int(time.time()),
"username": username,
"validate": "",
}
response = self.__session.post("https://passport.bilibili.com/x/passport-login/oauth2/login", timeout=5,
data={**payload, 'sign': self.sign(parse.urlencode(payload))})
r = response.json()
if r['code'] != 0 or r.get('data') is None or r['data'].get('cookie_info') is None:
raise RuntimeError(r)
try:
for cookie in r['data']['cookie_info']['cookies']:
self.__session.cookies.set(cookie['name'], cookie['value'])
if 'bili_jct' == cookie['name']:
self.__bili_jct = cookie['value']
self.cookies = self.__session.cookies.get_dict()
self.access_token = r['data']['token_info']['access_token']
self.refresh_token = r['data']['token_info']['refresh_token']
except:
raise RuntimeError(r)
return r
def login_by_cookies(self, cookie):
print('使用cookies上传')
requests.utils.add_dict_to_cookiejar(self.__session.cookies, cookie)
if 'bili_jct' in cookie:
self.__bili_jct = cookie["bili_jct"]
data = self.__session.get("https://api.bilibili.com/x/web-interface/nav", timeout=5).json()
if data["code"] != 0:
raise Exception(data)
def sign(self, param):
return hashlib.md5(f"{param}{self.appsec}".encode()).hexdigest()
def get_key(self):
url = "https://passport.bilibili.com/x/passport-login/web/key"
payload = {
'appkey': f'{self.app_key}',
'sign': self.sign(f"appkey={self.app_key}"),
}
response = self.__session.get(url, data=payload, timeout=5)
r = response.json()
if r and r["code"] == 0:
return r['data']['hash'], rsa.PublicKey.load_pkcs1_openssl_pem(r['data']['key'].encode())
def probe(self):
ret = self.__session.get('https://member.bilibili.com/preupload?r=probe', timeout=5).json()
logger.info(f"线路:{ret["lines"]}")
data, auto_os = None, None
min_cost = 0
if ret['probe'].get('get'):
method = 'get'
else:
method = 'post'
data = bytes(int(1024 * 0.1 * 1024))
for line in ret['lines']:
start = time.perf_counter()
test = self.__session.request(method, f"https:{line["probe_url"]}", data=data, timeout=30)
cost = time.perf_counter() - start
print(line['query'], cost)
if test.status_code != 200:
return
if not min_cost or min_cost > cost:
auto_os = line
min_cost = cost
auto_os['cost'] = min_cost
return auto_os
def upload_file(self, filepath: str, lines='AUTO', tasks=3):
"""上传本地视频文件,返回视频信息dict
b站目前支持4种上传线路upos, kodo, gcs, bos
gcs: {"os":"gcs","query":"bucket=bvcupcdngcsus&probe_version=20200810",
"probe_url":"//storage.googleapis.com/bvcupcdngcsus/OK"},
bos: {"os":"bos","query":"bucket=bvcupcdnboshb&probe_version=20200810",
"probe_url":"??"}
"""
if not self._auto_os:
self._auto_os = self.probe()
if lines == 'kodo':
self._auto_os = {"os": "kodo", "query": "bucket=bvcupcdnkodobm&probe_version=20200810",
"probe_url": "//up-na0.qbox.me/crossdomain.xml"}
if lines == 'bda2':
self._auto_os = {"os": "upos", "query": "upcdn=bda2&probe_version=20200810",
"probe_url": "//upos-sz-upcdnbda2.bilivideo.com/OK"}
if lines == 'ws':
self._auto_os = {"os": "upos", "query": "upcdn=ws&probe_version=20200810",
"probe_url": "//upos-sz-upcdnws.bilivideo.com/OK"}
if lines == 'qn':
self._auto_os = {"os": "upos", "query": "upcdn=qn&probe_version=20200810",
"probe_url": "//upos-sz-upcdnqn.bilivideo.com/OK"}
logger.info(f"线路选择 => {self._auto_os["os"]}: {self._auto_os["query"]}. time: {self._auto_os.get("cost")}")
if self._auto_os['os'] == 'upos':
upload = self.upos
elif self._auto_os['os'] == 'kodo':
upload = self.kodo
elif self._auto_os['os'] == "gcs":
raise NotImplementedError('gcs')
elif self._auto_os['os'] == "bos":
raise NotImplementedError('bos')
else:
logger.error(f"NoSearch:{self._auto_os["os"]}")
raise NotImplementedError(self._auto_os['os'])
total_size = os.path.getsize(filepath)
with open(filepath, 'rb') as f:
query = {
'r': self._auto_os['os'],
'profile': 'ugcupos/bup' if 'upos' == self._auto_os['os'] else "ugcupos/bupfetch",
'ssl': 0,
'version': '2.8.12',
'build': 2081200,
'name': f.name,
'size': total_size,
}
ret = self.__session.get(
f"https://member.bilibili.com/preupload?{self._auto_os["query"]}", params=query,
timeout=5)
return asyncio.run(upload(f, total_size, ret.json(), tasks=tasks))
async def kodo(self, file, total_size, ret, chunk_size=4194304, tasks=3):
filename = file.name
bili_filename = ret['bili_filename']
key = ret['key']
endpoint = f"https:{ret["endpoint"]}"
token = ret['uptoken']
fetch_url = ret['fetch_url']
fetch_headers = ret['fetch_headers']
url = f'{endpoint}/mkblk'
headers = {
'Authorization': f"UpToken {token}",
}
# 开始上传
parts = [] # 分块信息
chunks = math.ceil(total_size / chunk_size) # 获取分块数量
async def upload_chunk(session, chunks_data, params):
async with session.post(f'{url}/{len(chunks_data)}',
data=chunks_data, headers=headers) as response:
end = time.perf_counter() - start
ctx = await response.json()
parts.append({"index": params['chunk'], "ctx": ctx['ctx']})
sys.stdout.write(f"\r{params["end"] / 1000 / 1000 / end:.2f}MB/s "
f"=> {params["partNumber"] / chunks:.1%}")
start = time.perf_counter()
await self._upload({}, file, chunk_size, upload_chunk, tasks=tasks)
cost = time.perf_counter() - start
logger.info(f'{filename} uploaded >> {total_size / 1000 / 1000 / cost:.2f}MB/s')
parts.sort(key=lambda x: x['index'])
self.__session.post(f"{endpoint}/mkfile/{total_size}/key/{base64.urlsafe_b64encode(key.encode()).decode()}",
data=','.join(map(lambda x: x['ctx'], parts)), headers=headers, timeout=10)
r = self.__session.post(f"https:{fetch_url}", headers=fetch_headers, timeout=5).json()
if r["OK"] != 1:
raise Exception(r)
return {"title": splitext(filename)[0], "filename": bili_filename, "desc": ""}
async def upos(self, file, total_size, ret, tasks=3):
filename = file.name
chunk_size = ret['chunk_size']
auth = ret["auth"]
endpoint = ret["endpoint"]
biz_id = ret["biz_id"]
upos_uri = ret["upos_uri"]
url = f"https:{endpoint}/{upos_uri.replace("upos://", "")}" # 视频上传路径
headers = {
"X-Upos-Auth": auth
}
# 向上传地址申请上传,得到上传id等信息
upload_id = self.__session.post(f'{url}?uploads&output=json', timeout=5,
headers=headers).json()["upload_id"]
# 开始上传
parts = [] # 分块信息
chunks = math.ceil(total_size / chunk_size) # 获取分块数量
async def upload_chunk(session, chunks_data, params):
async with session.put(url, params=params, raise_for_status=True,
data=chunks_data, headers=headers):
end = time.perf_counter() - start
parts.append({"partNumber": params['chunk'] + 1, "eTag": "etag"})
sys.stdout.write(f"\r{params["end"] / 1000 / 1000 / end:.2f}MB/s "
f"=> {params["partNumber"] / chunks:.1%}")
start = time.perf_counter()
await self._upload({
'uploadId': upload_id,
'chunks': chunks,
'total': total_size
}, file, chunk_size, upload_chunk, tasks=tasks)
cost = time.perf_counter() - start
p = {
'name': filename,
'uploadId': upload_id,
'biz_id': biz_id,
'output': 'json',
'profile': 'ugcupos/bup'
}
ii = 0
while ii <= 3:
try:
r = self.__session.post(url, params=p, json={"parts": parts}, headers=headers, timeout=15).json()
if r.get('OK') == 1:
logger.info(f'{filename} uploaded >> {total_size / 1000 / 1000 / cost:.2f}MB/s. {r}')
return {"title": splitext(filename)[0], "filename": splitext(basename(upos_uri))[0], "desc": ""}
except(urllib3.exceptions.ReadTimeoutError, urllib3.exceptions.MaxRetryError,
requests.exceptions.ConnectionError):
ii += 1
logger.info("上传出现问题,尝试重连,次数:" + str(ii))
time.sleep(15)
if r.get('OK') != 1:
raise Exception(r)
@staticmethod
async def _upload(params, file, chunk_size, afunc, tasks=3):
params['chunk'] = -1
async def upload_chunk():
while True:
chunks_data = file.read(chunk_size)
if not chunks_data:
return
params['chunk'] += 1
params['size'] = len(chunks_data)
params['partNumber'] = params['chunk'] + 1
params['start'] = params['chunk'] * chunk_size
params['end'] = params['start'] + params['size']
clone = params.copy()
for i in range(10):
try:
await afunc(session, chunks_data, clone)
break
except (asyncio.TimeoutError, aiohttp.ClientError) as e:
logger.error(f"retry chunk{clone["chunk"]} >> {i + 1}. {e}")
async with aiohttp.ClientSession() as session:
await asyncio.gather(*[upload_chunk() for _ in range(tasks)])
def submit(self, submit_api=None):
if not self.video.title:
self.video.title = self.video.videos[0]["title"]
self.__session.get('https://member.bilibili.com/x/geetest/pre/add', timeout=5)
if submit_api is None:
total_info = self.__session.get('http://api.bilibili.com/x/space/myinfo', timeout=15).json()
if total_info.get('data') is None:
logger.error(total_info)
total_info = total_info.get('data')
if total_info['level'] > 3 and total_info['follower'] > 1000:
user_weight = 2
else:
user_weight = 1
logger.info(f'用户权重: {user_weight}')
submit_api = 'web' if user_weight == 2 else 'client'
ret = None
if submit_api == 'web':
ret = self.submit_web()
if ret["code"] == 21138:
logger.info(f'改用客户端接口提交{ret}')
submit_api = 'client'
if submit_api == 'client':
ret = self.submit_client()
if not ret:
raise Exception(f'不存在的选项:{submit_api}')
if ret["code"] == 0:
return ret
else:
raise Exception(ret)
def submit_web(self):
logger.info('使用网页端api提交')
return self.__session.post(f'https://member.bilibili.com/x/vu/web/add?csrf={self.__bili_jct}', timeout=5,
json=asdict(self.video)).json()
def submit_client(self):
logger.info('使用客户端api端提交')
if not self.access_token:
if self.account is None:
raise RuntimeError("Access token is required, but account and access_token does not exist!")
self.login_by_password(**self.account)
self.store()
while True:
ret = self.__session.post(f'http://member.bilibili.com/x/vu/client/add?access_key={self.access_token}',
timeout=5, json=asdict(self.video)).json()
if ret['code'] == -101:
logger.info(f'刷新token{ret}')
self.login_by_password(**config['user']['account'])
self.store()
continue
return ret
def cover_up(self, img: str):
"""
:param img: img path or stream
:return: img URL
"""
from PIL import Image
from io import BytesIO
with Image.open(img) as im:
# 宽和高,需要16:10
xsize, ysize = im.size
if xsize / ysize > 1.6:
delta = xsize - ysize * 1.6
region = im.crop((delta / 2, 0, xsize - delta / 2, ysize))
else:
delta = ysize - xsize * 10 / 16
region = im.crop((0, delta / 2, xsize, ysize - delta / 2))
buffered = BytesIO()
region.save(buffered, format=im.format)
r = self.__session.post(
url='https://member.bilibili.com/x/vu/web/cover/up',
data={
'cover': b'data:image/jpeg;base64,' + (base64.b64encode(buffered.getvalue())),
'csrf': self.__bili_jct
}, timeout=30
)
buffered.close()
res = r.json()
if res.get('data') is None:
raise Exception(res)
return res['data']['url']
def get_tags(self, upvideo, typeid="", desc="", cover="", groupid=1, vfea=""):
"""
上传视频后获得推荐标签
:param vfea:
:param groupid:
:param typeid:
:param desc:
:param cover:
:param upvideo:
:return: 返回官方推荐的tag
"""
url = f'https://member.bilibili.com/x/web/archive/tags?' \
f'typeid={typeid}&title={quote(upvideo['title'])}&filename=filename&desc={desc}&cover={cover}' \
f'&groupid={groupid}&vfea={vfea}'
return self.__session.get(url=url, timeout=5).json()
def __enter__(self):
return self
def __exit__(self, e_t, e_v, t_b):
self.close()
def close(self):
"""Closes all adapters and as such the session"""
self.__session.close()
@dataclass
class Data:
"""
cover: 封面图片,可由recovers方法得到视频的帧截图
"""
copyright: int = 2
source: str = ''
tid: int = 21
cover: str = ''
title: str = ''
desc_format_id: int = 0
desc: str = ''
dynamic: str = ''
subtitle: dict = field(init=False)
tag: Union[list, str] = ''
videos: list = field(default_factory=list)
dtime: Any = None
open_subtitle: InitVar[bool] = False
# interactive: int = 0
# no_reprint: int 1
# open_elec: int 1
def __post_init__(self, open_subtitle):
self.subtitle = {"open": int(open_subtitle), "lan": ""}
if self.dtime and self.dtime - int(time.time()) <= 14400:
self.dtime = None
if isinstance(self.tag, list):
self.dynamic = f"#{"##".join(self.tag)}#"
self.tag = ','.join(self.tag)
def delay_time(self, dtime: int):
"""设置延时发布时间,距离提交大于4小时,格式为10位时间戳"""
if dtime - int(time.time()) > 14400:
self.dtime = dtime
def set_tag(self, tag: list):
"""设置标签,tag为数组"""
if 'biliup' not in tag:
tag.append('biliup')
self.dynamic = f"#{"##".join(tag)}#"
self.tag = ','.join(tag)
def append(self, video):
self.videos.append(video)
| import asyncio
import base64
import hashlib
import json
import math
import os
import sys
import time
from dataclasses import asdict, dataclass, field, InitVar
from json import JSONDecodeError
from os.path import splitext, basename
from typing import Union, Any
from urllib import parse
from urllib.parse import quote
import aiohttp
import requests.utils
import rsa
import urllib3.exceptions
from requests.adapters import HTTPAdapter, Retry
from biliup import config
from ..engine import Plugin
from ..engine.upload import UploadBase, logger
@Plugin.upload(platform="bili_web")
class BiliWeb(UploadBase):
def __init__(self, principal, data, user, submit_api=None, copyright=2, postprocessor=None,
lines='AUTO', threads=3, tid=122, tags=None, cover_path=None, description=''):
super().__init__(principal, data, persistence_path='bili.cookie', postprocessor=postprocessor)
if tags is None:
tags = []
self.user = user
self.lines = lines
self.submit_api = submit_api
self.threads = threads
self.tid = tid
self.tags = tags
self.cover_path = cover_path
self.desc = description
self.copyright = copyright
def upload(self, file_list):
video = Data()
with BiliBili(video) as bili:
bili.app_key = self.user.get('app_key')
bili.appsec = self.user.get('appsec')
bili.login(self.persistence_path, self.user)
for file in file_list:
video_part = bili.upload_file(file, self.lines, self.threads) # 上传视频
video.append(video_part) # 添加已经上传的视频
video.title = self.data["format_title"]
video.desc = self.desc + '''
Powered By biliup
Github:https://github.com/ForgQi/biliup'''
video.copyright = self.copyright
if self.copyright == 2:
video.source = self.data["url"] # 添加转载地址说明
# 设置视频分区,默认为174 生活,其他分区
video.tid = self.tid
video.set_tag(self.tags)
if self.cover_path:
video.cover = bili.cover_up(self.cover_path).replace('http:', '')
ret = bili.submit(self.submit_api) # 提交视频
logger.info(f"上传成功: {ret}")
return file_list
class BiliBili:
def __init__(self, video: 'Data'):
self.app_key = None
self.appsec = None
if self.app_key is None or self.appsec is None:
self.app_key = 'ae57252b0c09105d'
self.appsec = 'c75875c596a69eb55bd119e74b07cfe3'
self.__session = requests.Session()
self.video = video
self.__session.mount('https://', HTTPAdapter(max_retries=Retry(total=5, method_whitelist=False)))
self.__session.headers.update({
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/63.0.3239.108",
"Referer": "https://www.bilibili.com/", 'Connection': 'keep-alive'
})
self.cookies = None
self.access_token = None
self.refresh_token = None
self.account = None
self.__bili_jct = None
self._auto_os = None
self.persistence_path = 'engine/bili.cookie'
def login(self, persistence_path, user):
self.persistence_path = persistence_path
if os.path.isfile(persistence_path):
print('使用持久化内容上传')
self.load()
if not self.cookies and user.get('cookies'):
self.cookies = user['cookies']
if not self.access_token and user.get('access_token'):
self.access_token = user['access_token']
if not self.account and user.get('account'):
self.account = user['account']
if self.cookies:
try:
self.login_by_cookies(self.cookies)
except:
logger.exception('login error')
self.login_by_password(**self.account)
else:
self.login_by_password(**self.account)
self.store()
def load(self):
try:
with open(self.persistence_path) as f:
self.cookies = json.load(f)
self.access_token = self.cookies['access_token']
except (JSONDecodeError, KeyError):
logger.exception('加载cookie出错')
def store(self):
with open(self.persistence_path, "w") as f:
json.dump({**self.cookies,
'access_token': self.access_token,
'refresh_token': self.refresh_token
}, f)
def login_by_password(self, username, password):
print('使用账号上传')
key_hash, pub_key = self.get_key()
encrypt_password = base64.b64encode(rsa.encrypt(f'{key_hash}{password}'.encode(), pub_key))
payload = {
"actionKey": 'appkey',
"appkey": self.app_key,
"build": 6270200,
"captcha": '',
"challenge": '',
"channel": 'bili',
"device": 'phone',
"mobi_app": 'android',
"password": encrypt_password,
"permission": 'ALL',
"platform": 'android',
"seccode": "",
"subid": 1,
"ts": int(time.time()),
"username": username,
"validate": "",
}
response = self.__session.post("https://passport.bilibili.com/x/passport-login/oauth2/login", timeout=5,
data={**payload, 'sign': self.sign(parse.urlencode(payload))})
r = response.json()
if r['code'] != 0 or r.get('data') is None or r['data'].get('cookie_info') is None:
raise RuntimeError(r)
try:
for cookie in r['data']['cookie_info']['cookies']:
self.__session.cookies.set(cookie['name'], cookie['value'])
if 'bili_jct' == cookie['name']:
self.__bili_jct = cookie['value']
self.cookies = self.__session.cookies.get_dict()
self.access_token = r['data']['token_info']['access_token']
self.refresh_token = r['data']['token_info']['refresh_token']
except:
raise RuntimeError(r)
return r
def login_by_cookies(self, cookie):
print('使用cookies上传')
requests.utils.add_dict_to_cookiejar(self.__session.cookies, cookie)
if 'bili_jct' in cookie:
self.__bili_jct = cookie["bili_jct"]
data = self.__session.get("https://api.bilibili.com/x/web-interface/nav", timeout=5).json()
if data["code"] != 0:
raise Exception(data)
def sign(self, param):
return hashlib.md5(f"{param}{self.appsec}".encode()).hexdigest()
def get_key(self):
url = "https://passport.bilibili.com/x/passport-login/web/key"
payload = {
'appkey': f'{self.app_key}',
'sign': self.sign(f"appkey={self.app_key}"),
}
response = self.__session.get(url, data=payload, timeout=5)
r = response.json()
if r and r["code"] == 0:
return r['data']['hash'], rsa.PublicKey.load_pkcs1_openssl_pem(r['data']['key'].encode())
def probe(self):
ret = self.__session.get('https://member.bilibili.com/preupload?r=probe', timeout=5).json()
logger.info(f"线路:{ret['lines']}")
data, auto_os = None, None
min_cost = 0
if ret['probe'].get('get'):
method = 'get'
else:
method = 'post'
data = bytes(int(1024 * 0.1 * 1024))
for line in ret['lines']:
start = time.perf_counter()
test = self.__session.request(method, f"https:{line['probe_url']}", data=data, timeout=30)
cost = time.perf_counter() - start
print(line['query'], cost)
if test.status_code != 200:
return
if not min_cost or min_cost > cost:
auto_os = line
min_cost = cost
auto_os['cost'] = min_cost
return auto_os
def upload_file(self, filepath: str, lines='AUTO', tasks=3):
"""上传本地视频文件,返回视频信息dict
b站目前支持4种上传线路upos, kodo, gcs, bos
gcs: {"os":"gcs","query":"bucket=bvcupcdngcsus&probe_version=20200810",
"probe_url":"//storage.googleapis.com/bvcupcdngcsus/OK"},
bos: {"os":"bos","query":"bucket=bvcupcdnboshb&probe_version=20200810",
"probe_url":"??"}
"""
if not self._auto_os:
self._auto_os = self.probe()
if lines == 'kodo':
self._auto_os = {"os": "kodo", "query": "bucket=bvcupcdnkodobm&probe_version=20200810",
"probe_url": "//up-na0.qbox.me/crossdomain.xml"}
if lines == 'bda2':
self._auto_os = {"os": "upos", "query": "upcdn=bda2&probe_version=20200810",
"probe_url": "//upos-sz-upcdnbda2.bilivideo.com/OK"}
if lines == 'ws':
self._auto_os = {"os": "upos", "query": "upcdn=ws&probe_version=20200810",
"probe_url": "//upos-sz-upcdnws.bilivideo.com/OK"}
if lines == 'qn':
self._auto_os = {"os": "upos", "query": "upcdn=qn&probe_version=20200810",
"probe_url": "//upos-sz-upcdnqn.bilivideo.com/OK"}
logger.info(f"线路选择 => {self._auto_os['os']}: {self._auto_os['query']}. time: {self._auto_os.get('cost')}")
if self._auto_os['os'] == 'upos':
upload = self.upos
elif self._auto_os['os'] == 'kodo':
upload = self.kodo
elif self._auto_os['os'] == "gcs":
raise NotImplementedError('gcs')
elif self._auto_os['os'] == "bos":
raise NotImplementedError('bos')
else:
logger.error(f"NoSearch:{self._auto_os['os']}")
raise NotImplementedError(self._auto_os['os'])
total_size = os.path.getsize(filepath)
with open(filepath, 'rb') as f:
query = {
'r': self._auto_os['os'],
'profile': 'ugcupos/bup' if 'upos' == self._auto_os['os'] else "ugcupos/bupfetch",
'ssl': 0,
'version': '2.8.12',
'build': 2081200,
'name': f.name,
'size': total_size,
}
ret = self.__session.get(
f"https://member.bilibili.com/preupload?{self._auto_os['query']}", params=query,
timeout=5)
return asyncio.run(upload(f, total_size, ret.json(), tasks=tasks))
async def kodo(self, file, total_size, ret, chunk_size=4194304, tasks=3):
filename = file.name
bili_filename = ret['bili_filename']
key = ret['key']
endpoint = f"https:{ret['endpoint']}"
token = ret['uptoken']
fetch_url = ret['fetch_url']
fetch_headers = ret['fetch_headers']
url = f'{endpoint}/mkblk'
headers = {
'Authorization': f"UpToken {token}",
}
# 开始上传
parts = [] # 分块信息
chunks = math.ceil(total_size / chunk_size) # 获取分块数量
async def upload_chunk(session, chunks_data, params):
async with session.post(f'{url}/{len(chunks_data)}',
data=chunks_data, headers=headers) as response:
end = time.perf_counter() - start
ctx = await response.json()
parts.append({"index": params['chunk'], "ctx": ctx['ctx']})
sys.stdout.write(f"\r{params['end'] / 1000 / 1000 / end:.2f}MB/s "
f"=> {params['partNumber'] / chunks:.1%}")
start = time.perf_counter()
await self._upload({}, file, chunk_size, upload_chunk, tasks=tasks)
cost = time.perf_counter() - start
logger.info(f'{filename} uploaded >> {total_size / 1000 / 1000 / cost:.2f}MB/s')
parts.sort(key=lambda x: x['index'])
self.__session.post(f"{endpoint}/mkfile/{total_size}/key/{base64.urlsafe_b64encode(key.encode()).decode()}",
data=','.join(map(lambda x: x['ctx'], parts)), headers=headers, timeout=10)
r = self.__session.post(f"https:{fetch_url}", headers=fetch_headers, timeout=5).json()
if r["OK"] != 1:
raise Exception(r)
return {"title": splitext(filename)[0], "filename": bili_filename, "desc": ""}
async def upos(self, file, total_size, ret, tasks=3):
filename = file.name
chunk_size = ret['chunk_size']
auth = ret["auth"]
endpoint = ret["endpoint"]
biz_id = ret["biz_id"]
upos_uri = ret["upos_uri"]
url = f"https:{endpoint}/{upos_uri.replace('upos://', '')}" # 视频上传路径
headers = {
"X-Upos-Auth": auth
}
# 向上传地址申请上传,得到上传id等信息
upload_id = self.__session.post(f'{url}?uploads&output=json', timeout=5,
headers=headers).json()["upload_id"]
# 开始上传
parts = [] # 分块信息
chunks = math.ceil(total_size / chunk_size) # 获取分块数量
async def upload_chunk(session, chunks_data, params):
async with session.put(url, params=params, raise_for_status=True,
data=chunks_data, headers=headers):
end = time.perf_counter() - start
parts.append({"partNumber": params['chunk'] + 1, "eTag": "etag"})
sys.stdout.write(f"\r{params['end'] / 1000 / 1000 / end:.2f}MB/s "
f"=> {params['partNumber'] / chunks:.1%}")
start = time.perf_counter()
await self._upload({
'uploadId': upload_id,
'chunks': chunks,
'total': total_size
}, file, chunk_size, upload_chunk, tasks=tasks)
cost = time.perf_counter() - start
p = {
'name': filename,
'uploadId': upload_id,
'biz_id': biz_id,
'output': 'json',
'profile': 'ugcupos/bup'
}
ii = 0
while ii <= 3:
try:
r = self.__session.post(url, params=p, json={"parts": parts}, headers=headers, timeout=15).json()
if r.get('OK') == 1:
logger.info(f'{filename} uploaded >> {total_size / 1000 / 1000 / cost:.2f}MB/s. {r}')
return {"title": splitext(filename)[0], "filename": splitext(basename(upos_uri))[0], "desc": ""}
except(urllib3.exceptions.ReadTimeoutError, urllib3.exceptions.MaxRetryError,
requests.exceptions.ConnectionError):
ii += 1
logger.info("上传出现问题,尝试重连,次数:" + str(ii))
time.sleep(15)
if r.get('OK') != 1:
raise Exception(r)
@staticmethod
async def _upload(params, file, chunk_size, afunc, tasks=3):
params['chunk'] = -1
async def upload_chunk():
while True:
chunks_data = file.read(chunk_size)
if not chunks_data:
return
params['chunk'] += 1
params['size'] = len(chunks_data)
params['partNumber'] = params['chunk'] + 1
params['start'] = params['chunk'] * chunk_size
params['end'] = params['start'] + params['size']
clone = params.copy()
for i in range(10):
try:
await afunc(session, chunks_data, clone)
break
except (asyncio.TimeoutError, aiohttp.ClientError) as e:
logger.error(f"retry chunk{clone['chunk']} >> {i + 1}. {e}")
async with aiohttp.ClientSession() as session:
await asyncio.gather(*[upload_chunk() for _ in range(tasks)])
def submit(self, submit_api=None):
if not self.video.title:
self.video.title = self.video.videos[0]["title"]
self.__session.get('https://member.bilibili.com/x/geetest/pre/add', timeout=5)
if submit_api is None:
total_info = self.__session.get('http://api.bilibili.com/x/space/myinfo', timeout=15).json()
if total_info.get('data') is None:
logger.error(total_info)
total_info = total_info.get('data')
if total_info['level'] > 3 and total_info['follower'] > 1000:
user_weight = 2
else:
user_weight = 1
logger.info(f'用户权重: {user_weight}')
submit_api = 'web' if user_weight == 2 else 'client'
ret = None
if submit_api == 'web':
ret = self.submit_web()
if ret["code"] == 21138:
logger.info(f'改用客户端接口提交{ret}')
submit_api = 'client'
if submit_api == 'client':
ret = self.submit_client()
if not ret:
raise Exception(f'不存在的选项:{submit_api}')
if ret["code"] == 0:
return ret
else:
raise Exception(ret)
def submit_web(self):
logger.info('使用网页端api提交')
return self.__session.post(f'https://member.bilibili.com/x/vu/web/add?csrf={self.__bili_jct}', timeout=5,
json=asdict(self.video)).json()
def submit_client(self):
logger.info('使用客户端api端提交')
if not self.access_token:
if self.account is None:
raise RuntimeError("Access token is required, but account and access_token does not exist!")
self.login_by_password(**self.account)
self.store()
while True:
ret = self.__session.post(f'http://member.bilibili.com/x/vu/client/add?access_key={self.access_token}',
timeout=5, json=asdict(self.video)).json()
if ret['code'] == -101:
logger.info(f'刷新token{ret}')
self.login_by_password(**config['user']['account'])
self.store()
continue
return ret
def cover_up(self, img: str):
"""
:param img: img path or stream
:return: img URL
"""
from PIL import Image
from io import BytesIO
with Image.open(img) as im:
# 宽和高,需要16:10
xsize, ysize = im.size
if xsize / ysize > 1.6:
delta = xsize - ysize * 1.6
region = im.crop((delta / 2, 0, xsize - delta / 2, ysize))
else:
delta = ysize - xsize * 10 / 16
region = im.crop((0, delta / 2, xsize, ysize - delta / 2))
buffered = BytesIO()
region.save(buffered, format=im.format)
r = self.__session.post(
url='https://member.bilibili.com/x/vu/web/cover/up',
data={
'cover': b'data:image/jpeg;base64,' + (base64.b64encode(buffered.getvalue())),
'csrf': self.__bili_jct
}, timeout=30
)
buffered.close()
res = r.json()
if res.get('data') is None:
raise Exception(res)
return res['data']['url']
def get_tags(self, upvideo, typeid="", desc="", cover="", groupid=1, vfea=""):
"""
上传视频后获得推荐标签
:param vfea:
:param groupid:
:param typeid:
:param desc:
:param cover:
:param upvideo:
:return: 返回官方推荐的tag
"""
url = f'https://member.bilibili.com/x/web/archive/tags?' \
f'typeid={typeid}&title={quote(upvideo["title"])}&filename=filename&desc={desc}&cover={cover}' \
f'&groupid={groupid}&vfea={vfea}'
return self.__session.get(url=url, timeout=5).json()
def __enter__(self):
return self
def __exit__(self, e_t, e_v, t_b):
self.close()
def close(self):
"""Closes all adapters and as such the session"""
self.__session.close()
@dataclass
class Data:
"""
cover: 封面图片,可由recovers方法得到视频的帧截图
"""
copyright: int = 2
source: str = ''
tid: int = 21
cover: str = ''
title: str = ''
desc_format_id: int = 0
desc: str = ''
dynamic: str = ''
subtitle: dict = field(init=False)
tag: Union[list, str] = ''
videos: list = field(default_factory=list)
dtime: Any = None
open_subtitle: InitVar[bool] = False
# interactive: int = 0
# no_reprint: int 1
# open_elec: int 1
def __post_init__(self, open_subtitle):
self.subtitle = {"open": int(open_subtitle), "lan": ""}
if self.dtime and self.dtime - int(time.time()) <= 14400:
self.dtime = None
if isinstance(self.tag, list):
self.dynamic = f"#{'##'.join(self.tag)}#"
self.tag = ','.join(self.tag)
def delay_time(self, dtime: int):
"""设置延时发布时间,距离提交大于4小时,格式为10位时间戳"""
if dtime - int(time.time()) > 14400:
self.dtime = dtime
def set_tag(self, tag: list):
"""设置标签,tag为数组"""
if 'biliup' not in tag:
tag.append('biliup')
self.dynamic = f"#{'##'.join(tag)}#"
self.tag = ','.join(tag)
def append(self, video):
self.videos.append(video)
|
import logging
import discord
from redbot.core import Config, commands
from redbot.core.bot import Red
from redbot.core.utils.chat_formatting import box, humanize_list
from .utils import Coordinate
log = logging.getLogger("red.craycogs.joinping")
guild_defaults = {
"ping_channels": [],
"delete_after": 2,
"ping_message": "{member.mention}",
}
class JoinPing(commands.Cog):
"""
Ghost ping users when they join."""
__version__ = "1.0.1"
__author__ = ["crayyy_zee#2900"]
def __init__(self, bot: Red):
self.bot = bot
self.config = Config.get_conf(self, identifier=56789, force_registration=True)
self.config.register_guild(**guild_defaults)
self.cache = {}
def format_help_for_context(self, ctx: commands.Context) -> str:
pre_processed = super().format_help_for_context(ctx)
n = "\n" if "\n\n" not in pre_processed else ""
text = [
f"{pre_processed}{n}",
f"Cog Version: **{self.__version__}**",
f"Author: {humanize_list(self.__author__)}",
]
return "\n".join(text)
async def _build_cache(self):
self.cache = await self.config.all_guilds()
async def red_delete_data_for_user(self, *, requester, user_id: int):
return True
@commands.Cog.listener()
async def on_member_join(self, member):
guild_data: dict = self.cache.get(member.guild.id)
if not guild_data:
return
if not guild_data.get("ping_channels"):
return
for i in guild_data.get("ping_channels"):
channel = self.bot.get_channel(i)
if not channel:
continue
message = f"{(guild_data.get("ping_message", "")).format_map(Coordinate(member=member, server=member.guild.name, guild=member.guild.name))}"
try:
await channel.send(
message,
delete_after=guild_data.get("delete_after"),
allowed_mentions=discord.AllowedMentions(users=True),
)
except discord.HTTPException:
pass
log.debug(
f"{member} joined the guild {member.guild.name} and was pinged in {humanize_list([str(i) for i in guild_data.get("ping_channels")])}"
)
@commands.group(name="jpset", aliases=["joinpingset"], invoke_without_command=True)
@commands.guild_only()
@commands.admin_or_permissions(administrator=True)
async def jpset(self, ctx):
"""
Adjust the settings for the cog."""
return await ctx.send_help()
@jpset.command(name="test", aliases=["testping"], hidden=True)
async def jpset_test(self, ctx):
"""
Test whether the pings and message you set up work correctly.
This is hidden as to not abuse the pings.
"""
if not self.cache.get(ctx.guild.id):
return await ctx.send("You haven't set up the join ping yet ._.")
await self.on_member_join(ctx.author)
@jpset.command(name="deleteafter", aliases=["da"])
async def jpset_da(self, ctx, seconds: int):
"""Set the time in seconds after which the ping message will be deleted."""
if seconds < 0:
return await ctx.send("The time must be a positive integer.")
await self.config.guild(ctx.guild).delete_after.set(seconds)
await self._build_cache()
await ctx.send(f"The ping message will be deleted after {seconds} seconds.")
@jpset.command(name="message", aliases=["m"])
async def jpset_msg(self, ctx, *, message: str):
"""Set the message that will be sent when a user joins.
Usable placeholders include:
- member (the member that joined)
- member.mention (the mention)
- member.id (the id)
- member.name (the name)
- member.discriminator (the discriminator)
- server (the name of the server the member joined)
These placeholders must be places within `{}` (curly brackets) to be replaced with actual values."""
await self.config.guild(ctx.guild).ping_message.set(message)
await self._build_cache()
await ctx.send(f"The ping message has been set to:\n{message}")
@jpset.group(name="channel", aliases=["c", "channels"], invoke_without_command=True)
async def jpset_channels(self, ctx):
"""
Set the channels where the pings will be sent on member join."""
@jpset_channels.command(name="remove", aliases=["r"])
async def jpsetchan_remove(self, ctx, *channels: discord.TextChannel):
"""
Add the channels to the list of channels where the pings will be sent on member join."""
cached_chans = self.cache.setdefault(ctx.guild.id, guild_defaults).get("ping_channels")
al_present = []
channels = list(channels)
for i in channels.copy():
if i.id not in cached_chans:
al_present.append(i.id)
channels.remove(i)
final = set(cached_chans) - set(channels)
await self.config.guild(ctx.guild).ping_channels.set(list(final))
await self._build_cache()
await ctx.send(
f"The channel to ping in have been removed. There are currently {len(final)} channels."
)
@jpset_channels.command(name="add", aliases=["a"])
async def jpsetchan_add(self, ctx, *channels: discord.TextChannel):
"""
Remove the channels from the list of channels where the pings will be sent on member join."""
cached_chans = self.cache.setdefault(ctx.guild.id, guild_defaults).get("ping_channels")
al_present = (channels := {a.id for a in channels}) & set(cached_chans)
channels -= al_present
cached_chans += channels
await self.config.guild(ctx.guild).ping_channels.set(cached_chans)
await self._build_cache()
await ctx.send(
f"The channel to ping in have been added. There are currently {len(cached_chans)} channels.\n"
+ (
f"The following channels were already present: {", ".join([f"<#{chan}>' for chan in al_present])}"
if al_present
else ""
)
)
@jpset.command(name="show", aliases=["showsettings", "settings", "setting"])
async def jpset_show(self, ctx):
data = self.cache.setdefault(ctx.guild.id, guild_defaults)
channels = data.get("ping_channels", [])
message = data.get("ping_message", "{member.mention}")
delete_after = data.get("delete_after", 2)
if not channels:
return await ctx.send(
f"JoinPing is not enabled for your guild. Please enable first by running the `{ctx.prefix}jpset channels` command."
)
embed = (
discord.Embed(
title=f"JoinPing Settings for **__{ctx.guild.name}__**",
color=await ctx.embed_colour(),
)
.add_field(
name="Channels", value=" ".join([f"<#{i}>" for i in channels]), inline=False
)
.add_field(name="Message", value=box(message, "py"), inline=False)
.add_field(
name="Delete After (seconds)", value=box(f"{delete_after} seconds"), inline=False
)
)
| import logging
import discord
from redbot.core import Config, commands
from redbot.core.bot import Red
from redbot.core.utils.chat_formatting import box, humanize_list
from .utils import Coordinate
log = logging.getLogger("red.craycogs.joinping")
guild_defaults = {
"ping_channels": [],
"delete_after": 2,
"ping_message": "{member.mention}",
}
class JoinPing(commands.Cog):
"""
Ghost ping users when they join."""
__version__ = "1.0.1"
__author__ = ["crayyy_zee#2900"]
def __init__(self, bot: Red):
self.bot = bot
self.config = Config.get_conf(self, identifier=56789, force_registration=True)
self.config.register_guild(**guild_defaults)
self.cache = {}
def format_help_for_context(self, ctx: commands.Context) -> str:
pre_processed = super().format_help_for_context(ctx)
n = "\n" if "\n\n" not in pre_processed else ""
text = [
f"{pre_processed}{n}",
f"Cog Version: **{self.__version__}**",
f"Author: {humanize_list(self.__author__)}",
]
return "\n".join(text)
async def _build_cache(self):
self.cache = await self.config.all_guilds()
async def red_delete_data_for_user(self, *, requester, user_id: int):
return True
@commands.Cog.listener()
async def on_member_join(self, member):
guild_data: dict = self.cache.get(member.guild.id)
if not guild_data:
return
if not guild_data.get("ping_channels"):
return
for i in guild_data.get("ping_channels"):
channel = self.bot.get_channel(i)
if not channel:
continue
message = f"{(guild_data.get('ping_message', '')).format_map(Coordinate(member=member, server=member.guild.name, guild=member.guild.name))}"
try:
await channel.send(
message,
delete_after=guild_data.get("delete_after"),
allowed_mentions=discord.AllowedMentions(users=True),
)
except discord.HTTPException:
pass
log.debug(
f"{member} joined the guild {member.guild.name} and was pinged in {humanize_list([str(i) for i in guild_data.get('ping_channels')])}"
)
@commands.group(name="jpset", aliases=["joinpingset"], invoke_without_command=True)
@commands.guild_only()
@commands.admin_or_permissions(administrator=True)
async def jpset(self, ctx):
"""
Adjust the settings for the cog."""
return await ctx.send_help()
@jpset.command(name="test", aliases=["testping"], hidden=True)
async def jpset_test(self, ctx):
"""
Test whether the pings and message you set up work correctly.
This is hidden as to not abuse the pings.
"""
if not self.cache.get(ctx.guild.id):
return await ctx.send("You haven't set up the join ping yet ._.")
await self.on_member_join(ctx.author)
@jpset.command(name="deleteafter", aliases=["da"])
async def jpset_da(self, ctx, seconds: int):
"""Set the time in seconds after which the ping message will be deleted."""
if seconds < 0:
return await ctx.send("The time must be a positive integer.")
await self.config.guild(ctx.guild).delete_after.set(seconds)
await self._build_cache()
await ctx.send(f"The ping message will be deleted after {seconds} seconds.")
@jpset.command(name="message", aliases=["m"])
async def jpset_msg(self, ctx, *, message: str):
"""Set the message that will be sent when a user joins.
Usable placeholders include:
- member (the member that joined)
- member.mention (the mention)
- member.id (the id)
- member.name (the name)
- member.discriminator (the discriminator)
- server (the name of the server the member joined)
These placeholders must be places within `{}` (curly brackets) to be replaced with actual values."""
await self.config.guild(ctx.guild).ping_message.set(message)
await self._build_cache()
await ctx.send(f"The ping message has been set to:\n{message}")
@jpset.group(name="channel", aliases=["c", "channels"], invoke_without_command=True)
async def jpset_channels(self, ctx):
"""
Set the channels where the pings will be sent on member join."""
@jpset_channels.command(name="remove", aliases=["r"])
async def jpsetchan_remove(self, ctx, *channels: discord.TextChannel):
"""
Add the channels to the list of channels where the pings will be sent on member join."""
cached_chans = self.cache.setdefault(ctx.guild.id, guild_defaults).get("ping_channels")
al_present = []
channels = list(channels)
for i in channels.copy():
if i.id not in cached_chans:
al_present.append(i.id)
channels.remove(i)
final = set(cached_chans) - set(channels)
await self.config.guild(ctx.guild).ping_channels.set(list(final))
await self._build_cache()
await ctx.send(
f"The channel to ping in have been removed. There are currently {len(final)} channels."
)
@jpset_channels.command(name="add", aliases=["a"])
async def jpsetchan_add(self, ctx, *channels: discord.TextChannel):
"""
Remove the channels from the list of channels where the pings will be sent on member join."""
cached_chans = self.cache.setdefault(ctx.guild.id, guild_defaults).get("ping_channels")
al_present = (channels := {a.id for a in channels}) & set(cached_chans)
channels -= al_present
cached_chans += channels
await self.config.guild(ctx.guild).ping_channels.set(cached_chans)
await self._build_cache()
await ctx.send(
f"The channel to ping in have been added. There are currently {len(cached_chans)} channels.\n"
+ (
f"The following channels were already present: {', '.join([f'<#{chan}>' for chan in al_present])}"
if al_present
else ""
)
)
@jpset.command(name="show", aliases=["showsettings", "settings", "setting"])
async def jpset_show(self, ctx):
data = self.cache.setdefault(ctx.guild.id, guild_defaults)
channels = data.get("ping_channels", [])
message = data.get("ping_message", "{member.mention}")
delete_after = data.get("delete_after", 2)
if not channels:
return await ctx.send(
f"JoinPing is not enabled for your guild. Please enable first by running the `{ctx.prefix}jpset channels` command."
)
embed = (
discord.Embed(
title=f"JoinPing Settings for **__{ctx.guild.name}__**",
color=await ctx.embed_colour(),
)
.add_field(
name="Channels", value=" ".join([f"<#{i}>" for i in channels]), inline=False
)
.add_field(name="Message", value=box(message, "py"), inline=False)
.add_field(
name="Delete After (seconds)", value=box(f"{delete_after} seconds"), inline=False
)
)
|
from contextlib import contextmanager
from pathlib import Path
from textwrap import indent
from typing import Tuple
import pytest
import sqlalchemy
import structlog
from click.testing import CliRunner
from datacube.drivers.postgres import PostgresDb
from datacube.drivers.postgres._core import METADATA as ODC_SCHEMA_METADATA
from datacube.index import Index
from datacube.index.hl import Doc2Dataset
from datacube.model import Dataset
from datacube.utils import read_documents
from digitalearthau.testing import factories
from flask.testing import FlaskClient
from structlog import DropEvent
import cubedash
from cubedash import _model, _utils, generate, logs
from cubedash.summary import SummaryStore
from cubedash.summary._schema import METADATA as CUBEDASH_METADATA
from cubedash.warmup import find_examples_of_all_public_urls
# Use module-scoped databases, as it takes a while to populate with
# our data, and we're treating it as read-only in tests.
# -> Note: Since we're reusing the default config unchanged, we can't use the
# default index/dea_index fixtures, as they'll override data from
# the same db.
from integration_tests.asserts import format_doc_diffs
module_vanilla_db = factories.db_fixture("local_config", scope="module")
def pytest_assertrepr_compare(op, left, right):
"""
Custom pytest error messages for large documents.
The default pytest dict==dict error messages are unreadable for
nested document-like dicts. (Such as our json and yaml docs!)
We just want to know which fields differ.
"""
def is_a_doc(o: object):
"""
Is it a dict that's not printable on one line?
"""
return isinstance(o, dict) and len(repr(o)) > 79
if (is_a_doc(left) or is_a_doc(right)) and op == "==":
return format_doc_diffs(left, right)
@pytest.fixture(scope="module")
def module_db(module_vanilla_db: PostgresDb) -> PostgresDb:
# Set all the tables to unlogged for faster perf.
_make_all_tables_unlogged(module_vanilla_db._engine, ODC_SCHEMA_METADATA)
return module_vanilla_db
def _make_all_tables_unlogged(engine, metadata: sqlalchemy.MetaData):
"""
Set all tables in this alchemy metadata to unlogged.
Make them faster, but data is lost on crashes. Which is a good
trade-off for tests.
"""
for table in reversed(metadata.sorted_tables):
table: sqlalchemy.Table
if table.name.startswith("mv_"):
# Not supported for materialised views.
continue
else:
engine.execute(f"""alter table {table.selectable.fullname} set unlogged;""")
module_index = factories.index_fixture("module_db", scope="module")
module_dea_index = factories.dea_index_fixture("module_index", scope="module")
TEST_DATA_DIR = Path(__file__).parent / "data"
@pytest.fixture()
def summary_store(module_dea_index: Index) -> SummaryStore:
store = SummaryStore.create(module_dea_index)
store.drop_all()
module_dea_index.close()
with disable_logging():
# Some CRS/storage tests use test data that is 3577
store.init(grouping_epsg_code=3577)
_make_all_tables_unlogged(
_utils.alchemy_engine(module_dea_index), CUBEDASH_METADATA
)
return store
@pytest.fixture()
def summariser(summary_store: SummaryStore):
return summary_store._summariser
@pytest.fixture(autouse=True, scope="session")
def _init_logs(pytestconfig):
logs.init_logging(
verbosity=pytestconfig.getoption("verbose"), cache_logger_on_first_use=False
)
@pytest.fixture()
def tmppath(tmpdir):
return Path(str(tmpdir))
@pytest.fixture()
def clirunner(global_integration_cli_args):
def _run_cli(cli_method, opts, catch_exceptions=False, expect_success=True):
exe_opts = list(global_integration_cli_args)
exe_opts.extend(opts)
runner = CliRunner()
result = runner.invoke(cli_method, exe_opts, catch_exceptions=catch_exceptions)
if expect_success:
assert (
0 == result.exit_code
), f"Error for {opts}. Out:\n{indent(result.output, " " * 4)}"
return result
return _run_cli
@pytest.fixture()
def run_generate(clirunner, summary_store, multi_processed=False):
def do(*args, expect_success=True):
args = args or ("--all",)
if not multi_processed:
args = ("-j", "1") + tuple(args)
res = clirunner(generate.cli, args, expect_success=expect_success)
return res
return do
@pytest.fixture(scope="module")
def dataset_loader(module_dea_index: Index):
def _populate_from_dump(expected_type: str, dump_path: Path):
ls8_nbar_scene = module_dea_index.products.get_by_name(expected_type)
dataset_count = 0
create_dataset = Doc2Dataset(module_dea_index)
for _, doc in read_documents(dump_path):
label = doc["ga_label"] if ("ga_label" in doc) else doc["id"]
# type: Tuple[Dataset, str]
dataset, err = create_dataset(
doc, f"file://example.com/test_dataset/{label}"
)
assert dataset is not None, err
assert dataset.type.name == expected_type
created = module_dea_index.datasets.add(dataset)
assert created.uris
assert created.type.name == ls8_nbar_scene.name
dataset_count += 1
print(f"Populated {dataset_count} of {expected_type}")
return dataset_count
return _populate_from_dump
@pytest.fixture()
def all_urls(summary_store: SummaryStore):
"""A list of public URLs to try on the current Explorer instance"""
return list(find_examples_of_all_public_urls(summary_store.index))
@pytest.fixture()
def empty_client(summary_store: SummaryStore) -> FlaskClient:
_model.cache.clear()
_model.STORE = summary_store
cubedash.app.config["TESTING"] = True
return cubedash.app.test_client()
@pytest.fixture()
def unpopulated_client(
empty_client: FlaskClient, summary_store: SummaryStore
) -> FlaskClient:
with disable_logging():
_model.STORE.refresh_all_product_extents()
return empty_client
@contextmanager
def disable_logging():
"""
Turn off logging within the if-block
Used for repetitive environment setup that makes test errors too verbose.
"""
original_processors = structlog.get_config()["processors"]
def swallow_log(_logger, _log_method, _event_dict):
raise DropEvent
structlog.configure(processors=[swallow_log])
try:
yield
finally:
structlog.configure(processors=original_processors)
@pytest.fixture()
def client(unpopulated_client: FlaskClient) -> FlaskClient:
with disable_logging():
for product in _model.STORE.index.products.get_all():
_model.STORE.refresh(product.name)
return unpopulated_client
@pytest.fixture(scope="module")
def populated_index(dataset_loader, module_dea_index):
"""
Index populated with example datasets. Assumes our tests wont modify the data!
It's module-scoped as it's expensive to populate.
"""
loaded = dataset_loader("wofs_albers", TEST_DATA_DIR / "wofs-albers-sample.yaml.gz")
assert loaded == 11
loaded = dataset_loader(
"high_tide_comp_20p", TEST_DATA_DIR / "high_tide_comp_20p.yaml.gz"
)
assert loaded == 306
# These have very large footprints, as they were unioned from many almost-identical
# polygons and not simplified. They will trip up postgis if used naively.
# (postgis gist index has max record size of 8k per entry)
loaded = dataset_loader(
"pq_count_summary", TEST_DATA_DIR / "pq_count_summary.yaml.gz"
)
assert loaded == 20
return module_dea_index
| from contextlib import contextmanager
from pathlib import Path
from textwrap import indent
from typing import Tuple
import pytest
import sqlalchemy
import structlog
from click.testing import CliRunner
from datacube.drivers.postgres import PostgresDb
from datacube.drivers.postgres._core import METADATA as ODC_SCHEMA_METADATA
from datacube.index import Index
from datacube.index.hl import Doc2Dataset
from datacube.model import Dataset
from datacube.utils import read_documents
from digitalearthau.testing import factories
from flask.testing import FlaskClient
from structlog import DropEvent
import cubedash
from cubedash import _model, _utils, generate, logs
from cubedash.summary import SummaryStore
from cubedash.summary._schema import METADATA as CUBEDASH_METADATA
from cubedash.warmup import find_examples_of_all_public_urls
# Use module-scoped databases, as it takes a while to populate with
# our data, and we're treating it as read-only in tests.
# -> Note: Since we're reusing the default config unchanged, we can't use the
# default index/dea_index fixtures, as they'll override data from
# the same db.
from integration_tests.asserts import format_doc_diffs
module_vanilla_db = factories.db_fixture("local_config", scope="module")
def pytest_assertrepr_compare(op, left, right):
"""
Custom pytest error messages for large documents.
The default pytest dict==dict error messages are unreadable for
nested document-like dicts. (Such as our json and yaml docs!)
We just want to know which fields differ.
"""
def is_a_doc(o: object):
"""
Is it a dict that's not printable on one line?
"""
return isinstance(o, dict) and len(repr(o)) > 79
if (is_a_doc(left) or is_a_doc(right)) and op == "==":
return format_doc_diffs(left, right)
@pytest.fixture(scope="module")
def module_db(module_vanilla_db: PostgresDb) -> PostgresDb:
# Set all the tables to unlogged for faster perf.
_make_all_tables_unlogged(module_vanilla_db._engine, ODC_SCHEMA_METADATA)
return module_vanilla_db
def _make_all_tables_unlogged(engine, metadata: sqlalchemy.MetaData):
"""
Set all tables in this alchemy metadata to unlogged.
Make them faster, but data is lost on crashes. Which is a good
trade-off for tests.
"""
for table in reversed(metadata.sorted_tables):
table: sqlalchemy.Table
if table.name.startswith("mv_"):
# Not supported for materialised views.
continue
else:
engine.execute(f"""alter table {table.selectable.fullname} set unlogged;""")
module_index = factories.index_fixture("module_db", scope="module")
module_dea_index = factories.dea_index_fixture("module_index", scope="module")
TEST_DATA_DIR = Path(__file__).parent / "data"
@pytest.fixture()
def summary_store(module_dea_index: Index) -> SummaryStore:
store = SummaryStore.create(module_dea_index)
store.drop_all()
module_dea_index.close()
with disable_logging():
# Some CRS/storage tests use test data that is 3577
store.init(grouping_epsg_code=3577)
_make_all_tables_unlogged(
_utils.alchemy_engine(module_dea_index), CUBEDASH_METADATA
)
return store
@pytest.fixture()
def summariser(summary_store: SummaryStore):
return summary_store._summariser
@pytest.fixture(autouse=True, scope="session")
def _init_logs(pytestconfig):
logs.init_logging(
verbosity=pytestconfig.getoption("verbose"), cache_logger_on_first_use=False
)
@pytest.fixture()
def tmppath(tmpdir):
return Path(str(tmpdir))
@pytest.fixture()
def clirunner(global_integration_cli_args):
def _run_cli(cli_method, opts, catch_exceptions=False, expect_success=True):
exe_opts = list(global_integration_cli_args)
exe_opts.extend(opts)
runner = CliRunner()
result = runner.invoke(cli_method, exe_opts, catch_exceptions=catch_exceptions)
if expect_success:
assert (
0 == result.exit_code
), f"Error for {opts}. Out:\n{indent(result.output, ' ' * 4)}"
return result
return _run_cli
@pytest.fixture()
def run_generate(clirunner, summary_store, multi_processed=False):
def do(*args, expect_success=True):
args = args or ("--all",)
if not multi_processed:
args = ("-j", "1") + tuple(args)
res = clirunner(generate.cli, args, expect_success=expect_success)
return res
return do
@pytest.fixture(scope="module")
def dataset_loader(module_dea_index: Index):
def _populate_from_dump(expected_type: str, dump_path: Path):
ls8_nbar_scene = module_dea_index.products.get_by_name(expected_type)
dataset_count = 0
create_dataset = Doc2Dataset(module_dea_index)
for _, doc in read_documents(dump_path):
label = doc["ga_label"] if ("ga_label" in doc) else doc["id"]
# type: Tuple[Dataset, str]
dataset, err = create_dataset(
doc, f"file://example.com/test_dataset/{label}"
)
assert dataset is not None, err
assert dataset.type.name == expected_type
created = module_dea_index.datasets.add(dataset)
assert created.uris
assert created.type.name == ls8_nbar_scene.name
dataset_count += 1
print(f"Populated {dataset_count} of {expected_type}")
return dataset_count
return _populate_from_dump
@pytest.fixture()
def all_urls(summary_store: SummaryStore):
"""A list of public URLs to try on the current Explorer instance"""
return list(find_examples_of_all_public_urls(summary_store.index))
@pytest.fixture()
def empty_client(summary_store: SummaryStore) -> FlaskClient:
_model.cache.clear()
_model.STORE = summary_store
cubedash.app.config["TESTING"] = True
return cubedash.app.test_client()
@pytest.fixture()
def unpopulated_client(
empty_client: FlaskClient, summary_store: SummaryStore
) -> FlaskClient:
with disable_logging():
_model.STORE.refresh_all_product_extents()
return empty_client
@contextmanager
def disable_logging():
"""
Turn off logging within the if-block
Used for repetitive environment setup that makes test errors too verbose.
"""
original_processors = structlog.get_config()["processors"]
def swallow_log(_logger, _log_method, _event_dict):
raise DropEvent
structlog.configure(processors=[swallow_log])
try:
yield
finally:
structlog.configure(processors=original_processors)
@pytest.fixture()
def client(unpopulated_client: FlaskClient) -> FlaskClient:
with disable_logging():
for product in _model.STORE.index.products.get_all():
_model.STORE.refresh(product.name)
return unpopulated_client
@pytest.fixture(scope="module")
def populated_index(dataset_loader, module_dea_index):
"""
Index populated with example datasets. Assumes our tests wont modify the data!
It's module-scoped as it's expensive to populate.
"""
loaded = dataset_loader("wofs_albers", TEST_DATA_DIR / "wofs-albers-sample.yaml.gz")
assert loaded == 11
loaded = dataset_loader(
"high_tide_comp_20p", TEST_DATA_DIR / "high_tide_comp_20p.yaml.gz"
)
assert loaded == 306
# These have very large footprints, as they were unioned from many almost-identical
# polygons and not simplified. They will trip up postgis if used naively.
# (postgis gist index has max record size of 8k per entry)
loaded = dataset_loader(
"pq_count_summary", TEST_DATA_DIR / "pq_count_summary.yaml.gz"
)
assert loaded == 20
return module_dea_index
|
import importlib
from types import ModuleType
from typing import Any, Dict
import click
from comeback import plugins
from comeback.utils import verbose_echo
def call(module: ModuleType,
**plugin_params: Dict[str, Any]) -> None:
try:
success, err = module.run_plugin(**plugin_params)
except TypeError as e:
success, err = False, str(e)
if not success:
click.echo(
'There was a problem executing the plugin' +
f' {module.__name__}: {err}')
exit(-1)
verbose_echo(f'Successfully started {module.__name__}!')
def does_exists(plugin_name: str) -> bool:
all_plugins = plugins.__all__
is_plugin_found = plugin_name in all_plugins
if not is_plugin_found:
click.echo(f'Installed plugins: {', '.join(all_plugins)}')
click.echo(f'Unknown plugin: {plugin_name}')
return is_plugin_found
def load(plugin_name: str) -> ModuleType:
if not plugin_name:
click.echo(f'Can\'t load a plugin without a plugin name')
exit(1)
importer = f'{plugins.__name__}.{plugin_name}.main'
return importlib.import_module(importer)
| import importlib
from types import ModuleType
from typing import Any, Dict
import click
from comeback import plugins
from comeback.utils import verbose_echo
def call(module: ModuleType,
**plugin_params: Dict[str, Any]) -> None:
try:
success, err = module.run_plugin(**plugin_params)
except TypeError as e:
success, err = False, str(e)
if not success:
click.echo(
'There was a problem executing the plugin' +
f' {module.__name__}: {err}')
exit(-1)
verbose_echo(f'Successfully started {module.__name__}!')
def does_exists(plugin_name: str) -> bool:
all_plugins = plugins.__all__
is_plugin_found = plugin_name in all_plugins
if not is_plugin_found:
click.echo(f'Installed plugins: {", ".join(all_plugins)}')
click.echo(f'Unknown plugin: {plugin_name}')
return is_plugin_found
def load(plugin_name: str) -> ModuleType:
if not plugin_name:
click.echo(f'Can\'t load a plugin without a plugin name')
exit(1)
importer = f'{plugins.__name__}.{plugin_name}.main'
return importlib.import_module(importer)
|
import json
import time
from typing import Callable, Iterator, Optional
import pandas as pd
from dagster_pandas import DataFrame
from dagster import (
Array,
AssetMaterialization,
Bool,
DagsterInvalidDefinitionError,
EventMetadataEntry,
Failure,
Field,
InputDefinition,
Int,
Noneable,
Nothing,
Output,
OutputDefinition,
Permissive,
RetryRequested,
String,
check,
solid,
)
from dagster.core.execution.context.compute import SolidExecutionContext
from ..errors import DagsterDbtRpcUnexpectedPollOutputError
from .types import DbtRpcOutput
from .utils import log_rpc, raise_for_rpc_error
def _generate_materializations(dro: DbtRpcOutput) -> Iterator[AssetMaterialization]:
"""Yields ``AssetMaterializations`` for metadata in the dbt RPC ``DbtRpcOutput``."""
for node_result in dro.result.results:
if node_result.node["resource_type"] in ["model", "snapshot"]:
success = not node_result.fail and not node_result.skip and not node_result.error
if success:
entries = [
EventMetadataEntry.json(data=node_result.node, label="Node"),
EventMetadataEntry.text(text=str(node_result.status), label="Status"),
EventMetadataEntry.text(
text=str(node_result.execution_time), label="Execution Time"
),
EventMetadataEntry.text(
text=node_result.node["config"]["materialized"],
label="Materialization Strategy",
),
EventMetadataEntry.text(text=node_result.node["database"], label="Database"),
EventMetadataEntry.text(text=node_result.node["schema"], label="Schema"),
EventMetadataEntry.text(text=node_result.node["alias"], label="Alias"),
EventMetadataEntry.text(
text=node_result.node["description"], label="Description"
),
]
for step_timing in node_result.step_timings:
if step_timing.name == "execute":
execution_entries = [
EventMetadataEntry.text(
text=step_timing.started_at.isoformat(timespec="seconds"),
label="Execution Started At",
),
EventMetadataEntry.text(
text=step_timing.completed_at.isoformat(timespec="seconds"),
label="Execution Completed At",
),
EventMetadataEntry.text(
text=str(step_timing.duration), label="Execution Duration"
),
]
entries.extend(execution_entries)
if step_timing.name == "compile":
execution_entries = [
EventMetadataEntry.text(
text=step_timing.started_at.isoformat(timespec="seconds"),
label="Compilation Started At",
),
EventMetadataEntry.text(
text=step_timing.completed_at.isoformat(timespec="seconds"),
label="Compilation Completed At",
),
EventMetadataEntry.text(
text=str(step_timing.duration), label="Compilation Duration"
),
]
entries.extend(execution_entries)
yield AssetMaterialization(
description="A materialized node within the dbt graph.",
metadata_entries=entries,
asset_key=node_result.node["unique_id"],
)
def _poll_rpc(
context: SolidExecutionContext, request_token: str, should_yield_materializations: bool = True
) -> DbtRpcOutput:
"""Polls the dbt RPC server for the status of a request until the state is ``success``."""
logs_start = 0
while True:
# Poll for the dbt RPC request.
context.log.debug(f"RequestToken: {request_token}")
resp = context.resources.dbt_rpc.poll(
request_token=request_token, logs=context.solid_config["logs"], logs_start=logs_start
)
raise_for_rpc_error(context, resp)
# Pass dbt RPC logs into the Dagster/Dagit logger.
if context.solid_config["logs"]:
logs = resp.json().get("result").get("logs")
if len(logs) > 0:
log_rpc(context, logs)
logs_start += len(logs)
# Stop polling if request's state is no longer "running".
if resp.json().get("result").get("state") != "running":
break
# Sleep for the configured time intervale before polling again.
context.log.debug(
f"Request {request_token} currently in state "{resp.json().get("result").get("state")}' (elapsed time {resp.json().get("result").get("elapsed", 0)} seconds). Sleeping for {context.solid_config.get("interval")}s.."
)
time.sleep(context.solid_config["interval"])
if resp.json().get("result").get("state") != "success":
raise Failure(
description=f"Request {request_token} finished with state "{resp.json().get("result").get("state")}' in {resp.json().get("result").get("elapsed")} seconds",
)
context.log.info(
f"Request {request_token} finished with state "{resp.json().get("result").get("state")}' in {resp.json().get("result").get("elapsed")} seconds"
)
context.log.debug(json.dumps(resp.json().get("result"), indent=2))
polled_run_results = DbtRpcOutput.from_dict(resp.json().get("result"))
if should_yield_materializations:
for materialization in _generate_materializations(polled_run_results):
yield materialization
yield Output(polled_run_results)
def unwrap_result(poll_rpc_generator) -> DbtRpcOutput:
"""A helper function that extracts the `DbtRpcOutput` value from a generator.
The parameter `poll_rpc_generator` is expected to be an invocation of `_poll_rpc`.
"""
output = None
for x in poll_rpc_generator:
output = x
if output is None:
raise DagsterDbtRpcUnexpectedPollOutputError(
description="poll_rpc yielded None as its last value. Expected value of type Output containing DbtRpcOutput.",
)
if not isinstance(output, Output):
raise DagsterDbtRpcUnexpectedPollOutputError(
description=f"poll_rpc yielded value of type {type(output)} as its last value. Expected value of type Output containing DbtRpcOutput.",
)
if not isinstance(output.value, DbtRpcOutput):
raise DagsterDbtRpcUnexpectedPollOutputError(
description=f"poll_rpc yielded Output containing {type(output.value)}. Expected DbtRpcOutput.",
)
return output.value
@solid(
description="A solid to invoke dbt run over RPC.",
input_defs=[InputDefinition(name="start_after", dagster_type=Nothing)],
output_defs=[
OutputDefinition(
name="request_token",
dagster_type=String,
description="The request token of the invoked dbt run.",
)
],
config_schema={
"models": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt models to run.",
),
"exclude": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt models to exclude.",
),
},
required_resource_keys={"dbt_rpc"},
tags={"kind": "dbt"},
)
def dbt_rpc_run(context: SolidExecutionContext) -> String:
"""This solid sends the ``dbt run`` command to a dbt RPC server and returns the request token.
This dbt RPC solid is asynchronous. The request token can be used in subsequent RPC requests to
poll the progress of the running dbt process.
"""
resp = context.resources.dbt_rpc.run(
models=context.solid_config["models"], exclude=context.solid_config["exclude"]
)
context.log.debug(resp.text)
raise_for_rpc_error(context, resp)
return resp.json().get("result").get("request_token")
@solid(
description="A solid to invoke dbt run over RPC and poll the resulting RPC process until it's complete.",
input_defs=[InputDefinition(name="start_after", dagster_type=Nothing)],
output_defs=[OutputDefinition(name="result", dagster_type=DbtRpcOutput)],
config_schema={
"models": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt models to run.",
),
"exclude": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt models to exclude.",
),
"full_refresh": Field(
config=Bool,
description="Whether or not to perform a --full-refresh.",
is_required=False,
default_value=False,
),
"fail_fast": Field(
config=Bool,
description="Whether or not to --fail-fast.",
is_required=False,
default_value=False,
),
"warn_error": Field(
config=Bool,
description="Whether or not to --warn-error.",
is_required=False,
default_value=False,
),
"interval": Field(
config=Int,
is_required=False,
default_value=10,
description="The interval (in seconds) at which to poll the dbt rpc process.",
),
"logs": Field(
config=Bool,
is_required=False,
default_value=True,
description="Whether or not to return logs from the process.",
),
"task_tags": Permissive(),
"max_retries": Field(config=Int, is_required=False, default_value=5),
"retry_interval": Field(config=Int, is_required=False, default_value=120),
},
required_resource_keys={"dbt_rpc"},
tags={"kind": "dbt"},
)
def dbt_rpc_run_and_wait(context: SolidExecutionContext) -> DbtRpcOutput:
"""This solid sends the ``dbt run`` command to a dbt RPC server and returns the result of the
executed dbt process.
This dbt RPC solid is synchronous, and will periodically poll the dbt RPC server until the dbt
process is completed.
"""
if context.solid_config["task_tags"]:
results = context.resources.dbt_rpc.ps().json()
for task in results["result"]["rows"]:
if task["tags"] == context.solid_config["task_tags"]:
context.log.warning(
f"RPC task with tags {json.dumps(task["tags"])} currently running."
)
raise RetryRequested(
max_retries=context.solid_config["max_retries"],
seconds_to_wait=context.solid_config["retry_interval"],
)
command = ""
if context.solid_config["warn_error"]:
command += " --warn-error"
command += " run"
if context.solid_config["models"]:
models = " ".join(set(context.solid_config["models"]))
command += f" --models {models}"
if context.solid_config["exclude"]:
exclude = " ".join(set(context.solid_config["exclude"]))
command += f" --exclude {exclude}"
if context.solid_config["full_refresh"]:
command += " --full-refresh"
if context.solid_config["fail_fast"]:
command += " --fail-fast"
context.log.debug(f"Running dbt command: dbt {command}")
resp = context.resources.dbt_rpc.cli(cli=command, **context.solid_config["task_tags"])
context.log.debug(resp.text)
raise_for_rpc_error(context, resp)
request_token = resp.json().get("result").get("request_token")
return _poll_rpc(context, request_token)
@solid(
description="A solid to invoke dbt test over RPC.",
input_defs=[InputDefinition(name="start_after", dagster_type=Nothing)],
output_defs=[
OutputDefinition(
name="request_token",
dagster_type=String,
description="The request token of the invoked dbt test.",
)
],
config_schema={
"models": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt models to test.",
),
"exclude": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt models to exclude.",
),
"data": Field(
config=Bool,
default_value=True,
is_required=False,
description="Whether or not to run custom data tests.",
),
"schema": Field(
config=Bool,
default_value=True,
is_required=False,
description="Whether or not to run schema tests.",
),
},
required_resource_keys={"dbt_rpc"},
tags={"kind": "dbt"},
)
def dbt_rpc_test(context: SolidExecutionContext) -> String:
"""This solid sends the ``dbt test`` command to a dbt RPC server and returns the request token.
This dbt RPC solid is asynchronous. The request token can be used in subsequent RPC requests to
poll the progress of the running dbt process.
"""
resp = context.resources.dbt_rpc.test(
models=context.solid_config["models"],
exclude=context.solid_config["exclude"],
data=context.solid_config["data"],
schema=context.solid_config["schema"],
)
context.log.debug(resp.text)
raise_for_rpc_error(context, resp)
return resp.json().get("result").get("request_token")
@solid(
description="A solid to invoke dbt test over RPC and poll the resulting RPC process until it's complete.",
input_defs=[InputDefinition(name="start_after", dagster_type=Nothing)],
output_defs=[OutputDefinition(name="result", dagster_type=DbtRpcOutput)],
config_schema={
"models": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt models to test.",
),
"exclude": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt models to exclude.",
),
"data": Field(
config=Bool,
default_value=True,
is_required=False,
description="Whether or not to run custom data tests.",
),
"schema": Field(
config=Bool,
default_value=True,
is_required=False,
description="Whether or not to run schema tests.",
),
"interval": Field(
config=Int,
is_required=False,
default_value=10,
description="The interval (in seconds) at which to poll the dbt rpc process.",
),
"logs": Field(
config=Bool,
is_required=False,
default_value=True,
description="Whether or not to return logs from the process.",
),
},
required_resource_keys={"dbt_rpc"},
tags={"kind": "dbt"},
)
def dbt_rpc_test_and_wait(context: SolidExecutionContext) -> DbtRpcOutput:
"""This solid sends the ``dbt test`` command to a dbt RPC server and returns the result of the
executed dbt process.
This dbt RPC solid is synchronous, and will periodically poll the dbt RPC server until the dbt
process is completed.
"""
resp = context.resources.dbt_rpc.test(
models=context.solid_config["models"],
exclude=context.solid_config["exclude"],
data=context.solid_config["data"],
schema=context.solid_config["schema"],
)
context.log.debug(resp.text)
raise_for_rpc_error(context, resp)
request_token = resp.json().get("result").get("request_token")
return _poll_rpc(context, request_token)
@solid(
description="A solid to invoke a dbt run operation over RPC.",
input_defs=[InputDefinition(name="start_after", dagster_type=Nothing)],
output_defs=[
OutputDefinition(
name="request_token",
dagster_type=String,
description="The request token of the invoked dbt run operation.",
)
],
config_schema={
"macro": Field(
config=String,
is_required=True,
description="The dbt macro to invoke as a run operation",
),
"args": Field(
config=Noneable(Permissive()),
is_required=False,
default_value=None,
description="Arguments to supply to the invoked macro.",
),
},
required_resource_keys={"dbt_rpc"},
tags={"kind": "dbt"},
)
def dbt_rpc_run_operation(context: SolidExecutionContext) -> String:
"""This solid sends the ``dbt run-operation`` command to a dbt RPC server and returns the
request token.
This dbt RPC solid is asynchronous. The request token can be used in subsequent RPC requests to
poll the progress of the running dbt process.
"""
resp = context.resources.dbt_rpc.run_operation(
macro=context.solid_config["macro"], args=context.solid_config["args"]
)
context.log.debug(resp.text)
raise_for_rpc_error(context, resp)
return resp.json().get("result").get("request_token")
@solid(
description="A solid to invoke a dbt run operation over RPC and poll the resulting RPC process until it's complete.",
input_defs=[InputDefinition(name="start_after", dagster_type=Nothing)],
output_defs=[OutputDefinition(name="result", dagster_type=DbtRpcOutput)],
config_schema={
"macro": Field(
config=String,
is_required=True,
description="The dbt macro to invoke as a run operation",
),
"args": Field(
config=Noneable(Permissive()),
is_required=False,
default_value=None,
description="Arguments to supply to the invoked macro.",
),
"interval": Field(
config=Int,
is_required=False,
default_value=10,
description="The interval (in seconds) at which to poll the dbt rpc process.",
),
"logs": Field(
config=Bool,
is_required=False,
default_value=True,
description="Whether or not to return logs from the process.",
),
},
required_resource_keys={"dbt_rpc"},
tags={"kind": "dbt"},
)
def dbt_rpc_run_operation_and_wait(context: SolidExecutionContext) -> DbtRpcOutput:
"""This solid sends the ``dbt run-operation`` command to a dbt RPC server and returns the result of the
executed dbt process.
This dbt RPC solid is synchronous, and will periodically poll the dbt RPC server until the dbt
process is completed.
"""
resp = context.resources.dbt_rpc.run_operation(
macro=context.solid_config["macro"], args=context.solid_config["args"]
)
context.log.debug(resp.text)
raise_for_rpc_error(context, resp)
request_token = resp.json().get("result").get("request_token")
return _poll_rpc(context, request_token)
@solid(
description="A solid to invoke a dbt snapshot over RPC.",
input_defs=[InputDefinition(name="start_after", dagster_type=Nothing)],
output_defs=[
OutputDefinition(
name="request_token",
dagster_type=String,
description="The request token of the invoked dbt snapshot.",
)
],
config_schema={
"select": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt snapshot files to snapshot.",
),
"exclude": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt snapshot files to exclude from the snapshot.",
),
},
required_resource_keys={"dbt_rpc"},
tags={"kind": "dbt"},
)
def dbt_rpc_snapshot(context: SolidExecutionContext) -> String:
"""This solid sends the ``dbt snapshot`` command to a dbt RPC server and returns the
request token.
This dbt RPC solid is asynchronous. The request token can be used in subsequent RPC requests to
poll the progress of the running dbt process.
"""
resp = context.resources.dbt_rpc.snapshot(
select=context.solid_config["select"], exclude=context.solid_config["exclude"]
)
context.log.debug(resp.text)
raise_for_rpc_error(context, resp)
return resp.json().get("result").get("request_token")
@solid(
description="A solid to invoke a dbt snapshot over RPC and poll the resulting RPC process until it's complete.",
input_defs=[InputDefinition(name="start_after", dagster_type=Nothing)],
output_defs=[OutputDefinition(name="result", dagster_type=DbtRpcOutput)],
config_schema={
"select": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt snapshot files to snapshot.",
),
"exclude": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt snapshot files to exclude from the snapshot.",
),
"interval": Field(
config=Int,
is_required=False,
default_value=10,
description="The interval (in seconds) at which to poll the dbt rpc process.",
),
"logs": Field(
config=Bool,
is_required=False,
default_value=True,
description="Whether or not to return logs from the process.",
),
"task_tags": Permissive(),
"max_retries": Field(config=Int, is_required=False, default_value=5),
"retry_interval": Field(config=Int, is_required=False, default_value=120),
},
required_resource_keys={"dbt_rpc"},
tags={"kind": "dbt"},
)
def dbt_rpc_snapshot_and_wait(context: SolidExecutionContext) -> DbtRpcOutput:
"""This solid sends the ``dbt snapshot`` command to a dbt RPC server and returns the result of
the executed dbt process.
This dbt RPC solid is synchronous, and will periodically poll the dbt RPC server until the dbt
process is completed.
"""
if context.solid_config["task_tags"]:
results = context.resources.dbt_rpc.ps().json()
for task in results["result"]["rows"]:
if task["tags"] == context.solid_config["task_tags"]:
context.log.warning(
f"RPC task with tags {json.dumps(task["tags"])} currently running."
)
raise RetryRequested(
max_retries=context.solid_config["max_retries"],
seconds_to_wait=context.solid_config["retry_interval"],
)
resp = context.resources.dbt_rpc.snapshot(
select=context.solid_config["select"], exclude=context.solid_config["exclude"]
)
context.log.debug(resp.text)
raise_for_rpc_error(context, resp)
request_token = resp.json().get("result").get("request_token")
return _poll_rpc(context, request_token)
@solid(
description="A solid to invoke dbt source snapshot-freshness over RPC.",
input_defs=[InputDefinition(name="start_after", dagster_type=Nothing)],
output_defs=[
OutputDefinition(
name="request_token",
dagster_type=String,
description="The request token of the invoked dbt snapshot.",
)
],
config_schema={
"select": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt sources to snapshot-freshness for.",
),
"warn_error": Field(
config=Bool,
description="Whether or not to --warn-error.",
is_required=False,
default_value=False,
),
},
required_resource_keys={"dbt_rpc"},
tags={"kind": "dbt"},
)
def dbt_rpc_snapshot_freshness(context: SolidExecutionContext) -> String:
"""This solid sends the ``dbt source snapshot-freshness`` command to a dbt RPC server and
returns the request token.
This dbt RPC solid is asynchronous. The request token can be used in subsequent RPC requests to
poll the progress of the running dbt process.
"""
command = ""
if context.solid_config["warn_error"]:
command += " --warn-error"
command += " source snapshot-freshness"
if context.solid_config["select"]:
select = " ".join(set(context.solid_config["select"]))
command += f" --select {select}"
context.log.debug(f"Running dbt command: dbt {command}")
resp = context.resources.dbt_rpc.cli(cli=command)
context.log.debug(resp.text)
raise_for_rpc_error(context, resp)
return resp.json().get("result").get("request_token")
@solid(
description="A solid to invoke dbt source snapshot-freshness over RPC and poll the resulting RPC process until it's complete.",
input_defs=[InputDefinition(name="start_after", dagster_type=Nothing)],
output_defs=[OutputDefinition(name="result", dagster_type=DbtRpcOutput)],
config_schema={
"select": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt sources to snapshot-freshness for.",
),
"warn_error": Field(
config=Bool,
description="Whether or not to --warn-error.",
is_required=False,
default_value=False,
),
"interval": Field(
config=Int,
is_required=False,
default_value=10,
description="The interval (in seconds) at which to poll the dbt rpc process.",
),
"logs": Field(
config=Bool,
is_required=False,
default_value=True,
description="Whether or not to return logs from the process.",
),
},
required_resource_keys={"dbt_rpc"},
tags={"kind": "dbt"},
)
def dbt_rpc_snapshot_freshness_and_wait(context: SolidExecutionContext) -> DbtRpcOutput:
"""This solid sends the ``dbt source snapshot`` command to a dbt RPC server and returns the
result of the executed dbt process.
This dbt RPC solid is synchronous, and will periodically poll the dbt RPC server until the dbt
process is completed.
"""
command = ""
if context.solid_config["warn_error"]:
command += " --warn-error"
command += " source snapshot-freshness"
if context.solid_config["select"]:
select = " ".join(set(context.solid_config["select"]))
command += f" --select {select}"
context.log.debug(f"Running dbt command: dbt {command}")
resp = context.resources.dbt_rpc.cli(cli=command)
context.log.debug(resp.text)
raise_for_rpc_error(context, resp)
request_token = resp.json().get("result").get("request_token")
return _poll_rpc(context, request_token)
@solid(
description="A solid to compile a SQL query in context of a dbt project over RPC.",
input_defs=[
InputDefinition(name="start_after", dagster_type=Nothing),
InputDefinition(
name="sql", description="The SQL query to be compiled.", dagster_type=String
),
],
output_defs=[
OutputDefinition(name="sql", description="The compiled SQL query.", dagster_type=String)
],
config_schema={
"name": Field(config=String),
"interval": Field(
config=Int,
is_required=False,
default_value=10,
description="The interval (in seconds) at which to poll the dbt rpc process.",
),
"logs": Field(
config=Bool,
is_required=False,
default_value=True,
description="Whether or not to return logs from the process.",
),
},
required_resource_keys={"dbt_rpc"},
tags={"kind": "dbt"},
)
def dbt_rpc_compile_sql(context: SolidExecutionContext, sql: String) -> String:
"""This solid sends the ``dbt compile`` command to a dbt RPC server and returns the request
token.
This dbt RPC solid is asynchronous. The request token can be used in subsequent RPC requests to
poll the progress of the running dbt process.
"""
resp = context.resources.dbt_rpc.compile_sql(sql=sql, name=context.solid_config["name"])
context.log.debug(resp.text)
raise_for_rpc_error(context, resp)
request_token = resp.json().get("result").get("request_token")
result = unwrap_result(_poll_rpc(context, request_token))
return result.results[0].node["compiled_sql"]
def create_dbt_rpc_run_sql_solid(
name: str, output_def: Optional[OutputDefinition] = None, **kwargs
) -> Callable:
"""This function is a factory which constructs a solid that will copy the results of a SQL query
run within the context of a dbt project to a pandas ``DataFrame``.
Any kwargs passed to this function will be passed along to the underlying :func:`@solid
<dagster.solid>` decorator. However, note that overriding ``config_schema``, ``input_defs``, and
``required_resource_keys`` is not allowed and will throw a :class:`DagsterInvalidDefinitionError
<dagster.DagsterInvalidDefinitionError>`.
If you would like to configure this solid with different config fields, you could consider using
:func:`@composite_solid <dagster.composite_solid>` to wrap this solid.
Args:
name (str): The name of this solid.
output_def (OutputDefinition, optional): The :class:`OutputDefinition
<dagster.OutputDefinition>` for the solid. This value should always be a representation
of a pandas ``DataFrame``. If not specified, the solid will default to an
:class:`OutputDefinition <dagster.OutputDefinition>` named "df" with a ``DataFrame``
dagster type.
Returns:
SolidDefinition: Returns the constructed solid definition.
"""
check.str_param(obj=name, param_name="name")
check.opt_inst_param(obj=output_def, param_name="output_def", ttype=OutputDefinition)
if "config_schema" in kwargs:
raise DagsterInvalidDefinitionError("Overriding config_schema is not supported.")
if "input_defs" in kwargs:
raise DagsterInvalidDefinitionError("Overriding input_defs is not supported.")
if "required_resource_keys" in kwargs:
raise DagsterInvalidDefinitionError("Overriding required_resource_keys is not supported.")
@solid(
name=name,
description=kwargs.pop(
"description",
"A solid to run a SQL query in context of a dbt project over RPC and return the results in a pandas DataFrame.",
),
input_defs=[
InputDefinition(name="start_after", dagster_type=Nothing),
InputDefinition(
name="sql", description="The SQL query to be run.", dagster_type=String
),
],
output_defs=[
output_def
or OutputDefinition(
name="df", description="The results of the SQL query.", dagster_type=DataFrame
)
],
config_schema={
"name": Field(config=String),
"interval": Field(
config=Int,
is_required=False,
default_value=10,
description="The interval (in seconds) at which to poll the dbt rpc process.",
),
"logs": Field(
config=Bool,
is_required=False,
default_value=True,
description="Whether or not to return logs from the process.",
),
},
required_resource_keys={"dbt_rpc"},
tags={"kind": "dbt"},
**kwargs,
)
def _dbt_rpc_run_sql(context: SolidExecutionContext, sql: String) -> DataFrame:
resp = context.resources.dbt_rpc.run_sql(sql=sql, name=context.solid_config["name"])
context.log.debug(resp.text)
raise_for_rpc_error(context, resp)
request_token = resp.json().get("result").get("request_token")
result = unwrap_result(_poll_rpc(context, request_token))
table = result.results[0].table
return pd.DataFrame.from_records(data=table["rows"], columns=table["column_names"])
return _dbt_rpc_run_sql
| import json
import time
from typing import Callable, Iterator, Optional
import pandas as pd
from dagster_pandas import DataFrame
from dagster import (
Array,
AssetMaterialization,
Bool,
DagsterInvalidDefinitionError,
EventMetadataEntry,
Failure,
Field,
InputDefinition,
Int,
Noneable,
Nothing,
Output,
OutputDefinition,
Permissive,
RetryRequested,
String,
check,
solid,
)
from dagster.core.execution.context.compute import SolidExecutionContext
from ..errors import DagsterDbtRpcUnexpectedPollOutputError
from .types import DbtRpcOutput
from .utils import log_rpc, raise_for_rpc_error
def _generate_materializations(dro: DbtRpcOutput) -> Iterator[AssetMaterialization]:
"""Yields ``AssetMaterializations`` for metadata in the dbt RPC ``DbtRpcOutput``."""
for node_result in dro.result.results:
if node_result.node["resource_type"] in ["model", "snapshot"]:
success = not node_result.fail and not node_result.skip and not node_result.error
if success:
entries = [
EventMetadataEntry.json(data=node_result.node, label="Node"),
EventMetadataEntry.text(text=str(node_result.status), label="Status"),
EventMetadataEntry.text(
text=str(node_result.execution_time), label="Execution Time"
),
EventMetadataEntry.text(
text=node_result.node["config"]["materialized"],
label="Materialization Strategy",
),
EventMetadataEntry.text(text=node_result.node["database"], label="Database"),
EventMetadataEntry.text(text=node_result.node["schema"], label="Schema"),
EventMetadataEntry.text(text=node_result.node["alias"], label="Alias"),
EventMetadataEntry.text(
text=node_result.node["description"], label="Description"
),
]
for step_timing in node_result.step_timings:
if step_timing.name == "execute":
execution_entries = [
EventMetadataEntry.text(
text=step_timing.started_at.isoformat(timespec="seconds"),
label="Execution Started At",
),
EventMetadataEntry.text(
text=step_timing.completed_at.isoformat(timespec="seconds"),
label="Execution Completed At",
),
EventMetadataEntry.text(
text=str(step_timing.duration), label="Execution Duration"
),
]
entries.extend(execution_entries)
if step_timing.name == "compile":
execution_entries = [
EventMetadataEntry.text(
text=step_timing.started_at.isoformat(timespec="seconds"),
label="Compilation Started At",
),
EventMetadataEntry.text(
text=step_timing.completed_at.isoformat(timespec="seconds"),
label="Compilation Completed At",
),
EventMetadataEntry.text(
text=str(step_timing.duration), label="Compilation Duration"
),
]
entries.extend(execution_entries)
yield AssetMaterialization(
description="A materialized node within the dbt graph.",
metadata_entries=entries,
asset_key=node_result.node["unique_id"],
)
def _poll_rpc(
context: SolidExecutionContext, request_token: str, should_yield_materializations: bool = True
) -> DbtRpcOutput:
"""Polls the dbt RPC server for the status of a request until the state is ``success``."""
logs_start = 0
while True:
# Poll for the dbt RPC request.
context.log.debug(f"RequestToken: {request_token}")
resp = context.resources.dbt_rpc.poll(
request_token=request_token, logs=context.solid_config["logs"], logs_start=logs_start
)
raise_for_rpc_error(context, resp)
# Pass dbt RPC logs into the Dagster/Dagit logger.
if context.solid_config["logs"]:
logs = resp.json().get("result").get("logs")
if len(logs) > 0:
log_rpc(context, logs)
logs_start += len(logs)
# Stop polling if request's state is no longer "running".
if resp.json().get("result").get("state") != "running":
break
# Sleep for the configured time intervale before polling again.
context.log.debug(
f"Request {request_token} currently in state '{resp.json().get('result').get('state')}' (elapsed time {resp.json().get('result').get('elapsed', 0)} seconds). Sleeping for {context.solid_config.get('interval')}s.."
)
time.sleep(context.solid_config["interval"])
if resp.json().get("result").get("state") != "success":
raise Failure(
description=f"Request {request_token} finished with state '{resp.json().get('result').get('state')}' in {resp.json().get('result').get('elapsed')} seconds",
)
context.log.info(
f"Request {request_token} finished with state '{resp.json().get('result').get('state')}' in {resp.json().get('result').get('elapsed')} seconds"
)
context.log.debug(json.dumps(resp.json().get("result"), indent=2))
polled_run_results = DbtRpcOutput.from_dict(resp.json().get("result"))
if should_yield_materializations:
for materialization in _generate_materializations(polled_run_results):
yield materialization
yield Output(polled_run_results)
def unwrap_result(poll_rpc_generator) -> DbtRpcOutput:
"""A helper function that extracts the `DbtRpcOutput` value from a generator.
The parameter `poll_rpc_generator` is expected to be an invocation of `_poll_rpc`.
"""
output = None
for x in poll_rpc_generator:
output = x
if output is None:
raise DagsterDbtRpcUnexpectedPollOutputError(
description="poll_rpc yielded None as its last value. Expected value of type Output containing DbtRpcOutput.",
)
if not isinstance(output, Output):
raise DagsterDbtRpcUnexpectedPollOutputError(
description=f"poll_rpc yielded value of type {type(output)} as its last value. Expected value of type Output containing DbtRpcOutput.",
)
if not isinstance(output.value, DbtRpcOutput):
raise DagsterDbtRpcUnexpectedPollOutputError(
description=f"poll_rpc yielded Output containing {type(output.value)}. Expected DbtRpcOutput.",
)
return output.value
@solid(
description="A solid to invoke dbt run over RPC.",
input_defs=[InputDefinition(name="start_after", dagster_type=Nothing)],
output_defs=[
OutputDefinition(
name="request_token",
dagster_type=String,
description="The request token of the invoked dbt run.",
)
],
config_schema={
"models": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt models to run.",
),
"exclude": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt models to exclude.",
),
},
required_resource_keys={"dbt_rpc"},
tags={"kind": "dbt"},
)
def dbt_rpc_run(context: SolidExecutionContext) -> String:
"""This solid sends the ``dbt run`` command to a dbt RPC server and returns the request token.
This dbt RPC solid is asynchronous. The request token can be used in subsequent RPC requests to
poll the progress of the running dbt process.
"""
resp = context.resources.dbt_rpc.run(
models=context.solid_config["models"], exclude=context.solid_config["exclude"]
)
context.log.debug(resp.text)
raise_for_rpc_error(context, resp)
return resp.json().get("result").get("request_token")
@solid(
description="A solid to invoke dbt run over RPC and poll the resulting RPC process until it's complete.",
input_defs=[InputDefinition(name="start_after", dagster_type=Nothing)],
output_defs=[OutputDefinition(name="result", dagster_type=DbtRpcOutput)],
config_schema={
"models": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt models to run.",
),
"exclude": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt models to exclude.",
),
"full_refresh": Field(
config=Bool,
description="Whether or not to perform a --full-refresh.",
is_required=False,
default_value=False,
),
"fail_fast": Field(
config=Bool,
description="Whether or not to --fail-fast.",
is_required=False,
default_value=False,
),
"warn_error": Field(
config=Bool,
description="Whether or not to --warn-error.",
is_required=False,
default_value=False,
),
"interval": Field(
config=Int,
is_required=False,
default_value=10,
description="The interval (in seconds) at which to poll the dbt rpc process.",
),
"logs": Field(
config=Bool,
is_required=False,
default_value=True,
description="Whether or not to return logs from the process.",
),
"task_tags": Permissive(),
"max_retries": Field(config=Int, is_required=False, default_value=5),
"retry_interval": Field(config=Int, is_required=False, default_value=120),
},
required_resource_keys={"dbt_rpc"},
tags={"kind": "dbt"},
)
def dbt_rpc_run_and_wait(context: SolidExecutionContext) -> DbtRpcOutput:
"""This solid sends the ``dbt run`` command to a dbt RPC server and returns the result of the
executed dbt process.
This dbt RPC solid is synchronous, and will periodically poll the dbt RPC server until the dbt
process is completed.
"""
if context.solid_config["task_tags"]:
results = context.resources.dbt_rpc.ps().json()
for task in results["result"]["rows"]:
if task["tags"] == context.solid_config["task_tags"]:
context.log.warning(
f"RPC task with tags {json.dumps(task['tags'])} currently running."
)
raise RetryRequested(
max_retries=context.solid_config["max_retries"],
seconds_to_wait=context.solid_config["retry_interval"],
)
command = ""
if context.solid_config["warn_error"]:
command += " --warn-error"
command += " run"
if context.solid_config["models"]:
models = " ".join(set(context.solid_config["models"]))
command += f" --models {models}"
if context.solid_config["exclude"]:
exclude = " ".join(set(context.solid_config["exclude"]))
command += f" --exclude {exclude}"
if context.solid_config["full_refresh"]:
command += " --full-refresh"
if context.solid_config["fail_fast"]:
command += " --fail-fast"
context.log.debug(f"Running dbt command: dbt {command}")
resp = context.resources.dbt_rpc.cli(cli=command, **context.solid_config["task_tags"])
context.log.debug(resp.text)
raise_for_rpc_error(context, resp)
request_token = resp.json().get("result").get("request_token")
return _poll_rpc(context, request_token)
@solid(
description="A solid to invoke dbt test over RPC.",
input_defs=[InputDefinition(name="start_after", dagster_type=Nothing)],
output_defs=[
OutputDefinition(
name="request_token",
dagster_type=String,
description="The request token of the invoked dbt test.",
)
],
config_schema={
"models": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt models to test.",
),
"exclude": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt models to exclude.",
),
"data": Field(
config=Bool,
default_value=True,
is_required=False,
description="Whether or not to run custom data tests.",
),
"schema": Field(
config=Bool,
default_value=True,
is_required=False,
description="Whether or not to run schema tests.",
),
},
required_resource_keys={"dbt_rpc"},
tags={"kind": "dbt"},
)
def dbt_rpc_test(context: SolidExecutionContext) -> String:
"""This solid sends the ``dbt test`` command to a dbt RPC server and returns the request token.
This dbt RPC solid is asynchronous. The request token can be used in subsequent RPC requests to
poll the progress of the running dbt process.
"""
resp = context.resources.dbt_rpc.test(
models=context.solid_config["models"],
exclude=context.solid_config["exclude"],
data=context.solid_config["data"],
schema=context.solid_config["schema"],
)
context.log.debug(resp.text)
raise_for_rpc_error(context, resp)
return resp.json().get("result").get("request_token")
@solid(
description="A solid to invoke dbt test over RPC and poll the resulting RPC process until it's complete.",
input_defs=[InputDefinition(name="start_after", dagster_type=Nothing)],
output_defs=[OutputDefinition(name="result", dagster_type=DbtRpcOutput)],
config_schema={
"models": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt models to test.",
),
"exclude": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt models to exclude.",
),
"data": Field(
config=Bool,
default_value=True,
is_required=False,
description="Whether or not to run custom data tests.",
),
"schema": Field(
config=Bool,
default_value=True,
is_required=False,
description="Whether or not to run schema tests.",
),
"interval": Field(
config=Int,
is_required=False,
default_value=10,
description="The interval (in seconds) at which to poll the dbt rpc process.",
),
"logs": Field(
config=Bool,
is_required=False,
default_value=True,
description="Whether or not to return logs from the process.",
),
},
required_resource_keys={"dbt_rpc"},
tags={"kind": "dbt"},
)
def dbt_rpc_test_and_wait(context: SolidExecutionContext) -> DbtRpcOutput:
"""This solid sends the ``dbt test`` command to a dbt RPC server and returns the result of the
executed dbt process.
This dbt RPC solid is synchronous, and will periodically poll the dbt RPC server until the dbt
process is completed.
"""
resp = context.resources.dbt_rpc.test(
models=context.solid_config["models"],
exclude=context.solid_config["exclude"],
data=context.solid_config["data"],
schema=context.solid_config["schema"],
)
context.log.debug(resp.text)
raise_for_rpc_error(context, resp)
request_token = resp.json().get("result").get("request_token")
return _poll_rpc(context, request_token)
@solid(
description="A solid to invoke a dbt run operation over RPC.",
input_defs=[InputDefinition(name="start_after", dagster_type=Nothing)],
output_defs=[
OutputDefinition(
name="request_token",
dagster_type=String,
description="The request token of the invoked dbt run operation.",
)
],
config_schema={
"macro": Field(
config=String,
is_required=True,
description="The dbt macro to invoke as a run operation",
),
"args": Field(
config=Noneable(Permissive()),
is_required=False,
default_value=None,
description="Arguments to supply to the invoked macro.",
),
},
required_resource_keys={"dbt_rpc"},
tags={"kind": "dbt"},
)
def dbt_rpc_run_operation(context: SolidExecutionContext) -> String:
"""This solid sends the ``dbt run-operation`` command to a dbt RPC server and returns the
request token.
This dbt RPC solid is asynchronous. The request token can be used in subsequent RPC requests to
poll the progress of the running dbt process.
"""
resp = context.resources.dbt_rpc.run_operation(
macro=context.solid_config["macro"], args=context.solid_config["args"]
)
context.log.debug(resp.text)
raise_for_rpc_error(context, resp)
return resp.json().get("result").get("request_token")
@solid(
description="A solid to invoke a dbt run operation over RPC and poll the resulting RPC process until it's complete.",
input_defs=[InputDefinition(name="start_after", dagster_type=Nothing)],
output_defs=[OutputDefinition(name="result", dagster_type=DbtRpcOutput)],
config_schema={
"macro": Field(
config=String,
is_required=True,
description="The dbt macro to invoke as a run operation",
),
"args": Field(
config=Noneable(Permissive()),
is_required=False,
default_value=None,
description="Arguments to supply to the invoked macro.",
),
"interval": Field(
config=Int,
is_required=False,
default_value=10,
description="The interval (in seconds) at which to poll the dbt rpc process.",
),
"logs": Field(
config=Bool,
is_required=False,
default_value=True,
description="Whether or not to return logs from the process.",
),
},
required_resource_keys={"dbt_rpc"},
tags={"kind": "dbt"},
)
def dbt_rpc_run_operation_and_wait(context: SolidExecutionContext) -> DbtRpcOutput:
"""This solid sends the ``dbt run-operation`` command to a dbt RPC server and returns the result of the
executed dbt process.
This dbt RPC solid is synchronous, and will periodically poll the dbt RPC server until the dbt
process is completed.
"""
resp = context.resources.dbt_rpc.run_operation(
macro=context.solid_config["macro"], args=context.solid_config["args"]
)
context.log.debug(resp.text)
raise_for_rpc_error(context, resp)
request_token = resp.json().get("result").get("request_token")
return _poll_rpc(context, request_token)
@solid(
description="A solid to invoke a dbt snapshot over RPC.",
input_defs=[InputDefinition(name="start_after", dagster_type=Nothing)],
output_defs=[
OutputDefinition(
name="request_token",
dagster_type=String,
description="The request token of the invoked dbt snapshot.",
)
],
config_schema={
"select": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt snapshot files to snapshot.",
),
"exclude": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt snapshot files to exclude from the snapshot.",
),
},
required_resource_keys={"dbt_rpc"},
tags={"kind": "dbt"},
)
def dbt_rpc_snapshot(context: SolidExecutionContext) -> String:
"""This solid sends the ``dbt snapshot`` command to a dbt RPC server and returns the
request token.
This dbt RPC solid is asynchronous. The request token can be used in subsequent RPC requests to
poll the progress of the running dbt process.
"""
resp = context.resources.dbt_rpc.snapshot(
select=context.solid_config["select"], exclude=context.solid_config["exclude"]
)
context.log.debug(resp.text)
raise_for_rpc_error(context, resp)
return resp.json().get("result").get("request_token")
@solid(
description="A solid to invoke a dbt snapshot over RPC and poll the resulting RPC process until it's complete.",
input_defs=[InputDefinition(name="start_after", dagster_type=Nothing)],
output_defs=[OutputDefinition(name="result", dagster_type=DbtRpcOutput)],
config_schema={
"select": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt snapshot files to snapshot.",
),
"exclude": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt snapshot files to exclude from the snapshot.",
),
"interval": Field(
config=Int,
is_required=False,
default_value=10,
description="The interval (in seconds) at which to poll the dbt rpc process.",
),
"logs": Field(
config=Bool,
is_required=False,
default_value=True,
description="Whether or not to return logs from the process.",
),
"task_tags": Permissive(),
"max_retries": Field(config=Int, is_required=False, default_value=5),
"retry_interval": Field(config=Int, is_required=False, default_value=120),
},
required_resource_keys={"dbt_rpc"},
tags={"kind": "dbt"},
)
def dbt_rpc_snapshot_and_wait(context: SolidExecutionContext) -> DbtRpcOutput:
"""This solid sends the ``dbt snapshot`` command to a dbt RPC server and returns the result of
the executed dbt process.
This dbt RPC solid is synchronous, and will periodically poll the dbt RPC server until the dbt
process is completed.
"""
if context.solid_config["task_tags"]:
results = context.resources.dbt_rpc.ps().json()
for task in results["result"]["rows"]:
if task["tags"] == context.solid_config["task_tags"]:
context.log.warning(
f"RPC task with tags {json.dumps(task['tags'])} currently running."
)
raise RetryRequested(
max_retries=context.solid_config["max_retries"],
seconds_to_wait=context.solid_config["retry_interval"],
)
resp = context.resources.dbt_rpc.snapshot(
select=context.solid_config["select"], exclude=context.solid_config["exclude"]
)
context.log.debug(resp.text)
raise_for_rpc_error(context, resp)
request_token = resp.json().get("result").get("request_token")
return _poll_rpc(context, request_token)
@solid(
description="A solid to invoke dbt source snapshot-freshness over RPC.",
input_defs=[InputDefinition(name="start_after", dagster_type=Nothing)],
output_defs=[
OutputDefinition(
name="request_token",
dagster_type=String,
description="The request token of the invoked dbt snapshot.",
)
],
config_schema={
"select": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt sources to snapshot-freshness for.",
),
"warn_error": Field(
config=Bool,
description="Whether or not to --warn-error.",
is_required=False,
default_value=False,
),
},
required_resource_keys={"dbt_rpc"},
tags={"kind": "dbt"},
)
def dbt_rpc_snapshot_freshness(context: SolidExecutionContext) -> String:
"""This solid sends the ``dbt source snapshot-freshness`` command to a dbt RPC server and
returns the request token.
This dbt RPC solid is asynchronous. The request token can be used in subsequent RPC requests to
poll the progress of the running dbt process.
"""
command = ""
if context.solid_config["warn_error"]:
command += " --warn-error"
command += " source snapshot-freshness"
if context.solid_config["select"]:
select = " ".join(set(context.solid_config["select"]))
command += f" --select {select}"
context.log.debug(f"Running dbt command: dbt {command}")
resp = context.resources.dbt_rpc.cli(cli=command)
context.log.debug(resp.text)
raise_for_rpc_error(context, resp)
return resp.json().get("result").get("request_token")
@solid(
description="A solid to invoke dbt source snapshot-freshness over RPC and poll the resulting RPC process until it's complete.",
input_defs=[InputDefinition(name="start_after", dagster_type=Nothing)],
output_defs=[OutputDefinition(name="result", dagster_type=DbtRpcOutput)],
config_schema={
"select": Field(
config=Noneable(Array(String)),
default_value=None,
is_required=False,
description="The dbt sources to snapshot-freshness for.",
),
"warn_error": Field(
config=Bool,
description="Whether or not to --warn-error.",
is_required=False,
default_value=False,
),
"interval": Field(
config=Int,
is_required=False,
default_value=10,
description="The interval (in seconds) at which to poll the dbt rpc process.",
),
"logs": Field(
config=Bool,
is_required=False,
default_value=True,
description="Whether or not to return logs from the process.",
),
},
required_resource_keys={"dbt_rpc"},
tags={"kind": "dbt"},
)
def dbt_rpc_snapshot_freshness_and_wait(context: SolidExecutionContext) -> DbtRpcOutput:
"""This solid sends the ``dbt source snapshot`` command to a dbt RPC server and returns the
result of the executed dbt process.
This dbt RPC solid is synchronous, and will periodically poll the dbt RPC server until the dbt
process is completed.
"""
command = ""
if context.solid_config["warn_error"]:
command += " --warn-error"
command += " source snapshot-freshness"
if context.solid_config["select"]:
select = " ".join(set(context.solid_config["select"]))
command += f" --select {select}"
context.log.debug(f"Running dbt command: dbt {command}")
resp = context.resources.dbt_rpc.cli(cli=command)
context.log.debug(resp.text)
raise_for_rpc_error(context, resp)
request_token = resp.json().get("result").get("request_token")
return _poll_rpc(context, request_token)
@solid(
description="A solid to compile a SQL query in context of a dbt project over RPC.",
input_defs=[
InputDefinition(name="start_after", dagster_type=Nothing),
InputDefinition(
name="sql", description="The SQL query to be compiled.", dagster_type=String
),
],
output_defs=[
OutputDefinition(name="sql", description="The compiled SQL query.", dagster_type=String)
],
config_schema={
"name": Field(config=String),
"interval": Field(
config=Int,
is_required=False,
default_value=10,
description="The interval (in seconds) at which to poll the dbt rpc process.",
),
"logs": Field(
config=Bool,
is_required=False,
default_value=True,
description="Whether or not to return logs from the process.",
),
},
required_resource_keys={"dbt_rpc"},
tags={"kind": "dbt"},
)
def dbt_rpc_compile_sql(context: SolidExecutionContext, sql: String) -> String:
"""This solid sends the ``dbt compile`` command to a dbt RPC server and returns the request
token.
This dbt RPC solid is asynchronous. The request token can be used in subsequent RPC requests to
poll the progress of the running dbt process.
"""
resp = context.resources.dbt_rpc.compile_sql(sql=sql, name=context.solid_config["name"])
context.log.debug(resp.text)
raise_for_rpc_error(context, resp)
request_token = resp.json().get("result").get("request_token")
result = unwrap_result(_poll_rpc(context, request_token))
return result.results[0].node["compiled_sql"]
def create_dbt_rpc_run_sql_solid(
name: str, output_def: Optional[OutputDefinition] = None, **kwargs
) -> Callable:
"""This function is a factory which constructs a solid that will copy the results of a SQL query
run within the context of a dbt project to a pandas ``DataFrame``.
Any kwargs passed to this function will be passed along to the underlying :func:`@solid
<dagster.solid>` decorator. However, note that overriding ``config_schema``, ``input_defs``, and
``required_resource_keys`` is not allowed and will throw a :class:`DagsterInvalidDefinitionError
<dagster.DagsterInvalidDefinitionError>`.
If you would like to configure this solid with different config fields, you could consider using
:func:`@composite_solid <dagster.composite_solid>` to wrap this solid.
Args:
name (str): The name of this solid.
output_def (OutputDefinition, optional): The :class:`OutputDefinition
<dagster.OutputDefinition>` for the solid. This value should always be a representation
of a pandas ``DataFrame``. If not specified, the solid will default to an
:class:`OutputDefinition <dagster.OutputDefinition>` named "df" with a ``DataFrame``
dagster type.
Returns:
SolidDefinition: Returns the constructed solid definition.
"""
check.str_param(obj=name, param_name="name")
check.opt_inst_param(obj=output_def, param_name="output_def", ttype=OutputDefinition)
if "config_schema" in kwargs:
raise DagsterInvalidDefinitionError("Overriding config_schema is not supported.")
if "input_defs" in kwargs:
raise DagsterInvalidDefinitionError("Overriding input_defs is not supported.")
if "required_resource_keys" in kwargs:
raise DagsterInvalidDefinitionError("Overriding required_resource_keys is not supported.")
@solid(
name=name,
description=kwargs.pop(
"description",
"A solid to run a SQL query in context of a dbt project over RPC and return the results in a pandas DataFrame.",
),
input_defs=[
InputDefinition(name="start_after", dagster_type=Nothing),
InputDefinition(
name="sql", description="The SQL query to be run.", dagster_type=String
),
],
output_defs=[
output_def
or OutputDefinition(
name="df", description="The results of the SQL query.", dagster_type=DataFrame
)
],
config_schema={
"name": Field(config=String),
"interval": Field(
config=Int,
is_required=False,
default_value=10,
description="The interval (in seconds) at which to poll the dbt rpc process.",
),
"logs": Field(
config=Bool,
is_required=False,
default_value=True,
description="Whether or not to return logs from the process.",
),
},
required_resource_keys={"dbt_rpc"},
tags={"kind": "dbt"},
**kwargs,
)
def _dbt_rpc_run_sql(context: SolidExecutionContext, sql: String) -> DataFrame:
resp = context.resources.dbt_rpc.run_sql(sql=sql, name=context.solid_config["name"])
context.log.debug(resp.text)
raise_for_rpc_error(context, resp)
request_token = resp.json().get("result").get("request_token")
result = unwrap_result(_poll_rpc(context, request_token))
table = result.results[0].table
return pd.DataFrame.from_records(data=table["rows"], columns=table["column_names"])
return _dbt_rpc_run_sql
|
#!/usr/bin/python3
import os
import boto3
import covid_scraper as cs
from botocore.exceptions import ClientError
from mimetypes import guess_type
INDEX='index.html'
CZECH_DATA='czechia_table.csv'
S3_DIR='data'
TMP='/tmp/'
# Client for operation with S3
# Requires IAM policy for S3 with following permissions:
# GetObject, PutObject and HeadObject
s3 = boto3.client('s3')
def get_paths(filename):
"""
Returns temporary path for Lambda processing and S3 path.
/tmp/filname
data/filename
"""
lamPath = os.path.join(TMP, filename)
s3Path = os.path.join(S3_DIR, filename)
return lamPath, s3Path
def is_S3File(bucket, key):
"""
Check if 'key' object exists in S3 Bucket.
bucket: Name of the S3 bucket
key: Object path in S3
"""
is_file = False
try:
s3.head_object(Bucket=bucket, Key=key)
is_file = True
except ClientError as err:
if err.response['Error']['Code'] == '404':
print(f"Error Message: {err.response["Error"]["Message"]}")
else:
raise
return is_file
def lambda_handler(event, context):
"""
AWS Lambda function to pull COVID-19 data and save them to S3
bucket.
"""
cvd_bucket = event["S3Bucket"] if "S3Bucket" in event else None
if not cvd_bucket:
print('Missing S3 bucket!')
return { 'message': 'Error: S3 bucket was not found in event data!' }
print("Pulling COVID-19 data.")
fileName, covidData = cs.get_covid_data()
tmpPath, newPath = get_paths(fileName)
if not covidData.empty:
covidData.to_csv(tmpPath)
else:
return { 'message': 'Failed to get today\'s COVID-19 data.' }
print(f"Saving '{fileName}' to S3 bucket '{cvd_bucket}/{S3_DIR}'.")
s3.upload_file(tmpPath, cvd_bucket, newPath)
print(f"Updating table data.")
tmpCzech, czechTable = get_paths(CZECH_DATA)
if is_S3File(cvd_bucket, czechTable):
s3.download_file(cvd_bucket, czechTable, tmpCzech)
newData = cs.update_csv(tmpCzech, covidData)
print(f"Saving {CZECH_DATA} to S3 bucket '{cvd_bucket}'.")
s3.upload_file(tmpCzech, cvd_bucket, czechTable)
print(f"Saving updated index.html to S3 bucket {cvd_bucket}.")
tmpIndex, _ = get_paths(INDEX)
cs.create_index(newData, tmpIndex)
content_type = guess_type(tmpIndex)[0]
s3.upload_file(tmpIndex, cvd_bucket, INDEX,
ExtraArgs={'ContentType': content_type, 'ACL': "public-read"})
print("All done.")
return { 'message': 'Success!' }
| #!/usr/bin/python3
import os
import boto3
import covid_scraper as cs
from botocore.exceptions import ClientError
from mimetypes import guess_type
INDEX='index.html'
CZECH_DATA='czechia_table.csv'
S3_DIR='data'
TMP='/tmp/'
# Client for operation with S3
# Requires IAM policy for S3 with following permissions:
# GetObject, PutObject and HeadObject
s3 = boto3.client('s3')
def get_paths(filename):
"""
Returns temporary path for Lambda processing and S3 path.
/tmp/filname
data/filename
"""
lamPath = os.path.join(TMP, filename)
s3Path = os.path.join(S3_DIR, filename)
return lamPath, s3Path
def is_S3File(bucket, key):
"""
Check if 'key' object exists in S3 Bucket.
bucket: Name of the S3 bucket
key: Object path in S3
"""
is_file = False
try:
s3.head_object(Bucket=bucket, Key=key)
is_file = True
except ClientError as err:
if err.response['Error']['Code'] == '404':
print(f"Error Message: {err.response['Error']['Message']}")
else:
raise
return is_file
def lambda_handler(event, context):
"""
AWS Lambda function to pull COVID-19 data and save them to S3
bucket.
"""
cvd_bucket = event["S3Bucket"] if "S3Bucket" in event else None
if not cvd_bucket:
print('Missing S3 bucket!')
return { 'message': 'Error: S3 bucket was not found in event data!' }
print("Pulling COVID-19 data.")
fileName, covidData = cs.get_covid_data()
tmpPath, newPath = get_paths(fileName)
if not covidData.empty:
covidData.to_csv(tmpPath)
else:
return { 'message': 'Failed to get today\'s COVID-19 data.' }
print(f"Saving '{fileName}' to S3 bucket '{cvd_bucket}/{S3_DIR}'.")
s3.upload_file(tmpPath, cvd_bucket, newPath)
print(f"Updating table data.")
tmpCzech, czechTable = get_paths(CZECH_DATA)
if is_S3File(cvd_bucket, czechTable):
s3.download_file(cvd_bucket, czechTable, tmpCzech)
newData = cs.update_csv(tmpCzech, covidData)
print(f"Saving {CZECH_DATA} to S3 bucket '{cvd_bucket}'.")
s3.upload_file(tmpCzech, cvd_bucket, czechTable)
print(f"Saving updated index.html to S3 bucket {cvd_bucket}.")
tmpIndex, _ = get_paths(INDEX)
cs.create_index(newData, tmpIndex)
content_type = guess_type(tmpIndex)[0]
s3.upload_file(tmpIndex, cvd_bucket, INDEX,
ExtraArgs={'ContentType': content_type, 'ACL': "public-read"})
print("All done.")
return { 'message': 'Success!' }
|
"""
A minimalistic version helper in the spirit of versioneer, that is able to run without build step using pkg_resources.
Developed by P Angerer, see https://github.com/flying-sheep/get_version.
"""
import re
import os
from pathlib import Path
from subprocess import run, PIPE, CalledProcessError
from typing import NamedTuple, List, Union, Optional
RE_VERSION = r"([\d.]+?)(?:\.dev(\d+))?(?:[_+-]([0-9a-zA-Z.]+))?"
RE_GIT_DESCRIBE = r"v?(?:([\d.]+)-(\d+)-g)?([0-9a-f]{7})(-dirty)?"
ON_RTD = os.environ.get("READTHEDOCS") == "True"
def match_groups(regex, target):
match = re.match(regex, target)
if match is None:
raise re.error(f"Regex does not match “{target}”. RE Pattern: {regex}", regex)
return match.groups()
class Version(NamedTuple):
release: str
dev: Optional[str]
labels: List[str]
@staticmethod
def parse(ver):
release, dev, labels = match_groups(f"{RE_VERSION}$", ver)
return Version(release, dev, labels.split(".") if labels else [])
def __str__(self):
release = self.release if self.release else "0.0"
dev = f".dev{self.dev}" if self.dev else ""
labels = f'+{'.'.join(self.labels)}' if self.labels else ""
return f"{release}{dev}{labels}"
def get_version_from_dirname(name, parent):
"""Extracted sdist"""
parent = parent.resolve()
re_dirname = re.compile(f"{name}-{RE_VERSION}$")
if not re_dirname.match(parent.name):
return None
return Version.parse(parent.name[len(name) + 1 :])
def get_version_from_git(parent):
parent = parent.resolve()
try:
p = run(
["git", "rev-parse", "--show-toplevel"],
cwd=str(parent),
stdout=PIPE,
stderr=PIPE,
encoding="utf-8",
check=True,
)
except (OSError, CalledProcessError):
return None
if Path(p.stdout.rstrip("\r\n")).resolve() != parent.resolve():
return None
p = run(
[
"git",
"describe",
"--tags",
"--dirty",
"--always",
"--long",
"--match",
"v[0-9]*",
],
cwd=str(parent),
stdout=PIPE,
stderr=PIPE,
encoding="utf-8",
check=True,
)
release, dev, hex_, dirty = match_groups(
f"{RE_GIT_DESCRIBE}$", p.stdout.rstrip("\r\n")
)
labels = []
if dev == "0":
dev = None
else:
labels.append(hex_)
if dirty and not ON_RTD:
labels.append("dirty")
return Version(release, dev, labels)
def get_version_from_metadata(name: str, parent: Optional[Path] = None):
try:
from pkg_resources import get_distribution, DistributionNotFound
except ImportError:
return None
try:
pkg = get_distribution(name)
except DistributionNotFound:
return None
# For an installed package, the parent is the install location
path_pkg = Path(pkg.location).resolve()
if parent is not None and path_pkg != parent.resolve():
msg = f"""\
metadata: Failed; distribution and package paths do not match:
{path_pkg}
!=
{parent.resolve()}\
"""
return None
return Version.parse(pkg.version)
def get_version(package: Union[Path, str]) -> str:
"""Get the version of a package or module
Pass a module path or package name.
The former is recommended, since it also works for not yet installed packages.
Supports getting the version from
#. The directory name (as created by ``setup.py sdist``)
#. The output of ``git describe``
#. The package metadata of an installed package
(This is the only possibility when passing a name)
Args:
package: package name or module path (``…/module.py`` or ``…/module/__init__.py``)
"""
path = Path(package)
if not path.suffix and len(path.parts) == 1: # Is probably not a path
v = get_version_from_metadata(package)
if v:
return str(v)
if path.suffix != ".py":
msg = f"“package” is neither the name of an installed module nor the path to a .py file."
if path.suffix:
msg += f" Unknown file suffix {path.suffix}"
raise ValueError(msg)
if path.name == "__init__.py":
name = path.parent.name
parent = path.parent.parent
else:
name = path.with_suffix("").name
parent = path.parent
return str(
get_version_from_dirname(name, parent)
or get_version_from_git(parent)
or get_version_from_metadata(name, parent)
or "0.0.0"
)
__version__ = get_version(__file__)
if __name__ == "__main__":
print(__version__)
| """
A minimalistic version helper in the spirit of versioneer, that is able to run without build step using pkg_resources.
Developed by P Angerer, see https://github.com/flying-sheep/get_version.
"""
import re
import os
from pathlib import Path
from subprocess import run, PIPE, CalledProcessError
from typing import NamedTuple, List, Union, Optional
RE_VERSION = r"([\d.]+?)(?:\.dev(\d+))?(?:[_+-]([0-9a-zA-Z.]+))?"
RE_GIT_DESCRIBE = r"v?(?:([\d.]+)-(\d+)-g)?([0-9a-f]{7})(-dirty)?"
ON_RTD = os.environ.get("READTHEDOCS") == "True"
def match_groups(regex, target):
match = re.match(regex, target)
if match is None:
raise re.error(f"Regex does not match “{target}”. RE Pattern: {regex}", regex)
return match.groups()
class Version(NamedTuple):
release: str
dev: Optional[str]
labels: List[str]
@staticmethod
def parse(ver):
release, dev, labels = match_groups(f"{RE_VERSION}$", ver)
return Version(release, dev, labels.split(".") if labels else [])
def __str__(self):
release = self.release if self.release else "0.0"
dev = f".dev{self.dev}" if self.dev else ""
labels = f'+{".".join(self.labels)}' if self.labels else ""
return f"{release}{dev}{labels}"
def get_version_from_dirname(name, parent):
"""Extracted sdist"""
parent = parent.resolve()
re_dirname = re.compile(f"{name}-{RE_VERSION}$")
if not re_dirname.match(parent.name):
return None
return Version.parse(parent.name[len(name) + 1 :])
def get_version_from_git(parent):
parent = parent.resolve()
try:
p = run(
["git", "rev-parse", "--show-toplevel"],
cwd=str(parent),
stdout=PIPE,
stderr=PIPE,
encoding="utf-8",
check=True,
)
except (OSError, CalledProcessError):
return None
if Path(p.stdout.rstrip("\r\n")).resolve() != parent.resolve():
return None
p = run(
[
"git",
"describe",
"--tags",
"--dirty",
"--always",
"--long",
"--match",
"v[0-9]*",
],
cwd=str(parent),
stdout=PIPE,
stderr=PIPE,
encoding="utf-8",
check=True,
)
release, dev, hex_, dirty = match_groups(
f"{RE_GIT_DESCRIBE}$", p.stdout.rstrip("\r\n")
)
labels = []
if dev == "0":
dev = None
else:
labels.append(hex_)
if dirty and not ON_RTD:
labels.append("dirty")
return Version(release, dev, labels)
def get_version_from_metadata(name: str, parent: Optional[Path] = None):
try:
from pkg_resources import get_distribution, DistributionNotFound
except ImportError:
return None
try:
pkg = get_distribution(name)
except DistributionNotFound:
return None
# For an installed package, the parent is the install location
path_pkg = Path(pkg.location).resolve()
if parent is not None and path_pkg != parent.resolve():
msg = f"""\
metadata: Failed; distribution and package paths do not match:
{path_pkg}
!=
{parent.resolve()}\
"""
return None
return Version.parse(pkg.version)
def get_version(package: Union[Path, str]) -> str:
"""Get the version of a package or module
Pass a module path or package name.
The former is recommended, since it also works for not yet installed packages.
Supports getting the version from
#. The directory name (as created by ``setup.py sdist``)
#. The output of ``git describe``
#. The package metadata of an installed package
(This is the only possibility when passing a name)
Args:
package: package name or module path (``…/module.py`` or ``…/module/__init__.py``)
"""
path = Path(package)
if not path.suffix and len(path.parts) == 1: # Is probably not a path
v = get_version_from_metadata(package)
if v:
return str(v)
if path.suffix != ".py":
msg = f"“package” is neither the name of an installed module nor the path to a .py file."
if path.suffix:
msg += f" Unknown file suffix {path.suffix}"
raise ValueError(msg)
if path.name == "__init__.py":
name = path.parent.name
parent = path.parent.parent
else:
name = path.with_suffix("").name
parent = path.parent
return str(
get_version_from_dirname(name, parent)
or get_version_from_git(parent)
or get_version_from_metadata(name, parent)
or "0.0.0"
)
__version__ = get_version(__file__)
if __name__ == "__main__":
print(__version__)
|
import random
import re
import datetime
import demjson
import requests
import time
import sys
sys.path.append('..')
from configure.settings import DBSelector, send_from_aliyun
from common.BaseService import BaseService
import warnings
warnings.filterwarnings("ignore")
now = datetime.datetime.now()
TODAY = now.strftime('%Y-%m-%d')
_time = now.strftime('%H:%M:%S')
if _time < '11:30:00':
TODAY += 'morning'
elif _time < '14:45:00':
TODAY += 'noon'
else:
TODAY += 'close'
# TODAY += 'noon' # 调试
NOTIFY_HOUR = 13
MAX_PAGE = 50
try:
DB = DBSelector()
conn = DB.get_mysql_conn('db_fund', 'qq')
cursor = conn.cursor()
except Exception as e:
print(e)
class TencentFundSpider(BaseService):
# 腾讯 基金数据爬虫 套利使用
def __init__(self):
super(TencentFundSpider, self).__init__(f'../log/{self.__class__.__name__}.log')
self.create_table()
self.session = requests.Session()
self.logger.info('start...qq fund')
self.LAST_TEXT = ''
@property
def headers(self):
_headers = {
'Connection': 'keep-alive',
'Pragma': 'no-cache',
'Cache-Control': 'no-cache',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
'Accept': '*/*',
# 'Referer': 'http://stockapp.finance.qq.com/mstats/?id=fund_close',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh,en;q=0.9,en-US;q=0.8',
}
return _headers
def create_table(self):
create_table = 'create table if not EXISTS `{}` (`基金代码` varchar(20) PRIMARY KEY,`基金简称` ' \
'varchar(100),`最新规模-万` float,' \
'`实时价格` float,`涨跌幅` float,`成交额-万` float,' \
'`净值日期` VARCHAR(10),`单位净值` float,`累计净值` ' \
'float,`折溢价率` float ,`申购状态` VARCHAR(20),`申赎状态` varchar(20),' \
'`基金经理` VARCHAR(200),' \
'`成立日期` VARCHAR(20), `管理人名称` VARCHAR(200),' \
'`实时估值` INT,`更新时间` VARCHAR(20),`数据源` VARCHAR(20) );'.format(
TODAY)
self.execute(create_table, (), conn, self.logger)
def crawl_fund_info_by_code_table(self):
code_list = self.get_fund_code(valid=False)
for code in code_list:
self.get_info_by_code(code)
def get_fund_code(self, valid=True):
query_cmd = 'select code from fund_main_code'
if valid:
query_cmd = query_cmd + 'where valid=1'
result = self.execute(query_cmd, (), conn, self.logger)
code_list = []
for row in result:
code_list.append(row[0])
return code_list
def convert(self, float_str):
try:
return_float = float(float_str)
except:
return_float = None
return return_float
def insert_data(self, jjdm, jjjc, zxgm, zxjg, jgzffd, cj_total_amount, jzrq, dwjz, ljjz, zyjl, sgzt, shzt, jjjl,
clrq, glrmc):
update_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
is_realtime = 1
zxgm = self.convert(zxgm)
zxjg = self.convert(zxjg)
jgzffd = self.convert(jgzffd)
cj_total_amount = self.convert(cj_total_amount)
dwjz = self.convert(dwjz)
ljjz = self.convert(ljjz)
zyjl = self.convert(zyjl)
source = '腾讯基金'
insert_data = 'insert into `{}` VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'.format(TODAY)
if jjdm is None:
# 部分没有数据的基金解析到的基金代码是空,跳过
return
self.execute(insert_data, (
jjdm, jjjc, zxgm, zxjg, jgzffd,
cj_total_amount, jzrq, dwjz,
ljjz,
zyjl, sgzt, shzt, jjjl, clrq,
glrmc, is_realtime, update_time, source), conn, self.logger)
def check_exist(self, code):
check_code_exists = 'select count(*) from `{}` WHERE `基金代码`=%s'.format(TODAY)
cursor.execute(check_code_exists, (code))
ret = cursor.fetchone()
return ret
def get(self, url, params, retry=5, js=False):
start = 0
while start < retry:
try:
response = self.session.get(url, headers=self.headers, params=params,
verify=False)
except Exception as e:
self.logger.error(e)
start += 1
else:
if js:
content = response.json()
else:
content = response.text
return content
if start == retry:
self.logger.error('重试太多')
return None
def crawl(self):
'''
废弃 网页内容不存在了
'''
url = 'http://stock.gtimg.cn/data/index.php'
for p in range(1, MAX_PAGE):
params = (
('appn', 'rank'),
('t', 'ranklof/chr'),
('p', p),
('o', '0'),
('l', '40'),
('v', 'list_data'),
)
content = self.get(url, params)
if content is None:
continue
if content == self.LAST_TEXT:
break
self.LAST_TEXT = content
ls_data = re.search('var list_data=(.*?);', content, re.S)
if ls_data:
ret = ls_data.group(1)
else:
self.logger.error('解析出错')
continue
js = demjson.decode(ret) # 解析json的库
query_string = js.get('data')
time.sleep(5 * random.random())
for code in query_string.split(','):
self.get_info_by_code(code)
def get_info_by_code(self, code):
code_set = set()
if code not in code_set:
code_set.add(code)
else:
return
ret = self.check_exist(code)
if ret[0] > 0:
return
detail_url = 'http://gu.qq.com/{}'
content = self.get(url=detail_url.format(code), params=None)
if content is None:
self.logger.error('请求内容为空')
return
self.parse_content_and_save(content)
def parse_content_and_save(self, content):
jjdm, jjjc, zxgm, zxjg, jgzffd, cj_total_amount, jzrq, dwjz, ljjz, zyjl, sgzt, shzt, jjjl, clrq, glrmc = self.parse_html(
content)
self.insert_data(jjdm, jjjc, zxgm, zxjg, jgzffd, cj_total_amount, jzrq, dwjz, ljjz, zyjl, sgzt,
shzt, jjjl, clrq, glrmc)
def parse_html(self, content):
search_str = re.search('<script>SSR\["hqpanel"\]=(.*?)</script>', content)
if search_str:
s = search_str.group(1)
js_ = demjson.decode(s)
sub_js = js_.get('data').get('data').get('data')
zxjg = sub_js.get('zxjg')
jgzffd = sub_js.get('jgzffd')
cj_total_amount = sub_js.get('cj_total_amount')
zyjl = float(sub_js.get('zyjl', 0)) * 100
info = js_.get('data').get('data').get('info')
jjdm = info.get('jjdm')
jjjc = info.get('jjjc')
zxgm = info.get('zxgm')
dwjz = info.get('dwjz')
ljjz = info.get('ljjz')
sgzt = info.get('sgzt')
shzt = info.get('shzt')
jjjl = info.get('jjjl')
clrq = info.get('clrq')
glrmc = info.get('glrmc')
jzrq = info.get('jzrq')
return jjdm, jjjc, zxgm, zxjg, jgzffd, cj_total_amount, jzrq, dwjz, ljjz, zyjl, sgzt, shzt, jjjl, clrq, glrmc
else:
return [None] * 15
def change_table_field(self, table):
add_column1 = 'alter table `{}` add column `实时净值` float'.format(table)
add_column2 = 'alter table `{}` add column `溢价率` float'.format(table)
self.execute(add_column1, (), conn, self.logger)
self.execute(add_column2, (), conn, self.logger)
def get_fund_info(self, table):
query = 'select `基金代码`,`基金简称`,`实时价格` from `{}`'.format(table)
return self.execute(query, (), conn, self.logger)
def udpate_db(self, table, jz, yjl, is_realtime, code):
update_sql = 'update `{}` set `实时净值`= %s,`溢价率`=%s ,`实时估值`=%s where `基金代码`=%s'.format(table)
self.execute(update_sql, (jz, yjl, is_realtime, code), conn, self.logger)
def update_netvalue(self):
'''
更新净值
:param table:
:return:
'''
# table='2020-02-25' # 用于获取code列
# TODAY=datetime.datetime.now().strftime('%Y-%m-%d')
table = TODAY
self.change_table_field(table)
all_fund_info = self.get_fund_info(table)
for item in all_fund_info:
jz, yjl, is_realtime, code = self.get_netvalue(table, item)
self.udpate_db(table, jz, yjl, is_realtime, code)
# print(f'更新代码{code}')
self.logger.info('更新成功')
self.notice_me(TODAY)
def get_netvalue(self, table, item):
# 获取净值
code = item[0]
is_realtime = 1
realtime_price = item[2]
url = 'http://web.ifzq.gtimg.cn/fund/newfund/fundSsgz/getSsgz?app=web&symbol=jj{}'
js = self.get(url=url.format(code), params=None, js=True)
data = js.get('data')
if data:
try:
data_list = data.get('data')
except Exception as e:
self.logger.error(e)
jz = None
yjl = None
else:
last_one = data_list[-1]
jz = last_one[1]
if js is None or realtime_price is None:
yjl = 0
else:
yjl = round((realtime_price - jz) / jz * 100, 2)
else:
is_realtime = 0
yjl, jz = self.get_fund(table, code)
return jz, yjl, is_realtime, code
def get_fund(self, table, code):
query = f'select `折溢价率`,`单位净值` from `{table}` where `基金代码`=%s'
cursor.execute(query, code)
ret = cursor.fetchone()
yjl, jz = ret[0], ret[1]
yjl = round(yjl, 3)
jz = round(jz, 3)
return yjl, jz
def query_fund_data(self, today, order):
query_sql = '''select `基金代码`,`基金简称`,`实时价格`,`实时净值`,`溢价率`,`净值日期` from `{}` where `申购状态`='开放' and `申赎状态`='开放' and `基金简称` not like '%%债%%' and `溢价率` is not null and !(`实时价格`=1 and `涨跌幅`=0 and `成交额-万`=0) order by `溢价率` {} limit 10'''.format(
today, order)
return self.execute(query_sql, (), conn, self.logger)
def html_formator(self, ret, html):
for row in ret:
html += f'<tr><td>{row[0]}</td><td>{row[1].replace('(LOF)', '')}</td><td>{row[2]}</td><td>{row[3]}</td><td>{row[4]}</td><td>{row[5]}</td></tr>'
html += '</table></div>'
return html
def combine_html(self, html, today):
body = '<div><table border="1">' \
'<tr><th>基金代码</th><th>基金简称</th><th>实时价格</th><th>实时净值</th><th>溢价率</th><th>净值日期</th></tr>'
html += body
result_asc = self.query_fund_data(today, 'asc')
if self.check_content(result_asc):
html = self.html_formator(result_asc, html)
html += body
result_desc = self.query_fund_data(today, 'desc')
if self.check_content(result_desc):
html = self.html_formator(result_desc, html)
return html
def check_content(self, content):
if content is None:
self.logger.error('获取内容为空')
return False
else:
return True
def notice_me(self, today):
now = datetime.datetime.now()
if now.hour > NOTIFY_HOUR:
# 下午才会发通知
title = f'{today} 基金折溢价'
html = ''
html = self.combine_html(html, TODAY)
try:
send_from_aliyun(title, html, types='html')
except Exception as e:
self.logger.error(e)
self.logger.info('发送失败')
else:
self.logger.info('发送成功')
if __name__ == '__main__':
now = datetime.datetime.now()
TODAY = now.strftime('%Y-%m-%d')
_time = now.strftime('%H:%M:%S')
if _time < '11:30:00':
TODAY += 'morning'
elif _time < '14:45:00':
TODAY += 'noon'
else:
TODAY += 'close'
# TODAY += 'noon'
app = TencentFundSpider()
app.crawl_fund_info_by_code_table()
# app.crawl()
# app.update_netvalue(TODAY)
# app.notice_me(TODAY)
# app.get_info_by_code('160137')
# print(app.get_fund_code())
app.update_netvalue()
| import random
import re
import datetime
import demjson
import requests
import time
import sys
sys.path.append('..')
from configure.settings import DBSelector, send_from_aliyun
from common.BaseService import BaseService
import warnings
warnings.filterwarnings("ignore")
now = datetime.datetime.now()
TODAY = now.strftime('%Y-%m-%d')
_time = now.strftime('%H:%M:%S')
if _time < '11:30:00':
TODAY += 'morning'
elif _time < '14:45:00':
TODAY += 'noon'
else:
TODAY += 'close'
# TODAY += 'noon' # 调试
NOTIFY_HOUR = 13
MAX_PAGE = 50
try:
DB = DBSelector()
conn = DB.get_mysql_conn('db_fund', 'qq')
cursor = conn.cursor()
except Exception as e:
print(e)
class TencentFundSpider(BaseService):
# 腾讯 基金数据爬虫 套利使用
def __init__(self):
super(TencentFundSpider, self).__init__(f'../log/{self.__class__.__name__}.log')
self.create_table()
self.session = requests.Session()
self.logger.info('start...qq fund')
self.LAST_TEXT = ''
@property
def headers(self):
_headers = {
'Connection': 'keep-alive',
'Pragma': 'no-cache',
'Cache-Control': 'no-cache',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
'Accept': '*/*',
# 'Referer': 'http://stockapp.finance.qq.com/mstats/?id=fund_close',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh,en;q=0.9,en-US;q=0.8',
}
return _headers
def create_table(self):
create_table = 'create table if not EXISTS `{}` (`基金代码` varchar(20) PRIMARY KEY,`基金简称` ' \
'varchar(100),`最新规模-万` float,' \
'`实时价格` float,`涨跌幅` float,`成交额-万` float,' \
'`净值日期` VARCHAR(10),`单位净值` float,`累计净值` ' \
'float,`折溢价率` float ,`申购状态` VARCHAR(20),`申赎状态` varchar(20),' \
'`基金经理` VARCHAR(200),' \
'`成立日期` VARCHAR(20), `管理人名称` VARCHAR(200),' \
'`实时估值` INT,`更新时间` VARCHAR(20),`数据源` VARCHAR(20) );'.format(
TODAY)
self.execute(create_table, (), conn, self.logger)
def crawl_fund_info_by_code_table(self):
code_list = self.get_fund_code(valid=False)
for code in code_list:
self.get_info_by_code(code)
def get_fund_code(self, valid=True):
query_cmd = 'select code from fund_main_code'
if valid:
query_cmd = query_cmd + 'where valid=1'
result = self.execute(query_cmd, (), conn, self.logger)
code_list = []
for row in result:
code_list.append(row[0])
return code_list
def convert(self, float_str):
try:
return_float = float(float_str)
except:
return_float = None
return return_float
def insert_data(self, jjdm, jjjc, zxgm, zxjg, jgzffd, cj_total_amount, jzrq, dwjz, ljjz, zyjl, sgzt, shzt, jjjl,
clrq, glrmc):
update_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
is_realtime = 1
zxgm = self.convert(zxgm)
zxjg = self.convert(zxjg)
jgzffd = self.convert(jgzffd)
cj_total_amount = self.convert(cj_total_amount)
dwjz = self.convert(dwjz)
ljjz = self.convert(ljjz)
zyjl = self.convert(zyjl)
source = '腾讯基金'
insert_data = 'insert into `{}` VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'.format(TODAY)
if jjdm is None:
# 部分没有数据的基金解析到的基金代码是空,跳过
return
self.execute(insert_data, (
jjdm, jjjc, zxgm, zxjg, jgzffd,
cj_total_amount, jzrq, dwjz,
ljjz,
zyjl, sgzt, shzt, jjjl, clrq,
glrmc, is_realtime, update_time, source), conn, self.logger)
def check_exist(self, code):
check_code_exists = 'select count(*) from `{}` WHERE `基金代码`=%s'.format(TODAY)
cursor.execute(check_code_exists, (code))
ret = cursor.fetchone()
return ret
def get(self, url, params, retry=5, js=False):
start = 0
while start < retry:
try:
response = self.session.get(url, headers=self.headers, params=params,
verify=False)
except Exception as e:
self.logger.error(e)
start += 1
else:
if js:
content = response.json()
else:
content = response.text
return content
if start == retry:
self.logger.error('重试太多')
return None
def crawl(self):
'''
废弃 网页内容不存在了
'''
url = 'http://stock.gtimg.cn/data/index.php'
for p in range(1, MAX_PAGE):
params = (
('appn', 'rank'),
('t', 'ranklof/chr'),
('p', p),
('o', '0'),
('l', '40'),
('v', 'list_data'),
)
content = self.get(url, params)
if content is None:
continue
if content == self.LAST_TEXT:
break
self.LAST_TEXT = content
ls_data = re.search('var list_data=(.*?);', content, re.S)
if ls_data:
ret = ls_data.group(1)
else:
self.logger.error('解析出错')
continue
js = demjson.decode(ret) # 解析json的库
query_string = js.get('data')
time.sleep(5 * random.random())
for code in query_string.split(','):
self.get_info_by_code(code)
def get_info_by_code(self, code):
code_set = set()
if code not in code_set:
code_set.add(code)
else:
return
ret = self.check_exist(code)
if ret[0] > 0:
return
detail_url = 'http://gu.qq.com/{}'
content = self.get(url=detail_url.format(code), params=None)
if content is None:
self.logger.error('请求内容为空')
return
self.parse_content_and_save(content)
def parse_content_and_save(self, content):
jjdm, jjjc, zxgm, zxjg, jgzffd, cj_total_amount, jzrq, dwjz, ljjz, zyjl, sgzt, shzt, jjjl, clrq, glrmc = self.parse_html(
content)
self.insert_data(jjdm, jjjc, zxgm, zxjg, jgzffd, cj_total_amount, jzrq, dwjz, ljjz, zyjl, sgzt,
shzt, jjjl, clrq, glrmc)
def parse_html(self, content):
search_str = re.search('<script>SSR\["hqpanel"\]=(.*?)</script>', content)
if search_str:
s = search_str.group(1)
js_ = demjson.decode(s)
sub_js = js_.get('data').get('data').get('data')
zxjg = sub_js.get('zxjg')
jgzffd = sub_js.get('jgzffd')
cj_total_amount = sub_js.get('cj_total_amount')
zyjl = float(sub_js.get('zyjl', 0)) * 100
info = js_.get('data').get('data').get('info')
jjdm = info.get('jjdm')
jjjc = info.get('jjjc')
zxgm = info.get('zxgm')
dwjz = info.get('dwjz')
ljjz = info.get('ljjz')
sgzt = info.get('sgzt')
shzt = info.get('shzt')
jjjl = info.get('jjjl')
clrq = info.get('clrq')
glrmc = info.get('glrmc')
jzrq = info.get('jzrq')
return jjdm, jjjc, zxgm, zxjg, jgzffd, cj_total_amount, jzrq, dwjz, ljjz, zyjl, sgzt, shzt, jjjl, clrq, glrmc
else:
return [None] * 15
def change_table_field(self, table):
add_column1 = 'alter table `{}` add column `实时净值` float'.format(table)
add_column2 = 'alter table `{}` add column `溢价率` float'.format(table)
self.execute(add_column1, (), conn, self.logger)
self.execute(add_column2, (), conn, self.logger)
def get_fund_info(self, table):
query = 'select `基金代码`,`基金简称`,`实时价格` from `{}`'.format(table)
return self.execute(query, (), conn, self.logger)
def udpate_db(self, table, jz, yjl, is_realtime, code):
update_sql = 'update `{}` set `实时净值`= %s,`溢价率`=%s ,`实时估值`=%s where `基金代码`=%s'.format(table)
self.execute(update_sql, (jz, yjl, is_realtime, code), conn, self.logger)
def update_netvalue(self):
'''
更新净值
:param table:
:return:
'''
# table='2020-02-25' # 用于获取code列
# TODAY=datetime.datetime.now().strftime('%Y-%m-%d')
table = TODAY
self.change_table_field(table)
all_fund_info = self.get_fund_info(table)
for item in all_fund_info:
jz, yjl, is_realtime, code = self.get_netvalue(table, item)
self.udpate_db(table, jz, yjl, is_realtime, code)
# print(f'更新代码{code}')
self.logger.info('更新成功')
self.notice_me(TODAY)
def get_netvalue(self, table, item):
# 获取净值
code = item[0]
is_realtime = 1
realtime_price = item[2]
url = 'http://web.ifzq.gtimg.cn/fund/newfund/fundSsgz/getSsgz?app=web&symbol=jj{}'
js = self.get(url=url.format(code), params=None, js=True)
data = js.get('data')
if data:
try:
data_list = data.get('data')
except Exception as e:
self.logger.error(e)
jz = None
yjl = None
else:
last_one = data_list[-1]
jz = last_one[1]
if js is None or realtime_price is None:
yjl = 0
else:
yjl = round((realtime_price - jz) / jz * 100, 2)
else:
is_realtime = 0
yjl, jz = self.get_fund(table, code)
return jz, yjl, is_realtime, code
def get_fund(self, table, code):
query = f'select `折溢价率`,`单位净值` from `{table}` where `基金代码`=%s'
cursor.execute(query, code)
ret = cursor.fetchone()
yjl, jz = ret[0], ret[1]
yjl = round(yjl, 3)
jz = round(jz, 3)
return yjl, jz
def query_fund_data(self, today, order):
query_sql = '''select `基金代码`,`基金简称`,`实时价格`,`实时净值`,`溢价率`,`净值日期` from `{}` where `申购状态`='开放' and `申赎状态`='开放' and `基金简称` not like '%%债%%' and `溢价率` is not null and !(`实时价格`=1 and `涨跌幅`=0 and `成交额-万`=0) order by `溢价率` {} limit 10'''.format(
today, order)
return self.execute(query_sql, (), conn, self.logger)
def html_formator(self, ret, html):
for row in ret:
html += f'<tr><td>{row[0]}</td><td>{row[1].replace("(LOF)", "")}</td><td>{row[2]}</td><td>{row[3]}</td><td>{row[4]}</td><td>{row[5]}</td></tr>'
html += '</table></div>'
return html
def combine_html(self, html, today):
body = '<div><table border="1">' \
'<tr><th>基金代码</th><th>基金简称</th><th>实时价格</th><th>实时净值</th><th>溢价率</th><th>净值日期</th></tr>'
html += body
result_asc = self.query_fund_data(today, 'asc')
if self.check_content(result_asc):
html = self.html_formator(result_asc, html)
html += body
result_desc = self.query_fund_data(today, 'desc')
if self.check_content(result_desc):
html = self.html_formator(result_desc, html)
return html
def check_content(self, content):
if content is None:
self.logger.error('获取内容为空')
return False
else:
return True
def notice_me(self, today):
now = datetime.datetime.now()
if now.hour > NOTIFY_HOUR:
# 下午才会发通知
title = f'{today} 基金折溢价'
html = ''
html = self.combine_html(html, TODAY)
try:
send_from_aliyun(title, html, types='html')
except Exception as e:
self.logger.error(e)
self.logger.info('发送失败')
else:
self.logger.info('发送成功')
if __name__ == '__main__':
now = datetime.datetime.now()
TODAY = now.strftime('%Y-%m-%d')
_time = now.strftime('%H:%M:%S')
if _time < '11:30:00':
TODAY += 'morning'
elif _time < '14:45:00':
TODAY += 'noon'
else:
TODAY += 'close'
# TODAY += 'noon'
app = TencentFundSpider()
app.crawl_fund_info_by_code_table()
# app.crawl()
# app.update_netvalue(TODAY)
# app.notice_me(TODAY)
# app.get_info_by_code('160137')
# print(app.get_fund_code())
app.update_netvalue()
|
"""
Copyright 2021 Dugal Harris - dugalh@gmail.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import importlib
import json
import os
import pathlib
from collections import namedtuple
import click
import ee
from geedim import collection as coll_api
from geedim import export as export_api
from geedim import info, image, _ee_init
class _CmdChainResults(object):
""" Class to hold results for command chaining """
def __init__(self):
self.search_ids = None
self.search_region = None
self.comp_image = None
self.comp_id = None
def _extract_region(region=None, bbox=None, region_buf=5):
""" Return geojson dict from region or bbox parameters """
if (bbox is None or len(bbox) == 0) and (region is None):
raise click.BadOptionUsage('region', 'Either pass --region or --bbox')
if isinstance(region, dict):
region_dict = region
elif region is not None: # read region file/string
region = pathlib.Path(region)
if not region.exists():
raise click.BadParameter(f'{region} does not exist.')
if 'json' in region.suffix:
with open(region) as f:
region_dict = json.load(f)
elif importlib.util.find_spec("rasterio"): # rasterio is installed, extract region from raster file
region_dict, _ = image.get_bounds(region, expand=region_buf)
else:
raise click.BadParameter(f'{region} is not a valid geojson or raster file.')
else: # convert bbox to geojson
xmin, ymin, xmax, ymax = bbox
coordinates = [[xmax, ymax], [xmax, ymin], [xmin, ymin], [xmin, ymax], [xmax, ymax]]
region_dict = dict(type='Polygon', coordinates=[coordinates])
return region_dict
def _export_im_list(im_list, path='', wait=True, overwrite=False, do_download=True, **kwargs):
""" Export/download image(s) """
click.echo('\nDownloading:\n') if do_download else click.echo('\nExporting:\n')
export_tasks = []
for im_dict in im_list:
if do_download:
filename = pathlib.Path(path).joinpath(im_dict['name'] + '.tif')
export_api.download_image(im_dict['image'], filename, overwrite=overwrite, **kwargs)
else:
task = export_api.export_image(im_dict['image'], im_dict['name'], folder=path, wait=False, **kwargs)
export_tasks.append(task)
if wait:
for task in export_tasks:
export_api.monitor_export_task(task)
def _create_im_list(ids, **kwargs):
""" Return a list of Image objects and names, given download/export CLI parameters """
im_list = []
for im_id in ids:
ee_coll_name, im_idx = image.split_id(im_id)
if ee_coll_name not in info.ee_to_gd:
im_list.append(dict(image=ee.Image(im_id), name=im_id.replace('/', '-')))
else:
gd_image = image.get_class(ee_coll_name).from_id(im_id, **kwargs)
im_list.append(dict(image=gd_image, name=im_id.replace('/', '-')))
return im_list
def _export_download(res=_CmdChainResults(), do_download=True, **kwargs):
""" Helper function to execute export/download commands """
ArgTuple = namedtuple('ArgTuple', kwargs)
params = ArgTuple(**kwargs)
# get the download/export region
if (params.region is None) and (params.bbox is None or len(params.bbox) == 0):
if res.search_region is None:
raise click.BadOptionUsage('region',
'Either pass --region / --box, or chain this command with a succesful `search`')
else:
region = res.search_region
else:
region = _extract_region(region=params.region, bbox=params.bbox) # get region geojson
# interpret the CRS
crs = params.crs
if crs is not None:
wkt_fn = pathlib.Path(params.crs)
if wkt_fn.exists(): # read WKT from file, if it exists
with open(wkt_fn, 'r') as f:
crs = f.read()
if importlib.util.find_spec("rasterio"): # clean WKT with rasterio if it is installed
from rasterio import crs as rio_crs
crs = rio_crs.CRS.from_string(crs).to_wkt()
# create a list of Image objects and names
im_list = []
if res.comp_image is not None: # download/export chained with composite command
im_list.append(dict(image=res.comp_image, name=res.comp_id.replace('/', '-')))
elif res.search_ids is not None: # download/export chained with search command
im_list = _create_im_list(res.search_ids, mask=params.mask)
elif len(params.id) > 0: # download/export image ids specified on command line
im_list = _create_im_list(params.id, mask=params.mask)
else:
raise click.BadOptionUsage('id',
'Either pass --id, or chain this command with a successful `search` or `composite`')
# download/export the image list
if do_download:
_export_im_list(im_list, region=region, path=params.download_dir, crs=crs, scale=params.scale,
resampling=params.resampling, overwrite=params.overwrite, do_download=True)
else:
_export_im_list(im_list, region=region, path=params.drive_folder, crs=crs, scale=params.scale,
resampling=params.resampling, do_download=False, wait=params.wait)
""" Define click options that are common to more than one command """
bbox_option = click.option(
"-b",
"--bbox",
type=click.FLOAT,
nargs=4,
help="Region defined by bounding box co-ordinates in WGS84 (xmin, ymin, xmax, ymax). "
"[One of --bbox or --region is required.]",
required=False,
default=None,
)
region_option = click.option(
"-r",
"--region",
type=click.Path(exists=True, file_okay=True, dir_okay=False, writable=False, readable=True, resolve_path=True,
allow_dash=False),
help="Region defined by geojson or raster file. [One of --bbox or --region is required.]",
required=False,
)
image_id_option = click.option(
"-i",
"--id",
type=click.STRING,
help="Earth engine image ID(s).",
required=False,
multiple=True,
)
crs_option = click.option(
"-c",
"--crs",
type=click.STRING,
default=None,
help="Reproject image(s) to this CRS (EPSG string or path to text file containing WKT). \n[default: source CRS]",
required=False,
)
scale_option = click.option(
"-s",
"--scale",
type=click.FLOAT,
default=None,
help="Resample image bands to this pixel resolution (m). \n[default: minimum of the source band resolutions]",
required=False,
)
mask_option = click.option(
"-m/-nm",
"--mask/--no-mask",
default=False,
help="Do/don't apply (cloud and shadow) nodata mask(s). [default: --no-mask]",
required=False,
)
resampling_option = click.option(
"-rs",
"--resampling",
type=click.Choice(["near", "bilinear", "bicubic"], case_sensitive=True),
help="Resampling method.",
default="near",
show_default=True,
)
# Define the geedim CLI and chained command group
@click.group(chain=True)
@click.pass_context
def cli(ctx):
_ee_init()
ctx.obj = _CmdChainResults() # object to hold chained results
# Define search command options
@click.command()
@click.option(
"-c",
"--collection",
type=click.Choice(list(info.gd_to_ee.keys()), case_sensitive=False),
help="Earth Engine image collection to search.",
default="landsat8_c2_l2",
show_default=True,
)
@click.option(
"-s",
"--start-date",
type=click.DateTime(),
help="Start date (UTC).",
required=True,
)
@click.option(
"-e",
"--end-date",
type=click.DateTime(),
help="End date (UTC). \n[default: start_date + 1 day]",
required=False,
)
@bbox_option
@region_option
@click.option(
"-vp",
"--valid-portion",
type=click.FloatRange(min=0, max=100),
default=0,
help="Lower limit of the portion of valid (cloud and shadow free) pixels (%).",
required=False,
show_default=True,
)
@click.option(
"-o",
"--output",
type=click.Path(exists=False, file_okay=True, dir_okay=False, writable=True, readable=False, resolve_path=True,
allow_dash=False),
default=None,
help="Write results to this filename, file type inferred from extension: [.csv|.json]",
required=False,
)
@click.pass_obj
def search(res, collection, start_date, end_date=None, bbox=None, region=None, valid_portion=0, output=None):
""" Search for images """
res.search_region = _extract_region(region=region, bbox=bbox) # store region for chaining
res.search_ids = None
click.echo(f'\nSearching for {info.gd_to_ee[collection]} images between '
f'{start_date.strftime('%Y-%m-%d')} and {end_date.strftime('%Y-%m-%d')}...')
# create collection wrapper and search
gd_collection = coll_api.Collection(collection)
im_df = gd_collection.search(start_date, end_date, res.search_region, valid_portion=valid_portion)
if im_df.shape[0] == 0:
click.echo('No images found\n')
else:
res.search_ids = im_df.ID.values.tolist() # store ids for chaining
click.echo(f'{len(res.search_ids)} images found\n')
click.echo(f'Image property descriptions:\n\n{gd_collection.summary_key}\n')
click.echo(f'Search Results:\n\n{gd_collection.summary}')
# write results to file
if (output is not None):
output = pathlib.Path(output)
if output.suffix == '.csv':
im_df.to_csv(output, index=False)
elif output.suffix == '.json':
im_df.to_json(output, orient='index')
else:
raise ValueError(f'Unknown output file extension: {output.suffix}')
return
cli.add_command(search)
# Define download command options
@click.command()
@image_id_option
@bbox_option
@region_option
@click.option(
"-dd",
"--download-dir",
type=click.Path(exists=True, file_okay=False, dir_okay=True, writable=True, readable=False, resolve_path=True,
allow_dash=False),
default=os.getcwd(),
help="Download image file(s) to this directory. [default: cwd]",
required=False,
)
@crs_option
@scale_option
@mask_option
@resampling_option
@click.option(
"-o",
"--overwrite",
is_flag=True,
default=False,
help="Overwrite the destination file if it exists. [default: prompt the user for confirmation]",
required=False,
show_default=False,
)
@click.pass_context
def download(ctx, id=(), bbox=None, region=None, download_dir=os.getcwd(), crs=None, scale=None, mask=False,
resampling='near', overwrite=False):
""" Download image(s), with cloud and shadow masking """
_export_download(res=ctx.obj, do_download=True, **ctx.params)
cli.add_command(download)
# Define export command options
@click.command()
@image_id_option
@bbox_option
@region_option
@click.option(
"-df",
"--drive-folder",
type=click.STRING,
default='',
help="Export image(s) to this Google Drive folder. [default: root]",
required=False,
)
@crs_option
@scale_option
@mask_option
@resampling_option
@click.option(
"-w/-nw",
"--wait/--no-wait",
default=True,
help="Wait / don't wait for export to complete. [default: --wait]",
required=False,
)
@click.pass_context
def export(ctx, id=(), bbox=None, region=None, drive_folder='', crs=None, scale=None, mask=False, resampling='near',
wait=True):
""" Export image(s) to Google Drive, with cloud and shadow masking """
_export_download(res=ctx.obj, do_download=False, **ctx.params)
cli.add_command(export)
# Define composite command options
@click.command()
@image_id_option
@click.option(
"-cm",
"--method",
type=click.Choice(coll_api.Collection.composite_methods, case_sensitive=False),
help="Compositing method to use.",
default="q_mosaic",
show_default=True,
required=False,
)
@click.option(
"-m/-nm",
"--mask/--no-mask",
default=True,
help="Do/don't apply (cloud and shadow) nodata mask(s) before compositing. [default: --mask]",
required=False,
)
@resampling_option
@click.pass_obj
def composite(res, id=None, mask=True, method='q_mosaic', resampling='near'):
""" Create a cloud-free composite image """
# get image ids from command line or chained search command
id = list(id)
if (id is None or len(id) == 0):
if res.search_ids is None:
raise click.BadOptionUsage('id', 'Either pass --id, or chain this command with a successful `search`')
else:
id = res.search_ids
res.search_ids = None
gd_collection = coll_api.Collection.from_ids(id, mask=mask)
res.comp_image, res.comp_id = gd_collection.composite(method=method, resampling=resampling)
cli.add_command(composite)
##
| """
Copyright 2021 Dugal Harris - dugalh@gmail.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import importlib
import json
import os
import pathlib
from collections import namedtuple
import click
import ee
from geedim import collection as coll_api
from geedim import export as export_api
from geedim import info, image, _ee_init
class _CmdChainResults(object):
""" Class to hold results for command chaining """
def __init__(self):
self.search_ids = None
self.search_region = None
self.comp_image = None
self.comp_id = None
def _extract_region(region=None, bbox=None, region_buf=5):
""" Return geojson dict from region or bbox parameters """
if (bbox is None or len(bbox) == 0) and (region is None):
raise click.BadOptionUsage('region', 'Either pass --region or --bbox')
if isinstance(region, dict):
region_dict = region
elif region is not None: # read region file/string
region = pathlib.Path(region)
if not region.exists():
raise click.BadParameter(f'{region} does not exist.')
if 'json' in region.suffix:
with open(region) as f:
region_dict = json.load(f)
elif importlib.util.find_spec("rasterio"): # rasterio is installed, extract region from raster file
region_dict, _ = image.get_bounds(region, expand=region_buf)
else:
raise click.BadParameter(f'{region} is not a valid geojson or raster file.')
else: # convert bbox to geojson
xmin, ymin, xmax, ymax = bbox
coordinates = [[xmax, ymax], [xmax, ymin], [xmin, ymin], [xmin, ymax], [xmax, ymax]]
region_dict = dict(type='Polygon', coordinates=[coordinates])
return region_dict
def _export_im_list(im_list, path='', wait=True, overwrite=False, do_download=True, **kwargs):
""" Export/download image(s) """
click.echo('\nDownloading:\n') if do_download else click.echo('\nExporting:\n')
export_tasks = []
for im_dict in im_list:
if do_download:
filename = pathlib.Path(path).joinpath(im_dict['name'] + '.tif')
export_api.download_image(im_dict['image'], filename, overwrite=overwrite, **kwargs)
else:
task = export_api.export_image(im_dict['image'], im_dict['name'], folder=path, wait=False, **kwargs)
export_tasks.append(task)
if wait:
for task in export_tasks:
export_api.monitor_export_task(task)
def _create_im_list(ids, **kwargs):
""" Return a list of Image objects and names, given download/export CLI parameters """
im_list = []
for im_id in ids:
ee_coll_name, im_idx = image.split_id(im_id)
if ee_coll_name not in info.ee_to_gd:
im_list.append(dict(image=ee.Image(im_id), name=im_id.replace('/', '-')))
else:
gd_image = image.get_class(ee_coll_name).from_id(im_id, **kwargs)
im_list.append(dict(image=gd_image, name=im_id.replace('/', '-')))
return im_list
def _export_download(res=_CmdChainResults(), do_download=True, **kwargs):
""" Helper function to execute export/download commands """
ArgTuple = namedtuple('ArgTuple', kwargs)
params = ArgTuple(**kwargs)
# get the download/export region
if (params.region is None) and (params.bbox is None or len(params.bbox) == 0):
if res.search_region is None:
raise click.BadOptionUsage('region',
'Either pass --region / --box, or chain this command with a succesful `search`')
else:
region = res.search_region
else:
region = _extract_region(region=params.region, bbox=params.bbox) # get region geojson
# interpret the CRS
crs = params.crs
if crs is not None:
wkt_fn = pathlib.Path(params.crs)
if wkt_fn.exists(): # read WKT from file, if it exists
with open(wkt_fn, 'r') as f:
crs = f.read()
if importlib.util.find_spec("rasterio"): # clean WKT with rasterio if it is installed
from rasterio import crs as rio_crs
crs = rio_crs.CRS.from_string(crs).to_wkt()
# create a list of Image objects and names
im_list = []
if res.comp_image is not None: # download/export chained with composite command
im_list.append(dict(image=res.comp_image, name=res.comp_id.replace('/', '-')))
elif res.search_ids is not None: # download/export chained with search command
im_list = _create_im_list(res.search_ids, mask=params.mask)
elif len(params.id) > 0: # download/export image ids specified on command line
im_list = _create_im_list(params.id, mask=params.mask)
else:
raise click.BadOptionUsage('id',
'Either pass --id, or chain this command with a successful `search` or `composite`')
# download/export the image list
if do_download:
_export_im_list(im_list, region=region, path=params.download_dir, crs=crs, scale=params.scale,
resampling=params.resampling, overwrite=params.overwrite, do_download=True)
else:
_export_im_list(im_list, region=region, path=params.drive_folder, crs=crs, scale=params.scale,
resampling=params.resampling, do_download=False, wait=params.wait)
""" Define click options that are common to more than one command """
bbox_option = click.option(
"-b",
"--bbox",
type=click.FLOAT,
nargs=4,
help="Region defined by bounding box co-ordinates in WGS84 (xmin, ymin, xmax, ymax). "
"[One of --bbox or --region is required.]",
required=False,
default=None,
)
region_option = click.option(
"-r",
"--region",
type=click.Path(exists=True, file_okay=True, dir_okay=False, writable=False, readable=True, resolve_path=True,
allow_dash=False),
help="Region defined by geojson or raster file. [One of --bbox or --region is required.]",
required=False,
)
image_id_option = click.option(
"-i",
"--id",
type=click.STRING,
help="Earth engine image ID(s).",
required=False,
multiple=True,
)
crs_option = click.option(
"-c",
"--crs",
type=click.STRING,
default=None,
help="Reproject image(s) to this CRS (EPSG string or path to text file containing WKT). \n[default: source CRS]",
required=False,
)
scale_option = click.option(
"-s",
"--scale",
type=click.FLOAT,
default=None,
help="Resample image bands to this pixel resolution (m). \n[default: minimum of the source band resolutions]",
required=False,
)
mask_option = click.option(
"-m/-nm",
"--mask/--no-mask",
default=False,
help="Do/don't apply (cloud and shadow) nodata mask(s). [default: --no-mask]",
required=False,
)
resampling_option = click.option(
"-rs",
"--resampling",
type=click.Choice(["near", "bilinear", "bicubic"], case_sensitive=True),
help="Resampling method.",
default="near",
show_default=True,
)
# Define the geedim CLI and chained command group
@click.group(chain=True)
@click.pass_context
def cli(ctx):
_ee_init()
ctx.obj = _CmdChainResults() # object to hold chained results
# Define search command options
@click.command()
@click.option(
"-c",
"--collection",
type=click.Choice(list(info.gd_to_ee.keys()), case_sensitive=False),
help="Earth Engine image collection to search.",
default="landsat8_c2_l2",
show_default=True,
)
@click.option(
"-s",
"--start-date",
type=click.DateTime(),
help="Start date (UTC).",
required=True,
)
@click.option(
"-e",
"--end-date",
type=click.DateTime(),
help="End date (UTC). \n[default: start_date + 1 day]",
required=False,
)
@bbox_option
@region_option
@click.option(
"-vp",
"--valid-portion",
type=click.FloatRange(min=0, max=100),
default=0,
help="Lower limit of the portion of valid (cloud and shadow free) pixels (%).",
required=False,
show_default=True,
)
@click.option(
"-o",
"--output",
type=click.Path(exists=False, file_okay=True, dir_okay=False, writable=True, readable=False, resolve_path=True,
allow_dash=False),
default=None,
help="Write results to this filename, file type inferred from extension: [.csv|.json]",
required=False,
)
@click.pass_obj
def search(res, collection, start_date, end_date=None, bbox=None, region=None, valid_portion=0, output=None):
""" Search for images """
res.search_region = _extract_region(region=region, bbox=bbox) # store region for chaining
res.search_ids = None
click.echo(f'\nSearching for {info.gd_to_ee[collection]} images between '
f'{start_date.strftime("%Y-%m-%d")} and {end_date.strftime("%Y-%m-%d")}...')
# create collection wrapper and search
gd_collection = coll_api.Collection(collection)
im_df = gd_collection.search(start_date, end_date, res.search_region, valid_portion=valid_portion)
if im_df.shape[0] == 0:
click.echo('No images found\n')
else:
res.search_ids = im_df.ID.values.tolist() # store ids for chaining
click.echo(f'{len(res.search_ids)} images found\n')
click.echo(f'Image property descriptions:\n\n{gd_collection.summary_key}\n')
click.echo(f'Search Results:\n\n{gd_collection.summary}')
# write results to file
if (output is not None):
output = pathlib.Path(output)
if output.suffix == '.csv':
im_df.to_csv(output, index=False)
elif output.suffix == '.json':
im_df.to_json(output, orient='index')
else:
raise ValueError(f'Unknown output file extension: {output.suffix}')
return
cli.add_command(search)
# Define download command options
@click.command()
@image_id_option
@bbox_option
@region_option
@click.option(
"-dd",
"--download-dir",
type=click.Path(exists=True, file_okay=False, dir_okay=True, writable=True, readable=False, resolve_path=True,
allow_dash=False),
default=os.getcwd(),
help="Download image file(s) to this directory. [default: cwd]",
required=False,
)
@crs_option
@scale_option
@mask_option
@resampling_option
@click.option(
"-o",
"--overwrite",
is_flag=True,
default=False,
help="Overwrite the destination file if it exists. [default: prompt the user for confirmation]",
required=False,
show_default=False,
)
@click.pass_context
def download(ctx, id=(), bbox=None, region=None, download_dir=os.getcwd(), crs=None, scale=None, mask=False,
resampling='near', overwrite=False):
""" Download image(s), with cloud and shadow masking """
_export_download(res=ctx.obj, do_download=True, **ctx.params)
cli.add_command(download)
# Define export command options
@click.command()
@image_id_option
@bbox_option
@region_option
@click.option(
"-df",
"--drive-folder",
type=click.STRING,
default='',
help="Export image(s) to this Google Drive folder. [default: root]",
required=False,
)
@crs_option
@scale_option
@mask_option
@resampling_option
@click.option(
"-w/-nw",
"--wait/--no-wait",
default=True,
help="Wait / don't wait for export to complete. [default: --wait]",
required=False,
)
@click.pass_context
def export(ctx, id=(), bbox=None, region=None, drive_folder='', crs=None, scale=None, mask=False, resampling='near',
wait=True):
""" Export image(s) to Google Drive, with cloud and shadow masking """
_export_download(res=ctx.obj, do_download=False, **ctx.params)
cli.add_command(export)
# Define composite command options
@click.command()
@image_id_option
@click.option(
"-cm",
"--method",
type=click.Choice(coll_api.Collection.composite_methods, case_sensitive=False),
help="Compositing method to use.",
default="q_mosaic",
show_default=True,
required=False,
)
@click.option(
"-m/-nm",
"--mask/--no-mask",
default=True,
help="Do/don't apply (cloud and shadow) nodata mask(s) before compositing. [default: --mask]",
required=False,
)
@resampling_option
@click.pass_obj
def composite(res, id=None, mask=True, method='q_mosaic', resampling='near'):
""" Create a cloud-free composite image """
# get image ids from command line or chained search command
id = list(id)
if (id is None or len(id) == 0):
if res.search_ids is None:
raise click.BadOptionUsage('id', 'Either pass --id, or chain this command with a successful `search`')
else:
id = res.search_ids
res.search_ids = None
gd_collection = coll_api.Collection.from_ids(id, mask=mask)
res.comp_image, res.comp_id = gd_collection.composite(method=method, resampling=resampling)
cli.add_command(composite)
##
|
from django.http import HttpResponse
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.conf import settings
from .models import Order, OrderLineItem
from products.models import Album
from profiles.models import UserProfile
import json
import time
class StripeWH_Handler:
"""Handle Stripe webhooks"""
def __init__(self, request):
self.request = request
def _send_confirmation_email(self, order):
"""Send the user a confirmation email"""
cust_email = order.email
subject = render_to_string(
"checkout/confirmation_emails/confirmation_email_subject.txt",
{"order": order},
)
body = render_to_string(
"checkout/confirmation_emails/confirmation_email_body.txt",
{"order": order, "contact_email": settings.DEFAULT_FROM_EMAIL},
)
send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, [cust_email])
def handle_event(self, event):
"""
Handle a generic/unknown/unexpected webhook event
"""
return HttpResponse(
content=f'Unhandled webhook received: {event['type']}', status=200
)
def handle_payment_intent_succeeded(self, event):
"""
Handle the payment_intent.succeeded webhook from Stripe
"""
intent = event.data.object
pid = intent.id
cart = intent.metadata.cart
save_info = intent.metadata.save_info
billing_details = intent.charges.data[0].billing_details
shipping_details = intent.shipping
grand_total = round(intent.charges.data[0].amount / 100, 2)
# Clean data in the shipping details
for field, value in shipping_details.address.items():
if value == "":
shipping_details.address[field] = None
# Update profile information if save_info was checked
profile = None
username = intent.metadata.username
if username != "AnonymousUser":
profile = UserProfile.objects.get(user__username=username)
if save_info:
profile.default_phone_number = shipping_details.phone
profile.default_address_line1 = shipping_details.address.line1
profile.default_address_line2 = shipping_details.address.line2
profile.default_city = shipping_details.address.city
profile.default_county = shipping_details.address.state
profile.default_eircode = shipping_details.address.postal_code
profile.save()
# Attempts to fetch order values 5 times and throws error if unable to
order_exists = False
attempt = 1
while attempt <= 5:
try:
order = Order.objects.get(
first_name__iexact=shipping_details.name.split(" ")[0],
last_name__iexact=shipping_details.name.split(" ")[1],
email__iexact=billing_details.email,
phone_number__iexact=shipping_details.phone,
address_line1__iexact=shipping_details.address.line1,
address_line2__iexact=shipping_details.address.line2,
county__iexact=shipping_details.address.state,
eircode__iexact=shipping_details.address.postal_code,
city__iexact=shipping_details.address.city,
grand_total=grand_total,
original_cart=cart,
stripe_pid=pid,
)
order_exists = True
break
except Order.DoesNotExist:
attempt += 1
time.sleep(1)
# Sends confirmation email if order exists or attempts to create order
# and send confirmation email if it doesn't exist
if order_exists:
self._send_confirmation_email(order)
return HttpResponse(
content=f'Webhook received: {event['type']} | SUCCESS: Verified order already in database',
status=200,
)
else:
order = None
try:
order = Order.objects.create(
first_name=shipping_details.name.split(" ")[0],
last_name=shipping_details.name.split(" ")[1],
user_profile=profile,
email=billing_details.email,
phone_number=shipping_details.phone,
address_line1=shipping_details.address.line1,
address_line2=shipping_details.address.line2,
county=shipping_details.address.state,
eircode=shipping_details.address.postal_code,
city=shipping_details.address.city,
original_cart=cart,
stripe_pid=pid,
)
for item_id, item_data in json.loads(cart).items():
album = Album.objects.get(id=item_id)
order_line_item = OrderLineItem(
order=order,
product=album,
quantity=item_data,
)
order_line_item.save()
except Exception as e:
if order:
order.delete()
return HttpResponse(
content=f'Webhook received: {event['type']} | ERROR: {e}',
status=500,
)
self._send_confirmation_email(order)
return HttpResponse(
content=f'Webhook received: {event['type']} | SUCCESS: Created order in webhook',
status=200,
)
def handle_payment_intent_payment_failed(self, event):
"""
Handle the payment_intent.payment_failed webhook from Stripe
"""
return HttpResponse(content=f'Webhook received: {event['type']}', status=200)
| from django.http import HttpResponse
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.conf import settings
from .models import Order, OrderLineItem
from products.models import Album
from profiles.models import UserProfile
import json
import time
class StripeWH_Handler:
"""Handle Stripe webhooks"""
def __init__(self, request):
self.request = request
def _send_confirmation_email(self, order):
"""Send the user a confirmation email"""
cust_email = order.email
subject = render_to_string(
"checkout/confirmation_emails/confirmation_email_subject.txt",
{"order": order},
)
body = render_to_string(
"checkout/confirmation_emails/confirmation_email_body.txt",
{"order": order, "contact_email": settings.DEFAULT_FROM_EMAIL},
)
send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, [cust_email])
def handle_event(self, event):
"""
Handle a generic/unknown/unexpected webhook event
"""
return HttpResponse(
content=f'Unhandled webhook received: {event["type"]}', status=200
)
def handle_payment_intent_succeeded(self, event):
"""
Handle the payment_intent.succeeded webhook from Stripe
"""
intent = event.data.object
pid = intent.id
cart = intent.metadata.cart
save_info = intent.metadata.save_info
billing_details = intent.charges.data[0].billing_details
shipping_details = intent.shipping
grand_total = round(intent.charges.data[0].amount / 100, 2)
# Clean data in the shipping details
for field, value in shipping_details.address.items():
if value == "":
shipping_details.address[field] = None
# Update profile information if save_info was checked
profile = None
username = intent.metadata.username
if username != "AnonymousUser":
profile = UserProfile.objects.get(user__username=username)
if save_info:
profile.default_phone_number = shipping_details.phone
profile.default_address_line1 = shipping_details.address.line1
profile.default_address_line2 = shipping_details.address.line2
profile.default_city = shipping_details.address.city
profile.default_county = shipping_details.address.state
profile.default_eircode = shipping_details.address.postal_code
profile.save()
# Attempts to fetch order values 5 times and throws error if unable to
order_exists = False
attempt = 1
while attempt <= 5:
try:
order = Order.objects.get(
first_name__iexact=shipping_details.name.split(" ")[0],
last_name__iexact=shipping_details.name.split(" ")[1],
email__iexact=billing_details.email,
phone_number__iexact=shipping_details.phone,
address_line1__iexact=shipping_details.address.line1,
address_line2__iexact=shipping_details.address.line2,
county__iexact=shipping_details.address.state,
eircode__iexact=shipping_details.address.postal_code,
city__iexact=shipping_details.address.city,
grand_total=grand_total,
original_cart=cart,
stripe_pid=pid,
)
order_exists = True
break
except Order.DoesNotExist:
attempt += 1
time.sleep(1)
# Sends confirmation email if order exists or attempts to create order
# and send confirmation email if it doesn't exist
if order_exists:
self._send_confirmation_email(order)
return HttpResponse(
content=f'Webhook received: {event["type"]} | SUCCESS: Verified order already in database',
status=200,
)
else:
order = None
try:
order = Order.objects.create(
first_name=shipping_details.name.split(" ")[0],
last_name=shipping_details.name.split(" ")[1],
user_profile=profile,
email=billing_details.email,
phone_number=shipping_details.phone,
address_line1=shipping_details.address.line1,
address_line2=shipping_details.address.line2,
county=shipping_details.address.state,
eircode=shipping_details.address.postal_code,
city=shipping_details.address.city,
original_cart=cart,
stripe_pid=pid,
)
for item_id, item_data in json.loads(cart).items():
album = Album.objects.get(id=item_id)
order_line_item = OrderLineItem(
order=order,
product=album,
quantity=item_data,
)
order_line_item.save()
except Exception as e:
if order:
order.delete()
return HttpResponse(
content=f'Webhook received: {event["type"]} | ERROR: {e}',
status=500,
)
self._send_confirmation_email(order)
return HttpResponse(
content=f'Webhook received: {event["type"]} | SUCCESS: Created order in webhook',
status=200,
)
def handle_payment_intent_payment_failed(self, event):
"""
Handle the payment_intent.payment_failed webhook from Stripe
"""
return HttpResponse(content=f'Webhook received: {event["type"]}', status=200)
|
import json
from pathlib import (
Path,
)
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generator,
Iterable,
List,
Optional,
Tuple,
Type,
Union,
cast,
)
from eth_typing import (
URI,
Address,
ContractName,
Manifest,
)
from eth_utils import (
to_canonical_address,
to_dict,
to_text,
to_tuple,
)
from ethpm._utils.cache import (
cached_property,
)
from ethpm._utils.contract import (
generate_contract_factory_kwargs,
)
from ethpm._utils.deployments import (
get_linked_deployments,
normalize_linked_references,
validate_deployments_tx_receipt,
validate_linked_references,
)
from ethpm.contract import (
LinkableContract,
)
from ethpm.dependencies import (
Dependencies,
)
from ethpm.deployments import (
DeploymentData,
Deployments,
)
from ethpm.exceptions import (
BytecodeLinkingError,
EthPMValidationError,
FailureToFetchIPFSAssetsError,
InsufficientAssetsError,
PyEthPMError,
)
from ethpm.uri import (
resolve_uri_contents,
)
from ethpm.validation.manifest import (
check_for_deployments,
validate_build_dependencies_are_present,
validate_manifest_against_schema,
validate_manifest_deployments,
validate_raw_manifest_format,
)
from ethpm.validation.misc import (
validate_w3_instance,
)
from ethpm.validation.package import (
validate_build_dependency,
validate_contract_name,
validate_minimal_contract_factory_data,
)
from ethpm.validation.uri import (
validate_single_matching_uri,
)
from web3._utils.validation import (
validate_address,
)
from web3.eth import (
Contract,
)
if TYPE_CHECKING:
from web3 import Web3 # noqa: F401
class Package(object):
def __init__(
self, manifest: Dict[str, Any], w3: "Web3", uri: Optional[str] = None
) -> None:
"""
A package should be created using one of the available
classmethods and a valid w3 instance.
"""
if not isinstance(manifest, dict):
raise TypeError(
"Package object must be initialized with a dictionary. "
f"Got {type(manifest)}"
)
if "manifest" not in manifest or manifest["manifest"] != "ethpm/3":
raise EthPMValidationError(
"Py-Ethpm currently only supports v3 ethpm manifests. "
"Please use the CLI to update or re-generate a v3 manifest. "
)
validate_manifest_against_schema(manifest)
validate_manifest_deployments(manifest)
validate_w3_instance(w3)
self.w3 = w3
self.w3.eth.defaultContractFactory = cast(Type[Contract], LinkableContract)
self.manifest = manifest
self._uri = uri
def update_w3(self, w3: "Web3") -> "Package":
"""
Returns a new instance of `Package` containing the same manifest,
but connected to a different web3 instance.
.. doctest::
>>> new_w3 = Web3(Web3.EthereumTesterProvider())
>>> NewPackage = OwnedPackage.update_w3(new_w3)
>>> assert NewPackage.w3 == new_w3
>>> assert OwnedPackage.manifest == NewPackage.manifest
"""
validate_w3_instance(w3)
return Package(self.manifest, w3, self.uri)
def __repr__(self) -> str:
"""
String readable representation of the Package.
.. doctest::
>>> OwnedPackage.__repr__()
'<Package owned==1.0.0>'
"""
name = self.name
version = self.version
return f"<Package {name}=={version}>"
@property
def name(self) -> str:
"""
The name of this ``Package``.
.. doctest::
>>> OwnedPackage.name
'owned'
"""
return self.manifest["name"]
@property
def version(self) -> str:
"""
The package version of a ``Package``.
.. doctest::
>>> OwnedPackage.version
'1.0.0'
"""
return self.manifest["version"]
@property
def manifest_version(self) -> str:
"""
The manifest version of a ``Package``.
.. doctest::
>>> OwnedPackage.manifest_version
'ethpm/3'
"""
return self.manifest["manifest"]
@property
def uri(self) -> Optional[str]:
"""
The uri (local file_path / content-addressed URI) of a ``Package``'s manifest.
"""
return self._uri
@property
def contract_types(self) -> List[str]:
"""
All contract types included in this package.
"""
if 'contractTypes' in self.manifest:
return sorted(self.manifest['contractTypes'].keys())
else:
raise ValueError("No contract types found in manifest; {self.__repr__()}.")
@classmethod
def from_file(cls, file_path: Path, w3: "Web3") -> "Package":
"""
Returns a ``Package`` instantiated by a manifest located at the provided Path.
``file_path`` arg must be a ``pathlib.Path`` instance.
A valid ``Web3`` instance is required to instantiate a ``Package``.
"""
if isinstance(file_path, Path):
raw_manifest = file_path.read_text()
validate_raw_manifest_format(raw_manifest)
manifest = json.loads(raw_manifest)
else:
raise TypeError(
"The Package.from_file method expects a pathlib.Path instance."
f"Got {type(file_path)} instead."
)
return cls(manifest, w3, file_path.as_uri())
@classmethod
def from_uri(cls, uri: URI, w3: "Web3") -> "Package":
"""
Returns a Package object instantiated by a manifest located at a content-addressed URI.
A valid ``Web3`` instance is also required.
URI schemes supported:
- IPFS: `ipfs://Qm...`
- HTTP: `https://api.github.com/repos/:owner/:repo/git/blobs/:file_sha`
- Registry: `erc1319://registry.eth:1/greeter?version=1.0.0`
.. code:: python
OwnedPackage = Package.from_uri('ipfs://QmbeVyFLSuEUxiXKwSsEjef7icpdTdA4kGG9BcrJXKNKUW', w3) # noqa: E501
"""
contents = to_text(resolve_uri_contents(uri))
validate_raw_manifest_format(contents)
manifest = json.loads(contents)
return cls(manifest, w3, uri)
#
# Contracts
#
def get_contract_factory(self, name: ContractName) -> LinkableContract:
"""
Return the contract factory for a given contract type, generated from the data vailable
in ``Package.manifest``. Contract factories are accessible from the package class.
.. code:: python
Owned = OwnedPackage.get_contract_factory('owned')
In cases where a contract uses a library, the contract factory will have
unlinked bytecode. The ``ethpm`` package ships with its own subclass of
``web3.contract.Contract``, ``ethpm.contract.LinkableContract`` with a few extra
methods and properties related to bytecode linking.
.. code:: python
>>> math = owned_package.contract_factories.math
>>> math.needs_bytecode_linking
True
>>> linked_math = math.link_bytecode({'MathLib': '0x1234...'})
>>> linked_math.needs_bytecode_linking
False
"""
validate_contract_name(name)
if "contractTypes" not in self.manifest:
raise InsufficientAssetsError(
"This package does not contain any contract type data."
)
try:
contract_data = self.manifest["contractTypes"][name]
except KeyError:
raise InsufficientAssetsError(
"This package does not contain any package data to generate "
f"a contract factory for contract type: {name}. Available contract types include: "
f"{self.contract_types}."
)
validate_minimal_contract_factory_data(contract_data)
contract_kwargs = generate_contract_factory_kwargs(contract_data)
contract_factory = self.w3.eth.contract(**contract_kwargs)
return contract_factory
def get_contract_instance(self, name: ContractName, address: Address) -> Contract:
"""
Will return a ``Web3.contract`` instance generated from the contract type data available
in ``Package.manifest`` and the provided ``address``. The provided ``address`` must be
valid on the connected chain available through ``Package.w3``.
"""
validate_address(address)
validate_contract_name(name)
try:
self.manifest["contractTypes"][name]["abi"]
except KeyError:
raise InsufficientAssetsError(
"Package does not have the ABI required to generate a contract instance "
f"for contract: {name} at address: {address!r}."
)
contract_kwargs = generate_contract_factory_kwargs(
self.manifest["contractTypes"][name]
)
contract_instance = self.w3.eth.contract(
address=address, **contract_kwargs
)
# TODO: type ignore may be able to be removed after more of AsyncContract is finished
return contract_instance # type: ignore
#
# Build Dependencies
#
@cached_property
def build_dependencies(self) -> "Dependencies":
"""
Return `Dependencies` instance containing the build dependencies available on this Package.
The ``Package`` class should provide access to the full dependency tree.
.. code:: python
>>> owned_package.build_dependencies['zeppelin']
<ZeppelinPackage>
"""
validate_build_dependencies_are_present(self.manifest)
dependencies = self.manifest["buildDependencies"]
dependency_packages = {}
for name, uri in dependencies.items():
try:
validate_build_dependency(name, uri)
dependency_package = Package.from_uri(uri, self.w3)
except PyEthPMError as e:
raise FailureToFetchIPFSAssetsError(
f"Failed to retrieve build dependency: {name} from URI: {uri}.\n"
f"Got error: {e}."
)
else:
dependency_packages[name] = dependency_package
return Dependencies(dependency_packages)
#
# Deployments
#
@cached_property
def deployments(self) -> Union["Deployments", Dict[None, None]]:
"""
Returns a ``Deployments`` object containing all the deployment data and contract
instances of a ``Package``'s `contract_types`. Automatically filters deployments
to only expose those available on the current ``Package.w3`` instance.
.. code:: python
package.deployments.get_instance("ContractType")
"""
if not check_for_deployments(self.manifest):
return {}
all_blockchain_uris = self.manifest["deployments"].keys()
matching_uri = validate_single_matching_uri(all_blockchain_uris, self.w3)
deployments = self.manifest["deployments"][matching_uri]
all_contract_instances = self._get_all_contract_instances(deployments)
validate_deployments_tx_receipt(deployments, self.w3, allow_missing_data=True)
linked_deployments = get_linked_deployments(deployments)
if linked_deployments:
for deployment_data in linked_deployments.values():
on_chain_bytecode = self.w3.eth.get_code(
deployment_data["address"]
)
unresolved_linked_refs = normalize_linked_references(
deployment_data["runtimeBytecode"]["linkDependencies"]
)
resolved_linked_refs = tuple(
self._resolve_linked_references(link_ref, deployments)
for link_ref in unresolved_linked_refs
)
for linked_ref in resolved_linked_refs:
validate_linked_references(linked_ref, on_chain_bytecode)
return Deployments(deployments, all_contract_instances)
@to_dict
def _get_all_contract_instances(
self, deployments: Dict[str, DeploymentData]
) -> Iterable[Tuple[str, Contract]]:
for deployment_name, deployment_data in deployments.items():
if deployment_data['contractType'] not in self.contract_types:
raise EthPMValidationError(
f"Contract type: {deployment_data["contractType"]} for alias: "
f"{deployment_name} not found. Available contract types include: "
f"{self.contract_types}."
)
contract_instance = self.get_contract_instance(
ContractName(deployment_data['contractType']),
deployment_data['address'],
)
yield deployment_name, contract_instance
@to_tuple
def _resolve_linked_references(
self, link_ref: Tuple[int, str, str], deployments: Dict[str, Any]
) -> Generator[Tuple[int, bytes], None, None]:
# No nested deployment: i.e. 'Owned'
offset, link_type, value = link_ref
if link_type == "literal":
yield offset, to_canonical_address(value)
elif value in deployments:
yield offset, to_canonical_address(deployments[value]["address"])
# No nested deployment, but invalid ref
elif ":" not in value:
raise BytecodeLinkingError(
f"Contract instance reference: {value} not found in package's deployment data."
)
# Expects child pkg in build_dependencies
elif value.split(":")[0] not in self.build_dependencies:
raise BytecodeLinkingError(
f"Expected build dependency: {value.split(":")[0]} not found "
"in package's build dependencies."
)
# Find and return resolved, nested ref
else:
unresolved_linked_ref = value.split(":", 1)[-1]
build_dependency = self.build_dependencies[value.split(":")[0]]
yield build_dependency._resolve_link_dependencies(unresolved_linked_ref)
def format_manifest(manifest: Manifest, *, prettify: bool = None) -> str:
if prettify:
return json.dumps(manifest, sort_keys=True, indent=4)
return json.dumps(manifest, sort_keys=True, separators=(",", ":"))
| import json
from pathlib import (
Path,
)
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generator,
Iterable,
List,
Optional,
Tuple,
Type,
Union,
cast,
)
from eth_typing import (
URI,
Address,
ContractName,
Manifest,
)
from eth_utils import (
to_canonical_address,
to_dict,
to_text,
to_tuple,
)
from ethpm._utils.cache import (
cached_property,
)
from ethpm._utils.contract import (
generate_contract_factory_kwargs,
)
from ethpm._utils.deployments import (
get_linked_deployments,
normalize_linked_references,
validate_deployments_tx_receipt,
validate_linked_references,
)
from ethpm.contract import (
LinkableContract,
)
from ethpm.dependencies import (
Dependencies,
)
from ethpm.deployments import (
DeploymentData,
Deployments,
)
from ethpm.exceptions import (
BytecodeLinkingError,
EthPMValidationError,
FailureToFetchIPFSAssetsError,
InsufficientAssetsError,
PyEthPMError,
)
from ethpm.uri import (
resolve_uri_contents,
)
from ethpm.validation.manifest import (
check_for_deployments,
validate_build_dependencies_are_present,
validate_manifest_against_schema,
validate_manifest_deployments,
validate_raw_manifest_format,
)
from ethpm.validation.misc import (
validate_w3_instance,
)
from ethpm.validation.package import (
validate_build_dependency,
validate_contract_name,
validate_minimal_contract_factory_data,
)
from ethpm.validation.uri import (
validate_single_matching_uri,
)
from web3._utils.validation import (
validate_address,
)
from web3.eth import (
Contract,
)
if TYPE_CHECKING:
from web3 import Web3 # noqa: F401
class Package(object):
def __init__(
self, manifest: Dict[str, Any], w3: "Web3", uri: Optional[str] = None
) -> None:
"""
A package should be created using one of the available
classmethods and a valid w3 instance.
"""
if not isinstance(manifest, dict):
raise TypeError(
"Package object must be initialized with a dictionary. "
f"Got {type(manifest)}"
)
if "manifest" not in manifest or manifest["manifest"] != "ethpm/3":
raise EthPMValidationError(
"Py-Ethpm currently only supports v3 ethpm manifests. "
"Please use the CLI to update or re-generate a v3 manifest. "
)
validate_manifest_against_schema(manifest)
validate_manifest_deployments(manifest)
validate_w3_instance(w3)
self.w3 = w3
self.w3.eth.defaultContractFactory = cast(Type[Contract], LinkableContract)
self.manifest = manifest
self._uri = uri
def update_w3(self, w3: "Web3") -> "Package":
"""
Returns a new instance of `Package` containing the same manifest,
but connected to a different web3 instance.
.. doctest::
>>> new_w3 = Web3(Web3.EthereumTesterProvider())
>>> NewPackage = OwnedPackage.update_w3(new_w3)
>>> assert NewPackage.w3 == new_w3
>>> assert OwnedPackage.manifest == NewPackage.manifest
"""
validate_w3_instance(w3)
return Package(self.manifest, w3, self.uri)
def __repr__(self) -> str:
"""
String readable representation of the Package.
.. doctest::
>>> OwnedPackage.__repr__()
'<Package owned==1.0.0>'
"""
name = self.name
version = self.version
return f"<Package {name}=={version}>"
@property
def name(self) -> str:
"""
The name of this ``Package``.
.. doctest::
>>> OwnedPackage.name
'owned'
"""
return self.manifest["name"]
@property
def version(self) -> str:
"""
The package version of a ``Package``.
.. doctest::
>>> OwnedPackage.version
'1.0.0'
"""
return self.manifest["version"]
@property
def manifest_version(self) -> str:
"""
The manifest version of a ``Package``.
.. doctest::
>>> OwnedPackage.manifest_version
'ethpm/3'
"""
return self.manifest["manifest"]
@property
def uri(self) -> Optional[str]:
"""
The uri (local file_path / content-addressed URI) of a ``Package``'s manifest.
"""
return self._uri
@property
def contract_types(self) -> List[str]:
"""
All contract types included in this package.
"""
if 'contractTypes' in self.manifest:
return sorted(self.manifest['contractTypes'].keys())
else:
raise ValueError("No contract types found in manifest; {self.__repr__()}.")
@classmethod
def from_file(cls, file_path: Path, w3: "Web3") -> "Package":
"""
Returns a ``Package`` instantiated by a manifest located at the provided Path.
``file_path`` arg must be a ``pathlib.Path`` instance.
A valid ``Web3`` instance is required to instantiate a ``Package``.
"""
if isinstance(file_path, Path):
raw_manifest = file_path.read_text()
validate_raw_manifest_format(raw_manifest)
manifest = json.loads(raw_manifest)
else:
raise TypeError(
"The Package.from_file method expects a pathlib.Path instance."
f"Got {type(file_path)} instead."
)
return cls(manifest, w3, file_path.as_uri())
@classmethod
def from_uri(cls, uri: URI, w3: "Web3") -> "Package":
"""
Returns a Package object instantiated by a manifest located at a content-addressed URI.
A valid ``Web3`` instance is also required.
URI schemes supported:
- IPFS: `ipfs://Qm...`
- HTTP: `https://api.github.com/repos/:owner/:repo/git/blobs/:file_sha`
- Registry: `erc1319://registry.eth:1/greeter?version=1.0.0`
.. code:: python
OwnedPackage = Package.from_uri('ipfs://QmbeVyFLSuEUxiXKwSsEjef7icpdTdA4kGG9BcrJXKNKUW', w3) # noqa: E501
"""
contents = to_text(resolve_uri_contents(uri))
validate_raw_manifest_format(contents)
manifest = json.loads(contents)
return cls(manifest, w3, uri)
#
# Contracts
#
def get_contract_factory(self, name: ContractName) -> LinkableContract:
"""
Return the contract factory for a given contract type, generated from the data vailable
in ``Package.manifest``. Contract factories are accessible from the package class.
.. code:: python
Owned = OwnedPackage.get_contract_factory('owned')
In cases where a contract uses a library, the contract factory will have
unlinked bytecode. The ``ethpm`` package ships with its own subclass of
``web3.contract.Contract``, ``ethpm.contract.LinkableContract`` with a few extra
methods and properties related to bytecode linking.
.. code:: python
>>> math = owned_package.contract_factories.math
>>> math.needs_bytecode_linking
True
>>> linked_math = math.link_bytecode({'MathLib': '0x1234...'})
>>> linked_math.needs_bytecode_linking
False
"""
validate_contract_name(name)
if "contractTypes" not in self.manifest:
raise InsufficientAssetsError(
"This package does not contain any contract type data."
)
try:
contract_data = self.manifest["contractTypes"][name]
except KeyError:
raise InsufficientAssetsError(
"This package does not contain any package data to generate "
f"a contract factory for contract type: {name}. Available contract types include: "
f"{self.contract_types}."
)
validate_minimal_contract_factory_data(contract_data)
contract_kwargs = generate_contract_factory_kwargs(contract_data)
contract_factory = self.w3.eth.contract(**contract_kwargs)
return contract_factory
def get_contract_instance(self, name: ContractName, address: Address) -> Contract:
"""
Will return a ``Web3.contract`` instance generated from the contract type data available
in ``Package.manifest`` and the provided ``address``. The provided ``address`` must be
valid on the connected chain available through ``Package.w3``.
"""
validate_address(address)
validate_contract_name(name)
try:
self.manifest["contractTypes"][name]["abi"]
except KeyError:
raise InsufficientAssetsError(
"Package does not have the ABI required to generate a contract instance "
f"for contract: {name} at address: {address!r}."
)
contract_kwargs = generate_contract_factory_kwargs(
self.manifest["contractTypes"][name]
)
contract_instance = self.w3.eth.contract(
address=address, **contract_kwargs
)
# TODO: type ignore may be able to be removed after more of AsyncContract is finished
return contract_instance # type: ignore
#
# Build Dependencies
#
@cached_property
def build_dependencies(self) -> "Dependencies":
"""
Return `Dependencies` instance containing the build dependencies available on this Package.
The ``Package`` class should provide access to the full dependency tree.
.. code:: python
>>> owned_package.build_dependencies['zeppelin']
<ZeppelinPackage>
"""
validate_build_dependencies_are_present(self.manifest)
dependencies = self.manifest["buildDependencies"]
dependency_packages = {}
for name, uri in dependencies.items():
try:
validate_build_dependency(name, uri)
dependency_package = Package.from_uri(uri, self.w3)
except PyEthPMError as e:
raise FailureToFetchIPFSAssetsError(
f"Failed to retrieve build dependency: {name} from URI: {uri}.\n"
f"Got error: {e}."
)
else:
dependency_packages[name] = dependency_package
return Dependencies(dependency_packages)
#
# Deployments
#
@cached_property
def deployments(self) -> Union["Deployments", Dict[None, None]]:
"""
Returns a ``Deployments`` object containing all the deployment data and contract
instances of a ``Package``'s `contract_types`. Automatically filters deployments
to only expose those available on the current ``Package.w3`` instance.
.. code:: python
package.deployments.get_instance("ContractType")
"""
if not check_for_deployments(self.manifest):
return {}
all_blockchain_uris = self.manifest["deployments"].keys()
matching_uri = validate_single_matching_uri(all_blockchain_uris, self.w3)
deployments = self.manifest["deployments"][matching_uri]
all_contract_instances = self._get_all_contract_instances(deployments)
validate_deployments_tx_receipt(deployments, self.w3, allow_missing_data=True)
linked_deployments = get_linked_deployments(deployments)
if linked_deployments:
for deployment_data in linked_deployments.values():
on_chain_bytecode = self.w3.eth.get_code(
deployment_data["address"]
)
unresolved_linked_refs = normalize_linked_references(
deployment_data["runtimeBytecode"]["linkDependencies"]
)
resolved_linked_refs = tuple(
self._resolve_linked_references(link_ref, deployments)
for link_ref in unresolved_linked_refs
)
for linked_ref in resolved_linked_refs:
validate_linked_references(linked_ref, on_chain_bytecode)
return Deployments(deployments, all_contract_instances)
@to_dict
def _get_all_contract_instances(
self, deployments: Dict[str, DeploymentData]
) -> Iterable[Tuple[str, Contract]]:
for deployment_name, deployment_data in deployments.items():
if deployment_data['contractType'] not in self.contract_types:
raise EthPMValidationError(
f"Contract type: {deployment_data['contractType']} for alias: "
f"{deployment_name} not found. Available contract types include: "
f"{self.contract_types}."
)
contract_instance = self.get_contract_instance(
ContractName(deployment_data['contractType']),
deployment_data['address'],
)
yield deployment_name, contract_instance
@to_tuple
def _resolve_linked_references(
self, link_ref: Tuple[int, str, str], deployments: Dict[str, Any]
) -> Generator[Tuple[int, bytes], None, None]:
# No nested deployment: i.e. 'Owned'
offset, link_type, value = link_ref
if link_type == "literal":
yield offset, to_canonical_address(value)
elif value in deployments:
yield offset, to_canonical_address(deployments[value]["address"])
# No nested deployment, but invalid ref
elif ":" not in value:
raise BytecodeLinkingError(
f"Contract instance reference: {value} not found in package's deployment data."
)
# Expects child pkg in build_dependencies
elif value.split(":")[0] not in self.build_dependencies:
raise BytecodeLinkingError(
f"Expected build dependency: {value.split(':')[0]} not found "
"in package's build dependencies."
)
# Find and return resolved, nested ref
else:
unresolved_linked_ref = value.split(":", 1)[-1]
build_dependency = self.build_dependencies[value.split(":")[0]]
yield build_dependency._resolve_link_dependencies(unresolved_linked_ref)
def format_manifest(manifest: Manifest, *, prettify: bool = None) -> str:
if prettify:
return json.dumps(manifest, sort_keys=True, indent=4)
return json.dumps(manifest, sort_keys=True, separators=(",", ":"))
|
import textwrap
import jikanpy
import requests
def getPosterLink(mal):
# grab poster from kitsu
kitsu = getKitsu(mal)
image = requests.get(f'https://kitsu.io/api/edge/anime/{kitsu}').json()
return image['data']['attributes']['posterImage']['original']
def getKitsu(mal):
# get kitsu id from mal id
link = f'https://kitsu.io/api/edge/mappings?filter[external_site]=myanimelist/anime&filter[external_id]={mal}'
result = requests.get(link).json()['data'][0]['id']
link = f'https://kitsu.io/api/edge/mappings/{result}/item?fields[anime]=slug'
kitsu = requests.get(link).json()['data']['id']
return kitsu
def getBannerLink(mal, kitsu_search=True):
# try getting kitsu backdrop
if kitsu_search:
kitsu = getKitsu(mal)
image = f'http://media.kitsu.io/anime/cover_images/{kitsu}/original.jpg'
response = requests.get(image)
if response.status_code == 200:
return image
# try getting anilist banner
query = """
query ($idMal: Int){
Media(idMal: $idMal){
bannerImage
}
}
"""
data = {'query': query, 'variables': {'idMal': int(mal)}}
image = requests.post('https://graphql.anilist.co', json=data).json()['data']['Media']['bannerImage']
if image:
return image
return getPosterLink(mal)
def get_anime_manga(mal_id, search_type, _user_id):
jikan = jikanpy.jikan.Jikan()
if search_type == "anime_anime":
result = jikan.anime(mal_id)
image = getBannerLink(mal_id)
studio_string = ', '.join(studio_info['name'] for studio_info in result['studios'])
producer_string = ', '.join(producer_info['name'] for producer_info in result['producers'])
elif search_type == "anime_manga":
result = jikan.manga(mal_id)
image = result['image_url']
caption = f"<a href=\'{result["url"]}\'>{result["title"]}</a>"
if result['title_japanese']:
caption += f" ({result["title_japanese"]})\n"
else:
caption += "\n"
alternative_names = []
if result['title_english'] is not None:
alternative_names.append(result['title_english'])
alternative_names.extend(result['title_synonyms'])
if alternative_names:
alternative_names_string = ", ".join(alternative_names)
caption += f"\n<b>Also known as</b>: <code>{alternative_names_string}</code>"
genre_string = ', '.join(genre_info['name'] for genre_info in result['genres'])
if result['synopsis'] is not None:
synopsis = result['synopsis'].split(" ", 60)
try:
synopsis.pop(60)
except IndexError:
pass
synopsis_string = ' '.join(synopsis) + "..."
else:
synopsis_string = "Unknown"
for entity in result:
if result[entity] is None:
result[entity] = "Unknown"
if search_type == "anime_anime":
caption += textwrap.dedent(f"""
<b>Type</b>: <code>{result['type']}</code>
<b>Status</b>: <code>{result['status']}</code>
<b>Aired</b>: <code>{result['aired']['string']}</code>
<b>Episodes</b>: <code>{result['episodes']}</code>
<b>Score</b>: <code>{result['score']}</code>
<b>Premiered</b>: <code>{result['premiered']}</code>
<b>Duration</b>: <code>{result['duration']}</code>
<b>Genres</b>: <code>{genre_string}</code>
<b>Studios</b>: <code>{studio_string}</code>
<b>Producers</b>: <code>{producer_string}</code>
📖 <b>Synopsis</b>: {synopsis_string} <a href='{result['url']}'>read more</a>
<i>Search an encode on..</i>
""")
elif search_type == "anime_manga":
caption += textwrap.dedent(f"""
<b>Type</b>: <code>{result['type']}</code>
<b>Status</b>: <code>{result['status']}</code>
<b>Volumes</b>: <code>{result['volumes']}</code>
<b>Chapters</b>: <code>{result['chapters']}</code>
<b>Score</b>: <code>{result['score']}</code>
<b>Genres</b>: <code>{genre_string}</code>
📖 <b>Synopsis</b>: {synopsis_string}
""")
return caption, image | import textwrap
import jikanpy
import requests
def getPosterLink(mal):
# grab poster from kitsu
kitsu = getKitsu(mal)
image = requests.get(f'https://kitsu.io/api/edge/anime/{kitsu}').json()
return image['data']['attributes']['posterImage']['original']
def getKitsu(mal):
# get kitsu id from mal id
link = f'https://kitsu.io/api/edge/mappings?filter[external_site]=myanimelist/anime&filter[external_id]={mal}'
result = requests.get(link).json()['data'][0]['id']
link = f'https://kitsu.io/api/edge/mappings/{result}/item?fields[anime]=slug'
kitsu = requests.get(link).json()['data']['id']
return kitsu
def getBannerLink(mal, kitsu_search=True):
# try getting kitsu backdrop
if kitsu_search:
kitsu = getKitsu(mal)
image = f'http://media.kitsu.io/anime/cover_images/{kitsu}/original.jpg'
response = requests.get(image)
if response.status_code == 200:
return image
# try getting anilist banner
query = """
query ($idMal: Int){
Media(idMal: $idMal){
bannerImage
}
}
"""
data = {'query': query, 'variables': {'idMal': int(mal)}}
image = requests.post('https://graphql.anilist.co', json=data).json()['data']['Media']['bannerImage']
if image:
return image
return getPosterLink(mal)
def get_anime_manga(mal_id, search_type, _user_id):
jikan = jikanpy.jikan.Jikan()
if search_type == "anime_anime":
result = jikan.anime(mal_id)
image = getBannerLink(mal_id)
studio_string = ', '.join(studio_info['name'] for studio_info in result['studios'])
producer_string = ', '.join(producer_info['name'] for producer_info in result['producers'])
elif search_type == "anime_manga":
result = jikan.manga(mal_id)
image = result['image_url']
caption = f"<a href=\'{result['url']}\'>{result['title']}</a>"
if result['title_japanese']:
caption += f" ({result['title_japanese']})\n"
else:
caption += "\n"
alternative_names = []
if result['title_english'] is not None:
alternative_names.append(result['title_english'])
alternative_names.extend(result['title_synonyms'])
if alternative_names:
alternative_names_string = ", ".join(alternative_names)
caption += f"\n<b>Also known as</b>: <code>{alternative_names_string}</code>"
genre_string = ', '.join(genre_info['name'] for genre_info in result['genres'])
if result['synopsis'] is not None:
synopsis = result['synopsis'].split(" ", 60)
try:
synopsis.pop(60)
except IndexError:
pass
synopsis_string = ' '.join(synopsis) + "..."
else:
synopsis_string = "Unknown"
for entity in result:
if result[entity] is None:
result[entity] = "Unknown"
if search_type == "anime_anime":
caption += textwrap.dedent(f"""
<b>Type</b>: <code>{result['type']}</code>
<b>Status</b>: <code>{result['status']}</code>
<b>Aired</b>: <code>{result['aired']['string']}</code>
<b>Episodes</b>: <code>{result['episodes']}</code>
<b>Score</b>: <code>{result['score']}</code>
<b>Premiered</b>: <code>{result['premiered']}</code>
<b>Duration</b>: <code>{result['duration']}</code>
<b>Genres</b>: <code>{genre_string}</code>
<b>Studios</b>: <code>{studio_string}</code>
<b>Producers</b>: <code>{producer_string}</code>
📖 <b>Synopsis</b>: {synopsis_string} <a href='{result['url']}'>read more</a>
<i>Search an encode on..</i>
""")
elif search_type == "anime_manga":
caption += textwrap.dedent(f"""
<b>Type</b>: <code>{result['type']}</code>
<b>Status</b>: <code>{result['status']}</code>
<b>Volumes</b>: <code>{result['volumes']}</code>
<b>Chapters</b>: <code>{result['chapters']}</code>
<b>Score</b>: <code>{result['score']}</code>
<b>Genres</b>: <code>{genre_string}</code>
📖 <b>Synopsis</b>: {synopsis_string}
""")
return caption, image |
#
# This file is part of LiteX.
#
# Copyright (c) 2020 Florent Kermarrec <florent@enjoy-digital.fr>
# Copyright (c) 2020 Dolu1990 <charles.papon.90@gmail.com>
# SPDX-License-Identifier: BSD-2-Clause
import os
from os import path
from migen import *
from litex import get_data_mod
from litex.soc.interconnect import wishbone
from litex.soc.interconnect.csr import *
from litex.soc.cores.cpu import CPU, CPU_GCC_TRIPLE_RISCV32
import os
class Open(Signal): pass
# Variants -----------------------------------------------------------------------------------------
CPU_VARIANTS = {
"standard": "VexRiscv",
"linux": "VexRiscv", # Similar to standard.
}
# VexRiscv SMP -------------------------------------------------------------------------------------
class VexRiscvSMP(CPU):
name = "vexriscv"
human_name = "VexRiscv SMP"
variants = CPU_VARIANTS
data_width = 32
endianness = "little"
gcc_triple = CPU_GCC_TRIPLE_RISCV32
linker_output_format = "elf32-littleriscv"
nop = "nop"
io_regions = {0x80000000: 0x80000000} # Origin, Length.
# Default parameters.
cpu_count = 1
dcache_size = 4096
icache_size = 4096
dcache_ways = 1
icache_ways = 1
coherent_dma = False
litedram_width = 32
dcache_width = 32
icache_width = 32
aes_instruction = False
out_of_order_decoder = True
wishbone_memory = False
with_fpu = False
cpu_per_fpu = 4
with_rvc = False
dtlb_size = 4
itlb_size = 4
# Command line configuration arguments.
@staticmethod
def args_fill(parser):
parser.add_argument("--cpu-count", default=1, help="Number of CPU(s) in the cluster.", type=int)
parser.add_argument("--with-coherent-dma", action="store_true", help="Enable Coherent DMA Slave interface.")
parser.add_argument("--without-coherent-dma", action="store_true", help="Disable Coherent DMA Slave interface.")
parser.add_argument("--dcache-width", default=None, help="L1 data cache bus width.")
parser.add_argument("--icache-width", default=None, help="L1 instruction cache bus width.")
parser.add_argument("--dcache-size", default=None, help="L1 data cache size in byte per CPU.")
parser.add_argument("--dcache-ways", default=None, help="L1 data cache ways per CPU.")
parser.add_argument("--icache-size", default=None, help="L1 instruction cache size in byte per CPU.")
parser.add_argument("--icache-ways", default=None, help="L1 instruction cache ways per CPU")
parser.add_argument("--aes-instruction", default=None, help="Enable AES instruction acceleration.")
parser.add_argument("--without-out-of-order-decoder", action="store_true", help="Reduce area at cost of peripheral access speed")
parser.add_argument("--with-wishbone-memory" , action="store_true", help="Disable native LiteDRAM interface")
parser.add_argument("--with-fpu" , action="store_true", help="Enable the F32/F64 FPU")
parser.add_argument("--cpu-per-fpu" , default="4", help="Maximal ratio between CPU count and FPU count. Will instanciate as many FPU as necessary.")
parser.add_argument("--with-rvc" , action="store_true", help="Enable RISC-V compressed instruction support")
parser.add_argument("--dtlb-size", default=4, help="Data TLB size.")
parser.add_argument("--itlb-size", default=4, help="Instruction TLB size.")
@staticmethod
def args_read(args):
VexRiscvSMP.cpu_count = args.cpu_count
if int(args.cpu_count) != 1:
VexRiscvSMP.icache_width = 64
VexRiscvSMP.dcache_width = 64
VexRiscvSMP.dcache_size = 8192
VexRiscvSMP.icache_size = 8192
VexRiscvSMP.dcache_ways = 2
VexRiscvSMP.icache_ways = 2
VexRiscvSMP.coherent_dma = True
if(args.with_coherent_dma): VexRiscvSMP.coherent_dma = bool(True)
if(args.without_coherent_dma): VexRiscvSMP.coherent_dma = bool(False)
if(args.dcache_width): VexRiscvSMP.dcache_width = int(args.dcache_width)
if(args.icache_width): VexRiscvSMP.icache_width = int(args.icache_width)
if(args.dcache_size): VexRiscvSMP.dcache_size = int(args.dcache_size)
if(args.icache_size): VexRiscvSMP.icache_size = int(args.icache_size)
if(args.dcache_ways): VexRiscvSMP.dcache_ways = int(args.dcache_ways)
if(args.icache_ways): VexRiscvSMP.icache_ways = int(args.icache_ways)
if(args.aes_instruction): VexRiscvSMP.aes_instruction = bool(args.aes_instruction)
if(args.without_out_of_order_decoder): VexRiscvSMP.out_of_order_decoder = False
if(args.with_wishbone_memory): VexRiscvSMP.wishbone_memory = True
if(args.with_fpu):
VexRiscvSMP.with_fpu = True
VexRiscvSMP.icache_width = 64
VexRiscvSMP.dcache_width = 64 # Required for F64
if(args.cpu_per_fpu):
VexRiscvSMP.cpu_per_fpu = args.cpu_per_fpu
if(args.with_rvc):
VexRiscvSMP.with_rvc = True
if(args.dtlb_size): VexRiscvSMP.dtlb_size = int(args.dtlb_size)
if(args.itlb_size): VexRiscvSMP.itlb_size = int(args.itlb_size)
# ABI.
@staticmethod
def get_abi():
abi = "ilp32"
if VexRiscvSMP.with_fpu:
abi +="d"
return abi
# Arch.
@staticmethod
def get_arch():
arch = "rv32ima"
if VexRiscvSMP.with_fpu:
arch += "fd"
if VexRiscvSMP.with_rvc:
arch += "c"
return arch
# Memory Mapping.
@property
def mem_map(self):
return {
"rom": 0x00000000,
"sram": 0x10000000,
"main_ram": 0x40000000,
"csr": 0xf0000000,
"clint": 0xf0010000,
"plic": 0xf0c00000,
}
# GCC Flags.
@property
def gcc_flags(self):
flags = f" -march={VexRiscvSMP.get_arch()} -mabi={VexRiscvSMP.get_abi()}"
flags += f" -D__vexriscv__"
flags += f" -DUART_POLLING"
return flags
# Cluster Name Generation.
@staticmethod
def generate_cluster_name():
ldw = f"Ldw{VexRiscvSMP.litedram_width}"
VexRiscvSMP.cluster_name = f"VexRiscvLitexSmpCluster_" \
f"Cc{VexRiscvSMP.cpu_count}" \
"_" \
f"Iw{VexRiscvSMP.icache_width}" \
f"Is{VexRiscvSMP.icache_size}" \
f"Iy{VexRiscvSMP.icache_ways}" \
"_" \
f"Dw{VexRiscvSMP.dcache_width}" \
f"Ds{VexRiscvSMP.dcache_size}" \
f"Dy{VexRiscvSMP.dcache_ways}" \
"_" \
f"ITs{VexRiscvSMP.itlb_size}" \
f"DTs{VexRiscvSMP.dtlb_size}" \
f"{"_"+ldw if not VexRiscvSMP.wishbone_memory else ""}" \
f"{"_Cdma" if VexRiscvSMP.coherent_dma else ""}" \
f"{"_Aes" if VexRiscvSMP.aes_instruction else ""}" \
f"{"_Ood" if VexRiscvSMP.out_of_order_decoder else ""}" \
f"{"_Wm" if VexRiscvSMP.wishbone_memory else ""}" \
f"{"_Fpu" + str(VexRiscvSMP.cpu_per_fpu) if VexRiscvSMP.with_fpu else ""}" \
f"{"_Rvc" if VexRiscvSMP.with_rvc else ""}"
# Default Configs Generation.
@staticmethod
def generate_default_configs():
# Single cores.
for data_width in [16, 32, 64, 128]:
VexRiscvSMP.litedram_width = data_width
VexRiscvSMP.icache_width = 32
VexRiscvSMP.dcache_width = 32
VexRiscvSMP.coherent_dma = False
VexRiscvSMP.cpu_count = 1
# Low cache amount.
VexRiscvSMP.dcache_size = 4096
VexRiscvSMP.icache_size = 4096
VexRiscvSMP.dcache_ways = 1
VexRiscvSMP.icache_ways = 1
# Without DMA.
VexRiscvSMP.coherent_dma = False
VexRiscvSMP.generate_cluster_name()
VexRiscvSMP.generate_netlist()
# With DMA.
VexRiscvSMP.coherent_dma = True
VexRiscvSMP.generate_cluster_name()
VexRiscvSMP.generate_netlist()
# High cache amount.
VexRiscvSMP.dcache_size = 8192
VexRiscvSMP.icache_size = 8192
VexRiscvSMP.dcache_ways = 2
VexRiscvSMP.icache_ways = 2
VexRiscvSMP.icache_width = 32 if data_width < 64 else 64
VexRiscvSMP.dcache_width = 32 if data_width < 64 else 64
# Without DMA.
VexRiscvSMP.coherent_dma = False
VexRiscvSMP.generate_cluster_name()
VexRiscvSMP.generate_netlist()
# With DMA.
VexRiscvSMP.coherent_dma = True
VexRiscvSMP.generate_cluster_name()
VexRiscvSMP.generate_netlist()
# Multi cores.
for core_count in [2,4]:
VexRiscvSMP.litedram_width = 128
VexRiscvSMP.icache_width = 64
VexRiscvSMP.dcache_width = 64
VexRiscvSMP.dcache_size = 8192
VexRiscvSMP.icache_size = 8192
VexRiscvSMP.dcache_ways = 2
VexRiscvSMP.icache_ways = 2
VexRiscvSMP.coherent_dma = True
VexRiscvSMP.cpu_count = core_count
VexRiscvSMP.generate_cluster_name()
VexRiscvSMP.generate_netlist()
# Netlist Generation.
@staticmethod
def generate_netlist():
print(f"Generating cluster netlist")
vdir = get_data_mod("cpu", "vexriscv_smp").data_location
gen_args = []
if(VexRiscvSMP.coherent_dma):
gen_args.append("--coherent-dma")
gen_args.append(f"--cpu-count={VexRiscvSMP.cpu_count}")
gen_args.append(f"--ibus-width={VexRiscvSMP.icache_width}")
gen_args.append(f"--dbus-width={VexRiscvSMP.dcache_width}")
gen_args.append(f"--dcache-size={VexRiscvSMP.dcache_size}")
gen_args.append(f"--icache-size={VexRiscvSMP.icache_size}")
gen_args.append(f"--dcache-ways={VexRiscvSMP.dcache_ways}")
gen_args.append(f"--icache-ways={VexRiscvSMP.icache_ways}")
gen_args.append(f"--litedram-width={VexRiscvSMP.litedram_width}")
gen_args.append(f"--aes-instruction={VexRiscvSMP.aes_instruction}")
gen_args.append(f"--out-of-order-decoder={VexRiscvSMP.out_of_order_decoder}")
gen_args.append(f"--wishbone-memory={VexRiscvSMP.wishbone_memory}")
gen_args.append(f"--fpu={VexRiscvSMP.with_fpu}")
gen_args.append(f"--cpu-per-fpu={VexRiscvSMP.cpu_per_fpu}")
gen_args.append(f"--rvc={VexRiscvSMP.with_rvc}")
gen_args.append(f"--netlist-name={VexRiscvSMP.cluster_name}")
gen_args.append(f"--netlist-directory={vdir}")
gen_args.append(f"--dtlb-size={VexRiscvSMP.dtlb_size}")
gen_args.append(f"--itlb-size={VexRiscvSMP.itlb_size}")
cmd = 'cd {path} && sbt "runMain vexriscv.demo.smp.VexRiscvLitexSmpClusterCmdGen {args}"'.format(path=os.path.join(vdir, "ext", "VexRiscv"), args=" ".join(gen_args))
if os.system(cmd) != 0:
raise OSError('Failed to run sbt')
def __init__(self, platform, variant):
self.platform = platform
self.variant = "standard"
self.human_name = self.human_name + "-" + variant.upper()
self.reset = Signal()
self.jtag_clk = Signal()
self.jtag_enable = Signal()
self.jtag_capture = Signal()
self.jtag_shift = Signal()
self.jtag_update = Signal()
self.jtag_reset = Signal()
self.jtag_tdo = Signal()
self.jtag_tdi = Signal()
self.interrupt = Signal(32)
self.pbus = pbus = wishbone.Interface()
self.periph_buses = [pbus] # Peripheral buses (Connected to main SoC's bus).
self.memory_buses = [] # Memory buses (Connected directly to LiteDRAM).
# # #
self.cpu_params = dict(
# Clk / Rst.
i_debugCd_external_clk = ClockSignal(),
i_debugCd_external_reset = ResetSignal() | self.reset,
# Interrupts.
i_interrupts = self.interrupt,
# JTAG.
i_jtag_clk = self.jtag_clk,
i_debugPort_enable = self.jtag_enable,
i_debugPort_capture = self.jtag_capture,
i_debugPort_shift = self.jtag_shift,
i_debugPort_update = self.jtag_update,
i_debugPort_reset = self.jtag_reset,
i_debugPort_tdi = self.jtag_tdi,
o_debugPort_tdo = self.jtag_tdo,
# Peripheral Bus (Master).
o_peripheral_CYC = pbus.cyc,
o_peripheral_STB = pbus.stb,
i_peripheral_ACK = pbus.ack,
o_peripheral_WE = pbus.we,
o_peripheral_ADR = pbus.adr,
i_peripheral_DAT_MISO = pbus.dat_r,
o_peripheral_DAT_MOSI = pbus.dat_w,
o_peripheral_SEL = pbus.sel,
i_peripheral_ERR = pbus.err,
o_peripheral_CTI = pbus.cti,
o_peripheral_BTE = pbus.bte
)
if VexRiscvSMP.coherent_dma:
self.dma_bus = dma_bus = wishbone.Interface(data_width=VexRiscvSMP.dcache_width)
dma_bus_stall = Signal()
dma_bus_inhibit = Signal()
self.cpu_params.update(
# DMA Bus (Slave).
i_dma_wishbone_CYC = dma_bus.cyc,
i_dma_wishbone_STB = dma_bus.stb & ~dma_bus_inhibit,
o_dma_wishbone_ACK = dma_bus.ack,
i_dma_wishbone_WE = dma_bus.we,
i_dma_wishbone_SEL = dma_bus.sel,
i_dma_wishbone_ADR = dma_bus.adr,
o_dma_wishbone_DAT_MISO = dma_bus.dat_r,
i_dma_wishbone_DAT_MOSI = dma_bus.dat_w,
o_dma_wishbone_STALL = dma_bus_stall
)
self.sync += [
If(dma_bus.stb & dma_bus.cyc & ~dma_bus_stall,
dma_bus_inhibit.eq(1),
),
If(dma_bus.ack,
dma_bus_inhibit.eq(0)
)
]
def set_reset_address(self, reset_address):
assert not hasattr(self, "reset_address")
self.reset_address = reset_address
assert reset_address == 0x00000000
def add_sources(self, platform):
vdir = get_data_mod("cpu", "vexriscv_smp").data_location
print(f"VexRiscv cluster : {self.cluster_name}")
if not path.exists(os.path.join(vdir, self.cluster_name + ".v")):
self.generate_netlist()
# Add RAM.
# By default, use Generic RAM implementation.
ram_filename = "Ram_1w_1rs_Generic.v"
# On Altera/Intel platforms, use specific implementation.
from litex.build.altera import AlteraPlatform
if isinstance(platform, AlteraPlatform):
ram_filename = "Ram_1w_1rs_Intel.v"
platform.add_source(os.path.join(vdir, ram_filename), "verilog")
# Add Cluster.
platform.add_source(os.path.join(vdir, self.cluster_name + ".v"), "verilog")
def add_soc_components(self, soc, soc_region_cls):
# Define number of CPUs
soc.add_config("CPU_COUNT", VexRiscvSMP.cpu_count)
soc.add_constant("CPU_ISA", VexRiscvSMP.get_arch())
# Constants for cache so we can add them in the DTS.
if (VexRiscvSMP.dcache_size > 0):
soc.add_constant("cpu_dcache_size", VexRiscvSMP.dcache_size)
soc.add_constant("cpu_dcache_ways", VexRiscvSMP.dcache_ways)
soc.add_constant("cpu_dcache_block_size", 64) # hardwired?
if (VexRiscvSMP.icache_size > 0):
soc.add_constant("cpu_icache_size", VexRiscvSMP.icache_size)
soc.add_constant("cpu_icache_ways", VexRiscvSMP.icache_ways)
soc.add_constant("cpu_icache_block_size", 64) # hardwired?
# Constants for TLB so we can add them in the DTS
# full associative so only the size is described.
if (VexRiscvSMP.dtlb_size > 0):
soc.add_constant("cpu_dtlb_size", VexRiscvSMP.dtlb_size)
soc.add_constant("cpu_dtlb_ways", VexRiscvSMP.dtlb_size)
if (VexRiscvSMP.itlb_size > 0):
soc.add_constant("cpu_itlb_size", VexRiscvSMP.itlb_size)
soc.add_constant("cpu_itlb_ways", VexRiscvSMP.itlb_size)
# Add PLIC as Bus Slave
self.plicbus = plicbus = wishbone.Interface()
self.cpu_params.update(
i_plicWishbone_CYC = plicbus.cyc,
i_plicWishbone_STB = plicbus.stb,
o_plicWishbone_ACK = plicbus.ack,
i_plicWishbone_WE = plicbus.we,
i_plicWishbone_ADR = plicbus.adr,
o_plicWishbone_DAT_MISO = plicbus.dat_r,
i_plicWishbone_DAT_MOSI = plicbus.dat_w
)
soc.bus.add_slave("plic", self.plicbus, region=soc_region_cls(origin=soc.mem_map.get("plic"), size=0x400000, cached=False))
# Add CLINT as Bus Slave
self.clintbus = clintbus = wishbone.Interface()
self.cpu_params.update(
i_clintWishbone_CYC = clintbus.cyc,
i_clintWishbone_STB = clintbus.stb,
o_clintWishbone_ACK = clintbus.ack,
i_clintWishbone_WE = clintbus.we,
i_clintWishbone_ADR = clintbus.adr,
o_clintWishbone_DAT_MISO = clintbus.dat_r,
i_clintWishbone_DAT_MOSI = clintbus.dat_w,
)
soc.bus.add_slave("clint", clintbus, region=soc_region_cls(origin=soc.mem_map.get("clint"), size=0x10000, cached=False))
def add_memory_buses(self, address_width, data_width):
VexRiscvSMP.litedram_width = data_width
VexRiscvSMP.generate_cluster_name()
from litedram.common import LiteDRAMNativePort
if(not VexRiscvSMP.wishbone_memory):
ibus = LiteDRAMNativePort(mode="both", address_width=32, data_width=VexRiscvSMP.litedram_width)
dbus = LiteDRAMNativePort(mode="both", address_width=32, data_width=VexRiscvSMP.litedram_width)
self.memory_buses.append(ibus)
self.memory_buses.append(dbus)
self.cpu_params.update(
# Instruction Memory Bus (Master).
o_iBridge_dram_cmd_valid = ibus.cmd.valid,
i_iBridge_dram_cmd_ready = ibus.cmd.ready,
o_iBridge_dram_cmd_payload_we = ibus.cmd.we,
o_iBridge_dram_cmd_payload_addr = ibus.cmd.addr,
o_iBridge_dram_wdata_valid = ibus.wdata.valid,
i_iBridge_dram_wdata_ready = ibus.wdata.ready,
o_iBridge_dram_wdata_payload_data = ibus.wdata.data,
o_iBridge_dram_wdata_payload_we = ibus.wdata.we,
i_iBridge_dram_rdata_valid = ibus.rdata.valid,
o_iBridge_dram_rdata_ready = ibus.rdata.ready,
i_iBridge_dram_rdata_payload_data = ibus.rdata.data,
# Data Memory Bus (Master).
o_dBridge_dram_cmd_valid = dbus.cmd.valid,
i_dBridge_dram_cmd_ready = dbus.cmd.ready,
o_dBridge_dram_cmd_payload_we = dbus.cmd.we,
o_dBridge_dram_cmd_payload_addr = dbus.cmd.addr,
o_dBridge_dram_wdata_valid = dbus.wdata.valid,
i_dBridge_dram_wdata_ready = dbus.wdata.ready,
o_dBridge_dram_wdata_payload_data = dbus.wdata.data,
o_dBridge_dram_wdata_payload_we = dbus.wdata.we,
i_dBridge_dram_rdata_valid = dbus.rdata.valid,
o_dBridge_dram_rdata_ready = dbus.rdata.ready,
i_dBridge_dram_rdata_payload_data = dbus.rdata.data,
)
def do_finalize(self):
assert hasattr(self, "reset_address")
self.specials += Instance(self.cluster_name, **self.cpu_params)
# Add Verilog sources
self.add_sources(self.platform)
| #
# This file is part of LiteX.
#
# Copyright (c) 2020 Florent Kermarrec <florent@enjoy-digital.fr>
# Copyright (c) 2020 Dolu1990 <charles.papon.90@gmail.com>
# SPDX-License-Identifier: BSD-2-Clause
import os
from os import path
from migen import *
from litex import get_data_mod
from litex.soc.interconnect import wishbone
from litex.soc.interconnect.csr import *
from litex.soc.cores.cpu import CPU, CPU_GCC_TRIPLE_RISCV32
import os
class Open(Signal): pass
# Variants -----------------------------------------------------------------------------------------
CPU_VARIANTS = {
"standard": "VexRiscv",
"linux": "VexRiscv", # Similar to standard.
}
# VexRiscv SMP -------------------------------------------------------------------------------------
class VexRiscvSMP(CPU):
name = "vexriscv"
human_name = "VexRiscv SMP"
variants = CPU_VARIANTS
data_width = 32
endianness = "little"
gcc_triple = CPU_GCC_TRIPLE_RISCV32
linker_output_format = "elf32-littleriscv"
nop = "nop"
io_regions = {0x80000000: 0x80000000} # Origin, Length.
# Default parameters.
cpu_count = 1
dcache_size = 4096
icache_size = 4096
dcache_ways = 1
icache_ways = 1
coherent_dma = False
litedram_width = 32
dcache_width = 32
icache_width = 32
aes_instruction = False
out_of_order_decoder = True
wishbone_memory = False
with_fpu = False
cpu_per_fpu = 4
with_rvc = False
dtlb_size = 4
itlb_size = 4
# Command line configuration arguments.
@staticmethod
def args_fill(parser):
parser.add_argument("--cpu-count", default=1, help="Number of CPU(s) in the cluster.", type=int)
parser.add_argument("--with-coherent-dma", action="store_true", help="Enable Coherent DMA Slave interface.")
parser.add_argument("--without-coherent-dma", action="store_true", help="Disable Coherent DMA Slave interface.")
parser.add_argument("--dcache-width", default=None, help="L1 data cache bus width.")
parser.add_argument("--icache-width", default=None, help="L1 instruction cache bus width.")
parser.add_argument("--dcache-size", default=None, help="L1 data cache size in byte per CPU.")
parser.add_argument("--dcache-ways", default=None, help="L1 data cache ways per CPU.")
parser.add_argument("--icache-size", default=None, help="L1 instruction cache size in byte per CPU.")
parser.add_argument("--icache-ways", default=None, help="L1 instruction cache ways per CPU")
parser.add_argument("--aes-instruction", default=None, help="Enable AES instruction acceleration.")
parser.add_argument("--without-out-of-order-decoder", action="store_true", help="Reduce area at cost of peripheral access speed")
parser.add_argument("--with-wishbone-memory" , action="store_true", help="Disable native LiteDRAM interface")
parser.add_argument("--with-fpu" , action="store_true", help="Enable the F32/F64 FPU")
parser.add_argument("--cpu-per-fpu" , default="4", help="Maximal ratio between CPU count and FPU count. Will instanciate as many FPU as necessary.")
parser.add_argument("--with-rvc" , action="store_true", help="Enable RISC-V compressed instruction support")
parser.add_argument("--dtlb-size", default=4, help="Data TLB size.")
parser.add_argument("--itlb-size", default=4, help="Instruction TLB size.")
@staticmethod
def args_read(args):
VexRiscvSMP.cpu_count = args.cpu_count
if int(args.cpu_count) != 1:
VexRiscvSMP.icache_width = 64
VexRiscvSMP.dcache_width = 64
VexRiscvSMP.dcache_size = 8192
VexRiscvSMP.icache_size = 8192
VexRiscvSMP.dcache_ways = 2
VexRiscvSMP.icache_ways = 2
VexRiscvSMP.coherent_dma = True
if(args.with_coherent_dma): VexRiscvSMP.coherent_dma = bool(True)
if(args.without_coherent_dma): VexRiscvSMP.coherent_dma = bool(False)
if(args.dcache_width): VexRiscvSMP.dcache_width = int(args.dcache_width)
if(args.icache_width): VexRiscvSMP.icache_width = int(args.icache_width)
if(args.dcache_size): VexRiscvSMP.dcache_size = int(args.dcache_size)
if(args.icache_size): VexRiscvSMP.icache_size = int(args.icache_size)
if(args.dcache_ways): VexRiscvSMP.dcache_ways = int(args.dcache_ways)
if(args.icache_ways): VexRiscvSMP.icache_ways = int(args.icache_ways)
if(args.aes_instruction): VexRiscvSMP.aes_instruction = bool(args.aes_instruction)
if(args.without_out_of_order_decoder): VexRiscvSMP.out_of_order_decoder = False
if(args.with_wishbone_memory): VexRiscvSMP.wishbone_memory = True
if(args.with_fpu):
VexRiscvSMP.with_fpu = True
VexRiscvSMP.icache_width = 64
VexRiscvSMP.dcache_width = 64 # Required for F64
if(args.cpu_per_fpu):
VexRiscvSMP.cpu_per_fpu = args.cpu_per_fpu
if(args.with_rvc):
VexRiscvSMP.with_rvc = True
if(args.dtlb_size): VexRiscvSMP.dtlb_size = int(args.dtlb_size)
if(args.itlb_size): VexRiscvSMP.itlb_size = int(args.itlb_size)
# ABI.
@staticmethod
def get_abi():
abi = "ilp32"
if VexRiscvSMP.with_fpu:
abi +="d"
return abi
# Arch.
@staticmethod
def get_arch():
arch = "rv32ima"
if VexRiscvSMP.with_fpu:
arch += "fd"
if VexRiscvSMP.with_rvc:
arch += "c"
return arch
# Memory Mapping.
@property
def mem_map(self):
return {
"rom": 0x00000000,
"sram": 0x10000000,
"main_ram": 0x40000000,
"csr": 0xf0000000,
"clint": 0xf0010000,
"plic": 0xf0c00000,
}
# GCC Flags.
@property
def gcc_flags(self):
flags = f" -march={VexRiscvSMP.get_arch()} -mabi={VexRiscvSMP.get_abi()}"
flags += f" -D__vexriscv__"
flags += f" -DUART_POLLING"
return flags
# Cluster Name Generation.
@staticmethod
def generate_cluster_name():
ldw = f"Ldw{VexRiscvSMP.litedram_width}"
VexRiscvSMP.cluster_name = f"VexRiscvLitexSmpCluster_" \
f"Cc{VexRiscvSMP.cpu_count}" \
"_" \
f"Iw{VexRiscvSMP.icache_width}" \
f"Is{VexRiscvSMP.icache_size}" \
f"Iy{VexRiscvSMP.icache_ways}" \
"_" \
f"Dw{VexRiscvSMP.dcache_width}" \
f"Ds{VexRiscvSMP.dcache_size}" \
f"Dy{VexRiscvSMP.dcache_ways}" \
"_" \
f"ITs{VexRiscvSMP.itlb_size}" \
f"DTs{VexRiscvSMP.dtlb_size}" \
f"{'_'+ldw if not VexRiscvSMP.wishbone_memory else ''}" \
f"{'_Cdma' if VexRiscvSMP.coherent_dma else ''}" \
f"{'_Aes' if VexRiscvSMP.aes_instruction else ''}" \
f"{'_Ood' if VexRiscvSMP.out_of_order_decoder else ''}" \
f"{'_Wm' if VexRiscvSMP.wishbone_memory else ''}" \
f"{'_Fpu' + str(VexRiscvSMP.cpu_per_fpu) if VexRiscvSMP.with_fpu else ''}" \
f"{'_Rvc' if VexRiscvSMP.with_rvc else ''}"
# Default Configs Generation.
@staticmethod
def generate_default_configs():
# Single cores.
for data_width in [16, 32, 64, 128]:
VexRiscvSMP.litedram_width = data_width
VexRiscvSMP.icache_width = 32
VexRiscvSMP.dcache_width = 32
VexRiscvSMP.coherent_dma = False
VexRiscvSMP.cpu_count = 1
# Low cache amount.
VexRiscvSMP.dcache_size = 4096
VexRiscvSMP.icache_size = 4096
VexRiscvSMP.dcache_ways = 1
VexRiscvSMP.icache_ways = 1
# Without DMA.
VexRiscvSMP.coherent_dma = False
VexRiscvSMP.generate_cluster_name()
VexRiscvSMP.generate_netlist()
# With DMA.
VexRiscvSMP.coherent_dma = True
VexRiscvSMP.generate_cluster_name()
VexRiscvSMP.generate_netlist()
# High cache amount.
VexRiscvSMP.dcache_size = 8192
VexRiscvSMP.icache_size = 8192
VexRiscvSMP.dcache_ways = 2
VexRiscvSMP.icache_ways = 2
VexRiscvSMP.icache_width = 32 if data_width < 64 else 64
VexRiscvSMP.dcache_width = 32 if data_width < 64 else 64
# Without DMA.
VexRiscvSMP.coherent_dma = False
VexRiscvSMP.generate_cluster_name()
VexRiscvSMP.generate_netlist()
# With DMA.
VexRiscvSMP.coherent_dma = True
VexRiscvSMP.generate_cluster_name()
VexRiscvSMP.generate_netlist()
# Multi cores.
for core_count in [2,4]:
VexRiscvSMP.litedram_width = 128
VexRiscvSMP.icache_width = 64
VexRiscvSMP.dcache_width = 64
VexRiscvSMP.dcache_size = 8192
VexRiscvSMP.icache_size = 8192
VexRiscvSMP.dcache_ways = 2
VexRiscvSMP.icache_ways = 2
VexRiscvSMP.coherent_dma = True
VexRiscvSMP.cpu_count = core_count
VexRiscvSMP.generate_cluster_name()
VexRiscvSMP.generate_netlist()
# Netlist Generation.
@staticmethod
def generate_netlist():
print(f"Generating cluster netlist")
vdir = get_data_mod("cpu", "vexriscv_smp").data_location
gen_args = []
if(VexRiscvSMP.coherent_dma):
gen_args.append("--coherent-dma")
gen_args.append(f"--cpu-count={VexRiscvSMP.cpu_count}")
gen_args.append(f"--ibus-width={VexRiscvSMP.icache_width}")
gen_args.append(f"--dbus-width={VexRiscvSMP.dcache_width}")
gen_args.append(f"--dcache-size={VexRiscvSMP.dcache_size}")
gen_args.append(f"--icache-size={VexRiscvSMP.icache_size}")
gen_args.append(f"--dcache-ways={VexRiscvSMP.dcache_ways}")
gen_args.append(f"--icache-ways={VexRiscvSMP.icache_ways}")
gen_args.append(f"--litedram-width={VexRiscvSMP.litedram_width}")
gen_args.append(f"--aes-instruction={VexRiscvSMP.aes_instruction}")
gen_args.append(f"--out-of-order-decoder={VexRiscvSMP.out_of_order_decoder}")
gen_args.append(f"--wishbone-memory={VexRiscvSMP.wishbone_memory}")
gen_args.append(f"--fpu={VexRiscvSMP.with_fpu}")
gen_args.append(f"--cpu-per-fpu={VexRiscvSMP.cpu_per_fpu}")
gen_args.append(f"--rvc={VexRiscvSMP.with_rvc}")
gen_args.append(f"--netlist-name={VexRiscvSMP.cluster_name}")
gen_args.append(f"--netlist-directory={vdir}")
gen_args.append(f"--dtlb-size={VexRiscvSMP.dtlb_size}")
gen_args.append(f"--itlb-size={VexRiscvSMP.itlb_size}")
cmd = 'cd {path} && sbt "runMain vexriscv.demo.smp.VexRiscvLitexSmpClusterCmdGen {args}"'.format(path=os.path.join(vdir, "ext", "VexRiscv"), args=" ".join(gen_args))
if os.system(cmd) != 0:
raise OSError('Failed to run sbt')
def __init__(self, platform, variant):
self.platform = platform
self.variant = "standard"
self.human_name = self.human_name + "-" + variant.upper()
self.reset = Signal()
self.jtag_clk = Signal()
self.jtag_enable = Signal()
self.jtag_capture = Signal()
self.jtag_shift = Signal()
self.jtag_update = Signal()
self.jtag_reset = Signal()
self.jtag_tdo = Signal()
self.jtag_tdi = Signal()
self.interrupt = Signal(32)
self.pbus = pbus = wishbone.Interface()
self.periph_buses = [pbus] # Peripheral buses (Connected to main SoC's bus).
self.memory_buses = [] # Memory buses (Connected directly to LiteDRAM).
# # #
self.cpu_params = dict(
# Clk / Rst.
i_debugCd_external_clk = ClockSignal(),
i_debugCd_external_reset = ResetSignal() | self.reset,
# Interrupts.
i_interrupts = self.interrupt,
# JTAG.
i_jtag_clk = self.jtag_clk,
i_debugPort_enable = self.jtag_enable,
i_debugPort_capture = self.jtag_capture,
i_debugPort_shift = self.jtag_shift,
i_debugPort_update = self.jtag_update,
i_debugPort_reset = self.jtag_reset,
i_debugPort_tdi = self.jtag_tdi,
o_debugPort_tdo = self.jtag_tdo,
# Peripheral Bus (Master).
o_peripheral_CYC = pbus.cyc,
o_peripheral_STB = pbus.stb,
i_peripheral_ACK = pbus.ack,
o_peripheral_WE = pbus.we,
o_peripheral_ADR = pbus.adr,
i_peripheral_DAT_MISO = pbus.dat_r,
o_peripheral_DAT_MOSI = pbus.dat_w,
o_peripheral_SEL = pbus.sel,
i_peripheral_ERR = pbus.err,
o_peripheral_CTI = pbus.cti,
o_peripheral_BTE = pbus.bte
)
if VexRiscvSMP.coherent_dma:
self.dma_bus = dma_bus = wishbone.Interface(data_width=VexRiscvSMP.dcache_width)
dma_bus_stall = Signal()
dma_bus_inhibit = Signal()
self.cpu_params.update(
# DMA Bus (Slave).
i_dma_wishbone_CYC = dma_bus.cyc,
i_dma_wishbone_STB = dma_bus.stb & ~dma_bus_inhibit,
o_dma_wishbone_ACK = dma_bus.ack,
i_dma_wishbone_WE = dma_bus.we,
i_dma_wishbone_SEL = dma_bus.sel,
i_dma_wishbone_ADR = dma_bus.adr,
o_dma_wishbone_DAT_MISO = dma_bus.dat_r,
i_dma_wishbone_DAT_MOSI = dma_bus.dat_w,
o_dma_wishbone_STALL = dma_bus_stall
)
self.sync += [
If(dma_bus.stb & dma_bus.cyc & ~dma_bus_stall,
dma_bus_inhibit.eq(1),
),
If(dma_bus.ack,
dma_bus_inhibit.eq(0)
)
]
def set_reset_address(self, reset_address):
assert not hasattr(self, "reset_address")
self.reset_address = reset_address
assert reset_address == 0x00000000
def add_sources(self, platform):
vdir = get_data_mod("cpu", "vexriscv_smp").data_location
print(f"VexRiscv cluster : {self.cluster_name}")
if not path.exists(os.path.join(vdir, self.cluster_name + ".v")):
self.generate_netlist()
# Add RAM.
# By default, use Generic RAM implementation.
ram_filename = "Ram_1w_1rs_Generic.v"
# On Altera/Intel platforms, use specific implementation.
from litex.build.altera import AlteraPlatform
if isinstance(platform, AlteraPlatform):
ram_filename = "Ram_1w_1rs_Intel.v"
platform.add_source(os.path.join(vdir, ram_filename), "verilog")
# Add Cluster.
platform.add_source(os.path.join(vdir, self.cluster_name + ".v"), "verilog")
def add_soc_components(self, soc, soc_region_cls):
# Define number of CPUs
soc.add_config("CPU_COUNT", VexRiscvSMP.cpu_count)
soc.add_constant("CPU_ISA", VexRiscvSMP.get_arch())
# Constants for cache so we can add them in the DTS.
if (VexRiscvSMP.dcache_size > 0):
soc.add_constant("cpu_dcache_size", VexRiscvSMP.dcache_size)
soc.add_constant("cpu_dcache_ways", VexRiscvSMP.dcache_ways)
soc.add_constant("cpu_dcache_block_size", 64) # hardwired?
if (VexRiscvSMP.icache_size > 0):
soc.add_constant("cpu_icache_size", VexRiscvSMP.icache_size)
soc.add_constant("cpu_icache_ways", VexRiscvSMP.icache_ways)
soc.add_constant("cpu_icache_block_size", 64) # hardwired?
# Constants for TLB so we can add them in the DTS
# full associative so only the size is described.
if (VexRiscvSMP.dtlb_size > 0):
soc.add_constant("cpu_dtlb_size", VexRiscvSMP.dtlb_size)
soc.add_constant("cpu_dtlb_ways", VexRiscvSMP.dtlb_size)
if (VexRiscvSMP.itlb_size > 0):
soc.add_constant("cpu_itlb_size", VexRiscvSMP.itlb_size)
soc.add_constant("cpu_itlb_ways", VexRiscvSMP.itlb_size)
# Add PLIC as Bus Slave
self.plicbus = plicbus = wishbone.Interface()
self.cpu_params.update(
i_plicWishbone_CYC = plicbus.cyc,
i_plicWishbone_STB = plicbus.stb,
o_plicWishbone_ACK = plicbus.ack,
i_plicWishbone_WE = plicbus.we,
i_plicWishbone_ADR = plicbus.adr,
o_plicWishbone_DAT_MISO = plicbus.dat_r,
i_plicWishbone_DAT_MOSI = plicbus.dat_w
)
soc.bus.add_slave("plic", self.plicbus, region=soc_region_cls(origin=soc.mem_map.get("plic"), size=0x400000, cached=False))
# Add CLINT as Bus Slave
self.clintbus = clintbus = wishbone.Interface()
self.cpu_params.update(
i_clintWishbone_CYC = clintbus.cyc,
i_clintWishbone_STB = clintbus.stb,
o_clintWishbone_ACK = clintbus.ack,
i_clintWishbone_WE = clintbus.we,
i_clintWishbone_ADR = clintbus.adr,
o_clintWishbone_DAT_MISO = clintbus.dat_r,
i_clintWishbone_DAT_MOSI = clintbus.dat_w,
)
soc.bus.add_slave("clint", clintbus, region=soc_region_cls(origin=soc.mem_map.get("clint"), size=0x10000, cached=False))
def add_memory_buses(self, address_width, data_width):
VexRiscvSMP.litedram_width = data_width
VexRiscvSMP.generate_cluster_name()
from litedram.common import LiteDRAMNativePort
if(not VexRiscvSMP.wishbone_memory):
ibus = LiteDRAMNativePort(mode="both", address_width=32, data_width=VexRiscvSMP.litedram_width)
dbus = LiteDRAMNativePort(mode="both", address_width=32, data_width=VexRiscvSMP.litedram_width)
self.memory_buses.append(ibus)
self.memory_buses.append(dbus)
self.cpu_params.update(
# Instruction Memory Bus (Master).
o_iBridge_dram_cmd_valid = ibus.cmd.valid,
i_iBridge_dram_cmd_ready = ibus.cmd.ready,
o_iBridge_dram_cmd_payload_we = ibus.cmd.we,
o_iBridge_dram_cmd_payload_addr = ibus.cmd.addr,
o_iBridge_dram_wdata_valid = ibus.wdata.valid,
i_iBridge_dram_wdata_ready = ibus.wdata.ready,
o_iBridge_dram_wdata_payload_data = ibus.wdata.data,
o_iBridge_dram_wdata_payload_we = ibus.wdata.we,
i_iBridge_dram_rdata_valid = ibus.rdata.valid,
o_iBridge_dram_rdata_ready = ibus.rdata.ready,
i_iBridge_dram_rdata_payload_data = ibus.rdata.data,
# Data Memory Bus (Master).
o_dBridge_dram_cmd_valid = dbus.cmd.valid,
i_dBridge_dram_cmd_ready = dbus.cmd.ready,
o_dBridge_dram_cmd_payload_we = dbus.cmd.we,
o_dBridge_dram_cmd_payload_addr = dbus.cmd.addr,
o_dBridge_dram_wdata_valid = dbus.wdata.valid,
i_dBridge_dram_wdata_ready = dbus.wdata.ready,
o_dBridge_dram_wdata_payload_data = dbus.wdata.data,
o_dBridge_dram_wdata_payload_we = dbus.wdata.we,
i_dBridge_dram_rdata_valid = dbus.rdata.valid,
o_dBridge_dram_rdata_ready = dbus.rdata.ready,
i_dBridge_dram_rdata_payload_data = dbus.rdata.data,
)
def do_finalize(self):
assert hasattr(self, "reset_address")
self.specials += Instance(self.cluster_name, **self.cpu_params)
# Add Verilog sources
self.add_sources(self.platform)
|
""""""
from typing import Callable, Dict, List
import pytz
from datetime import datetime
from time import sleep
from ..api import (
MdApi,
TdApi,
USTP_FTDC_AF_Delete,
USTP_FTDC_CAS_Accepted,
USTP_FTDC_CAS_Rejected,
USTP_FTDC_CAS_Submitted,
USTP_FTDC_CHF_Speculation,
USTP_FTDC_D_Buy,
USTP_FTDC_D_Sell,
USTP_FTDC_FCR_NotForceClose,
USTP_FTDC_OF_Close,
USTP_FTDC_OF_CloseToday,
USTP_FTDC_OF_CloseYesterday,
USTP_FTDC_OF_Open,
USTP_FTDC_OPT_AnyPrice,
USTP_FTDC_OPT_LimitPrice,
USTP_FTDC_OS_AllTraded,
USTP_FTDC_OS_Canceled,
USTP_FTDC_OS_NoTradeQueueing,
USTP_FTDC_OS_PartTradedQueueing,
USTP_FTDC_OT_CallOptions,
USTP_FTDC_OT_PutOptions,
USTP_FTDC_TC_GFD,
USTP_FTDC_TC_IOC,
USTP_FTDC_VC_AV,
USTP_FTDC_VC_CV
)
from vnpy.event.engine import EventEngine
from vnpy.trader.constant import (
Direction,
Exchange,
Offset,
OptionType,
OrderType,
Status,
Product
)
from vnpy.trader.event import EVENT_TIMER
from vnpy.trader.gateway import BaseGateway
from vnpy.trader.object import (
AccountData,
CancelRequest,
ContractData,
OrderData,
OrderRequest,
PositionData,
SubscribeRequest,
TickData,
TradeData,
)
from vnpy.trader.utility import get_folder_path
STATUS_FEMAS2VT = {
USTP_FTDC_CAS_Submitted: Status.SUBMITTING,
USTP_FTDC_CAS_Accepted: Status.SUBMITTING,
USTP_FTDC_CAS_Rejected: Status.REJECTED,
USTP_FTDC_OS_NoTradeQueueing: Status.NOTTRADED,
USTP_FTDC_OS_PartTradedQueueing: Status.PARTTRADED,
USTP_FTDC_OS_AllTraded: Status.ALLTRADED,
USTP_FTDC_OS_Canceled: Status.CANCELLED,
}
DIRECTION_VT2FEMAS = {
Direction.LONG: USTP_FTDC_D_Buy,
Direction.SHORT: USTP_FTDC_D_Sell,
}
DIRECTION_FEMAS2VT = {v: k for k, v in DIRECTION_VT2FEMAS.items()}
ORDERTYPE_VT2FEMAS = {
OrderType.LIMIT: USTP_FTDC_OPT_LimitPrice,
OrderType.MARKET: USTP_FTDC_OPT_AnyPrice,
}
OFFSET_VT2FEMAS = {
Offset.OPEN: USTP_FTDC_OF_Open,
Offset.CLOSE: USTP_FTDC_OF_Close,
Offset.CLOSETODAY: USTP_FTDC_OF_CloseYesterday,
Offset.CLOSEYESTERDAY: USTP_FTDC_OF_CloseToday,
}
OFFSET_FEMAS2VT = {v: k for k, v in OFFSET_VT2FEMAS.items()}
EXCHANGE_FEMAS2VT = {
"CFFEX": Exchange.CFFEX,
"SHFE": Exchange.SHFE,
"CZCE": Exchange.CZCE,
"DCE": Exchange.DCE,
"INE": Exchange.INE,
}
OPTIONTYPE_FEMAS2VT = {
USTP_FTDC_OT_CallOptions: OptionType.CALL,
USTP_FTDC_OT_PutOptions: OptionType.PUT,
}
CHINA_TZ = pytz.timezone("Asia/Shanghai")
symbol_contract_map: Dict[str, ContractData] = {}
class FemasGateway(BaseGateway):
"""
VeighNa用于连接飞马柜台的接口
"""
default_name: str = "FEMAS"
default_setting: dict = {
"用户名": "",
"密码": "",
"经纪商代码": "",
"交易服务器": "",
"行情服务器": "",
"产品名称": "",
"授权编码": "",
}
exchanges: List[str] = list(EXCHANGE_FEMAS2VT.values())
def __init__(self, event_engine: EventEngine, gateway_name: str) -> None:
"""构造函数"""
super().__init__(event_engine, gateway_name)
self.td_api: FemasTdApi = FemasTdApi(self)
self.md_api: FemasTdApi = FemasMdApi(self)
def connect(self, setting: dict) -> None:
"""连接交易接口"""
userid: str = setting["用户名"]
password: str = setting["密码"]
brokerid: str = setting["经纪商代码"]
td_address: str = setting["交易服务器"]
md_address: str = setting["行情服务器"]
if not td_address.startswith("tcp://"):
td_address = "tcp://" + td_address
if not md_address.startswith("tcp://"):
md_address = "tcp://" + md_address
appid: str = setting["产品名称"]
auth_code: str = setting["授权编码"]
self.td_api.connect(td_address, userid, password, brokerid, auth_code, appid)
self.md_api.connect(md_address, userid, password, brokerid)
self.init_query()
def subscribe(self, req: SubscribeRequest) -> None:
"""订阅行情"""
self.md_api.subscribe(req)
def send_order(self, req: OrderRequest) -> None:
"""委托下单"""
return self.td_api.send_order(req)
def cancel_order(self, req: CancelRequest) -> None:
"""委托撤单"""
self.td_api.cancel_order(req)
def query_account(self) -> None:
"""查询资金"""
self.td_api.query_account()
def query_position(self) -> None:
"""查询持仓"""
self.td_api.query_position()
def close(self) -> None:
"""关闭接口"""
self.td_api.close()
self.md_api.close()
def write_error(self, msg: str, error: dict) -> None:
"""输出错误信息日志"""
error_id: str = error["ErrorID"]
error_msg: str = error["ErrorMsg"]
msg: str = f"{msg},代码:{error_id},信息:{error_msg}"
self.write_log(msg)
def process_timer_event(self, event) -> None:
"""定时事件处理"""
self.count += 1
if self.count < 2:
return
self.count = 0
func: Callable = self.query_functions.pop(0)
func()
self.query_functions.append(func)
def init_query(self) -> None:
"""初始化查询任务"""
self.count: int = 0
self.query_functions: List[Callable] = [self.query_account, self.query_position]
self.event_engine.register(EVENT_TIMER, self.process_timer_event)
class FemasMdApi(MdApi):
""""""
def __init__(self, gateway: FemasGateway) -> None:
"""构造函数"""
super(FemasMdApi, self).__init__()
self.gateway: FemasGateway = gateway
self.gateway_name: str = gateway.gateway_name
self.reqid: int = 0
self.connect_status: bool = False
self.login_status: bool = False
self.auth_staus: bool = False
self.login_failed: bool = False
self.subscribed: List[str] = set()
self.userid: str = ""
self.password: str = ""
self.brokerid: int = 0
def onFrontConnected(self) -> None:
"""服务器连接成功回报"""
self.gateway.write_log("行情服务器连接成功")
self.login()
def onFrontDisconnected(self, reason: int) -> None:
"""服务器连接断开回报"""
self.login_status = False
self.gateway.write_log(f"行情服务器连接断开,原因{reason}")
def onRspUserLogin(self, data: dict, error: dict, reqid: int, last: bool) -> None:
"""用户登录请求回报"""
if not error["ErrorID"]:
self.login_status = True
self.gateway.write_log("行情服务器登录成功")
for symbol in self.subscribed:
self.subMarketData(symbol)
else:
self.gateway.write_error("行情服务器登录失败", error)
def onRspError(self, error: dict, reqid: int, last: bool) -> None:
"""请求报错回报"""
self.gateway.write_error("行情接口报错", error)
def onRspSubMarketData(self, data: dict, error: dict, reqid: int, last: bool) -> None:
"""订阅行情回报"""
if not error or not error["ErrorID"]:
return
self.gateway.write_error("行情订阅失败", error)
def onRtnDepthMarketData(self, data: dict) -> None:
"""行情数据推送"""
symbol: str = data["InstrumentID"]
contract: ContractData = symbol_contract_map.get(symbol, None)
if not contract:
return
timestamp: str = f"{data["TradingDay"]} {data["UpdateTime"]}.{int(data["UpdateMillisec"] / 100)}"
dt: datetime = datetime.strptime(timestamp, "%Y%m%d %H:%M:%S.%f")
dt = CHINA_TZ.localize(dt)
tick: TickData = TickData(
symbol=symbol,
exchange=contract.exchange,
datetime=dt,
name=contract.name,
volume=data["Volume"],
last_price=data["LastPrice"],
limit_up=data["UpperLimitPrice"],
limit_down=data["LowerLimitPrice"],
open_price=data["OpenPrice"],
high_price=data["HighestPrice"],
low_price=data["LowestPrice"],
pre_close=data["PreClosePrice"],
bid_price_1=data["BidPrice1"],
ask_price_1=data["AskPrice1"],
bid_volume_1=data["BidVolume1"],
ask_volume_1=data["AskVolume1"],
gateway_name=self.gateway_name,
)
self.gateway.on_tick(tick)
def connect(self, address: str, userid: str, password: str, brokerid: int) -> None:
"""连接服务器"""
self.userid = userid
self.password = password
self.brokerid = brokerid
# 禁止重复发起连接,会导致异常崩溃
if not self.connect_status:
path = get_folder_path(self.gateway_name.lower())
self.createFtdcMdApi((str(path) + "\\Md").encode("GBK"))
self.subscribeMarketDataTopic(100, 2)
self.registerFront(address)
self.init()
self.connect_status = True
# 如果已经连接过了,直接登录
elif not self.login_status:
self.login()
def login(self) -> None:
"""用户登录"""
req: dict = {
"UserID": self.userid,
"Password": self.password,
"BrokerID": self.brokerid,
}
self.reqid += 1
self.reqUserLogin(req, self.reqid)
def subscribe(self, req: SubscribeRequest) -> None:
"""订阅行情"""
if self.login_status:
self.subMarketData(req.symbol)
self.subscribed.add(req.symbol)
def close(self) -> None:
"""关闭连接"""
if self.connect_status:
self.exit()
class FemasTdApi(TdApi):
""""""
def __init__(self, gateway: FemasGateway):
"""构造函数"""
super(FemasTdApi, self).__init__()
self.gateway: FemasGateway = gateway
self.gateway_name: str = gateway.gateway_name
self.reqid: int = 0
self.localid: int = int(10e5 + 8888)
self.connect_status: bool = False
self.login_status: bool = False
self.login_failed: bool = False
self.login_status: bool = False
self.userid: str = ""
self.investorid: str = ""
self.password: str = ""
self.brokerid: int = 0
self.auth_code: str = ""
self.appid: str = ""
self.positions: dict = {}
self.tradeids: List[str] = set()
def onFrontConnected(self) -> None:
"""服务器连接成功回报"""
self.gateway.write_log("交易服务器连接成功")
if self.auth_code:
self.authenticate()
else:
self.login()
def onFrontDisconnected(self, reason: int) -> None:
"""服务器连接断开回报"""
self.login_status = False
self.gateway.write_log(f"交易服务器连接断开,原因{reason}")
def onRspDSUserCertification(self, data: dict, error: dict, reqid: int, last: bool) -> None:
"""用户授权验证回报"""
if not error["ErrorID"]:
self.auth_staus = True
self.gateway.write_log("交易服务器授权验证成功")
self.login()
else:
self.gateway.write_error("交易服务器授权验证失败", error)
def onRspUserLogin(self, data: dict, error: dict, reqid: int, last: bool) -> None:
"""用户登录请求回报"""
if not error["ErrorID"]:
if data["MaxOrderLocalID"]:
self.localid = int(data["MaxOrderLocalID"])
self.login_status = True
self.gateway.write_log("交易服务器登录成功")
self.query_investor()
else:
self.login_failed = True
self.gateway.write_error("交易服务器登录失败", error)
def onRspQryUserInvestor(self, data: dict, error: dict, reqid: int, last: bool) -> None:
"""委托查询投资者代码回报"""
self.investorid = data['InvestorID']
self.gateway.write_log("投资者代码查询成功")
sleep(1) # 由于流量控制,需要等待1秒钟
self.reqid += 1
self.reqQryInstrument({}, self.reqid)
def onRspOrderInsert(self, data: dict, error: dict, reqid: int, last: bool) -> None:
"""委托下单失败回报"""
if not error["ErrorID"]:
return
orderid:str = data["UserOrderLocalID"]
symbol: str = data["InstrumentID"]
contract: ContractData = symbol_contract_map[symbol]
order: OrderData = OrderData(
symbol=symbol,
exchange=contract.exchange,
orderid=orderid,
direction=DIRECTION_FEMAS2VT[data["Direction"]],
offset=OFFSET_FEMAS2VT[data["OffsetFlag"]],
price=data["LimitPrice"],
volume=data["Volume"],
status=Status.REJECTED,
gateway_name=self.gateway_name,
)
self.gateway.on_order(order)
self.gateway.write_error("交易委托失败", error)
def onRspOrderAction(self, data: dict, error: dict, reqid: int, last: bool) -> None:
"""委托撤单失败回报"""
if not error["ErrorID"]:
return
self.gateway.write_error("交易撤单失败", error)
def onRspQueryMaxOrderVolume(self, data: dict, error: dict, reqid: int, last: bool) -> None:
""""""
pass
def onRspSettlementInfoConfirm(
self, data: dict, error: dict, reqid: int, last: bool
) -> None:
"""确认结算单回报"""
self.gateway.write_log("结算信息确认成功")
self.reqid += 1
self.reqQryInstrument({}, self.reqid)
def onRspQryInvestorPosition(self, data: dict, error: dict, reqid: int, last: bool) -> None:
"""持仓查询回报"""
if not data:
return
# 必须收到了合约信息后才能处理
symbol: str = data["InstrumentID"]
contract: ContractData = symbol_contract_map.get(symbol, None)
if contract:
# 获取之前缓存的持仓数据缓存
key: str = f"{data["InstrumentID"], data["Direction"]}"
position: PositionData = self.positions.get(key, None)
if not position:
position = PositionData(
symbol=data["InstrumentID"],
exchange=contract.exchange,
direction=DIRECTION_FEMAS2VT[data["Direction"]],
gateway_name=self.gateway_name,
)
self.positions[key] = position
position.yd_volume = data["YdPosition"]
# 计算之前已有仓位的持仓总成本
cost: float = position.price * position.volume
# 累加更新持仓数量
position.volume += data["Position"]
# 计算更新后的持仓总成本和均价
if position.volume:
cost += data["PositionCost"]
position.price = cost / position.volume
# 更新仓位冻结数量
position.frozen += data["FrozenPosition"]
if last:
for position in self.positions.values():
self.gateway.on_position(position)
self.positions.clear()
def onRspQryInvestorAccount(self, data: dict, error: dict, reqid: int, last: bool) -> None:
"""资金查询回报"""
account: AccountData = AccountData(
accountid=data["AccountID"],
frozen=data["LongMargin"] + data["ShortMargin"],
balance=data["PreBalance"],
gateway_name=self.gateway_name,
)
self.gateway.on_account(account)
def onRspQryInstrument(self, data: dict, error: dict, reqid: int, last: bool) -> None:
"""合约查询回报"""
# 飞马柜台没有提供ProductClass数据,因此需要使用以下逻辑确定产品类型。
option_type: OptionType = OPTIONTYPE_FEMAS2VT.get(data["OptionsType"], None)
if option_type:
product = Product.OPTION
elif data["InstrumentID_2"]:
product = Product.SPREAD
else:
product = Product.FUTURES
contract: ContractData = ContractData(
symbol=data["InstrumentID"],
exchange=EXCHANGE_FEMAS2VT[data["ExchangeID"]],
name=data["InstrumentName"],
size=data["VolumeMultiple"],
pricetick=data["PriceTick"],
product=product,
gateway_name=self.gateway_name
)
if product == Product.OPTION:
# 移除郑商所期权产品名称带有的C/P后缀
if contract.exchange == Exchange.CZCE:
contract.option_portfolio = data["ProductID"][:-1]
else:
contract.option_portfolio = data["ProductID"]
contract.option_underlying = data["UnderlyingInstrID"]
contract.option_type = OPTIONTYPE_FEMAS2VT.get(data["OptionsType"], None)
contract.option_strike = data["StrikePrice"]
contract.option_index = str(data["StrikePrice"])
contract.option_expiry = datetime.strptime(data["ExpireDate"], "%Y%m%d")
self.gateway.on_contract(contract)
symbol_contract_map[contract.symbol] = contract
if last:
self.gateway.write_log("合约信息查询成功")
def onRtnOrder(self, data: dict) -> None:
"""委托更新推送"""
timestamp: str = f"{data["InsertDate"]} {data["InsertTime"]}"
dt: datetime = datetime.strptime(timestamp, "%Y%m%d %H:%M:%S")
dt = CHINA_TZ.localize(dt)
order: OrderData = OrderData(
symbol=data["InstrumentID"],
exchange=EXCHANGE_FEMAS2VT[data["ExchangeID"]],
orderid=data["UserOrderLocalID"],
direction=DIRECTION_FEMAS2VT[data["Direction"]],
offset=OFFSET_FEMAS2VT[data["OffsetFlag"]],
price=data["LimitPrice"],
volume=data["Volume"],
traded=data["VolumeTraded"],
status=STATUS_FEMAS2VT[data["OrderStatus"]],
datettime=dt,
gateway_name=self.gateway_name,
)
self.localid = max(self.localid, int(order.orderid))
self.gateway.on_order(order)
def onRtnTrade(self, data: dict) -> None:
"""成交数据推送"""
# 过滤重复交易数据推送
tradeid: str = data["TradeID"]
if tradeid in self.tradeids:
return
self.tradeids.add(tradeid)
timestamp: str = f"{data["TradeDate"]} {data["TradeTime"]}"
dt: datetime = datetime.strptime(timestamp, "%Y%m%d %H:%M:%S")
dt = CHINA_TZ.localize(dt)
trade: OrderData = TradeData(
symbol=data["InstrumentID"],
exchange=EXCHANGE_FEMAS2VT[data["ExchangeID"]],
orderid=data["UserOrderLocalID"],
tradeid=tradeid,
direction=DIRECTION_FEMAS2VT[data["Direction"]],
offset=OFFSET_FEMAS2VT[data["OffsetFlag"]],
price=data["TradePrice"],
volume=data["TradeVolume"],
datetime=dt,
gateway_name=self.gateway_name,
)
self.gateway.on_trade(trade)
def connect(
self,
address: str,
userid: str,
password: str,
brokerid: int,
auth_code: str,
appid: str,
) -> None:
"""连接服务器"""
self.userid = userid
self.password = password
self.brokerid = brokerid
self.address = address
self.auth_code = auth_code
self.appid = appid
if not self.connect_status:
path = get_folder_path(self.gateway_name.lower())
self.createFtdcTraderApi(str(path) + "\\Td")
self.subscribePrivateTopic(0)
self.subscribePublicTopic(0)
self.subscribeUserTopic(0)
self.registerFront(address)
self.init()
self.connect_status = True
else:
self.authenticate()
def authenticate(self) -> None:
"""发起授权验证"""
req: dict = {
"AppID": self.appid,
"AuthCode": self.auth_code,
"EncryptType": "1",
}
self.reqid += 1
self.reqDSUserCertification(req, self.reqid)
def login(self) -> None:
"""用户登录"""
if self.login_failed:
return
req: dict = {
"UserID": self.userid,
"Password": self.password,
"BrokerID": self.brokerid,
"AppID": self.appid
}
self.reqid += 1
self.reqUserLogin(req, self.reqid)
def query_investor(self) -> None:
"""委托查询可用投资者"""
self.reqid += 1
req = {
"BrokerID": self.brokerid,
"UserID": self.userid,
}
self.reqQryUserInvestor(req, self.reqid)
def send_order(self, req: OrderRequest) -> str:
"""委托下单"""
if req.offset not in OFFSET_VT2FEMAS:
self.gateway.write_log("请选择开平方向")
return ""
self.localid += 1
orderid: str = str(self.localid).rjust(12, "0")
femas_req: dict = {
"InstrumentID": req.symbol,
"ExchangeID": str(req.exchange).split(".")[1],
"BrokerID": self.brokerid,
"InvestorID": self.investorid,
"UserID": self.userid,
"LimitPrice": req.price,
"Volume": int(req.volume),
"OrderPriceType": ORDERTYPE_VT2FEMAS.get(req.type, ""),
"Direction": DIRECTION_VT2FEMAS.get(req.direction, ""),
"OffsetFlag": OFFSET_VT2FEMAS.get(req.offset, ""),
"UserOrderLocalID": orderid,
"HedgeFlag": USTP_FTDC_CHF_Speculation,
"ForceCloseReason": USTP_FTDC_FCR_NotForceClose,
"IsAutoSuspend": 0,
"TimeCondition": USTP_FTDC_TC_GFD,
"VolumeCondition": USTP_FTDC_VC_AV,
"MinVolume": 1,
}
if req.type == OrderType.FAK:
femas_req["OrderPriceType"] = USTP_FTDC_OPT_LimitPrice
femas_req["TimeCondition"] = USTP_FTDC_TC_IOC
femas_req["VolumeCondition"] = USTP_FTDC_VC_AV
elif req.type == OrderType.FOK:
femas_req["OrderPriceType"] = USTP_FTDC_OPT_LimitPrice
femas_req["TimeCondition"] = USTP_FTDC_TC_IOC
femas_req["VolumeCondition"] = USTP_FTDC_VC_CV
self.reqid += 1
self.reqOrderInsert(femas_req, self.reqid)
order: OrderData = req.create_order_data(orderid, self.gateway_name)
self.gateway.on_order(order)
return order.vt_orderid
def cancel_order(self, req: CancelRequest) -> None:
"""委托撤单"""
self.localid += 1
orderid: str = str(self.localid).rjust(12, "0")
femas_req: dict = {
"InstrumentID": req.symbol,
"ExchangeID": str(req.exchange).split(".")[1],
"UserOrderLocalID": req.orderid,
"UserOrderActionLocalID": orderid,
"ActionFlag": USTP_FTDC_AF_Delete,
"BrokerID": self.brokerid,
"InvestorID": self.investorid,
"UserID": self.userid,
}
self.reqid += 1
self.reqOrderAction(femas_req, self.reqid)
def query_account(self) -> None:
"""查询资金"""
if not self.investorid:
return
req: dict = {
"BrokerID": self.brokerid,
"InvestorID": self.investorid,
"UserID": self.userid,
}
self.reqid += 1
self.reqQryInvestorAccount(req, self.reqid)
def query_position(self) -> None:
"""查询持仓"""
if not symbol_contract_map:
return
req: dict = {
"BrokerID": self.brokerid,
"InvestorID": self.investorid,
"UserID": self.userid,
}
self.reqid += 1
self.reqQryInvestorPosition(req, self.reqid)
def close(self) -> None:
"""关闭连接"""
if self.connect_status:
self.exit()
| """"""
from typing import Callable, Dict, List
import pytz
from datetime import datetime
from time import sleep
from ..api import (
MdApi,
TdApi,
USTP_FTDC_AF_Delete,
USTP_FTDC_CAS_Accepted,
USTP_FTDC_CAS_Rejected,
USTP_FTDC_CAS_Submitted,
USTP_FTDC_CHF_Speculation,
USTP_FTDC_D_Buy,
USTP_FTDC_D_Sell,
USTP_FTDC_FCR_NotForceClose,
USTP_FTDC_OF_Close,
USTP_FTDC_OF_CloseToday,
USTP_FTDC_OF_CloseYesterday,
USTP_FTDC_OF_Open,
USTP_FTDC_OPT_AnyPrice,
USTP_FTDC_OPT_LimitPrice,
USTP_FTDC_OS_AllTraded,
USTP_FTDC_OS_Canceled,
USTP_FTDC_OS_NoTradeQueueing,
USTP_FTDC_OS_PartTradedQueueing,
USTP_FTDC_OT_CallOptions,
USTP_FTDC_OT_PutOptions,
USTP_FTDC_TC_GFD,
USTP_FTDC_TC_IOC,
USTP_FTDC_VC_AV,
USTP_FTDC_VC_CV
)
from vnpy.event.engine import EventEngine
from vnpy.trader.constant import (
Direction,
Exchange,
Offset,
OptionType,
OrderType,
Status,
Product
)
from vnpy.trader.event import EVENT_TIMER
from vnpy.trader.gateway import BaseGateway
from vnpy.trader.object import (
AccountData,
CancelRequest,
ContractData,
OrderData,
OrderRequest,
PositionData,
SubscribeRequest,
TickData,
TradeData,
)
from vnpy.trader.utility import get_folder_path
STATUS_FEMAS2VT = {
USTP_FTDC_CAS_Submitted: Status.SUBMITTING,
USTP_FTDC_CAS_Accepted: Status.SUBMITTING,
USTP_FTDC_CAS_Rejected: Status.REJECTED,
USTP_FTDC_OS_NoTradeQueueing: Status.NOTTRADED,
USTP_FTDC_OS_PartTradedQueueing: Status.PARTTRADED,
USTP_FTDC_OS_AllTraded: Status.ALLTRADED,
USTP_FTDC_OS_Canceled: Status.CANCELLED,
}
DIRECTION_VT2FEMAS = {
Direction.LONG: USTP_FTDC_D_Buy,
Direction.SHORT: USTP_FTDC_D_Sell,
}
DIRECTION_FEMAS2VT = {v: k for k, v in DIRECTION_VT2FEMAS.items()}
ORDERTYPE_VT2FEMAS = {
OrderType.LIMIT: USTP_FTDC_OPT_LimitPrice,
OrderType.MARKET: USTP_FTDC_OPT_AnyPrice,
}
OFFSET_VT2FEMAS = {
Offset.OPEN: USTP_FTDC_OF_Open,
Offset.CLOSE: USTP_FTDC_OF_Close,
Offset.CLOSETODAY: USTP_FTDC_OF_CloseYesterday,
Offset.CLOSEYESTERDAY: USTP_FTDC_OF_CloseToday,
}
OFFSET_FEMAS2VT = {v: k for k, v in OFFSET_VT2FEMAS.items()}
EXCHANGE_FEMAS2VT = {
"CFFEX": Exchange.CFFEX,
"SHFE": Exchange.SHFE,
"CZCE": Exchange.CZCE,
"DCE": Exchange.DCE,
"INE": Exchange.INE,
}
OPTIONTYPE_FEMAS2VT = {
USTP_FTDC_OT_CallOptions: OptionType.CALL,
USTP_FTDC_OT_PutOptions: OptionType.PUT,
}
CHINA_TZ = pytz.timezone("Asia/Shanghai")
symbol_contract_map: Dict[str, ContractData] = {}
class FemasGateway(BaseGateway):
"""
VeighNa用于连接飞马柜台的接口
"""
default_name: str = "FEMAS"
default_setting: dict = {
"用户名": "",
"密码": "",
"经纪商代码": "",
"交易服务器": "",
"行情服务器": "",
"产品名称": "",
"授权编码": "",
}
exchanges: List[str] = list(EXCHANGE_FEMAS2VT.values())
def __init__(self, event_engine: EventEngine, gateway_name: str) -> None:
"""构造函数"""
super().__init__(event_engine, gateway_name)
self.td_api: FemasTdApi = FemasTdApi(self)
self.md_api: FemasTdApi = FemasMdApi(self)
def connect(self, setting: dict) -> None:
"""连接交易接口"""
userid: str = setting["用户名"]
password: str = setting["密码"]
brokerid: str = setting["经纪商代码"]
td_address: str = setting["交易服务器"]
md_address: str = setting["行情服务器"]
if not td_address.startswith("tcp://"):
td_address = "tcp://" + td_address
if not md_address.startswith("tcp://"):
md_address = "tcp://" + md_address
appid: str = setting["产品名称"]
auth_code: str = setting["授权编码"]
self.td_api.connect(td_address, userid, password, brokerid, auth_code, appid)
self.md_api.connect(md_address, userid, password, brokerid)
self.init_query()
def subscribe(self, req: SubscribeRequest) -> None:
"""订阅行情"""
self.md_api.subscribe(req)
def send_order(self, req: OrderRequest) -> None:
"""委托下单"""
return self.td_api.send_order(req)
def cancel_order(self, req: CancelRequest) -> None:
"""委托撤单"""
self.td_api.cancel_order(req)
def query_account(self) -> None:
"""查询资金"""
self.td_api.query_account()
def query_position(self) -> None:
"""查询持仓"""
self.td_api.query_position()
def close(self) -> None:
"""关闭接口"""
self.td_api.close()
self.md_api.close()
def write_error(self, msg: str, error: dict) -> None:
"""输出错误信息日志"""
error_id: str = error["ErrorID"]
error_msg: str = error["ErrorMsg"]
msg: str = f"{msg},代码:{error_id},信息:{error_msg}"
self.write_log(msg)
def process_timer_event(self, event) -> None:
"""定时事件处理"""
self.count += 1
if self.count < 2:
return
self.count = 0
func: Callable = self.query_functions.pop(0)
func()
self.query_functions.append(func)
def init_query(self) -> None:
"""初始化查询任务"""
self.count: int = 0
self.query_functions: List[Callable] = [self.query_account, self.query_position]
self.event_engine.register(EVENT_TIMER, self.process_timer_event)
class FemasMdApi(MdApi):
""""""
def __init__(self, gateway: FemasGateway) -> None:
"""构造函数"""
super(FemasMdApi, self).__init__()
self.gateway: FemasGateway = gateway
self.gateway_name: str = gateway.gateway_name
self.reqid: int = 0
self.connect_status: bool = False
self.login_status: bool = False
self.auth_staus: bool = False
self.login_failed: bool = False
self.subscribed: List[str] = set()
self.userid: str = ""
self.password: str = ""
self.brokerid: int = 0
def onFrontConnected(self) -> None:
"""服务器连接成功回报"""
self.gateway.write_log("行情服务器连接成功")
self.login()
def onFrontDisconnected(self, reason: int) -> None:
"""服务器连接断开回报"""
self.login_status = False
self.gateway.write_log(f"行情服务器连接断开,原因{reason}")
def onRspUserLogin(self, data: dict, error: dict, reqid: int, last: bool) -> None:
"""用户登录请求回报"""
if not error["ErrorID"]:
self.login_status = True
self.gateway.write_log("行情服务器登录成功")
for symbol in self.subscribed:
self.subMarketData(symbol)
else:
self.gateway.write_error("行情服务器登录失败", error)
def onRspError(self, error: dict, reqid: int, last: bool) -> None:
"""请求报错回报"""
self.gateway.write_error("行情接口报错", error)
def onRspSubMarketData(self, data: dict, error: dict, reqid: int, last: bool) -> None:
"""订阅行情回报"""
if not error or not error["ErrorID"]:
return
self.gateway.write_error("行情订阅失败", error)
def onRtnDepthMarketData(self, data: dict) -> None:
"""行情数据推送"""
symbol: str = data["InstrumentID"]
contract: ContractData = symbol_contract_map.get(symbol, None)
if not contract:
return
timestamp: str = f"{data['TradingDay']} {data['UpdateTime']}.{int(data['UpdateMillisec'] / 100)}"
dt: datetime = datetime.strptime(timestamp, "%Y%m%d %H:%M:%S.%f")
dt = CHINA_TZ.localize(dt)
tick: TickData = TickData(
symbol=symbol,
exchange=contract.exchange,
datetime=dt,
name=contract.name,
volume=data["Volume"],
last_price=data["LastPrice"],
limit_up=data["UpperLimitPrice"],
limit_down=data["LowerLimitPrice"],
open_price=data["OpenPrice"],
high_price=data["HighestPrice"],
low_price=data["LowestPrice"],
pre_close=data["PreClosePrice"],
bid_price_1=data["BidPrice1"],
ask_price_1=data["AskPrice1"],
bid_volume_1=data["BidVolume1"],
ask_volume_1=data["AskVolume1"],
gateway_name=self.gateway_name,
)
self.gateway.on_tick(tick)
def connect(self, address: str, userid: str, password: str, brokerid: int) -> None:
"""连接服务器"""
self.userid = userid
self.password = password
self.brokerid = brokerid
# 禁止重复发起连接,会导致异常崩溃
if not self.connect_status:
path = get_folder_path(self.gateway_name.lower())
self.createFtdcMdApi((str(path) + "\\Md").encode("GBK"))
self.subscribeMarketDataTopic(100, 2)
self.registerFront(address)
self.init()
self.connect_status = True
# 如果已经连接过了,直接登录
elif not self.login_status:
self.login()
def login(self) -> None:
"""用户登录"""
req: dict = {
"UserID": self.userid,
"Password": self.password,
"BrokerID": self.brokerid,
}
self.reqid += 1
self.reqUserLogin(req, self.reqid)
def subscribe(self, req: SubscribeRequest) -> None:
"""订阅行情"""
if self.login_status:
self.subMarketData(req.symbol)
self.subscribed.add(req.symbol)
def close(self) -> None:
"""关闭连接"""
if self.connect_status:
self.exit()
class FemasTdApi(TdApi):
""""""
def __init__(self, gateway: FemasGateway):
"""构造函数"""
super(FemasTdApi, self).__init__()
self.gateway: FemasGateway = gateway
self.gateway_name: str = gateway.gateway_name
self.reqid: int = 0
self.localid: int = int(10e5 + 8888)
self.connect_status: bool = False
self.login_status: bool = False
self.login_failed: bool = False
self.login_status: bool = False
self.userid: str = ""
self.investorid: str = ""
self.password: str = ""
self.brokerid: int = 0
self.auth_code: str = ""
self.appid: str = ""
self.positions: dict = {}
self.tradeids: List[str] = set()
def onFrontConnected(self) -> None:
"""服务器连接成功回报"""
self.gateway.write_log("交易服务器连接成功")
if self.auth_code:
self.authenticate()
else:
self.login()
def onFrontDisconnected(self, reason: int) -> None:
"""服务器连接断开回报"""
self.login_status = False
self.gateway.write_log(f"交易服务器连接断开,原因{reason}")
def onRspDSUserCertification(self, data: dict, error: dict, reqid: int, last: bool) -> None:
"""用户授权验证回报"""
if not error["ErrorID"]:
self.auth_staus = True
self.gateway.write_log("交易服务器授权验证成功")
self.login()
else:
self.gateway.write_error("交易服务器授权验证失败", error)
def onRspUserLogin(self, data: dict, error: dict, reqid: int, last: bool) -> None:
"""用户登录请求回报"""
if not error["ErrorID"]:
if data["MaxOrderLocalID"]:
self.localid = int(data["MaxOrderLocalID"])
self.login_status = True
self.gateway.write_log("交易服务器登录成功")
self.query_investor()
else:
self.login_failed = True
self.gateway.write_error("交易服务器登录失败", error)
def onRspQryUserInvestor(self, data: dict, error: dict, reqid: int, last: bool) -> None:
"""委托查询投资者代码回报"""
self.investorid = data['InvestorID']
self.gateway.write_log("投资者代码查询成功")
sleep(1) # 由于流量控制,需要等待1秒钟
self.reqid += 1
self.reqQryInstrument({}, self.reqid)
def onRspOrderInsert(self, data: dict, error: dict, reqid: int, last: bool) -> None:
"""委托下单失败回报"""
if not error["ErrorID"]:
return
orderid:str = data["UserOrderLocalID"]
symbol: str = data["InstrumentID"]
contract: ContractData = symbol_contract_map[symbol]
order: OrderData = OrderData(
symbol=symbol,
exchange=contract.exchange,
orderid=orderid,
direction=DIRECTION_FEMAS2VT[data["Direction"]],
offset=OFFSET_FEMAS2VT[data["OffsetFlag"]],
price=data["LimitPrice"],
volume=data["Volume"],
status=Status.REJECTED,
gateway_name=self.gateway_name,
)
self.gateway.on_order(order)
self.gateway.write_error("交易委托失败", error)
def onRspOrderAction(self, data: dict, error: dict, reqid: int, last: bool) -> None:
"""委托撤单失败回报"""
if not error["ErrorID"]:
return
self.gateway.write_error("交易撤单失败", error)
def onRspQueryMaxOrderVolume(self, data: dict, error: dict, reqid: int, last: bool) -> None:
""""""
pass
def onRspSettlementInfoConfirm(
self, data: dict, error: dict, reqid: int, last: bool
) -> None:
"""确认结算单回报"""
self.gateway.write_log("结算信息确认成功")
self.reqid += 1
self.reqQryInstrument({}, self.reqid)
def onRspQryInvestorPosition(self, data: dict, error: dict, reqid: int, last: bool) -> None:
"""持仓查询回报"""
if not data:
return
# 必须收到了合约信息后才能处理
symbol: str = data["InstrumentID"]
contract: ContractData = symbol_contract_map.get(symbol, None)
if contract:
# 获取之前缓存的持仓数据缓存
key: str = f"{data['InstrumentID'], data['Direction']}"
position: PositionData = self.positions.get(key, None)
if not position:
position = PositionData(
symbol=data["InstrumentID"],
exchange=contract.exchange,
direction=DIRECTION_FEMAS2VT[data["Direction"]],
gateway_name=self.gateway_name,
)
self.positions[key] = position
position.yd_volume = data["YdPosition"]
# 计算之前已有仓位的持仓总成本
cost: float = position.price * position.volume
# 累加更新持仓数量
position.volume += data["Position"]
# 计算更新后的持仓总成本和均价
if position.volume:
cost += data["PositionCost"]
position.price = cost / position.volume
# 更新仓位冻结数量
position.frozen += data["FrozenPosition"]
if last:
for position in self.positions.values():
self.gateway.on_position(position)
self.positions.clear()
def onRspQryInvestorAccount(self, data: dict, error: dict, reqid: int, last: bool) -> None:
"""资金查询回报"""
account: AccountData = AccountData(
accountid=data["AccountID"],
frozen=data["LongMargin"] + data["ShortMargin"],
balance=data["PreBalance"],
gateway_name=self.gateway_name,
)
self.gateway.on_account(account)
def onRspQryInstrument(self, data: dict, error: dict, reqid: int, last: bool) -> None:
"""合约查询回报"""
# 飞马柜台没有提供ProductClass数据,因此需要使用以下逻辑确定产品类型。
option_type: OptionType = OPTIONTYPE_FEMAS2VT.get(data["OptionsType"], None)
if option_type:
product = Product.OPTION
elif data["InstrumentID_2"]:
product = Product.SPREAD
else:
product = Product.FUTURES
contract: ContractData = ContractData(
symbol=data["InstrumentID"],
exchange=EXCHANGE_FEMAS2VT[data["ExchangeID"]],
name=data["InstrumentName"],
size=data["VolumeMultiple"],
pricetick=data["PriceTick"],
product=product,
gateway_name=self.gateway_name
)
if product == Product.OPTION:
# 移除郑商所期权产品名称带有的C/P后缀
if contract.exchange == Exchange.CZCE:
contract.option_portfolio = data["ProductID"][:-1]
else:
contract.option_portfolio = data["ProductID"]
contract.option_underlying = data["UnderlyingInstrID"]
contract.option_type = OPTIONTYPE_FEMAS2VT.get(data["OptionsType"], None)
contract.option_strike = data["StrikePrice"]
contract.option_index = str(data["StrikePrice"])
contract.option_expiry = datetime.strptime(data["ExpireDate"], "%Y%m%d")
self.gateway.on_contract(contract)
symbol_contract_map[contract.symbol] = contract
if last:
self.gateway.write_log("合约信息查询成功")
def onRtnOrder(self, data: dict) -> None:
"""委托更新推送"""
timestamp: str = f"{data['InsertDate']} {data['InsertTime']}"
dt: datetime = datetime.strptime(timestamp, "%Y%m%d %H:%M:%S")
dt = CHINA_TZ.localize(dt)
order: OrderData = OrderData(
symbol=data["InstrumentID"],
exchange=EXCHANGE_FEMAS2VT[data["ExchangeID"]],
orderid=data["UserOrderLocalID"],
direction=DIRECTION_FEMAS2VT[data["Direction"]],
offset=OFFSET_FEMAS2VT[data["OffsetFlag"]],
price=data["LimitPrice"],
volume=data["Volume"],
traded=data["VolumeTraded"],
status=STATUS_FEMAS2VT[data["OrderStatus"]],
datettime=dt,
gateway_name=self.gateway_name,
)
self.localid = max(self.localid, int(order.orderid))
self.gateway.on_order(order)
def onRtnTrade(self, data: dict) -> None:
"""成交数据推送"""
# 过滤重复交易数据推送
tradeid: str = data["TradeID"]
if tradeid in self.tradeids:
return
self.tradeids.add(tradeid)
timestamp: str = f"{data['TradeDate']} {data['TradeTime']}"
dt: datetime = datetime.strptime(timestamp, "%Y%m%d %H:%M:%S")
dt = CHINA_TZ.localize(dt)
trade: OrderData = TradeData(
symbol=data["InstrumentID"],
exchange=EXCHANGE_FEMAS2VT[data["ExchangeID"]],
orderid=data["UserOrderLocalID"],
tradeid=tradeid,
direction=DIRECTION_FEMAS2VT[data["Direction"]],
offset=OFFSET_FEMAS2VT[data["OffsetFlag"]],
price=data["TradePrice"],
volume=data["TradeVolume"],
datetime=dt,
gateway_name=self.gateway_name,
)
self.gateway.on_trade(trade)
def connect(
self,
address: str,
userid: str,
password: str,
brokerid: int,
auth_code: str,
appid: str,
) -> None:
"""连接服务器"""
self.userid = userid
self.password = password
self.brokerid = brokerid
self.address = address
self.auth_code = auth_code
self.appid = appid
if not self.connect_status:
path = get_folder_path(self.gateway_name.lower())
self.createFtdcTraderApi(str(path) + "\\Td")
self.subscribePrivateTopic(0)
self.subscribePublicTopic(0)
self.subscribeUserTopic(0)
self.registerFront(address)
self.init()
self.connect_status = True
else:
self.authenticate()
def authenticate(self) -> None:
"""发起授权验证"""
req: dict = {
"AppID": self.appid,
"AuthCode": self.auth_code,
"EncryptType": "1",
}
self.reqid += 1
self.reqDSUserCertification(req, self.reqid)
def login(self) -> None:
"""用户登录"""
if self.login_failed:
return
req: dict = {
"UserID": self.userid,
"Password": self.password,
"BrokerID": self.brokerid,
"AppID": self.appid
}
self.reqid += 1
self.reqUserLogin(req, self.reqid)
def query_investor(self) -> None:
"""委托查询可用投资者"""
self.reqid += 1
req = {
"BrokerID": self.brokerid,
"UserID": self.userid,
}
self.reqQryUserInvestor(req, self.reqid)
def send_order(self, req: OrderRequest) -> str:
"""委托下单"""
if req.offset not in OFFSET_VT2FEMAS:
self.gateway.write_log("请选择开平方向")
return ""
self.localid += 1
orderid: str = str(self.localid).rjust(12, "0")
femas_req: dict = {
"InstrumentID": req.symbol,
"ExchangeID": str(req.exchange).split(".")[1],
"BrokerID": self.brokerid,
"InvestorID": self.investorid,
"UserID": self.userid,
"LimitPrice": req.price,
"Volume": int(req.volume),
"OrderPriceType": ORDERTYPE_VT2FEMAS.get(req.type, ""),
"Direction": DIRECTION_VT2FEMAS.get(req.direction, ""),
"OffsetFlag": OFFSET_VT2FEMAS.get(req.offset, ""),
"UserOrderLocalID": orderid,
"HedgeFlag": USTP_FTDC_CHF_Speculation,
"ForceCloseReason": USTP_FTDC_FCR_NotForceClose,
"IsAutoSuspend": 0,
"TimeCondition": USTP_FTDC_TC_GFD,
"VolumeCondition": USTP_FTDC_VC_AV,
"MinVolume": 1,
}
if req.type == OrderType.FAK:
femas_req["OrderPriceType"] = USTP_FTDC_OPT_LimitPrice
femas_req["TimeCondition"] = USTP_FTDC_TC_IOC
femas_req["VolumeCondition"] = USTP_FTDC_VC_AV
elif req.type == OrderType.FOK:
femas_req["OrderPriceType"] = USTP_FTDC_OPT_LimitPrice
femas_req["TimeCondition"] = USTP_FTDC_TC_IOC
femas_req["VolumeCondition"] = USTP_FTDC_VC_CV
self.reqid += 1
self.reqOrderInsert(femas_req, self.reqid)
order: OrderData = req.create_order_data(orderid, self.gateway_name)
self.gateway.on_order(order)
return order.vt_orderid
def cancel_order(self, req: CancelRequest) -> None:
"""委托撤单"""
self.localid += 1
orderid: str = str(self.localid).rjust(12, "0")
femas_req: dict = {
"InstrumentID": req.symbol,
"ExchangeID": str(req.exchange).split(".")[1],
"UserOrderLocalID": req.orderid,
"UserOrderActionLocalID": orderid,
"ActionFlag": USTP_FTDC_AF_Delete,
"BrokerID": self.brokerid,
"InvestorID": self.investorid,
"UserID": self.userid,
}
self.reqid += 1
self.reqOrderAction(femas_req, self.reqid)
def query_account(self) -> None:
"""查询资金"""
if not self.investorid:
return
req: dict = {
"BrokerID": self.brokerid,
"InvestorID": self.investorid,
"UserID": self.userid,
}
self.reqid += 1
self.reqQryInvestorAccount(req, self.reqid)
def query_position(self) -> None:
"""查询持仓"""
if not symbol_contract_map:
return
req: dict = {
"BrokerID": self.brokerid,
"InvestorID": self.investorid,
"UserID": self.userid,
}
self.reqid += 1
self.reqQryInvestorPosition(req, self.reqid)
def close(self) -> None:
"""关闭连接"""
if self.connect_status:
self.exit()
|
import sys
from baselines.common.cmd_util import common_arg_parser
from baselines.run import parse_cmdline_kwargs
from baselines.her.metric_diversification import MetricDiversifier
from baselines.her.cover_measure import init_from_point
import gym
#import gym_maze
import numpy as np
import time
from baselines.her.paper_utils import utils as paper_utils
np.set_printoptions(precision=2)
import random
def set_goal(env, scrb):
if len(scrb.used_slots()) == 0:
return env.reset()
return env.set_goal(goal=scrb.draw(1)[0]['ag'])
# return env.set_goal(goal=random.choice(scrb)['ag'])
def reset_env(env, scrb, mode='intrinsic'):
if mode == 'intrinsic':
return env.reset()
elif mode == 'extrinsic':
assert 'cover_path' is not None, 'missing cover path argument'
pnt = scrb.draw(1)[0]
# pnt = random.choice(scrb)
if pnt is None:
return env.reset()
obs = init_from_point(env, pnt)
return obs
elif mode == 'random':
obs = env.reset()
qpos = obs["qpos"]
qvel = obs["qvel"]
ex_init = {'o': None, 'qpos': np.zeros_like(qpos), 'qvel': np.zeros_like(qvel), 'g': None}
env.reset(ex_init=ex_init)
def scan_cover(env, action_repetition=1, cover_path=None, **kwargs):
scrb = MetricDiversifier(k=100, load_model=cover_path, reward_func=None)
obs = reset_env(env, scrb, mode='intrinsic')
for i in range(100000):
env.render()
time.sleep(.1)
if i % action_repetition == 0:
a = env.action_space.sample()
obs, reward, done, info = env.step(a)
if i % 1 == 0:
ob = reset_env(env, scrb, mode='extrinsic')
# print(np.linalg.norm(ob["qvel"]))
time.sleep(.5)
env.close()
def plain_loop(env, action_repetition=1, clip_range=0.5, **kwargs):
reset_env(env, scrb=None, mode='intrinsic')
print(f"Obs: {env.observation_space["observation"].shape}, goal: {env.observation_space["achieved_goal"].shape}, action: {env.action_space.shape}")
sys.exit()
i = 0
while True:
i += 1
env.render()
time.sleep(.1)
if i % action_repetition == 0:
a = np.clip(env.action_space.sample(), -clip_range, clip_range)
o, r, d, info = env.step(a)
if i % 1000 == 0:
reset_env(env, scrb=None, mode='intrinsic')
print(f"Reset")
i = 0
env.close()
def play_policy(env, env_id, T=20, load_path=None, cover_path=None, semi_metric=False, eps_greedy=False, **kwargs):
policy, reward_fun = paper_utils.load_policy(env_id, **kwargs)
paper_utils.load_model(load_path=load_path)
scrb = MetricDiversifier(k=100, load_model=cover_path, reward_func=None)
obs = reset_env(env, scrb, mode='intrinsic')
i = 0
while True:
i += 1
env.render()
time.sleep(.01)
action, _, state, _ = policy.step(obs)
if eps_greedy and i % 10 == 0:
action = env.action_space.sample()
obs, reward, done, info = env.step(action)
success = info['is_success']
timeout = i % T == 0
done = success or timeout
if done:
# input(f"success: {success}, invalid: {invalid}, timeout: {timeout}")
if scrb is None or semi_metric:
reset_env(env, scrb, mode='intrinsic')
else:
reset_env(env, scrb, mode='extrinsic')
obs = set_goal(env, scrb)
i = 0
env.close()
def exp1_loop(env, scrb, policy, eps_greedy, T, semi_metric, nsteps):
obs = reset_env(env, scrb, mode='intrinsic')
while len(scrb.open_slots()) > 0:
pnt = scrb.init_record(o=obs['observation'].copy())
scrb.load_new_point(pnt, d_func=policy.get_actions)
assert not scrb.dilute_overlaps
reached_goal = False
t = 0
counter = 0
times = []
radii = []
while counter < nsteps:
# 1. environment step
action, _, state, _ = policy.step(obs)
if reached_goal or (eps_greedy and t % 10 == 0):
action = env.action_space.sample()
obs, reward, done, info = env.step(action)
success = info['is_success']
reached_goal = reached_goal or success
# 2. GPI update
pnt = scrb.init_record(o=obs['observation'].copy())
scrb.load_new_point(pnt, d_func=policy.get_actions)
r_pack = env._max_episode_steps + scrb.M.min()
times.append(counter)
radii.append(r_pack)
if counter % 1000 == 0:
...
# scrb.save(message=counter)
# print(f"counter: {counter}, cover size: {scrb.current_size}, packing radius: {r_pack}")
# TODO: add back after debug
# scrb.age += 1
# 3. measure packing radius
...
# 4. episodic reset
if t % T == 0:
t = 0
reached_goal = False
if semi_metric:
reset_env(env, scrb, mode='intrinsic')
else:
reset_env(env, scrb, mode='extrinsic')
obs = set_goal(env, scrb)
counter += 1
t += 1
return times, radii
def experiment1(env, env_id, T=100, k=50, load_path=None, save_path=None, semi_metric=False, eps_greedy=False,
dilute_overlaps=True, ntrials=5, nsteps=10000, random_mode=False, **kwargs):
policy, reward_fun = paper_utils.load_policy(env_id, **kwargs)
paper_utils.load_model(load_path=load_path)
if semi_metric:
metric_str = "semi_metric"
else:
metric_str = "full_metric"
for random_mode in [True, False]:
if random_mode:
random_str = 'random'
alpha = 0
else:
random_str = 'scrb'
alpha = 0.5
log_path = f"{save_path}/{metric_str}_{random_str}"
results = dict()
k_vec = [10, 20, 30, 40, 50]
# k_vec = [50]
for k in k_vec:
results[k] = dict()
k_radii = []
for trial_idx in range(ntrials):
scrb = MetricDiversifier(k=k, vis=False, dilute_overlaps=dilute_overlaps, vis_coords=[0, 1], save_path=log_path,
reward_func=reward_fun, random_mode=random_mode)
times, radii = exp1_loop(env, scrb, policy, eps_greedy, T, semi_metric, nsteps)
k_radii.append(radii)
print(f"k: {k}, trial: {trial_idx}/{ntrials}, nsteps: {nsteps}")
results[k]["mean"] = np.asarray(k_radii).mean(axis=0)
results[k]["std"] = np.asarray(k_radii).std(axis=0)
results[k]["time"] = times
paper_utils.exp1_to_figure(results, save_directory=log_path, alpha=alpha, message=f"{metric_str}_{random_str}")
exp1_loop(env, scrb, policy, eps_greedy, T, semi_metric, 50)
paper_utils.exp1_overlayed_figure(env, scrb, save_directory=log_path, message=f"{metric_str}_{random_str}")
def exp2_loop(env, policy, models_path, epochs, ngoals, max_steps, vis=False, eps_greedy=False):
goals = [env.env.draw_goal() for _ in range(ngoals)]
recall_at_epoch = []
# epochs = paper_utils.list_epochs(models_path)
# epochs.sort()
# epochs = [epoch for epoch in epochs if epoch % 25 == 0]
# epochs = epochs[:2]
for epoch_idx in epochs:
reached = np.zeros(len(goals))
paper_utils.load_model(load_path=f"{models_path}/epoch_{epoch_idx}.model")
for gidx, goal in enumerate(goals):
if reached[gidx]:
continue
obs = reset_env(env, scrb=None, mode='intrinsic')
env.env.set_goal(goal=goal)
for t in range(max_steps):
if reached[gidx]:
break
if vis:
env.render()
time.sleep(.01)
action, _, state, _ = policy.step(obs)
if eps_greedy and t % 10 == 0:
action = env.action_space.sample()
obs, reward, done, info = env.step(action)
if info['is_success']:
reached[gidx] = 1
recall_at_epoch.append(reached.mean())
return epochs, recall_at_epoch
def experiment2(env, env_id, T=100, scrb_models_path=None, plain_models_path=None, save_path=None, eps_greedy=False, ntrials=5, ngoals=100, vis=False, **kwargs):
policy, reward_fun = paper_utils.load_policy(env_id, **kwargs)
scrb_epochs = paper_utils.list_epochs(scrb_models_path)
plain_epochs = paper_utils.list_epochs(plain_models_path)
scrb_epochs.sort()
plain_epochs.sort()
scrb_epochs = [epoch for epoch in scrb_epochs if epoch % 50 == 0]
plain_epochs = [epoch for epoch in plain_epochs if epoch % 50 == 0]
nepochs = np.minimum(len(scrb_epochs), len(plain_epochs))
epochs = scrb_epochs[:nepochs]
print(epochs)
results = dict()
for scrb in [True, False]:
if scrb:
scrb_str = 'scrb'
method_name = r'$\alpha =$' + f"{0.5}"
models_path = scrb_models_path
else:
scrb_str = 'naive'
method_name = r'$\alpha =$' + f"{0.0}"
models_path = plain_models_path
recalls = []
results[scrb_str] = dict()
for trial_idx in range(ntrials):
print(f"------------------experiment 2: trial #{trial_idx}-----------------")
epochs, recall = exp2_loop(env, policy, models_path, epochs, ngoals, max_steps=T, vis=vis, eps_greedy=eps_greedy)
recalls.append(recall)
results[scrb_str]["mean"] = np.asarray(recalls).mean(axis=0)
results[scrb_str]["std"] = np.asarray(recalls).std(axis=0)
results[scrb_str]['method_name'] = method_name
results[scrb_str]["epochs"] = epochs
paper_utils.exp3_to_figure(results, save_directory=save_path, message=f"{env_id}")
def exp3_loop(env, policy, models_path, covers_path, ngoals, max_steps, semi_metric, vis=False, eps_greedy=False):
variance_at_epoch = []
min_dists = []
hit_times = []
epochs = paper_utils.list_epochs(covers_path)
epochs.sort()
epochs = [epoch for epoch in epochs if epoch % 25 == 0]
# epochs = epochs[:2]
for epoch_idx in epochs:
model_path = f"{models_path}/epoch_{epochs[-1]}.model"
paper_utils.load_model(load_path=model_path)
cover_path = f"{covers_path}/epoch_{epoch_idx}.json"
scrb = MetricDiversifier(k=100, vis=False, vis_coords=[0, 1], save_path=None, load_model=cover_path, reward_func=None)
min_dist = scrb.M.min()
pnts = scrb.draw(ngoals, replace=False)
reached = np.zeros(len(pnts))
hit_time = [max_steps for _ in range(ngoals)]
reached_list = []
for pidx, pnt in enumerate(pnts):
goal = pnt['ag']
if reached[pidx]:
continue
if semi_metric:
obs = reset_env(env, scrb=scrb, mode='intrinsic')
else:
refidx=pidx
while refidx == pidx:
refidx = random.choice([i for i in range(len(pnts))])
refpnt = pnts[refidx]
obs = init_from_point(env, refpnt)
env.env.set_goal(goal=np.asarray(goal))
for t in range(max_steps):
if reached[pidx]:
break
if vis:
env.render()
time.sleep(.01)
action, _, state, _ = policy.step(obs)
if eps_greedy and t % 10 == 0:
action = env.action_space.sample()
obs, reward, done, info = env.step(action)
if info['is_success']:
reached[pidx] = 1
reached_list.append(goal)
hit_time[pidx] = t
if len(reached_list) == 0:
variance_at_epoch.append(0)
else:
variance_at_epoch.append(np.asarray(reached_list).std())
min_dists.append(min_dist)
hit_times.append(np.mean(hit_time))
return epochs, variance_at_epoch, min_dists, hit_times
def experiment3(env, env_id, T=100, models_path=None, covers_path=None, save_path=None, eps_greedy=False, semi_metric=False, ntrials=5, ngoals=100, vis=False, **kwargs):
policy, reward_fun = paper_utils.load_policy(env_id, **kwargs)
metric = 'mean_hit_time'
results = dict()
for scrb in [True, False]:
if not scrb:
continue
if scrb:
scrb_str = 'scrb'
method_name = r'$\alpha =$' + f"{0.5}"
else:
scrb_str = 'naive'
method_name = r'$\alpha =$' + f"{0.0}"
variances = []
min_dists = []
mean_hit_times = []
results[scrb_str] = dict()
for trial_idx in range(ntrials):
print(f"------------------experiment 3: trial #{trial_idx}-----------------")
epochs, variance, min_dist, mean_hit_time = exp3_loop(env, policy, models_path, covers_path, ngoals, semi_metric=semi_metric, max_steps=T, vis=vis, eps_greedy=eps_greedy)
variances.append(variance)
min_dists.append(min_dist)
mean_hit_times.append(mean_hit_time)
if metric == 'variance':
results[scrb_str]["mean"] = np.asarray(variances).mean(axis=0)
results[scrb_str]["std"] = np.asarray(variances).std(axis=0)
elif metric == 'min_dists':
results[scrb_str]["mean"] = np.asarray(min_dists).mean(axis=0)
results[scrb_str]["std"] = np.asarray(min_dists).std(axis=0)
elif metric == 'mean_hit_time':
results[scrb_str]["mean"] = np.asarray(mean_hit_times).mean(axis=0)
results[scrb_str]["std"] = np.asarray(mean_hit_times).std(axis=0)
results[scrb_str]['method_name'] = method_name
results[scrb_str]["epochs"] = epochs
paper_utils.exp3_to_figure(results, save_directory=save_path, message=f"{env_id}_{metric}")
def exp4_loop(env, policy, models_path, covers_path, ngoals, max_steps, semi_metric, vis=False, eps_greedy=False):
recall_at_epoch = []
hit_time_at_epoch = []
model_epochs = paper_utils.list_epochs(models_path)
cover_epochs = paper_utils.list_epochs(covers_path)
model_epochs = [epoch for epoch in model_epochs if epoch % 25 == 0]
cover_epochs = [epoch for epoch in cover_epochs if epoch % 25 == 0]
n_epochs = np.minimum(len(model_epochs), len(cover_epochs))
epochs = model_epochs[:n_epochs]
for epoch_idx in epochs:
cover_path = f"{covers_path}/epoch_{epoch_idx}.json"
scrb = MetricDiversifier(k=100, load_model=cover_path, reward_func=None)
ngoals = np.minimum(ngoals, scrb.k)
paper_utils.load_model(load_path=f"{models_path}/epoch_{epoch_idx}.model")
pnts = scrb.draw(ngoals, replace=False)
reached = np.zeros(len(pnts))
hit_time = [max_steps for _ in range(len(pnts))]
for pidx, pnt in enumerate(pnts):
goal = pnt['ag']
if reached[pidx]:
continue
if semi_metric:
obs = reset_env(env, scrb=scrb, mode='intrinsic')
else:
refidx = pidx
while refidx == pidx:
refidx = random.choice([i for i in range(len(pnts))])
refpnt = pnts[refidx]
obs = init_from_point(env, refpnt)
env.env.set_goal(goal=np.asarray(goal))
for t in range(max_steps):
if reached[pidx]:
break
if vis:
env.render()
time.sleep(.01)
action, _, state, _ = policy.step(obs)
if eps_greedy and t % 10 == 0:
action = env.action_space.sample()
obs, reward, done, info = env.step(action)
if info['is_success']:
reached[pidx] = 1
hit_time[pidx] = t
recall_at_epoch.append(reached.mean())
hit_time_at_epoch.append(np.mean(hit_time))
return epochs, recall_at_epoch, hit_time_at_epoch
def experiment4(env, env_id, T=100, models_path_a=None, models_path_b=None, covers_path_a=None, covers_path_b=None,
save_path=None, eps_greedy=False, ntrials=5, ngoals=100, vis=False, semi_metric=False, **kwargs):
policy, reward_fun = paper_utils.load_policy(env_id, **kwargs)
results = dict()
ab_recalls = []
ba_recalls = []
ab_hit_times = []
ba_hit_times = []
for metric in ['coverage', 'hit_time']:
results[f"{metric}"] = dict()
results[f"{metric}"] = dict()
for type in ["a2b", "b2a"]:
results[f"{metric}"][f"{type}"] = dict()
results[f"{metric}"][f"{type}"] = dict()
for trial_idx in range(ntrials):
print(f"------------------experiment 4: trial #{trial_idx}-----------------")
# A - > B
epochs, ab_recall, ab_hit_time = exp4_loop(env, policy, models_path_a, covers_path_b, semi_metric=semi_metric, ngoals=ngoals, max_steps=T, vis=vis, eps_greedy=eps_greedy)
ab_recalls.append(ab_recall)
ab_hit_times.append(ab_hit_time)
# B - > A
epochs, ba_recall, ba_hit_time = exp4_loop(env, policy, models_path_b, covers_path_a, semi_metric=semi_metric, ngoals=ngoals, max_steps=T, vis=vis, eps_greedy=eps_greedy)
ba_recalls.append(ba_recall)
ba_hit_times.append(ba_hit_time)
for metric in ['coverage', 'hit_time']:
if metric == 'coverage':
ab_values = ab_recalls
ba_values = ba_recalls
elif metric == 'hit_time':
ab_values = ab_hit_times
ba_values = ba_hit_times
results[metric]["a2b"]["mean"] = np.asarray(ab_values).mean(axis=0)
results[metric]["a2b"]["std"] = np.asarray(ab_values).std(axis=0)
results[metric]["a2b"]['method_name'] = r'$\alpha =$' + f"{0.0}"
results[metric]["a2b"]["epochs"] = epochs
results[metric]["b2a"]["mean"] = np.asarray(ba_values).mean(axis=0)
results[metric]["b2a"]["std"] = np.asarray(ba_values).std(axis=0)
results[metric]["b2a"]['method_name'] = r'$\alpha =$' + f"{0.5}"
results[metric]["b2a"]["epochs"] = epochs
paper_utils.exp3_to_figure(results[f"{metric}"], save_directory=save_path, message=f"{env_id}_{metric}")
if __name__ == '__main__':
arg_parser = common_arg_parser()
args, unknown_args = arg_parser.parse_known_args(sys.argv)
extra_args = parse_cmdline_kwargs(unknown_args)
environment = gym.make(args.env, **extra_args)
if extra_args['option'] == 'scan_cover':
scan_cover(environment, **extra_args)
elif extra_args['option'] == 'plain_loop':
plain_loop(environment, **extra_args)
elif extra_args['option'] == 'play_policy':
assert extra_args['load_path'] is not None
play_policy(env=environment, env_id=args.env, **extra_args)
elif extra_args['option'] == 'experiment1':
assert extra_args['load_path'] is not None, 'load path is none'
assert args.save_path is not None, 'save path is none'
experiment1(env=environment, env_id=args.env, save_path=args.save_path, **extra_args)
elif extra_args['option'] == 'experiment2':
assert extra_args['scrb_models_path'] is not None, 'models path is none'
assert extra_args['plain_models_path'] is not None, 'models path is none'
assert args.save_path is not None, 'save path is none'
experiment2(env=environment, env_id=args.env, save_path=args.save_path, **extra_args)
elif extra_args['option'] == 'experiment3':
assert extra_args['models_path'] is not None, 'models path is none'
assert extra_args['covers_path'] is not None, 'covers path is none'
assert args.save_path is not None, 'save path is none'
experiment3(env=environment, env_id=args.env, save_path=args.save_path, **extra_args)
elif extra_args['option'] == 'experiment4':
assert extra_args['models_path_a'] is not None, 'models path is none'
assert extra_args['models_path_b'] is not None, 'models path is none'
assert extra_args['covers_path_a'] is not None, 'covers path is none'
assert extra_args['covers_path_b'] is not None, 'covers path is none'
assert args.save_path is not None, 'save path is none'
experiment4(env=environment, env_id=args.env, save_path=args.save_path, **extra_args) | import sys
from baselines.common.cmd_util import common_arg_parser
from baselines.run import parse_cmdline_kwargs
from baselines.her.metric_diversification import MetricDiversifier
from baselines.her.cover_measure import init_from_point
import gym
#import gym_maze
import numpy as np
import time
from baselines.her.paper_utils import utils as paper_utils
np.set_printoptions(precision=2)
import random
def set_goal(env, scrb):
if len(scrb.used_slots()) == 0:
return env.reset()
return env.set_goal(goal=scrb.draw(1)[0]['ag'])
# return env.set_goal(goal=random.choice(scrb)['ag'])
def reset_env(env, scrb, mode='intrinsic'):
if mode == 'intrinsic':
return env.reset()
elif mode == 'extrinsic':
assert 'cover_path' is not None, 'missing cover path argument'
pnt = scrb.draw(1)[0]
# pnt = random.choice(scrb)
if pnt is None:
return env.reset()
obs = init_from_point(env, pnt)
return obs
elif mode == 'random':
obs = env.reset()
qpos = obs["qpos"]
qvel = obs["qvel"]
ex_init = {'o': None, 'qpos': np.zeros_like(qpos), 'qvel': np.zeros_like(qvel), 'g': None}
env.reset(ex_init=ex_init)
def scan_cover(env, action_repetition=1, cover_path=None, **kwargs):
scrb = MetricDiversifier(k=100, load_model=cover_path, reward_func=None)
obs = reset_env(env, scrb, mode='intrinsic')
for i in range(100000):
env.render()
time.sleep(.1)
if i % action_repetition == 0:
a = env.action_space.sample()
obs, reward, done, info = env.step(a)
if i % 1 == 0:
ob = reset_env(env, scrb, mode='extrinsic')
# print(np.linalg.norm(ob["qvel"]))
time.sleep(.5)
env.close()
def plain_loop(env, action_repetition=1, clip_range=0.5, **kwargs):
reset_env(env, scrb=None, mode='intrinsic')
print(f"Obs: {env.observation_space['observation'].shape}, goal: {env.observation_space['achieved_goal'].shape}, action: {env.action_space.shape}")
sys.exit()
i = 0
while True:
i += 1
env.render()
time.sleep(.1)
if i % action_repetition == 0:
a = np.clip(env.action_space.sample(), -clip_range, clip_range)
o, r, d, info = env.step(a)
if i % 1000 == 0:
reset_env(env, scrb=None, mode='intrinsic')
print(f"Reset")
i = 0
env.close()
def play_policy(env, env_id, T=20, load_path=None, cover_path=None, semi_metric=False, eps_greedy=False, **kwargs):
policy, reward_fun = paper_utils.load_policy(env_id, **kwargs)
paper_utils.load_model(load_path=load_path)
scrb = MetricDiversifier(k=100, load_model=cover_path, reward_func=None)
obs = reset_env(env, scrb, mode='intrinsic')
i = 0
while True:
i += 1
env.render()
time.sleep(.01)
action, _, state, _ = policy.step(obs)
if eps_greedy and i % 10 == 0:
action = env.action_space.sample()
obs, reward, done, info = env.step(action)
success = info['is_success']
timeout = i % T == 0
done = success or timeout
if done:
# input(f"success: {success}, invalid: {invalid}, timeout: {timeout}")
if scrb is None or semi_metric:
reset_env(env, scrb, mode='intrinsic')
else:
reset_env(env, scrb, mode='extrinsic')
obs = set_goal(env, scrb)
i = 0
env.close()
def exp1_loop(env, scrb, policy, eps_greedy, T, semi_metric, nsteps):
obs = reset_env(env, scrb, mode='intrinsic')
while len(scrb.open_slots()) > 0:
pnt = scrb.init_record(o=obs['observation'].copy())
scrb.load_new_point(pnt, d_func=policy.get_actions)
assert not scrb.dilute_overlaps
reached_goal = False
t = 0
counter = 0
times = []
radii = []
while counter < nsteps:
# 1. environment step
action, _, state, _ = policy.step(obs)
if reached_goal or (eps_greedy and t % 10 == 0):
action = env.action_space.sample()
obs, reward, done, info = env.step(action)
success = info['is_success']
reached_goal = reached_goal or success
# 2. GPI update
pnt = scrb.init_record(o=obs['observation'].copy())
scrb.load_new_point(pnt, d_func=policy.get_actions)
r_pack = env._max_episode_steps + scrb.M.min()
times.append(counter)
radii.append(r_pack)
if counter % 1000 == 0:
...
# scrb.save(message=counter)
# print(f"counter: {counter}, cover size: {scrb.current_size}, packing radius: {r_pack}")
# TODO: add back after debug
# scrb.age += 1
# 3. measure packing radius
...
# 4. episodic reset
if t % T == 0:
t = 0
reached_goal = False
if semi_metric:
reset_env(env, scrb, mode='intrinsic')
else:
reset_env(env, scrb, mode='extrinsic')
obs = set_goal(env, scrb)
counter += 1
t += 1
return times, radii
def experiment1(env, env_id, T=100, k=50, load_path=None, save_path=None, semi_metric=False, eps_greedy=False,
dilute_overlaps=True, ntrials=5, nsteps=10000, random_mode=False, **kwargs):
policy, reward_fun = paper_utils.load_policy(env_id, **kwargs)
paper_utils.load_model(load_path=load_path)
if semi_metric:
metric_str = "semi_metric"
else:
metric_str = "full_metric"
for random_mode in [True, False]:
if random_mode:
random_str = 'random'
alpha = 0
else:
random_str = 'scrb'
alpha = 0.5
log_path = f"{save_path}/{metric_str}_{random_str}"
results = dict()
k_vec = [10, 20, 30, 40, 50]
# k_vec = [50]
for k in k_vec:
results[k] = dict()
k_radii = []
for trial_idx in range(ntrials):
scrb = MetricDiversifier(k=k, vis=False, dilute_overlaps=dilute_overlaps, vis_coords=[0, 1], save_path=log_path,
reward_func=reward_fun, random_mode=random_mode)
times, radii = exp1_loop(env, scrb, policy, eps_greedy, T, semi_metric, nsteps)
k_radii.append(radii)
print(f"k: {k}, trial: {trial_idx}/{ntrials}, nsteps: {nsteps}")
results[k]["mean"] = np.asarray(k_radii).mean(axis=0)
results[k]["std"] = np.asarray(k_radii).std(axis=0)
results[k]["time"] = times
paper_utils.exp1_to_figure(results, save_directory=log_path, alpha=alpha, message=f"{metric_str}_{random_str}")
exp1_loop(env, scrb, policy, eps_greedy, T, semi_metric, 50)
paper_utils.exp1_overlayed_figure(env, scrb, save_directory=log_path, message=f"{metric_str}_{random_str}")
def exp2_loop(env, policy, models_path, epochs, ngoals, max_steps, vis=False, eps_greedy=False):
goals = [env.env.draw_goal() for _ in range(ngoals)]
recall_at_epoch = []
# epochs = paper_utils.list_epochs(models_path)
# epochs.sort()
# epochs = [epoch for epoch in epochs if epoch % 25 == 0]
# epochs = epochs[:2]
for epoch_idx in epochs:
reached = np.zeros(len(goals))
paper_utils.load_model(load_path=f"{models_path}/epoch_{epoch_idx}.model")
for gidx, goal in enumerate(goals):
if reached[gidx]:
continue
obs = reset_env(env, scrb=None, mode='intrinsic')
env.env.set_goal(goal=goal)
for t in range(max_steps):
if reached[gidx]:
break
if vis:
env.render()
time.sleep(.01)
action, _, state, _ = policy.step(obs)
if eps_greedy and t % 10 == 0:
action = env.action_space.sample()
obs, reward, done, info = env.step(action)
if info['is_success']:
reached[gidx] = 1
recall_at_epoch.append(reached.mean())
return epochs, recall_at_epoch
def experiment2(env, env_id, T=100, scrb_models_path=None, plain_models_path=None, save_path=None, eps_greedy=False, ntrials=5, ngoals=100, vis=False, **kwargs):
policy, reward_fun = paper_utils.load_policy(env_id, **kwargs)
scrb_epochs = paper_utils.list_epochs(scrb_models_path)
plain_epochs = paper_utils.list_epochs(plain_models_path)
scrb_epochs.sort()
plain_epochs.sort()
scrb_epochs = [epoch for epoch in scrb_epochs if epoch % 50 == 0]
plain_epochs = [epoch for epoch in plain_epochs if epoch % 50 == 0]
nepochs = np.minimum(len(scrb_epochs), len(plain_epochs))
epochs = scrb_epochs[:nepochs]
print(epochs)
results = dict()
for scrb in [True, False]:
if scrb:
scrb_str = 'scrb'
method_name = r'$\alpha =$' + f"{0.5}"
models_path = scrb_models_path
else:
scrb_str = 'naive'
method_name = r'$\alpha =$' + f"{0.0}"
models_path = plain_models_path
recalls = []
results[scrb_str] = dict()
for trial_idx in range(ntrials):
print(f"------------------experiment 2: trial #{trial_idx}-----------------")
epochs, recall = exp2_loop(env, policy, models_path, epochs, ngoals, max_steps=T, vis=vis, eps_greedy=eps_greedy)
recalls.append(recall)
results[scrb_str]["mean"] = np.asarray(recalls).mean(axis=0)
results[scrb_str]["std"] = np.asarray(recalls).std(axis=0)
results[scrb_str]['method_name'] = method_name
results[scrb_str]["epochs"] = epochs
paper_utils.exp3_to_figure(results, save_directory=save_path, message=f"{env_id}")
def exp3_loop(env, policy, models_path, covers_path, ngoals, max_steps, semi_metric, vis=False, eps_greedy=False):
variance_at_epoch = []
min_dists = []
hit_times = []
epochs = paper_utils.list_epochs(covers_path)
epochs.sort()
epochs = [epoch for epoch in epochs if epoch % 25 == 0]
# epochs = epochs[:2]
for epoch_idx in epochs:
model_path = f"{models_path}/epoch_{epochs[-1]}.model"
paper_utils.load_model(load_path=model_path)
cover_path = f"{covers_path}/epoch_{epoch_idx}.json"
scrb = MetricDiversifier(k=100, vis=False, vis_coords=[0, 1], save_path=None, load_model=cover_path, reward_func=None)
min_dist = scrb.M.min()
pnts = scrb.draw(ngoals, replace=False)
reached = np.zeros(len(pnts))
hit_time = [max_steps for _ in range(ngoals)]
reached_list = []
for pidx, pnt in enumerate(pnts):
goal = pnt['ag']
if reached[pidx]:
continue
if semi_metric:
obs = reset_env(env, scrb=scrb, mode='intrinsic')
else:
refidx=pidx
while refidx == pidx:
refidx = random.choice([i for i in range(len(pnts))])
refpnt = pnts[refidx]
obs = init_from_point(env, refpnt)
env.env.set_goal(goal=np.asarray(goal))
for t in range(max_steps):
if reached[pidx]:
break
if vis:
env.render()
time.sleep(.01)
action, _, state, _ = policy.step(obs)
if eps_greedy and t % 10 == 0:
action = env.action_space.sample()
obs, reward, done, info = env.step(action)
if info['is_success']:
reached[pidx] = 1
reached_list.append(goal)
hit_time[pidx] = t
if len(reached_list) == 0:
variance_at_epoch.append(0)
else:
variance_at_epoch.append(np.asarray(reached_list).std())
min_dists.append(min_dist)
hit_times.append(np.mean(hit_time))
return epochs, variance_at_epoch, min_dists, hit_times
def experiment3(env, env_id, T=100, models_path=None, covers_path=None, save_path=None, eps_greedy=False, semi_metric=False, ntrials=5, ngoals=100, vis=False, **kwargs):
policy, reward_fun = paper_utils.load_policy(env_id, **kwargs)
metric = 'mean_hit_time'
results = dict()
for scrb in [True, False]:
if not scrb:
continue
if scrb:
scrb_str = 'scrb'
method_name = r'$\alpha =$' + f"{0.5}"
else:
scrb_str = 'naive'
method_name = r'$\alpha =$' + f"{0.0}"
variances = []
min_dists = []
mean_hit_times = []
results[scrb_str] = dict()
for trial_idx in range(ntrials):
print(f"------------------experiment 3: trial #{trial_idx}-----------------")
epochs, variance, min_dist, mean_hit_time = exp3_loop(env, policy, models_path, covers_path, ngoals, semi_metric=semi_metric, max_steps=T, vis=vis, eps_greedy=eps_greedy)
variances.append(variance)
min_dists.append(min_dist)
mean_hit_times.append(mean_hit_time)
if metric == 'variance':
results[scrb_str]["mean"] = np.asarray(variances).mean(axis=0)
results[scrb_str]["std"] = np.asarray(variances).std(axis=0)
elif metric == 'min_dists':
results[scrb_str]["mean"] = np.asarray(min_dists).mean(axis=0)
results[scrb_str]["std"] = np.asarray(min_dists).std(axis=0)
elif metric == 'mean_hit_time':
results[scrb_str]["mean"] = np.asarray(mean_hit_times).mean(axis=0)
results[scrb_str]["std"] = np.asarray(mean_hit_times).std(axis=0)
results[scrb_str]['method_name'] = method_name
results[scrb_str]["epochs"] = epochs
paper_utils.exp3_to_figure(results, save_directory=save_path, message=f"{env_id}_{metric}")
def exp4_loop(env, policy, models_path, covers_path, ngoals, max_steps, semi_metric, vis=False, eps_greedy=False):
recall_at_epoch = []
hit_time_at_epoch = []
model_epochs = paper_utils.list_epochs(models_path)
cover_epochs = paper_utils.list_epochs(covers_path)
model_epochs = [epoch for epoch in model_epochs if epoch % 25 == 0]
cover_epochs = [epoch for epoch in cover_epochs if epoch % 25 == 0]
n_epochs = np.minimum(len(model_epochs), len(cover_epochs))
epochs = model_epochs[:n_epochs]
for epoch_idx in epochs:
cover_path = f"{covers_path}/epoch_{epoch_idx}.json"
scrb = MetricDiversifier(k=100, load_model=cover_path, reward_func=None)
ngoals = np.minimum(ngoals, scrb.k)
paper_utils.load_model(load_path=f"{models_path}/epoch_{epoch_idx}.model")
pnts = scrb.draw(ngoals, replace=False)
reached = np.zeros(len(pnts))
hit_time = [max_steps for _ in range(len(pnts))]
for pidx, pnt in enumerate(pnts):
goal = pnt['ag']
if reached[pidx]:
continue
if semi_metric:
obs = reset_env(env, scrb=scrb, mode='intrinsic')
else:
refidx = pidx
while refidx == pidx:
refidx = random.choice([i for i in range(len(pnts))])
refpnt = pnts[refidx]
obs = init_from_point(env, refpnt)
env.env.set_goal(goal=np.asarray(goal))
for t in range(max_steps):
if reached[pidx]:
break
if vis:
env.render()
time.sleep(.01)
action, _, state, _ = policy.step(obs)
if eps_greedy and t % 10 == 0:
action = env.action_space.sample()
obs, reward, done, info = env.step(action)
if info['is_success']:
reached[pidx] = 1
hit_time[pidx] = t
recall_at_epoch.append(reached.mean())
hit_time_at_epoch.append(np.mean(hit_time))
return epochs, recall_at_epoch, hit_time_at_epoch
def experiment4(env, env_id, T=100, models_path_a=None, models_path_b=None, covers_path_a=None, covers_path_b=None,
save_path=None, eps_greedy=False, ntrials=5, ngoals=100, vis=False, semi_metric=False, **kwargs):
policy, reward_fun = paper_utils.load_policy(env_id, **kwargs)
results = dict()
ab_recalls = []
ba_recalls = []
ab_hit_times = []
ba_hit_times = []
for metric in ['coverage', 'hit_time']:
results[f"{metric}"] = dict()
results[f"{metric}"] = dict()
for type in ["a2b", "b2a"]:
results[f"{metric}"][f"{type}"] = dict()
results[f"{metric}"][f"{type}"] = dict()
for trial_idx in range(ntrials):
print(f"------------------experiment 4: trial #{trial_idx}-----------------")
# A - > B
epochs, ab_recall, ab_hit_time = exp4_loop(env, policy, models_path_a, covers_path_b, semi_metric=semi_metric, ngoals=ngoals, max_steps=T, vis=vis, eps_greedy=eps_greedy)
ab_recalls.append(ab_recall)
ab_hit_times.append(ab_hit_time)
# B - > A
epochs, ba_recall, ba_hit_time = exp4_loop(env, policy, models_path_b, covers_path_a, semi_metric=semi_metric, ngoals=ngoals, max_steps=T, vis=vis, eps_greedy=eps_greedy)
ba_recalls.append(ba_recall)
ba_hit_times.append(ba_hit_time)
for metric in ['coverage', 'hit_time']:
if metric == 'coverage':
ab_values = ab_recalls
ba_values = ba_recalls
elif metric == 'hit_time':
ab_values = ab_hit_times
ba_values = ba_hit_times
results[metric]["a2b"]["mean"] = np.asarray(ab_values).mean(axis=0)
results[metric]["a2b"]["std"] = np.asarray(ab_values).std(axis=0)
results[metric]["a2b"]['method_name'] = r'$\alpha =$' + f"{0.0}"
results[metric]["a2b"]["epochs"] = epochs
results[metric]["b2a"]["mean"] = np.asarray(ba_values).mean(axis=0)
results[metric]["b2a"]["std"] = np.asarray(ba_values).std(axis=0)
results[metric]["b2a"]['method_name'] = r'$\alpha =$' + f"{0.5}"
results[metric]["b2a"]["epochs"] = epochs
paper_utils.exp3_to_figure(results[f"{metric}"], save_directory=save_path, message=f"{env_id}_{metric}")
if __name__ == '__main__':
arg_parser = common_arg_parser()
args, unknown_args = arg_parser.parse_known_args(sys.argv)
extra_args = parse_cmdline_kwargs(unknown_args)
environment = gym.make(args.env, **extra_args)
if extra_args['option'] == 'scan_cover':
scan_cover(environment, **extra_args)
elif extra_args['option'] == 'plain_loop':
plain_loop(environment, **extra_args)
elif extra_args['option'] == 'play_policy':
assert extra_args['load_path'] is not None
play_policy(env=environment, env_id=args.env, **extra_args)
elif extra_args['option'] == 'experiment1':
assert extra_args['load_path'] is not None, 'load path is none'
assert args.save_path is not None, 'save path is none'
experiment1(env=environment, env_id=args.env, save_path=args.save_path, **extra_args)
elif extra_args['option'] == 'experiment2':
assert extra_args['scrb_models_path'] is not None, 'models path is none'
assert extra_args['plain_models_path'] is not None, 'models path is none'
assert args.save_path is not None, 'save path is none'
experiment2(env=environment, env_id=args.env, save_path=args.save_path, **extra_args)
elif extra_args['option'] == 'experiment3':
assert extra_args['models_path'] is not None, 'models path is none'
assert extra_args['covers_path'] is not None, 'covers path is none'
assert args.save_path is not None, 'save path is none'
experiment3(env=environment, env_id=args.env, save_path=args.save_path, **extra_args)
elif extra_args['option'] == 'experiment4':
assert extra_args['models_path_a'] is not None, 'models path is none'
assert extra_args['models_path_b'] is not None, 'models path is none'
assert extra_args['covers_path_a'] is not None, 'covers path is none'
assert extra_args['covers_path_b'] is not None, 'covers path is none'
assert args.save_path is not None, 'save path is none'
experiment4(env=environment, env_id=args.env, save_path=args.save_path, **extra_args) |
import asyncio
import dataclasses
import logging
import random
import time
import traceback
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
import aiosqlite
from blspy import AugSchemeMPL
import chialite.server.ws_connection as ws # lgtm [py/import-and-import-from]
from chialite.consensus.block_creation import unfinished_block_to_full_block
from chialite.consensus.block_record import BlockRecord
from chialite.consensus.blockchain import Blockchain, ReceiveBlockResult
from chialite.consensus.constants import ConsensusConstants
from chialite.consensus.difficulty_adjustment import get_next_sub_slot_iters_and_difficulty
from chialite.consensus.make_sub_epoch_summary import next_sub_epoch_summary
from chialite.consensus.multiprocess_validation import PreValidationResult
from chialite.consensus.pot_iterations import calculate_sp_iters
from chialite.full_node.block_store import BlockStore
from chialite.full_node.bundle_tools import detect_potential_template_generator
from chialite.full_node.coin_store import CoinStore
from chialite.full_node.full_node_store import FullNodeStore
from chialite.full_node.mempool_manager import MempoolManager
from chialite.full_node.signage_point import SignagePoint
from chialite.full_node.sync_store import SyncStore
from chialite.full_node.weight_proof import WeightProofHandler
from chialite.protocols import farmer_protocol, full_node_protocol, timelord_protocol, wallet_protocol
from chialite.protocols.full_node_protocol import (
RejectBlocks,
RequestBlocks,
RespondBlock,
RespondBlocks,
RespondSignagePoint,
)
from chialite.protocols.protocol_message_types import ProtocolMessageTypes
from chialite.server.node_discovery import FullNodePeers
from chialite.server.outbound_message import Message, NodeType, make_msg
from chialite.server.server import ChialiteServer
from chialite.types.blockchain_format.classgroup import ClassgroupElement
from chialite.types.blockchain_format.pool_target import PoolTarget
from chialite.types.blockchain_format.sized_bytes import bytes32
from chialite.types.blockchain_format.sub_epoch_summary import SubEpochSummary
from chialite.types.blockchain_format.vdf import CompressibleVDFField, VDFInfo, VDFProof
from chialite.types.end_of_slot_bundle import EndOfSubSlotBundle
from chialite.types.full_block import FullBlock
from chialite.types.header_block import HeaderBlock
from chialite.types.mempool_inclusion_status import MempoolInclusionStatus
from chialite.types.spend_bundle import SpendBundle
from chialite.types.unfinished_block import UnfinishedBlock
from chialite.util.bech32m import encode_puzzle_hash
from chialite.util.db_wrapper import DBWrapper
from chialite.util.errors import ConsensusError, Err
from chialite.util.ints import uint8, uint32, uint64, uint128
from chialite.util.path import mkdir, path_from_root
from chialite.util.safe_cancel_task import cancel_task_safe
from chialite.util.profiler import profile_task
class FullNode:
block_store: BlockStore
full_node_store: FullNodeStore
full_node_peers: Optional[FullNodePeers]
sync_store: Any
coin_store: CoinStore
mempool_manager: MempoolManager
connection: aiosqlite.Connection
_sync_task: Optional[asyncio.Task]
blockchain: Blockchain
config: Dict
server: Any
log: logging.Logger
constants: ConsensusConstants
_shut_down: bool
root_path: Path
state_changed_callback: Optional[Callable]
timelord_lock: asyncio.Lock
initialized: bool
weight_proof_handler: Optional[WeightProofHandler]
def __init__(
self,
config: Dict,
root_path: Path,
consensus_constants: ConsensusConstants,
name: str = None,
):
self.initialized = False
self.root_path = root_path
self.config = config
self.server = None
self._shut_down = False # Set to true to close all infinite loops
self.constants = consensus_constants
self.pow_creation: Dict[uint32, asyncio.Event] = {}
self.state_changed_callback: Optional[Callable] = None
self.full_node_peers = None
self.sync_store = None
self.signage_point_times = [time.time() for _ in range(self.constants.NUM_SPS_SUB_SLOT)]
self.full_node_store = FullNodeStore(self.constants)
if name:
self.log = logging.getLogger(name)
else:
self.log = logging.getLogger(__name__)
db_path_replaced: str = config["database_path"].replace("CHALLENGE", config["selected_network"])
self.db_path = path_from_root(root_path, db_path_replaced)
mkdir(self.db_path.parent)
def _set_state_changed_callback(self, callback: Callable):
self.state_changed_callback = callback
async def _start(self):
self.timelord_lock = asyncio.Lock()
self.compact_vdf_lock = asyncio.Semaphore(4)
self.new_peak_lock = asyncio.Semaphore(8)
# create the store (db) and full node instance
self.connection = await aiosqlite.connect(self.db_path)
self.db_wrapper = DBWrapper(self.connection)
self.block_store = await BlockStore.create(self.db_wrapper)
self.sync_store = await SyncStore.create()
self.coin_store = await CoinStore.create(self.db_wrapper)
self.log.info("Initializing blockchain from disk")
start_time = time.time()
self.blockchain = await Blockchain.create(self.coin_store, self.block_store, self.constants)
self.mempool_manager = MempoolManager(self.coin_store, self.constants)
self.weight_proof_handler = None
asyncio.create_task(self.initialize_weight_proof())
if self.config.get("enable_profiler", False):
asyncio.create_task(profile_task(self.root_path, self.log))
self._sync_task = None
self._segment_task = None
time_taken = time.time() - start_time
if self.blockchain.get_peak() is None:
self.log.info(f"Initialized with empty blockchain time taken: {int(time_taken)}s")
else:
self.log.info(
f"Blockchain initialized to peak {self.blockchain.get_peak().header_hash} height"
f" {self.blockchain.get_peak().height}, "
f"time taken: {int(time_taken)}s"
)
pending_tx = await self.mempool_manager.new_peak(self.blockchain.get_peak())
assert len(pending_tx) == 0 # no pending transactions when starting up
peak: Optional[BlockRecord] = self.blockchain.get_peak()
self.uncompact_task = None
if peak is not None:
full_peak = await self.blockchain.get_full_peak()
await self.peak_post_processing(full_peak, peak, max(peak.height - 1, 0), None)
if self.config["send_uncompact_interval"] != 0:
sanitize_weight_proof_only = False
if "sanitize_weight_proof_only" in self.config:
sanitize_weight_proof_only = self.config["sanitize_weight_proof_only"]
assert self.config["target_uncompact_proofs"] != 0
self.uncompact_task = asyncio.create_task(
self.broadcast_uncompact_blocks(
self.config["send_uncompact_interval"],
self.config["target_uncompact_proofs"],
sanitize_weight_proof_only,
)
)
self.initialized = True
if self.full_node_peers is not None:
asyncio.create_task(self.full_node_peers.start())
async def initialize_weight_proof(self):
self.weight_proof_handler = WeightProofHandler(self.constants, self.blockchain)
peak = self.blockchain.get_peak()
if peak is not None:
await self.weight_proof_handler.create_sub_epoch_segments()
def set_server(self, server: ChialiteServer):
self.server = server
dns_servers = []
if "dns_servers" in self.config:
dns_servers = self.config["dns_servers"]
elif self.config["port"] == 8444:
# If `dns_servers` misses from the `config`, hardcode it if we're running mainnet.
dns_servers.append("dns-introducer.chialite.net")
try:
self.full_node_peers = FullNodePeers(
self.server,
self.root_path,
self.config["target_peer_count"] - self.config["target_outbound_peer_count"],
self.config["target_outbound_peer_count"],
self.config["peer_db_path"],
self.config["introducer_peer"],
dns_servers,
self.config["peer_connect_interval"],
self.log,
)
except Exception as e:
error_stack = traceback.format_exc()
self.log.error(f"Exception: {e}")
self.log.error(f"Exception in peer discovery: {e}")
self.log.error(f"Exception Stack: {error_stack}")
def _state_changed(self, change: str):
if self.state_changed_callback is not None:
self.state_changed_callback(change)
async def short_sync_batch(self, peer: ws.WSChialiteConnection, start_height: uint32, target_height: uint32) -> bool:
"""
Tries to sync to a chain which is not too far in the future, by downloading batches of blocks. If the first
block that we download is not connected to our chain, we return False and do an expensive long sync instead.
Long sync is not preferred because it requires downloading and validating a weight proof.
Args:
peer: peer to sync from
start_height: height that we should start downloading at. (Our peak is higher)
target_height: target to sync to
Returns:
False if the fork point was not found, and we need to do a long sync. True otherwise.
"""
# Don't trigger multiple batch syncs to the same peer
if (
peer.peer_node_id in self.sync_store.backtrack_syncing
and self.sync_store.backtrack_syncing[peer.peer_node_id] > 0
):
return True # Don't batch sync, we are already in progress of a backtrack sync
if peer.peer_node_id in self.sync_store.batch_syncing:
return True # Don't trigger a long sync
self.sync_store.batch_syncing.add(peer.peer_node_id)
self.log.info(f"Starting batch short sync from {start_height} to height {target_height}")
if start_height > 0:
first = await peer.request_block(full_node_protocol.RequestBlock(uint32(start_height), False))
if first is None or not isinstance(first, full_node_protocol.RespondBlock):
self.sync_store.batch_syncing.remove(peer.peer_node_id)
raise ValueError(f"Error short batch syncing, could not fetch block at height {start_height}")
if not self.blockchain.contains_block(first.block.prev_header_hash):
self.log.info("Batch syncing stopped, this is a deep chain")
self.sync_store.batch_syncing.remove(peer.peer_node_id)
# First sb not connected to our blockchain, do a long sync instead
return False
batch_size = self.constants.MAX_BLOCK_COUNT_PER_REQUESTS
if self._segment_task is not None and (not self._segment_task.done()):
try:
self._segment_task.cancel()
except Exception as e:
self.log.warning(f"failed to cancel segment task {e}")
self._segment_task = None
try:
for height in range(start_height, target_height, batch_size):
end_height = min(target_height, height + batch_size)
request = RequestBlocks(uint32(height), uint32(end_height), True)
response = await peer.request_blocks(request)
if not response:
raise ValueError(f"Error short batch syncing, invalid/no response for {height}-{end_height}")
async with self.blockchain.lock:
success, advanced_peak, fork_height = await self.receive_block_batch(response.blocks, peer, None)
if not success:
raise ValueError(f"Error short batch syncing, failed to validate blocks {height}-{end_height}")
if advanced_peak:
peak = self.blockchain.get_peak()
peak_fb: Optional[FullBlock] = await self.blockchain.get_full_peak()
assert peak is not None and peak_fb is not None and fork_height is not None
await self.peak_post_processing(peak_fb, peak, fork_height, peer)
self.log.info(f"Added blocks {height}-{end_height}")
except Exception:
self.sync_store.batch_syncing.remove(peer.peer_node_id)
raise
self.sync_store.batch_syncing.remove(peer.peer_node_id)
return True
async def short_sync_backtrack(
self, peer: ws.WSChialiteConnection, peak_height: uint32, target_height: uint32, target_unf_hash: bytes32
):
"""
Performs a backtrack sync, where blocks are downloaded one at a time from newest to oldest. If we do not
find the fork point 5 deeper than our peak, we return False and do a long sync instead.
Args:
peer: peer to sync from
peak_height: height of our peak
target_height: target height
target_unf_hash: partial hash of the unfinished block of the target
Returns:
True iff we found the fork point, and we do not need to long sync.
"""
try:
if peer.peer_node_id not in self.sync_store.backtrack_syncing:
self.sync_store.backtrack_syncing[peer.peer_node_id] = 0
self.sync_store.backtrack_syncing[peer.peer_node_id] += 1
unfinished_block: Optional[UnfinishedBlock] = self.full_node_store.get_unfinished_block(target_unf_hash)
curr_height: int = target_height
found_fork_point = False
responses = []
while curr_height > peak_height - 5:
# If we already have the unfinished block, don't fetch the transactions. In the normal case, we will
# already have the unfinished block, from when it was broadcast, so we just need to download the header,
# but not the transactions
fetch_tx: bool = unfinished_block is None or curr_height != target_height
curr = await peer.request_block(full_node_protocol.RequestBlock(uint32(curr_height), fetch_tx))
if curr is None:
raise ValueError(f"Failed to fetch block {curr_height} from {peer.get_peer_info()}, timed out")
if curr is None or not isinstance(curr, full_node_protocol.RespondBlock):
raise ValueError(
f"Failed to fetch block {curr_height} from {peer.get_peer_info()}, wrong type {type(curr)}"
)
responses.append(curr)
if self.blockchain.contains_block(curr.block.prev_header_hash) or curr_height == 0:
found_fork_point = True
break
curr_height -= 1
if found_fork_point:
for response in reversed(responses):
await self.respond_block(response, peer)
except Exception as e:
self.sync_store.backtrack_syncing[peer.peer_node_id] -= 1
raise e
self.sync_store.backtrack_syncing[peer.peer_node_id] -= 1
return found_fork_point
async def new_peak(self, request: full_node_protocol.NewPeak, peer: ws.WSChialiteConnection):
"""
We have received a notification of a new peak from a peer. This happens either when we have just connected,
or when the peer has updated their peak.
Args:
request: information about the new peak
peer: peer that sent the message
"""
# Store this peak/peer combination in case we want to sync to it, and to keep track of peers
self.sync_store.peer_has_block(request.header_hash, peer.peer_node_id, request.weight, request.height, True)
if self.blockchain.contains_block(request.header_hash):
return None
# Not interested in less heavy peaks
peak: Optional[BlockRecord] = self.blockchain.get_peak()
curr_peak_height = uint32(0) if peak is None else peak.height
if peak is not None and peak.weight > request.weight:
return None
if self.sync_store.get_sync_mode():
# If peer connects while we are syncing, check if they have the block we are syncing towards
peak_sync_hash = self.sync_store.get_sync_target_hash()
peak_sync_height = self.sync_store.get_sync_target_height()
if peak_sync_hash is not None and request.header_hash != peak_sync_hash and peak_sync_height is not None:
peak_peers: Set[bytes32] = self.sync_store.get_peers_that_have_peak([peak_sync_hash])
# Don't ask if we already know this peer has the peak
if peer.peer_node_id not in peak_peers:
target_peak_response: Optional[RespondBlock] = await peer.request_block(
full_node_protocol.RequestBlock(uint32(peak_sync_height), False), timeout=10
)
if target_peak_response is not None and isinstance(target_peak_response, RespondBlock):
self.sync_store.peer_has_block(
peak_sync_hash,
peer.peer_node_id,
target_peak_response.block.weight,
peak_sync_height,
False,
)
else:
if request.height <= curr_peak_height + self.config["short_sync_blocks_behind_threshold"]:
# This is the normal case of receiving the next block
if await self.short_sync_backtrack(
peer, curr_peak_height, request.height, request.unfinished_reward_block_hash
):
return None
if request.height < self.constants.WEIGHT_PROOF_RECENT_BLOCKS:
# This is the case of syncing up more than a few blocks, at the start of the chain
# TODO(almog): fix weight proofs so they work at the beginning as well
self.log.debug("Doing batch sync, no backup")
await self.short_sync_batch(peer, uint32(0), request.height)
return None
if request.height < curr_peak_height + self.config["sync_blocks_behind_threshold"]:
# This case of being behind but not by so much
if await self.short_sync_batch(peer, uint32(max(curr_peak_height - 6, 0)), request.height):
return None
# This is the either the case where we were not able to sync successfully (for example, due to the fork
# point being in the past), or we are very far behind. Performs a long sync.
self._sync_task = asyncio.create_task(self._sync())
async def send_peak_to_timelords(
self, peak_block: Optional[FullBlock] = None, peer: Optional[ws.WSChialiteConnection] = None
):
"""
Sends current peak to timelords
"""
if peak_block is None:
peak_block = await self.blockchain.get_full_peak()
if peak_block is not None:
peak = self.blockchain.block_record(peak_block.header_hash)
difficulty = self.blockchain.get_next_difficulty(peak.header_hash, False)
ses: Optional[SubEpochSummary] = next_sub_epoch_summary(
self.constants,
self.blockchain,
peak.required_iters,
peak_block,
True,
)
recent_rc = self.blockchain.get_recent_reward_challenges()
curr = peak
while not curr.is_challenge_block(self.constants) and not curr.first_in_sub_slot:
curr = self.blockchain.block_record(curr.prev_hash)
if curr.is_challenge_block(self.constants):
last_csb_or_eos = curr.total_iters
else:
last_csb_or_eos = curr.ip_sub_slot_total_iters(self.constants)
curr = peak
passed_ses_height_but_not_yet_included = True
while (curr.height % self.constants.SUB_EPOCH_BLOCKS) != 0:
if curr.sub_epoch_summary_included:
passed_ses_height_but_not_yet_included = False
curr = self.blockchain.block_record(curr.prev_hash)
if curr.sub_epoch_summary_included or curr.height == 0:
passed_ses_height_but_not_yet_included = False
timelord_new_peak: timelord_protocol.NewPeakTimelord = timelord_protocol.NewPeakTimelord(
peak_block.reward_chain_block,
difficulty,
peak.deficit,
peak.sub_slot_iters,
ses,
recent_rc,
last_csb_or_eos,
passed_ses_height_but_not_yet_included,
)
msg = make_msg(ProtocolMessageTypes.new_peak_timelord, timelord_new_peak)
if peer is None:
await self.server.send_to_all([msg], NodeType.TIMELORD)
else:
await self.server.send_to_specific([msg], peer.peer_node_id)
async def synced(self) -> bool:
curr: Optional[BlockRecord] = self.blockchain.get_peak()
if curr is None:
return False
while curr is not None and not curr.is_transaction_block:
curr = self.blockchain.try_block_record(curr.prev_hash)
now = time.time()
if (
curr is None
or curr.timestamp is None
or curr.timestamp < uint64(int(now - 60 * 7))
or self.sync_store.get_sync_mode()
):
return False
else:
return True
async def on_connect(self, connection: ws.WSChialiteConnection):
"""
Whenever we connect to another node / wallet, send them our current heads. Also send heads to farmers
and challenges to timelords.
"""
self._state_changed("add_connection")
self._state_changed("sync_mode")
if self.full_node_peers is not None:
asyncio.create_task(self.full_node_peers.on_connect(connection))
if self.initialized is False:
return None
if connection.connection_type is NodeType.FULL_NODE:
# Send filter to node and request mempool items that are not in it (Only if we are currently synced)
synced = await self.synced()
peak_height = self.blockchain.get_peak_height()
current_time = int(time.time())
if synced and peak_height is not None and current_time > self.constants.INITIAL_FREEZE_END_TIMESTAMP:
my_filter = self.mempool_manager.get_filter()
mempool_request = full_node_protocol.RequestMempoolTransactions(my_filter)
msg = make_msg(ProtocolMessageTypes.request_mempool_transactions, mempool_request)
await connection.send_message(msg)
peak_full: Optional[FullBlock] = await self.blockchain.get_full_peak()
if peak_full is not None:
peak: BlockRecord = self.blockchain.block_record(peak_full.header_hash)
if connection.connection_type is NodeType.FULL_NODE:
request_node = full_node_protocol.NewPeak(
peak.header_hash,
peak.height,
peak.weight,
peak.height,
peak_full.reward_chain_block.get_unfinished().get_hash(),
)
await connection.send_message(make_msg(ProtocolMessageTypes.new_peak, request_node))
elif connection.connection_type is NodeType.WALLET:
# If connected to a wallet, send the Peak
request_wallet = wallet_protocol.NewPeakWallet(
peak.header_hash,
peak.height,
peak.weight,
peak.height,
)
await connection.send_message(make_msg(ProtocolMessageTypes.new_peak_wallet, request_wallet))
elif connection.connection_type is NodeType.TIMELORD:
await self.send_peak_to_timelords()
def on_disconnect(self, connection: ws.WSChialiteConnection):
self.log.info(f"peer disconnected {connection.get_peer_info()}")
self._state_changed("close_connection")
self._state_changed("sync_mode")
if self.sync_store is not None:
self.sync_store.peer_disconnected(connection.peer_node_id)
def _num_needed_peers(self) -> int:
assert self.server is not None
assert self.server.all_connections is not None
diff = self.config["target_peer_count"] - len(self.server.all_connections)
return diff if diff >= 0 else 0
def _close(self):
self._shut_down = True
if self.blockchain is not None:
self.blockchain.shut_down()
if self.mempool_manager is not None:
self.mempool_manager.shut_down()
if self.full_node_peers is not None:
asyncio.create_task(self.full_node_peers.close())
if self.uncompact_task is not None:
self.uncompact_task.cancel()
async def _await_closed(self):
cancel_task_safe(self._sync_task, self.log)
for task_id, task in list(self.full_node_store.tx_fetch_tasks.items()):
cancel_task_safe(task, self.log)
await self.connection.close()
async def _sync(self):
"""
Performs a full sync of the blockchain up to the peak.
- Wait a few seconds for peers to send us their peaks
- Select the heaviest peak, and request a weight proof from a peer with that peak
- Validate the weight proof, and disconnect from the peer if invalid
- Find the fork point to see where to start downloading blocks
- Download blocks in batch (and in parallel) and verify them one at a time
- Disconnect peers that provide invalid blocks or don't have the blocks
"""
if self.weight_proof_handler is None:
return None
# Ensure we are only syncing once and not double calling this method
if self.sync_store.get_sync_mode():
return None
if self.sync_store.get_long_sync():
self.log.debug("already in long sync")
return None
self.sync_store.set_long_sync(True)
self.log.debug("long sync started")
try:
self.log.info("Starting to perform sync.")
self.log.info("Waiting to receive peaks from peers.")
# Wait until we have 3 peaks or up to a max of 30 seconds
peaks = []
for i in range(300):
peaks = [tup[0] for tup in self.sync_store.get_peak_of_each_peer().values()]
if len(self.sync_store.get_peers_that_have_peak(peaks)) < 3:
if self._shut_down:
return None
await asyncio.sleep(0.1)
self.log.info(f"Collected a total of {len(peaks)} peaks.")
self.sync_peers_handler = None
# Based on responses from peers about the current peaks, see which peak is the heaviest
# (similar to longest chain rule).
target_peak = self.sync_store.get_heaviest_peak()
if target_peak is None:
raise RuntimeError("Not performing sync, no peaks collected")
heaviest_peak_hash, heaviest_peak_height, heaviest_peak_weight = target_peak
self.sync_store.set_peak_target(heaviest_peak_hash, heaviest_peak_height)
self.log.info(f"Selected peak {heaviest_peak_height}, {heaviest_peak_hash}")
# Check which peers are updated to this height
peers = []
coroutines = []
for peer in self.server.all_connections.values():
if peer.connection_type == NodeType.FULL_NODE:
peers.append(peer.peer_node_id)
coroutines.append(
peer.request_block(
full_node_protocol.RequestBlock(uint32(heaviest_peak_height), True), timeout=10
)
)
for i, target_peak_response in enumerate(await asyncio.gather(*coroutines)):
if target_peak_response is not None and isinstance(target_peak_response, RespondBlock):
self.sync_store.peer_has_block(
heaviest_peak_hash, peers[i], heaviest_peak_weight, heaviest_peak_height, False
)
# TODO: disconnect from peer which gave us the heaviest_peak, if nobody has the peak
peer_ids: Set[bytes32] = self.sync_store.get_peers_that_have_peak([heaviest_peak_hash])
peers_with_peak: List = [c for c in self.server.all_connections.values() if c.peer_node_id in peer_ids]
# Request weight proof from a random peer
self.log.info(f"Total of {len(peers_with_peak)} peers with peak {heaviest_peak_height}")
weight_proof_peer = random.choice(peers_with_peak)
self.log.info(
f"Requesting weight proof from peer {weight_proof_peer.peer_host} up to height"
f" {heaviest_peak_height}"
)
if self.blockchain.get_peak() is not None and heaviest_peak_weight <= self.blockchain.get_peak().weight:
raise ValueError("Not performing sync, already caught up.")
wp_timeout = 360
if "weight_proof_timeout" in self.config:
wp_timeout = self.config["weight_proof_timeout"]
self.log.debug(f"weight proof timeout is {wp_timeout} sec")
request = full_node_protocol.RequestProofOfWeight(heaviest_peak_height, heaviest_peak_hash)
response = await weight_proof_peer.request_proof_of_weight(request, timeout=wp_timeout)
# Disconnect from this peer, because they have not behaved properly
if response is None or not isinstance(response, full_node_protocol.RespondProofOfWeight):
await weight_proof_peer.close(600)
raise RuntimeError(f"Weight proof did not arrive in time from peer: {weight_proof_peer.peer_host}")
if response.wp.recent_chain_data[-1].reward_chain_block.height != heaviest_peak_height:
await weight_proof_peer.close(600)
raise RuntimeError(f"Weight proof had the wrong height: {weight_proof_peer.peer_host}")
if response.wp.recent_chain_data[-1].reward_chain_block.weight != heaviest_peak_weight:
await weight_proof_peer.close(600)
raise RuntimeError(f"Weight proof had the wrong weight: {weight_proof_peer.peer_host}")
# dont sync to wp if local peak is heavier,
# dont ban peer, we asked for this peak
current_peak = self.blockchain.get_peak()
if current_peak is not None:
if response.wp.recent_chain_data[-1].reward_chain_block.weight <= current_peak.weight:
raise RuntimeError(f"current peak is heavier than Weight proof peek: {weight_proof_peer.peer_host}")
try:
validated, fork_point, summaries = await self.weight_proof_handler.validate_weight_proof(response.wp)
except Exception as e:
await weight_proof_peer.close(600)
raise ValueError(f"Weight proof validation threw an error {e}")
if not validated:
await weight_proof_peer.close(600)
raise ValueError("Weight proof validation failed")
self.log.info(f"Re-checked peers: total of {len(peers_with_peak)} peers with peak {heaviest_peak_height}")
self.sync_store.set_sync_mode(True)
self._state_changed("sync_mode")
# Ensures that the fork point does not change
async with self.blockchain.lock:
await self.blockchain.warmup(fork_point)
await self.sync_from_fork_point(fork_point, heaviest_peak_height, heaviest_peak_hash, summaries)
except asyncio.CancelledError:
self.log.warning("Syncing failed, CancelledError")
except Exception as e:
tb = traceback.format_exc()
self.log.error(f"Error with syncing: {type(e)}{tb}")
finally:
if self._shut_down:
return None
await self._finish_sync()
async def sync_from_fork_point(
self,
fork_point_height: int,
target_peak_sb_height: uint32,
peak_hash: bytes32,
summaries: List[SubEpochSummary],
):
self.log.info(f"Start syncing from fork point at {fork_point_height} up to {target_peak_sb_height}")
peer_ids: Set[bytes32] = self.sync_store.get_peers_that_have_peak([peak_hash])
peers_with_peak: List = [c for c in self.server.all_connections.values() if c.peer_node_id in peer_ids]
if len(peers_with_peak) == 0:
raise RuntimeError(f"Not syncing, no peers with header_hash {peak_hash} ")
advanced_peak = False
batch_size = self.constants.MAX_BLOCK_COUNT_PER_REQUESTS
our_peak_height = self.blockchain.get_peak_height()
ses_heigths = self.blockchain.get_ses_heights()
if len(ses_heigths) > 2 and our_peak_height is not None:
ses_heigths.sort()
max_fork_ses_height = ses_heigths[-3]
# This is fork point in SES in case where fork was not detected
if self.blockchain.get_peak_height() is not None and fork_point_height == max_fork_ses_height:
for peer in peers_with_peak:
# Grab a block at peak + 1 and check if fork point is actually our current height
block_response: Optional[Any] = await peer.request_block(
full_node_protocol.RequestBlock(uint32(our_peak_height + 1), True)
)
if block_response is not None and isinstance(block_response, full_node_protocol.RespondBlock):
peak = self.blockchain.get_peak()
if peak is not None and block_response.block.prev_header_hash == peak.header_hash:
fork_point_height = our_peak_height
break
for i in range(fork_point_height, target_peak_sb_height, batch_size):
start_height = i
end_height = min(target_peak_sb_height, start_height + batch_size)
request = RequestBlocks(uint32(start_height), uint32(end_height), True)
self.log.info(f"Requesting blocks: {start_height} to {end_height}")
batch_added = False
to_remove = []
for peer in peers_with_peak:
if peer.closed:
to_remove.append(peer)
continue
response = await peer.request_blocks(request, timeout=60)
if response is None:
await peer.close()
to_remove.append(peer)
continue
if isinstance(response, RejectBlocks):
to_remove.append(peer)
continue
elif isinstance(response, RespondBlocks):
success, advanced_peak, _ = await self.receive_block_batch(
response.blocks, peer, None if advanced_peak else uint32(fork_point_height), summaries
)
if success is False:
await peer.close(600)
continue
else:
batch_added = True
break
peak = self.blockchain.get_peak()
assert peak is not None
msg = make_msg(
ProtocolMessageTypes.new_peak_wallet,
wallet_protocol.NewPeakWallet(
peak.header_hash,
peak.height,
peak.weight,
uint32(max(peak.height - 1, uint32(0))),
),
)
await self.server.send_to_all([msg], NodeType.WALLET)
for peer in to_remove:
peers_with_peak.remove(peer)
if self.sync_store.peers_changed.is_set():
peer_ids = self.sync_store.get_peers_that_have_peak([peak_hash])
peers_with_peak = [c for c in self.server.all_connections.values() if c.peer_node_id in peer_ids]
self.log.info(f"Number of peers we are syncing from: {len(peers_with_peak)}")
self.sync_store.peers_changed.clear()
if batch_added is False:
self.log.info(f"Failed to fetch blocks {start_height} to {end_height} from peers: {peers_with_peak}")
break
else:
self.log.info(f"Added blocks {start_height} to {end_height}")
self.blockchain.clean_block_record(
min(
end_height - self.constants.BLOCKS_CACHE_SIZE,
peak.height - self.constants.BLOCKS_CACHE_SIZE,
)
)
async def receive_block_batch(
self,
all_blocks: List[FullBlock],
peer: ws.WSChialiteConnection,
fork_point: Optional[uint32],
wp_summaries: Optional[List[SubEpochSummary]] = None,
) -> Tuple[bool, bool, Optional[uint32]]:
advanced_peak = False
fork_height: Optional[uint32] = uint32(0)
blocks_to_validate: List[FullBlock] = []
for i, block in enumerate(all_blocks):
if not self.blockchain.contains_block(block.header_hash):
blocks_to_validate = all_blocks[i:]
break
if len(blocks_to_validate) == 0:
return True, False, fork_height
pre_validate_start = time.time()
pre_validation_results: Optional[
List[PreValidationResult]
] = await self.blockchain.pre_validate_blocks_multiprocessing(blocks_to_validate, {})
self.log.debug(f"Block pre-validation time: {time.time() - pre_validate_start}")
if pre_validation_results is None:
return False, False, None
for i, block in enumerate(blocks_to_validate):
if pre_validation_results[i].error is not None:
self.log.error(
f"Invalid block from peer: {peer.get_peer_info()} {Err(pre_validation_results[i].error)}"
)
return False, advanced_peak, fork_height
for i, block in enumerate(blocks_to_validate):
assert pre_validation_results[i].required_iters is not None
(result, error, fork_height,) = await self.blockchain.receive_block(
block, pre_validation_results[i], None if advanced_peak else fork_point, wp_summaries
)
if result == ReceiveBlockResult.NEW_PEAK:
advanced_peak = True
elif result == ReceiveBlockResult.INVALID_BLOCK or result == ReceiveBlockResult.DISCONNECTED_BLOCK:
if error is not None:
self.log.error(f"Error: {error}, Invalid block from peer: {peer.get_peer_info()} ")
return False, advanced_peak, fork_height
block_record = self.blockchain.block_record(block.header_hash)
if block_record.sub_epoch_summary_included is not None:
if self.weight_proof_handler is not None:
await self.weight_proof_handler.create_prev_sub_epoch_segments()
if advanced_peak:
self._state_changed("new_peak")
self.log.debug(
f"Total time for {len(blocks_to_validate)} blocks: {time.time() - pre_validate_start}, "
f"advanced: {advanced_peak}"
)
return True, advanced_peak, fork_height
async def _finish_sync(self):
"""
Finalize sync by setting sync mode to False, clearing all sync information, and adding any final
blocks that we have finalized recently.
"""
self.log.info("long sync done")
self.sync_store.set_long_sync(False)
self.sync_store.set_sync_mode(False)
self._state_changed("sync_mode")
if self.server is None:
return None
peak: Optional[BlockRecord] = self.blockchain.get_peak()
async with self.blockchain.lock:
await self.sync_store.clear_sync_info()
peak_fb: FullBlock = await self.blockchain.get_full_peak()
if peak is not None:
await self.peak_post_processing(peak_fb, peak, peak.height - 1, None)
if peak is not None and self.weight_proof_handler is not None:
await self.weight_proof_handler.get_proof_of_weight(peak.header_hash)
self._state_changed("block")
def has_valid_pool_sig(self, block: Union[UnfinishedBlock, FullBlock]):
if (
block.foliage.foliage_block_data.pool_target
== PoolTarget(self.constants.GENESIS_PRE_FARM_POOL_PUZZLE_HASH, uint32(0))
and block.foliage.prev_block_hash != self.constants.GENESIS_CHALLENGE
and block.reward_chain_block.proof_of_space.pool_public_key is not None
):
if not AugSchemeMPL.verify(
block.reward_chain_block.proof_of_space.pool_public_key,
bytes(block.foliage.foliage_block_data.pool_target),
block.foliage.foliage_block_data.pool_signature,
):
return False
return True
async def signage_point_post_processing(
self,
request: full_node_protocol.RespondSignagePoint,
peer: ws.WSChialiteConnection,
ip_sub_slot: Optional[EndOfSubSlotBundle],
):
self.log.info(
f"⏲️ Finished signage point {request.index_from_challenge}/"
f"{self.constants.NUM_SPS_SUB_SLOT}: "
f"CC: {request.challenge_chain_vdf.output.get_hash()} "
f"RC: {request.reward_chain_vdf.output.get_hash()} "
)
self.signage_point_times[request.index_from_challenge] = time.time()
sub_slot_tuple = self.full_node_store.get_sub_slot(request.challenge_chain_vdf.challenge)
if sub_slot_tuple is not None:
prev_challenge = sub_slot_tuple[0].challenge_chain.challenge_chain_end_of_slot_vdf.challenge
else:
prev_challenge = None
# Notify nodes of the new signage point
broadcast = full_node_protocol.NewSignagePointOrEndOfSubSlot(
prev_challenge,
request.challenge_chain_vdf.challenge,
request.index_from_challenge,
request.reward_chain_vdf.challenge,
)
msg = make_msg(ProtocolMessageTypes.new_signage_point_or_end_of_sub_slot, broadcast)
await self.server.send_to_all_except([msg], NodeType.FULL_NODE, peer.peer_node_id)
peak = self.blockchain.get_peak()
if peak is not None and peak.height > self.constants.MAX_SUB_SLOT_BLOCKS:
sub_slot_iters = peak.sub_slot_iters
difficulty = uint64(peak.weight - self.blockchain.block_record(peak.prev_hash).weight)
# Makes sure to potentially update the difficulty if we are past the peak (into a new sub-slot)
assert ip_sub_slot is not None
if request.challenge_chain_vdf.challenge != ip_sub_slot.challenge_chain.get_hash():
next_difficulty = self.blockchain.get_next_difficulty(peak.header_hash, True)
next_sub_slot_iters = self.blockchain.get_next_slot_iters(peak.header_hash, True)
difficulty = next_difficulty
sub_slot_iters = next_sub_slot_iters
else:
difficulty = self.constants.DIFFICULTY_STARTING
sub_slot_iters = self.constants.SUB_SLOT_ITERS_STARTING
# Notify farmers of the new signage point
broadcast_farmer = farmer_protocol.NewSignagePoint(
request.challenge_chain_vdf.challenge,
request.challenge_chain_vdf.output.get_hash(),
request.reward_chain_vdf.output.get_hash(),
difficulty,
sub_slot_iters,
request.index_from_challenge,
)
msg = make_msg(ProtocolMessageTypes.new_signage_point, broadcast_farmer)
await self.server.send_to_all([msg], NodeType.FARMER)
async def peak_post_processing(
self, block: FullBlock, record: BlockRecord, fork_height: uint32, peer: Optional[ws.WSChialiteConnection]
):
"""
Must be called under self.blockchain.lock. This updates the internal state of the full node with the
latest peak information. It also notifies peers about the new peak.
"""
difficulty = self.blockchain.get_next_difficulty(record.header_hash, False)
sub_slot_iters = self.blockchain.get_next_slot_iters(record.header_hash, False)
self.log.info(
f"🌱 Updated peak to height {record.height}, weight {record.weight}, "
f"hh {record.header_hash}, "
f"forked at {fork_height}, rh: {record.reward_infusion_new_challenge}, "
f"total iters: {record.total_iters}, "
f"overflow: {record.overflow}, "
f"deficit: {record.deficit}, "
f"difficulty: {difficulty}, "
f"sub slot iters: {sub_slot_iters}, "
f"Generator size: "
f"{len(bytes(block.transactions_generator)) if block.transactions_generator else "No tx"}, "
f"Generator ref list size: "
f"{len(block.transactions_generator_ref_list) if block.transactions_generator else "No tx"}"
)
sub_slots = await self.blockchain.get_sp_and_ip_sub_slots(record.header_hash)
assert sub_slots is not None
if not self.sync_store.get_sync_mode():
self.blockchain.clean_block_records()
fork_block: Optional[BlockRecord] = None
if fork_height != block.height - 1 and block.height != 0:
# This is a reorg
fork_block = self.blockchain.block_record(self.blockchain.height_to_hash(fork_height))
added_eos, new_sps, new_ips = self.full_node_store.new_peak(
record,
block,
sub_slots[0],
sub_slots[1],
fork_block,
self.blockchain,
)
if sub_slots[1] is None:
assert record.ip_sub_slot_total_iters(self.constants) == 0
# Ensure the signage point is also in the store, for consistency
self.full_node_store.new_signage_point(
record.signage_point_index,
self.blockchain,
record,
record.sub_slot_iters,
SignagePoint(
block.reward_chain_block.challenge_chain_sp_vdf,
block.challenge_chain_sp_proof,
block.reward_chain_block.reward_chain_sp_vdf,
block.reward_chain_sp_proof,
),
skip_vdf_validation=True,
)
# Update the mempool (returns successful pending transactions added to the mempool)
for bundle, result, spend_name in await self.mempool_manager.new_peak(self.blockchain.get_peak()):
self.log.debug(f"Added transaction to mempool: {spend_name}")
mempool_item = self.mempool_manager.get_mempool_item(spend_name)
assert mempool_item is not None
fees = mempool_item.fee
assert fees >= 0
assert mempool_item.cost is not None
new_tx = full_node_protocol.NewTransaction(
spend_name,
mempool_item.cost,
uint64(bundle.fees()),
)
msg = make_msg(ProtocolMessageTypes.new_transaction, new_tx)
await self.server.send_to_all([msg], NodeType.FULL_NODE)
# If there were pending end of slots that happen after this peak, broadcast them if they are added
if added_eos is not None:
broadcast = full_node_protocol.NewSignagePointOrEndOfSubSlot(
added_eos.challenge_chain.challenge_chain_end_of_slot_vdf.challenge,
added_eos.challenge_chain.get_hash(),
uint8(0),
added_eos.reward_chain.end_of_slot_vdf.challenge,
)
msg = make_msg(ProtocolMessageTypes.new_signage_point_or_end_of_sub_slot, broadcast)
await self.server.send_to_all([msg], NodeType.FULL_NODE)
if new_sps is not None and peer is not None:
for index, sp in new_sps:
assert (
sp.cc_vdf is not None
and sp.cc_proof is not None
and sp.rc_vdf is not None
and sp.rc_proof is not None
)
await self.signage_point_post_processing(
RespondSignagePoint(index, sp.cc_vdf, sp.cc_proof, sp.rc_vdf, sp.rc_proof), peer, sub_slots[1]
)
# TODO: maybe add and broadcast new IPs as well
if record.height % 1000 == 0:
# Occasionally clear data in full node store to keep memory usage small
self.full_node_store.clear_seen_unfinished_blocks()
self.full_node_store.clear_old_cache_entries()
if self.sync_store.get_sync_mode() is False:
await self.send_peak_to_timelords(block)
# Tell full nodes about the new peak
msg = make_msg(
ProtocolMessageTypes.new_peak,
full_node_protocol.NewPeak(
record.header_hash,
record.height,
record.weight,
fork_height,
block.reward_chain_block.get_unfinished().get_hash(),
),
)
if peer is not None:
await self.server.send_to_all_except([msg], NodeType.FULL_NODE, peer.peer_node_id)
else:
await self.server.send_to_all([msg], NodeType.FULL_NODE)
# Tell wallets about the new peak
msg = make_msg(
ProtocolMessageTypes.new_peak_wallet,
wallet_protocol.NewPeakWallet(
record.header_hash,
record.height,
record.weight,
fork_height,
),
)
await self.server.send_to_all([msg], NodeType.WALLET)
# Check if we detected a spent transaction, to load up our generator cache
if block.transactions_generator is not None and self.full_node_store.previous_generator is None:
generator_arg = detect_potential_template_generator(block.height, block.transactions_generator)
if generator_arg:
self.log.info(f"Saving previous generator for height {block.height}")
self.full_node_store.previous_generator = generator_arg
self._state_changed("new_peak")
async def respond_block(
self,
respond_block: full_node_protocol.RespondBlock,
peer: Optional[ws.WSChialiteConnection] = None,
) -> Optional[Message]:
"""
Receive a full block from a peer full node (or ourselves).
"""
block: FullBlock = respond_block.block
if self.sync_store.get_sync_mode():
return None
# Adds the block to seen, and check if it's seen before (which means header is in memory)
header_hash = block.header_hash
if self.blockchain.contains_block(header_hash):
return None
pre_validation_result: Optional[PreValidationResult] = None
if (
block.is_transaction_block()
and block.transactions_info is not None
and block.transactions_info.generator_root != bytes([0] * 32)
and block.transactions_generator is None
):
# This is the case where we already had the unfinished block, and asked for this block without
# the transactions (since we already had them). Therefore, here we add the transactions.
unfinished_rh: bytes32 = block.reward_chain_block.get_unfinished().get_hash()
unf_block: Optional[UnfinishedBlock] = self.full_node_store.get_unfinished_block(unfinished_rh)
if (
unf_block is not None
and unf_block.transactions_generator is not None
and unf_block.foliage_transaction_block == block.foliage_transaction_block
):
pre_validation_result = self.full_node_store.get_unfinished_block_result(unfinished_rh)
assert pre_validation_result is not None
block = dataclasses.replace(
block,
transactions_generator=unf_block.transactions_generator,
transactions_generator_ref_list=unf_block.transactions_generator_ref_list,
)
else:
# We still do not have the correct information for this block, perhaps there is a duplicate block
# with the same unfinished block hash in the cache, so we need to fetch the correct one
if peer is None:
return None
block_response: Optional[Any] = await peer.request_block(
full_node_protocol.RequestBlock(block.height, True)
)
if block_response is None or not isinstance(block_response, full_node_protocol.RespondBlock):
self.log.warning(
f"Was not able to fetch the correct block for height {block.height} {block_response}"
)
return None
new_block: FullBlock = block_response.block
if new_block.foliage_transaction_block != block.foliage_transaction_block:
self.log.warning(f"Received the wrong block for height {block.height} {new_block.header_hash}")
return None
assert new_block.transactions_generator is not None
self.log.debug(
f"Wrong info in the cache for bh {new_block.header_hash}, there might be multiple blocks from the "
f"same farmer with the same pospace."
)
# This recursion ends here, we cannot recurse again because transactions_generator is not None
return await self.respond_block(block_response, peer)
async with self.blockchain.lock:
# After acquiring the lock, check again, because another asyncio thread might have added it
if self.blockchain.contains_block(header_hash):
return None
validation_start = time.time()
# Tries to add the block to the blockchain, if we already validated transactions, don't do it again
npc_results = {}
if pre_validation_result is not None and pre_validation_result.npc_result is not None:
npc_results[block.height] = pre_validation_result.npc_result
pre_validation_results: Optional[
List[PreValidationResult]
] = await self.blockchain.pre_validate_blocks_multiprocessing([block], npc_results)
if pre_validation_results is None:
raise ValueError(f"Failed to validate block {header_hash} height {block.height}")
if pre_validation_results[0].error is not None:
if Err(pre_validation_results[0].error) == Err.INVALID_PREV_BLOCK_HASH:
added: ReceiveBlockResult = ReceiveBlockResult.DISCONNECTED_BLOCK
error_code: Optional[Err] = Err.INVALID_PREV_BLOCK_HASH
fork_height: Optional[uint32] = None
else:
raise ValueError(
f"Failed to validate block {header_hash} height "
f"{block.height}: {Err(pre_validation_results[0].error).name}"
)
else:
result_to_validate = (
pre_validation_results[0] if pre_validation_result is None else pre_validation_result
)
assert result_to_validate.required_iters == pre_validation_results[0].required_iters
added, error_code, fork_height = await self.blockchain.receive_block(block, result_to_validate, None)
if (
self.full_node_store.previous_generator is not None
and fork_height is not None
and fork_height < self.full_node_store.previous_generator.block_height
):
self.full_node_store.previous_generator = None
validation_time = time.time() - validation_start
if added == ReceiveBlockResult.ALREADY_HAVE_BLOCK:
return None
elif added == ReceiveBlockResult.INVALID_BLOCK:
assert error_code is not None
self.log.error(f"Block {header_hash} at height {block.height} is invalid with code {error_code}.")
raise ConsensusError(error_code, header_hash)
elif added == ReceiveBlockResult.DISCONNECTED_BLOCK:
self.log.info(f"Disconnected block {header_hash} at height {block.height}")
return None
elif added == ReceiveBlockResult.NEW_PEAK:
# Only propagate blocks which extend the blockchain (becomes one of the heads)
new_peak: Optional[BlockRecord] = self.blockchain.get_peak()
assert new_peak is not None and fork_height is not None
await self.peak_post_processing(block, new_peak, fork_height, peer)
elif added == ReceiveBlockResult.ADDED_AS_ORPHAN:
self.log.info(
f"Received orphan block of height {block.height} rh " f"{block.reward_chain_block.get_hash()}"
)
else:
# Should never reach here, all the cases are covered
raise RuntimeError(f"Invalid result from receive_block {added}")
percent_full_str = (
(
", percent full: "
+ str(round(100.0 * float(block.transactions_info.cost) / self.constants.MAX_BLOCK_COST_CLVM, 3))
+ "%"
)
if block.transactions_info is not None
else ""
)
self.log.info(
f"Block validation time: {validation_time}, "
f"cost: {block.transactions_info.cost if block.transactions_info is not None else "None"}"
f"{percent_full_str}"
)
# This code path is reached if added == ADDED_AS_ORPHAN or NEW_TIP
peak = self.blockchain.get_peak()
assert peak is not None
# Removes all temporary data for old blocks
clear_height = uint32(max(0, peak.height - 50))
self.full_node_store.clear_candidate_blocks_below(clear_height)
self.full_node_store.clear_unfinished_blocks_below(clear_height)
if peak.height % 1000 == 0 and not self.sync_store.get_sync_mode():
await self.sync_store.clear_sync_info() # Occasionally clear sync peer info
self._state_changed("block")
record = self.blockchain.block_record(block.header_hash)
if self.weight_proof_handler is not None and record.sub_epoch_summary_included is not None:
if self._segment_task is None or self._segment_task.done():
self._segment_task = asyncio.create_task(self.weight_proof_handler.create_prev_sub_epoch_segments())
return None
async def respond_unfinished_block(
self,
respond_unfinished_block: full_node_protocol.RespondUnfinishedBlock,
peer: Optional[ws.WSChialiteConnection],
farmed_block: bool = False,
):
"""
We have received an unfinished block, either created by us, or from another peer.
We can validate it and if it's a good block, propagate it to other peers and
timelords.
"""
block = respond_unfinished_block.unfinished_block
if block.prev_header_hash != self.constants.GENESIS_CHALLENGE and not self.blockchain.contains_block(
block.prev_header_hash
):
# No need to request the parent, since the peer will send it to us anyway, via NewPeak
self.log.debug("Received a disconnected unfinished block")
return None
# Adds the unfinished block to seen, and check if it's seen before, to prevent
# processing it twice. This searches for the exact version of the unfinished block (there can be many different
# foliages for the same trunk). This is intentional, to prevent DOS attacks.
# Note that it does not require that this block was successfully processed
if self.full_node_store.seen_unfinished_block(block.get_hash()):
return None
block_hash = block.reward_chain_block.get_hash()
# This searched for the trunk hash (unfinished reward hash). If we have already added a block with the same
# hash, return
if self.full_node_store.get_unfinished_block(block_hash) is not None:
return None
peak: Optional[BlockRecord] = self.blockchain.get_peak()
if peak is not None:
if block.total_iters < peak.sp_total_iters(self.constants):
# This means this unfinished block is pretty far behind, it will not add weight to our chain
return None
if block.prev_header_hash == self.constants.GENESIS_CHALLENGE:
prev_b = None
else:
prev_b = self.blockchain.block_record(block.prev_header_hash)
# Count the blocks in sub slot, and check if it's a new epoch
if len(block.finished_sub_slots) > 0:
num_blocks_in_ss = 1 # Curr
else:
curr = self.blockchain.try_block_record(block.prev_header_hash)
num_blocks_in_ss = 2 # Curr and prev
while (curr is not None) and not curr.first_in_sub_slot:
curr = self.blockchain.try_block_record(curr.prev_hash)
num_blocks_in_ss += 1
if num_blocks_in_ss > self.constants.MAX_SUB_SLOT_BLOCKS:
# TODO: potentially allow overflow blocks here, which count for the next slot
self.log.warning("Too many blocks added, not adding block")
return None
async with self.blockchain.lock:
# TODO: pre-validate VDFs outside of lock
validation_start = time.time()
validate_result = await self.blockchain.validate_unfinished_block(block)
if validate_result.error is not None:
if validate_result.error == Err.COIN_AMOUNT_NEGATIVE.value:
# TODO: remove in the future, hotfix for 1.1.5 peers to not disconnect older peers
self.log.info(f"Consensus error {validate_result.error}, not disconnecting")
return
raise ConsensusError(Err(validate_result.error))
validation_time = time.time() - validation_start
assert validate_result.required_iters is not None
# Perform another check, in case we have already concurrently added the same unfinished block
if self.full_node_store.get_unfinished_block(block_hash) is not None:
return None
if block.prev_header_hash == self.constants.GENESIS_CHALLENGE:
height = uint32(0)
else:
height = uint32(self.blockchain.block_record(block.prev_header_hash).height + 1)
ses: Optional[SubEpochSummary] = next_sub_epoch_summary(
self.constants,
self.blockchain,
validate_result.required_iters,
block,
True,
)
self.full_node_store.add_unfinished_block(height, block, validate_result)
if farmed_block is True:
self.log.info(
f"🍀 ️Farmed unfinished_block {block_hash}, SP: {block.reward_chain_block.signage_point_index}, "
f"validation time: {validation_time}, "
f"cost: {block.transactions_info.cost if block.transactions_info else "None"}"
)
else:
percent_full_str = (
(
", percent full: "
+ str(round(100.0 * float(block.transactions_info.cost) / self.constants.MAX_BLOCK_COST_CLVM, 3))
+ "%"
)
if block.transactions_info is not None
else ""
)
self.log.info(
f"Added unfinished_block {block_hash}, not farmed by us,"
f" SP: {block.reward_chain_block.signage_point_index} farmer response time: "
f"{time.time() - self.signage_point_times[block.reward_chain_block.signage_point_index]}, "
f"Pool pk {encode_puzzle_hash(block.foliage.foliage_block_data.pool_target.puzzle_hash, "xsh")}, "
f"validation time: {validation_time}, "
f"cost: {block.transactions_info.cost if block.transactions_info else "None"}"
f"{percent_full_str}"
)
sub_slot_iters, difficulty = get_next_sub_slot_iters_and_difficulty(
self.constants,
len(block.finished_sub_slots) > 0,
prev_b,
self.blockchain,
)
if block.reward_chain_block.signage_point_index == 0:
res = self.full_node_store.get_sub_slot(block.reward_chain_block.pos_ss_cc_challenge_hash)
if res is None:
if block.reward_chain_block.pos_ss_cc_challenge_hash == self.constants.GENESIS_CHALLENGE:
rc_prev = self.constants.GENESIS_CHALLENGE
else:
self.log.warning(f"Do not have sub slot {block.reward_chain_block.pos_ss_cc_challenge_hash}")
return None
else:
rc_prev = res[0].reward_chain.get_hash()
else:
assert block.reward_chain_block.reward_chain_sp_vdf is not None
rc_prev = block.reward_chain_block.reward_chain_sp_vdf.challenge
timelord_request = timelord_protocol.NewUnfinishedBlockTimelord(
block.reward_chain_block,
difficulty,
sub_slot_iters,
block.foliage,
ses,
rc_prev,
)
timelord_msg = make_msg(ProtocolMessageTypes.new_unfinished_block_timelord, timelord_request)
await self.server.send_to_all([timelord_msg], NodeType.TIMELORD)
full_node_request = full_node_protocol.NewUnfinishedBlock(block.reward_chain_block.get_hash())
msg = make_msg(ProtocolMessageTypes.new_unfinished_block, full_node_request)
if peer is not None:
await self.server.send_to_all_except([msg], NodeType.FULL_NODE, peer.peer_node_id)
else:
await self.server.send_to_all([msg], NodeType.FULL_NODE)
self._state_changed("unfinished_block")
async def new_infusion_point_vdf(
self, request: timelord_protocol.NewInfusionPointVDF, timelord_peer: Optional[ws.WSChialiteConnection] = None
) -> Optional[Message]:
# Lookup unfinished blocks
unfinished_block: Optional[UnfinishedBlock] = self.full_node_store.get_unfinished_block(
request.unfinished_reward_hash
)
if unfinished_block is None:
self.log.warning(
f"Do not have unfinished reward chain block {request.unfinished_reward_hash}, cannot finish."
)
return None
prev_b: Optional[BlockRecord] = None
target_rc_hash = request.reward_chain_ip_vdf.challenge
last_slot_cc_hash = request.challenge_chain_ip_vdf.challenge
# Backtracks through end of slot objects, should work for multiple empty sub slots
for eos, _, _ in reversed(self.full_node_store.finished_sub_slots):
if eos is not None and eos.reward_chain.get_hash() == target_rc_hash:
target_rc_hash = eos.reward_chain.end_of_slot_vdf.challenge
if target_rc_hash == self.constants.GENESIS_CHALLENGE:
prev_b = None
else:
# Find the prev block, starts looking backwards from the peak. target_rc_hash must be the hash of a block
# and not an end of slot (since we just looked through the slots and backtracked)
curr: Optional[BlockRecord] = self.blockchain.get_peak()
for _ in range(10):
if curr is None:
break
if curr.reward_infusion_new_challenge == target_rc_hash:
# Found our prev block
prev_b = curr
break
curr = self.blockchain.try_block_record(curr.prev_hash)
# If not found, cache keyed on prev block
if prev_b is None:
self.full_node_store.add_to_future_ip(request)
self.log.warning(f"Previous block is None, infusion point {request.reward_chain_ip_vdf.challenge}")
return None
finished_sub_slots: Optional[List[EndOfSubSlotBundle]] = self.full_node_store.get_finished_sub_slots(
self.blockchain,
prev_b,
last_slot_cc_hash,
)
if finished_sub_slots is None:
return None
sub_slot_iters, difficulty = get_next_sub_slot_iters_and_difficulty(
self.constants,
len(finished_sub_slots) > 0,
prev_b,
self.blockchain,
)
if unfinished_block.reward_chain_block.pos_ss_cc_challenge_hash == self.constants.GENESIS_CHALLENGE:
sub_slot_start_iters = uint128(0)
else:
ss_res = self.full_node_store.get_sub_slot(unfinished_block.reward_chain_block.pos_ss_cc_challenge_hash)
if ss_res is None:
self.log.warning(f"Do not have sub slot {unfinished_block.reward_chain_block.pos_ss_cc_challenge_hash}")
return None
_, _, sub_slot_start_iters = ss_res
sp_total_iters = uint128(
sub_slot_start_iters
+ calculate_sp_iters(
self.constants,
sub_slot_iters,
unfinished_block.reward_chain_block.signage_point_index,
)
)
block: FullBlock = unfinished_block_to_full_block(
unfinished_block,
request.challenge_chain_ip_vdf,
request.challenge_chain_ip_proof,
request.reward_chain_ip_vdf,
request.reward_chain_ip_proof,
request.infused_challenge_chain_ip_vdf,
request.infused_challenge_chain_ip_proof,
finished_sub_slots,
prev_b,
self.blockchain,
sp_total_iters,
difficulty,
)
if not self.has_valid_pool_sig(block):
self.log.warning("Trying to make a pre-farm block but height is not 0")
return None
try:
await self.respond_block(full_node_protocol.RespondBlock(block))
except Exception as e:
self.log.warning(f"Consensus error validating block: {e}")
if timelord_peer is not None:
# Only sends to the timelord who sent us this VDF, to reset them to the correct peak
await self.send_peak_to_timelords(peer=timelord_peer)
return None
async def respond_end_of_sub_slot(
self, request: full_node_protocol.RespondEndOfSubSlot, peer: ws.WSChialiteConnection
) -> Tuple[Optional[Message], bool]:
fetched_ss = self.full_node_store.get_sub_slot(request.end_of_slot_bundle.challenge_chain.get_hash())
if fetched_ss is not None:
# Already have the sub-slot
return None, True
async with self.timelord_lock:
fetched_ss = self.full_node_store.get_sub_slot(
request.end_of_slot_bundle.challenge_chain.challenge_chain_end_of_slot_vdf.challenge
)
if (
(fetched_ss is None)
and request.end_of_slot_bundle.challenge_chain.challenge_chain_end_of_slot_vdf.challenge
!= self.constants.GENESIS_CHALLENGE
):
# If we don't have the prev, request the prev instead
full_node_request = full_node_protocol.RequestSignagePointOrEndOfSubSlot(
request.end_of_slot_bundle.challenge_chain.challenge_chain_end_of_slot_vdf.challenge,
uint8(0),
bytes([0] * 32),
)
return (
make_msg(ProtocolMessageTypes.request_signage_point_or_end_of_sub_slot, full_node_request),
False,
)
peak = self.blockchain.get_peak()
if peak is not None and peak.height > 2:
next_sub_slot_iters = self.blockchain.get_next_slot_iters(peak.header_hash, True)
next_difficulty = self.blockchain.get_next_difficulty(peak.header_hash, True)
else:
next_sub_slot_iters = self.constants.SUB_SLOT_ITERS_STARTING
next_difficulty = self.constants.DIFFICULTY_STARTING
# Adds the sub slot and potentially get new infusions
new_infusions = self.full_node_store.new_finished_sub_slot(
request.end_of_slot_bundle,
self.blockchain,
peak,
await self.blockchain.get_full_peak(),
)
# It may be an empty list, even if it's not None. Not None means added successfully
if new_infusions is not None:
self.log.info(
f"⏲️ Finished sub slot, SP {self.constants.NUM_SPS_SUB_SLOT}/{self.constants.NUM_SPS_SUB_SLOT}, "
f"{request.end_of_slot_bundle.challenge_chain.get_hash()}, "
f"number of sub-slots: {len(self.full_node_store.finished_sub_slots)}, "
f"RC hash: {request.end_of_slot_bundle.reward_chain.get_hash()}, "
f"Deficit {request.end_of_slot_bundle.reward_chain.deficit}"
)
# Notify full nodes of the new sub-slot
broadcast = full_node_protocol.NewSignagePointOrEndOfSubSlot(
request.end_of_slot_bundle.challenge_chain.challenge_chain_end_of_slot_vdf.challenge,
request.end_of_slot_bundle.challenge_chain.get_hash(),
uint8(0),
request.end_of_slot_bundle.reward_chain.end_of_slot_vdf.challenge,
)
msg = make_msg(ProtocolMessageTypes.new_signage_point_or_end_of_sub_slot, broadcast)
await self.server.send_to_all_except([msg], NodeType.FULL_NODE, peer.peer_node_id)
for infusion in new_infusions:
await self.new_infusion_point_vdf(infusion)
# Notify farmers of the new sub-slot
broadcast_farmer = farmer_protocol.NewSignagePoint(
request.end_of_slot_bundle.challenge_chain.get_hash(),
request.end_of_slot_bundle.challenge_chain.get_hash(),
request.end_of_slot_bundle.reward_chain.get_hash(),
next_difficulty,
next_sub_slot_iters,
uint8(0),
)
msg = make_msg(ProtocolMessageTypes.new_signage_point, broadcast_farmer)
await self.server.send_to_all([msg], NodeType.FARMER)
return None, True
else:
self.log.info(
f"End of slot not added CC challenge "
f"{request.end_of_slot_bundle.challenge_chain.challenge_chain_end_of_slot_vdf.challenge}"
)
return None, False
async def respond_transaction(
self,
transaction: SpendBundle,
spend_name: bytes32,
peer: Optional[ws.WSChialiteConnection] = None,
test: bool = False,
) -> Tuple[MempoolInclusionStatus, Optional[Err]]:
if self.sync_store.get_sync_mode():
return MempoolInclusionStatus.FAILED, Err.NO_TRANSACTIONS_WHILE_SYNCING
if not test and not (await self.synced()):
return MempoolInclusionStatus.FAILED, Err.NO_TRANSACTIONS_WHILE_SYNCING
# No transactions in mempool in initial client. Remove 6 weeks after launch
if int(time.time()) <= self.constants.INITIAL_FREEZE_END_TIMESTAMP:
return MempoolInclusionStatus.FAILED, Err.INITIAL_TRANSACTION_FREEZE
if self.mempool_manager.seen(spend_name):
return MempoolInclusionStatus.FAILED, Err.ALREADY_INCLUDING_TRANSACTION
self.mempool_manager.add_and_maybe_pop_seen(spend_name)
self.log.debug(f"Processing transaction: {spend_name}")
# Ignore if syncing
if self.sync_store.get_sync_mode():
status = MempoolInclusionStatus.FAILED
error: Optional[Err] = Err.NO_TRANSACTIONS_WHILE_SYNCING
self.mempool_manager.remove_seen(spend_name)
else:
try:
cost_result = await self.mempool_manager.pre_validate_spendbundle(transaction)
except Exception as e:
self.mempool_manager.remove_seen(spend_name)
raise e
async with self.mempool_manager.lock:
if self.mempool_manager.get_spendbundle(spend_name) is not None:
self.mempool_manager.remove_seen(spend_name)
return MempoolInclusionStatus.FAILED, Err.ALREADY_INCLUDING_TRANSACTION
cost, status, error = await self.mempool_manager.add_spendbundle(transaction, cost_result, spend_name)
if status == MempoolInclusionStatus.SUCCESS:
self.log.debug(
f"Added transaction to mempool: {spend_name} mempool size: "
f"{self.mempool_manager.mempool.total_mempool_cost}"
)
# Only broadcast successful transactions, not pending ones. Otherwise it's a DOS
# vector.
mempool_item = self.mempool_manager.get_mempool_item(spend_name)
assert mempool_item is not None
fees = mempool_item.fee
assert fees >= 0
assert cost is not None
new_tx = full_node_protocol.NewTransaction(
spend_name,
cost,
fees,
)
msg = make_msg(ProtocolMessageTypes.new_transaction, new_tx)
if peer is None:
await self.server.send_to_all([msg], NodeType.FULL_NODE)
else:
await self.server.send_to_all_except([msg], NodeType.FULL_NODE, peer.peer_node_id)
else:
self.mempool_manager.remove_seen(spend_name)
self.log.debug(
f"Wasn't able to add transaction with id {spend_name}, " f"status {status} error: {error}"
)
return status, error
async def _needs_compact_proof(
self, vdf_info: VDFInfo, header_block: HeaderBlock, field_vdf: CompressibleVDFField
) -> bool:
if field_vdf == CompressibleVDFField.CC_EOS_VDF:
for sub_slot in header_block.finished_sub_slots:
if sub_slot.challenge_chain.challenge_chain_end_of_slot_vdf == vdf_info:
if (
sub_slot.proofs.challenge_chain_slot_proof.witness_type == 0
and sub_slot.proofs.challenge_chain_slot_proof.normalized_to_identity
):
return False
return True
if field_vdf == CompressibleVDFField.ICC_EOS_VDF:
for sub_slot in header_block.finished_sub_slots:
if (
sub_slot.infused_challenge_chain is not None
and sub_slot.infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf == vdf_info
):
assert sub_slot.proofs.infused_challenge_chain_slot_proof is not None
if (
sub_slot.proofs.infused_challenge_chain_slot_proof.witness_type == 0
and sub_slot.proofs.infused_challenge_chain_slot_proof.normalized_to_identity
):
return False
return True
if field_vdf == CompressibleVDFField.CC_SP_VDF:
if header_block.reward_chain_block.challenge_chain_sp_vdf is None:
return False
if vdf_info == header_block.reward_chain_block.challenge_chain_sp_vdf:
assert header_block.challenge_chain_sp_proof is not None
if (
header_block.challenge_chain_sp_proof.witness_type == 0
and header_block.challenge_chain_sp_proof.normalized_to_identity
):
return False
return True
if field_vdf == CompressibleVDFField.CC_IP_VDF:
if vdf_info == header_block.reward_chain_block.challenge_chain_ip_vdf:
if (
header_block.challenge_chain_ip_proof.witness_type == 0
and header_block.challenge_chain_ip_proof.normalized_to_identity
):
return False
return True
return False
async def _can_accept_compact_proof(
self,
vdf_info: VDFInfo,
vdf_proof: VDFProof,
height: uint32,
header_hash: bytes32,
field_vdf: CompressibleVDFField,
) -> bool:
"""
- Checks if the provided proof is indeed compact.
- Checks if proof verifies given the vdf_info from the start of sub-slot.
- Checks if the provided vdf_info is correct, assuming it refers to the start of sub-slot.
- Checks if the existing proof was non-compact. Ignore this proof if we already have a compact proof.
"""
is_fully_compactified = await self.block_store.is_fully_compactified(header_hash)
if is_fully_compactified is None or is_fully_compactified:
self.log.info(f"Already compactified block: {header_hash}. Ignoring.")
return False
if vdf_proof.witness_type > 0 or not vdf_proof.normalized_to_identity:
self.log.error(f"Received vdf proof is not compact: {vdf_proof}.")
return False
if not vdf_proof.is_valid(self.constants, ClassgroupElement.get_default_element(), vdf_info):
self.log.error(f"Received compact vdf proof is not valid: {vdf_proof}.")
return False
header_block = await self.blockchain.get_header_block_by_height(height, header_hash, tx_filter=False)
if header_block is None:
self.log.error(f"Can't find block for given compact vdf. Height: {height} Header hash: {header_hash}")
return False
is_new_proof = await self._needs_compact_proof(vdf_info, header_block, field_vdf)
if not is_new_proof:
self.log.info(f"Duplicate compact proof. Height: {height}. Header hash: {header_hash}.")
return is_new_proof
async def _replace_proof(
self,
vdf_info: VDFInfo,
vdf_proof: VDFProof,
height: uint32,
field_vdf: CompressibleVDFField,
):
full_blocks = await self.block_store.get_full_blocks_at([height])
assert len(full_blocks) > 0
for block in full_blocks:
new_block = None
block_record = await self.blockchain.get_block_record_from_db(self.blockchain.height_to_hash(height))
assert block_record is not None
if field_vdf == CompressibleVDFField.CC_EOS_VDF:
for index, sub_slot in enumerate(block.finished_sub_slots):
if sub_slot.challenge_chain.challenge_chain_end_of_slot_vdf == vdf_info:
new_proofs = dataclasses.replace(sub_slot.proofs, challenge_chain_slot_proof=vdf_proof)
new_subslot = dataclasses.replace(sub_slot, proofs=new_proofs)
new_finished_subslots = block.finished_sub_slots
new_finished_subslots[index] = new_subslot
new_block = dataclasses.replace(block, finished_sub_slots=new_finished_subslots)
break
if field_vdf == CompressibleVDFField.ICC_EOS_VDF:
for index, sub_slot in enumerate(block.finished_sub_slots):
if (
sub_slot.infused_challenge_chain is not None
and sub_slot.infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf == vdf_info
):
new_proofs = dataclasses.replace(sub_slot.proofs, infused_challenge_chain_slot_proof=vdf_proof)
new_subslot = dataclasses.replace(sub_slot, proofs=new_proofs)
new_finished_subslots = block.finished_sub_slots
new_finished_subslots[index] = new_subslot
new_block = dataclasses.replace(block, finished_sub_slots=new_finished_subslots)
break
if field_vdf == CompressibleVDFField.CC_SP_VDF:
if block.reward_chain_block.challenge_chain_sp_vdf == vdf_info:
assert block.challenge_chain_sp_proof is not None
new_block = dataclasses.replace(block, challenge_chain_sp_proof=vdf_proof)
if field_vdf == CompressibleVDFField.CC_IP_VDF:
if block.reward_chain_block.challenge_chain_ip_vdf == vdf_info:
new_block = dataclasses.replace(block, challenge_chain_ip_proof=vdf_proof)
if new_block is None:
self.log.debug("did not replace any proof, vdf does not match")
return
async with self.db_wrapper.lock:
await self.block_store.add_full_block(new_block.header_hash, new_block, block_record)
await self.block_store.db_wrapper.commit_transaction()
async def respond_compact_proof_of_time(self, request: timelord_protocol.RespondCompactProofOfTime):
field_vdf = CompressibleVDFField(int(request.field_vdf))
if not await self._can_accept_compact_proof(
request.vdf_info, request.vdf_proof, request.height, request.header_hash, field_vdf
):
return None
async with self.blockchain.compact_proof_lock:
await self._replace_proof(request.vdf_info, request.vdf_proof, request.height, field_vdf)
msg = make_msg(
ProtocolMessageTypes.new_compact_vdf,
full_node_protocol.NewCompactVDF(request.height, request.header_hash, request.field_vdf, request.vdf_info),
)
if self.server is not None:
await self.server.send_to_all([msg], NodeType.FULL_NODE)
async def new_compact_vdf(self, request: full_node_protocol.NewCompactVDF, peer: ws.WSChialiteConnection):
is_fully_compactified = await self.block_store.is_fully_compactified(request.header_hash)
if is_fully_compactified is None or is_fully_compactified:
return False
header_block = await self.blockchain.get_header_block_by_height(
request.height, request.header_hash, tx_filter=False
)
if header_block is None:
return None
field_vdf = CompressibleVDFField(int(request.field_vdf))
if await self._needs_compact_proof(request.vdf_info, header_block, field_vdf):
peer_request = full_node_protocol.RequestCompactVDF(
request.height, request.header_hash, request.field_vdf, request.vdf_info
)
response = await peer.request_compact_vdf(peer_request, timeout=10)
if response is not None and isinstance(response, full_node_protocol.RespondCompactVDF):
await self.respond_compact_vdf(response, peer)
async def request_compact_vdf(self, request: full_node_protocol.RequestCompactVDF, peer: ws.WSChialiteConnection):
header_block = await self.blockchain.get_header_block_by_height(
request.height, request.header_hash, tx_filter=False
)
if header_block is None:
return None
vdf_proof: Optional[VDFProof] = None
field_vdf = CompressibleVDFField(int(request.field_vdf))
if field_vdf == CompressibleVDFField.CC_EOS_VDF:
for sub_slot in header_block.finished_sub_slots:
if sub_slot.challenge_chain.challenge_chain_end_of_slot_vdf == request.vdf_info:
vdf_proof = sub_slot.proofs.challenge_chain_slot_proof
break
if field_vdf == CompressibleVDFField.ICC_EOS_VDF:
for sub_slot in header_block.finished_sub_slots:
if (
sub_slot.infused_challenge_chain is not None
and sub_slot.infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf == request.vdf_info
):
vdf_proof = sub_slot.proofs.infused_challenge_chain_slot_proof
break
if (
field_vdf == CompressibleVDFField.CC_SP_VDF
and header_block.reward_chain_block.challenge_chain_sp_vdf == request.vdf_info
):
vdf_proof = header_block.challenge_chain_sp_proof
if (
field_vdf == CompressibleVDFField.CC_IP_VDF
and header_block.reward_chain_block.challenge_chain_ip_vdf == request.vdf_info
):
vdf_proof = header_block.challenge_chain_ip_proof
if vdf_proof is None or vdf_proof.witness_type > 0 or not vdf_proof.normalized_to_identity:
self.log.error(f"{peer} requested compact vdf we don't have, height: {request.height}.")
return None
compact_vdf = full_node_protocol.RespondCompactVDF(
request.height,
request.header_hash,
request.field_vdf,
request.vdf_info,
vdf_proof,
)
msg = make_msg(ProtocolMessageTypes.respond_compact_vdf, compact_vdf)
await peer.send_message(msg)
async def respond_compact_vdf(self, request: full_node_protocol.RespondCompactVDF, peer: ws.WSChialiteConnection):
field_vdf = CompressibleVDFField(int(request.field_vdf))
if not await self._can_accept_compact_proof(
request.vdf_info, request.vdf_proof, request.height, request.header_hash, field_vdf
):
return None
async with self.blockchain.compact_proof_lock:
if self.blockchain.seen_compact_proofs(request.vdf_info, request.height):
return None
await self._replace_proof(request.vdf_info, request.vdf_proof, request.height, field_vdf)
msg = make_msg(
ProtocolMessageTypes.new_compact_vdf,
full_node_protocol.NewCompactVDF(request.height, request.header_hash, request.field_vdf, request.vdf_info),
)
if self.server is not None:
await self.server.send_to_all_except([msg], NodeType.FULL_NODE, peer.peer_node_id)
async def broadcast_uncompact_blocks(
self, uncompact_interval_scan: int, target_uncompact_proofs: int, sanitize_weight_proof_only: bool
):
min_height: Optional[int] = 0
try:
while not self._shut_down:
while self.sync_store.get_sync_mode():
if self._shut_down:
return None
await asyncio.sleep(30)
broadcast_list: List[timelord_protocol.RequestCompactProofOfTime] = []
new_min_height = None
max_height = self.blockchain.get_peak_height()
if max_height is None:
await asyncio.sleep(30)
continue
# Calculate 'min_height' correctly the first time this task is launched, using the db
assert min_height is not None
min_height = await self.block_store.get_first_not_compactified(min_height)
if min_height is None or min_height > max(0, max_height - 1000):
min_height = max(0, max_height - 1000)
batches_finished = 0
self.log.info("Scanning the blockchain for uncompact blocks.")
assert max_height is not None
assert min_height is not None
for h in range(min_height, max_height, 100):
# Got 10 times the target header count, sampling the target headers should contain
# enough randomness to split the work between blueboxes.
if len(broadcast_list) > target_uncompact_proofs * 10:
break
stop_height = min(h + 99, max_height)
assert min_height is not None
headers = await self.blockchain.get_header_blocks_in_range(min_height, stop_height, tx_filter=False)
records: Dict[bytes32, BlockRecord] = {}
if sanitize_weight_proof_only:
records = await self.blockchain.get_block_records_in_range(min_height, stop_height)
for header in headers.values():
prev_broadcast_list_len = len(broadcast_list)
expected_header_hash = self.blockchain.height_to_hash(header.height)
if header.header_hash != expected_header_hash:
continue
if sanitize_weight_proof_only:
assert header.header_hash in records
record = records[header.header_hash]
for sub_slot in header.finished_sub_slots:
if (
sub_slot.proofs.challenge_chain_slot_proof.witness_type > 0
or not sub_slot.proofs.challenge_chain_slot_proof.normalized_to_identity
):
broadcast_list.append(
timelord_protocol.RequestCompactProofOfTime(
sub_slot.challenge_chain.challenge_chain_end_of_slot_vdf,
header.header_hash,
header.height,
uint8(CompressibleVDFField.CC_EOS_VDF),
)
)
if sub_slot.proofs.infused_challenge_chain_slot_proof is not None and (
sub_slot.proofs.infused_challenge_chain_slot_proof.witness_type > 0
or not sub_slot.proofs.infused_challenge_chain_slot_proof.normalized_to_identity
):
assert sub_slot.infused_challenge_chain is not None
broadcast_list.append(
timelord_protocol.RequestCompactProofOfTime(
sub_slot.infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf,
header.header_hash,
header.height,
uint8(CompressibleVDFField.ICC_EOS_VDF),
)
)
# Running in 'sanitize_weight_proof_only' ignores CC_SP_VDF and CC_IP_VDF
# unless this is a challenge block.
if sanitize_weight_proof_only:
if not record.is_challenge_block(self.constants):
# Calculates 'new_min_height' as described below.
if (
prev_broadcast_list_len == 0
and len(broadcast_list) > 0
and h <= max(0, max_height - 1000)
):
new_min_height = header.height
# Skip calculations for CC_SP_VDF and CC_IP_VDF.
continue
if header.challenge_chain_sp_proof is not None and (
header.challenge_chain_sp_proof.witness_type > 0
or not header.challenge_chain_sp_proof.normalized_to_identity
):
assert header.reward_chain_block.challenge_chain_sp_vdf is not None
broadcast_list.append(
timelord_protocol.RequestCompactProofOfTime(
header.reward_chain_block.challenge_chain_sp_vdf,
header.header_hash,
header.height,
uint8(CompressibleVDFField.CC_SP_VDF),
)
)
if (
header.challenge_chain_ip_proof.witness_type > 0
or not header.challenge_chain_ip_proof.normalized_to_identity
):
broadcast_list.append(
timelord_protocol.RequestCompactProofOfTime(
header.reward_chain_block.challenge_chain_ip_vdf,
header.header_hash,
header.height,
uint8(CompressibleVDFField.CC_IP_VDF),
)
)
# This is the first header with uncompact proofs. Store its height so next time we iterate
# only from here. Fix header block iteration window to at least 1000, so reorgs will be
# handled correctly.
if prev_broadcast_list_len == 0 and len(broadcast_list) > 0 and h <= max(0, max_height - 1000):
new_min_height = header.height
# Small sleep between batches.
batches_finished += 1
if batches_finished % 10 == 0:
await asyncio.sleep(1)
# We have no uncompact blocks, but mentain the block iteration window to at least 1000 blocks.
if new_min_height is None:
new_min_height = max(0, max_height - 1000)
min_height = new_min_height
if len(broadcast_list) > target_uncompact_proofs:
random.shuffle(broadcast_list)
broadcast_list = broadcast_list[:target_uncompact_proofs]
if self.sync_store.get_sync_mode():
continue
if self.server is not None:
for new_pot in broadcast_list:
msg = make_msg(ProtocolMessageTypes.request_compact_proof_of_time, new_pot)
await self.server.send_to_all([msg], NodeType.TIMELORD)
await asyncio.sleep(uncompact_interval_scan)
except Exception as e:
error_stack = traceback.format_exc()
self.log.error(f"Exception in broadcast_uncompact_blocks: {e}")
self.log.error(f"Exception Stack: {error_stack}")
| import asyncio
import dataclasses
import logging
import random
import time
import traceback
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
import aiosqlite
from blspy import AugSchemeMPL
import chialite.server.ws_connection as ws # lgtm [py/import-and-import-from]
from chialite.consensus.block_creation import unfinished_block_to_full_block
from chialite.consensus.block_record import BlockRecord
from chialite.consensus.blockchain import Blockchain, ReceiveBlockResult
from chialite.consensus.constants import ConsensusConstants
from chialite.consensus.difficulty_adjustment import get_next_sub_slot_iters_and_difficulty
from chialite.consensus.make_sub_epoch_summary import next_sub_epoch_summary
from chialite.consensus.multiprocess_validation import PreValidationResult
from chialite.consensus.pot_iterations import calculate_sp_iters
from chialite.full_node.block_store import BlockStore
from chialite.full_node.bundle_tools import detect_potential_template_generator
from chialite.full_node.coin_store import CoinStore
from chialite.full_node.full_node_store import FullNodeStore
from chialite.full_node.mempool_manager import MempoolManager
from chialite.full_node.signage_point import SignagePoint
from chialite.full_node.sync_store import SyncStore
from chialite.full_node.weight_proof import WeightProofHandler
from chialite.protocols import farmer_protocol, full_node_protocol, timelord_protocol, wallet_protocol
from chialite.protocols.full_node_protocol import (
RejectBlocks,
RequestBlocks,
RespondBlock,
RespondBlocks,
RespondSignagePoint,
)
from chialite.protocols.protocol_message_types import ProtocolMessageTypes
from chialite.server.node_discovery import FullNodePeers
from chialite.server.outbound_message import Message, NodeType, make_msg
from chialite.server.server import ChialiteServer
from chialite.types.blockchain_format.classgroup import ClassgroupElement
from chialite.types.blockchain_format.pool_target import PoolTarget
from chialite.types.blockchain_format.sized_bytes import bytes32
from chialite.types.blockchain_format.sub_epoch_summary import SubEpochSummary
from chialite.types.blockchain_format.vdf import CompressibleVDFField, VDFInfo, VDFProof
from chialite.types.end_of_slot_bundle import EndOfSubSlotBundle
from chialite.types.full_block import FullBlock
from chialite.types.header_block import HeaderBlock
from chialite.types.mempool_inclusion_status import MempoolInclusionStatus
from chialite.types.spend_bundle import SpendBundle
from chialite.types.unfinished_block import UnfinishedBlock
from chialite.util.bech32m import encode_puzzle_hash
from chialite.util.db_wrapper import DBWrapper
from chialite.util.errors import ConsensusError, Err
from chialite.util.ints import uint8, uint32, uint64, uint128
from chialite.util.path import mkdir, path_from_root
from chialite.util.safe_cancel_task import cancel_task_safe
from chialite.util.profiler import profile_task
class FullNode:
block_store: BlockStore
full_node_store: FullNodeStore
full_node_peers: Optional[FullNodePeers]
sync_store: Any
coin_store: CoinStore
mempool_manager: MempoolManager
connection: aiosqlite.Connection
_sync_task: Optional[asyncio.Task]
blockchain: Blockchain
config: Dict
server: Any
log: logging.Logger
constants: ConsensusConstants
_shut_down: bool
root_path: Path
state_changed_callback: Optional[Callable]
timelord_lock: asyncio.Lock
initialized: bool
weight_proof_handler: Optional[WeightProofHandler]
def __init__(
self,
config: Dict,
root_path: Path,
consensus_constants: ConsensusConstants,
name: str = None,
):
self.initialized = False
self.root_path = root_path
self.config = config
self.server = None
self._shut_down = False # Set to true to close all infinite loops
self.constants = consensus_constants
self.pow_creation: Dict[uint32, asyncio.Event] = {}
self.state_changed_callback: Optional[Callable] = None
self.full_node_peers = None
self.sync_store = None
self.signage_point_times = [time.time() for _ in range(self.constants.NUM_SPS_SUB_SLOT)]
self.full_node_store = FullNodeStore(self.constants)
if name:
self.log = logging.getLogger(name)
else:
self.log = logging.getLogger(__name__)
db_path_replaced: str = config["database_path"].replace("CHALLENGE", config["selected_network"])
self.db_path = path_from_root(root_path, db_path_replaced)
mkdir(self.db_path.parent)
def _set_state_changed_callback(self, callback: Callable):
self.state_changed_callback = callback
async def _start(self):
self.timelord_lock = asyncio.Lock()
self.compact_vdf_lock = asyncio.Semaphore(4)
self.new_peak_lock = asyncio.Semaphore(8)
# create the store (db) and full node instance
self.connection = await aiosqlite.connect(self.db_path)
self.db_wrapper = DBWrapper(self.connection)
self.block_store = await BlockStore.create(self.db_wrapper)
self.sync_store = await SyncStore.create()
self.coin_store = await CoinStore.create(self.db_wrapper)
self.log.info("Initializing blockchain from disk")
start_time = time.time()
self.blockchain = await Blockchain.create(self.coin_store, self.block_store, self.constants)
self.mempool_manager = MempoolManager(self.coin_store, self.constants)
self.weight_proof_handler = None
asyncio.create_task(self.initialize_weight_proof())
if self.config.get("enable_profiler", False):
asyncio.create_task(profile_task(self.root_path, self.log))
self._sync_task = None
self._segment_task = None
time_taken = time.time() - start_time
if self.blockchain.get_peak() is None:
self.log.info(f"Initialized with empty blockchain time taken: {int(time_taken)}s")
else:
self.log.info(
f"Blockchain initialized to peak {self.blockchain.get_peak().header_hash} height"
f" {self.blockchain.get_peak().height}, "
f"time taken: {int(time_taken)}s"
)
pending_tx = await self.mempool_manager.new_peak(self.blockchain.get_peak())
assert len(pending_tx) == 0 # no pending transactions when starting up
peak: Optional[BlockRecord] = self.blockchain.get_peak()
self.uncompact_task = None
if peak is not None:
full_peak = await self.blockchain.get_full_peak()
await self.peak_post_processing(full_peak, peak, max(peak.height - 1, 0), None)
if self.config["send_uncompact_interval"] != 0:
sanitize_weight_proof_only = False
if "sanitize_weight_proof_only" in self.config:
sanitize_weight_proof_only = self.config["sanitize_weight_proof_only"]
assert self.config["target_uncompact_proofs"] != 0
self.uncompact_task = asyncio.create_task(
self.broadcast_uncompact_blocks(
self.config["send_uncompact_interval"],
self.config["target_uncompact_proofs"],
sanitize_weight_proof_only,
)
)
self.initialized = True
if self.full_node_peers is not None:
asyncio.create_task(self.full_node_peers.start())
async def initialize_weight_proof(self):
self.weight_proof_handler = WeightProofHandler(self.constants, self.blockchain)
peak = self.blockchain.get_peak()
if peak is not None:
await self.weight_proof_handler.create_sub_epoch_segments()
def set_server(self, server: ChialiteServer):
self.server = server
dns_servers = []
if "dns_servers" in self.config:
dns_servers = self.config["dns_servers"]
elif self.config["port"] == 8444:
# If `dns_servers` misses from the `config`, hardcode it if we're running mainnet.
dns_servers.append("dns-introducer.chialite.net")
try:
self.full_node_peers = FullNodePeers(
self.server,
self.root_path,
self.config["target_peer_count"] - self.config["target_outbound_peer_count"],
self.config["target_outbound_peer_count"],
self.config["peer_db_path"],
self.config["introducer_peer"],
dns_servers,
self.config["peer_connect_interval"],
self.log,
)
except Exception as e:
error_stack = traceback.format_exc()
self.log.error(f"Exception: {e}")
self.log.error(f"Exception in peer discovery: {e}")
self.log.error(f"Exception Stack: {error_stack}")
def _state_changed(self, change: str):
if self.state_changed_callback is not None:
self.state_changed_callback(change)
async def short_sync_batch(self, peer: ws.WSChialiteConnection, start_height: uint32, target_height: uint32) -> bool:
"""
Tries to sync to a chain which is not too far in the future, by downloading batches of blocks. If the first
block that we download is not connected to our chain, we return False and do an expensive long sync instead.
Long sync is not preferred because it requires downloading and validating a weight proof.
Args:
peer: peer to sync from
start_height: height that we should start downloading at. (Our peak is higher)
target_height: target to sync to
Returns:
False if the fork point was not found, and we need to do a long sync. True otherwise.
"""
# Don't trigger multiple batch syncs to the same peer
if (
peer.peer_node_id in self.sync_store.backtrack_syncing
and self.sync_store.backtrack_syncing[peer.peer_node_id] > 0
):
return True # Don't batch sync, we are already in progress of a backtrack sync
if peer.peer_node_id in self.sync_store.batch_syncing:
return True # Don't trigger a long sync
self.sync_store.batch_syncing.add(peer.peer_node_id)
self.log.info(f"Starting batch short sync from {start_height} to height {target_height}")
if start_height > 0:
first = await peer.request_block(full_node_protocol.RequestBlock(uint32(start_height), False))
if first is None or not isinstance(first, full_node_protocol.RespondBlock):
self.sync_store.batch_syncing.remove(peer.peer_node_id)
raise ValueError(f"Error short batch syncing, could not fetch block at height {start_height}")
if not self.blockchain.contains_block(first.block.prev_header_hash):
self.log.info("Batch syncing stopped, this is a deep chain")
self.sync_store.batch_syncing.remove(peer.peer_node_id)
# First sb not connected to our blockchain, do a long sync instead
return False
batch_size = self.constants.MAX_BLOCK_COUNT_PER_REQUESTS
if self._segment_task is not None and (not self._segment_task.done()):
try:
self._segment_task.cancel()
except Exception as e:
self.log.warning(f"failed to cancel segment task {e}")
self._segment_task = None
try:
for height in range(start_height, target_height, batch_size):
end_height = min(target_height, height + batch_size)
request = RequestBlocks(uint32(height), uint32(end_height), True)
response = await peer.request_blocks(request)
if not response:
raise ValueError(f"Error short batch syncing, invalid/no response for {height}-{end_height}")
async with self.blockchain.lock:
success, advanced_peak, fork_height = await self.receive_block_batch(response.blocks, peer, None)
if not success:
raise ValueError(f"Error short batch syncing, failed to validate blocks {height}-{end_height}")
if advanced_peak:
peak = self.blockchain.get_peak()
peak_fb: Optional[FullBlock] = await self.blockchain.get_full_peak()
assert peak is not None and peak_fb is not None and fork_height is not None
await self.peak_post_processing(peak_fb, peak, fork_height, peer)
self.log.info(f"Added blocks {height}-{end_height}")
except Exception:
self.sync_store.batch_syncing.remove(peer.peer_node_id)
raise
self.sync_store.batch_syncing.remove(peer.peer_node_id)
return True
async def short_sync_backtrack(
self, peer: ws.WSChialiteConnection, peak_height: uint32, target_height: uint32, target_unf_hash: bytes32
):
"""
Performs a backtrack sync, where blocks are downloaded one at a time from newest to oldest. If we do not
find the fork point 5 deeper than our peak, we return False and do a long sync instead.
Args:
peer: peer to sync from
peak_height: height of our peak
target_height: target height
target_unf_hash: partial hash of the unfinished block of the target
Returns:
True iff we found the fork point, and we do not need to long sync.
"""
try:
if peer.peer_node_id not in self.sync_store.backtrack_syncing:
self.sync_store.backtrack_syncing[peer.peer_node_id] = 0
self.sync_store.backtrack_syncing[peer.peer_node_id] += 1
unfinished_block: Optional[UnfinishedBlock] = self.full_node_store.get_unfinished_block(target_unf_hash)
curr_height: int = target_height
found_fork_point = False
responses = []
while curr_height > peak_height - 5:
# If we already have the unfinished block, don't fetch the transactions. In the normal case, we will
# already have the unfinished block, from when it was broadcast, so we just need to download the header,
# but not the transactions
fetch_tx: bool = unfinished_block is None or curr_height != target_height
curr = await peer.request_block(full_node_protocol.RequestBlock(uint32(curr_height), fetch_tx))
if curr is None:
raise ValueError(f"Failed to fetch block {curr_height} from {peer.get_peer_info()}, timed out")
if curr is None or not isinstance(curr, full_node_protocol.RespondBlock):
raise ValueError(
f"Failed to fetch block {curr_height} from {peer.get_peer_info()}, wrong type {type(curr)}"
)
responses.append(curr)
if self.blockchain.contains_block(curr.block.prev_header_hash) or curr_height == 0:
found_fork_point = True
break
curr_height -= 1
if found_fork_point:
for response in reversed(responses):
await self.respond_block(response, peer)
except Exception as e:
self.sync_store.backtrack_syncing[peer.peer_node_id] -= 1
raise e
self.sync_store.backtrack_syncing[peer.peer_node_id] -= 1
return found_fork_point
async def new_peak(self, request: full_node_protocol.NewPeak, peer: ws.WSChialiteConnection):
"""
We have received a notification of a new peak from a peer. This happens either when we have just connected,
or when the peer has updated their peak.
Args:
request: information about the new peak
peer: peer that sent the message
"""
# Store this peak/peer combination in case we want to sync to it, and to keep track of peers
self.sync_store.peer_has_block(request.header_hash, peer.peer_node_id, request.weight, request.height, True)
if self.blockchain.contains_block(request.header_hash):
return None
# Not interested in less heavy peaks
peak: Optional[BlockRecord] = self.blockchain.get_peak()
curr_peak_height = uint32(0) if peak is None else peak.height
if peak is not None and peak.weight > request.weight:
return None
if self.sync_store.get_sync_mode():
# If peer connects while we are syncing, check if they have the block we are syncing towards
peak_sync_hash = self.sync_store.get_sync_target_hash()
peak_sync_height = self.sync_store.get_sync_target_height()
if peak_sync_hash is not None and request.header_hash != peak_sync_hash and peak_sync_height is not None:
peak_peers: Set[bytes32] = self.sync_store.get_peers_that_have_peak([peak_sync_hash])
# Don't ask if we already know this peer has the peak
if peer.peer_node_id not in peak_peers:
target_peak_response: Optional[RespondBlock] = await peer.request_block(
full_node_protocol.RequestBlock(uint32(peak_sync_height), False), timeout=10
)
if target_peak_response is not None and isinstance(target_peak_response, RespondBlock):
self.sync_store.peer_has_block(
peak_sync_hash,
peer.peer_node_id,
target_peak_response.block.weight,
peak_sync_height,
False,
)
else:
if request.height <= curr_peak_height + self.config["short_sync_blocks_behind_threshold"]:
# This is the normal case of receiving the next block
if await self.short_sync_backtrack(
peer, curr_peak_height, request.height, request.unfinished_reward_block_hash
):
return None
if request.height < self.constants.WEIGHT_PROOF_RECENT_BLOCKS:
# This is the case of syncing up more than a few blocks, at the start of the chain
# TODO(almog): fix weight proofs so they work at the beginning as well
self.log.debug("Doing batch sync, no backup")
await self.short_sync_batch(peer, uint32(0), request.height)
return None
if request.height < curr_peak_height + self.config["sync_blocks_behind_threshold"]:
# This case of being behind but not by so much
if await self.short_sync_batch(peer, uint32(max(curr_peak_height - 6, 0)), request.height):
return None
# This is the either the case where we were not able to sync successfully (for example, due to the fork
# point being in the past), or we are very far behind. Performs a long sync.
self._sync_task = asyncio.create_task(self._sync())
async def send_peak_to_timelords(
self, peak_block: Optional[FullBlock] = None, peer: Optional[ws.WSChialiteConnection] = None
):
"""
Sends current peak to timelords
"""
if peak_block is None:
peak_block = await self.blockchain.get_full_peak()
if peak_block is not None:
peak = self.blockchain.block_record(peak_block.header_hash)
difficulty = self.blockchain.get_next_difficulty(peak.header_hash, False)
ses: Optional[SubEpochSummary] = next_sub_epoch_summary(
self.constants,
self.blockchain,
peak.required_iters,
peak_block,
True,
)
recent_rc = self.blockchain.get_recent_reward_challenges()
curr = peak
while not curr.is_challenge_block(self.constants) and not curr.first_in_sub_slot:
curr = self.blockchain.block_record(curr.prev_hash)
if curr.is_challenge_block(self.constants):
last_csb_or_eos = curr.total_iters
else:
last_csb_or_eos = curr.ip_sub_slot_total_iters(self.constants)
curr = peak
passed_ses_height_but_not_yet_included = True
while (curr.height % self.constants.SUB_EPOCH_BLOCKS) != 0:
if curr.sub_epoch_summary_included:
passed_ses_height_but_not_yet_included = False
curr = self.blockchain.block_record(curr.prev_hash)
if curr.sub_epoch_summary_included or curr.height == 0:
passed_ses_height_but_not_yet_included = False
timelord_new_peak: timelord_protocol.NewPeakTimelord = timelord_protocol.NewPeakTimelord(
peak_block.reward_chain_block,
difficulty,
peak.deficit,
peak.sub_slot_iters,
ses,
recent_rc,
last_csb_or_eos,
passed_ses_height_but_not_yet_included,
)
msg = make_msg(ProtocolMessageTypes.new_peak_timelord, timelord_new_peak)
if peer is None:
await self.server.send_to_all([msg], NodeType.TIMELORD)
else:
await self.server.send_to_specific([msg], peer.peer_node_id)
async def synced(self) -> bool:
curr: Optional[BlockRecord] = self.blockchain.get_peak()
if curr is None:
return False
while curr is not None and not curr.is_transaction_block:
curr = self.blockchain.try_block_record(curr.prev_hash)
now = time.time()
if (
curr is None
or curr.timestamp is None
or curr.timestamp < uint64(int(now - 60 * 7))
or self.sync_store.get_sync_mode()
):
return False
else:
return True
async def on_connect(self, connection: ws.WSChialiteConnection):
"""
Whenever we connect to another node / wallet, send them our current heads. Also send heads to farmers
and challenges to timelords.
"""
self._state_changed("add_connection")
self._state_changed("sync_mode")
if self.full_node_peers is not None:
asyncio.create_task(self.full_node_peers.on_connect(connection))
if self.initialized is False:
return None
if connection.connection_type is NodeType.FULL_NODE:
# Send filter to node and request mempool items that are not in it (Only if we are currently synced)
synced = await self.synced()
peak_height = self.blockchain.get_peak_height()
current_time = int(time.time())
if synced and peak_height is not None and current_time > self.constants.INITIAL_FREEZE_END_TIMESTAMP:
my_filter = self.mempool_manager.get_filter()
mempool_request = full_node_protocol.RequestMempoolTransactions(my_filter)
msg = make_msg(ProtocolMessageTypes.request_mempool_transactions, mempool_request)
await connection.send_message(msg)
peak_full: Optional[FullBlock] = await self.blockchain.get_full_peak()
if peak_full is not None:
peak: BlockRecord = self.blockchain.block_record(peak_full.header_hash)
if connection.connection_type is NodeType.FULL_NODE:
request_node = full_node_protocol.NewPeak(
peak.header_hash,
peak.height,
peak.weight,
peak.height,
peak_full.reward_chain_block.get_unfinished().get_hash(),
)
await connection.send_message(make_msg(ProtocolMessageTypes.new_peak, request_node))
elif connection.connection_type is NodeType.WALLET:
# If connected to a wallet, send the Peak
request_wallet = wallet_protocol.NewPeakWallet(
peak.header_hash,
peak.height,
peak.weight,
peak.height,
)
await connection.send_message(make_msg(ProtocolMessageTypes.new_peak_wallet, request_wallet))
elif connection.connection_type is NodeType.TIMELORD:
await self.send_peak_to_timelords()
def on_disconnect(self, connection: ws.WSChialiteConnection):
self.log.info(f"peer disconnected {connection.get_peer_info()}")
self._state_changed("close_connection")
self._state_changed("sync_mode")
if self.sync_store is not None:
self.sync_store.peer_disconnected(connection.peer_node_id)
def _num_needed_peers(self) -> int:
assert self.server is not None
assert self.server.all_connections is not None
diff = self.config["target_peer_count"] - len(self.server.all_connections)
return diff if diff >= 0 else 0
def _close(self):
self._shut_down = True
if self.blockchain is not None:
self.blockchain.shut_down()
if self.mempool_manager is not None:
self.mempool_manager.shut_down()
if self.full_node_peers is not None:
asyncio.create_task(self.full_node_peers.close())
if self.uncompact_task is not None:
self.uncompact_task.cancel()
async def _await_closed(self):
cancel_task_safe(self._sync_task, self.log)
for task_id, task in list(self.full_node_store.tx_fetch_tasks.items()):
cancel_task_safe(task, self.log)
await self.connection.close()
async def _sync(self):
"""
Performs a full sync of the blockchain up to the peak.
- Wait a few seconds for peers to send us their peaks
- Select the heaviest peak, and request a weight proof from a peer with that peak
- Validate the weight proof, and disconnect from the peer if invalid
- Find the fork point to see where to start downloading blocks
- Download blocks in batch (and in parallel) and verify them one at a time
- Disconnect peers that provide invalid blocks or don't have the blocks
"""
if self.weight_proof_handler is None:
return None
# Ensure we are only syncing once and not double calling this method
if self.sync_store.get_sync_mode():
return None
if self.sync_store.get_long_sync():
self.log.debug("already in long sync")
return None
self.sync_store.set_long_sync(True)
self.log.debug("long sync started")
try:
self.log.info("Starting to perform sync.")
self.log.info("Waiting to receive peaks from peers.")
# Wait until we have 3 peaks or up to a max of 30 seconds
peaks = []
for i in range(300):
peaks = [tup[0] for tup in self.sync_store.get_peak_of_each_peer().values()]
if len(self.sync_store.get_peers_that_have_peak(peaks)) < 3:
if self._shut_down:
return None
await asyncio.sleep(0.1)
self.log.info(f"Collected a total of {len(peaks)} peaks.")
self.sync_peers_handler = None
# Based on responses from peers about the current peaks, see which peak is the heaviest
# (similar to longest chain rule).
target_peak = self.sync_store.get_heaviest_peak()
if target_peak is None:
raise RuntimeError("Not performing sync, no peaks collected")
heaviest_peak_hash, heaviest_peak_height, heaviest_peak_weight = target_peak
self.sync_store.set_peak_target(heaviest_peak_hash, heaviest_peak_height)
self.log.info(f"Selected peak {heaviest_peak_height}, {heaviest_peak_hash}")
# Check which peers are updated to this height
peers = []
coroutines = []
for peer in self.server.all_connections.values():
if peer.connection_type == NodeType.FULL_NODE:
peers.append(peer.peer_node_id)
coroutines.append(
peer.request_block(
full_node_protocol.RequestBlock(uint32(heaviest_peak_height), True), timeout=10
)
)
for i, target_peak_response in enumerate(await asyncio.gather(*coroutines)):
if target_peak_response is not None and isinstance(target_peak_response, RespondBlock):
self.sync_store.peer_has_block(
heaviest_peak_hash, peers[i], heaviest_peak_weight, heaviest_peak_height, False
)
# TODO: disconnect from peer which gave us the heaviest_peak, if nobody has the peak
peer_ids: Set[bytes32] = self.sync_store.get_peers_that_have_peak([heaviest_peak_hash])
peers_with_peak: List = [c for c in self.server.all_connections.values() if c.peer_node_id in peer_ids]
# Request weight proof from a random peer
self.log.info(f"Total of {len(peers_with_peak)} peers with peak {heaviest_peak_height}")
weight_proof_peer = random.choice(peers_with_peak)
self.log.info(
f"Requesting weight proof from peer {weight_proof_peer.peer_host} up to height"
f" {heaviest_peak_height}"
)
if self.blockchain.get_peak() is not None and heaviest_peak_weight <= self.blockchain.get_peak().weight:
raise ValueError("Not performing sync, already caught up.")
wp_timeout = 360
if "weight_proof_timeout" in self.config:
wp_timeout = self.config["weight_proof_timeout"]
self.log.debug(f"weight proof timeout is {wp_timeout} sec")
request = full_node_protocol.RequestProofOfWeight(heaviest_peak_height, heaviest_peak_hash)
response = await weight_proof_peer.request_proof_of_weight(request, timeout=wp_timeout)
# Disconnect from this peer, because they have not behaved properly
if response is None or not isinstance(response, full_node_protocol.RespondProofOfWeight):
await weight_proof_peer.close(600)
raise RuntimeError(f"Weight proof did not arrive in time from peer: {weight_proof_peer.peer_host}")
if response.wp.recent_chain_data[-1].reward_chain_block.height != heaviest_peak_height:
await weight_proof_peer.close(600)
raise RuntimeError(f"Weight proof had the wrong height: {weight_proof_peer.peer_host}")
if response.wp.recent_chain_data[-1].reward_chain_block.weight != heaviest_peak_weight:
await weight_proof_peer.close(600)
raise RuntimeError(f"Weight proof had the wrong weight: {weight_proof_peer.peer_host}")
# dont sync to wp if local peak is heavier,
# dont ban peer, we asked for this peak
current_peak = self.blockchain.get_peak()
if current_peak is not None:
if response.wp.recent_chain_data[-1].reward_chain_block.weight <= current_peak.weight:
raise RuntimeError(f"current peak is heavier than Weight proof peek: {weight_proof_peer.peer_host}")
try:
validated, fork_point, summaries = await self.weight_proof_handler.validate_weight_proof(response.wp)
except Exception as e:
await weight_proof_peer.close(600)
raise ValueError(f"Weight proof validation threw an error {e}")
if not validated:
await weight_proof_peer.close(600)
raise ValueError("Weight proof validation failed")
self.log.info(f"Re-checked peers: total of {len(peers_with_peak)} peers with peak {heaviest_peak_height}")
self.sync_store.set_sync_mode(True)
self._state_changed("sync_mode")
# Ensures that the fork point does not change
async with self.blockchain.lock:
await self.blockchain.warmup(fork_point)
await self.sync_from_fork_point(fork_point, heaviest_peak_height, heaviest_peak_hash, summaries)
except asyncio.CancelledError:
self.log.warning("Syncing failed, CancelledError")
except Exception as e:
tb = traceback.format_exc()
self.log.error(f"Error with syncing: {type(e)}{tb}")
finally:
if self._shut_down:
return None
await self._finish_sync()
async def sync_from_fork_point(
self,
fork_point_height: int,
target_peak_sb_height: uint32,
peak_hash: bytes32,
summaries: List[SubEpochSummary],
):
self.log.info(f"Start syncing from fork point at {fork_point_height} up to {target_peak_sb_height}")
peer_ids: Set[bytes32] = self.sync_store.get_peers_that_have_peak([peak_hash])
peers_with_peak: List = [c for c in self.server.all_connections.values() if c.peer_node_id in peer_ids]
if len(peers_with_peak) == 0:
raise RuntimeError(f"Not syncing, no peers with header_hash {peak_hash} ")
advanced_peak = False
batch_size = self.constants.MAX_BLOCK_COUNT_PER_REQUESTS
our_peak_height = self.blockchain.get_peak_height()
ses_heigths = self.blockchain.get_ses_heights()
if len(ses_heigths) > 2 and our_peak_height is not None:
ses_heigths.sort()
max_fork_ses_height = ses_heigths[-3]
# This is fork point in SES in case where fork was not detected
if self.blockchain.get_peak_height() is not None and fork_point_height == max_fork_ses_height:
for peer in peers_with_peak:
# Grab a block at peak + 1 and check if fork point is actually our current height
block_response: Optional[Any] = await peer.request_block(
full_node_protocol.RequestBlock(uint32(our_peak_height + 1), True)
)
if block_response is not None and isinstance(block_response, full_node_protocol.RespondBlock):
peak = self.blockchain.get_peak()
if peak is not None and block_response.block.prev_header_hash == peak.header_hash:
fork_point_height = our_peak_height
break
for i in range(fork_point_height, target_peak_sb_height, batch_size):
start_height = i
end_height = min(target_peak_sb_height, start_height + batch_size)
request = RequestBlocks(uint32(start_height), uint32(end_height), True)
self.log.info(f"Requesting blocks: {start_height} to {end_height}")
batch_added = False
to_remove = []
for peer in peers_with_peak:
if peer.closed:
to_remove.append(peer)
continue
response = await peer.request_blocks(request, timeout=60)
if response is None:
await peer.close()
to_remove.append(peer)
continue
if isinstance(response, RejectBlocks):
to_remove.append(peer)
continue
elif isinstance(response, RespondBlocks):
success, advanced_peak, _ = await self.receive_block_batch(
response.blocks, peer, None if advanced_peak else uint32(fork_point_height), summaries
)
if success is False:
await peer.close(600)
continue
else:
batch_added = True
break
peak = self.blockchain.get_peak()
assert peak is not None
msg = make_msg(
ProtocolMessageTypes.new_peak_wallet,
wallet_protocol.NewPeakWallet(
peak.header_hash,
peak.height,
peak.weight,
uint32(max(peak.height - 1, uint32(0))),
),
)
await self.server.send_to_all([msg], NodeType.WALLET)
for peer in to_remove:
peers_with_peak.remove(peer)
if self.sync_store.peers_changed.is_set():
peer_ids = self.sync_store.get_peers_that_have_peak([peak_hash])
peers_with_peak = [c for c in self.server.all_connections.values() if c.peer_node_id in peer_ids]
self.log.info(f"Number of peers we are syncing from: {len(peers_with_peak)}")
self.sync_store.peers_changed.clear()
if batch_added is False:
self.log.info(f"Failed to fetch blocks {start_height} to {end_height} from peers: {peers_with_peak}")
break
else:
self.log.info(f"Added blocks {start_height} to {end_height}")
self.blockchain.clean_block_record(
min(
end_height - self.constants.BLOCKS_CACHE_SIZE,
peak.height - self.constants.BLOCKS_CACHE_SIZE,
)
)
async def receive_block_batch(
self,
all_blocks: List[FullBlock],
peer: ws.WSChialiteConnection,
fork_point: Optional[uint32],
wp_summaries: Optional[List[SubEpochSummary]] = None,
) -> Tuple[bool, bool, Optional[uint32]]:
advanced_peak = False
fork_height: Optional[uint32] = uint32(0)
blocks_to_validate: List[FullBlock] = []
for i, block in enumerate(all_blocks):
if not self.blockchain.contains_block(block.header_hash):
blocks_to_validate = all_blocks[i:]
break
if len(blocks_to_validate) == 0:
return True, False, fork_height
pre_validate_start = time.time()
pre_validation_results: Optional[
List[PreValidationResult]
] = await self.blockchain.pre_validate_blocks_multiprocessing(blocks_to_validate, {})
self.log.debug(f"Block pre-validation time: {time.time() - pre_validate_start}")
if pre_validation_results is None:
return False, False, None
for i, block in enumerate(blocks_to_validate):
if pre_validation_results[i].error is not None:
self.log.error(
f"Invalid block from peer: {peer.get_peer_info()} {Err(pre_validation_results[i].error)}"
)
return False, advanced_peak, fork_height
for i, block in enumerate(blocks_to_validate):
assert pre_validation_results[i].required_iters is not None
(result, error, fork_height,) = await self.blockchain.receive_block(
block, pre_validation_results[i], None if advanced_peak else fork_point, wp_summaries
)
if result == ReceiveBlockResult.NEW_PEAK:
advanced_peak = True
elif result == ReceiveBlockResult.INVALID_BLOCK or result == ReceiveBlockResult.DISCONNECTED_BLOCK:
if error is not None:
self.log.error(f"Error: {error}, Invalid block from peer: {peer.get_peer_info()} ")
return False, advanced_peak, fork_height
block_record = self.blockchain.block_record(block.header_hash)
if block_record.sub_epoch_summary_included is not None:
if self.weight_proof_handler is not None:
await self.weight_proof_handler.create_prev_sub_epoch_segments()
if advanced_peak:
self._state_changed("new_peak")
self.log.debug(
f"Total time for {len(blocks_to_validate)} blocks: {time.time() - pre_validate_start}, "
f"advanced: {advanced_peak}"
)
return True, advanced_peak, fork_height
async def _finish_sync(self):
"""
Finalize sync by setting sync mode to False, clearing all sync information, and adding any final
blocks that we have finalized recently.
"""
self.log.info("long sync done")
self.sync_store.set_long_sync(False)
self.sync_store.set_sync_mode(False)
self._state_changed("sync_mode")
if self.server is None:
return None
peak: Optional[BlockRecord] = self.blockchain.get_peak()
async with self.blockchain.lock:
await self.sync_store.clear_sync_info()
peak_fb: FullBlock = await self.blockchain.get_full_peak()
if peak is not None:
await self.peak_post_processing(peak_fb, peak, peak.height - 1, None)
if peak is not None and self.weight_proof_handler is not None:
await self.weight_proof_handler.get_proof_of_weight(peak.header_hash)
self._state_changed("block")
def has_valid_pool_sig(self, block: Union[UnfinishedBlock, FullBlock]):
if (
block.foliage.foliage_block_data.pool_target
== PoolTarget(self.constants.GENESIS_PRE_FARM_POOL_PUZZLE_HASH, uint32(0))
and block.foliage.prev_block_hash != self.constants.GENESIS_CHALLENGE
and block.reward_chain_block.proof_of_space.pool_public_key is not None
):
if not AugSchemeMPL.verify(
block.reward_chain_block.proof_of_space.pool_public_key,
bytes(block.foliage.foliage_block_data.pool_target),
block.foliage.foliage_block_data.pool_signature,
):
return False
return True
async def signage_point_post_processing(
self,
request: full_node_protocol.RespondSignagePoint,
peer: ws.WSChialiteConnection,
ip_sub_slot: Optional[EndOfSubSlotBundle],
):
self.log.info(
f"⏲️ Finished signage point {request.index_from_challenge}/"
f"{self.constants.NUM_SPS_SUB_SLOT}: "
f"CC: {request.challenge_chain_vdf.output.get_hash()} "
f"RC: {request.reward_chain_vdf.output.get_hash()} "
)
self.signage_point_times[request.index_from_challenge] = time.time()
sub_slot_tuple = self.full_node_store.get_sub_slot(request.challenge_chain_vdf.challenge)
if sub_slot_tuple is not None:
prev_challenge = sub_slot_tuple[0].challenge_chain.challenge_chain_end_of_slot_vdf.challenge
else:
prev_challenge = None
# Notify nodes of the new signage point
broadcast = full_node_protocol.NewSignagePointOrEndOfSubSlot(
prev_challenge,
request.challenge_chain_vdf.challenge,
request.index_from_challenge,
request.reward_chain_vdf.challenge,
)
msg = make_msg(ProtocolMessageTypes.new_signage_point_or_end_of_sub_slot, broadcast)
await self.server.send_to_all_except([msg], NodeType.FULL_NODE, peer.peer_node_id)
peak = self.blockchain.get_peak()
if peak is not None and peak.height > self.constants.MAX_SUB_SLOT_BLOCKS:
sub_slot_iters = peak.sub_slot_iters
difficulty = uint64(peak.weight - self.blockchain.block_record(peak.prev_hash).weight)
# Makes sure to potentially update the difficulty if we are past the peak (into a new sub-slot)
assert ip_sub_slot is not None
if request.challenge_chain_vdf.challenge != ip_sub_slot.challenge_chain.get_hash():
next_difficulty = self.blockchain.get_next_difficulty(peak.header_hash, True)
next_sub_slot_iters = self.blockchain.get_next_slot_iters(peak.header_hash, True)
difficulty = next_difficulty
sub_slot_iters = next_sub_slot_iters
else:
difficulty = self.constants.DIFFICULTY_STARTING
sub_slot_iters = self.constants.SUB_SLOT_ITERS_STARTING
# Notify farmers of the new signage point
broadcast_farmer = farmer_protocol.NewSignagePoint(
request.challenge_chain_vdf.challenge,
request.challenge_chain_vdf.output.get_hash(),
request.reward_chain_vdf.output.get_hash(),
difficulty,
sub_slot_iters,
request.index_from_challenge,
)
msg = make_msg(ProtocolMessageTypes.new_signage_point, broadcast_farmer)
await self.server.send_to_all([msg], NodeType.FARMER)
async def peak_post_processing(
self, block: FullBlock, record: BlockRecord, fork_height: uint32, peer: Optional[ws.WSChialiteConnection]
):
"""
Must be called under self.blockchain.lock. This updates the internal state of the full node with the
latest peak information. It also notifies peers about the new peak.
"""
difficulty = self.blockchain.get_next_difficulty(record.header_hash, False)
sub_slot_iters = self.blockchain.get_next_slot_iters(record.header_hash, False)
self.log.info(
f"🌱 Updated peak to height {record.height}, weight {record.weight}, "
f"hh {record.header_hash}, "
f"forked at {fork_height}, rh: {record.reward_infusion_new_challenge}, "
f"total iters: {record.total_iters}, "
f"overflow: {record.overflow}, "
f"deficit: {record.deficit}, "
f"difficulty: {difficulty}, "
f"sub slot iters: {sub_slot_iters}, "
f"Generator size: "
f"{len(bytes(block.transactions_generator)) if block.transactions_generator else 'No tx'}, "
f"Generator ref list size: "
f"{len(block.transactions_generator_ref_list) if block.transactions_generator else 'No tx'}"
)
sub_slots = await self.blockchain.get_sp_and_ip_sub_slots(record.header_hash)
assert sub_slots is not None
if not self.sync_store.get_sync_mode():
self.blockchain.clean_block_records()
fork_block: Optional[BlockRecord] = None
if fork_height != block.height - 1 and block.height != 0:
# This is a reorg
fork_block = self.blockchain.block_record(self.blockchain.height_to_hash(fork_height))
added_eos, new_sps, new_ips = self.full_node_store.new_peak(
record,
block,
sub_slots[0],
sub_slots[1],
fork_block,
self.blockchain,
)
if sub_slots[1] is None:
assert record.ip_sub_slot_total_iters(self.constants) == 0
# Ensure the signage point is also in the store, for consistency
self.full_node_store.new_signage_point(
record.signage_point_index,
self.blockchain,
record,
record.sub_slot_iters,
SignagePoint(
block.reward_chain_block.challenge_chain_sp_vdf,
block.challenge_chain_sp_proof,
block.reward_chain_block.reward_chain_sp_vdf,
block.reward_chain_sp_proof,
),
skip_vdf_validation=True,
)
# Update the mempool (returns successful pending transactions added to the mempool)
for bundle, result, spend_name in await self.mempool_manager.new_peak(self.blockchain.get_peak()):
self.log.debug(f"Added transaction to mempool: {spend_name}")
mempool_item = self.mempool_manager.get_mempool_item(spend_name)
assert mempool_item is not None
fees = mempool_item.fee
assert fees >= 0
assert mempool_item.cost is not None
new_tx = full_node_protocol.NewTransaction(
spend_name,
mempool_item.cost,
uint64(bundle.fees()),
)
msg = make_msg(ProtocolMessageTypes.new_transaction, new_tx)
await self.server.send_to_all([msg], NodeType.FULL_NODE)
# If there were pending end of slots that happen after this peak, broadcast them if they are added
if added_eos is not None:
broadcast = full_node_protocol.NewSignagePointOrEndOfSubSlot(
added_eos.challenge_chain.challenge_chain_end_of_slot_vdf.challenge,
added_eos.challenge_chain.get_hash(),
uint8(0),
added_eos.reward_chain.end_of_slot_vdf.challenge,
)
msg = make_msg(ProtocolMessageTypes.new_signage_point_or_end_of_sub_slot, broadcast)
await self.server.send_to_all([msg], NodeType.FULL_NODE)
if new_sps is not None and peer is not None:
for index, sp in new_sps:
assert (
sp.cc_vdf is not None
and sp.cc_proof is not None
and sp.rc_vdf is not None
and sp.rc_proof is not None
)
await self.signage_point_post_processing(
RespondSignagePoint(index, sp.cc_vdf, sp.cc_proof, sp.rc_vdf, sp.rc_proof), peer, sub_slots[1]
)
# TODO: maybe add and broadcast new IPs as well
if record.height % 1000 == 0:
# Occasionally clear data in full node store to keep memory usage small
self.full_node_store.clear_seen_unfinished_blocks()
self.full_node_store.clear_old_cache_entries()
if self.sync_store.get_sync_mode() is False:
await self.send_peak_to_timelords(block)
# Tell full nodes about the new peak
msg = make_msg(
ProtocolMessageTypes.new_peak,
full_node_protocol.NewPeak(
record.header_hash,
record.height,
record.weight,
fork_height,
block.reward_chain_block.get_unfinished().get_hash(),
),
)
if peer is not None:
await self.server.send_to_all_except([msg], NodeType.FULL_NODE, peer.peer_node_id)
else:
await self.server.send_to_all([msg], NodeType.FULL_NODE)
# Tell wallets about the new peak
msg = make_msg(
ProtocolMessageTypes.new_peak_wallet,
wallet_protocol.NewPeakWallet(
record.header_hash,
record.height,
record.weight,
fork_height,
),
)
await self.server.send_to_all([msg], NodeType.WALLET)
# Check if we detected a spent transaction, to load up our generator cache
if block.transactions_generator is not None and self.full_node_store.previous_generator is None:
generator_arg = detect_potential_template_generator(block.height, block.transactions_generator)
if generator_arg:
self.log.info(f"Saving previous generator for height {block.height}")
self.full_node_store.previous_generator = generator_arg
self._state_changed("new_peak")
async def respond_block(
self,
respond_block: full_node_protocol.RespondBlock,
peer: Optional[ws.WSChialiteConnection] = None,
) -> Optional[Message]:
"""
Receive a full block from a peer full node (or ourselves).
"""
block: FullBlock = respond_block.block
if self.sync_store.get_sync_mode():
return None
# Adds the block to seen, and check if it's seen before (which means header is in memory)
header_hash = block.header_hash
if self.blockchain.contains_block(header_hash):
return None
pre_validation_result: Optional[PreValidationResult] = None
if (
block.is_transaction_block()
and block.transactions_info is not None
and block.transactions_info.generator_root != bytes([0] * 32)
and block.transactions_generator is None
):
# This is the case where we already had the unfinished block, and asked for this block without
# the transactions (since we already had them). Therefore, here we add the transactions.
unfinished_rh: bytes32 = block.reward_chain_block.get_unfinished().get_hash()
unf_block: Optional[UnfinishedBlock] = self.full_node_store.get_unfinished_block(unfinished_rh)
if (
unf_block is not None
and unf_block.transactions_generator is not None
and unf_block.foliage_transaction_block == block.foliage_transaction_block
):
pre_validation_result = self.full_node_store.get_unfinished_block_result(unfinished_rh)
assert pre_validation_result is not None
block = dataclasses.replace(
block,
transactions_generator=unf_block.transactions_generator,
transactions_generator_ref_list=unf_block.transactions_generator_ref_list,
)
else:
# We still do not have the correct information for this block, perhaps there is a duplicate block
# with the same unfinished block hash in the cache, so we need to fetch the correct one
if peer is None:
return None
block_response: Optional[Any] = await peer.request_block(
full_node_protocol.RequestBlock(block.height, True)
)
if block_response is None or not isinstance(block_response, full_node_protocol.RespondBlock):
self.log.warning(
f"Was not able to fetch the correct block for height {block.height} {block_response}"
)
return None
new_block: FullBlock = block_response.block
if new_block.foliage_transaction_block != block.foliage_transaction_block:
self.log.warning(f"Received the wrong block for height {block.height} {new_block.header_hash}")
return None
assert new_block.transactions_generator is not None
self.log.debug(
f"Wrong info in the cache for bh {new_block.header_hash}, there might be multiple blocks from the "
f"same farmer with the same pospace."
)
# This recursion ends here, we cannot recurse again because transactions_generator is not None
return await self.respond_block(block_response, peer)
async with self.blockchain.lock:
# After acquiring the lock, check again, because another asyncio thread might have added it
if self.blockchain.contains_block(header_hash):
return None
validation_start = time.time()
# Tries to add the block to the blockchain, if we already validated transactions, don't do it again
npc_results = {}
if pre_validation_result is not None and pre_validation_result.npc_result is not None:
npc_results[block.height] = pre_validation_result.npc_result
pre_validation_results: Optional[
List[PreValidationResult]
] = await self.blockchain.pre_validate_blocks_multiprocessing([block], npc_results)
if pre_validation_results is None:
raise ValueError(f"Failed to validate block {header_hash} height {block.height}")
if pre_validation_results[0].error is not None:
if Err(pre_validation_results[0].error) == Err.INVALID_PREV_BLOCK_HASH:
added: ReceiveBlockResult = ReceiveBlockResult.DISCONNECTED_BLOCK
error_code: Optional[Err] = Err.INVALID_PREV_BLOCK_HASH
fork_height: Optional[uint32] = None
else:
raise ValueError(
f"Failed to validate block {header_hash} height "
f"{block.height}: {Err(pre_validation_results[0].error).name}"
)
else:
result_to_validate = (
pre_validation_results[0] if pre_validation_result is None else pre_validation_result
)
assert result_to_validate.required_iters == pre_validation_results[0].required_iters
added, error_code, fork_height = await self.blockchain.receive_block(block, result_to_validate, None)
if (
self.full_node_store.previous_generator is not None
and fork_height is not None
and fork_height < self.full_node_store.previous_generator.block_height
):
self.full_node_store.previous_generator = None
validation_time = time.time() - validation_start
if added == ReceiveBlockResult.ALREADY_HAVE_BLOCK:
return None
elif added == ReceiveBlockResult.INVALID_BLOCK:
assert error_code is not None
self.log.error(f"Block {header_hash} at height {block.height} is invalid with code {error_code}.")
raise ConsensusError(error_code, header_hash)
elif added == ReceiveBlockResult.DISCONNECTED_BLOCK:
self.log.info(f"Disconnected block {header_hash} at height {block.height}")
return None
elif added == ReceiveBlockResult.NEW_PEAK:
# Only propagate blocks which extend the blockchain (becomes one of the heads)
new_peak: Optional[BlockRecord] = self.blockchain.get_peak()
assert new_peak is not None and fork_height is not None
await self.peak_post_processing(block, new_peak, fork_height, peer)
elif added == ReceiveBlockResult.ADDED_AS_ORPHAN:
self.log.info(
f"Received orphan block of height {block.height} rh " f"{block.reward_chain_block.get_hash()}"
)
else:
# Should never reach here, all the cases are covered
raise RuntimeError(f"Invalid result from receive_block {added}")
percent_full_str = (
(
", percent full: "
+ str(round(100.0 * float(block.transactions_info.cost) / self.constants.MAX_BLOCK_COST_CLVM, 3))
+ "%"
)
if block.transactions_info is not None
else ""
)
self.log.info(
f"Block validation time: {validation_time}, "
f"cost: {block.transactions_info.cost if block.transactions_info is not None else 'None'}"
f"{percent_full_str}"
)
# This code path is reached if added == ADDED_AS_ORPHAN or NEW_TIP
peak = self.blockchain.get_peak()
assert peak is not None
# Removes all temporary data for old blocks
clear_height = uint32(max(0, peak.height - 50))
self.full_node_store.clear_candidate_blocks_below(clear_height)
self.full_node_store.clear_unfinished_blocks_below(clear_height)
if peak.height % 1000 == 0 and not self.sync_store.get_sync_mode():
await self.sync_store.clear_sync_info() # Occasionally clear sync peer info
self._state_changed("block")
record = self.blockchain.block_record(block.header_hash)
if self.weight_proof_handler is not None and record.sub_epoch_summary_included is not None:
if self._segment_task is None or self._segment_task.done():
self._segment_task = asyncio.create_task(self.weight_proof_handler.create_prev_sub_epoch_segments())
return None
async def respond_unfinished_block(
self,
respond_unfinished_block: full_node_protocol.RespondUnfinishedBlock,
peer: Optional[ws.WSChialiteConnection],
farmed_block: bool = False,
):
"""
We have received an unfinished block, either created by us, or from another peer.
We can validate it and if it's a good block, propagate it to other peers and
timelords.
"""
block = respond_unfinished_block.unfinished_block
if block.prev_header_hash != self.constants.GENESIS_CHALLENGE and not self.blockchain.contains_block(
block.prev_header_hash
):
# No need to request the parent, since the peer will send it to us anyway, via NewPeak
self.log.debug("Received a disconnected unfinished block")
return None
# Adds the unfinished block to seen, and check if it's seen before, to prevent
# processing it twice. This searches for the exact version of the unfinished block (there can be many different
# foliages for the same trunk). This is intentional, to prevent DOS attacks.
# Note that it does not require that this block was successfully processed
if self.full_node_store.seen_unfinished_block(block.get_hash()):
return None
block_hash = block.reward_chain_block.get_hash()
# This searched for the trunk hash (unfinished reward hash). If we have already added a block with the same
# hash, return
if self.full_node_store.get_unfinished_block(block_hash) is not None:
return None
peak: Optional[BlockRecord] = self.blockchain.get_peak()
if peak is not None:
if block.total_iters < peak.sp_total_iters(self.constants):
# This means this unfinished block is pretty far behind, it will not add weight to our chain
return None
if block.prev_header_hash == self.constants.GENESIS_CHALLENGE:
prev_b = None
else:
prev_b = self.blockchain.block_record(block.prev_header_hash)
# Count the blocks in sub slot, and check if it's a new epoch
if len(block.finished_sub_slots) > 0:
num_blocks_in_ss = 1 # Curr
else:
curr = self.blockchain.try_block_record(block.prev_header_hash)
num_blocks_in_ss = 2 # Curr and prev
while (curr is not None) and not curr.first_in_sub_slot:
curr = self.blockchain.try_block_record(curr.prev_hash)
num_blocks_in_ss += 1
if num_blocks_in_ss > self.constants.MAX_SUB_SLOT_BLOCKS:
# TODO: potentially allow overflow blocks here, which count for the next slot
self.log.warning("Too many blocks added, not adding block")
return None
async with self.blockchain.lock:
# TODO: pre-validate VDFs outside of lock
validation_start = time.time()
validate_result = await self.blockchain.validate_unfinished_block(block)
if validate_result.error is not None:
if validate_result.error == Err.COIN_AMOUNT_NEGATIVE.value:
# TODO: remove in the future, hotfix for 1.1.5 peers to not disconnect older peers
self.log.info(f"Consensus error {validate_result.error}, not disconnecting")
return
raise ConsensusError(Err(validate_result.error))
validation_time = time.time() - validation_start
assert validate_result.required_iters is not None
# Perform another check, in case we have already concurrently added the same unfinished block
if self.full_node_store.get_unfinished_block(block_hash) is not None:
return None
if block.prev_header_hash == self.constants.GENESIS_CHALLENGE:
height = uint32(0)
else:
height = uint32(self.blockchain.block_record(block.prev_header_hash).height + 1)
ses: Optional[SubEpochSummary] = next_sub_epoch_summary(
self.constants,
self.blockchain,
validate_result.required_iters,
block,
True,
)
self.full_node_store.add_unfinished_block(height, block, validate_result)
if farmed_block is True:
self.log.info(
f"🍀 ️Farmed unfinished_block {block_hash}, SP: {block.reward_chain_block.signage_point_index}, "
f"validation time: {validation_time}, "
f"cost: {block.transactions_info.cost if block.transactions_info else 'None'}"
)
else:
percent_full_str = (
(
", percent full: "
+ str(round(100.0 * float(block.transactions_info.cost) / self.constants.MAX_BLOCK_COST_CLVM, 3))
+ "%"
)
if block.transactions_info is not None
else ""
)
self.log.info(
f"Added unfinished_block {block_hash}, not farmed by us,"
f" SP: {block.reward_chain_block.signage_point_index} farmer response time: "
f"{time.time() - self.signage_point_times[block.reward_chain_block.signage_point_index]}, "
f"Pool pk {encode_puzzle_hash(block.foliage.foliage_block_data.pool_target.puzzle_hash, 'xsh')}, "
f"validation time: {validation_time}, "
f"cost: {block.transactions_info.cost if block.transactions_info else 'None'}"
f"{percent_full_str}"
)
sub_slot_iters, difficulty = get_next_sub_slot_iters_and_difficulty(
self.constants,
len(block.finished_sub_slots) > 0,
prev_b,
self.blockchain,
)
if block.reward_chain_block.signage_point_index == 0:
res = self.full_node_store.get_sub_slot(block.reward_chain_block.pos_ss_cc_challenge_hash)
if res is None:
if block.reward_chain_block.pos_ss_cc_challenge_hash == self.constants.GENESIS_CHALLENGE:
rc_prev = self.constants.GENESIS_CHALLENGE
else:
self.log.warning(f"Do not have sub slot {block.reward_chain_block.pos_ss_cc_challenge_hash}")
return None
else:
rc_prev = res[0].reward_chain.get_hash()
else:
assert block.reward_chain_block.reward_chain_sp_vdf is not None
rc_prev = block.reward_chain_block.reward_chain_sp_vdf.challenge
timelord_request = timelord_protocol.NewUnfinishedBlockTimelord(
block.reward_chain_block,
difficulty,
sub_slot_iters,
block.foliage,
ses,
rc_prev,
)
timelord_msg = make_msg(ProtocolMessageTypes.new_unfinished_block_timelord, timelord_request)
await self.server.send_to_all([timelord_msg], NodeType.TIMELORD)
full_node_request = full_node_protocol.NewUnfinishedBlock(block.reward_chain_block.get_hash())
msg = make_msg(ProtocolMessageTypes.new_unfinished_block, full_node_request)
if peer is not None:
await self.server.send_to_all_except([msg], NodeType.FULL_NODE, peer.peer_node_id)
else:
await self.server.send_to_all([msg], NodeType.FULL_NODE)
self._state_changed("unfinished_block")
async def new_infusion_point_vdf(
self, request: timelord_protocol.NewInfusionPointVDF, timelord_peer: Optional[ws.WSChialiteConnection] = None
) -> Optional[Message]:
# Lookup unfinished blocks
unfinished_block: Optional[UnfinishedBlock] = self.full_node_store.get_unfinished_block(
request.unfinished_reward_hash
)
if unfinished_block is None:
self.log.warning(
f"Do not have unfinished reward chain block {request.unfinished_reward_hash}, cannot finish."
)
return None
prev_b: Optional[BlockRecord] = None
target_rc_hash = request.reward_chain_ip_vdf.challenge
last_slot_cc_hash = request.challenge_chain_ip_vdf.challenge
# Backtracks through end of slot objects, should work for multiple empty sub slots
for eos, _, _ in reversed(self.full_node_store.finished_sub_slots):
if eos is not None and eos.reward_chain.get_hash() == target_rc_hash:
target_rc_hash = eos.reward_chain.end_of_slot_vdf.challenge
if target_rc_hash == self.constants.GENESIS_CHALLENGE:
prev_b = None
else:
# Find the prev block, starts looking backwards from the peak. target_rc_hash must be the hash of a block
# and not an end of slot (since we just looked through the slots and backtracked)
curr: Optional[BlockRecord] = self.blockchain.get_peak()
for _ in range(10):
if curr is None:
break
if curr.reward_infusion_new_challenge == target_rc_hash:
# Found our prev block
prev_b = curr
break
curr = self.blockchain.try_block_record(curr.prev_hash)
# If not found, cache keyed on prev block
if prev_b is None:
self.full_node_store.add_to_future_ip(request)
self.log.warning(f"Previous block is None, infusion point {request.reward_chain_ip_vdf.challenge}")
return None
finished_sub_slots: Optional[List[EndOfSubSlotBundle]] = self.full_node_store.get_finished_sub_slots(
self.blockchain,
prev_b,
last_slot_cc_hash,
)
if finished_sub_slots is None:
return None
sub_slot_iters, difficulty = get_next_sub_slot_iters_and_difficulty(
self.constants,
len(finished_sub_slots) > 0,
prev_b,
self.blockchain,
)
if unfinished_block.reward_chain_block.pos_ss_cc_challenge_hash == self.constants.GENESIS_CHALLENGE:
sub_slot_start_iters = uint128(0)
else:
ss_res = self.full_node_store.get_sub_slot(unfinished_block.reward_chain_block.pos_ss_cc_challenge_hash)
if ss_res is None:
self.log.warning(f"Do not have sub slot {unfinished_block.reward_chain_block.pos_ss_cc_challenge_hash}")
return None
_, _, sub_slot_start_iters = ss_res
sp_total_iters = uint128(
sub_slot_start_iters
+ calculate_sp_iters(
self.constants,
sub_slot_iters,
unfinished_block.reward_chain_block.signage_point_index,
)
)
block: FullBlock = unfinished_block_to_full_block(
unfinished_block,
request.challenge_chain_ip_vdf,
request.challenge_chain_ip_proof,
request.reward_chain_ip_vdf,
request.reward_chain_ip_proof,
request.infused_challenge_chain_ip_vdf,
request.infused_challenge_chain_ip_proof,
finished_sub_slots,
prev_b,
self.blockchain,
sp_total_iters,
difficulty,
)
if not self.has_valid_pool_sig(block):
self.log.warning("Trying to make a pre-farm block but height is not 0")
return None
try:
await self.respond_block(full_node_protocol.RespondBlock(block))
except Exception as e:
self.log.warning(f"Consensus error validating block: {e}")
if timelord_peer is not None:
# Only sends to the timelord who sent us this VDF, to reset them to the correct peak
await self.send_peak_to_timelords(peer=timelord_peer)
return None
async def respond_end_of_sub_slot(
self, request: full_node_protocol.RespondEndOfSubSlot, peer: ws.WSChialiteConnection
) -> Tuple[Optional[Message], bool]:
fetched_ss = self.full_node_store.get_sub_slot(request.end_of_slot_bundle.challenge_chain.get_hash())
if fetched_ss is not None:
# Already have the sub-slot
return None, True
async with self.timelord_lock:
fetched_ss = self.full_node_store.get_sub_slot(
request.end_of_slot_bundle.challenge_chain.challenge_chain_end_of_slot_vdf.challenge
)
if (
(fetched_ss is None)
and request.end_of_slot_bundle.challenge_chain.challenge_chain_end_of_slot_vdf.challenge
!= self.constants.GENESIS_CHALLENGE
):
# If we don't have the prev, request the prev instead
full_node_request = full_node_protocol.RequestSignagePointOrEndOfSubSlot(
request.end_of_slot_bundle.challenge_chain.challenge_chain_end_of_slot_vdf.challenge,
uint8(0),
bytes([0] * 32),
)
return (
make_msg(ProtocolMessageTypes.request_signage_point_or_end_of_sub_slot, full_node_request),
False,
)
peak = self.blockchain.get_peak()
if peak is not None and peak.height > 2:
next_sub_slot_iters = self.blockchain.get_next_slot_iters(peak.header_hash, True)
next_difficulty = self.blockchain.get_next_difficulty(peak.header_hash, True)
else:
next_sub_slot_iters = self.constants.SUB_SLOT_ITERS_STARTING
next_difficulty = self.constants.DIFFICULTY_STARTING
# Adds the sub slot and potentially get new infusions
new_infusions = self.full_node_store.new_finished_sub_slot(
request.end_of_slot_bundle,
self.blockchain,
peak,
await self.blockchain.get_full_peak(),
)
# It may be an empty list, even if it's not None. Not None means added successfully
if new_infusions is not None:
self.log.info(
f"⏲️ Finished sub slot, SP {self.constants.NUM_SPS_SUB_SLOT}/{self.constants.NUM_SPS_SUB_SLOT}, "
f"{request.end_of_slot_bundle.challenge_chain.get_hash()}, "
f"number of sub-slots: {len(self.full_node_store.finished_sub_slots)}, "
f"RC hash: {request.end_of_slot_bundle.reward_chain.get_hash()}, "
f"Deficit {request.end_of_slot_bundle.reward_chain.deficit}"
)
# Notify full nodes of the new sub-slot
broadcast = full_node_protocol.NewSignagePointOrEndOfSubSlot(
request.end_of_slot_bundle.challenge_chain.challenge_chain_end_of_slot_vdf.challenge,
request.end_of_slot_bundle.challenge_chain.get_hash(),
uint8(0),
request.end_of_slot_bundle.reward_chain.end_of_slot_vdf.challenge,
)
msg = make_msg(ProtocolMessageTypes.new_signage_point_or_end_of_sub_slot, broadcast)
await self.server.send_to_all_except([msg], NodeType.FULL_NODE, peer.peer_node_id)
for infusion in new_infusions:
await self.new_infusion_point_vdf(infusion)
# Notify farmers of the new sub-slot
broadcast_farmer = farmer_protocol.NewSignagePoint(
request.end_of_slot_bundle.challenge_chain.get_hash(),
request.end_of_slot_bundle.challenge_chain.get_hash(),
request.end_of_slot_bundle.reward_chain.get_hash(),
next_difficulty,
next_sub_slot_iters,
uint8(0),
)
msg = make_msg(ProtocolMessageTypes.new_signage_point, broadcast_farmer)
await self.server.send_to_all([msg], NodeType.FARMER)
return None, True
else:
self.log.info(
f"End of slot not added CC challenge "
f"{request.end_of_slot_bundle.challenge_chain.challenge_chain_end_of_slot_vdf.challenge}"
)
return None, False
async def respond_transaction(
self,
transaction: SpendBundle,
spend_name: bytes32,
peer: Optional[ws.WSChialiteConnection] = None,
test: bool = False,
) -> Tuple[MempoolInclusionStatus, Optional[Err]]:
if self.sync_store.get_sync_mode():
return MempoolInclusionStatus.FAILED, Err.NO_TRANSACTIONS_WHILE_SYNCING
if not test and not (await self.synced()):
return MempoolInclusionStatus.FAILED, Err.NO_TRANSACTIONS_WHILE_SYNCING
# No transactions in mempool in initial client. Remove 6 weeks after launch
if int(time.time()) <= self.constants.INITIAL_FREEZE_END_TIMESTAMP:
return MempoolInclusionStatus.FAILED, Err.INITIAL_TRANSACTION_FREEZE
if self.mempool_manager.seen(spend_name):
return MempoolInclusionStatus.FAILED, Err.ALREADY_INCLUDING_TRANSACTION
self.mempool_manager.add_and_maybe_pop_seen(spend_name)
self.log.debug(f"Processing transaction: {spend_name}")
# Ignore if syncing
if self.sync_store.get_sync_mode():
status = MempoolInclusionStatus.FAILED
error: Optional[Err] = Err.NO_TRANSACTIONS_WHILE_SYNCING
self.mempool_manager.remove_seen(spend_name)
else:
try:
cost_result = await self.mempool_manager.pre_validate_spendbundle(transaction)
except Exception as e:
self.mempool_manager.remove_seen(spend_name)
raise e
async with self.mempool_manager.lock:
if self.mempool_manager.get_spendbundle(spend_name) is not None:
self.mempool_manager.remove_seen(spend_name)
return MempoolInclusionStatus.FAILED, Err.ALREADY_INCLUDING_TRANSACTION
cost, status, error = await self.mempool_manager.add_spendbundle(transaction, cost_result, spend_name)
if status == MempoolInclusionStatus.SUCCESS:
self.log.debug(
f"Added transaction to mempool: {spend_name} mempool size: "
f"{self.mempool_manager.mempool.total_mempool_cost}"
)
# Only broadcast successful transactions, not pending ones. Otherwise it's a DOS
# vector.
mempool_item = self.mempool_manager.get_mempool_item(spend_name)
assert mempool_item is not None
fees = mempool_item.fee
assert fees >= 0
assert cost is not None
new_tx = full_node_protocol.NewTransaction(
spend_name,
cost,
fees,
)
msg = make_msg(ProtocolMessageTypes.new_transaction, new_tx)
if peer is None:
await self.server.send_to_all([msg], NodeType.FULL_NODE)
else:
await self.server.send_to_all_except([msg], NodeType.FULL_NODE, peer.peer_node_id)
else:
self.mempool_manager.remove_seen(spend_name)
self.log.debug(
f"Wasn't able to add transaction with id {spend_name}, " f"status {status} error: {error}"
)
return status, error
async def _needs_compact_proof(
self, vdf_info: VDFInfo, header_block: HeaderBlock, field_vdf: CompressibleVDFField
) -> bool:
if field_vdf == CompressibleVDFField.CC_EOS_VDF:
for sub_slot in header_block.finished_sub_slots:
if sub_slot.challenge_chain.challenge_chain_end_of_slot_vdf == vdf_info:
if (
sub_slot.proofs.challenge_chain_slot_proof.witness_type == 0
and sub_slot.proofs.challenge_chain_slot_proof.normalized_to_identity
):
return False
return True
if field_vdf == CompressibleVDFField.ICC_EOS_VDF:
for sub_slot in header_block.finished_sub_slots:
if (
sub_slot.infused_challenge_chain is not None
and sub_slot.infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf == vdf_info
):
assert sub_slot.proofs.infused_challenge_chain_slot_proof is not None
if (
sub_slot.proofs.infused_challenge_chain_slot_proof.witness_type == 0
and sub_slot.proofs.infused_challenge_chain_slot_proof.normalized_to_identity
):
return False
return True
if field_vdf == CompressibleVDFField.CC_SP_VDF:
if header_block.reward_chain_block.challenge_chain_sp_vdf is None:
return False
if vdf_info == header_block.reward_chain_block.challenge_chain_sp_vdf:
assert header_block.challenge_chain_sp_proof is not None
if (
header_block.challenge_chain_sp_proof.witness_type == 0
and header_block.challenge_chain_sp_proof.normalized_to_identity
):
return False
return True
if field_vdf == CompressibleVDFField.CC_IP_VDF:
if vdf_info == header_block.reward_chain_block.challenge_chain_ip_vdf:
if (
header_block.challenge_chain_ip_proof.witness_type == 0
and header_block.challenge_chain_ip_proof.normalized_to_identity
):
return False
return True
return False
async def _can_accept_compact_proof(
self,
vdf_info: VDFInfo,
vdf_proof: VDFProof,
height: uint32,
header_hash: bytes32,
field_vdf: CompressibleVDFField,
) -> bool:
"""
- Checks if the provided proof is indeed compact.
- Checks if proof verifies given the vdf_info from the start of sub-slot.
- Checks if the provided vdf_info is correct, assuming it refers to the start of sub-slot.
- Checks if the existing proof was non-compact. Ignore this proof if we already have a compact proof.
"""
is_fully_compactified = await self.block_store.is_fully_compactified(header_hash)
if is_fully_compactified is None or is_fully_compactified:
self.log.info(f"Already compactified block: {header_hash}. Ignoring.")
return False
if vdf_proof.witness_type > 0 or not vdf_proof.normalized_to_identity:
self.log.error(f"Received vdf proof is not compact: {vdf_proof}.")
return False
if not vdf_proof.is_valid(self.constants, ClassgroupElement.get_default_element(), vdf_info):
self.log.error(f"Received compact vdf proof is not valid: {vdf_proof}.")
return False
header_block = await self.blockchain.get_header_block_by_height(height, header_hash, tx_filter=False)
if header_block is None:
self.log.error(f"Can't find block for given compact vdf. Height: {height} Header hash: {header_hash}")
return False
is_new_proof = await self._needs_compact_proof(vdf_info, header_block, field_vdf)
if not is_new_proof:
self.log.info(f"Duplicate compact proof. Height: {height}. Header hash: {header_hash}.")
return is_new_proof
async def _replace_proof(
self,
vdf_info: VDFInfo,
vdf_proof: VDFProof,
height: uint32,
field_vdf: CompressibleVDFField,
):
full_blocks = await self.block_store.get_full_blocks_at([height])
assert len(full_blocks) > 0
for block in full_blocks:
new_block = None
block_record = await self.blockchain.get_block_record_from_db(self.blockchain.height_to_hash(height))
assert block_record is not None
if field_vdf == CompressibleVDFField.CC_EOS_VDF:
for index, sub_slot in enumerate(block.finished_sub_slots):
if sub_slot.challenge_chain.challenge_chain_end_of_slot_vdf == vdf_info:
new_proofs = dataclasses.replace(sub_slot.proofs, challenge_chain_slot_proof=vdf_proof)
new_subslot = dataclasses.replace(sub_slot, proofs=new_proofs)
new_finished_subslots = block.finished_sub_slots
new_finished_subslots[index] = new_subslot
new_block = dataclasses.replace(block, finished_sub_slots=new_finished_subslots)
break
if field_vdf == CompressibleVDFField.ICC_EOS_VDF:
for index, sub_slot in enumerate(block.finished_sub_slots):
if (
sub_slot.infused_challenge_chain is not None
and sub_slot.infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf == vdf_info
):
new_proofs = dataclasses.replace(sub_slot.proofs, infused_challenge_chain_slot_proof=vdf_proof)
new_subslot = dataclasses.replace(sub_slot, proofs=new_proofs)
new_finished_subslots = block.finished_sub_slots
new_finished_subslots[index] = new_subslot
new_block = dataclasses.replace(block, finished_sub_slots=new_finished_subslots)
break
if field_vdf == CompressibleVDFField.CC_SP_VDF:
if block.reward_chain_block.challenge_chain_sp_vdf == vdf_info:
assert block.challenge_chain_sp_proof is not None
new_block = dataclasses.replace(block, challenge_chain_sp_proof=vdf_proof)
if field_vdf == CompressibleVDFField.CC_IP_VDF:
if block.reward_chain_block.challenge_chain_ip_vdf == vdf_info:
new_block = dataclasses.replace(block, challenge_chain_ip_proof=vdf_proof)
if new_block is None:
self.log.debug("did not replace any proof, vdf does not match")
return
async with self.db_wrapper.lock:
await self.block_store.add_full_block(new_block.header_hash, new_block, block_record)
await self.block_store.db_wrapper.commit_transaction()
async def respond_compact_proof_of_time(self, request: timelord_protocol.RespondCompactProofOfTime):
field_vdf = CompressibleVDFField(int(request.field_vdf))
if not await self._can_accept_compact_proof(
request.vdf_info, request.vdf_proof, request.height, request.header_hash, field_vdf
):
return None
async with self.blockchain.compact_proof_lock:
await self._replace_proof(request.vdf_info, request.vdf_proof, request.height, field_vdf)
msg = make_msg(
ProtocolMessageTypes.new_compact_vdf,
full_node_protocol.NewCompactVDF(request.height, request.header_hash, request.field_vdf, request.vdf_info),
)
if self.server is not None:
await self.server.send_to_all([msg], NodeType.FULL_NODE)
async def new_compact_vdf(self, request: full_node_protocol.NewCompactVDF, peer: ws.WSChialiteConnection):
is_fully_compactified = await self.block_store.is_fully_compactified(request.header_hash)
if is_fully_compactified is None or is_fully_compactified:
return False
header_block = await self.blockchain.get_header_block_by_height(
request.height, request.header_hash, tx_filter=False
)
if header_block is None:
return None
field_vdf = CompressibleVDFField(int(request.field_vdf))
if await self._needs_compact_proof(request.vdf_info, header_block, field_vdf):
peer_request = full_node_protocol.RequestCompactVDF(
request.height, request.header_hash, request.field_vdf, request.vdf_info
)
response = await peer.request_compact_vdf(peer_request, timeout=10)
if response is not None and isinstance(response, full_node_protocol.RespondCompactVDF):
await self.respond_compact_vdf(response, peer)
async def request_compact_vdf(self, request: full_node_protocol.RequestCompactVDF, peer: ws.WSChialiteConnection):
header_block = await self.blockchain.get_header_block_by_height(
request.height, request.header_hash, tx_filter=False
)
if header_block is None:
return None
vdf_proof: Optional[VDFProof] = None
field_vdf = CompressibleVDFField(int(request.field_vdf))
if field_vdf == CompressibleVDFField.CC_EOS_VDF:
for sub_slot in header_block.finished_sub_slots:
if sub_slot.challenge_chain.challenge_chain_end_of_slot_vdf == request.vdf_info:
vdf_proof = sub_slot.proofs.challenge_chain_slot_proof
break
if field_vdf == CompressibleVDFField.ICC_EOS_VDF:
for sub_slot in header_block.finished_sub_slots:
if (
sub_slot.infused_challenge_chain is not None
and sub_slot.infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf == request.vdf_info
):
vdf_proof = sub_slot.proofs.infused_challenge_chain_slot_proof
break
if (
field_vdf == CompressibleVDFField.CC_SP_VDF
and header_block.reward_chain_block.challenge_chain_sp_vdf == request.vdf_info
):
vdf_proof = header_block.challenge_chain_sp_proof
if (
field_vdf == CompressibleVDFField.CC_IP_VDF
and header_block.reward_chain_block.challenge_chain_ip_vdf == request.vdf_info
):
vdf_proof = header_block.challenge_chain_ip_proof
if vdf_proof is None or vdf_proof.witness_type > 0 or not vdf_proof.normalized_to_identity:
self.log.error(f"{peer} requested compact vdf we don't have, height: {request.height}.")
return None
compact_vdf = full_node_protocol.RespondCompactVDF(
request.height,
request.header_hash,
request.field_vdf,
request.vdf_info,
vdf_proof,
)
msg = make_msg(ProtocolMessageTypes.respond_compact_vdf, compact_vdf)
await peer.send_message(msg)
async def respond_compact_vdf(self, request: full_node_protocol.RespondCompactVDF, peer: ws.WSChialiteConnection):
field_vdf = CompressibleVDFField(int(request.field_vdf))
if not await self._can_accept_compact_proof(
request.vdf_info, request.vdf_proof, request.height, request.header_hash, field_vdf
):
return None
async with self.blockchain.compact_proof_lock:
if self.blockchain.seen_compact_proofs(request.vdf_info, request.height):
return None
await self._replace_proof(request.vdf_info, request.vdf_proof, request.height, field_vdf)
msg = make_msg(
ProtocolMessageTypes.new_compact_vdf,
full_node_protocol.NewCompactVDF(request.height, request.header_hash, request.field_vdf, request.vdf_info),
)
if self.server is not None:
await self.server.send_to_all_except([msg], NodeType.FULL_NODE, peer.peer_node_id)
async def broadcast_uncompact_blocks(
self, uncompact_interval_scan: int, target_uncompact_proofs: int, sanitize_weight_proof_only: bool
):
min_height: Optional[int] = 0
try:
while not self._shut_down:
while self.sync_store.get_sync_mode():
if self._shut_down:
return None
await asyncio.sleep(30)
broadcast_list: List[timelord_protocol.RequestCompactProofOfTime] = []
new_min_height = None
max_height = self.blockchain.get_peak_height()
if max_height is None:
await asyncio.sleep(30)
continue
# Calculate 'min_height' correctly the first time this task is launched, using the db
assert min_height is not None
min_height = await self.block_store.get_first_not_compactified(min_height)
if min_height is None or min_height > max(0, max_height - 1000):
min_height = max(0, max_height - 1000)
batches_finished = 0
self.log.info("Scanning the blockchain for uncompact blocks.")
assert max_height is not None
assert min_height is not None
for h in range(min_height, max_height, 100):
# Got 10 times the target header count, sampling the target headers should contain
# enough randomness to split the work between blueboxes.
if len(broadcast_list) > target_uncompact_proofs * 10:
break
stop_height = min(h + 99, max_height)
assert min_height is not None
headers = await self.blockchain.get_header_blocks_in_range(min_height, stop_height, tx_filter=False)
records: Dict[bytes32, BlockRecord] = {}
if sanitize_weight_proof_only:
records = await self.blockchain.get_block_records_in_range(min_height, stop_height)
for header in headers.values():
prev_broadcast_list_len = len(broadcast_list)
expected_header_hash = self.blockchain.height_to_hash(header.height)
if header.header_hash != expected_header_hash:
continue
if sanitize_weight_proof_only:
assert header.header_hash in records
record = records[header.header_hash]
for sub_slot in header.finished_sub_slots:
if (
sub_slot.proofs.challenge_chain_slot_proof.witness_type > 0
or not sub_slot.proofs.challenge_chain_slot_proof.normalized_to_identity
):
broadcast_list.append(
timelord_protocol.RequestCompactProofOfTime(
sub_slot.challenge_chain.challenge_chain_end_of_slot_vdf,
header.header_hash,
header.height,
uint8(CompressibleVDFField.CC_EOS_VDF),
)
)
if sub_slot.proofs.infused_challenge_chain_slot_proof is not None and (
sub_slot.proofs.infused_challenge_chain_slot_proof.witness_type > 0
or not sub_slot.proofs.infused_challenge_chain_slot_proof.normalized_to_identity
):
assert sub_slot.infused_challenge_chain is not None
broadcast_list.append(
timelord_protocol.RequestCompactProofOfTime(
sub_slot.infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf,
header.header_hash,
header.height,
uint8(CompressibleVDFField.ICC_EOS_VDF),
)
)
# Running in 'sanitize_weight_proof_only' ignores CC_SP_VDF and CC_IP_VDF
# unless this is a challenge block.
if sanitize_weight_proof_only:
if not record.is_challenge_block(self.constants):
# Calculates 'new_min_height' as described below.
if (
prev_broadcast_list_len == 0
and len(broadcast_list) > 0
and h <= max(0, max_height - 1000)
):
new_min_height = header.height
# Skip calculations for CC_SP_VDF and CC_IP_VDF.
continue
if header.challenge_chain_sp_proof is not None and (
header.challenge_chain_sp_proof.witness_type > 0
or not header.challenge_chain_sp_proof.normalized_to_identity
):
assert header.reward_chain_block.challenge_chain_sp_vdf is not None
broadcast_list.append(
timelord_protocol.RequestCompactProofOfTime(
header.reward_chain_block.challenge_chain_sp_vdf,
header.header_hash,
header.height,
uint8(CompressibleVDFField.CC_SP_VDF),
)
)
if (
header.challenge_chain_ip_proof.witness_type > 0
or not header.challenge_chain_ip_proof.normalized_to_identity
):
broadcast_list.append(
timelord_protocol.RequestCompactProofOfTime(
header.reward_chain_block.challenge_chain_ip_vdf,
header.header_hash,
header.height,
uint8(CompressibleVDFField.CC_IP_VDF),
)
)
# This is the first header with uncompact proofs. Store its height so next time we iterate
# only from here. Fix header block iteration window to at least 1000, so reorgs will be
# handled correctly.
if prev_broadcast_list_len == 0 and len(broadcast_list) > 0 and h <= max(0, max_height - 1000):
new_min_height = header.height
# Small sleep between batches.
batches_finished += 1
if batches_finished % 10 == 0:
await asyncio.sleep(1)
# We have no uncompact blocks, but mentain the block iteration window to at least 1000 blocks.
if new_min_height is None:
new_min_height = max(0, max_height - 1000)
min_height = new_min_height
if len(broadcast_list) > target_uncompact_proofs:
random.shuffle(broadcast_list)
broadcast_list = broadcast_list[:target_uncompact_proofs]
if self.sync_store.get_sync_mode():
continue
if self.server is not None:
for new_pot in broadcast_list:
msg = make_msg(ProtocolMessageTypes.request_compact_proof_of_time, new_pot)
await self.server.send_to_all([msg], NodeType.TIMELORD)
await asyncio.sleep(uncompact_interval_scan)
except Exception as e:
error_stack = traceback.format_exc()
self.log.error(f"Exception in broadcast_uncompact_blocks: {e}")
self.log.error(f"Exception Stack: {error_stack}")
|
# -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets
import numpy as np
import os
from GUI.audio_device_widget import AudioDeviceWidget
from GUI.plot_widget import PlotWidget, PlotWidget_HPIRs, PlotWidget_HPCF
use_vispy = True
try:
from GUI.vispyWidget import VispyCanvas
except ImportError:
use_vispy = False
class UiMainWindow(QtWidgets.QMainWindow):
def __init__(self, measurement_ref):
super().__init__()
self.setObjectName("MainWindow")
self.cwidget = QtWidgets.QWidget()
self.setCentralWidget(self.cwidget)
self.measurement_ref = measurement_ref
self.setWindowTitle("FreeGrid")
# VISPY WIDGET
self.azimuthLabel = QtWidgets.QLabel("Az: ")
self.azimuthLabel.setFont(QtGui.QFont("Arial", 24))
self.azimuthLabel.setMaximumHeight(30)
self.elevationLabel = QtWidgets.QLabel("El: ")
self.elevationLabel.setFont(QtGui.QFont("Arial", 24))
self.elevationLabel.setMaximumHeight(30)
self.radiusLabel = QtWidgets.QLabel("Radius: ")
self.radiusLabel.setFont(QtGui.QFont("Arial", 15))
self.radiusLabel.setMaximumHeight(30)
self.vpWidget = QtWidgets.QGroupBox("Virtual Speaker Position")
self.vpWidget.setObjectName("vpWidget")
self.vpWidget.setLayout(QtWidgets.QGridLayout())
if use_vispy:
self.vpWidget.setMinimumSize(400, 400)
self.vispy_canvas = VispyCanvas(self, measurement_ref)
self.sliderTheta = QtWidgets.QSlider()
self.sliderPhi = QtWidgets.QSlider()
self.vpWidget.layout().addWidget(self.vispy_canvas.native, 0, 0, 4, 4)
self.vpWidget.layout().addWidget(self.sliderTheta, 5, 0, 1, 4)
self.vpWidget.layout().addWidget(self.sliderPhi, 0, 5, 4, 1)
self.sliderTheta.setOrientation(QtCore.Qt.Horizontal)
self.sliderTheta.setObjectName("sliderTheta")
self.sliderTheta.valueChanged.connect(self.vispy_canvas.update_theta)
self.sliderPhi.setOrientation(QtCore.Qt.Vertical)
self.sliderPhi.setMinimum(-25)
self.sliderPhi.setMaximum(25)
self.sliderPhi.setValue(0)
self.sliderPhi.setObjectName("sliderPhi")
self.sliderPhi.valueChanged.connect(self.vispy_canvas.update_phi)
self.vpWidget.layout().addWidget(self.azimuthLabel, 6, 1, 1, 1)
self.vpWidget.layout().addWidget(self.elevationLabel, 6, 2, 1, 1)
self.vpWidget.layout().addWidget(self.radiusLabel, 6, 3, 1, 1)
else:
self.vp_missing_label = QtWidgets.QLabel("Vispy package missing or deactivated: \n3D speaker representation disabled.")
self.vpWidget.layout().addWidget(self.vp_missing_label, 1, 1, 1, 3)
self.vpWidget.layout().addWidget(self.azimuthLabel, 2, 1, 1, 1)
self.vpWidget.layout().addWidget(self.elevationLabel, 2, 2, 1, 1)
self.vpWidget.layout().addWidget(self.radiusLabel, 2, 3, 1, 1)
# DEVICE STATUS WIDGET
self.device_status_widget = QtWidgets.QGroupBox("Audio Device Status")
self.device_status_widget.setLayout(QtWidgets.QHBoxLayout())
self.device_status_widget.layout().addWidget(AudioDeviceWidget(self.measurement_ref.measurement))
self.device_status_widget.layout().setSizeConstraint(QtWidgets.QLayout.SetFixedSize)
# TRACKER STATUS WIDGET
self.tracker_status_widget = QtWidgets.QGroupBox("Vive Tracker Status")
tracker_status = self.measurement_ref.tracker.check_tracker_availability()
self.tracker1_status_label = QtWidgets.QLabel(tracker_status["tracker1"])
self.tracker2_status_label = QtWidgets.QLabel(tracker_status["tracker2"])
self.tracker1_label = QtWidgets.QLabel("(Head) Tracker 1:")
self.tracker2_label = QtWidgets.QLabel("Tracker 2:")
self.tracker_status_widget.setLayout(QtWidgets.QFormLayout())
self.tracker_status_widget.layout().addRow(self.tracker1_label, self.tracker1_status_label)
self.tracker_status_widget.layout().addRow(self.tracker2_label, self.tracker2_status_label)
self.tracker_status_widget.setMaximumHeight(100)
# OSC STATUS WIDGET
self.osc_status_box = QtWidgets.QGroupBox("OSC Input Status")
self.osc_status_box.setMaximumHeight(100)
self.osc_status_box.setLayout(QtWidgets.QVBoxLayout())
self.osc_status_indicator = QtWidgets.QCheckBox(" OSC Input")
self.osc_status_indicator.setStyleSheet("QCheckBox::indicator"
"{"
"background-color : lightgrey;"
"}")
self.osc_status_indicator.setCheckable(False)
self.osc_status_box.layout().addWidget(self.osc_status_indicator)
self.osc_status_box.hide()
# MANUAL AZ/EL/R box
self.azimuthBox = QtWidgets.QSpinBox()
self.azimuthBox.setMaximum(359)
self.azimuthBox.valueChanged.connect(self.manual_update_az)
self.elevationBox = QtWidgets.QSpinBox()
self.elevationBox.setMaximum(90)
self.elevationBox.setMinimum(-90)
self.elevationBox.valueChanged.connect(self.manual_update_el)
self.radiusBox = QtWidgets.QSpinBox()
self.radiusBox.setMinimum(20)
self.radiusBox.setMaximum(999)
self.radiusBox.valueChanged.connect(self.manual_update_radius)
self.manualAngleBox = QtWidgets.QGroupBox(
"Set angle manually (Only when VIVE trackers are disconnected)")
layout = QtWidgets.QHBoxLayout()
layout.addWidget(QtWidgets.QLabel("Azimuth °"))
layout.addWidget(self.azimuthBox)
layout.addWidget(QtWidgets.QLabel("Elevation °"))
layout.addWidget(self.elevationBox)
layout.addWidget(QtWidgets.QLabel("Radius cm"))
layout.addWidget(self.radiusBox)
layout.setSizeConstraint(QtWidgets.QLayout.SetFixedSize)
self.manualAngleBox.setLayout(layout)
# TAB WIDGET
self.tabWidget = QtWidgets.QTabWidget(self)
self.tabWidget.setEnabled(True)
self.tabWidget.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)
self.tabWidget.setTabPosition(QtWidgets.QTabWidget.North)
self.tabWidget.setTabShape(QtWidgets.QTabWidget.Rounded)
self.tabWidget.setIconSize(QtCore.QSize(32, 32))
self.tabWidget.setDocumentMode(True)
self.tabWidget.setTabsClosable(False)
self.tabWidget.setMovable(False)
self.tabWidget.setTabBarAutoHide(False)
self.tabWidget.setObjectName("tabWidget")
self.tabWidget.currentChanged.connect(self.tab_changed)
self.tab_config = QtWidgets.QWidget()
self.tab_config.setEnabled(True)
self.tab_config.setObjectName("tab_config")
self.tab_config.setLayout(QtWidgets.QVBoxLayout())
self.tab_config.layout().setAlignment(QtCore.Qt.AlignTop)
self.tabWidget.addTab(self.tab_config, "")
self.tab_measure = QtWidgets.QWidget()
self.tab_measure.setEnabled(True)
self.tab_measure.setObjectName("tab_measure")
self.tab_measure.setLayout(QtWidgets.QVBoxLayout())
self.tab_measure.layout().setAlignment(QtCore.Qt.AlignCenter)
self.tabWidget.addTab(self.tab_measure, "")
self.tab_data = QtWidgets.QWidget()
self.tab_data.setEnabled(True)
self.tab_data.setObjectName("tab_data")
self.tab_data.setLayout(QtWidgets.QGridLayout())
#self.tab_data.layout().setAlignment(QtCore.Qt.AlignCenter)
self.tabWidget.addTab(self.tab_data, "")
self.tab_data_index = self.tabWidget.count()-1
self.tab_hpc = QtWidgets.QWidget()
self.tab_hpc.setEnabled(True)
self.tab_hpc.setLayout(QtWidgets.QVBoxLayout())
self.tab_hpc.layout().setAlignment(QtCore.Qt.AlignCenter)
self.tabWidget.addTab(self.tab_hpc, "")
# Config Tab
#############################
#############################
# Config Tab
# Select Tracking Input
############################
self.tracking_input_box = QtWidgets.QGroupBox("Tracking Input")
self.tracking_input_box.setFixedHeight(70)
self.tracking_input_box.setLayout(QtWidgets.QHBoxLayout())
self.tracking_input_vive = QtWidgets.QRadioButton("Vive Trackers")
self.tracking_input_vive.setChecked(True)
self.tracking_input_vive.sourcename = "Vive"
self.tracking_input_vive.toggled.connect(self.select_tracking_input)
self.tracking_input_box.layout().addWidget(self.tracking_input_vive)
self.tracking_input_OSC_direct = QtWidgets.QRadioButton("External: OSC (Az|El|R)")
self.tracking_input_OSC_direct.sourcename = "OSC_direct"
self.tracking_input_OSC_direct.toggled.connect(self.select_tracking_input)
self.tracking_input_box.layout().addWidget(self.tracking_input_OSC_direct)
self.tab_config.layout().addWidget(self.tracking_input_box)
# Config Tab
# Vive Tracker Box
# Show Instructions Dialog Box:
###########################
self.vivetracker_box = QtWidgets.QGroupBox("Tracker Calibration")
self.vivetracker_box.setLayout(QtWidgets.QVBoxLayout())
self.vivetracker_box.layout().setAlignment(QtCore.Qt.AlignTop)
self.vivetracker_box.setFixedHeight(500)
self.tab_config.layout().addWidget(self.vivetracker_box)
self.dlg = InstructionsDialogBox()
self.show_instructions_button = QtWidgets.QPushButton()
self.show_instructions_button.setText("Show Calibration Instructions")
self.show_instructions_button.clicked.connect(self.dlg.show)
self.show_instructions_button.setMaximumWidth(200)
self.vivetracker_box.layout().addWidget(self.show_instructions_button)
# Config Tab
# Vive Tracker Box
# Switch Trackers Box:
###########################
self.switchTrackersButton = QtWidgets.QPushButton()
self.switchTrackersButton.setText("Switch Tracker Roles")
self.switchTrackersButton.setObjectName("switchTrackersButton")
self.switchTrackersButton.setMaximumWidth(200)
self.switchTrackersButton.clicked.connect(self.switch_trackers)
self.vivetracker_box.layout().addWidget(self.switchTrackersButton)
# Config Tab
# Vive Tracker Box
# Delay trackers textfield:
###########################
self.delay_calibration_layout = QtWidgets.QHBoxLayout()
self.delay_calibration_layout.setAlignment(QtCore.Qt.AlignLeft)
self.vivetracker_box.layout().addLayout(self.delay_calibration_layout)
self.calibration_info_label = QtWidgets.QLabel("Delay calibration triggers (s)")
self.delay_calibration_layout.addWidget(self.calibration_info_label)
self.calibration_wait_time = QtWidgets.QSpinBox()
self.delay_calibration_layout.addWidget(self.calibration_wait_time)
# Config Tab
# Vive Tracker Box
# Head Dimensions Dialog:
###########################
self.head_dimensions_dialog = QtWidgets.QDialog()
self.head_dimensions_dialog.setModal(False)
self.head_dimensions_dialog.setWindowTitle("Measure Head Dimensions")
Btn = QtWidgets.QDialogButtonBox.Close
self.head_dimensions_dialog.buttonBox = QtWidgets.QDialogButtonBox(Btn)
self.head_dimensions_dialog.buttonBox.clicked.connect(self.head_dimensions_dialog.close)
self.head_dimensions_dialog.setLayout(QtWidgets.QVBoxLayout())
self.head_dimensions_dialog.layout().setAlignment(QtCore.Qt.AlignLeft)
self.head_dimensions_info = QtWidgets.QLabel("Measure the width and length of the head by holding the tracker to the left, right, front and back of the head (above the ears). This data is not mandatory for the measurement, but can be used as meta data during post processing. It is stored along with the HRIR data.")
self.head_dimensions_info.setWordWrap(True)
self.head_dimensions_dialog.layout().addWidget(self.head_dimensions_info)
self.head_dimensions_formlayout = QtWidgets.QFormLayout()
self.head_dimensions_dialog.layout().addLayout(self.head_dimensions_formlayout)
calibration_button_width = 180
calibration_button_size = QtCore.QSize(calibration_button_width, 50)
self.calibrate_left_head = QtWidgets.QPushButton(text='Left Side')
self.calibrate_left_head.setAutoDefault(False)
# self.calibrate_ear_left.setFixedSize(calibration_button_size)
self.calibrate_left_head.setFixedWidth(calibration_button_width)
self.calibrate_left_head.clicked.connect(lambda: self.calibrate(self.calibrate_head_left))
self.calibrate_left_head_label = QtWidgets.QLabel(text="Uncalibrated")
self.head_dimensions_formlayout.addRow(self.calibrate_left_head, self.calibrate_left_head_label)
self.calibrate_right_head = QtWidgets.QPushButton(text='Right Side')
self.calibrate_right_head.setAutoDefault(False)
# self.calibrate_ear_right.setFixedSize(calibration_button_size)
self.calibrate_right_head.setFixedWidth(calibration_button_width)
self.calibrate_right_head.clicked.connect(lambda: self.calibrate(self.calibrate_head_right))
self.calibrate_right_head_label = QtWidgets.QLabel(text="Uncalibrated")
self.head_dimensions_formlayout.addRow(self.calibrate_right_head, self.calibrate_right_head_label)
self.head_width_label = QtWidgets.QLabel(text="Head Width: - ")
self.head_dimensions_formlayout.addRow(QtWidgets.QLabel(""), self.head_width_label)
self.calibrate_front_head = QtWidgets.QPushButton(text='Front Of Head')
self.calibrate_front_head.setAutoDefault(False)
# self.calibrate_front_head.setFixedSize(calibration_button_size)
self.calibrate_front_head.setFixedWidth(calibration_button_width)
self.calibrate_front_head.clicked.connect(lambda: self.calibrate(self.calibrate_head_front))
self.calibrate_front_head_label = QtWidgets.QLabel(text="Uncalibrated")
self.head_dimensions_formlayout.addRow(self.calibrate_front_head, self.calibrate_front_head_label)
self.calibrate_back_head = QtWidgets.QPushButton(text='Back Of Head')
self.calibrate_back_head.setAutoDefault(False)
# self.calibrate_back_head.setFixedSize(calibration_button_size)
self.calibrate_back_head.setFixedWidth(calibration_button_width)
self.calibrate_back_head.clicked.connect(lambda: self.calibrate(self.calibrate_head_back))
self.calibrate_back_head_label = QtWidgets.QLabel(text="Uncalibrated")
self.head_dimensions_formlayout.addRow(self.calibrate_back_head, self.calibrate_back_head_label)
self.head_length_label = QtWidgets.QLabel(text="Head Length: - ")
self.head_dimensions_formlayout.addRow(QtWidgets.QLabel(""), self.head_length_label)
self.head_dimensions_dialog.layout().addWidget(self.head_dimensions_dialog.buttonBox)
self.show_head_dimensions = QtWidgets.QPushButton()
self.show_head_dimensions.setText("Optional: Head Dimensions")
self.show_head_dimensions.clicked.connect(self.head_dimensions_dialog.show)
self.show_head_dimensions.setMaximumWidth(200)
self.vivetracker_box.layout().addWidget(self.show_head_dimensions)
# Config Tab
# Vive Tracker Box
# Calibration Box
self.calibration_box = QtWidgets.QGroupBox("Tracker Calibration")
self.calibration_box.setLayout(QtWidgets.QVBoxLayout())
self.calibration_box.layout().setAlignment(QtCore.Qt.AlignLeft)
self.vivetracker_box.layout().addWidget(self.calibration_box)
self.calibrations_formlayout = QtWidgets.QFormLayout()
self.calibration_box.layout().addLayout(self.calibrations_formlayout)
calibration_button_width = 180
calibration_button_size = QtCore.QSize(calibration_button_width, 50)
self.calibrate_ear_left = QtWidgets.QPushButton(text='Calibrate Left Ear')
#self.calibrate_ear_left.setFixedSize(calibration_button_size)
self.calibrate_ear_left.setFixedWidth(calibration_button_width)
self.calibrate_ear_left.clicked.connect(lambda: self.calibrate(self.calibrate_left_ear))
self.calibrate_ear_left_label = QtWidgets.QLabel(text="Uncalibrated")
self.calibrations_formlayout.addRow(self.calibrate_ear_left, self.calibrate_ear_left_label)
self.calibrate_ear_right = QtWidgets.QPushButton(text='Calibrate Right Ear')
#self.calibrate_ear_right.setFixedSize(calibration_button_size)
self.calibrate_ear_right.setFixedWidth(calibration_button_width)
self.calibrate_ear_right.clicked.connect(lambda: self.calibrate(self.calibrate_right_ear))
self.calibrate_ear_right_label = QtWidgets.QLabel(text="Uncalibrated")
self.calibrations_formlayout.addRow(self.calibrate_ear_right, self.calibrate_ear_right_label)
self.calibrate_acoustical_center = QtWidgets.QPushButton(text='Calibrate Speaker')
#self.calibrate_acoustical_center.setFixedSize(calibration_button_size)
self.calibrate_acoustical_center.setFixedWidth(calibration_button_width)
self.calibrate_acoustical_center.clicked.connect(lambda: self.calibrate(self.calibrate_acoustical_centre))
self.calibrate_acoustical_center_label = QtWidgets.QLabel(text="Uncalibrated")
self.calibrations_formlayout.addRow(self.calibrate_acoustical_center, self.calibrate_acoustical_center_label)
self.calibrateButton = QtWidgets.QPushButton(self.tab_measure)
self.calibrateButton.setText("Calibrate Orientation")
self.calibrateButton.setObjectName("calibrateButton")
#self.calibrateButton.setFixedSize(calibration_button_size)
self.calibrateButton.setFixedWidth(calibration_button_width)
self.calibrateButton.clicked.connect(lambda: self.calibrate(self.calibrate_orientation))
self.calibrate_orientation_label = QtWidgets.QLabel("Uncalibrated")
self.calibrations_formlayout.addRow(self.calibrateButton, self.calibrate_orientation_label)
# Config Tab
# OSC Config Box
############################
self.osc_config_box = QtWidgets.QGroupBox("OSC Configuration")
self.osc_config_box.setLayout(QtWidgets.QVBoxLayout())
self.osc_config_box.setFixedHeight(500)
self.osc_config_box.layout().setAlignment(QtCore.Qt.AlignTop)
self.osc_config_box.hide()
self.osc_ip_label = QtWidgets.QLabel("Current Host IP: ")
self.osc_port_label = QtWidgets.QLabel("OSC Server Port: ")
self.osc_address_label = QtWidgets.QLabel("Listening for list of [Az, El, R] on osc-address '/guided_hrtfs/angle'")
self.osc_address_label.setWordWrap(True)
self.osc_config_box.layout().addWidget(self.osc_ip_label)
self.osc_config_box.layout().addWidget(self.osc_port_label)
self.osc_config_box.layout().addWidget(self.osc_address_label)
self.tab_config.layout().addWidget(self.osc_config_box)
# Config Tab
# Measurement Parameters Box:
############################
self.measuremet_paramteres_box = QtWidgets.QGroupBox("Measurement Parameters")
self.measuremet_paramteres_box.setLayout(QtWidgets.QVBoxLayout())
self.sweep_parameters_dialog = QtWidgets.QDialog()
self.sweep_parameters_dialog.setModal(False)
self.sweep_parameters_dialog.setWindowTitle("Sweep Parameters")
Btn_ok = QtWidgets.QDialogButtonBox.Ok
self.sweep_parameters_dialog.buttonBox = QtWidgets.QDialogButtonBox(Btn_ok)
self.sweep_parameters_dialog.buttonBox.clicked.connect(self.update_sweep_parameters)
self.sweep_parameters_dialog.setLayout(QtWidgets.QVBoxLayout())
self.sweep_parameters_dialog.layout().setAlignment(QtCore.Qt.AlignLeft)
self.sweep_parameters_formlayout = QtWidgets.QFormLayout()
self.sweep_parameters_dialog.layout().addLayout(self.sweep_parameters_formlayout)
# get current parameters
sweep_params = self.measurement_ref.measurement.get_sweep_parameters()
# add row entries for each parameter
self.sweeplength_sec = QtWidgets.QLineEdit(str(sweep_params['sweeplength_sec']))
self.sweep_parameters_formlayout.addRow(self.sweeplength_sec, QtWidgets.QLabel(text='Sweep length (sec)'))
self.post_silence_sec = QtWidgets.QLineEdit(str(sweep_params['post_silence_sec']))
self.sweep_parameters_formlayout.addRow(self.post_silence_sec, QtWidgets.QLabel(text='Silence after sweep (sec)'))
self.f_start = QtWidgets.QLineEdit(str(sweep_params['f_start']))
self.sweep_parameters_formlayout.addRow(self.f_start, QtWidgets.QLabel(text='Sweep start frequency (Hz)'))
self.f_end = QtWidgets.QLineEdit(str(sweep_params['f_end']))
self.sweep_parameters_formlayout.addRow(self.f_end, QtWidgets.QLabel(text='Sweep stop frequency (Hz)'))
self.amp_db = QtWidgets.QLineEdit(str(sweep_params['amp_db']))
self.sweep_parameters_formlayout.addRow(self.amp_db, QtWidgets.QLabel(text='Sweep gain (dB)'))
self.fade_out_samples = QtWidgets.QLineEdit(str(sweep_params['fade_out_samples']))
self.sweep_parameters_formlayout.addRow(self.fade_out_samples, QtWidgets.QLabel(text='Fadeout before sweep end (samples)'))
self.sweep_parameters_errormessage = QtWidgets.QLabel("Invalid Sweep Paramters")
self.sweep_parameters_formlayout.addRow(self.sweep_parameters_errormessage)
self.sweep_parameters_errormessage.setVisible(False)
# add bottom button box
self.sweep_parameters_dialog.layout().addWidget(self.sweep_parameters_dialog.buttonBox)
self.show_sweep_parameters = QtWidgets.QPushButton()
self.show_sweep_parameters.setText("Set Sweep Parameters")
self.show_sweep_parameters.clicked.connect(self.sweep_parameters_dialog.show)
self.show_sweep_parameters.setMaximumWidth(200)
self.measuremet_paramteres_box.layout().addWidget(self.show_sweep_parameters)
self.tab_config.layout().addWidget(self.measuremet_paramteres_box)
# Config Tab
# Output Folder Box:
############################
self.output_folder_box = QtWidgets.QGroupBox("Select output folder for measured data")
self.output_folder_box.setFixedHeight(80)
self.output_folder_box.setLayout(QtWidgets.QHBoxLayout())
path = os.getcwd()
path = os.path.join(path, "Measurements")
if not os.path.exists(path):
try:
os.mkdir(path)
except:
path = os.getcwd()
self.measurement_ref.set_output_path(path)
self.output_folder_select = QtWidgets.QLineEdit()
self.output_folder_select.setText(path)
self.output_folder_box.layout().addWidget(self.output_folder_select)
self.select_folder_button = QtWidgets.QPushButton()
self.select_folder_button.setText("...")
self.select_folder_button.clicked.connect(self.select_folder_dialog)
self.output_folder_box.layout().addWidget(self.select_folder_button)
self.tab_config.layout().addWidget(self.output_folder_box)
# Config Tab
# Send OSC Box:
############################
self.send_osc_box = QtWidgets.QGroupBox("Send OSC data to external application")
self.send_osc_box.setFixedHeight(200)
self.send_osc_box.setLayout(QtWidgets.QFormLayout())
self.send_osc_box.layout().setLabelAlignment(QtCore.Qt.AlignLeft)
ip, port, address = self.measurement_ref.get_osc_parameters()
self.send_osc_ip_select = QtWidgets.QLineEdit()
self.send_osc_ip_select.setText(ip)
self.send_osc_box.layout().addRow("OSC IP Address: ", self.send_osc_ip_select)
self.send_osc_port_select = QtWidgets.QLineEdit()
self.send_osc_port_select.setText(f'{port}')
self.send_osc_box.layout().addRow("OSC Port: ", self.send_osc_port_select)
self.send_osc_address_select = QtWidgets.QLineEdit()
self.send_osc_address_select.setText(address)
self.send_osc_box.layout().addRow("OSC Address: ", self.send_osc_address_select)
self.send_osc_button = QtWidgets.QPushButton()
self.send_osc_button.setText("Send OSC")
self.send_osc_button.clicked.connect(self.activate_osc_send)
self.send_osc_button.setFixedSize(100, 50)
self.send_osc_button.setCheckable(True)
#self.send_osc_button.setStyleSheet("background-color : lightgrey")
self.send_osc_box.layout().addRow(self.send_osc_button)
self.tab_config.layout().addWidget(self.send_osc_box)
## MEASURE TAB
#############################
#############################
self.measurements_main_group = QtWidgets.QGroupBox()
self.measurements_main_group.setLayout(QtWidgets.QHBoxLayout())
self.measurements_main_group.layout().addWidget(QtWidgets.QLabel("Session Name:"))
self.session_name = QtWidgets.QLineEdit()
self.measurements_main_group.layout().addWidget(self.session_name)
self.measurements_main_group.layout().addStretch()
self.clear_measurements_button = QtWidgets.QPushButton("Clear / Start New")
self.clear_measurements_button.clicked.connect(self.clear_measurements)
self.measurements_main_group.layout().addWidget(self.clear_measurements_button)
self.tab_measure.layout().addWidget(self.measurements_main_group)
self.startMeasurementGroupBox = QtWidgets.QGroupBox('Start Measurement')
self.startMeasurementGroupBox.setLayout(QtWidgets.QGridLayout())
self.centerTriggerButton = QtWidgets.QPushButton('Center Measurement')
self.centerTriggerButton.setObjectName("Center Measurement")
self.centerTriggerButton.clicked.connect(self.trigger_center_measurement)
self.measurementTriggerButton = QtWidgets.QPushButton('Single Measurement')
self.measurementTriggerButton.setObjectName("Single Measurement")
self.measurementTriggerButton.setFixedSize(QtCore.QSize(200, 100))
self.measurementTriggerButton.clicked.connect(self.measurement_ref.trigger_measurement)
self.autoTriggerButton = QtWidgets.QPushButton('Auto Measurement')
self.autoTriggerButton.clicked.connect(self.measurement_ref.trigger_auto_measurement)
self.autoMeasurementTriggerProgress = QtWidgets.QProgressBar()
self.autoMeasurementTriggerProgress.setVisible(False)
self.autoTriggerStopButton = QtWidgets.QPushButton('Stop Auto Measurement')
self.autoTriggerStopButton.clicked.connect(self.measurement_ref.stop_auto_measurement)
#self.startMeasurementGroupBox.layout().addStretch()
self.startMeasurementGroupBox.layout().addWidget(self.centerTriggerButton, 1, 0, 1, 1)
self.startMeasurementGroupBox.layout().addWidget(self.measurementTriggerButton, 0, 1, 3, 1)
self.startMeasurementGroupBox.layout().addWidget(self.autoTriggerButton, 1, 2, 1, 1)
self.startMeasurementGroupBox.layout().addWidget(self.autoMeasurementTriggerProgress, 2, 2, 1, 1)
self.startMeasurementGroupBox.layout().addWidget(self.autoTriggerStopButton, 1, 3, 1, 1)
#self.startMeasurementGroupBox.layout().addStretch()
self.tab_measure.layout().addWidget(self.startMeasurementGroupBox)
self.point_recommender_groupbox = QtWidgets.QGroupBox('Point Recommender')
self.point_recommender_groupbox.setLayout(QtWidgets.QHBoxLayout())
self.point_recommender_groupbox.setEnabled(False)
self.recommend_point_button = QtWidgets.QPushButton('Recommend Point')
self.recommend_point_button.clicked.connect(self.trigger_point_recommendation)
self.start_guiding_button = QtWidgets.QPushButton('Start Guidance')
self.start_guiding_button.clicked.connect(self.trigger_guided_measurement)
self.clear_recommended_points_button = QtWidgets.QPushButton('Clear Recommendations')
self.clear_recommended_points_button.clicked.connect(self.clear_recommended_points)
self.point_recommender_groupbox.layout().addStretch()
self.point_recommender_groupbox.layout().addWidget(self.recommend_point_button)
self.point_recommender_groupbox.layout().addWidget(self.start_guiding_button)
self.point_recommender_groupbox.layout().addWidget(self.clear_recommended_points_button)
self.tab_measure.layout().addWidget(self.point_recommender_groupbox)
self.plotgroupbox = QtWidgets.QGroupBox('Measurement Plots')
self.plotgroupbox.setLayout(QtWidgets.QVBoxLayout())
self.plot_widget = PlotWidget()
self.plotgroupbox.layout().addWidget(self.plot_widget)
self.tab_measure.layout().addWidget(self.plotgroupbox)
## DATA LIST TAB
#############################
self.positions_table = QtWidgets.QTableView()
self.positions_table.setModel(self.measurement_ref.positions_list)
self.positions_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
self.positions_table.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
self.positions_table.verticalHeader().show()
self.positions_table.horizontalHeader().setSectionResizeMode(1)
self.positions_table.verticalHeader().setSectionResizeMode(3)
self.positions_table.setFont(QtGui.QFont('Helvetica', 13))
self.positions_table.setShowGrid(False)
#self.positions_table.setMaximumWidth(300)
self.positions_table_selection = self.positions_table.selectionModel()
self.positions_table_selection.currentRowChanged.connect(self.data_table_selection)
self.tab_data.layout().addWidget(self.positions_table, 0, 0, 1, 1)
self.remove_measurement_button = QtWidgets.QPushButton("Delete Selected")
self.remove_measurement_button.clicked.connect(self.remove_measurement)
self.tab_data.layout().addWidget(self.remove_measurement_button, 1, 0, 1, 1)
self.plot_widget2 = PlotWidget()
#self.plot_widget2.setMaximumWidth(200)
self.tab_data.layout().addWidget(self.plot_widget2, 0, 1, 1, 1)
## HEADPHONE COMPENSATION TAB
#############################
self.hp_main_group = QtWidgets.QGroupBox()
self.hp_main_group.setLayout(QtWidgets.QHBoxLayout())
self.hp_main_group.layout().addWidget(QtWidgets.QLabel("Headphone Name:"))
self.headphone_name = QtWidgets.QLineEdit()
self.hp_main_group.layout().addWidget(self.headphone_name)
self.hp_main_group.layout().addStretch()
self.clear_hp_measurements_button = QtWidgets.QPushButton("Clear / Start New")
self.clear_hp_measurements_button.clicked.connect(self.clear_hp_measurements)
self.hp_main_group.layout().addWidget(self.clear_hp_measurements_button)
self.tab_hpc.layout().addWidget(self.hp_main_group)
self.hp_controls_group = QtWidgets.QGroupBox()
self.hp_controls_group.setLayout(QtWidgets.QHBoxLayout())
self.hp_controls_group.setAlignment(QtCore.Qt.AlignLeft)
self.trigger_hp_measurement_button = QtWidgets.QPushButton("Trigger Headphone \n Measurement")
self.trigger_hp_measurement_button.clicked.connect(self.trigger_hp_measurement)
self.trigger_hp_measurement_button.setFixedSize(QtCore.QSize(200, 100))
self.hp_controls_group.layout().addWidget(self.trigger_hp_measurement_button)
self.remove_hp_measurement_button = QtWidgets.QPushButton("Remove Last \n HP Measurement")
self.remove_hp_measurement_button.clicked.connect(self.remove_hp_measurement)
self.remove_measurement_button.setFixedSize(QtCore.QSize(200, 50))
self.hp_controls_group.layout().addWidget(self.remove_hp_measurement_button)
self.hp_controls_group.layout().addStretch()
self.hp_measurement_count = QtWidgets.QLabel("")
# self.hp_measurement_count.setFixedWidth(16)
self.hp_controls_group.layout().addWidget(self.hp_measurement_count)
self.tab_hpc.layout().addWidget(self.hp_controls_group)
#self.plot_hpc_widget = PlotWidget()
#self.tab_hpc.layout().addWidget(self.plot_hpc_widget)
self.plot_hpirs_widget = PlotWidget_HPIRs()
self.tab_hpc.layout().addWidget(self.plot_hpirs_widget)
self.reg_beta_layout = QtWidgets.QHBoxLayout()
self.reg_beta_layout.setAlignment(QtCore.Qt.AlignCenter)
self.reg_beta_layout.addWidget(QtWidgets.QLabel("Reg Beta:"))
self.regularization_beta_box = QtWidgets.QDoubleSpinBox()
self.regularization_beta_box.setMaximum(1.0)
self.regularization_beta_box.setSingleStep(0.05)
self.regularization_beta_box.setValue(0.4)
self.regularization_beta_box.setFixedWidth(100)
self.regularization_beta_box.valueChanged.connect(self.set_regularization_beta)
self.reg_beta_layout.addWidget(self.regularization_beta_box)
self.tab_hpc.layout().addLayout(self.reg_beta_layout)
self.plot_hpcf_widget = PlotWidget_HPCF()
self.tab_hpc.layout().addWidget(self.plot_hpcf_widget)
self.plot_hptf(np.array([]))
self.plot_hpc_estimate(np.array([]), np.array([]))
## Layout finalilzation
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.addWidget(self.tabWidget, 0, 1, 4, 1)
self.gridLayout.addWidget(self.vpWidget, 0, 0, 1, 1)
self.gridLayout.addWidget(self.device_status_widget, 1, 0, 1, 1)
self.gridLayout.addWidget(self.tracker_status_widget, 2, 0, 1, 1)
self.gridLayout.addWidget(self.osc_status_box, 2, 0, 1, 1)
self.gridLayout.addWidget(self.manualAngleBox, 3, 0, 1, 1)
self.gridLayout.setColumnStretch(0, 10)
self.gridLayout.setColumnStretch(1, 10)
self.cwidget.setLayout(self.gridLayout)
#self.gridLayout.setSizeConstraint(QtWidgets.QLayout.SetFixedSize)
self.resize(1100, 600)
# self.menubar = QtWidgets.QMenuBar(MainWindow)
# self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
# self.menubar.setObjectName("menubar")
# MainWindow.setMenuBar(self.menubar)
# self.statusbar = QtWidgets.QStatusBar(MainWindow)
# self.statusbar.setObjectName("statusbar")
# MainWindow.setStatusBar(self.statusbar)
self.tabWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(self)
self.measurement_ref.register_gui_handler(self)
def closeEvent(self, *args, **kwargs):
super(QtWidgets.QMainWindow, self).closeEvent(*args, **kwargs)
def resizeEvent(self, event):
_translate = QtCore.QCoreApplication.translate
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_config), _translate("MainWindow", "Configure"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_measure), _translate("MainWindow", "Measure"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_data), _translate("MainWindow", "Data List"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_hpc), _translate("MainWindow", "Headphone Compensation"))
self.positions_table.setColumnWidth(0, self.positions_table.width() / 3)
self.positions_table.setColumnWidth(1, self.positions_table.width() / 3)
self.positions_table.setColumnWidth(2, self.positions_table.width() / 3)
def manual_update_az(self):
self.measurement_ref.tracker.fallback_angle[0] = self.azimuthBox.value()
def manual_update_el(self):
self.measurement_ref.tracker.fallback_angle[1] = self.elevationBox.value()
def manual_update_radius(self):
self.measurement_ref.tracker.fallback_angle[2] = self.radiusBox.value() / 100
def add_measurement_point(self, az, el):
if use_vispy:
self.vispy_canvas.meas_points.add_point(az, el)
def add_center_point(self):
if use_vispy:
self.vispy_canvas.center_points.add_point(0, 0)
#def remove_measurement_point(self, az, el):
def plot_recordings(self, rec_l, rec_r, fb_loop, fs, fb_loop_used=False):
self.plot_widget.plot_recordings(rec_l, rec_r, fb_loop, fs=fs, fb_loop_used=fb_loop_used)
def plot_IRs(self, ir_l, ir_r, fs):
self.plot_widget.plot_IRs(ir_l, ir_r, fs=fs)
def updateMeasurementList(self, measurement_data):
pass
def switch_trackers(self):
self.measurement_ref.tracker.switch_trackers()
if self.measurement_ref.tracker.trackers_switched:
self.tracker1_label = QtWidgets.QLabel("Tracker 1:")
self.tracker2_label = QtWidgets.QLabel("(Head) Tracker 2:")
else:
self.tracker1_label = QtWidgets.QLabel("(Head) Tracker 1:")
self.tracker2_label = QtWidgets.QLabel("Tracker 2:")
def update_tracker_status(self, status):
self.tracker1_status_label.setText(status["tracker1"])
self.tracker2_status_label.setText(status["tracker2"])
if status["tracker1"] == "Tracking" and status["tracker2"] == "Tracking" \
or self.measurement_ref.tracker.tracking_mode == "OSC_direct":
self.show_manual_angle_box(False)
else:
self.show_manual_angle_box(True)
def show_manual_angle_box(self, show):
if show:
if self.gridLayout.indexOf(self.manualAngleBox) == -1:
self.gridLayout.removeWidget(self.tabWidget)
self.gridLayout.addWidget(self.tabWidget, 0, 1, 4, 1)
self.gridLayout.addWidget(self.manualAngleBox, 3, 0, 1, 1)
self.manualAngleBox.setVisible(True)
else:
if self.gridLayout.indexOf(self.manualAngleBox) != -1:
self.gridLayout.removeWidget(self.tabWidget)
self.gridLayout.removeWidget(self.manualAngleBox)
self.manualAngleBox.setVisible(False)
self.gridLayout.addWidget(self.tabWidget, 0, 1, 3, 1)
def updateCurrentAngle(self, az, el, r):
r = r*100
self.azimuthLabel.setText("Az: %.0f°" % az)
self.elevationLabel.setText("El: %.0f°" % el)
self.radiusLabel.setText("Radius: %.0fcm" % r)
def set_offset_speaker_z(self):
self.measurement_ref.tracker.offset_cm['speaker_z'] = self.offset_speaker_z.value()
def set_offset_speaker_y(self):
self.measurement_ref.tracker.offset_cm['speaker_y'] = self.offset_speaker_y.value()
def set_offset_head_y(self):
self.measurement_ref.tracker.offset_cm['head_y'] = self.offset_head_y.value()
def select_folder_dialog(self):
path = QtWidgets.QFileDialog.getExistingDirectory(self.cwidget,
'Open Directory',
self.output_folder_select.text(),
QtWidgets.QFileDialog.ShowDirsOnly | QtWidgets.QFileDialog.DontResolveSymlinks)
if path:
self.output_folder_select.setText(path)
self.measurement_ref.set_output_path(path)
# helper function to give all calibration functions the time delay
def calibrate(self, calibration_function):
interval = self.calibration_wait_time.value() * 1000
QtCore.QTimer.singleShot(interval, calibration_function)
def calibrate_orientation(self):
if self.measurement_ref.tracker.calibrate_orientation():
self.measurement_ref.measurement.play_sound(True)
self.calibrate_orientation_label.setText("Calibrated")
else:
self.measurement_ref.measurement.play_sound(False)
# NOTES on the calibrating of head dimensions:
# left_ear and right_ear are for yielding the correct head center.
# head_left and head_right are for yielding the correct anthropometric head width
# head_front and head_right are for yielding the correct anthropometric head length
def calibrate_left_ear(self):
if self.measurement_ref.tracker.calibrate_headdimensions('left_ear', multiple_calls=False):
self.calibrate_ear_left_label.setText(f"Calibrated")#, {self.measurement_ref.tracker.head_dimensions["ear_pos_l"]}")
self.measurement_ref.measurement.play_sound(True)
else:
self.measurement_ref.measurement.play_sound(False)
if self.measurement_ref.tracker.head_dimensions['ear_pos_l'] is not None:
self.calibrate_ear_left_label.setText(f"Recalibration failed")#, {self.measurement_ref.tracker.head_dimensions["ear_pos_l"]}")
def calibrate_right_ear(self):
if self.measurement_ref.tracker.calibrate_headdimensions('right_ear', multiple_calls=False):
self.calibrate_ear_right_label.setText(f"Calibrated")#, {self.measurement_ref.tracker.head_dimensions["ear_pos_r"]}")
self.measurement_ref.measurement.play_sound(True)
else:
self.measurement_ref.measurement.play_sound(False)
if self.measurement_ref.tracker.head_dimensions['ear_pos_r'] is not None:
self.calibrate_ear_right_label.setText(f"Recalibration failed")#, {self.measurement_ref.tracker.head_dimensions["ear_pos_r"]}")
def calibrate_head_left(self):
if self.measurement_ref.tracker.calibrate_headdimensions('left'):
self.measurement_ref.measurement.play_sound(True)
self.calibrate_left_head_label.setText("Calibrated")
if self.measurement_ref.tracker.head_dimensions['head_width'] is not None:
self.head_width_label.setText(f"Head Width: {self.measurement_ref.tracker.head_dimensions["head_width"]:.3f}")
else:
self.calibrate_left_head_label.setText("Calibration Failed")
self.measurement_ref.measurement.play_sound(False)
def calibrate_head_right(self):
if self.measurement_ref.tracker.calibrate_headdimensions('right'):
self.measurement_ref.measurement.play_sound(True)
self.calibrate_right_head_label.setText("Calibrated")
if self.measurement_ref.tracker.head_dimensions['head_width'] is not None:
self.head_width_label.setText(f"Head Width: {self.measurement_ref.tracker.head_dimensions["head_width"]:.3f}")
else:
self.calibrate_right_head_label.setText("Calibration Failed")
self.measurement_ref.measurement.play_sound(False)
def calibrate_head_front(self):
if self.measurement_ref.tracker.calibrate_headdimensions('front'):
self.measurement_ref.measurement.play_sound(True)
self.calibrate_front_head_label.setText("Calibrated")
if self.measurement_ref.tracker.head_dimensions['head_length'] is not None:
self.head_length_label.setText(f"Head Length: {self.measurement_ref.tracker.head_dimensions["head_length"]:.3f}")
else:
self.calibrate_front_head_label.setText("Calibration Failed")
self.measurement_ref.measurement.play_sound(False)
def calibrate_head_back(self):
if self.measurement_ref.tracker.calibrate_headdimensions('back'):
self.measurement_ref.measurement.play_sound(True)
self.calibrate_back_head_label.setText("Calibrated")
if self.measurement_ref.tracker.head_dimensions['head_length'] is not None:
self.head_length_label.setText(f"Head Length: {self.measurement_ref.tracker.head_dimensions["head_length"]:.3f}")
else:
self.calibrate_back_head_label.setText("Calibration Failed")
def calibrate_acoustical_centre(self):
if self.measurement_ref.tracker.calibrate_acoustical_center():
self.measurement_ref.measurement.play_sound(True)
self.calibrate_acoustical_center_label.setText(f'Calibrated')#, {self.measurement_ref.tracker.acoustical_center_pos}')
else:
self.measurement_ref.measurement.play_sound(False)
def trigger_center_measurement(self):
interval = 0.5 * 1000
QtCore.QTimer.singleShot(interval, self.measurement_ref.trigger_center_measurement)
def trigger_point_recommendation(self):
az, el = self.measurement_ref.recommend_points(1)
def trigger_guided_measurement(self):
self.measurement_ref.start_guided_measurement()
def clear_recommended_points(self):
self.measurement_ref.clear_recommended_points()
def enable_point_recommendation(self):
self.point_recommender_groupbox.setEnabled(True)
def data_table_selection(self, selected, deselected):
if use_vispy:
self.vispy_canvas.meas_points.deselect_points(deselected.row())
self.vispy_canvas.meas_points.select_point(selected.row())
#print("Data Table Selection: " + str(selected.row()))
idx = selected.row()
try:
ir_l = self.measurement_ref.measurements[idx, 0, :]
ir_r = self.measurement_ref.measurements[idx, 1, :]
raw_l = self.measurement_ref.raw_signals[idx, 0, :]
raw_r = self.measurement_ref.raw_signals[idx, 1, :]
fb = self.measurement_ref.raw_feedbackloop[idx, 0, :]
self.plot_widget2.plot_IRs(ir_l, ir_r, plot='spectrogram')
self.plot_widget2.plot_recordings(raw_l, raw_r, fb, fs=self.measurement_ref.measurement.get_samplerate(), plot='spectrogram', fb_loop_used=self.measurement_ref.measurement.feedback_loop_used)
except IndexError:
print("Could not plot data: Invalid id")
def tab_changed(self, index):
try:
if index is not self.tab_data_index:
if use_vispy:
self.vispy_canvas.meas_points.deselect_points()
else:
numRows = self.positions_table.model().rowCount(QtCore.QModelIndex())
self.positions_table.selectRow(numRows-1)
except AttributeError:
pass
def clear_measurements(self):
self.measurement_ref.delete_all_measurements()
self.session_name.clear()
def remove_measurement(self):
indexes = self.positions_table_selection.selectedRows()
for index in indexes:
id = index.row()
dialog = QtWidgets.QMessageBox
ret = dialog.question(self,'', "Are you sure you want to delete this measurement?", dialog.Yes | dialog.No)
if ret == dialog.Yes:
#print("Deleting Measurement " + str(id))
self.measurement_ref.delete_measurement(id)
def update_dev_status(self):
devs = self.measurement_ref.devices
self.label_out_exc.setText(devs['out_excitation'])
self.label_out_exc_2.setText(devs['out_excitation_2'])
self.label_out_fb.setText(devs['out_feedback'])
self.label_in_left.setText(devs['in_left'])
self.label_in_right.setText(devs['in_right'])
self.label_in_fb.setText(devs['in_feedback'])
def trigger_hp_measurement(self):
self.measurement_ref.hp_measurement()
def remove_hp_measurement(self):
self.measurement_ref.remove_hp_measurement()
# def plot_hpc_recordings(self, rec_l, rec_r, fb_loop):
# self.plot_hpc_widget.plot_recordings(rec_l, rec_r, fb_loop)
def plot_hptf(self, hpc_irs, hpc_average=None, fs=48000):
self.plot_hpirs_widget.plot_hptf(hpc_irs, hpc_average=hpc_average, fs=fs)
def plot_hpc_estimate(self, H_l, H_r, fs=48000):
self.plot_hpcf_widget.plot_hpcf(H_l, H_r, fs=fs)
def set_regularization_beta(self):
self.measurement_ref.estimate_hpcf(self.regularization_beta_box.value())
def clear_hp_measurements(self):
self.measurement_ref.remove_all_hp_measurements()
self.headphone_name.clear()
def warning_invalid_tracking(self, warning=True):
palette = self.tracker_status_widget.palette()
if warning:
palette.setColor(QtGui.QPalette.Window, QtGui.QColor('red'))
else:
palette.setColor(QtGui.QPalette.Window, QtGui.QColor('grey'))
self.tracker_status_widget.setPalette(palette)
self.tracker_status_widget.setAutoFillBackground(True)
self.tracker_status_widget.repaint()
def select_tracking_input(self):
radioButton = self.tracking_input_box.sender()
if radioButton.isChecked():
if radioButton.sourcename == "Vive":
self.vivetracker_box.show()
self.osc_config_box.hide()
self.osc_status_box.hide()
self.tracker_status_widget.show()
self.measurement_ref.tracker.set_tracking_mode(radioButton.sourcename)
self.send_osc_box.setEnabled(True)
if radioButton.sourcename == "OSC_direct":
self.vivetracker_box.hide()
self.osc_config_box.show()
self.tracker_status_widget.hide()
self.osc_status_box.show()
self.measurement_ref.tracker.set_tracking_mode(radioButton.sourcename)
ip, port = self.measurement_ref.tracker.osc_input_server.get_current_ip_and_port()
self.osc_ip_label.setText(f"Current Host IP: {ip}")
self.osc_port_label.setText(f"OSC Server Port: {port}")
self.send_osc_box.setEnabled(False)
self.show_manual_angle_box(False)
def set_osc_status(self, osc_status):
if osc_status:
#self.osc_status_indicator.setStyleSheet("color: green")
self.osc_status_indicator.setStyleSheet("QCheckBox::indicator"
"{"
"background-color : lightgreen;"
"}")
else:
#self.osc_status_indicator.setStyleSheet("color: white")
self.osc_status_indicator.setStyleSheet("QCheckBox::indicator"
"{"
"background-color : white;"
"}")
def activate_osc_send(self):
checked = self.send_osc_button.isChecked()
if self.send_osc_button.isChecked():
if self.measurement_ref.start_osc_send(self.send_osc_ip_select.text(), self.send_osc_port_select.text(), self.send_osc_address_select.text()):
self.send_osc_ip_select.setEnabled(False)
self.send_osc_port_select.setEnabled(False)
self.send_osc_address_select.setEnabled(False)
self.tracking_input_OSC_direct.setEnabled(False)
else:
self.send_osc_button.setChecked(False)
else:
self.measurement_ref.stop_osc_send()
self.send_osc_ip_select.setEnabled(True)
self.send_osc_port_select.setEnabled(True)
self.send_osc_address_select.setEnabled(True)
self.tracking_input_OSC_direct.setEnabled(True)
def update_sweep_parameters(self):
try:
self.measurement_ref.measurement.set_sweep_parameters(d_sweep_sec=float(self.sweeplength_sec.text()),
d_post_silence_sec=float(self.post_silence_sec.text()),
f_start=int(self.f_start.text()),
f_end = int(self.f_end.text()),
amp_db=float(self.amp_db.text()),
fade_out_samples=int(self.fade_out_samples.text()))
except ValueError:
self.sweep_parameters_errormessage.setVisible(True)
return
self.sweep_parameters_errormessage.setVisible(False)
self.sweep_parameters_dialog.close()
return
def deactivate_vispy(self):
use_vispy = False
self.vpWidget.layout().removeWidget(self.vispy_canvas.native)
self.vpWidget.layout().removeWidget(self.sliderTheta)
self.vpWidget.layout().removeWidget(self.sliderPhi)
self.vispy_canvas.native.hide()
self.sliderTheta.hide()
self.sliderPhi.hide()
#del self.vispy_canvas
#del self.sliderPhi
#del self.sliderTheta
self.vp_missing_label = QtWidgets.QLabel(
"Vispy package missing or deactivated: \n3D speaker representation disabled.")
self.vpWidget.layout().addWidget(self.vp_missing_label, 1, 1, 1, 3)
class InstructionsDialogBox(QtWidgets.QDialog):
def __init__(self, *args, **kwargs):
instruction_text = \
"1. Mount tracker T1 on listener head. The orientation and exact position are not important, as long as it stays fixed. \n\n" \
"2. Check if tracker roles are correct by rotating tracker T2. The angles shouldn't change since only the position of tracker T2 is used. Switch tracker roles if necessary\n\n" \
"3. Hold tracker T2 to both ears (bottom center on ear canal) and calibrate each ear. Tracker T2 orientation does not matter here, but from now on tracker T1 (on the listeners head) has to stay fixed & stable on the head.\n\n" \
"4. Hold tracker T2 to acoustical center of speaker and calibrate it. Tracker orientation does not matter here\n\n" \
"5. Put tracker T2 on a planar surface (eg. on top of speaker, floor) pointing towards the same direction as frontal view of listener. Translation does not matter here\n\n" \
"NOTE: If acoustical center is calibrated, this calibrated position stays fixed. If the speaker is moved the calibration has to be repeated."
super(InstructionsDialogBox, self).__init__(*args, **kwargs)
self.setModal(False)
self.setWindowTitle("Calibration Instructions")
self.instructionsbox = QtWidgets.QLabel()
self.instructionsbox.setText(instruction_text)
self.instructionsbox.setWordWrap(True)
Btn = QtWidgets.QDialogButtonBox.Close
self.buttonBox = QtWidgets.QDialogButtonBox(Btn)
self.buttonBox.clicked.connect(self.close)
self.layout = QtWidgets.QVBoxLayout()
self.layout.addWidget(self.instructionsbox)
self.layout.addWidget(self.buttonBox)
self.setLayout(self.layout)
| # -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets
import numpy as np
import os
from GUI.audio_device_widget import AudioDeviceWidget
from GUI.plot_widget import PlotWidget, PlotWidget_HPIRs, PlotWidget_HPCF
use_vispy = True
try:
from GUI.vispyWidget import VispyCanvas
except ImportError:
use_vispy = False
class UiMainWindow(QtWidgets.QMainWindow):
def __init__(self, measurement_ref):
super().__init__()
self.setObjectName("MainWindow")
self.cwidget = QtWidgets.QWidget()
self.setCentralWidget(self.cwidget)
self.measurement_ref = measurement_ref
self.setWindowTitle("FreeGrid")
# VISPY WIDGET
self.azimuthLabel = QtWidgets.QLabel("Az: ")
self.azimuthLabel.setFont(QtGui.QFont("Arial", 24))
self.azimuthLabel.setMaximumHeight(30)
self.elevationLabel = QtWidgets.QLabel("El: ")
self.elevationLabel.setFont(QtGui.QFont("Arial", 24))
self.elevationLabel.setMaximumHeight(30)
self.radiusLabel = QtWidgets.QLabel("Radius: ")
self.radiusLabel.setFont(QtGui.QFont("Arial", 15))
self.radiusLabel.setMaximumHeight(30)
self.vpWidget = QtWidgets.QGroupBox("Virtual Speaker Position")
self.vpWidget.setObjectName("vpWidget")
self.vpWidget.setLayout(QtWidgets.QGridLayout())
if use_vispy:
self.vpWidget.setMinimumSize(400, 400)
self.vispy_canvas = VispyCanvas(self, measurement_ref)
self.sliderTheta = QtWidgets.QSlider()
self.sliderPhi = QtWidgets.QSlider()
self.vpWidget.layout().addWidget(self.vispy_canvas.native, 0, 0, 4, 4)
self.vpWidget.layout().addWidget(self.sliderTheta, 5, 0, 1, 4)
self.vpWidget.layout().addWidget(self.sliderPhi, 0, 5, 4, 1)
self.sliderTheta.setOrientation(QtCore.Qt.Horizontal)
self.sliderTheta.setObjectName("sliderTheta")
self.sliderTheta.valueChanged.connect(self.vispy_canvas.update_theta)
self.sliderPhi.setOrientation(QtCore.Qt.Vertical)
self.sliderPhi.setMinimum(-25)
self.sliderPhi.setMaximum(25)
self.sliderPhi.setValue(0)
self.sliderPhi.setObjectName("sliderPhi")
self.sliderPhi.valueChanged.connect(self.vispy_canvas.update_phi)
self.vpWidget.layout().addWidget(self.azimuthLabel, 6, 1, 1, 1)
self.vpWidget.layout().addWidget(self.elevationLabel, 6, 2, 1, 1)
self.vpWidget.layout().addWidget(self.radiusLabel, 6, 3, 1, 1)
else:
self.vp_missing_label = QtWidgets.QLabel("Vispy package missing or deactivated: \n3D speaker representation disabled.")
self.vpWidget.layout().addWidget(self.vp_missing_label, 1, 1, 1, 3)
self.vpWidget.layout().addWidget(self.azimuthLabel, 2, 1, 1, 1)
self.vpWidget.layout().addWidget(self.elevationLabel, 2, 2, 1, 1)
self.vpWidget.layout().addWidget(self.radiusLabel, 2, 3, 1, 1)
# DEVICE STATUS WIDGET
self.device_status_widget = QtWidgets.QGroupBox("Audio Device Status")
self.device_status_widget.setLayout(QtWidgets.QHBoxLayout())
self.device_status_widget.layout().addWidget(AudioDeviceWidget(self.measurement_ref.measurement))
self.device_status_widget.layout().setSizeConstraint(QtWidgets.QLayout.SetFixedSize)
# TRACKER STATUS WIDGET
self.tracker_status_widget = QtWidgets.QGroupBox("Vive Tracker Status")
tracker_status = self.measurement_ref.tracker.check_tracker_availability()
self.tracker1_status_label = QtWidgets.QLabel(tracker_status["tracker1"])
self.tracker2_status_label = QtWidgets.QLabel(tracker_status["tracker2"])
self.tracker1_label = QtWidgets.QLabel("(Head) Tracker 1:")
self.tracker2_label = QtWidgets.QLabel("Tracker 2:")
self.tracker_status_widget.setLayout(QtWidgets.QFormLayout())
self.tracker_status_widget.layout().addRow(self.tracker1_label, self.tracker1_status_label)
self.tracker_status_widget.layout().addRow(self.tracker2_label, self.tracker2_status_label)
self.tracker_status_widget.setMaximumHeight(100)
# OSC STATUS WIDGET
self.osc_status_box = QtWidgets.QGroupBox("OSC Input Status")
self.osc_status_box.setMaximumHeight(100)
self.osc_status_box.setLayout(QtWidgets.QVBoxLayout())
self.osc_status_indicator = QtWidgets.QCheckBox(" OSC Input")
self.osc_status_indicator.setStyleSheet("QCheckBox::indicator"
"{"
"background-color : lightgrey;"
"}")
self.osc_status_indicator.setCheckable(False)
self.osc_status_box.layout().addWidget(self.osc_status_indicator)
self.osc_status_box.hide()
# MANUAL AZ/EL/R box
self.azimuthBox = QtWidgets.QSpinBox()
self.azimuthBox.setMaximum(359)
self.azimuthBox.valueChanged.connect(self.manual_update_az)
self.elevationBox = QtWidgets.QSpinBox()
self.elevationBox.setMaximum(90)
self.elevationBox.setMinimum(-90)
self.elevationBox.valueChanged.connect(self.manual_update_el)
self.radiusBox = QtWidgets.QSpinBox()
self.radiusBox.setMinimum(20)
self.radiusBox.setMaximum(999)
self.radiusBox.valueChanged.connect(self.manual_update_radius)
self.manualAngleBox = QtWidgets.QGroupBox(
"Set angle manually (Only when VIVE trackers are disconnected)")
layout = QtWidgets.QHBoxLayout()
layout.addWidget(QtWidgets.QLabel("Azimuth °"))
layout.addWidget(self.azimuthBox)
layout.addWidget(QtWidgets.QLabel("Elevation °"))
layout.addWidget(self.elevationBox)
layout.addWidget(QtWidgets.QLabel("Radius cm"))
layout.addWidget(self.radiusBox)
layout.setSizeConstraint(QtWidgets.QLayout.SetFixedSize)
self.manualAngleBox.setLayout(layout)
# TAB WIDGET
self.tabWidget = QtWidgets.QTabWidget(self)
self.tabWidget.setEnabled(True)
self.tabWidget.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)
self.tabWidget.setTabPosition(QtWidgets.QTabWidget.North)
self.tabWidget.setTabShape(QtWidgets.QTabWidget.Rounded)
self.tabWidget.setIconSize(QtCore.QSize(32, 32))
self.tabWidget.setDocumentMode(True)
self.tabWidget.setTabsClosable(False)
self.tabWidget.setMovable(False)
self.tabWidget.setTabBarAutoHide(False)
self.tabWidget.setObjectName("tabWidget")
self.tabWidget.currentChanged.connect(self.tab_changed)
self.tab_config = QtWidgets.QWidget()
self.tab_config.setEnabled(True)
self.tab_config.setObjectName("tab_config")
self.tab_config.setLayout(QtWidgets.QVBoxLayout())
self.tab_config.layout().setAlignment(QtCore.Qt.AlignTop)
self.tabWidget.addTab(self.tab_config, "")
self.tab_measure = QtWidgets.QWidget()
self.tab_measure.setEnabled(True)
self.tab_measure.setObjectName("tab_measure")
self.tab_measure.setLayout(QtWidgets.QVBoxLayout())
self.tab_measure.layout().setAlignment(QtCore.Qt.AlignCenter)
self.tabWidget.addTab(self.tab_measure, "")
self.tab_data = QtWidgets.QWidget()
self.tab_data.setEnabled(True)
self.tab_data.setObjectName("tab_data")
self.tab_data.setLayout(QtWidgets.QGridLayout())
#self.tab_data.layout().setAlignment(QtCore.Qt.AlignCenter)
self.tabWidget.addTab(self.tab_data, "")
self.tab_data_index = self.tabWidget.count()-1
self.tab_hpc = QtWidgets.QWidget()
self.tab_hpc.setEnabled(True)
self.tab_hpc.setLayout(QtWidgets.QVBoxLayout())
self.tab_hpc.layout().setAlignment(QtCore.Qt.AlignCenter)
self.tabWidget.addTab(self.tab_hpc, "")
# Config Tab
#############################
#############################
# Config Tab
# Select Tracking Input
############################
self.tracking_input_box = QtWidgets.QGroupBox("Tracking Input")
self.tracking_input_box.setFixedHeight(70)
self.tracking_input_box.setLayout(QtWidgets.QHBoxLayout())
self.tracking_input_vive = QtWidgets.QRadioButton("Vive Trackers")
self.tracking_input_vive.setChecked(True)
self.tracking_input_vive.sourcename = "Vive"
self.tracking_input_vive.toggled.connect(self.select_tracking_input)
self.tracking_input_box.layout().addWidget(self.tracking_input_vive)
self.tracking_input_OSC_direct = QtWidgets.QRadioButton("External: OSC (Az|El|R)")
self.tracking_input_OSC_direct.sourcename = "OSC_direct"
self.tracking_input_OSC_direct.toggled.connect(self.select_tracking_input)
self.tracking_input_box.layout().addWidget(self.tracking_input_OSC_direct)
self.tab_config.layout().addWidget(self.tracking_input_box)
# Config Tab
# Vive Tracker Box
# Show Instructions Dialog Box:
###########################
self.vivetracker_box = QtWidgets.QGroupBox("Tracker Calibration")
self.vivetracker_box.setLayout(QtWidgets.QVBoxLayout())
self.vivetracker_box.layout().setAlignment(QtCore.Qt.AlignTop)
self.vivetracker_box.setFixedHeight(500)
self.tab_config.layout().addWidget(self.vivetracker_box)
self.dlg = InstructionsDialogBox()
self.show_instructions_button = QtWidgets.QPushButton()
self.show_instructions_button.setText("Show Calibration Instructions")
self.show_instructions_button.clicked.connect(self.dlg.show)
self.show_instructions_button.setMaximumWidth(200)
self.vivetracker_box.layout().addWidget(self.show_instructions_button)
# Config Tab
# Vive Tracker Box
# Switch Trackers Box:
###########################
self.switchTrackersButton = QtWidgets.QPushButton()
self.switchTrackersButton.setText("Switch Tracker Roles")
self.switchTrackersButton.setObjectName("switchTrackersButton")
self.switchTrackersButton.setMaximumWidth(200)
self.switchTrackersButton.clicked.connect(self.switch_trackers)
self.vivetracker_box.layout().addWidget(self.switchTrackersButton)
# Config Tab
# Vive Tracker Box
# Delay trackers textfield:
###########################
self.delay_calibration_layout = QtWidgets.QHBoxLayout()
self.delay_calibration_layout.setAlignment(QtCore.Qt.AlignLeft)
self.vivetracker_box.layout().addLayout(self.delay_calibration_layout)
self.calibration_info_label = QtWidgets.QLabel("Delay calibration triggers (s)")
self.delay_calibration_layout.addWidget(self.calibration_info_label)
self.calibration_wait_time = QtWidgets.QSpinBox()
self.delay_calibration_layout.addWidget(self.calibration_wait_time)
# Config Tab
# Vive Tracker Box
# Head Dimensions Dialog:
###########################
self.head_dimensions_dialog = QtWidgets.QDialog()
self.head_dimensions_dialog.setModal(False)
self.head_dimensions_dialog.setWindowTitle("Measure Head Dimensions")
Btn = QtWidgets.QDialogButtonBox.Close
self.head_dimensions_dialog.buttonBox = QtWidgets.QDialogButtonBox(Btn)
self.head_dimensions_dialog.buttonBox.clicked.connect(self.head_dimensions_dialog.close)
self.head_dimensions_dialog.setLayout(QtWidgets.QVBoxLayout())
self.head_dimensions_dialog.layout().setAlignment(QtCore.Qt.AlignLeft)
self.head_dimensions_info = QtWidgets.QLabel("Measure the width and length of the head by holding the tracker to the left, right, front and back of the head (above the ears). This data is not mandatory for the measurement, but can be used as meta data during post processing. It is stored along with the HRIR data.")
self.head_dimensions_info.setWordWrap(True)
self.head_dimensions_dialog.layout().addWidget(self.head_dimensions_info)
self.head_dimensions_formlayout = QtWidgets.QFormLayout()
self.head_dimensions_dialog.layout().addLayout(self.head_dimensions_formlayout)
calibration_button_width = 180
calibration_button_size = QtCore.QSize(calibration_button_width, 50)
self.calibrate_left_head = QtWidgets.QPushButton(text='Left Side')
self.calibrate_left_head.setAutoDefault(False)
# self.calibrate_ear_left.setFixedSize(calibration_button_size)
self.calibrate_left_head.setFixedWidth(calibration_button_width)
self.calibrate_left_head.clicked.connect(lambda: self.calibrate(self.calibrate_head_left))
self.calibrate_left_head_label = QtWidgets.QLabel(text="Uncalibrated")
self.head_dimensions_formlayout.addRow(self.calibrate_left_head, self.calibrate_left_head_label)
self.calibrate_right_head = QtWidgets.QPushButton(text='Right Side')
self.calibrate_right_head.setAutoDefault(False)
# self.calibrate_ear_right.setFixedSize(calibration_button_size)
self.calibrate_right_head.setFixedWidth(calibration_button_width)
self.calibrate_right_head.clicked.connect(lambda: self.calibrate(self.calibrate_head_right))
self.calibrate_right_head_label = QtWidgets.QLabel(text="Uncalibrated")
self.head_dimensions_formlayout.addRow(self.calibrate_right_head, self.calibrate_right_head_label)
self.head_width_label = QtWidgets.QLabel(text="Head Width: - ")
self.head_dimensions_formlayout.addRow(QtWidgets.QLabel(""), self.head_width_label)
self.calibrate_front_head = QtWidgets.QPushButton(text='Front Of Head')
self.calibrate_front_head.setAutoDefault(False)
# self.calibrate_front_head.setFixedSize(calibration_button_size)
self.calibrate_front_head.setFixedWidth(calibration_button_width)
self.calibrate_front_head.clicked.connect(lambda: self.calibrate(self.calibrate_head_front))
self.calibrate_front_head_label = QtWidgets.QLabel(text="Uncalibrated")
self.head_dimensions_formlayout.addRow(self.calibrate_front_head, self.calibrate_front_head_label)
self.calibrate_back_head = QtWidgets.QPushButton(text='Back Of Head')
self.calibrate_back_head.setAutoDefault(False)
# self.calibrate_back_head.setFixedSize(calibration_button_size)
self.calibrate_back_head.setFixedWidth(calibration_button_width)
self.calibrate_back_head.clicked.connect(lambda: self.calibrate(self.calibrate_head_back))
self.calibrate_back_head_label = QtWidgets.QLabel(text="Uncalibrated")
self.head_dimensions_formlayout.addRow(self.calibrate_back_head, self.calibrate_back_head_label)
self.head_length_label = QtWidgets.QLabel(text="Head Length: - ")
self.head_dimensions_formlayout.addRow(QtWidgets.QLabel(""), self.head_length_label)
self.head_dimensions_dialog.layout().addWidget(self.head_dimensions_dialog.buttonBox)
self.show_head_dimensions = QtWidgets.QPushButton()
self.show_head_dimensions.setText("Optional: Head Dimensions")
self.show_head_dimensions.clicked.connect(self.head_dimensions_dialog.show)
self.show_head_dimensions.setMaximumWidth(200)
self.vivetracker_box.layout().addWidget(self.show_head_dimensions)
# Config Tab
# Vive Tracker Box
# Calibration Box
self.calibration_box = QtWidgets.QGroupBox("Tracker Calibration")
self.calibration_box.setLayout(QtWidgets.QVBoxLayout())
self.calibration_box.layout().setAlignment(QtCore.Qt.AlignLeft)
self.vivetracker_box.layout().addWidget(self.calibration_box)
self.calibrations_formlayout = QtWidgets.QFormLayout()
self.calibration_box.layout().addLayout(self.calibrations_formlayout)
calibration_button_width = 180
calibration_button_size = QtCore.QSize(calibration_button_width, 50)
self.calibrate_ear_left = QtWidgets.QPushButton(text='Calibrate Left Ear')
#self.calibrate_ear_left.setFixedSize(calibration_button_size)
self.calibrate_ear_left.setFixedWidth(calibration_button_width)
self.calibrate_ear_left.clicked.connect(lambda: self.calibrate(self.calibrate_left_ear))
self.calibrate_ear_left_label = QtWidgets.QLabel(text="Uncalibrated")
self.calibrations_formlayout.addRow(self.calibrate_ear_left, self.calibrate_ear_left_label)
self.calibrate_ear_right = QtWidgets.QPushButton(text='Calibrate Right Ear')
#self.calibrate_ear_right.setFixedSize(calibration_button_size)
self.calibrate_ear_right.setFixedWidth(calibration_button_width)
self.calibrate_ear_right.clicked.connect(lambda: self.calibrate(self.calibrate_right_ear))
self.calibrate_ear_right_label = QtWidgets.QLabel(text="Uncalibrated")
self.calibrations_formlayout.addRow(self.calibrate_ear_right, self.calibrate_ear_right_label)
self.calibrate_acoustical_center = QtWidgets.QPushButton(text='Calibrate Speaker')
#self.calibrate_acoustical_center.setFixedSize(calibration_button_size)
self.calibrate_acoustical_center.setFixedWidth(calibration_button_width)
self.calibrate_acoustical_center.clicked.connect(lambda: self.calibrate(self.calibrate_acoustical_centre))
self.calibrate_acoustical_center_label = QtWidgets.QLabel(text="Uncalibrated")
self.calibrations_formlayout.addRow(self.calibrate_acoustical_center, self.calibrate_acoustical_center_label)
self.calibrateButton = QtWidgets.QPushButton(self.tab_measure)
self.calibrateButton.setText("Calibrate Orientation")
self.calibrateButton.setObjectName("calibrateButton")
#self.calibrateButton.setFixedSize(calibration_button_size)
self.calibrateButton.setFixedWidth(calibration_button_width)
self.calibrateButton.clicked.connect(lambda: self.calibrate(self.calibrate_orientation))
self.calibrate_orientation_label = QtWidgets.QLabel("Uncalibrated")
self.calibrations_formlayout.addRow(self.calibrateButton, self.calibrate_orientation_label)
# Config Tab
# OSC Config Box
############################
self.osc_config_box = QtWidgets.QGroupBox("OSC Configuration")
self.osc_config_box.setLayout(QtWidgets.QVBoxLayout())
self.osc_config_box.setFixedHeight(500)
self.osc_config_box.layout().setAlignment(QtCore.Qt.AlignTop)
self.osc_config_box.hide()
self.osc_ip_label = QtWidgets.QLabel("Current Host IP: ")
self.osc_port_label = QtWidgets.QLabel("OSC Server Port: ")
self.osc_address_label = QtWidgets.QLabel("Listening for list of [Az, El, R] on osc-address '/guided_hrtfs/angle'")
self.osc_address_label.setWordWrap(True)
self.osc_config_box.layout().addWidget(self.osc_ip_label)
self.osc_config_box.layout().addWidget(self.osc_port_label)
self.osc_config_box.layout().addWidget(self.osc_address_label)
self.tab_config.layout().addWidget(self.osc_config_box)
# Config Tab
# Measurement Parameters Box:
############################
self.measuremet_paramteres_box = QtWidgets.QGroupBox("Measurement Parameters")
self.measuremet_paramteres_box.setLayout(QtWidgets.QVBoxLayout())
self.sweep_parameters_dialog = QtWidgets.QDialog()
self.sweep_parameters_dialog.setModal(False)
self.sweep_parameters_dialog.setWindowTitle("Sweep Parameters")
Btn_ok = QtWidgets.QDialogButtonBox.Ok
self.sweep_parameters_dialog.buttonBox = QtWidgets.QDialogButtonBox(Btn_ok)
self.sweep_parameters_dialog.buttonBox.clicked.connect(self.update_sweep_parameters)
self.sweep_parameters_dialog.setLayout(QtWidgets.QVBoxLayout())
self.sweep_parameters_dialog.layout().setAlignment(QtCore.Qt.AlignLeft)
self.sweep_parameters_formlayout = QtWidgets.QFormLayout()
self.sweep_parameters_dialog.layout().addLayout(self.sweep_parameters_formlayout)
# get current parameters
sweep_params = self.measurement_ref.measurement.get_sweep_parameters()
# add row entries for each parameter
self.sweeplength_sec = QtWidgets.QLineEdit(str(sweep_params['sweeplength_sec']))
self.sweep_parameters_formlayout.addRow(self.sweeplength_sec, QtWidgets.QLabel(text='Sweep length (sec)'))
self.post_silence_sec = QtWidgets.QLineEdit(str(sweep_params['post_silence_sec']))
self.sweep_parameters_formlayout.addRow(self.post_silence_sec, QtWidgets.QLabel(text='Silence after sweep (sec)'))
self.f_start = QtWidgets.QLineEdit(str(sweep_params['f_start']))
self.sweep_parameters_formlayout.addRow(self.f_start, QtWidgets.QLabel(text='Sweep start frequency (Hz)'))
self.f_end = QtWidgets.QLineEdit(str(sweep_params['f_end']))
self.sweep_parameters_formlayout.addRow(self.f_end, QtWidgets.QLabel(text='Sweep stop frequency (Hz)'))
self.amp_db = QtWidgets.QLineEdit(str(sweep_params['amp_db']))
self.sweep_parameters_formlayout.addRow(self.amp_db, QtWidgets.QLabel(text='Sweep gain (dB)'))
self.fade_out_samples = QtWidgets.QLineEdit(str(sweep_params['fade_out_samples']))
self.sweep_parameters_formlayout.addRow(self.fade_out_samples, QtWidgets.QLabel(text='Fadeout before sweep end (samples)'))
self.sweep_parameters_errormessage = QtWidgets.QLabel("Invalid Sweep Paramters")
self.sweep_parameters_formlayout.addRow(self.sweep_parameters_errormessage)
self.sweep_parameters_errormessage.setVisible(False)
# add bottom button box
self.sweep_parameters_dialog.layout().addWidget(self.sweep_parameters_dialog.buttonBox)
self.show_sweep_parameters = QtWidgets.QPushButton()
self.show_sweep_parameters.setText("Set Sweep Parameters")
self.show_sweep_parameters.clicked.connect(self.sweep_parameters_dialog.show)
self.show_sweep_parameters.setMaximumWidth(200)
self.measuremet_paramteres_box.layout().addWidget(self.show_sweep_parameters)
self.tab_config.layout().addWidget(self.measuremet_paramteres_box)
# Config Tab
# Output Folder Box:
############################
self.output_folder_box = QtWidgets.QGroupBox("Select output folder for measured data")
self.output_folder_box.setFixedHeight(80)
self.output_folder_box.setLayout(QtWidgets.QHBoxLayout())
path = os.getcwd()
path = os.path.join(path, "Measurements")
if not os.path.exists(path):
try:
os.mkdir(path)
except:
path = os.getcwd()
self.measurement_ref.set_output_path(path)
self.output_folder_select = QtWidgets.QLineEdit()
self.output_folder_select.setText(path)
self.output_folder_box.layout().addWidget(self.output_folder_select)
self.select_folder_button = QtWidgets.QPushButton()
self.select_folder_button.setText("...")
self.select_folder_button.clicked.connect(self.select_folder_dialog)
self.output_folder_box.layout().addWidget(self.select_folder_button)
self.tab_config.layout().addWidget(self.output_folder_box)
# Config Tab
# Send OSC Box:
############################
self.send_osc_box = QtWidgets.QGroupBox("Send OSC data to external application")
self.send_osc_box.setFixedHeight(200)
self.send_osc_box.setLayout(QtWidgets.QFormLayout())
self.send_osc_box.layout().setLabelAlignment(QtCore.Qt.AlignLeft)
ip, port, address = self.measurement_ref.get_osc_parameters()
self.send_osc_ip_select = QtWidgets.QLineEdit()
self.send_osc_ip_select.setText(ip)
self.send_osc_box.layout().addRow("OSC IP Address: ", self.send_osc_ip_select)
self.send_osc_port_select = QtWidgets.QLineEdit()
self.send_osc_port_select.setText(f'{port}')
self.send_osc_box.layout().addRow("OSC Port: ", self.send_osc_port_select)
self.send_osc_address_select = QtWidgets.QLineEdit()
self.send_osc_address_select.setText(address)
self.send_osc_box.layout().addRow("OSC Address: ", self.send_osc_address_select)
self.send_osc_button = QtWidgets.QPushButton()
self.send_osc_button.setText("Send OSC")
self.send_osc_button.clicked.connect(self.activate_osc_send)
self.send_osc_button.setFixedSize(100, 50)
self.send_osc_button.setCheckable(True)
#self.send_osc_button.setStyleSheet("background-color : lightgrey")
self.send_osc_box.layout().addRow(self.send_osc_button)
self.tab_config.layout().addWidget(self.send_osc_box)
## MEASURE TAB
#############################
#############################
self.measurements_main_group = QtWidgets.QGroupBox()
self.measurements_main_group.setLayout(QtWidgets.QHBoxLayout())
self.measurements_main_group.layout().addWidget(QtWidgets.QLabel("Session Name:"))
self.session_name = QtWidgets.QLineEdit()
self.measurements_main_group.layout().addWidget(self.session_name)
self.measurements_main_group.layout().addStretch()
self.clear_measurements_button = QtWidgets.QPushButton("Clear / Start New")
self.clear_measurements_button.clicked.connect(self.clear_measurements)
self.measurements_main_group.layout().addWidget(self.clear_measurements_button)
self.tab_measure.layout().addWidget(self.measurements_main_group)
self.startMeasurementGroupBox = QtWidgets.QGroupBox('Start Measurement')
self.startMeasurementGroupBox.setLayout(QtWidgets.QGridLayout())
self.centerTriggerButton = QtWidgets.QPushButton('Center Measurement')
self.centerTriggerButton.setObjectName("Center Measurement")
self.centerTriggerButton.clicked.connect(self.trigger_center_measurement)
self.measurementTriggerButton = QtWidgets.QPushButton('Single Measurement')
self.measurementTriggerButton.setObjectName("Single Measurement")
self.measurementTriggerButton.setFixedSize(QtCore.QSize(200, 100))
self.measurementTriggerButton.clicked.connect(self.measurement_ref.trigger_measurement)
self.autoTriggerButton = QtWidgets.QPushButton('Auto Measurement')
self.autoTriggerButton.clicked.connect(self.measurement_ref.trigger_auto_measurement)
self.autoMeasurementTriggerProgress = QtWidgets.QProgressBar()
self.autoMeasurementTriggerProgress.setVisible(False)
self.autoTriggerStopButton = QtWidgets.QPushButton('Stop Auto Measurement')
self.autoTriggerStopButton.clicked.connect(self.measurement_ref.stop_auto_measurement)
#self.startMeasurementGroupBox.layout().addStretch()
self.startMeasurementGroupBox.layout().addWidget(self.centerTriggerButton, 1, 0, 1, 1)
self.startMeasurementGroupBox.layout().addWidget(self.measurementTriggerButton, 0, 1, 3, 1)
self.startMeasurementGroupBox.layout().addWidget(self.autoTriggerButton, 1, 2, 1, 1)
self.startMeasurementGroupBox.layout().addWidget(self.autoMeasurementTriggerProgress, 2, 2, 1, 1)
self.startMeasurementGroupBox.layout().addWidget(self.autoTriggerStopButton, 1, 3, 1, 1)
#self.startMeasurementGroupBox.layout().addStretch()
self.tab_measure.layout().addWidget(self.startMeasurementGroupBox)
self.point_recommender_groupbox = QtWidgets.QGroupBox('Point Recommender')
self.point_recommender_groupbox.setLayout(QtWidgets.QHBoxLayout())
self.point_recommender_groupbox.setEnabled(False)
self.recommend_point_button = QtWidgets.QPushButton('Recommend Point')
self.recommend_point_button.clicked.connect(self.trigger_point_recommendation)
self.start_guiding_button = QtWidgets.QPushButton('Start Guidance')
self.start_guiding_button.clicked.connect(self.trigger_guided_measurement)
self.clear_recommended_points_button = QtWidgets.QPushButton('Clear Recommendations')
self.clear_recommended_points_button.clicked.connect(self.clear_recommended_points)
self.point_recommender_groupbox.layout().addStretch()
self.point_recommender_groupbox.layout().addWidget(self.recommend_point_button)
self.point_recommender_groupbox.layout().addWidget(self.start_guiding_button)
self.point_recommender_groupbox.layout().addWidget(self.clear_recommended_points_button)
self.tab_measure.layout().addWidget(self.point_recommender_groupbox)
self.plotgroupbox = QtWidgets.QGroupBox('Measurement Plots')
self.plotgroupbox.setLayout(QtWidgets.QVBoxLayout())
self.plot_widget = PlotWidget()
self.plotgroupbox.layout().addWidget(self.plot_widget)
self.tab_measure.layout().addWidget(self.plotgroupbox)
## DATA LIST TAB
#############################
self.positions_table = QtWidgets.QTableView()
self.positions_table.setModel(self.measurement_ref.positions_list)
self.positions_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
self.positions_table.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
self.positions_table.verticalHeader().show()
self.positions_table.horizontalHeader().setSectionResizeMode(1)
self.positions_table.verticalHeader().setSectionResizeMode(3)
self.positions_table.setFont(QtGui.QFont('Helvetica', 13))
self.positions_table.setShowGrid(False)
#self.positions_table.setMaximumWidth(300)
self.positions_table_selection = self.positions_table.selectionModel()
self.positions_table_selection.currentRowChanged.connect(self.data_table_selection)
self.tab_data.layout().addWidget(self.positions_table, 0, 0, 1, 1)
self.remove_measurement_button = QtWidgets.QPushButton("Delete Selected")
self.remove_measurement_button.clicked.connect(self.remove_measurement)
self.tab_data.layout().addWidget(self.remove_measurement_button, 1, 0, 1, 1)
self.plot_widget2 = PlotWidget()
#self.plot_widget2.setMaximumWidth(200)
self.tab_data.layout().addWidget(self.plot_widget2, 0, 1, 1, 1)
## HEADPHONE COMPENSATION TAB
#############################
self.hp_main_group = QtWidgets.QGroupBox()
self.hp_main_group.setLayout(QtWidgets.QHBoxLayout())
self.hp_main_group.layout().addWidget(QtWidgets.QLabel("Headphone Name:"))
self.headphone_name = QtWidgets.QLineEdit()
self.hp_main_group.layout().addWidget(self.headphone_name)
self.hp_main_group.layout().addStretch()
self.clear_hp_measurements_button = QtWidgets.QPushButton("Clear / Start New")
self.clear_hp_measurements_button.clicked.connect(self.clear_hp_measurements)
self.hp_main_group.layout().addWidget(self.clear_hp_measurements_button)
self.tab_hpc.layout().addWidget(self.hp_main_group)
self.hp_controls_group = QtWidgets.QGroupBox()
self.hp_controls_group.setLayout(QtWidgets.QHBoxLayout())
self.hp_controls_group.setAlignment(QtCore.Qt.AlignLeft)
self.trigger_hp_measurement_button = QtWidgets.QPushButton("Trigger Headphone \n Measurement")
self.trigger_hp_measurement_button.clicked.connect(self.trigger_hp_measurement)
self.trigger_hp_measurement_button.setFixedSize(QtCore.QSize(200, 100))
self.hp_controls_group.layout().addWidget(self.trigger_hp_measurement_button)
self.remove_hp_measurement_button = QtWidgets.QPushButton("Remove Last \n HP Measurement")
self.remove_hp_measurement_button.clicked.connect(self.remove_hp_measurement)
self.remove_measurement_button.setFixedSize(QtCore.QSize(200, 50))
self.hp_controls_group.layout().addWidget(self.remove_hp_measurement_button)
self.hp_controls_group.layout().addStretch()
self.hp_measurement_count = QtWidgets.QLabel("")
# self.hp_measurement_count.setFixedWidth(16)
self.hp_controls_group.layout().addWidget(self.hp_measurement_count)
self.tab_hpc.layout().addWidget(self.hp_controls_group)
#self.plot_hpc_widget = PlotWidget()
#self.tab_hpc.layout().addWidget(self.plot_hpc_widget)
self.plot_hpirs_widget = PlotWidget_HPIRs()
self.tab_hpc.layout().addWidget(self.plot_hpirs_widget)
self.reg_beta_layout = QtWidgets.QHBoxLayout()
self.reg_beta_layout.setAlignment(QtCore.Qt.AlignCenter)
self.reg_beta_layout.addWidget(QtWidgets.QLabel("Reg Beta:"))
self.regularization_beta_box = QtWidgets.QDoubleSpinBox()
self.regularization_beta_box.setMaximum(1.0)
self.regularization_beta_box.setSingleStep(0.05)
self.regularization_beta_box.setValue(0.4)
self.regularization_beta_box.setFixedWidth(100)
self.regularization_beta_box.valueChanged.connect(self.set_regularization_beta)
self.reg_beta_layout.addWidget(self.regularization_beta_box)
self.tab_hpc.layout().addLayout(self.reg_beta_layout)
self.plot_hpcf_widget = PlotWidget_HPCF()
self.tab_hpc.layout().addWidget(self.plot_hpcf_widget)
self.plot_hptf(np.array([]))
self.plot_hpc_estimate(np.array([]), np.array([]))
## Layout finalilzation
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.addWidget(self.tabWidget, 0, 1, 4, 1)
self.gridLayout.addWidget(self.vpWidget, 0, 0, 1, 1)
self.gridLayout.addWidget(self.device_status_widget, 1, 0, 1, 1)
self.gridLayout.addWidget(self.tracker_status_widget, 2, 0, 1, 1)
self.gridLayout.addWidget(self.osc_status_box, 2, 0, 1, 1)
self.gridLayout.addWidget(self.manualAngleBox, 3, 0, 1, 1)
self.gridLayout.setColumnStretch(0, 10)
self.gridLayout.setColumnStretch(1, 10)
self.cwidget.setLayout(self.gridLayout)
#self.gridLayout.setSizeConstraint(QtWidgets.QLayout.SetFixedSize)
self.resize(1100, 600)
# self.menubar = QtWidgets.QMenuBar(MainWindow)
# self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
# self.menubar.setObjectName("menubar")
# MainWindow.setMenuBar(self.menubar)
# self.statusbar = QtWidgets.QStatusBar(MainWindow)
# self.statusbar.setObjectName("statusbar")
# MainWindow.setStatusBar(self.statusbar)
self.tabWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(self)
self.measurement_ref.register_gui_handler(self)
def closeEvent(self, *args, **kwargs):
super(QtWidgets.QMainWindow, self).closeEvent(*args, **kwargs)
def resizeEvent(self, event):
_translate = QtCore.QCoreApplication.translate
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_config), _translate("MainWindow", "Configure"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_measure), _translate("MainWindow", "Measure"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_data), _translate("MainWindow", "Data List"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_hpc), _translate("MainWindow", "Headphone Compensation"))
self.positions_table.setColumnWidth(0, self.positions_table.width() / 3)
self.positions_table.setColumnWidth(1, self.positions_table.width() / 3)
self.positions_table.setColumnWidth(2, self.positions_table.width() / 3)
def manual_update_az(self):
self.measurement_ref.tracker.fallback_angle[0] = self.azimuthBox.value()
def manual_update_el(self):
self.measurement_ref.tracker.fallback_angle[1] = self.elevationBox.value()
def manual_update_radius(self):
self.measurement_ref.tracker.fallback_angle[2] = self.radiusBox.value() / 100
def add_measurement_point(self, az, el):
if use_vispy:
self.vispy_canvas.meas_points.add_point(az, el)
def add_center_point(self):
if use_vispy:
self.vispy_canvas.center_points.add_point(0, 0)
#def remove_measurement_point(self, az, el):
def plot_recordings(self, rec_l, rec_r, fb_loop, fs, fb_loop_used=False):
self.plot_widget.plot_recordings(rec_l, rec_r, fb_loop, fs=fs, fb_loop_used=fb_loop_used)
def plot_IRs(self, ir_l, ir_r, fs):
self.plot_widget.plot_IRs(ir_l, ir_r, fs=fs)
def updateMeasurementList(self, measurement_data):
pass
def switch_trackers(self):
self.measurement_ref.tracker.switch_trackers()
if self.measurement_ref.tracker.trackers_switched:
self.tracker1_label = QtWidgets.QLabel("Tracker 1:")
self.tracker2_label = QtWidgets.QLabel("(Head) Tracker 2:")
else:
self.tracker1_label = QtWidgets.QLabel("(Head) Tracker 1:")
self.tracker2_label = QtWidgets.QLabel("Tracker 2:")
def update_tracker_status(self, status):
self.tracker1_status_label.setText(status["tracker1"])
self.tracker2_status_label.setText(status["tracker2"])
if status["tracker1"] == "Tracking" and status["tracker2"] == "Tracking" \
or self.measurement_ref.tracker.tracking_mode == "OSC_direct":
self.show_manual_angle_box(False)
else:
self.show_manual_angle_box(True)
def show_manual_angle_box(self, show):
if show:
if self.gridLayout.indexOf(self.manualAngleBox) == -1:
self.gridLayout.removeWidget(self.tabWidget)
self.gridLayout.addWidget(self.tabWidget, 0, 1, 4, 1)
self.gridLayout.addWidget(self.manualAngleBox, 3, 0, 1, 1)
self.manualAngleBox.setVisible(True)
else:
if self.gridLayout.indexOf(self.manualAngleBox) != -1:
self.gridLayout.removeWidget(self.tabWidget)
self.gridLayout.removeWidget(self.manualAngleBox)
self.manualAngleBox.setVisible(False)
self.gridLayout.addWidget(self.tabWidget, 0, 1, 3, 1)
def updateCurrentAngle(self, az, el, r):
r = r*100
self.azimuthLabel.setText("Az: %.0f°" % az)
self.elevationLabel.setText("El: %.0f°" % el)
self.radiusLabel.setText("Radius: %.0fcm" % r)
def set_offset_speaker_z(self):
self.measurement_ref.tracker.offset_cm['speaker_z'] = self.offset_speaker_z.value()
def set_offset_speaker_y(self):
self.measurement_ref.tracker.offset_cm['speaker_y'] = self.offset_speaker_y.value()
def set_offset_head_y(self):
self.measurement_ref.tracker.offset_cm['head_y'] = self.offset_head_y.value()
def select_folder_dialog(self):
path = QtWidgets.QFileDialog.getExistingDirectory(self.cwidget,
'Open Directory',
self.output_folder_select.text(),
QtWidgets.QFileDialog.ShowDirsOnly | QtWidgets.QFileDialog.DontResolveSymlinks)
if path:
self.output_folder_select.setText(path)
self.measurement_ref.set_output_path(path)
# helper function to give all calibration functions the time delay
def calibrate(self, calibration_function):
interval = self.calibration_wait_time.value() * 1000
QtCore.QTimer.singleShot(interval, calibration_function)
def calibrate_orientation(self):
if self.measurement_ref.tracker.calibrate_orientation():
self.measurement_ref.measurement.play_sound(True)
self.calibrate_orientation_label.setText("Calibrated")
else:
self.measurement_ref.measurement.play_sound(False)
# NOTES on the calibrating of head dimensions:
# left_ear and right_ear are for yielding the correct head center.
# head_left and head_right are for yielding the correct anthropometric head width
# head_front and head_right are for yielding the correct anthropometric head length
def calibrate_left_ear(self):
if self.measurement_ref.tracker.calibrate_headdimensions('left_ear', multiple_calls=False):
self.calibrate_ear_left_label.setText(f"Calibrated")#, {self.measurement_ref.tracker.head_dimensions['ear_pos_l']}")
self.measurement_ref.measurement.play_sound(True)
else:
self.measurement_ref.measurement.play_sound(False)
if self.measurement_ref.tracker.head_dimensions['ear_pos_l'] is not None:
self.calibrate_ear_left_label.setText(f"Recalibration failed")#, {self.measurement_ref.tracker.head_dimensions['ear_pos_l']}")
def calibrate_right_ear(self):
if self.measurement_ref.tracker.calibrate_headdimensions('right_ear', multiple_calls=False):
self.calibrate_ear_right_label.setText(f"Calibrated")#, {self.measurement_ref.tracker.head_dimensions['ear_pos_r']}")
self.measurement_ref.measurement.play_sound(True)
else:
self.measurement_ref.measurement.play_sound(False)
if self.measurement_ref.tracker.head_dimensions['ear_pos_r'] is not None:
self.calibrate_ear_right_label.setText(f"Recalibration failed")#, {self.measurement_ref.tracker.head_dimensions['ear_pos_r']}")
def calibrate_head_left(self):
if self.measurement_ref.tracker.calibrate_headdimensions('left'):
self.measurement_ref.measurement.play_sound(True)
self.calibrate_left_head_label.setText("Calibrated")
if self.measurement_ref.tracker.head_dimensions['head_width'] is not None:
self.head_width_label.setText(f"Head Width: {self.measurement_ref.tracker.head_dimensions['head_width']:.3f}")
else:
self.calibrate_left_head_label.setText("Calibration Failed")
self.measurement_ref.measurement.play_sound(False)
def calibrate_head_right(self):
if self.measurement_ref.tracker.calibrate_headdimensions('right'):
self.measurement_ref.measurement.play_sound(True)
self.calibrate_right_head_label.setText("Calibrated")
if self.measurement_ref.tracker.head_dimensions['head_width'] is not None:
self.head_width_label.setText(f"Head Width: {self.measurement_ref.tracker.head_dimensions['head_width']:.3f}")
else:
self.calibrate_right_head_label.setText("Calibration Failed")
self.measurement_ref.measurement.play_sound(False)
def calibrate_head_front(self):
if self.measurement_ref.tracker.calibrate_headdimensions('front'):
self.measurement_ref.measurement.play_sound(True)
self.calibrate_front_head_label.setText("Calibrated")
if self.measurement_ref.tracker.head_dimensions['head_length'] is not None:
self.head_length_label.setText(f"Head Length: {self.measurement_ref.tracker.head_dimensions['head_length']:.3f}")
else:
self.calibrate_front_head_label.setText("Calibration Failed")
self.measurement_ref.measurement.play_sound(False)
def calibrate_head_back(self):
if self.measurement_ref.tracker.calibrate_headdimensions('back'):
self.measurement_ref.measurement.play_sound(True)
self.calibrate_back_head_label.setText("Calibrated")
if self.measurement_ref.tracker.head_dimensions['head_length'] is not None:
self.head_length_label.setText(f"Head Length: {self.measurement_ref.tracker.head_dimensions['head_length']:.3f}")
else:
self.calibrate_back_head_label.setText("Calibration Failed")
def calibrate_acoustical_centre(self):
if self.measurement_ref.tracker.calibrate_acoustical_center():
self.measurement_ref.measurement.play_sound(True)
self.calibrate_acoustical_center_label.setText(f'Calibrated')#, {self.measurement_ref.tracker.acoustical_center_pos}')
else:
self.measurement_ref.measurement.play_sound(False)
def trigger_center_measurement(self):
interval = 0.5 * 1000
QtCore.QTimer.singleShot(interval, self.measurement_ref.trigger_center_measurement)
def trigger_point_recommendation(self):
az, el = self.measurement_ref.recommend_points(1)
def trigger_guided_measurement(self):
self.measurement_ref.start_guided_measurement()
def clear_recommended_points(self):
self.measurement_ref.clear_recommended_points()
def enable_point_recommendation(self):
self.point_recommender_groupbox.setEnabled(True)
def data_table_selection(self, selected, deselected):
if use_vispy:
self.vispy_canvas.meas_points.deselect_points(deselected.row())
self.vispy_canvas.meas_points.select_point(selected.row())
#print("Data Table Selection: " + str(selected.row()))
idx = selected.row()
try:
ir_l = self.measurement_ref.measurements[idx, 0, :]
ir_r = self.measurement_ref.measurements[idx, 1, :]
raw_l = self.measurement_ref.raw_signals[idx, 0, :]
raw_r = self.measurement_ref.raw_signals[idx, 1, :]
fb = self.measurement_ref.raw_feedbackloop[idx, 0, :]
self.plot_widget2.plot_IRs(ir_l, ir_r, plot='spectrogram')
self.plot_widget2.plot_recordings(raw_l, raw_r, fb, fs=self.measurement_ref.measurement.get_samplerate(), plot='spectrogram', fb_loop_used=self.measurement_ref.measurement.feedback_loop_used)
except IndexError:
print("Could not plot data: Invalid id")
def tab_changed(self, index):
try:
if index is not self.tab_data_index:
if use_vispy:
self.vispy_canvas.meas_points.deselect_points()
else:
numRows = self.positions_table.model().rowCount(QtCore.QModelIndex())
self.positions_table.selectRow(numRows-1)
except AttributeError:
pass
def clear_measurements(self):
self.measurement_ref.delete_all_measurements()
self.session_name.clear()
def remove_measurement(self):
indexes = self.positions_table_selection.selectedRows()
for index in indexes:
id = index.row()
dialog = QtWidgets.QMessageBox
ret = dialog.question(self,'', "Are you sure you want to delete this measurement?", dialog.Yes | dialog.No)
if ret == dialog.Yes:
#print("Deleting Measurement " + str(id))
self.measurement_ref.delete_measurement(id)
def update_dev_status(self):
devs = self.measurement_ref.devices
self.label_out_exc.setText(devs['out_excitation'])
self.label_out_exc_2.setText(devs['out_excitation_2'])
self.label_out_fb.setText(devs['out_feedback'])
self.label_in_left.setText(devs['in_left'])
self.label_in_right.setText(devs['in_right'])
self.label_in_fb.setText(devs['in_feedback'])
def trigger_hp_measurement(self):
self.measurement_ref.hp_measurement()
def remove_hp_measurement(self):
self.measurement_ref.remove_hp_measurement()
# def plot_hpc_recordings(self, rec_l, rec_r, fb_loop):
# self.plot_hpc_widget.plot_recordings(rec_l, rec_r, fb_loop)
def plot_hptf(self, hpc_irs, hpc_average=None, fs=48000):
self.plot_hpirs_widget.plot_hptf(hpc_irs, hpc_average=hpc_average, fs=fs)
def plot_hpc_estimate(self, H_l, H_r, fs=48000):
self.plot_hpcf_widget.plot_hpcf(H_l, H_r, fs=fs)
def set_regularization_beta(self):
self.measurement_ref.estimate_hpcf(self.regularization_beta_box.value())
def clear_hp_measurements(self):
self.measurement_ref.remove_all_hp_measurements()
self.headphone_name.clear()
def warning_invalid_tracking(self, warning=True):
palette = self.tracker_status_widget.palette()
if warning:
palette.setColor(QtGui.QPalette.Window, QtGui.QColor('red'))
else:
palette.setColor(QtGui.QPalette.Window, QtGui.QColor('grey'))
self.tracker_status_widget.setPalette(palette)
self.tracker_status_widget.setAutoFillBackground(True)
self.tracker_status_widget.repaint()
def select_tracking_input(self):
radioButton = self.tracking_input_box.sender()
if radioButton.isChecked():
if radioButton.sourcename == "Vive":
self.vivetracker_box.show()
self.osc_config_box.hide()
self.osc_status_box.hide()
self.tracker_status_widget.show()
self.measurement_ref.tracker.set_tracking_mode(radioButton.sourcename)
self.send_osc_box.setEnabled(True)
if radioButton.sourcename == "OSC_direct":
self.vivetracker_box.hide()
self.osc_config_box.show()
self.tracker_status_widget.hide()
self.osc_status_box.show()
self.measurement_ref.tracker.set_tracking_mode(radioButton.sourcename)
ip, port = self.measurement_ref.tracker.osc_input_server.get_current_ip_and_port()
self.osc_ip_label.setText(f"Current Host IP: {ip}")
self.osc_port_label.setText(f"OSC Server Port: {port}")
self.send_osc_box.setEnabled(False)
self.show_manual_angle_box(False)
def set_osc_status(self, osc_status):
if osc_status:
#self.osc_status_indicator.setStyleSheet("color: green")
self.osc_status_indicator.setStyleSheet("QCheckBox::indicator"
"{"
"background-color : lightgreen;"
"}")
else:
#self.osc_status_indicator.setStyleSheet("color: white")
self.osc_status_indicator.setStyleSheet("QCheckBox::indicator"
"{"
"background-color : white;"
"}")
def activate_osc_send(self):
checked = self.send_osc_button.isChecked()
if self.send_osc_button.isChecked():
if self.measurement_ref.start_osc_send(self.send_osc_ip_select.text(), self.send_osc_port_select.text(), self.send_osc_address_select.text()):
self.send_osc_ip_select.setEnabled(False)
self.send_osc_port_select.setEnabled(False)
self.send_osc_address_select.setEnabled(False)
self.tracking_input_OSC_direct.setEnabled(False)
else:
self.send_osc_button.setChecked(False)
else:
self.measurement_ref.stop_osc_send()
self.send_osc_ip_select.setEnabled(True)
self.send_osc_port_select.setEnabled(True)
self.send_osc_address_select.setEnabled(True)
self.tracking_input_OSC_direct.setEnabled(True)
def update_sweep_parameters(self):
try:
self.measurement_ref.measurement.set_sweep_parameters(d_sweep_sec=float(self.sweeplength_sec.text()),
d_post_silence_sec=float(self.post_silence_sec.text()),
f_start=int(self.f_start.text()),
f_end = int(self.f_end.text()),
amp_db=float(self.amp_db.text()),
fade_out_samples=int(self.fade_out_samples.text()))
except ValueError:
self.sweep_parameters_errormessage.setVisible(True)
return
self.sweep_parameters_errormessage.setVisible(False)
self.sweep_parameters_dialog.close()
return
def deactivate_vispy(self):
use_vispy = False
self.vpWidget.layout().removeWidget(self.vispy_canvas.native)
self.vpWidget.layout().removeWidget(self.sliderTheta)
self.vpWidget.layout().removeWidget(self.sliderPhi)
self.vispy_canvas.native.hide()
self.sliderTheta.hide()
self.sliderPhi.hide()
#del self.vispy_canvas
#del self.sliderPhi
#del self.sliderTheta
self.vp_missing_label = QtWidgets.QLabel(
"Vispy package missing or deactivated: \n3D speaker representation disabled.")
self.vpWidget.layout().addWidget(self.vp_missing_label, 1, 1, 1, 3)
class InstructionsDialogBox(QtWidgets.QDialog):
def __init__(self, *args, **kwargs):
instruction_text = \
"1. Mount tracker T1 on listener head. The orientation and exact position are not important, as long as it stays fixed. \n\n" \
"2. Check if tracker roles are correct by rotating tracker T2. The angles shouldn't change since only the position of tracker T2 is used. Switch tracker roles if necessary\n\n" \
"3. Hold tracker T2 to both ears (bottom center on ear canal) and calibrate each ear. Tracker T2 orientation does not matter here, but from now on tracker T1 (on the listeners head) has to stay fixed & stable on the head.\n\n" \
"4. Hold tracker T2 to acoustical center of speaker and calibrate it. Tracker orientation does not matter here\n\n" \
"5. Put tracker T2 on a planar surface (eg. on top of speaker, floor) pointing towards the same direction as frontal view of listener. Translation does not matter here\n\n" \
"NOTE: If acoustical center is calibrated, this calibrated position stays fixed. If the speaker is moved the calibration has to be repeated."
super(InstructionsDialogBox, self).__init__(*args, **kwargs)
self.setModal(False)
self.setWindowTitle("Calibration Instructions")
self.instructionsbox = QtWidgets.QLabel()
self.instructionsbox.setText(instruction_text)
self.instructionsbox.setWordWrap(True)
Btn = QtWidgets.QDialogButtonBox.Close
self.buttonBox = QtWidgets.QDialogButtonBox(Btn)
self.buttonBox.clicked.connect(self.close)
self.layout = QtWidgets.QVBoxLayout()
self.layout.addWidget(self.instructionsbox)
self.layout.addWidget(self.buttonBox)
self.setLayout(self.layout)
|
#!/usr/bin/env python3
import logging
import re
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import (CallbackQueryHandler, CommandHandler,
ConversationHandler, Filters, MessageHandler,
Updater)
from commons import checkId, authentication, format_bytes, format_long_list_message
import logger
import radarr as radarr
import sonarr as sonarr
from config import config
from translations import i18n
__version__ = "0.3"
# Set up logging
logLevel = logging.DEBUG if config.get("debugLogging", False) else logging.INFO
logger = logger.getLogger("addarr", logLevel, config.get("logToConsole", False))
logger.debug(f"Addarr v{__version__} starting up...")
SERIE_MOVIE_AUTHENTICATED, READ_CHOICE, GIVE_OPTION, GIVE_PATHS, TSL_NORMAL = range(5)
updater = Updater(config["telegram"]["token"], use_context=True)
dispatcher = updater.dispatcher
def main():
auth_handler_command = CommandHandler(config["entrypointAuth"], authentication)
auth_handler_text = MessageHandler(
Filters.regex(
re.compile(r"^" + config["entrypointAuth"] + "$", re.IGNORECASE)
),
authentication,
)
allSeries_handler_command = CommandHandler(config["entrypointAllSeries"], allSeries)
allSeries_handler_text = MessageHandler(
Filters.regex(
re.compile(r"^" + config["entrypointAllSeries"] + "$", re.IGNORECASE)
),
allSeries,
)
allMovies_handler_command = CommandHandler(config["entrypointAllMovies"], allMovies)
allMovies_handler_text = MessageHandler(
Filters.regex(
re.compile(r"^" + config["entrypointAllMovies"] + "$", re.IGNORECASE)
),
allMovies,
)
addMovieserie_handler = ConversationHandler(
entry_points=[
CommandHandler(config["entrypointAdd"], startSerieMovie),
CommandHandler(i18n.t("addarr.Movie"), startSerieMovie),
CommandHandler(i18n.t("addarr.Serie"), startSerieMovie),
MessageHandler(
Filters.regex(
re.compile(r'^' + config["entrypointAdd"] + '$', re.IGNORECASE)
),
startSerieMovie,
),
],
states={
SERIE_MOVIE_AUTHENTICATED: [MessageHandler(Filters.text, choiceSerieMovie)],
READ_CHOICE: [
MessageHandler(
Filters.regex(f'^({i18n.t('addarr.Movie')}|{i18n.t('addarr.Serie')})$'),
searchSerieMovie,
),
CallbackQueryHandler(searchSerieMovie, pattern=f'^({i18n.t('addarr.Movie')}|{i18n.t('addarr.Serie')})$')
],
GIVE_OPTION: [
CallbackQueryHandler(pathSerieMovie, pattern=f'({i18n.t('addarr.Add')})'),
MessageHandler(
Filters.regex(f'^({i18n.t('addarr.Add')})$'),
pathSerieMovie
),
CallbackQueryHandler(nextOption, pattern=f'({i18n.t('addarr.Next result')})'),
MessageHandler(
Filters.regex(f'^({i18n.t('addarr.Next result')})$'),
nextOption
),
MessageHandler(
Filters.regex(f'^({i18n.t('addarr.New')})$'),
startSerieMovie
),
CallbackQueryHandler(startSerieMovie, pattern=f'({i18n.t('addarr.New')})'),
],
GIVE_PATHS: [
CallbackQueryHandler(addSerieMovie, pattern="^(Path: )(.*)$"),
],
},
fallbacks=[
CommandHandler("stop", stop),
MessageHandler(Filters.regex("^(?i)Stop$"), stop),
CallbackQueryHandler(stop, pattern=f"^(?i)Stop$"),
],
)
if config["transmission"]["enable"]:
import transmission as transmission
changeTransmissionSpeed_handler = ConversationHandler(
entry_points=[
CommandHandler(config["entrypointTransmission"], transmission.transmission),
MessageHandler(
Filters.regex(
re.compile(
r"" + config["entrypointTransmission"] + "", re.IGNORECASE
)
),
transmission.transmission,
),
],
states={
transmission.TSL_NORMAL: [
CallbackQueryHandler(transmission.changeSpeedTransmission),
]
},
fallbacks=[
CommandHandler("stop", stop),
MessageHandler(Filters.regex("^(Stop|stop)$"), stop),
],
)
dispatcher.add_handler(changeTransmissionSpeed_handler)
if config["sabnzbd"]["enable"]:
import sabnzbd as sabnzbd
changeSabznbdSpeed_handler = ConversationHandler(
entry_points=[
CommandHandler(config["entrypointSabnzbd"], sabnzbd.sabnzbd),
MessageHandler(
Filters.regex(
re.compile(
r"" + config["entrypointSabnzbd"] + "", re.IGNORECASE
)
),
sabnzbd.sabnzbd,
),
],
states={
sabnzbd.SABNZBD_SPEED_LIMIT_100: [
CallbackQueryHandler(sabnzbd.changeSpeedSabnzbd),
]
},
fallbacks=[
CommandHandler("stop", stop),
MessageHandler(Filters.regex("^(Stop|stop)$"), stop),
],
)
dispatcher.add_handler(changeSabznbdSpeed_handler)
dispatcher.add_handler(auth_handler_command)
dispatcher.add_handler(auth_handler_text)
dispatcher.add_handler(allSeries_handler_command)
dispatcher.add_handler(allSeries_handler_text)
dispatcher.add_handler(allMovies_handler_command)
dispatcher.add_handler(allMovies_handler_text)
dispatcher.add_handler(addMovieserie_handler)
help_handler_command = CommandHandler(config["entrypointHelp"], help)
dispatcher.add_handler(help_handler_command)
logger.info(i18n.t("addarr.Start chatting"))
updater.start_polling()
updater.idle()
def stop(update, context):
clearUserData(context)
context.bot.send_message(
chat_id=update.effective_message.chat_id, text=i18n.t("addarr.End")
)
return ConversationHandler.END
def startSerieMovie(update : Update, context):
if not checkId(update):
context.bot.send_message(
chat_id=update.effective_message.chat_id, text=i18n.t("addarr.Authorize")
)
return SERIE_MOVIE_AUTHENTICATED
if update.message is not None:
reply = update.message.text.lower()
elif update.callback_query is not None:
reply = update.callback_query.data.lower()
else:
return SERIE_MOVIE_AUTHENTICATED
if reply[1:] in [
i18n.t("addarr.Serie").lower(),
i18n.t("addarr.Movie").lower(),
]:
logger.debug(
f"User issued {reply} command, so setting user_data[choice] accordingly"
)
context.user_data.update(
{
"choice": i18n.t("addarr.Serie")
if reply[1:] == i18n.t("addarr.Serie").lower()
else i18n.t("addarr.Movie")
}
)
elif reply == i18n.t("addarr.New").lower():
logger.debug("User issued New command, so clearing user_data")
clearUserData(context)
context.bot.send_message(
chat_id=update.effective_message.chat_id, text='\U0001F3F7 '+i18n.t("addarr.Title")
)
return SERIE_MOVIE_AUTHENTICATED
def choiceSerieMovie(update, context):
if not checkId(update):
if (
authentication(update, context) == "added"
): # To also stop the beginning command
return ConversationHandler.END
elif update.message.text.lower() == "/stop".lower() or update.message.text.lower() == "stop".lower():
return stop(update, context)
else:
if update.message is not None:
reply = update.message.text
elif update.callback_query is not None:
reply = update.callback_query.data
else:
return SERIE_MOVIE_AUTHENTICATED
if reply.lower() not in [
i18n.t("addarr.Serie").lower(),
i18n.t("addarr.Movie").lower(),
]:
logger.debug(
f"User entered a title {reply}"
)
context.user_data["title"] = reply
if context.user_data.get("choice") in [
i18n.t("addarr.Serie"),
i18n.t("addarr.Movie"),
]:
logger.debug(
f"user_data[choice] is {context.user_data["choice"]}, skipping step of selecting movie/series"
)
return searchSerieMovie(update, context)
else:
keyboard = [
[
InlineKeyboardButton(
'\U0001F3AC '+i18n.t("addarr.Movie"),
callback_data=i18n.t("addarr.Movie")
),
InlineKeyboardButton(
'\U0001F4FA '+i18n.t("addarr.Serie"),
callback_data=i18n.t("addarr.Serie")
),
],
[ InlineKeyboardButton(
'\U0001F50D '+i18n.t("addarr.New"),
callback_data=i18n.t("addarr.New")
),
]
]
markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text(i18n.t("addarr.What is this?"), reply_markup=markup)
return READ_CHOICE
def searchSerieMovie(update, context):
title = context.user_data["title"]
if not context.user_data.get("choice"):
choice = None
if update.message is not None:
choice = update.message.text
elif update.callback_query is not None:
choice = update.callback_query.data
context.user_data["choice"] = choice
choice = context.user_data["choice"]
context.user_data["position"] = 0
service = getService(context)
position = context.user_data["position"]
searchResult = service.search(title)
if not searchResult:
context.bot.send_message(
chat_id=update.effective_message.chat_id, text=i18n.t("addarr.searchresults", count=0),
)
clearUserData(context)
return ConversationHandler.END
context.user_data["output"] = service.giveTitles(searchResult)
context.bot.send_message(
chat_id=update.effective_message.chat_id,
text=i18n.t("addarr.searchresults", count=len(searchResult)),
)
keyboard = [
[
InlineKeyboardButton(
'\U00002795 '+i18n.t("addarr.Add"),
callback_data=i18n.t("addarr.Add")
),
],[
InlineKeyboardButton(
'\U000023ED '+i18n.t("addarr.Next result"),
callback_data=i18n.t("addarr.Next result")
),
],[
InlineKeyboardButton(
'\U0001F5D1 '+i18n.t("addarr.New"),
callback_data=i18n.t("addarr.New")
),
],[
InlineKeyboardButton(
'\U0001F6D1 '+i18n.t("addarr.Stop"),
callback_data=i18n.t("addarr.Stop")
),
],
]
markup = InlineKeyboardMarkup(keyboard)
context.bot.send_message(
chat_id=update.effective_message.chat_id,
text=i18n.t("addarr.messages.This", subject=choice.lower()),
)
context.bot.sendPhoto(
chat_id=update.effective_message.chat_id,
photo=context.user_data["output"][position]["poster"],
)
text = f"{context.user_data["output"][position]["title"]} ({context.user_data["output"][position]["year"]})"
context.bot.send_message(
chat_id=update.effective_message.chat_id, text=text, reply_markup=markup
)
return GIVE_OPTION
def nextOption(update, context):
position = context.user_data["position"] + 1
context.user_data["position"] = position
choice = context.user_data["choice"]
if position < len(context.user_data["output"]):
keyboard = [
[
InlineKeyboardButton(
'\U00002795 '+i18n.t("addarr.messages.Add", subject=choice.lower()),
callback_data=i18n.t("addarr.messages.Add", subject=choice.lower())
),
],[
InlineKeyboardButton(
'\U000023ED '+i18n.t("addarr.Next result"),
callback_data=i18n.t("addarr.Next result")
),
],[
InlineKeyboardButton(
'\U0001F5D1 '+i18n.t("addarr.New"),
callback_data=i18n.t("addarr.New")
),
],[
InlineKeyboardButton(
'\U0001F6D1 '+i18n.t("addarr.Stop"),
callback_data=i18n.t("addarr.Stop")
),
],
]
markup = InlineKeyboardMarkup(keyboard)
context.bot.send_message(
chat_id=update.effective_message.chat_id,
text=i18n.t("addarr.messages.This", subject=choice.lower()),
)
context.bot.sendPhoto(
chat_id=update.effective_message.chat_id,
photo=context.user_data["output"][position]["poster"],
)
text = (
context.user_data["output"][position]["title"]
+ " ("
+ str(context.user_data["output"][position]["year"])
+ ")"
)
context.bot.send_message(
chat_id=update.effective_message.chat_id, text=text, reply_markup=markup
)
return GIVE_OPTION
else:
context.bot.send_message(
chat_id=update.effective_message.chat_id,
text=i18n.t("addarr.Last result")
)
clearUserData(context)
return ConversationHandler.END
def pathSerieMovie(update, context):
service = getService(context)
paths = service.getRootFolders()
excluded_root_folders = service.config.get("excludedRootFolders", [])
paths = [p for p in paths if p["path"] not in excluded_root_folders]
logger.debug(f"Excluded root folders: {excluded_root_folders}")
context.user_data.update({"paths": [p["path"] for p in paths]})
if len(paths) == 1:
# There is only 1 path, so use it!
logger.debug("Only found 1 path, so proceeding with that one...")
context.user_data["path"] = paths[0]["path"]
return addSerieMovie(update, context)
logger.debug("Found multiple paths: "+str(paths))
keyboard = []
for p in paths:
free = format_bytes(p['freeSpace'])
keyboard += [[
InlineKeyboardButton(
f"Path: {p["path"]}, Free: {free}",
callback_data=f"Path: {p["path"]}"
),
]]
markup = InlineKeyboardMarkup(keyboard)
context.bot.send_message(
chat_id=update.effective_message.chat_id,
text=i18n.t("addarr.Select a path"),
reply_markup=markup,
)
return GIVE_PATHS
def addSerieMovie(update, context):
position = context.user_data["position"]
choice = context.user_data["choice"]
idnumber = context.user_data["output"][position]["id"]
if not context.user_data.get("path"):
# Path selection should be in the update message
path = None
if update.callback_query is not None:
try_path = update.callback_query.data.replace("Path: ", "").strip()
if try_path in context.user_data.get("paths", {}):
context.user_data["path"] = try_path
path = try_path
if path is None:
logger.debug(
f"Callback query [{update.callback_query.data.replace("Path: ", "").strip()}] doesn't match any of the paths. Sending paths for selection..."
)
return pathSerieMovie(update, context)
path = context.user_data["path"]
service = getService(context)
if not service.inLibrary(idnumber):
if service.addToLibrary(idnumber, path):
context.bot.send_message(
chat_id=update.effective_message.chat_id,
text=i18n.t("addarr.messages.Success", subject=choice.lower()),
)
clearUserData(context)
return ConversationHandler.END
else:
context.bot.send_message(
chat_id=update.effective_message.chat_id,
text=i18n.t("addarr.messages.Failed", subject=choice.lower()),
)
clearUserData(context)
return ConversationHandler.END
else:
context.bot.send_message(
chat_id=update.effective_message.chat_id,
text=i18n.t("addarr.messages.Exist", subject=choice.lower()),
)
clearUserData(context)
return ConversationHandler.END
def allSeries(update, context):
if not checkId(update):
if (
authentication(update, context) == "added"
): # To also stop the beginning command
return ConversationHandler.END
else:
result = sonarr.allSeries()
content = format_long_list_message(result)
if isinstance(content, str):
context.bot.send_message(
chat_id=update.effective_message.chat_id,
text=content,
)
else:
# print every substring
for subString in content:
context.bot.send_message(
chat_id=update.effective_message.chat_id,
text=subString,
)
return ConversationHandler.END
def allMovies(update, context):
if not checkId(update):
if (
authentication(update, context) == "added"
): # To also stop the beginning command
return ConversationHandler.END
else:
result = radarr.all_movies()
content = format_long_list_message(result)
if isinstance(content, str):
context.bot.send_message(
chat_id=update.effective_message.chat_id,
text=content,
)
else:
# print every substring
for subString in content:
context.bot.send_message(
chat_id=update.effective_message.chat_id,
text=subString,
)
return ConversationHandler.END
def getService(context):
if context.user_data.get("choice") == i18n.t("addarr.Serie"):
return sonarr
elif context.user_data.get("choice") == i18n.t("addarr.Movie"):
return radarr
else:
raise ValueError(
f"Cannot determine service based on unknown or missing choice: {context.user_data.get("choice")}."
)
def help(update, context):
context.bot.send_message(
chat_id=update.effective_message.chat_id, text=i18n.t("addarr.Help",
help=config["entrypointHelp"],
authenticate=config["entrypointAuth"],
add=config["entrypointAdd"],
serie='serie',
movie='movie',
allseries=config["entrypointAllSeries"],
allMovies=config["entrypointAllMovies"],
transmission=config["entrypointTransmission"],
)
)
return ConversationHandler.END
def clearUserData(context):
logger.debug(
"Removing choice, title, position, paths, and output from context.user_data..."
)
for x in [
x
for x in ["choice", "title", "position", "output", "paths", "path"]
if x in context.user_data.keys()
]:
context.user_data.pop(x)
if __name__ == "__main__":
main()
| #!/usr/bin/env python3
import logging
import re
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import (CallbackQueryHandler, CommandHandler,
ConversationHandler, Filters, MessageHandler,
Updater)
from commons import checkId, authentication, format_bytes, format_long_list_message
import logger
import radarr as radarr
import sonarr as sonarr
from config import config
from translations import i18n
__version__ = "0.3"
# Set up logging
logLevel = logging.DEBUG if config.get("debugLogging", False) else logging.INFO
logger = logger.getLogger("addarr", logLevel, config.get("logToConsole", False))
logger.debug(f"Addarr v{__version__} starting up...")
SERIE_MOVIE_AUTHENTICATED, READ_CHOICE, GIVE_OPTION, GIVE_PATHS, TSL_NORMAL = range(5)
updater = Updater(config["telegram"]["token"], use_context=True)
dispatcher = updater.dispatcher
def main():
auth_handler_command = CommandHandler(config["entrypointAuth"], authentication)
auth_handler_text = MessageHandler(
Filters.regex(
re.compile(r"^" + config["entrypointAuth"] + "$", re.IGNORECASE)
),
authentication,
)
allSeries_handler_command = CommandHandler(config["entrypointAllSeries"], allSeries)
allSeries_handler_text = MessageHandler(
Filters.regex(
re.compile(r"^" + config["entrypointAllSeries"] + "$", re.IGNORECASE)
),
allSeries,
)
allMovies_handler_command = CommandHandler(config["entrypointAllMovies"], allMovies)
allMovies_handler_text = MessageHandler(
Filters.regex(
re.compile(r"^" + config["entrypointAllMovies"] + "$", re.IGNORECASE)
),
allMovies,
)
addMovieserie_handler = ConversationHandler(
entry_points=[
CommandHandler(config["entrypointAdd"], startSerieMovie),
CommandHandler(i18n.t("addarr.Movie"), startSerieMovie),
CommandHandler(i18n.t("addarr.Serie"), startSerieMovie),
MessageHandler(
Filters.regex(
re.compile(r'^' + config["entrypointAdd"] + '$', re.IGNORECASE)
),
startSerieMovie,
),
],
states={
SERIE_MOVIE_AUTHENTICATED: [MessageHandler(Filters.text, choiceSerieMovie)],
READ_CHOICE: [
MessageHandler(
Filters.regex(f'^({i18n.t("addarr.Movie")}|{i18n.t("addarr.Serie")})$'),
searchSerieMovie,
),
CallbackQueryHandler(searchSerieMovie, pattern=f'^({i18n.t("addarr.Movie")}|{i18n.t("addarr.Serie")})$')
],
GIVE_OPTION: [
CallbackQueryHandler(pathSerieMovie, pattern=f'({i18n.t("addarr.Add")})'),
MessageHandler(
Filters.regex(f'^({i18n.t("addarr.Add")})$'),
pathSerieMovie
),
CallbackQueryHandler(nextOption, pattern=f'({i18n.t("addarr.Next result")})'),
MessageHandler(
Filters.regex(f'^({i18n.t("addarr.Next result")})$'),
nextOption
),
MessageHandler(
Filters.regex(f'^({i18n.t("addarr.New")})$'),
startSerieMovie
),
CallbackQueryHandler(startSerieMovie, pattern=f'({i18n.t("addarr.New")})'),
],
GIVE_PATHS: [
CallbackQueryHandler(addSerieMovie, pattern="^(Path: )(.*)$"),
],
},
fallbacks=[
CommandHandler("stop", stop),
MessageHandler(Filters.regex("^(?i)Stop$"), stop),
CallbackQueryHandler(stop, pattern=f"^(?i)Stop$"),
],
)
if config["transmission"]["enable"]:
import transmission as transmission
changeTransmissionSpeed_handler = ConversationHandler(
entry_points=[
CommandHandler(config["entrypointTransmission"], transmission.transmission),
MessageHandler(
Filters.regex(
re.compile(
r"" + config["entrypointTransmission"] + "", re.IGNORECASE
)
),
transmission.transmission,
),
],
states={
transmission.TSL_NORMAL: [
CallbackQueryHandler(transmission.changeSpeedTransmission),
]
},
fallbacks=[
CommandHandler("stop", stop),
MessageHandler(Filters.regex("^(Stop|stop)$"), stop),
],
)
dispatcher.add_handler(changeTransmissionSpeed_handler)
if config["sabnzbd"]["enable"]:
import sabnzbd as sabnzbd
changeSabznbdSpeed_handler = ConversationHandler(
entry_points=[
CommandHandler(config["entrypointSabnzbd"], sabnzbd.sabnzbd),
MessageHandler(
Filters.regex(
re.compile(
r"" + config["entrypointSabnzbd"] + "", re.IGNORECASE
)
),
sabnzbd.sabnzbd,
),
],
states={
sabnzbd.SABNZBD_SPEED_LIMIT_100: [
CallbackQueryHandler(sabnzbd.changeSpeedSabnzbd),
]
},
fallbacks=[
CommandHandler("stop", stop),
MessageHandler(Filters.regex("^(Stop|stop)$"), stop),
],
)
dispatcher.add_handler(changeSabznbdSpeed_handler)
dispatcher.add_handler(auth_handler_command)
dispatcher.add_handler(auth_handler_text)
dispatcher.add_handler(allSeries_handler_command)
dispatcher.add_handler(allSeries_handler_text)
dispatcher.add_handler(allMovies_handler_command)
dispatcher.add_handler(allMovies_handler_text)
dispatcher.add_handler(addMovieserie_handler)
help_handler_command = CommandHandler(config["entrypointHelp"], help)
dispatcher.add_handler(help_handler_command)
logger.info(i18n.t("addarr.Start chatting"))
updater.start_polling()
updater.idle()
def stop(update, context):
clearUserData(context)
context.bot.send_message(
chat_id=update.effective_message.chat_id, text=i18n.t("addarr.End")
)
return ConversationHandler.END
def startSerieMovie(update : Update, context):
if not checkId(update):
context.bot.send_message(
chat_id=update.effective_message.chat_id, text=i18n.t("addarr.Authorize")
)
return SERIE_MOVIE_AUTHENTICATED
if update.message is not None:
reply = update.message.text.lower()
elif update.callback_query is not None:
reply = update.callback_query.data.lower()
else:
return SERIE_MOVIE_AUTHENTICATED
if reply[1:] in [
i18n.t("addarr.Serie").lower(),
i18n.t("addarr.Movie").lower(),
]:
logger.debug(
f"User issued {reply} command, so setting user_data[choice] accordingly"
)
context.user_data.update(
{
"choice": i18n.t("addarr.Serie")
if reply[1:] == i18n.t("addarr.Serie").lower()
else i18n.t("addarr.Movie")
}
)
elif reply == i18n.t("addarr.New").lower():
logger.debug("User issued New command, so clearing user_data")
clearUserData(context)
context.bot.send_message(
chat_id=update.effective_message.chat_id, text='\U0001F3F7 '+i18n.t("addarr.Title")
)
return SERIE_MOVIE_AUTHENTICATED
def choiceSerieMovie(update, context):
if not checkId(update):
if (
authentication(update, context) == "added"
): # To also stop the beginning command
return ConversationHandler.END
elif update.message.text.lower() == "/stop".lower() or update.message.text.lower() == "stop".lower():
return stop(update, context)
else:
if update.message is not None:
reply = update.message.text
elif update.callback_query is not None:
reply = update.callback_query.data
else:
return SERIE_MOVIE_AUTHENTICATED
if reply.lower() not in [
i18n.t("addarr.Serie").lower(),
i18n.t("addarr.Movie").lower(),
]:
logger.debug(
f"User entered a title {reply}"
)
context.user_data["title"] = reply
if context.user_data.get("choice") in [
i18n.t("addarr.Serie"),
i18n.t("addarr.Movie"),
]:
logger.debug(
f"user_data[choice] is {context.user_data['choice']}, skipping step of selecting movie/series"
)
return searchSerieMovie(update, context)
else:
keyboard = [
[
InlineKeyboardButton(
'\U0001F3AC '+i18n.t("addarr.Movie"),
callback_data=i18n.t("addarr.Movie")
),
InlineKeyboardButton(
'\U0001F4FA '+i18n.t("addarr.Serie"),
callback_data=i18n.t("addarr.Serie")
),
],
[ InlineKeyboardButton(
'\U0001F50D '+i18n.t("addarr.New"),
callback_data=i18n.t("addarr.New")
),
]
]
markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text(i18n.t("addarr.What is this?"), reply_markup=markup)
return READ_CHOICE
def searchSerieMovie(update, context):
title = context.user_data["title"]
if not context.user_data.get("choice"):
choice = None
if update.message is not None:
choice = update.message.text
elif update.callback_query is not None:
choice = update.callback_query.data
context.user_data["choice"] = choice
choice = context.user_data["choice"]
context.user_data["position"] = 0
service = getService(context)
position = context.user_data["position"]
searchResult = service.search(title)
if not searchResult:
context.bot.send_message(
chat_id=update.effective_message.chat_id, text=i18n.t("addarr.searchresults", count=0),
)
clearUserData(context)
return ConversationHandler.END
context.user_data["output"] = service.giveTitles(searchResult)
context.bot.send_message(
chat_id=update.effective_message.chat_id,
text=i18n.t("addarr.searchresults", count=len(searchResult)),
)
keyboard = [
[
InlineKeyboardButton(
'\U00002795 '+i18n.t("addarr.Add"),
callback_data=i18n.t("addarr.Add")
),
],[
InlineKeyboardButton(
'\U000023ED '+i18n.t("addarr.Next result"),
callback_data=i18n.t("addarr.Next result")
),
],[
InlineKeyboardButton(
'\U0001F5D1 '+i18n.t("addarr.New"),
callback_data=i18n.t("addarr.New")
),
],[
InlineKeyboardButton(
'\U0001F6D1 '+i18n.t("addarr.Stop"),
callback_data=i18n.t("addarr.Stop")
),
],
]
markup = InlineKeyboardMarkup(keyboard)
context.bot.send_message(
chat_id=update.effective_message.chat_id,
text=i18n.t("addarr.messages.This", subject=choice.lower()),
)
context.bot.sendPhoto(
chat_id=update.effective_message.chat_id,
photo=context.user_data["output"][position]["poster"],
)
text = f"{context.user_data['output'][position]['title']} ({context.user_data['output'][position]['year']})"
context.bot.send_message(
chat_id=update.effective_message.chat_id, text=text, reply_markup=markup
)
return GIVE_OPTION
def nextOption(update, context):
position = context.user_data["position"] + 1
context.user_data["position"] = position
choice = context.user_data["choice"]
if position < len(context.user_data["output"]):
keyboard = [
[
InlineKeyboardButton(
'\U00002795 '+i18n.t("addarr.messages.Add", subject=choice.lower()),
callback_data=i18n.t("addarr.messages.Add", subject=choice.lower())
),
],[
InlineKeyboardButton(
'\U000023ED '+i18n.t("addarr.Next result"),
callback_data=i18n.t("addarr.Next result")
),
],[
InlineKeyboardButton(
'\U0001F5D1 '+i18n.t("addarr.New"),
callback_data=i18n.t("addarr.New")
),
],[
InlineKeyboardButton(
'\U0001F6D1 '+i18n.t("addarr.Stop"),
callback_data=i18n.t("addarr.Stop")
),
],
]
markup = InlineKeyboardMarkup(keyboard)
context.bot.send_message(
chat_id=update.effective_message.chat_id,
text=i18n.t("addarr.messages.This", subject=choice.lower()),
)
context.bot.sendPhoto(
chat_id=update.effective_message.chat_id,
photo=context.user_data["output"][position]["poster"],
)
text = (
context.user_data["output"][position]["title"]
+ " ("
+ str(context.user_data["output"][position]["year"])
+ ")"
)
context.bot.send_message(
chat_id=update.effective_message.chat_id, text=text, reply_markup=markup
)
return GIVE_OPTION
else:
context.bot.send_message(
chat_id=update.effective_message.chat_id,
text=i18n.t("addarr.Last result")
)
clearUserData(context)
return ConversationHandler.END
def pathSerieMovie(update, context):
service = getService(context)
paths = service.getRootFolders()
excluded_root_folders = service.config.get("excludedRootFolders", [])
paths = [p for p in paths if p["path"] not in excluded_root_folders]
logger.debug(f"Excluded root folders: {excluded_root_folders}")
context.user_data.update({"paths": [p["path"] for p in paths]})
if len(paths) == 1:
# There is only 1 path, so use it!
logger.debug("Only found 1 path, so proceeding with that one...")
context.user_data["path"] = paths[0]["path"]
return addSerieMovie(update, context)
logger.debug("Found multiple paths: "+str(paths))
keyboard = []
for p in paths:
free = format_bytes(p['freeSpace'])
keyboard += [[
InlineKeyboardButton(
f"Path: {p['path']}, Free: {free}",
callback_data=f"Path: {p['path']}"
),
]]
markup = InlineKeyboardMarkup(keyboard)
context.bot.send_message(
chat_id=update.effective_message.chat_id,
text=i18n.t("addarr.Select a path"),
reply_markup=markup,
)
return GIVE_PATHS
def addSerieMovie(update, context):
position = context.user_data["position"]
choice = context.user_data["choice"]
idnumber = context.user_data["output"][position]["id"]
if not context.user_data.get("path"):
# Path selection should be in the update message
path = None
if update.callback_query is not None:
try_path = update.callback_query.data.replace("Path: ", "").strip()
if try_path in context.user_data.get("paths", {}):
context.user_data["path"] = try_path
path = try_path
if path is None:
logger.debug(
f"Callback query [{update.callback_query.data.replace('Path: ', '').strip()}] doesn't match any of the paths. Sending paths for selection..."
)
return pathSerieMovie(update, context)
path = context.user_data["path"]
service = getService(context)
if not service.inLibrary(idnumber):
if service.addToLibrary(idnumber, path):
context.bot.send_message(
chat_id=update.effective_message.chat_id,
text=i18n.t("addarr.messages.Success", subject=choice.lower()),
)
clearUserData(context)
return ConversationHandler.END
else:
context.bot.send_message(
chat_id=update.effective_message.chat_id,
text=i18n.t("addarr.messages.Failed", subject=choice.lower()),
)
clearUserData(context)
return ConversationHandler.END
else:
context.bot.send_message(
chat_id=update.effective_message.chat_id,
text=i18n.t("addarr.messages.Exist", subject=choice.lower()),
)
clearUserData(context)
return ConversationHandler.END
def allSeries(update, context):
if not checkId(update):
if (
authentication(update, context) == "added"
): # To also stop the beginning command
return ConversationHandler.END
else:
result = sonarr.allSeries()
content = format_long_list_message(result)
if isinstance(content, str):
context.bot.send_message(
chat_id=update.effective_message.chat_id,
text=content,
)
else:
# print every substring
for subString in content:
context.bot.send_message(
chat_id=update.effective_message.chat_id,
text=subString,
)
return ConversationHandler.END
def allMovies(update, context):
if not checkId(update):
if (
authentication(update, context) == "added"
): # To also stop the beginning command
return ConversationHandler.END
else:
result = radarr.all_movies()
content = format_long_list_message(result)
if isinstance(content, str):
context.bot.send_message(
chat_id=update.effective_message.chat_id,
text=content,
)
else:
# print every substring
for subString in content:
context.bot.send_message(
chat_id=update.effective_message.chat_id,
text=subString,
)
return ConversationHandler.END
def getService(context):
if context.user_data.get("choice") == i18n.t("addarr.Serie"):
return sonarr
elif context.user_data.get("choice") == i18n.t("addarr.Movie"):
return radarr
else:
raise ValueError(
f"Cannot determine service based on unknown or missing choice: {context.user_data.get('choice')}."
)
def help(update, context):
context.bot.send_message(
chat_id=update.effective_message.chat_id, text=i18n.t("addarr.Help",
help=config["entrypointHelp"],
authenticate=config["entrypointAuth"],
add=config["entrypointAdd"],
serie='serie',
movie='movie',
allseries=config["entrypointAllSeries"],
allMovies=config["entrypointAllMovies"],
transmission=config["entrypointTransmission"],
)
)
return ConversationHandler.END
def clearUserData(context):
logger.debug(
"Removing choice, title, position, paths, and output from context.user_data..."
)
for x in [
x
for x in ["choice", "title", "position", "output", "paths", "path"]
if x in context.user_data.keys()
]:
context.user_data.pop(x)
if __name__ == "__main__":
main()
|
# Copyright 2016-2021, Pulumi Corporation.
#
# 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 asyncio
import os
import traceback
from typing import Optional, Any, Callable, List, NamedTuple, Dict, Set, Tuple, Union, TYPE_CHECKING, cast, Mapping
from google.protobuf import struct_pb2
import grpc
from . import rpc, settings, known_types
from .. import log
from ..runtime.proto import provider_pb2, resource_pb2
from .rpc_manager import RPC_MANAGER
from .settings import handle_grpc_error
from .. import _types
if TYPE_CHECKING:
from .. import Resource, ResourceOptions, CustomResource, Inputs, Output, ProviderResource
class ResourceResolverOperations(NamedTuple):
"""
The set of properties resulting from a successful call to prepare_resource.
"""
parent_urn: Optional[str]
"""
This resource's parent URN.
"""
serialized_props: struct_pb2.Struct
"""
This resource's input properties, serialized into protobuf structures.
"""
dependencies: Set[str]
"""
The set of URNs, corresponding to the resources that this resource depends on.
"""
provider_ref: Optional[str]
"""
An optional reference to a provider that should be used for this resource's CRUD operations.
"""
provider_refs: Dict[str, Optional[str]]
"""
An optional dict of references to providers that should be used for this resource's CRUD operations.
"""
property_dependencies: Dict[str, List[Optional[str]]]
"""
A map from property name to the URNs of the resources the property depends on.
"""
aliases: List[Optional[str]]
"""
A list of aliases applied to this resource.
"""
# Prepares for an RPC that will manufacture a resource, and hence deals with input and output properties.
# pylint: disable=too-many-locals
async def prepare_resource(res: 'Resource',
ty: str,
custom: bool,
remote: bool,
props: 'Inputs',
opts: Optional['ResourceOptions'],
typ: Optional[type] = None) -> ResourceResolverOperations:
from .. import Output # pylint: disable=import-outside-toplevel
# Before we can proceed, all our dependencies must be finished.
explicit_urn_dependencies = []
if opts is not None and opts.depends_on is not None:
dependent_urns = list(map(lambda r: r.urn.future(), opts.depends_on))
explicit_urn_dependencies = await asyncio.gather(*dependent_urns)
# Serialize out all our props to their final values. In doing so, we'll also collect all
# the Resources pointed to by any Dependency objects we encounter, adding them to 'implicit_dependencies'.
property_dependencies_resources: Dict[str, List['Resource']] = {}
# If we have type information, we'll use it for translations rather than the resource's translate_input_property.
translate: Optional[Callable[[str], str]] = res.translate_input_property
if typ is not None:
translate = None
serialized_props = await rpc.serialize_properties(props, property_dependencies_resources, translate, typ)
# Wait for our parent to resolve
parent_urn: Optional[str] = ""
if opts is not None and opts.parent is not None:
parent_urn = await opts.parent.urn.future()
# TODO(sean) is it necessary to check the type here?
elif ty != "pulumi:pulumi:Stack":
# If no parent was provided, parent to the root resource.
parent = settings.get_root_resource()
if parent is not None:
parent_urn = await parent.urn.future()
# Construct the provider reference, if we were given a provider to use.
provider_ref = None
if custom and opts is not None and opts.provider is not None:
provider = opts.provider
# If we were given a provider, wait for it to resolve and construct a provider reference from it.
# A provider reference is a well-known string (two ::-separated values) that the engine interprets.
provider_urn = await provider.urn.future()
provider_id = await provider.id.future() or rpc.UNKNOWN
provider_ref = f"{provider_urn}::{provider_id}"
# For remote resources, merge any provider opts into a single dict, and then create a new dict with all of the
# resolved provider refs.
provider_refs: Dict[str, Optional[str]] = {}
if remote and opts is not None:
providers = convert_providers(opts.provider, opts.providers)
for name, provider in providers.items():
# If we were given providers, wait for them to resolve and construct provider references from them.
# A provider reference is a well-known string (two ::-separated values) that the engine interprets.
urn = await provider.urn.future()
id_ = await provider.id.future() or rpc.UNKNOWN
ref = f"{urn}::{id_}"
provider_refs[name] = ref
dependencies = set(explicit_urn_dependencies)
property_dependencies: Dict[str, List[Optional[str]]] = {}
for key, deps in property_dependencies_resources.items():
urns = set()
for dep in deps:
urn = await dep.urn.future()
urns.add(urn)
dependencies.add(urn)
property_dependencies[key] = list(urns)
# Wait for all aliases. Note that we use `res._aliases` instead of `opts.aliases` as the
# former has been processed in the Resource constructor prior to calling
# `register_resource` - both adding new inherited aliases and simplifying aliases down
# to URNs.
aliases: List[Optional[str]] = []
for alias in res._aliases:
alias_val = await Output.from_input(alias).future()
if not alias_val in aliases:
aliases.append(alias_val)
return ResourceResolverOperations(
parent_urn,
serialized_props,
dependencies,
provider_ref,
provider_refs,
property_dependencies,
aliases,
)
def resource_output(res: 'Resource') -> Tuple[Callable[[Any, bool, bool, Optional[Exception]], None], 'Output']:
from .. import Output # pylint: disable=import-outside-toplevel
value_future: asyncio.Future[Any] = asyncio.Future()
known_future: asyncio.Future[bool] = asyncio.Future()
secret_future: asyncio.Future[bool] = asyncio.Future()
def resolve(value: Any, known: bool, secret: bool, exn: Optional[Exception]):
if exn is not None:
value_future.set_exception(exn)
known_future.set_exception(exn)
secret_future.set_exception(exn)
else:
value_future.set_result(value)
known_future.set_result(known)
secret_future.set_result(secret)
return resolve, Output({res}, value_future, known_future, secret_future)
def get_resource(res: 'Resource',
props: 'Inputs',
custom: bool,
urn: str,
typ: Optional[type] = None) -> None:
log.debug(f"getting resource: urn={urn}")
# If we have type information, we'll use its and the resource's type/name metadata
# for name translations rather than using the resource's translation methods.
transform_using_type_metadata = typ is not None
# Extract the resource type from the URN.
urn_parts = urn.split("::")
qualified_type = urn_parts[2]
ty = qualified_type.split("$")[-1]
# Initialize the URN property on the resource.
(resolve_urn, res.__dict__["urn"]) = resource_output(res)
# If this is a custom resource, initialize its ID property.
resolve_id: Optional[Callable[[Any, bool, bool, Optional[Exception]], None]] = None
if custom:
(resolve_id, res.__dict__["id"]) = resource_output(res)
# Like the other resource functions, "transfer" all input properties onto unresolved futures on res.
resolvers = rpc.transfer_properties(res, props)
async def do_get():
try:
resolver = await prepare_resource(res, ty, custom, False, props, None, typ)
monitor = settings.get_monitor()
inputs = await rpc.serialize_properties({"urn": urn}, {})
req = provider_pb2.InvokeRequest(tok="pulumi:pulumi:getResource", args=inputs, provider="", version="")
def do_invoke():
try:
return monitor.Invoke(req)
except grpc.RpcError as exn:
handle_grpc_error(exn)
return None
resp = await asyncio.get_event_loop().run_in_executor(None, do_invoke)
# If the invoke failed, raise an error.
if resp.failures:
raise Exception(f"getResource failed: {resp.failures[0].reason} ({resp.failures[0].property})")
except Exception as exn:
log.debug(
f"exception when preparing or executing rpc: {traceback.format_exc()}")
rpc.resolve_outputs_due_to_exception(resolvers, exn)
resolve_urn(None, True, False, exn)
if resolve_id is not None:
resolve_id(None, True, False, exn)
raise
# Otherwise, grab the URN, ID, and output properties and resolve all of them.
resp = getattr(resp, 'return')
log.debug(f"getResource completed successfully: ty={ty}, urn={resp["urn"]}")
resolve_urn(resp["urn"], True, False, None)
if resolve_id:
# The ID is known if (and only if) it is a non-empty string. If it's either None or an
# empty string, we should treat it as unknown. TFBridge in particular is known to send
# the empty string as an ID when doing a preview.
is_known = bool(resp["id"])
resolve_id(resp["id"], is_known, False, None)
rpc.resolve_outputs(res, resolver.serialized_props, resp["state"], {}, resolvers, transform_using_type_metadata)
asyncio.ensure_future(RPC_MANAGER.do_rpc("get resource", do_get)())
def _translate_ignore_changes(res: 'Resource',
typ: Optional[type],
ignore_changes: Optional[List[str]]) -> Optional[List[str]]:
if ignore_changes is not None:
if typ is not None:
# If `typ` is specified, use its type/name metadata for translation.
input_names = _types.input_type_py_to_pulumi_names(typ)
ignore_changes = list(map(lambda k: input_names.get(k) or k, ignore_changes))
elif res.translate_input_property is not None:
ignore_changes = list(map(res.translate_input_property, ignore_changes))
return ignore_changes
def _translate_additional_secret_outputs(res: 'Resource',
typ: Optional[type],
additional_secret_outputs: Optional[List[str]]) -> Optional[List[str]]:
if additional_secret_outputs is not None:
if typ is not None:
# If a `typ` is specified, we've opt-ed in to doing translations using type/name metadata rather
# than using the resource's tranlate_input_property. Use the resource's metadata to translate.
output_names = _types.resource_py_to_pulumi_names(type(res))
additional_secret_outputs = list(map(lambda k: output_names.get(k) or k, additional_secret_outputs))
elif res.translate_input_property is not None:
# Note that while `additional_secret_outputs` lists property names that are outputs, we
# call `translate_input_property` because it is the method that converts from the
# language projection name to the provider name, which is what we want.
additional_secret_outputs = list(map(res.translate_input_property, additional_secret_outputs))
return additional_secret_outputs
def read_resource(res: 'CustomResource',
ty: str,
name: str,
props: 'Inputs',
opts: 'ResourceOptions',
typ: Optional[type] = None) -> None:
if opts.id is None:
raise Exception(
"Cannot read resource whose options are lacking an ID value")
log.debug(f"reading resource: ty={ty}, name={name}, id={opts.id}")
monitor = settings.get_monitor()
# If we have type information, we'll use its and the resource's type/name metadata
# for name translations rather than using the resource's translation methods.
transform_using_type_metadata = typ is not None
# Prepare the resource, similar to a RegisterResource. Reads are deliberately similar to RegisterResource except
# that we are populating the Resource object with properties associated with an already-live resource.
#
# Same as below, we initialize the URN property on the resource, which will always be resolved.
(resolve_urn, res.__dict__["urn"]) = resource_output(res)
# Furthermore, since resources being Read must always be custom resources (enforced in the
# Resource constructor), we'll need to set up the ID field which will be populated at the end of
# the ReadResource call.
#
# Note that we technically already have the ID (opts.id), but it's more consistent with the rest
# of the model to resolve it asynchronously along with all of the other resources.
(resolve_id, res.__dict__["id"]) = resource_output(res)
# Like below, "transfer" all input properties onto unresolved futures on res.
resolvers = rpc.transfer_properties(res, props)
async def do_read():
try:
resolver = await prepare_resource(res, ty, True, False, props, opts, typ)
# Resolve the ID that we were given. Note that we are explicitly discarding the list of
# dependencies returned to us from "serialize_property" (the second argument). This is
# because a "read" resource does not actually have any dependencies at all in the cloud
# provider sense, because a read resource already exists. We do not need to track this
# dependency.
resolved_id = await rpc.serialize_property(opts.id, [])
log.debug(f"read prepared: ty={ty}, name={name}, id={opts.id}")
# These inputs will end up in the snapshot, so if there are any additional secret
# outputs, record them here.
additional_secret_outputs = _translate_additional_secret_outputs(res, typ, opts.additional_secret_outputs)
accept_resources = not (os.getenv("PULUMI_DISABLE_RESOURCE_REFERENCES", "").upper() in {"TRUE", "1"})
req = resource_pb2.ReadResourceRequest(
type=ty,
name=name,
id=resolved_id,
parent=resolver.parent_urn,
provider=resolver.provider_ref,
properties=resolver.serialized_props,
dependencies=resolver.dependencies,
version=opts.version or "",
acceptSecrets=True,
acceptResources=accept_resources,
additionalSecretOutputs=additional_secret_outputs,
)
from ..resource import create_urn # pylint: disable=import-outside-toplevel
mock_urn = await create_urn(name, ty, resolver.parent_urn).future()
def do_rpc_call():
if monitor is None:
# If no monitor is available, we'll need to fake up a response, for testing.
return RegisterResponse(mock_urn, None, resolver.serialized_props, None)
# If there is a monitor available, make the true RPC request to the engine.
try:
return monitor.ReadResource(req)
except grpc.RpcError as exn:
handle_grpc_error(exn)
return None
resp = await asyncio.get_event_loop().run_in_executor(None, do_rpc_call)
except Exception as exn:
log.debug(
f"exception when preparing or executing rpc: {traceback.format_exc()}")
rpc.resolve_outputs_due_to_exception(resolvers, exn)
resolve_urn(None, True, False, exn)
resolve_id(None, True, False, exn)
raise
log.debug(f"resource read successful: ty={ty}, urn={resp.urn}")
resolve_urn(resp.urn, True, False, None)
resolve_id(resolved_id, True, False, None) # Read IDs are always known.
rpc.resolve_outputs(res, resolver.serialized_props, resp.properties, {}, resolvers,
transform_using_type_metadata)
asyncio.ensure_future(RPC_MANAGER.do_rpc("read resource", do_read)())
def register_resource(res: 'Resource',
ty: str,
name: str,
custom: bool,
remote: bool,
new_dependency: Callable[[str], 'Resource'],
props: 'Inputs',
opts: Optional['ResourceOptions'],
typ: Optional[type] = None) -> None:
"""
Registers a new resource object with a given type t and name. It returns the
auto-generated URN and the ID that will resolve after the deployment has completed. All
properties will be initialized to property objects that the registration operation will resolve
at the right time (or remain unresolved for deployments).
"""
log.debug(f"registering resource: ty={ty}, name={name}, custom={custom}, remote={remote}")
monitor = settings.get_monitor()
# If we have type information, we'll use its and the resource's type/name metadata
# for name translations rather than using the resource's translation methods.
transform_using_type_metadata = typ is not None
# Prepare the resource.
# Simply initialize the URN property and get prepared to resolve it later on.
# Note: a resource urn will always get a value, and thus the output property
# for it can always run .apply calls.
(resolve_urn, res.__dict__["urn"]) = resource_output(res)
# If a custom resource, make room for the ID property.
resolve_id: Optional[Callable[[Any, bool, bool, Optional[Exception]], None]] = None
if custom:
(resolve_id, res.__dict__["id"]) = resource_output(res)
# Now "transfer" all input properties into unresolved futures on res. This way,
# this resource will look like it has all its output properties to anyone it is
# passed to. However, those futures won't actually resolve until the RPC returns
resolvers = rpc.transfer_properties(res, props)
async def do_register():
try:
resolver = await prepare_resource(res, ty, custom, remote, props, opts, typ)
log.debug(f"resource registration prepared: ty={ty}, name={name}")
property_dependencies = {}
for key, deps in resolver.property_dependencies.items():
property_dependencies[key] = resource_pb2.RegisterResourceRequest.PropertyDependencies(
urns=deps)
ignore_changes = _translate_ignore_changes(res, typ, opts.ignore_changes)
additional_secret_outputs = _translate_additional_secret_outputs(res, typ, opts.additional_secret_outputs)
# Translate the CustomTimeouts object.
custom_timeouts = None
if opts.custom_timeouts is not None:
custom_timeouts = resource_pb2.RegisterResourceRequest.CustomTimeouts()
# It could be an actual CustomTimeouts object.
if known_types.is_custom_timeouts(opts.custom_timeouts):
if opts.custom_timeouts.create is not None:
custom_timeouts.create = opts.custom_timeouts.create
if opts.custom_timeouts.update is not None:
custom_timeouts.update = opts.custom_timeouts.update
if opts.custom_timeouts.delete is not None:
custom_timeouts.delete = opts.custom_timeouts.delete
# Or, it could be a workaround passing in a dict.
elif isinstance(opts.custom_timeouts, dict):
if 'create' in opts.custom_timeouts:
custom_timeouts.create = opts.custom_timeouts['create']
if 'update' in opts.custom_timeouts:
custom_timeouts.update = opts.custom_timeouts['update']
if 'delete' in opts.custom_timeouts:
custom_timeouts.delete = opts.custom_timeouts['delete']
else:
raise Exception("Expected custom_timeouts to be a CustomTimeouts object")
accept_resources = not (os.getenv("PULUMI_DISABLE_RESOURCE_REFERENCES", "").upper() in {"TRUE", "1"})
req = resource_pb2.RegisterResourceRequest(
type=ty,
name=name,
parent=resolver.parent_urn,
custom=custom,
object=resolver.serialized_props,
protect=opts.protect,
provider=resolver.provider_ref,
providers=resolver.provider_refs,
dependencies=resolver.dependencies,
propertyDependencies=property_dependencies,
deleteBeforeReplace=opts.delete_before_replace,
deleteBeforeReplaceDefined=opts.delete_before_replace is not None,
ignoreChanges=ignore_changes,
version=opts.version or "",
acceptSecrets=True,
acceptResources=accept_resources,
additionalSecretOutputs=additional_secret_outputs,
importId=opts.import_,
customTimeouts=custom_timeouts,
aliases=resolver.aliases,
supportsPartialValues=True,
remote=remote,
)
from ..resource import create_urn # pylint: disable=import-outside-toplevel
mock_urn = await create_urn(name, ty, resolver.parent_urn).future()
def do_rpc_call():
if monitor is None:
# If no monitor is available, we'll need to fake up a response, for testing.
return RegisterResponse(mock_urn, None, resolver.serialized_props, None)
# If there is a monitor available, make the true RPC request to the engine.
try:
return monitor.RegisterResource(req)
except grpc.RpcError as exn:
handle_grpc_error(exn)
return None
resp = await asyncio.get_event_loop().run_in_executor(None, do_rpc_call)
except Exception as exn:
log.debug(
f"exception when preparing or executing rpc: {traceback.format_exc()}")
rpc.resolve_outputs_due_to_exception(resolvers, exn)
resolve_urn(None, True, False, exn)
if resolve_id is not None:
resolve_id(None, True, False, exn)
raise
if resp is None:
return
log.debug(f"resource registration successful: ty={ty}, urn={resp.urn}")
resolve_urn(resp.urn, True, False, None)
if resolve_id is not None:
# The ID is known if (and only if) it is a non-empty string. If it's either None or an
# empty string, we should treat it as unknown. TFBridge in particular is known to send
# the empty string as an ID when doing a preview.
is_known = bool(resp.id)
resolve_id(resp.id, is_known, False, None)
deps = {}
rpc_deps = resp.propertyDependencies
if rpc_deps:
for k, v in rpc_deps.items():
urns = list(v.urns)
deps[k] = set(map(new_dependency, urns))
rpc.resolve_outputs(res, resolver.serialized_props, resp.object, deps, resolvers, transform_using_type_metadata)
asyncio.ensure_future(RPC_MANAGER.do_rpc(
"register resource", do_register)())
def register_resource_outputs(res: 'Resource', outputs: 'Union[Inputs, Output[Inputs]]'):
async def do_register_resource_outputs():
urn = await res.urn.future()
serialized_props = await rpc.serialize_properties(outputs, {})
log.debug(
f"register resource outputs prepared: urn={urn}, props={serialized_props}")
monitor = settings.get_monitor()
req = resource_pb2.RegisterResourceOutputsRequest(
urn=urn, outputs=serialized_props)
def do_rpc_call():
if monitor is None:
# If there's no engine attached, simply ignore it.
return None
try:
return monitor.RegisterResourceOutputs(req)
except grpc.RpcError as exn:
handle_grpc_error(exn)
return None
await asyncio.get_event_loop().run_in_executor(None, do_rpc_call)
log.debug(
f"resource registration successful: urn={urn}, props={serialized_props}")
asyncio.ensure_future(RPC_MANAGER.do_rpc(
"register resource outputs", do_register_resource_outputs)())
class PropertyDependencies:
urns: List[str]
def __init__(self, urns: List[str]):
self.urns = urns
class RegisterResponse:
urn: str
id: Optional[str]
object: struct_pb2.Struct
propertyDependencies: Optional[Dict[str, PropertyDependencies]]
# pylint: disable=redefined-builtin
def __init__(self,
urn: str,
id: Optional[str],
object: struct_pb2.Struct,
propertyDependencies: Optional[Dict[str, PropertyDependencies]]):
self.urn = urn
self.id = id
self.object = object
self.propertyDependencies = propertyDependencies
# Merge all providers opts (opts.provider and both list and dict forms of opts.providers) into a single dict.
def convert_providers(
provider: Optional['ProviderResource'],
providers: Optional[Union[Mapping[str, 'ProviderResource'],
List['ProviderResource']]]) -> Mapping[str, 'ProviderResource']:
if provider is not None:
return convert_providers(None, [provider])
if providers is None:
return {}
if not isinstance(providers, list):
return providers
result = {}
for p in providers:
result[p.package] = p
return result
| # Copyright 2016-2021, Pulumi Corporation.
#
# 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 asyncio
import os
import traceback
from typing import Optional, Any, Callable, List, NamedTuple, Dict, Set, Tuple, Union, TYPE_CHECKING, cast, Mapping
from google.protobuf import struct_pb2
import grpc
from . import rpc, settings, known_types
from .. import log
from ..runtime.proto import provider_pb2, resource_pb2
from .rpc_manager import RPC_MANAGER
from .settings import handle_grpc_error
from .. import _types
if TYPE_CHECKING:
from .. import Resource, ResourceOptions, CustomResource, Inputs, Output, ProviderResource
class ResourceResolverOperations(NamedTuple):
"""
The set of properties resulting from a successful call to prepare_resource.
"""
parent_urn: Optional[str]
"""
This resource's parent URN.
"""
serialized_props: struct_pb2.Struct
"""
This resource's input properties, serialized into protobuf structures.
"""
dependencies: Set[str]
"""
The set of URNs, corresponding to the resources that this resource depends on.
"""
provider_ref: Optional[str]
"""
An optional reference to a provider that should be used for this resource's CRUD operations.
"""
provider_refs: Dict[str, Optional[str]]
"""
An optional dict of references to providers that should be used for this resource's CRUD operations.
"""
property_dependencies: Dict[str, List[Optional[str]]]
"""
A map from property name to the URNs of the resources the property depends on.
"""
aliases: List[Optional[str]]
"""
A list of aliases applied to this resource.
"""
# Prepares for an RPC that will manufacture a resource, and hence deals with input and output properties.
# pylint: disable=too-many-locals
async def prepare_resource(res: 'Resource',
ty: str,
custom: bool,
remote: bool,
props: 'Inputs',
opts: Optional['ResourceOptions'],
typ: Optional[type] = None) -> ResourceResolverOperations:
from .. import Output # pylint: disable=import-outside-toplevel
# Before we can proceed, all our dependencies must be finished.
explicit_urn_dependencies = []
if opts is not None and opts.depends_on is not None:
dependent_urns = list(map(lambda r: r.urn.future(), opts.depends_on))
explicit_urn_dependencies = await asyncio.gather(*dependent_urns)
# Serialize out all our props to their final values. In doing so, we'll also collect all
# the Resources pointed to by any Dependency objects we encounter, adding them to 'implicit_dependencies'.
property_dependencies_resources: Dict[str, List['Resource']] = {}
# If we have type information, we'll use it for translations rather than the resource's translate_input_property.
translate: Optional[Callable[[str], str]] = res.translate_input_property
if typ is not None:
translate = None
serialized_props = await rpc.serialize_properties(props, property_dependencies_resources, translate, typ)
# Wait for our parent to resolve
parent_urn: Optional[str] = ""
if opts is not None and opts.parent is not None:
parent_urn = await opts.parent.urn.future()
# TODO(sean) is it necessary to check the type here?
elif ty != "pulumi:pulumi:Stack":
# If no parent was provided, parent to the root resource.
parent = settings.get_root_resource()
if parent is not None:
parent_urn = await parent.urn.future()
# Construct the provider reference, if we were given a provider to use.
provider_ref = None
if custom and opts is not None and opts.provider is not None:
provider = opts.provider
# If we were given a provider, wait for it to resolve and construct a provider reference from it.
# A provider reference is a well-known string (two ::-separated values) that the engine interprets.
provider_urn = await provider.urn.future()
provider_id = await provider.id.future() or rpc.UNKNOWN
provider_ref = f"{provider_urn}::{provider_id}"
# For remote resources, merge any provider opts into a single dict, and then create a new dict with all of the
# resolved provider refs.
provider_refs: Dict[str, Optional[str]] = {}
if remote and opts is not None:
providers = convert_providers(opts.provider, opts.providers)
for name, provider in providers.items():
# If we were given providers, wait for them to resolve and construct provider references from them.
# A provider reference is a well-known string (two ::-separated values) that the engine interprets.
urn = await provider.urn.future()
id_ = await provider.id.future() or rpc.UNKNOWN
ref = f"{urn}::{id_}"
provider_refs[name] = ref
dependencies = set(explicit_urn_dependencies)
property_dependencies: Dict[str, List[Optional[str]]] = {}
for key, deps in property_dependencies_resources.items():
urns = set()
for dep in deps:
urn = await dep.urn.future()
urns.add(urn)
dependencies.add(urn)
property_dependencies[key] = list(urns)
# Wait for all aliases. Note that we use `res._aliases` instead of `opts.aliases` as the
# former has been processed in the Resource constructor prior to calling
# `register_resource` - both adding new inherited aliases and simplifying aliases down
# to URNs.
aliases: List[Optional[str]] = []
for alias in res._aliases:
alias_val = await Output.from_input(alias).future()
if not alias_val in aliases:
aliases.append(alias_val)
return ResourceResolverOperations(
parent_urn,
serialized_props,
dependencies,
provider_ref,
provider_refs,
property_dependencies,
aliases,
)
def resource_output(res: 'Resource') -> Tuple[Callable[[Any, bool, bool, Optional[Exception]], None], 'Output']:
from .. import Output # pylint: disable=import-outside-toplevel
value_future: asyncio.Future[Any] = asyncio.Future()
known_future: asyncio.Future[bool] = asyncio.Future()
secret_future: asyncio.Future[bool] = asyncio.Future()
def resolve(value: Any, known: bool, secret: bool, exn: Optional[Exception]):
if exn is not None:
value_future.set_exception(exn)
known_future.set_exception(exn)
secret_future.set_exception(exn)
else:
value_future.set_result(value)
known_future.set_result(known)
secret_future.set_result(secret)
return resolve, Output({res}, value_future, known_future, secret_future)
def get_resource(res: 'Resource',
props: 'Inputs',
custom: bool,
urn: str,
typ: Optional[type] = None) -> None:
log.debug(f"getting resource: urn={urn}")
# If we have type information, we'll use its and the resource's type/name metadata
# for name translations rather than using the resource's translation methods.
transform_using_type_metadata = typ is not None
# Extract the resource type from the URN.
urn_parts = urn.split("::")
qualified_type = urn_parts[2]
ty = qualified_type.split("$")[-1]
# Initialize the URN property on the resource.
(resolve_urn, res.__dict__["urn"]) = resource_output(res)
# If this is a custom resource, initialize its ID property.
resolve_id: Optional[Callable[[Any, bool, bool, Optional[Exception]], None]] = None
if custom:
(resolve_id, res.__dict__["id"]) = resource_output(res)
# Like the other resource functions, "transfer" all input properties onto unresolved futures on res.
resolvers = rpc.transfer_properties(res, props)
async def do_get():
try:
resolver = await prepare_resource(res, ty, custom, False, props, None, typ)
monitor = settings.get_monitor()
inputs = await rpc.serialize_properties({"urn": urn}, {})
req = provider_pb2.InvokeRequest(tok="pulumi:pulumi:getResource", args=inputs, provider="", version="")
def do_invoke():
try:
return monitor.Invoke(req)
except grpc.RpcError as exn:
handle_grpc_error(exn)
return None
resp = await asyncio.get_event_loop().run_in_executor(None, do_invoke)
# If the invoke failed, raise an error.
if resp.failures:
raise Exception(f"getResource failed: {resp.failures[0].reason} ({resp.failures[0].property})")
except Exception as exn:
log.debug(
f"exception when preparing or executing rpc: {traceback.format_exc()}")
rpc.resolve_outputs_due_to_exception(resolvers, exn)
resolve_urn(None, True, False, exn)
if resolve_id is not None:
resolve_id(None, True, False, exn)
raise
# Otherwise, grab the URN, ID, and output properties and resolve all of them.
resp = getattr(resp, 'return')
log.debug(f"getResource completed successfully: ty={ty}, urn={resp['urn']}")
resolve_urn(resp["urn"], True, False, None)
if resolve_id:
# The ID is known if (and only if) it is a non-empty string. If it's either None or an
# empty string, we should treat it as unknown. TFBridge in particular is known to send
# the empty string as an ID when doing a preview.
is_known = bool(resp["id"])
resolve_id(resp["id"], is_known, False, None)
rpc.resolve_outputs(res, resolver.serialized_props, resp["state"], {}, resolvers, transform_using_type_metadata)
asyncio.ensure_future(RPC_MANAGER.do_rpc("get resource", do_get)())
def _translate_ignore_changes(res: 'Resource',
typ: Optional[type],
ignore_changes: Optional[List[str]]) -> Optional[List[str]]:
if ignore_changes is not None:
if typ is not None:
# If `typ` is specified, use its type/name metadata for translation.
input_names = _types.input_type_py_to_pulumi_names(typ)
ignore_changes = list(map(lambda k: input_names.get(k) or k, ignore_changes))
elif res.translate_input_property is not None:
ignore_changes = list(map(res.translate_input_property, ignore_changes))
return ignore_changes
def _translate_additional_secret_outputs(res: 'Resource',
typ: Optional[type],
additional_secret_outputs: Optional[List[str]]) -> Optional[List[str]]:
if additional_secret_outputs is not None:
if typ is not None:
# If a `typ` is specified, we've opt-ed in to doing translations using type/name metadata rather
# than using the resource's tranlate_input_property. Use the resource's metadata to translate.
output_names = _types.resource_py_to_pulumi_names(type(res))
additional_secret_outputs = list(map(lambda k: output_names.get(k) or k, additional_secret_outputs))
elif res.translate_input_property is not None:
# Note that while `additional_secret_outputs` lists property names that are outputs, we
# call `translate_input_property` because it is the method that converts from the
# language projection name to the provider name, which is what we want.
additional_secret_outputs = list(map(res.translate_input_property, additional_secret_outputs))
return additional_secret_outputs
def read_resource(res: 'CustomResource',
ty: str,
name: str,
props: 'Inputs',
opts: 'ResourceOptions',
typ: Optional[type] = None) -> None:
if opts.id is None:
raise Exception(
"Cannot read resource whose options are lacking an ID value")
log.debug(f"reading resource: ty={ty}, name={name}, id={opts.id}")
monitor = settings.get_monitor()
# If we have type information, we'll use its and the resource's type/name metadata
# for name translations rather than using the resource's translation methods.
transform_using_type_metadata = typ is not None
# Prepare the resource, similar to a RegisterResource. Reads are deliberately similar to RegisterResource except
# that we are populating the Resource object with properties associated with an already-live resource.
#
# Same as below, we initialize the URN property on the resource, which will always be resolved.
(resolve_urn, res.__dict__["urn"]) = resource_output(res)
# Furthermore, since resources being Read must always be custom resources (enforced in the
# Resource constructor), we'll need to set up the ID field which will be populated at the end of
# the ReadResource call.
#
# Note that we technically already have the ID (opts.id), but it's more consistent with the rest
# of the model to resolve it asynchronously along with all of the other resources.
(resolve_id, res.__dict__["id"]) = resource_output(res)
# Like below, "transfer" all input properties onto unresolved futures on res.
resolvers = rpc.transfer_properties(res, props)
async def do_read():
try:
resolver = await prepare_resource(res, ty, True, False, props, opts, typ)
# Resolve the ID that we were given. Note that we are explicitly discarding the list of
# dependencies returned to us from "serialize_property" (the second argument). This is
# because a "read" resource does not actually have any dependencies at all in the cloud
# provider sense, because a read resource already exists. We do not need to track this
# dependency.
resolved_id = await rpc.serialize_property(opts.id, [])
log.debug(f"read prepared: ty={ty}, name={name}, id={opts.id}")
# These inputs will end up in the snapshot, so if there are any additional secret
# outputs, record them here.
additional_secret_outputs = _translate_additional_secret_outputs(res, typ, opts.additional_secret_outputs)
accept_resources = not (os.getenv("PULUMI_DISABLE_RESOURCE_REFERENCES", "").upper() in {"TRUE", "1"})
req = resource_pb2.ReadResourceRequest(
type=ty,
name=name,
id=resolved_id,
parent=resolver.parent_urn,
provider=resolver.provider_ref,
properties=resolver.serialized_props,
dependencies=resolver.dependencies,
version=opts.version or "",
acceptSecrets=True,
acceptResources=accept_resources,
additionalSecretOutputs=additional_secret_outputs,
)
from ..resource import create_urn # pylint: disable=import-outside-toplevel
mock_urn = await create_urn(name, ty, resolver.parent_urn).future()
def do_rpc_call():
if monitor is None:
# If no monitor is available, we'll need to fake up a response, for testing.
return RegisterResponse(mock_urn, None, resolver.serialized_props, None)
# If there is a monitor available, make the true RPC request to the engine.
try:
return monitor.ReadResource(req)
except grpc.RpcError as exn:
handle_grpc_error(exn)
return None
resp = await asyncio.get_event_loop().run_in_executor(None, do_rpc_call)
except Exception as exn:
log.debug(
f"exception when preparing or executing rpc: {traceback.format_exc()}")
rpc.resolve_outputs_due_to_exception(resolvers, exn)
resolve_urn(None, True, False, exn)
resolve_id(None, True, False, exn)
raise
log.debug(f"resource read successful: ty={ty}, urn={resp.urn}")
resolve_urn(resp.urn, True, False, None)
resolve_id(resolved_id, True, False, None) # Read IDs are always known.
rpc.resolve_outputs(res, resolver.serialized_props, resp.properties, {}, resolvers,
transform_using_type_metadata)
asyncio.ensure_future(RPC_MANAGER.do_rpc("read resource", do_read)())
def register_resource(res: 'Resource',
ty: str,
name: str,
custom: bool,
remote: bool,
new_dependency: Callable[[str], 'Resource'],
props: 'Inputs',
opts: Optional['ResourceOptions'],
typ: Optional[type] = None) -> None:
"""
Registers a new resource object with a given type t and name. It returns the
auto-generated URN and the ID that will resolve after the deployment has completed. All
properties will be initialized to property objects that the registration operation will resolve
at the right time (or remain unresolved for deployments).
"""
log.debug(f"registering resource: ty={ty}, name={name}, custom={custom}, remote={remote}")
monitor = settings.get_monitor()
# If we have type information, we'll use its and the resource's type/name metadata
# for name translations rather than using the resource's translation methods.
transform_using_type_metadata = typ is not None
# Prepare the resource.
# Simply initialize the URN property and get prepared to resolve it later on.
# Note: a resource urn will always get a value, and thus the output property
# for it can always run .apply calls.
(resolve_urn, res.__dict__["urn"]) = resource_output(res)
# If a custom resource, make room for the ID property.
resolve_id: Optional[Callable[[Any, bool, bool, Optional[Exception]], None]] = None
if custom:
(resolve_id, res.__dict__["id"]) = resource_output(res)
# Now "transfer" all input properties into unresolved futures on res. This way,
# this resource will look like it has all its output properties to anyone it is
# passed to. However, those futures won't actually resolve until the RPC returns
resolvers = rpc.transfer_properties(res, props)
async def do_register():
try:
resolver = await prepare_resource(res, ty, custom, remote, props, opts, typ)
log.debug(f"resource registration prepared: ty={ty}, name={name}")
property_dependencies = {}
for key, deps in resolver.property_dependencies.items():
property_dependencies[key] = resource_pb2.RegisterResourceRequest.PropertyDependencies(
urns=deps)
ignore_changes = _translate_ignore_changes(res, typ, opts.ignore_changes)
additional_secret_outputs = _translate_additional_secret_outputs(res, typ, opts.additional_secret_outputs)
# Translate the CustomTimeouts object.
custom_timeouts = None
if opts.custom_timeouts is not None:
custom_timeouts = resource_pb2.RegisterResourceRequest.CustomTimeouts()
# It could be an actual CustomTimeouts object.
if known_types.is_custom_timeouts(opts.custom_timeouts):
if opts.custom_timeouts.create is not None:
custom_timeouts.create = opts.custom_timeouts.create
if opts.custom_timeouts.update is not None:
custom_timeouts.update = opts.custom_timeouts.update
if opts.custom_timeouts.delete is not None:
custom_timeouts.delete = opts.custom_timeouts.delete
# Or, it could be a workaround passing in a dict.
elif isinstance(opts.custom_timeouts, dict):
if 'create' in opts.custom_timeouts:
custom_timeouts.create = opts.custom_timeouts['create']
if 'update' in opts.custom_timeouts:
custom_timeouts.update = opts.custom_timeouts['update']
if 'delete' in opts.custom_timeouts:
custom_timeouts.delete = opts.custom_timeouts['delete']
else:
raise Exception("Expected custom_timeouts to be a CustomTimeouts object")
accept_resources = not (os.getenv("PULUMI_DISABLE_RESOURCE_REFERENCES", "").upper() in {"TRUE", "1"})
req = resource_pb2.RegisterResourceRequest(
type=ty,
name=name,
parent=resolver.parent_urn,
custom=custom,
object=resolver.serialized_props,
protect=opts.protect,
provider=resolver.provider_ref,
providers=resolver.provider_refs,
dependencies=resolver.dependencies,
propertyDependencies=property_dependencies,
deleteBeforeReplace=opts.delete_before_replace,
deleteBeforeReplaceDefined=opts.delete_before_replace is not None,
ignoreChanges=ignore_changes,
version=opts.version or "",
acceptSecrets=True,
acceptResources=accept_resources,
additionalSecretOutputs=additional_secret_outputs,
importId=opts.import_,
customTimeouts=custom_timeouts,
aliases=resolver.aliases,
supportsPartialValues=True,
remote=remote,
)
from ..resource import create_urn # pylint: disable=import-outside-toplevel
mock_urn = await create_urn(name, ty, resolver.parent_urn).future()
def do_rpc_call():
if monitor is None:
# If no monitor is available, we'll need to fake up a response, for testing.
return RegisterResponse(mock_urn, None, resolver.serialized_props, None)
# If there is a monitor available, make the true RPC request to the engine.
try:
return monitor.RegisterResource(req)
except grpc.RpcError as exn:
handle_grpc_error(exn)
return None
resp = await asyncio.get_event_loop().run_in_executor(None, do_rpc_call)
except Exception as exn:
log.debug(
f"exception when preparing or executing rpc: {traceback.format_exc()}")
rpc.resolve_outputs_due_to_exception(resolvers, exn)
resolve_urn(None, True, False, exn)
if resolve_id is not None:
resolve_id(None, True, False, exn)
raise
if resp is None:
return
log.debug(f"resource registration successful: ty={ty}, urn={resp.urn}")
resolve_urn(resp.urn, True, False, None)
if resolve_id is not None:
# The ID is known if (and only if) it is a non-empty string. If it's either None or an
# empty string, we should treat it as unknown. TFBridge in particular is known to send
# the empty string as an ID when doing a preview.
is_known = bool(resp.id)
resolve_id(resp.id, is_known, False, None)
deps = {}
rpc_deps = resp.propertyDependencies
if rpc_deps:
for k, v in rpc_deps.items():
urns = list(v.urns)
deps[k] = set(map(new_dependency, urns))
rpc.resolve_outputs(res, resolver.serialized_props, resp.object, deps, resolvers, transform_using_type_metadata)
asyncio.ensure_future(RPC_MANAGER.do_rpc(
"register resource", do_register)())
def register_resource_outputs(res: 'Resource', outputs: 'Union[Inputs, Output[Inputs]]'):
async def do_register_resource_outputs():
urn = await res.urn.future()
serialized_props = await rpc.serialize_properties(outputs, {})
log.debug(
f"register resource outputs prepared: urn={urn}, props={serialized_props}")
monitor = settings.get_monitor()
req = resource_pb2.RegisterResourceOutputsRequest(
urn=urn, outputs=serialized_props)
def do_rpc_call():
if monitor is None:
# If there's no engine attached, simply ignore it.
return None
try:
return monitor.RegisterResourceOutputs(req)
except grpc.RpcError as exn:
handle_grpc_error(exn)
return None
await asyncio.get_event_loop().run_in_executor(None, do_rpc_call)
log.debug(
f"resource registration successful: urn={urn}, props={serialized_props}")
asyncio.ensure_future(RPC_MANAGER.do_rpc(
"register resource outputs", do_register_resource_outputs)())
class PropertyDependencies:
urns: List[str]
def __init__(self, urns: List[str]):
self.urns = urns
class RegisterResponse:
urn: str
id: Optional[str]
object: struct_pb2.Struct
propertyDependencies: Optional[Dict[str, PropertyDependencies]]
# pylint: disable=redefined-builtin
def __init__(self,
urn: str,
id: Optional[str],
object: struct_pb2.Struct,
propertyDependencies: Optional[Dict[str, PropertyDependencies]]):
self.urn = urn
self.id = id
self.object = object
self.propertyDependencies = propertyDependencies
# Merge all providers opts (opts.provider and both list and dict forms of opts.providers) into a single dict.
def convert_providers(
provider: Optional['ProviderResource'],
providers: Optional[Union[Mapping[str, 'ProviderResource'],
List['ProviderResource']]]) -> Mapping[str, 'ProviderResource']:
if provider is not None:
return convert_providers(None, [provider])
if providers is None:
return {}
if not isinstance(providers, list):
return providers
result = {}
for p in providers:
result[p.package] = p
return result
|
# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the MIT license.
# See the LICENSE file in the project root for more information.
from contextlib import contextmanager
from dataclasses import dataclass
from os import environ
from pathlib import Path
from random import randint
from signal import SIGINT
from shutil import which
from subprocess import PIPE, Popen
from sys import executable as py
from tempfile import TemporaryDirectory
from time import sleep, time
from typing import Iterable, Iterator, Mapping, Optional, Sequence, Tuple
from psutil import process_iter
from ..analysis.core_analysis import get_process_info, process_predicate_from_id
from ..analysis.clr import Clr
from ..analysis.types import ProcessInfo
from ..commonlib.bench_file import (
Benchmark,
BenchOptions,
CollectKind,
GCPerfSimResult,
LogOptions,
SingleTestCombination,
TestConfigCombined,
TestConfigContainer,
TestPaths,
TestRunStatus,
)
from ..commonlib.get_built import Built, CoreclrPaths
from ..commonlib.collection_util import (
combine_mappings,
empty_mapping,
empty_sequence,
find,
is_empty,
)
from ..commonlib.config import GC_PATH, EXEC_ENV_PATH, PERFVIEW_PATH
from ..commonlib.option import map_option, non_null, optional_to_iter, option_or, option_or_3
from ..commonlib.parse_and_serialize import parse_yaml
from ..commonlib.type_utils import with_slots
from ..commonlib.util import (
args_with_cmd,
assert_admin,
check_no_processes,
decode_stdout,
ensure_empty_dir,
ExecArgs,
exec_and_expect_output,
exec_and_get_output,
exec_and_get_result,
exec_cmd,
exec_start,
ExecutableNotFoundException,
gb_to_mb,
give_user_permissions,
hex_no_0x,
is_admin,
kill_process,
mb_to_bytes,
os_is_windows,
seconds_to_usec,
unlink_if_exists,
USECS_PER_SECOND,
wait_on_process_with_timeout,
)
_TEST_MIN_SECONDS_DEFAULT = 10.0
_TEST_MAX_SECONDS_DEFAULT = 90.0
@with_slots
@dataclass(frozen=True)
class SingleTest:
"""
Unlike SingleTestCombination, contains processed information for actually executing the test.
"""
test: SingleTestCombination
coreclr: Optional[CoreclrPaths]
test_exe: Path
options: BenchOptions
default_env: Mapping[str, str]
@property
def coreclr_name(self) -> str:
return self.test.coreclr_name
@property
def benchmark_name(self) -> str:
return self.test.benchmark_name
@property
def benchmark(self) -> Benchmark:
return self.test.benchmark.benchmark
@property
def config_name(self) -> str:
return self.test.config_name
@property
def config(self) -> TestConfigCombined:
return TestConfigCombined(self.test.config.config)
# Writes to out_path.etl, out_path.yaml, and out_path as a directory
def run_single_test(built: Built, t: SingleTest, out: TestPaths) -> TestRunStatus:
check_no_test_processes()
partial_test_status = _do_run_single_test(built, t, out)
gcperfsim_result = (
_parse_gcperfsim_result(partial_test_status.stdout)
if t.benchmark.executable is None
or any(t.benchmark.executable.endswith(x) for x in ("GCPerfSim", "GCPerfSim.exe"))
else None
)
test_status = TestRunStatus(
test=t.test,
success=partial_test_status.success,
process_id=partial_test_status.process_id,
seconds_taken=partial_test_status.seconds_taken,
trace_file_name=partial_test_status.trace_file_name,
stdout=partial_test_status.stdout,
gcperfsim_result=gcperfsim_result,
)
out.write_test_status(test_status)
if not os_is_windows() and is_admin():
give_user_permissions(out.test_status_path)
if test_status.success:
print(f"Took {test_status.seconds_taken} seconds")
min_seconds = option_or_3(
t.benchmark.min_seconds, t.options.default_min_seconds, _TEST_MIN_SECONDS_DEFAULT
)
if test_status.seconds_taken < min_seconds:
desc = f"coreclr={t.coreclr_name} config={t.config_name} benchmark={t.benchmark_name}"
raise Exception(
f"{desc} took {test_status.seconds_taken} seconds, minimum is {min_seconds}"
"(you could change the benchmark's min_seconds or options.default_min_seconds)"
)
else:
print("Test failed, continuing...")
sleep(1) # Give process time to close
check_no_test_processes()
return test_status
def _parse_gcperfsim_result(stdout: str) -> GCPerfSimResult:
# Everything before the marker is ignored
marker = "=== STATS ==="
try:
idx = stdout.index(marker)
except ValueError:
print(f"STDOUT: '{stdout}'")
raise Exception(f"GCPerfSim stdout does not include '{marker}'") from None
yaml = stdout[idx + len(marker) :]
return parse_yaml(GCPerfSimResult, yaml)
@with_slots
@dataclass(frozen=True)
class _PartialTestRunStatus:
"""Compared to TestRunStatus, this is missing perfview_result, we parse that at the end."""
success: bool
process_id: int
seconds_taken: float
trace_file_name: Optional[str]
stdout: str
def _do_run_single_test(built: Built, t: SingleTest, out: TestPaths) -> _PartialTestRunStatus:
if t.options.collect == CollectKind.none:
return _run_single_test_no_collect(built, t, out)
elif t.options.always_use_dotnet_trace or not os_is_windows():
return _run_single_test_dotnet_trace(built, t, out)
else:
return _run_single_test_windows_perfview(built, t, out)
# Use this instead of TemporaryDirectory if you want to analyze the output
@contextmanager
def NonTemporaryDirectory(name: str) -> Iterator[Path]:
yield GC_PATH / "temp" / (name + str(randint(0, 99)))
def run_single_test_temporary(clr: Clr, built: Built, t: SingleTest) -> ProcessInfo:
with TemporaryDirectory(t.coreclr_name) as td:
temp = Path(td)
paths = TestPaths(temp / "temp")
test_status = run_single_test(built, t, paths)
# TODO: configurable process_predicate
trace_file = non_null(paths.trace_file_path(test_status))
return get_process_info(
clr, trace_file, str(trace_file), process_predicate_from_id(test_status.process_id)
)
def check_env() -> Mapping[str, str]:
e = environ
bad_environment_variables = [
k
for k in e.keys()
if any(k.lower().startswith(start) for start in ("complus", "core_root"))
]
if not is_empty(bad_environment_variables):
start = f"Environment variables should not be set: {", ".join(bad_environment_variables)}"
msg = (
start if os_is_windows() else f'{start}\nTry running: unset "${{!COMPlus@}}" CORE_ROOT'
)
raise Exception(msg)
return e
TEST_PROCESS_NAMES: Sequence[str] = ("corerun", "dotnet", "make_memory_load", "perfview")
def check_no_test_processes() -> None:
check_no_processes(TEST_PROCESS_NAMES)
def kill_test_processes() -> None:
for proc in process_iter():
if any(name in proc.name().lower() for name in TEST_PROCESS_NAMES):
print(f"Killing {proc.name()}")
for _ in range(10):
proc.kill()
# Sometimes it's still alive after being killed ...
sleep(1)
if not proc.is_running():
break
assert not proc.is_running()
check_no_test_processes()
_PERFVIEW_ALWAYS_ARGS: Sequence[str] = (
"-NoV2Rundown",
"-NoNGENRundown",
"-NoRundown",
"-AcceptEULA",
"-NoGUI",
"-Merge:true",
"-SessionName:CoreGCBench", # TODO:necessary?
"-zip:false",
)
def get_perfview_run_cmd(
built: Built,
t: SingleTest,
log_file: Path,
trace_file: Path,
perfview: bool = True,
ignore_container: bool = False,
) -> Sequence[str]:
test_args = _get_windows_test_cmd(built, t, ignore_container).command
if perfview:
# Since this is a perf test, we don't want to waste time logging the output.
# We will log errors though.
return (
str(PERFVIEW_PATH),
*_get_perfview_collect_or_run_common_args(t, log_file, trace_file),
"run",
*test_args,
)
else:
return test_args
@with_slots
@dataclass(frozen=True)
class CommandAndIsRunInJob:
command: Sequence[str]
is_run_in_job: bool
def _get_windows_test_cmd(
built: Built, t: SingleTest, ignore_container: bool
) -> CommandAndIsRunInJob:
test_args: Sequence[str] = _benchmark_command(t)
if (t.config.container is not None or t.config.affinitize) and not ignore_container:
c = t.config.container
assert c is None or c.image_name is None, "TODO"
return CommandAndIsRunInJob(
command=(
str(built.win.run_in_job_exe),
*(
empty_sequence()
if c is None or c.memory_mb is None
else ["--memory-mb", str(c.memory_mb)]
),
*(empty_sequence() if not t.config.affinitize else ["--affinitize"]),
*(
empty_sequence()
if c is None or c.cpu_rate_hard_cap is None
else ["--cpu-rate-hard-cap", str(c.cpu_rate_hard_cap)]
),
"--",
*test_args,
),
is_run_in_job=True,
)
else:
return CommandAndIsRunInJob(command=test_args, is_run_in_job=False)
def _get_perfview_start_or_stop_cmd(
t: SingleTest, log_file: Path, trace_file: Path, is_start: bool
) -> Sequence[str]:
return (
str(PERFVIEW_PATH),
"start" if is_start else "stop",
*_get_perfview_collect_or_run_common_args(t, log_file, trace_file),
)
_DEFAULT_MAX_TRACE_SIZE_GB = 1
def _get_perfview_collect_or_run_common_args(
t: SingleTest, log_file: Path, trace_file: Path
) -> Sequence[str]:
collect_args: Sequence[str] = {
CollectKind.gc: ["-GCCollectOnly"],
CollectKind.verbose: ["-GCCollectOnly", "-ClrEventLevel:Verbose"],
# Need default kernel events to get the process name
CollectKind.cpu_samples: [
"-OnlyProviders:ClrPrivate:1:5,Clr:1:5",
"-ClrEvents:GC+Stack",
"-ClrEventLevel:Verbose",
"-KernelEvents:Default",
],
CollectKind.cswitch: [
# Use verbose events (4 instead of 5)
"-OnlyProviders:ClrPrivate:1:5,Clr:1:5",
"-ClrEvents:GC+Stack",
f"-KernelEvents:Default,ContextSwitch",
],
}[t.options.get_collect]
max_trace_size_mb = round(
gb_to_mb(option_or(t.options.max_trace_size_gb, _DEFAULT_MAX_TRACE_SIZE_GB))
)
return (
*_PERFVIEW_ALWAYS_ARGS,
*collect_args,
# This option prevents perfview from opening a console
# and requiring the user to press enter
f"-LogFile:{log_file}",
f"-CircularMB:{max_trace_size_mb}",
f"-BufferSizeMB:{max_trace_size_mb}",
f"-DataFile:{trace_file}",
)
def log_env(log: Optional[LogOptions], path: Path) -> Mapping[str, str]:
if log is None:
return empty_mapping()
else:
return {
"COMPlus_GCLogEnabled": "1",
"COMPlus_GCLogFile": str(path),
"COMPlus_GCLogFileSize": hex_no_0x(option_or(log.file_size_mb, 0x30)),
"COMPlus_SOEnableDefaultRWValidation": "0", # TODO: is this needed?
# This env var no longer exists, must recompile to change level
# "COMPlus_GCprnLvl": hex_no_0x(log.level),
}
def _run_single_test_windows_perfview(
built: Built, t: SingleTest, out: TestPaths
) -> _PartialTestRunStatus:
assert_admin()
ensure_empty_dir(out.out_path_base)
# Start with the memory load
mem_load = t.config.memory_load
mem_load_process = None
if mem_load is not None:
print("setting up memory load...")
mem_load_args: Sequence[str] = (
str(built.win.make_memory_load),
"-percent",
str(mem_load.percent),
*optional_to_iter("-noReadjust" if mem_load.no_readjust else None),
)
mem_load_process = Popen(args=mem_load_args, stderr=PIPE)
assert mem_load_process.stderr is not None
# Wait on it to start up
line = decode_stdout(mem_load_process.stderr.readline())
assert (
line == "make_memory_load finished starting up"
), f"Unexpected make_memory_load output {line}"
print("done")
log_file = out.add_ext("perfview-log.txt")
trace_file = out.add_ext("etl")
timeout_seconds = _get_timeout(t)
exec_and_expect_output(
ExecArgs(_get_perfview_start_or_stop_cmd(t, log_file, trace_file, is_start=True)),
expected_output="",
err="PerfView start failed",
)
start_time_seconds = time()
test_cmd = _get_windows_test_cmd(built, t, ignore_container=False)
run_process = exec_start(_get_exec_args(test_cmd.command, t, out), pipe_stdout=True)
try:
run_result = wait_on_process_with_timeout(
run_process, start_time_seconds=start_time_seconds, timeout_seconds=timeout_seconds
)
finally:
# Stop PerfView even if the test failed
exec_and_expect_output(
ExecArgs(_get_perfview_start_or_stop_cmd(t, log_file, trace_file, is_start=False)),
expected_output="",
err="PerfView stop failed",
)
if run_result.time_taken is None:
kill_test_processes()
elif mem_load_process is not None:
# Releasing all the memory can take a while, so give it plenty of time
kill_process(mem_load_process, time_allowed_seconds=60)
# WIll have a return code of 2 because we interrupted it.
assert mem_load_process.returncode == 2
_rename_gcperfsim_out(out)
success = (
run_process.returncode == 0
and run_result.time_taken is not None
and not _perfview_has_warnings(log_file.read_text(encoding="utf-8"))
)
# If running in job, run_process.pid is run-in-job's PID, not the test process' PID.
# So it prints 'PID: 123' before exiting.
stdout, process_id = (
_strip_pid(run_result.stdout)
if test_cmd.is_run_in_job
else (run_result.stdout, run_process.pid)
)
return _PartialTestRunStatus(
success=success,
process_id=process_id,
seconds_taken=timeout_seconds
if run_result.time_taken is None
else run_result.time_taken.total_seconds(),
trace_file_name=trace_file.name,
stdout=stdout,
)
def _strip_pid(stdout: str) -> Tuple[str, int]:
pid_str = "PID: "
idx = stdout.rindex(pid_str)
return stdout[:idx].rstrip(), int(stdout[idx + len(pid_str) :])
def _rename_only_file_in_dir(dir_path: Path, expected_suffix: str, target: Path) -> None:
files_in_dir = tuple(dir_path.iterdir())
if not is_empty(files_in_dir):
assert len(files_in_dir) == 1
file = files_in_dir[0]
# assert file.name.endswith(expected_suffix)
if file.name.endswith(expected_suffix):
file.rename(target)
else:
file.unlink()
dir_path.rmdir()
_ALLOWED_WARNINGS: Sequence[str] = (
# Some coreclr benchmarks return 100 for some reason
"warning: command exited with non-success error code 0x64",
"warning: newly-allocated dummy ended up in gen 1",
"warning no _nt_symbol_path set ...",
)
for w in _ALLOWED_WARNINGS:
assert w.islower()
def _perfview_has_warnings(text: str) -> bool:
text_lower = text.lower()
if any(s in text_lower for s in ("process is terminating", "unhandled exception")):
return True
def is_allowed_warning(idx: int) -> bool:
rest = text_lower[idx:]
return any(rest.startswith(w) for w in _ALLOWED_WARNINGS)
warning_index = find(
lambda idx: not is_allowed_warning(idx), _substring_locations(text_lower, "warning")
)
if warning_index is not None:
print("Failing due to warning: ", text[warning_index:].split("\n")[0])
return True
else:
return False
def _get_timeout(t: SingleTest) -> float:
return option_or_3(
t.benchmark.max_seconds, t.options.default_max_seconds, _TEST_MAX_SECONDS_DEFAULT
)
def _run_single_test_no_collect(
_built: Built, t: SingleTest, out: TestPaths
) -> _PartialTestRunStatus:
if t.options.log is not None:
raise Exception("TODO")
if t.config.memory_load is not None:
# The script only works on windows right now
raise Exception("TODO")
out.out_path_base.mkdir() # GCPerfSim will write here
test_process_args: Sequence[str] = _benchmark_command(t)
args = _get_exec_args(test_process_args, t, out)
container = t.config.container
timeout_seconds = _get_timeout(t)
if container is not None or t.config.affinitize:
raise Exception("TODO")
start_time_seconds = time()
process = exec_start(args, pipe_stdout=True)
wait_result = wait_on_process_with_timeout(process, start_time_seconds, timeout_seconds)
gcperfsim_out = _rename_gcperfsim_out(out)
if container is not None:
give_user_permissions(gcperfsim_out)
# TODO: handle failure
return _PartialTestRunStatus(
success=wait_result.time_taken is not None,
process_id=process.pid,
seconds_taken=timeout_seconds
if wait_result.time_taken is None
else wait_result.time_taken.total_seconds(),
trace_file_name=None,
stdout=wait_result.stdout,
)
def _run_single_test_dotnet_trace(
_built: Built, t: SingleTest, out: TestPaths
) -> _PartialTestRunStatus:
if t.options.log is not None:
raise Exception("TODO")
if t.config.affinitize:
raise Exception("TODO")
if t.config.memory_load is not None:
# The script only works on windows right now
raise Exception("TODO")
test_process_args: Sequence[str] = _benchmark_command(t)
trace_out_dir = out.out_path_base.parent / "trace"
trace_out_dir.mkdir()
out.out_path_base.mkdir() # GCPerfSim will write here
args = _get_exec_args(test_process_args, t, out)
container = t.config.container
start_time_seconds = time()
if container is not None:
process_to_wait_on, pid_to_trace = _launch_process_in_cgroup(container, args)
else:
process_to_wait_on = exec_start(args, pipe_stdout=True)
pid_to_trace = process_to_wait_on.pid
trace_file = out.add_ext("nettrace")
dotnet_trace = exec_start(
_get_dotnet_trace_args(t.options, pid_to_trace, trace_file), pipe_stdout=False
)
timeout_seconds = _get_timeout(t)
wait_result = wait_on_process_with_timeout(
process_to_wait_on, start_time_seconds=start_time_seconds, timeout_seconds=timeout_seconds
)
# Shouldn't take more than 10 seconds to shut down
trace_stdout, trace_stderr = dotnet_trace.communicate("\n", timeout=10)
assert trace_stdout is None and trace_stderr is None
if container is not None:
_delete_cgroup()
# WARN: If the test is too short and no events fire, the output file will not be written to.
_rename_only_file_in_dir(trace_out_dir, expected_suffix=".nettrace", target=trace_file)
gcperfsim_out = _rename_gcperfsim_out(out)
if container is not None:
for file in (trace_file, gcperfsim_out):
give_user_permissions(file)
# TODO: handle failure
return _PartialTestRunStatus(
success=wait_result.time_taken is not None,
process_id=pid_to_trace,
seconds_taken=timeout_seconds
if wait_result.time_taken is None
else wait_result.time_taken.total_seconds(),
trace_file_name=trace_file.name,
stdout=wait_result.stdout,
)
def _get_dotnet_trace_path(options: BenchOptions) -> Path:
if options.dotnet_trace_path is not None:
return Path(options.dotnet_trace_path)
else:
res = which("dotnet-trace")
if res is None:
raise Exception("Can't find 'dotnet-trace' installed.")
else:
return Path(res)
def _get_dotnet_trace_args(options: BenchOptions, pid_to_trace: int, trace_file: Path) -> ExecArgs:
# if collect == CollectKind.gc:
# # 1 means GC, 4 means informational
# providers = "Microsoft-Windows-DotNETRuntime:1:4"
# elif collect == CollectKind.verbose:
# # 5 means verbose
# providers = "Microsoft-Windows-DotNETRuntime:1:5"
# else:
# raise Exception(f"TODO: handle collect kind {collect} on linux")
profile = {
CollectKind.gc: "gc-collect",
CollectKind.verbose: "gc-verbose",
CollectKind.cpu_samples: "cpu-sampling",
}[options.get_collect]
args: Sequence[str] = (
str(_get_dotnet_trace_path(options)),
"collect",
"--process-id",
str(pid_to_trace),
"--output",
str(trace_file),
*(
empty_sequence()
if options.dotnet_trace_buffersize_mb is None
else ["--buffersize", str(options.dotnet_trace_buffersize_mb)]
),
# TODO: use args.collect option to determine providers
# "--providers",
# 1 = GC, 4 = informational (5 = verbose)
# providers,
"--profile",
profile,
)
env: Mapping[str, str] = empty_mapping() if options.dotnet_path is None else {
"DOTNET_ROOT": str(options.dotnet_path.parent)
}
return ExecArgs(args, env=env)
_WRITE_PID_AND_EXEC_PATH = EXEC_ENV_PATH / "write_pid_and_exec.py"
_PID_FILE_PATH = EXEC_ENV_PATH / "__pid.txt"
_ALL_CGROUP_CATEGORIES: Sequence[str] = ("memory", "cpu")
_CGROUP_NAME = "gc-test-cgroup"
def _get_cgroup_categories_and_name(container: TestConfigContainer) -> str:
categories: Sequence[str] = (
(
*optional_to_iter(None if container.memory_mb is None else "memory"),
*optional_to_iter(None if container.cpu_rate_hard_cap is None else "cpu"),
)
)
assert all(c in _ALL_CGROUP_CATEGORIES for c in categories)
return f"{",".join(categories)}:{_CGROUP_NAME}"
def _create_cgroup(container: TestConfigContainer) -> None:
memory_mb = container.memory_mb
cpu_cap = container.cpu_rate_hard_cap
assert memory_mb is not None or cpu_cap is not None
if _cgroup_exists():
# cgroup_exists() may be a false positive, so allow failure
_delete_cgroup()
assert not _cgroup_exists()
exec_cmd(ExecArgs(("cgcreate", "-g", _get_cgroup_categories_and_name(container))))
if memory_mb is not None:
exec_cmd(
ExecArgs(
("cgset", "-r", f"memory.limit_in_bytes={mb_to_bytes(memory_mb)}", _CGROUP_NAME)
)
)
if cpu_cap is not None:
quota = round(seconds_to_usec(cpu_cap))
exec_cmd(
ExecArgs(
(
"cgset",
"-r",
f"cpu.cfs_period_us={USECS_PER_SECOND}",
f"cpu.cfs_quota_us={quota}",
_CGROUP_NAME,
)
)
)
def _ls_cgroup() -> str:
try:
return exec_and_get_output(ExecArgs(("lscgroup",), quiet_print=True))
except ExecutableNotFoundException:
raise Exception("cgroup-tools is not installed.")
# WARN: this sometimes has a false positive
def _cgroup_exists() -> bool:
return _CGROUP_NAME in _ls_cgroup()
def _delete_cgroup() -> None:
assert _cgroup_exists()
result = exec_and_get_result(
ExecArgs(("cgdelete", "-g", f"{",".join(_ALL_CGROUP_CATEGORIES)}:{_CGROUP_NAME}"))
)
assert result.exit_code
if result.exit_code == 96:
# Sometimes 'lscgroup' tells us the group exists, but then it doesn't. Just allow this.
assert (
result.stderr
== f"cgdelete: cannot remove group '{_CGROUP_NAME}': No such file or directory"
)
assert result.stdout == ""
else:
assert result.exit_code == 0 and result.stdout == "" and result.stderr == ""
assert not _cgroup_exists()
# Returns: The 'cgexec' process to wait on, and the PID of the *inner* process.
def _launch_process_in_cgroup(
container: TestConfigContainer, args: ExecArgs
) -> Tuple["Popen[str]", int]:
assert_admin()
_create_cgroup(container)
unlink_if_exists(_PID_FILE_PATH)
# TODO: Would be nice to have a better way to get the PID of the inner process.
cgexec_args = args_with_cmd(
args,
(
"cgexec",
"-g",
_get_cgroup_categories_and_name(container),
py,
str(_WRITE_PID_AND_EXEC_PATH),
*args.cmd,
),
)
cgexec_process = exec_start(cgexec_args, pipe_stdout=True)
# TODO: lower timeout_seconds
pid = int(
_read_file_when_it_exists(_PID_FILE_PATH, timeout_seconds=0.5, time_between_tries=0.1)
)
_PID_FILE_PATH.unlink()
return cgexec_process, pid
def _read_file_when_it_exists(path: Path, timeout_seconds: float, time_between_tries: float) -> str:
start = time()
while True:
try:
return path.read_text(encoding="utf-8")
except FileNotFoundError:
sleep(time_between_tries)
time_taken = time() - start
if time_taken > timeout_seconds:
raise Exception(f"{path} still doesn't exist after {timeout_seconds} seconds")
def _rename_gcperfsim_out(out: TestPaths) -> Path:
# Move the output file to avoid nested directoriess
target = out.add_ext("output.txt")
_rename_only_file_in_dir(out.out_path_base, expected_suffix="-output.txt", target=target)
return target
def _get_exec_args(cmd: Sequence[str], t: SingleTest, out: TestPaths) -> ExecArgs:
env = combine_mappings(
t.default_env,
t.config.with_coreclr(t.coreclr_name).env(map_option(t.coreclr, lambda c: c.core_root)),
log_env(t.options.log, out.out_path_base),
)
return ExecArgs(
cmd,
env=env,
# GCPerfSim will write a file `{pid}-output.txt` inside this directory
cwd=out.out_path_base,
)
# TODO: This isn't working yet. Uses lttng instead of eventpipe
def _run_single_test_linux_perfcollect(t: SingleTest, out: TestPaths) -> TestRunStatus:
# TODO: Could launch sudo just for the part it needs?
# TODO: running in sudo causes output files to only be readable by super user...
# A future perfcollect may fix this.
assert_admin()
ensure_empty_dir(out.out_path_base)
cwd = non_null(t.coreclr).corerun.parent # TODO: handle self-contained executables
env = combine_mappings(
t.config.with_coreclr(t.coreclr_name).env(map_option(t.coreclr, lambda c: c.core_root)),
{"COMPlus_PerfMapEnabled": "1", "COMPlus_EnableEventLog": "1"},
)
cmd: Sequence[str] = _benchmark_command(t)
print(f"cd {cwd}")
print(" ".join(cmd))
test_process = Popen(cmd, cwd=cwd, env=env)
test_process_pid = test_process.pid
# launch
print("PID", test_process_pid)
# Now launch that thing with the stuff
perfcollect_cmd = (
str(_PERFCOLLECT),
"collect",
str(out.out_path_base),
"-gccollectonly", # TODO: if I pass this, only event I get is EventID(200) ?
"-pid",
str(test_process_pid),
)
print(" ".join(perfcollect_cmd))
# TODO: not sure cwd needs to be set...
perfcollect_process = Popen(perfcollect_cmd, cwd=_PERFCOLLECT.parent)
print("waiting on test...")
test_process.wait()
assert test_process.returncode == 0
print("sending signal...")
perfcollect_process.send_signal(SIGINT)
print("waiting on perfcollect...")
perfcollect_process.wait()
assert perfcollect_process.returncode == 0
print("Closed")
raise Exception("TODO:finish")
_GC_KEYWORDS: Sequence[str] = (
"GC",
# Above isn't enough -- want GlobalHeapHistory ...
# "GCHandle",
# "GCHeapDump",
# "GCSampledObjectAllocationHigh",
# "GCHeapSurvivalAndMovement",
# "GCHeapCollect",
# "GCSampledObjectAllocationLow",
)
_GC_EVENTS_ID = 1
_GC_LEVEL = 5 # TODO: where is this documented?
_GC_PROVIDER: str = f"Microsoft-Windows-DotNETRuntime:0xFFFFFFFFFFFFFFFF:{_GC_LEVEL}"
# This is a bash script, no need to build
_PERFCOLLECT = Path("/home/anhans/work/corefx-tools/src/performance/perfcollect/perfcollect")
def _benchmark_command(t: SingleTest) -> Sequence[str]:
return (
*optional_to_iter(map_option(t.coreclr, lambda c: str(c.corerun))),
str(t.test_exe),
*t.benchmark.arguments_list,
)
# TODO:MOVE
def _substring_locations(s: str, substr: str) -> Iterable[int]:
idx = 0
while True:
idx = s.find(substr, idx)
if idx == -1:
break
yield idx
idx = idx + 1
| # Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the MIT license.
# See the LICENSE file in the project root for more information.
from contextlib import contextmanager
from dataclasses import dataclass
from os import environ
from pathlib import Path
from random import randint
from signal import SIGINT
from shutil import which
from subprocess import PIPE, Popen
from sys import executable as py
from tempfile import TemporaryDirectory
from time import sleep, time
from typing import Iterable, Iterator, Mapping, Optional, Sequence, Tuple
from psutil import process_iter
from ..analysis.core_analysis import get_process_info, process_predicate_from_id
from ..analysis.clr import Clr
from ..analysis.types import ProcessInfo
from ..commonlib.bench_file import (
Benchmark,
BenchOptions,
CollectKind,
GCPerfSimResult,
LogOptions,
SingleTestCombination,
TestConfigCombined,
TestConfigContainer,
TestPaths,
TestRunStatus,
)
from ..commonlib.get_built import Built, CoreclrPaths
from ..commonlib.collection_util import (
combine_mappings,
empty_mapping,
empty_sequence,
find,
is_empty,
)
from ..commonlib.config import GC_PATH, EXEC_ENV_PATH, PERFVIEW_PATH
from ..commonlib.option import map_option, non_null, optional_to_iter, option_or, option_or_3
from ..commonlib.parse_and_serialize import parse_yaml
from ..commonlib.type_utils import with_slots
from ..commonlib.util import (
args_with_cmd,
assert_admin,
check_no_processes,
decode_stdout,
ensure_empty_dir,
ExecArgs,
exec_and_expect_output,
exec_and_get_output,
exec_and_get_result,
exec_cmd,
exec_start,
ExecutableNotFoundException,
gb_to_mb,
give_user_permissions,
hex_no_0x,
is_admin,
kill_process,
mb_to_bytes,
os_is_windows,
seconds_to_usec,
unlink_if_exists,
USECS_PER_SECOND,
wait_on_process_with_timeout,
)
_TEST_MIN_SECONDS_DEFAULT = 10.0
_TEST_MAX_SECONDS_DEFAULT = 90.0
@with_slots
@dataclass(frozen=True)
class SingleTest:
"""
Unlike SingleTestCombination, contains processed information for actually executing the test.
"""
test: SingleTestCombination
coreclr: Optional[CoreclrPaths]
test_exe: Path
options: BenchOptions
default_env: Mapping[str, str]
@property
def coreclr_name(self) -> str:
return self.test.coreclr_name
@property
def benchmark_name(self) -> str:
return self.test.benchmark_name
@property
def benchmark(self) -> Benchmark:
return self.test.benchmark.benchmark
@property
def config_name(self) -> str:
return self.test.config_name
@property
def config(self) -> TestConfigCombined:
return TestConfigCombined(self.test.config.config)
# Writes to out_path.etl, out_path.yaml, and out_path as a directory
def run_single_test(built: Built, t: SingleTest, out: TestPaths) -> TestRunStatus:
check_no_test_processes()
partial_test_status = _do_run_single_test(built, t, out)
gcperfsim_result = (
_parse_gcperfsim_result(partial_test_status.stdout)
if t.benchmark.executable is None
or any(t.benchmark.executable.endswith(x) for x in ("GCPerfSim", "GCPerfSim.exe"))
else None
)
test_status = TestRunStatus(
test=t.test,
success=partial_test_status.success,
process_id=partial_test_status.process_id,
seconds_taken=partial_test_status.seconds_taken,
trace_file_name=partial_test_status.trace_file_name,
stdout=partial_test_status.stdout,
gcperfsim_result=gcperfsim_result,
)
out.write_test_status(test_status)
if not os_is_windows() and is_admin():
give_user_permissions(out.test_status_path)
if test_status.success:
print(f"Took {test_status.seconds_taken} seconds")
min_seconds = option_or_3(
t.benchmark.min_seconds, t.options.default_min_seconds, _TEST_MIN_SECONDS_DEFAULT
)
if test_status.seconds_taken < min_seconds:
desc = f"coreclr={t.coreclr_name} config={t.config_name} benchmark={t.benchmark_name}"
raise Exception(
f"{desc} took {test_status.seconds_taken} seconds, minimum is {min_seconds}"
"(you could change the benchmark's min_seconds or options.default_min_seconds)"
)
else:
print("Test failed, continuing...")
sleep(1) # Give process time to close
check_no_test_processes()
return test_status
def _parse_gcperfsim_result(stdout: str) -> GCPerfSimResult:
# Everything before the marker is ignored
marker = "=== STATS ==="
try:
idx = stdout.index(marker)
except ValueError:
print(f"STDOUT: '{stdout}'")
raise Exception(f"GCPerfSim stdout does not include '{marker}'") from None
yaml = stdout[idx + len(marker) :]
return parse_yaml(GCPerfSimResult, yaml)
@with_slots
@dataclass(frozen=True)
class _PartialTestRunStatus:
"""Compared to TestRunStatus, this is missing perfview_result, we parse that at the end."""
success: bool
process_id: int
seconds_taken: float
trace_file_name: Optional[str]
stdout: str
def _do_run_single_test(built: Built, t: SingleTest, out: TestPaths) -> _PartialTestRunStatus:
if t.options.collect == CollectKind.none:
return _run_single_test_no_collect(built, t, out)
elif t.options.always_use_dotnet_trace or not os_is_windows():
return _run_single_test_dotnet_trace(built, t, out)
else:
return _run_single_test_windows_perfview(built, t, out)
# Use this instead of TemporaryDirectory if you want to analyze the output
@contextmanager
def NonTemporaryDirectory(name: str) -> Iterator[Path]:
yield GC_PATH / "temp" / (name + str(randint(0, 99)))
def run_single_test_temporary(clr: Clr, built: Built, t: SingleTest) -> ProcessInfo:
with TemporaryDirectory(t.coreclr_name) as td:
temp = Path(td)
paths = TestPaths(temp / "temp")
test_status = run_single_test(built, t, paths)
# TODO: configurable process_predicate
trace_file = non_null(paths.trace_file_path(test_status))
return get_process_info(
clr, trace_file, str(trace_file), process_predicate_from_id(test_status.process_id)
)
def check_env() -> Mapping[str, str]:
e = environ
bad_environment_variables = [
k
for k in e.keys()
if any(k.lower().startswith(start) for start in ("complus", "core_root"))
]
if not is_empty(bad_environment_variables):
start = f"Environment variables should not be set: {', '.join(bad_environment_variables)}"
msg = (
start if os_is_windows() else f'{start}\nTry running: unset "${{!COMPlus@}}" CORE_ROOT'
)
raise Exception(msg)
return e
TEST_PROCESS_NAMES: Sequence[str] = ("corerun", "dotnet", "make_memory_load", "perfview")
def check_no_test_processes() -> None:
check_no_processes(TEST_PROCESS_NAMES)
def kill_test_processes() -> None:
for proc in process_iter():
if any(name in proc.name().lower() for name in TEST_PROCESS_NAMES):
print(f"Killing {proc.name()}")
for _ in range(10):
proc.kill()
# Sometimes it's still alive after being killed ...
sleep(1)
if not proc.is_running():
break
assert not proc.is_running()
check_no_test_processes()
_PERFVIEW_ALWAYS_ARGS: Sequence[str] = (
"-NoV2Rundown",
"-NoNGENRundown",
"-NoRundown",
"-AcceptEULA",
"-NoGUI",
"-Merge:true",
"-SessionName:CoreGCBench", # TODO:necessary?
"-zip:false",
)
def get_perfview_run_cmd(
built: Built,
t: SingleTest,
log_file: Path,
trace_file: Path,
perfview: bool = True,
ignore_container: bool = False,
) -> Sequence[str]:
test_args = _get_windows_test_cmd(built, t, ignore_container).command
if perfview:
# Since this is a perf test, we don't want to waste time logging the output.
# We will log errors though.
return (
str(PERFVIEW_PATH),
*_get_perfview_collect_or_run_common_args(t, log_file, trace_file),
"run",
*test_args,
)
else:
return test_args
@with_slots
@dataclass(frozen=True)
class CommandAndIsRunInJob:
command: Sequence[str]
is_run_in_job: bool
def _get_windows_test_cmd(
built: Built, t: SingleTest, ignore_container: bool
) -> CommandAndIsRunInJob:
test_args: Sequence[str] = _benchmark_command(t)
if (t.config.container is not None or t.config.affinitize) and not ignore_container:
c = t.config.container
assert c is None or c.image_name is None, "TODO"
return CommandAndIsRunInJob(
command=(
str(built.win.run_in_job_exe),
*(
empty_sequence()
if c is None or c.memory_mb is None
else ["--memory-mb", str(c.memory_mb)]
),
*(empty_sequence() if not t.config.affinitize else ["--affinitize"]),
*(
empty_sequence()
if c is None or c.cpu_rate_hard_cap is None
else ["--cpu-rate-hard-cap", str(c.cpu_rate_hard_cap)]
),
"--",
*test_args,
),
is_run_in_job=True,
)
else:
return CommandAndIsRunInJob(command=test_args, is_run_in_job=False)
def _get_perfview_start_or_stop_cmd(
t: SingleTest, log_file: Path, trace_file: Path, is_start: bool
) -> Sequence[str]:
return (
str(PERFVIEW_PATH),
"start" if is_start else "stop",
*_get_perfview_collect_or_run_common_args(t, log_file, trace_file),
)
_DEFAULT_MAX_TRACE_SIZE_GB = 1
def _get_perfview_collect_or_run_common_args(
t: SingleTest, log_file: Path, trace_file: Path
) -> Sequence[str]:
collect_args: Sequence[str] = {
CollectKind.gc: ["-GCCollectOnly"],
CollectKind.verbose: ["-GCCollectOnly", "-ClrEventLevel:Verbose"],
# Need default kernel events to get the process name
CollectKind.cpu_samples: [
"-OnlyProviders:ClrPrivate:1:5,Clr:1:5",
"-ClrEvents:GC+Stack",
"-ClrEventLevel:Verbose",
"-KernelEvents:Default",
],
CollectKind.cswitch: [
# Use verbose events (4 instead of 5)
"-OnlyProviders:ClrPrivate:1:5,Clr:1:5",
"-ClrEvents:GC+Stack",
f"-KernelEvents:Default,ContextSwitch",
],
}[t.options.get_collect]
max_trace_size_mb = round(
gb_to_mb(option_or(t.options.max_trace_size_gb, _DEFAULT_MAX_TRACE_SIZE_GB))
)
return (
*_PERFVIEW_ALWAYS_ARGS,
*collect_args,
# This option prevents perfview from opening a console
# and requiring the user to press enter
f"-LogFile:{log_file}",
f"-CircularMB:{max_trace_size_mb}",
f"-BufferSizeMB:{max_trace_size_mb}",
f"-DataFile:{trace_file}",
)
def log_env(log: Optional[LogOptions], path: Path) -> Mapping[str, str]:
if log is None:
return empty_mapping()
else:
return {
"COMPlus_GCLogEnabled": "1",
"COMPlus_GCLogFile": str(path),
"COMPlus_GCLogFileSize": hex_no_0x(option_or(log.file_size_mb, 0x30)),
"COMPlus_SOEnableDefaultRWValidation": "0", # TODO: is this needed?
# This env var no longer exists, must recompile to change level
# "COMPlus_GCprnLvl": hex_no_0x(log.level),
}
def _run_single_test_windows_perfview(
built: Built, t: SingleTest, out: TestPaths
) -> _PartialTestRunStatus:
assert_admin()
ensure_empty_dir(out.out_path_base)
# Start with the memory load
mem_load = t.config.memory_load
mem_load_process = None
if mem_load is not None:
print("setting up memory load...")
mem_load_args: Sequence[str] = (
str(built.win.make_memory_load),
"-percent",
str(mem_load.percent),
*optional_to_iter("-noReadjust" if mem_load.no_readjust else None),
)
mem_load_process = Popen(args=mem_load_args, stderr=PIPE)
assert mem_load_process.stderr is not None
# Wait on it to start up
line = decode_stdout(mem_load_process.stderr.readline())
assert (
line == "make_memory_load finished starting up"
), f"Unexpected make_memory_load output {line}"
print("done")
log_file = out.add_ext("perfview-log.txt")
trace_file = out.add_ext("etl")
timeout_seconds = _get_timeout(t)
exec_and_expect_output(
ExecArgs(_get_perfview_start_or_stop_cmd(t, log_file, trace_file, is_start=True)),
expected_output="",
err="PerfView start failed",
)
start_time_seconds = time()
test_cmd = _get_windows_test_cmd(built, t, ignore_container=False)
run_process = exec_start(_get_exec_args(test_cmd.command, t, out), pipe_stdout=True)
try:
run_result = wait_on_process_with_timeout(
run_process, start_time_seconds=start_time_seconds, timeout_seconds=timeout_seconds
)
finally:
# Stop PerfView even if the test failed
exec_and_expect_output(
ExecArgs(_get_perfview_start_or_stop_cmd(t, log_file, trace_file, is_start=False)),
expected_output="",
err="PerfView stop failed",
)
if run_result.time_taken is None:
kill_test_processes()
elif mem_load_process is not None:
# Releasing all the memory can take a while, so give it plenty of time
kill_process(mem_load_process, time_allowed_seconds=60)
# WIll have a return code of 2 because we interrupted it.
assert mem_load_process.returncode == 2
_rename_gcperfsim_out(out)
success = (
run_process.returncode == 0
and run_result.time_taken is not None
and not _perfview_has_warnings(log_file.read_text(encoding="utf-8"))
)
# If running in job, run_process.pid is run-in-job's PID, not the test process' PID.
# So it prints 'PID: 123' before exiting.
stdout, process_id = (
_strip_pid(run_result.stdout)
if test_cmd.is_run_in_job
else (run_result.stdout, run_process.pid)
)
return _PartialTestRunStatus(
success=success,
process_id=process_id,
seconds_taken=timeout_seconds
if run_result.time_taken is None
else run_result.time_taken.total_seconds(),
trace_file_name=trace_file.name,
stdout=stdout,
)
def _strip_pid(stdout: str) -> Tuple[str, int]:
pid_str = "PID: "
idx = stdout.rindex(pid_str)
return stdout[:idx].rstrip(), int(stdout[idx + len(pid_str) :])
def _rename_only_file_in_dir(dir_path: Path, expected_suffix: str, target: Path) -> None:
files_in_dir = tuple(dir_path.iterdir())
if not is_empty(files_in_dir):
assert len(files_in_dir) == 1
file = files_in_dir[0]
# assert file.name.endswith(expected_suffix)
if file.name.endswith(expected_suffix):
file.rename(target)
else:
file.unlink()
dir_path.rmdir()
_ALLOWED_WARNINGS: Sequence[str] = (
# Some coreclr benchmarks return 100 for some reason
"warning: command exited with non-success error code 0x64",
"warning: newly-allocated dummy ended up in gen 1",
"warning no _nt_symbol_path set ...",
)
for w in _ALLOWED_WARNINGS:
assert w.islower()
def _perfview_has_warnings(text: str) -> bool:
text_lower = text.lower()
if any(s in text_lower for s in ("process is terminating", "unhandled exception")):
return True
def is_allowed_warning(idx: int) -> bool:
rest = text_lower[idx:]
return any(rest.startswith(w) for w in _ALLOWED_WARNINGS)
warning_index = find(
lambda idx: not is_allowed_warning(idx), _substring_locations(text_lower, "warning")
)
if warning_index is not None:
print("Failing due to warning: ", text[warning_index:].split("\n")[0])
return True
else:
return False
def _get_timeout(t: SingleTest) -> float:
return option_or_3(
t.benchmark.max_seconds, t.options.default_max_seconds, _TEST_MAX_SECONDS_DEFAULT
)
def _run_single_test_no_collect(
_built: Built, t: SingleTest, out: TestPaths
) -> _PartialTestRunStatus:
if t.options.log is not None:
raise Exception("TODO")
if t.config.memory_load is not None:
# The script only works on windows right now
raise Exception("TODO")
out.out_path_base.mkdir() # GCPerfSim will write here
test_process_args: Sequence[str] = _benchmark_command(t)
args = _get_exec_args(test_process_args, t, out)
container = t.config.container
timeout_seconds = _get_timeout(t)
if container is not None or t.config.affinitize:
raise Exception("TODO")
start_time_seconds = time()
process = exec_start(args, pipe_stdout=True)
wait_result = wait_on_process_with_timeout(process, start_time_seconds, timeout_seconds)
gcperfsim_out = _rename_gcperfsim_out(out)
if container is not None:
give_user_permissions(gcperfsim_out)
# TODO: handle failure
return _PartialTestRunStatus(
success=wait_result.time_taken is not None,
process_id=process.pid,
seconds_taken=timeout_seconds
if wait_result.time_taken is None
else wait_result.time_taken.total_seconds(),
trace_file_name=None,
stdout=wait_result.stdout,
)
def _run_single_test_dotnet_trace(
_built: Built, t: SingleTest, out: TestPaths
) -> _PartialTestRunStatus:
if t.options.log is not None:
raise Exception("TODO")
if t.config.affinitize:
raise Exception("TODO")
if t.config.memory_load is not None:
# The script only works on windows right now
raise Exception("TODO")
test_process_args: Sequence[str] = _benchmark_command(t)
trace_out_dir = out.out_path_base.parent / "trace"
trace_out_dir.mkdir()
out.out_path_base.mkdir() # GCPerfSim will write here
args = _get_exec_args(test_process_args, t, out)
container = t.config.container
start_time_seconds = time()
if container is not None:
process_to_wait_on, pid_to_trace = _launch_process_in_cgroup(container, args)
else:
process_to_wait_on = exec_start(args, pipe_stdout=True)
pid_to_trace = process_to_wait_on.pid
trace_file = out.add_ext("nettrace")
dotnet_trace = exec_start(
_get_dotnet_trace_args(t.options, pid_to_trace, trace_file), pipe_stdout=False
)
timeout_seconds = _get_timeout(t)
wait_result = wait_on_process_with_timeout(
process_to_wait_on, start_time_seconds=start_time_seconds, timeout_seconds=timeout_seconds
)
# Shouldn't take more than 10 seconds to shut down
trace_stdout, trace_stderr = dotnet_trace.communicate("\n", timeout=10)
assert trace_stdout is None and trace_stderr is None
if container is not None:
_delete_cgroup()
# WARN: If the test is too short and no events fire, the output file will not be written to.
_rename_only_file_in_dir(trace_out_dir, expected_suffix=".nettrace", target=trace_file)
gcperfsim_out = _rename_gcperfsim_out(out)
if container is not None:
for file in (trace_file, gcperfsim_out):
give_user_permissions(file)
# TODO: handle failure
return _PartialTestRunStatus(
success=wait_result.time_taken is not None,
process_id=pid_to_trace,
seconds_taken=timeout_seconds
if wait_result.time_taken is None
else wait_result.time_taken.total_seconds(),
trace_file_name=trace_file.name,
stdout=wait_result.stdout,
)
def _get_dotnet_trace_path(options: BenchOptions) -> Path:
if options.dotnet_trace_path is not None:
return Path(options.dotnet_trace_path)
else:
res = which("dotnet-trace")
if res is None:
raise Exception("Can't find 'dotnet-trace' installed.")
else:
return Path(res)
def _get_dotnet_trace_args(options: BenchOptions, pid_to_trace: int, trace_file: Path) -> ExecArgs:
# if collect == CollectKind.gc:
# # 1 means GC, 4 means informational
# providers = "Microsoft-Windows-DotNETRuntime:1:4"
# elif collect == CollectKind.verbose:
# # 5 means verbose
# providers = "Microsoft-Windows-DotNETRuntime:1:5"
# else:
# raise Exception(f"TODO: handle collect kind {collect} on linux")
profile = {
CollectKind.gc: "gc-collect",
CollectKind.verbose: "gc-verbose",
CollectKind.cpu_samples: "cpu-sampling",
}[options.get_collect]
args: Sequence[str] = (
str(_get_dotnet_trace_path(options)),
"collect",
"--process-id",
str(pid_to_trace),
"--output",
str(trace_file),
*(
empty_sequence()
if options.dotnet_trace_buffersize_mb is None
else ["--buffersize", str(options.dotnet_trace_buffersize_mb)]
),
# TODO: use args.collect option to determine providers
# "--providers",
# 1 = GC, 4 = informational (5 = verbose)
# providers,
"--profile",
profile,
)
env: Mapping[str, str] = empty_mapping() if options.dotnet_path is None else {
"DOTNET_ROOT": str(options.dotnet_path.parent)
}
return ExecArgs(args, env=env)
_WRITE_PID_AND_EXEC_PATH = EXEC_ENV_PATH / "write_pid_and_exec.py"
_PID_FILE_PATH = EXEC_ENV_PATH / "__pid.txt"
_ALL_CGROUP_CATEGORIES: Sequence[str] = ("memory", "cpu")
_CGROUP_NAME = "gc-test-cgroup"
def _get_cgroup_categories_and_name(container: TestConfigContainer) -> str:
categories: Sequence[str] = (
(
*optional_to_iter(None if container.memory_mb is None else "memory"),
*optional_to_iter(None if container.cpu_rate_hard_cap is None else "cpu"),
)
)
assert all(c in _ALL_CGROUP_CATEGORIES for c in categories)
return f"{','.join(categories)}:{_CGROUP_NAME}"
def _create_cgroup(container: TestConfigContainer) -> None:
memory_mb = container.memory_mb
cpu_cap = container.cpu_rate_hard_cap
assert memory_mb is not None or cpu_cap is not None
if _cgroup_exists():
# cgroup_exists() may be a false positive, so allow failure
_delete_cgroup()
assert not _cgroup_exists()
exec_cmd(ExecArgs(("cgcreate", "-g", _get_cgroup_categories_and_name(container))))
if memory_mb is not None:
exec_cmd(
ExecArgs(
("cgset", "-r", f"memory.limit_in_bytes={mb_to_bytes(memory_mb)}", _CGROUP_NAME)
)
)
if cpu_cap is not None:
quota = round(seconds_to_usec(cpu_cap))
exec_cmd(
ExecArgs(
(
"cgset",
"-r",
f"cpu.cfs_period_us={USECS_PER_SECOND}",
f"cpu.cfs_quota_us={quota}",
_CGROUP_NAME,
)
)
)
def _ls_cgroup() -> str:
try:
return exec_and_get_output(ExecArgs(("lscgroup",), quiet_print=True))
except ExecutableNotFoundException:
raise Exception("cgroup-tools is not installed.")
# WARN: this sometimes has a false positive
def _cgroup_exists() -> bool:
return _CGROUP_NAME in _ls_cgroup()
def _delete_cgroup() -> None:
assert _cgroup_exists()
result = exec_and_get_result(
ExecArgs(("cgdelete", "-g", f"{','.join(_ALL_CGROUP_CATEGORIES)}:{_CGROUP_NAME}"))
)
assert result.exit_code
if result.exit_code == 96:
# Sometimes 'lscgroup' tells us the group exists, but then it doesn't. Just allow this.
assert (
result.stderr
== f"cgdelete: cannot remove group '{_CGROUP_NAME}': No such file or directory"
)
assert result.stdout == ""
else:
assert result.exit_code == 0 and result.stdout == "" and result.stderr == ""
assert not _cgroup_exists()
# Returns: The 'cgexec' process to wait on, and the PID of the *inner* process.
def _launch_process_in_cgroup(
container: TestConfigContainer, args: ExecArgs
) -> Tuple["Popen[str]", int]:
assert_admin()
_create_cgroup(container)
unlink_if_exists(_PID_FILE_PATH)
# TODO: Would be nice to have a better way to get the PID of the inner process.
cgexec_args = args_with_cmd(
args,
(
"cgexec",
"-g",
_get_cgroup_categories_and_name(container),
py,
str(_WRITE_PID_AND_EXEC_PATH),
*args.cmd,
),
)
cgexec_process = exec_start(cgexec_args, pipe_stdout=True)
# TODO: lower timeout_seconds
pid = int(
_read_file_when_it_exists(_PID_FILE_PATH, timeout_seconds=0.5, time_between_tries=0.1)
)
_PID_FILE_PATH.unlink()
return cgexec_process, pid
def _read_file_when_it_exists(path: Path, timeout_seconds: float, time_between_tries: float) -> str:
start = time()
while True:
try:
return path.read_text(encoding="utf-8")
except FileNotFoundError:
sleep(time_between_tries)
time_taken = time() - start
if time_taken > timeout_seconds:
raise Exception(f"{path} still doesn't exist after {timeout_seconds} seconds")
def _rename_gcperfsim_out(out: TestPaths) -> Path:
# Move the output file to avoid nested directoriess
target = out.add_ext("output.txt")
_rename_only_file_in_dir(out.out_path_base, expected_suffix="-output.txt", target=target)
return target
def _get_exec_args(cmd: Sequence[str], t: SingleTest, out: TestPaths) -> ExecArgs:
env = combine_mappings(
t.default_env,
t.config.with_coreclr(t.coreclr_name).env(map_option(t.coreclr, lambda c: c.core_root)),
log_env(t.options.log, out.out_path_base),
)
return ExecArgs(
cmd,
env=env,
# GCPerfSim will write a file `{pid}-output.txt` inside this directory
cwd=out.out_path_base,
)
# TODO: This isn't working yet. Uses lttng instead of eventpipe
def _run_single_test_linux_perfcollect(t: SingleTest, out: TestPaths) -> TestRunStatus:
# TODO: Could launch sudo just for the part it needs?
# TODO: running in sudo causes output files to only be readable by super user...
# A future perfcollect may fix this.
assert_admin()
ensure_empty_dir(out.out_path_base)
cwd = non_null(t.coreclr).corerun.parent # TODO: handle self-contained executables
env = combine_mappings(
t.config.with_coreclr(t.coreclr_name).env(map_option(t.coreclr, lambda c: c.core_root)),
{"COMPlus_PerfMapEnabled": "1", "COMPlus_EnableEventLog": "1"},
)
cmd: Sequence[str] = _benchmark_command(t)
print(f"cd {cwd}")
print(" ".join(cmd))
test_process = Popen(cmd, cwd=cwd, env=env)
test_process_pid = test_process.pid
# launch
print("PID", test_process_pid)
# Now launch that thing with the stuff
perfcollect_cmd = (
str(_PERFCOLLECT),
"collect",
str(out.out_path_base),
"-gccollectonly", # TODO: if I pass this, only event I get is EventID(200) ?
"-pid",
str(test_process_pid),
)
print(" ".join(perfcollect_cmd))
# TODO: not sure cwd needs to be set...
perfcollect_process = Popen(perfcollect_cmd, cwd=_PERFCOLLECT.parent)
print("waiting on test...")
test_process.wait()
assert test_process.returncode == 0
print("sending signal...")
perfcollect_process.send_signal(SIGINT)
print("waiting on perfcollect...")
perfcollect_process.wait()
assert perfcollect_process.returncode == 0
print("Closed")
raise Exception("TODO:finish")
_GC_KEYWORDS: Sequence[str] = (
"GC",
# Above isn't enough -- want GlobalHeapHistory ...
# "GCHandle",
# "GCHeapDump",
# "GCSampledObjectAllocationHigh",
# "GCHeapSurvivalAndMovement",
# "GCHeapCollect",
# "GCSampledObjectAllocationLow",
)
_GC_EVENTS_ID = 1
_GC_LEVEL = 5 # TODO: where is this documented?
_GC_PROVIDER: str = f"Microsoft-Windows-DotNETRuntime:0xFFFFFFFFFFFFFFFF:{_GC_LEVEL}"
# This is a bash script, no need to build
_PERFCOLLECT = Path("/home/anhans/work/corefx-tools/src/performance/perfcollect/perfcollect")
def _benchmark_command(t: SingleTest) -> Sequence[str]:
return (
*optional_to_iter(map_option(t.coreclr, lambda c: str(c.corerun))),
str(t.test_exe),
*t.benchmark.arguments_list,
)
# TODO:MOVE
def _substring_locations(s: str, substr: str) -> Iterable[int]:
idx = 0
while True:
idx = s.find(substr, idx)
if idx == -1:
break
yield idx
idx = idx + 1
|
import struct, io, collections, os, random, ipaddress
from . import enums, crypto
class Payload:
def __init__(self, type, critical=False):
self.type = enums.Payload(type)
self.critical = critical
self.data = None
@classmethod
def parse(cls, type, critical, stream, length):
self = cls.__new__(cls)
Payload.__init__(self, type, critical)
self.parse_data(stream, length)
return self
def parse_data(self, stream, length):
self.data = stream.read(length)
def to_bytes(self):
return self.data
def to_repr(self):
return f'data={self.data}'
def __repr__(self):
return f'{self.type.name}({'critical, ' if self.critical else ''}{self.to_repr()})'
def attr_parse(stream, length, attr_type_cls):
values = collections.OrderedDict()
while length > 0:
attr_type, value = struct.unpack('>HH', stream.read(4))
length -= 4
if attr_type & 0x8000:
attr_type &= 0x7FFF
else:
length -= value
value = stream.read(value)
values[attr_type_cls(attr_type)] = value
return values
def attr_to_bytes(values):
return b''.join((struct.pack('>HH', i|0x8000, j) if isinstance(j, int) else struct.pack('>HH', i, len(j))+j) for i, j in values.items())
Transform_1 = collections.namedtuple('Transform', 'num id values')
class Proposal_1:
def __init__(self, num, protocol, spi, transforms):
self.num = num
self.protocol = enums.Protocol(protocol)
self.spi = spi
self.transforms = transforms
@classmethod
def parse(cls, stream):
num, protocol, spi_size, n_transforms = struct.unpack('>BBBB', stream.read(4))
spi = stream.read(spi_size)
transforms = []
more = True
while more:
more, length, tnum, id = struct.unpack('>BxHBB2x', stream.read(8))
if protocol == enums.Protocol.ESP:
values = attr_parse(stream, length-8, enums.ESPAttr)
for attr_type in values:
if attr_type in enums.ESPTable_1:
values[attr_type] = enums.ESPTable_1[attr_type](values[attr_type])
transforms.append(Transform_1(tnum, enums.EncrId(id), values))
else:
values = attr_parse(stream, length-8, enums.TransformAttr)
for attr_type in values:
if attr_type in enums.TransformTable_1:
values[attr_type] = enums.TransformTable_1[attr_type](values[attr_type])
transforms.append(Transform_1(tnum, enums.Protocol(id), values))
return Proposal_1(num, protocol, spi, transforms)
def to_bytes(self):
data = bytearray()
data.extend(struct.pack('>BBBB', self.num, self.protocol, len(self.spi), len(self.transforms)))
data.extend(self.spi)
for idx, transform in enumerate(self.transforms):
transform_data = attr_to_bytes(transform.values)
data.extend(struct.pack('>BxHBB2x', 0 if idx==len(self.transforms)-1 else 3,
len(transform_data)+8, transform.num, transform.id))
data.extend(transform_data)
return data
def to_repr(self):
return f'{self.protocol.name}:{self.num}(spi={self.spi.hex() or 'None'}, ' + ', '.join(
f'{i.id.name}:{i.num}({', '.join(j.name+'='+str(k) for j,k in i.values.items())})' for i in self.transforms) + ')'
class PayloadSA_1(Payload):
def __init__(self, doi, situation, proposals):
Payload.__init__(self, enums.Payload.SA_1)
self.doi = doi
self.situation = situation
self.proposals = proposals
def parse_data(self, stream, length):
self.doi, self.situation = struct.unpack('>II', stream.read(8))
self.proposals = []
more = True
while more:
more, length = struct.unpack('>BxH', stream.read(4))
self.proposals.append(Proposal_1.parse(stream))
def to_bytes(self):
data = bytearray(struct.pack('>II', self.doi, self.situation))
for idx, proposal in enumerate(self.proposals):
proposal_data = proposal.to_bytes()
data.extend(struct.pack('>BxH', 0 if idx==len(self.proposals)-1 else 2, len(proposal_data)+4))
data.extend(proposal_data)
return data
def to_repr(self):
return f'doi={self.doi}, situation={self.situation}, ' + ', '.join(i.to_repr() for i in self.proposals)
class PayloadKE_1(Payload):
def __init__(self, ke_data):
Payload.__init__(self, enums.Payload.KE_1)
self.ke_data = ke_data
def parse_data(self, stream, length):
self.ke_data = stream.read(length)
def to_bytes(self):
return self.ke_data
def to_repr(self):
return f'{self.ke_data.hex()}'
class PayloadID_1(Payload):
def __init__(self, id_type, id_data, prot=0, port=0, critical=False):
Payload.__init__(self, enums.Payload.ID_1, critical)
self.id_type = enums.IDType(id_type)
self.prot = enums.IpProto(prot)
self.port = port
self.id_data = id_data
def parse_data(self, stream, length):
id_type, prot, self.port = struct.unpack('>BBH', stream.read(4))
self.id_type = enums.IDType(id_type)
self.prot = enums.IpProto(prot)
self.id_data = stream.read(length-4)
def to_bytes(self):
return struct.pack('>BBH', self.id_type, self.prot, self.port) + self.id_data
def _id_data_str(self):
if self.id_type in (enums.IDType.ID_RFC822_ADDR, enums.IDType.ID_FQDN):
return self.id_data.decode()
elif self.id_type in (enums.IDType.ID_IPV4_ADDR, enums.IDType.ID_IPV6_ADDR):
return str(ipaddress.ip_address(self.id_data))+(f':{self.port}({self.prot.name})' if self.prot!=0 else '')
else:
return self.id_data.hex()
def to_repr(self):
return f'{self.id_type.name}({self._id_data_str()})'
class PayloadHASH_1(Payload):
def __init__(self, data):
Payload.__init__(self, enums.Payload.HASH_1)
self.data = data
def parse_data(self, stream, length):
self.data = stream.read(length)
def to_bytes(self):
return self.data
def to_repr(self):
return f'{self.data.hex()}'
class PayloadNONCE_1(Payload):
def __init__(self, nonce=None, critical=False):
Payload.__init__(self, enums.Payload.NONCE_1, critical)
self.nonce = os.urandom(random.randrange(16, 256)) if nonce is None else nonce
def parse_data(self, stream, length):
self.nonce = stream.read(length)
def to_bytes(self):
return self.nonce
def to_repr(self):
return f'{self.nonce.hex()}'
class PayloadNOTIFY_1(Payload):
def __init__(self, doi, protocol, notify, spi, data):
Payload.__init__(self, enums.Payload.NOTIFY_1)
self.doi = doi
self.protocol = enums.Protocol(protocol)
self.notify = enums.Notify(notify)
self.spi = spi
self.data = data
def parse_data(self, stream, length):
self.doi, protocol, spi_size, notify = struct.unpack('>IBBH', stream.read(8))
self.protocol = enums.Protocol(protocol)
self.notify = enums.Notify(notify)
self.spi = stream.read(spi_size)
self.data = stream.read(length-8-spi_size)
def to_bytes(self):
data = bytearray(struct.pack('>IBBH', self.doi, self.protocol, len(self.spi), self.notify))
data.extend(self.spi)
data.extend(self.data)
return data
def to_repr(self):
return f'{self.notify.name}(doi={self.doi}, {'protocol='+self.protocol.name+', ' if self.protocol else ''}{'spi='+self.spi.hex()+', ' if self.spi else ''}{'data='+self.data.hex() if self.data else ''})'
class PayloadDELETE_1(Payload):
def __init__(self, doi, protocol, spis):
Payload.__init__(self, enums.Payload.DELETE_1)
self.doi = doi
self.protocol = enums.Protocol(protocol)
self.spis = spis
def parse_data(self, stream, length):
self.doi, protocol, spi_size, num_spis = struct.unpack('>IBBH', stream.read(8))
self.protocol = enums.Protocol(protocol)
self.spis = [stream.read(spi_size) for i in range(num_spis)]
def to_bytes(self):
data = bytearray()
data.extend(struct.pack('>IBBH', self.doi, self.protocol, len(self.spis[0]) if self.spis else 0, len(self.spis)))
for spi in self.spis:
data.extend(spi)
return data
def to_repr(self):
return f'{self.protocol.name}(doi={self.doi}, {', '.join(i.hex() for i in self.spis)})'
class PayloadVENDOR_1(Payload):
def __init__(self, vendor):
Payload.__init__(self, enums.Payload.VENDOR_1, False)
self.vendor = vendor
def parse_data(self, stream, length):
self.vendor = stream.read(length)
def to_bytes(self):
return self.vendor
def to_repr(self):
return f'{self.vendor.hex()}'
class PayloadCP_1(Payload):
def __init__(self, type, attrs, critical=False, identifier=0):
Payload.__init__(self, enums.Payload.CP_1, critical)
self.cftype = enums.CFGType(type)
self.identifier = identifier
self.attrs = attrs
def parse_data(self, stream, length):
cftype, self.identifier = struct.unpack('>BxH', stream.read(4))
self.cftype = enums.CFGType(cftype)
self.attrs = attr_parse(stream, length-4, enums.CPAttrType)
def to_bytes(self):
return struct.pack('>BxH', self.cftype, self.identifier) + attr_to_bytes(self.attrs)
def to_repr(self):
return f'{self.cftype.name}(id={self.identifier}, {', '.join(k.name+'='+(str(v) if type(v) is int else (v.hex() or 'None')) for k, v in self.attrs.items())})'
class PayloadNATD_1(Payload):
def __init__(self, data):
Payload.__init__(self, enums.Payload.NATD_1, False)
self.data = data
def parse_data(self, stream, length):
self.data = stream.read(length)
def to_bytes(self):
return self.data
def to_repr(self):
return f'{self.data.hex()}'
Transform = collections.namedtuple('Transform', 'type id keylen')
class Proposal:
def __init__(self, num, protocol, spi, transforms):
self.num = num
self.protocol = enums.Protocol(protocol)
self.spi = spi
self.transforms = transforms
@classmethod
def parse(cls, stream):
num, protocol, spi_size, n_transforms = struct.unpack('>BBBB', stream.read(4))
spi = stream.read(spi_size)
transforms = []
more = True
while more:
more, length, type, id = struct.unpack('>BxHBxH', stream.read(8))
values = attr_parse(stream, length-8, enums.TransformAttr)
keylen = values.get(enums.TransformAttr.KEY_LENGTH)
transforms.append(Transform(enums.Transform(type), enums.TransformTable[type](id), keylen))
return Proposal(num, protocol, spi, transforms)
def to_bytes(self):
data = bytearray()
data.extend(struct.pack('>BBBB', self.num, self.protocol, len(self.spi), len(self.transforms)))
data.extend(self.spi)
for idx, transform in enumerate(self.transforms):
transform_data = struct.pack('>HH', 0x800e, transform.keylen) if transform.keylen else b''
data.extend(struct.pack('>BxHBxH', 0 if idx==len(self.transforms)-1 else 3,
len(transform_data)+8, transform.type, transform.id))
data.extend(transform_data)
return data
def to_repr(self):
return f'{self.protocol.name}:{self.num}(spi={self.spi.hex() or 'None'}, ' + ', '.join(
f'{i.id.name}{'(keylen='+str(i.keylen)+')' if i.keylen else ''}' for i in self.transforms) + ')'
def remove_redundancy(self):
transforms = []
transformtypes = set()
for t in self.transforms:
if t.type not in transformtypes:
transformtypes.add(t.type)
if t.id == enums.PrfId.PRF_AES128_XCBC:
t = t._replace(id=enums.PrfId.PRF_HMAC_SHA2_256)
transforms.append(t)
print('++++++ transforms.id: ', t.id)
return Proposal(self.num, self.protocol, self.spi, transforms)
def get_transform(self, type):
return next((x for x in self.transforms if x.type == type), None)
class PayloadSA(Payload):
def __init__(self, proposals, critical=False):
Payload.__init__(self, enums.Payload.SA, critical)
self.proposals = proposals
def parse_data(self, stream, length):
self.proposals = []
more = True
while more:
more, length = struct.unpack('>BxH', stream.read(4))
self.proposals.append(Proposal.parse(stream))
def get_proposal(self, encr_id):
for i in self.proposals:
if i.get_transform(enums.Transform.ENCR).id == encr_id:
return i.remove_redundancy()
def to_bytes(self):
data = bytearray()
for idx, proposal in enumerate(self.proposals):
proposal_data = proposal.to_bytes()
data.extend(struct.pack('>BxH', 0 if idx==len(self.proposals)-1 else 2, len(proposal_data)+4))
data.extend(proposal_data)
return data
def to_repr(self):
return ', '.join(i.to_repr() for i in self.proposals)
class PayloadKE(Payload):
def __init__(self, dh_group, ke_data, critical=False):
Payload.__init__(self, enums.Payload.KE, critical)
self.dh_group = dh_group
self.ke_data = ke_data
def parse_data(self, stream, length):
self.dh_group, = struct.unpack('>H2x', stream.read(4))
self.ke_data = stream.read(length-4)
def to_bytes(self):
return struct.pack('>H2x', self.dh_group) + self.ke_data
def to_repr(self):
return f'{self.dh_group}, {self.ke_data.hex()}'
class PayloadIDi(PayloadID_1):
def __init__(self, id_type, id_data, prot=0, port=0, critical=False):
PayloadID_1.__init__(self, id_type, id_data, prot, port, critical)
self.type = enums.Payload.IDi
class PayloadIDr(PayloadID_1):
def __init__(self, id_type, id_data, prot=0, port=0, critical=False):
PayloadID_1.__init__(self, id_type, id_data, prot, port, critical)
self.type = enums.Payload.IDr
class PayloadAUTH(Payload):
def __init__(self, method, auth_data, critical=False):
Payload.__init__(self, enums.Payload.AUTH, critical)
self.method = enums.AuthMethod(method)
self.auth_data = auth_data
def parse_data(self, stream, length):
self.method = enums.AuthMethod(struct.unpack('>B3x', stream.read(4))[0])
self.auth_data = stream.read(length-4)
def to_bytes(self):
return struct.pack('>B3x', self.method) + self.auth_data
def to_repr(self):
return f'{self.method.name}({self.auth_data.hex()})'
class PayloadNONCE(PayloadNONCE_1):
def __init__(self, nonce=None, critical=False):
PayloadNONCE_1.__init__(self, nonce, critical)
self.type = enums.Payload.NONCE
class PayloadNOTIFY(Payload):
def __init__(self, protocol, notify, spi, data, critical=False):
Payload.__init__(self, enums.Payload.NOTIFY, critical)
self.protocol = enums.Protocol(protocol)
self.notify = enums.Notify(notify)
self.spi = spi
self.data = data
def parse_data(self, stream, length):
protocol, spi_size, notify = struct.unpack('>BBH', stream.read(4))
self.protocol = enums.Protocol(protocol)
self.notify = enums.Notify(notify)
self.spi = stream.read(spi_size)
self.data = stream.read(length-4-spi_size)
def to_bytes(self):
data = bytearray(struct.pack('>BBH', self.protocol, len(self.spi), self.notify))
data.extend(self.spi)
data.extend(self.data)
return data
def to_repr(self):
return f'{self.notify.name}({'protocol='+self.protocol.name+', ' if self.protocol else ''}{'spi='+self.spi.hex()+', ' if self.spi else ''}{'data='+self.data.hex() if self.data else ''})'
class PayloadDELETE(Payload):
def __init__(self, protocol, spis, critical=False):
Payload.__init__(self, enums.Payload.DELETE, critical)
self.protocol = enums.Protocol(protocol)
self.spis = spis
def parse_data(self, stream, length):
protocol, spi_size, num_spis = struct.unpack('>BBH', stream.read(4))
self.protocol = enums.Protocol(protocol)
self.spis = [stream.read(spi_size) for i in range(num_spis)]
def to_bytes(self):
data = bytearray()
data.extend(struct.pack('>BBH', self.protocol, len(self.spis[0]) if self.spis else 0, len(self.spis)))
for spi in self.spis:
data.extend(spi)
return data
def to_repr(self):
return f'{self.protocol.name}({', '.join(i.hex() for i in self.spis)})'
class PayloadVENDOR(Payload):
def __init__(self, vendor=None, critical=False):
Payload.__init__(self, enums.Payload.VENDOR, critical)
self.vendor = vendor
def parse_data(self, stream, length):
self.vendor = stream.read(length)
def to_bytes(self):
return self.vendor
def to_repr(self):
return f'{self.vendor.decode()}'
class TrafficSelector:
def __init__(self, ts_type, ip_proto, start_port, end_port, start_addr, end_addr):
self.ts_type = enums.TSType(ts_type)
self.ip_proto = enums.IpProto(ip_proto)
self.start_port = start_port
self.end_port = end_port
self.start_addr = start_addr
self.end_addr = end_addr
@classmethod
def from_network(cls, subnet, port, ip_proto):
return TrafficSelector(enums.TSType.TS_IPV4_ADDR_RANGE, ip_proto, port,
65535 if port == 0 else port, subnet[0], subnet[-1])
def get_network(self):
network = ipaddress.ip_network(self.start_addr)
while self.end_addr not in network:
network = network.supernet()
return network
def get_port(self):
return 0 if self.start_port==0 and self.end_port==65535 else self.end_port
@classmethod
def parse(cls, stream):
ts_type, ip_proto, length, start_port, end_port = struct.unpack('>BBHHH', stream.read(8))
addr_len = (length - 8) // 2
start_addr = stream.read(addr_len)
end_addr = stream.read(addr_len)
return TrafficSelector(ts_type, ip_proto, start_port, end_port, ipaddress.ip_address(start_addr),
ipaddress.ip_address(end_addr))
def to_bytes(self):
pack_addr = self.start_addr.packed + self.end_addr.packed
return struct.pack('>BBHHH', self.ts_type, self.ip_proto, 8 + len(pack_addr), self.start_port, self.end_port) + pack_addr
def __repr__(self):
return f'{self.ts_type.name}({self.ip_proto.name}, {self.start_addr} - {self.end_addr}, {self.start_port} - {self.end_port})'
class PayloadTSi(Payload):
def __init__(self, traffic_selectors, critical=False):
Payload.__init__(self, enums.Payload.TSi, critical)
self.traffic_selectors = traffic_selectors
def parse_data(self, stream, length):
n_ts, = struct.unpack_from('>B3x', stream.read(4))
self.traffic_selectors = [TrafficSelector.parse(stream) for i in range(n_ts)]
def to_bytes(self):
data = bytearray(struct.pack('>BBH', len(self.traffic_selectors), 0, 0))
for ts in self.traffic_selectors:
data.extend(ts.to_bytes())
return data
def to_repr(self):
return ', '.join(repr(i) for i in self.traffic_selectors)
class PayloadTSr(PayloadTSi):
def __init__(self, traffic_selectors, critical=False):
Payload.__init__(self, enums.Payload.TSr, critical)
self.traffic_selectors = traffic_selectors
class PayloadSK(Payload):
def __init__(self, ciphertext, critical=False):
Payload.__init__(self, enums.Payload.SK, critical)
self.ciphertext = ciphertext
def parse_data(self, stream, length):
self.ciphertext = stream.read(length)
def to_bytes(self):
return self.ciphertext
def to_repr(self):
return self.ciphertext.hex()
class PayloadCP(PayloadCP_1):
def __init__(self, type, attrs, critical=False):
PayloadCP_1.__init__(self, type, attrs, critical)
self.type = enums.Payload.CP
class PayloadEAP(Payload):
def __init__(self, code, data, critical=False):
Payload.__init__(self, enums.Payload.EAP, critical)
self.code = enums.EAPCode(code)
self.data = data
def parse_data(self, stream, length):
self.code = enums.EAPCode(stream.unpack('>B3x', stream.read(4))[0])
self.data = stream.read(length-4)
def to_bytes(self):
data = struct.pack('>BxH', self.code, len(self.data)+4)
return data+self.data
def to_repr(self):
return f'{self.code.name}({self.data.hex()})'
PayloadClass = {
enums.Payload.SA_1: PayloadSA_1,
enums.Payload.KE_1: PayloadKE_1,
enums.Payload.ID_1: PayloadID_1,
enums.Payload.HASH_1: PayloadHASH_1,
enums.Payload.NONCE_1: PayloadNONCE_1,
enums.Payload.NOTIFY_1: PayloadNOTIFY_1,
enums.Payload.DELETE_1: PayloadDELETE_1,
enums.Payload.VENDOR_1: PayloadVENDOR_1,
enums.Payload.CP_1: PayloadCP_1,
enums.Payload.NATD_1: PayloadNATD_1,
enums.Payload.SA: PayloadSA,
enums.Payload.KE: PayloadKE,
enums.Payload.IDi: PayloadIDi,
enums.Payload.IDr: PayloadIDr,
enums.Payload.AUTH: PayloadAUTH,
enums.Payload.NONCE: PayloadNONCE,
enums.Payload.NOTIFY: PayloadNOTIFY,
enums.Payload.DELETE: PayloadDELETE,
enums.Payload.VENDOR: PayloadVENDOR,
enums.Payload.TSi: PayloadTSi,
enums.Payload.TSr: PayloadTSr,
enums.Payload.SK: PayloadSK,
enums.Payload.CP: PayloadCP,
enums.Payload.EAP: PayloadEAP,
}
class Message:
def __init__(self, spi_i, spi_r, version, exchange, flag, message_id, payloads=None, *, first_payload=None):
self.spi_i = spi_i
self.spi_r = spi_r
self.version = version
self.exchange = enums.Exchange(exchange)
self.flag = enums.MsgFlag(flag)
self.message_id = message_id
self.first_payload = first_payload
self.payloads = [] if payloads is None else payloads
@classmethod
def parse(cls, stream):
header = struct.unpack('>8s8s4B2L', stream.read(28))
return Message(header[0], header[1], header[3], header[4], header[5], header[6], first_payload=header[2])
def parse_payloads(self, stream, *, crypto=None):
if self.flag & enums.MsgFlag.Encryption:
stream = io.BytesIO(crypto.decrypt_1(stream.read(), self.message_id))
next_payload = self.first_payload
while next_payload:
payload_id = next_payload
next_payload, critical, length = struct.unpack('>BBH', stream.read(4))
critical = bool(critical >> 7)
payload = PayloadClass.get(payload_id, Payload).parse(payload_id, critical, stream, length-4)
if payload_id == enums.Payload.SK:
if crypto is not None:
crypto.verify_checksum(stream.getvalue())
decrypted = crypto.decrypt(payload.ciphertext)
stream = io.BytesIO(decrypted)
continue
payload.next_payload = next_payload
next_payload = enums.Payload.NONE
self.payloads.append(payload)
@classmethod
def encode_payloads(cls, payloads):
data = bytearray()
for idx, payload in enumerate(payloads):
payload_data = payload.to_bytes()
if idx < len(payloads) - 1:
next_payload = payloads[idx+1].type
else:
next_payload = enums.Payload.NONE
data.extend(struct.pack('>BBH', next_payload, 0x80 if payload.critical else 0x00, len(payload_data) + 4))
data.extend(payload_data)
return data
def to_bytes(self, *, crypto=None):
first_payload = self.payloads[0].type if self.payloads else enums.Payload.NONE
data = self.encode_payloads(self.payloads)
if crypto and self.version == 0x10:
data = bytearray(crypto.encrypt_1(data, self.message_id))
self.flag |= enums.MsgFlag.Encryption
elif crypto and self.version == 0x20:
payload_sk = PayloadSK(crypto.encrypt(data))
payload_data = payload_sk.to_bytes()
data = bytearray(struct.pack('>BxH', first_payload, len(payload_data) + 4) + payload_data)
first_payload = enums.Payload.SK
data[0:0] = struct.pack(
'>8s8s4B2L', self.spi_i, self.spi_r, first_payload,
self.version, self.exchange, self.flag,
self.message_id, 28+len(data))
if crypto and self.version == 0x20:
crypto.add_checksum(data)
return data
def __repr__(self):
return f'{self.exchange.name}(spi_i={self.spi_i.hex()}, spi_r={self.spi_r.hex()}, version={self.version>>4}.{self.version&0xF}, flag={self.flag!s}, message_id={self.message_id}, ' + \
(', '.join(repr(i) for i in self.payloads) or 'NONE') + ')'
def get_payload(self, payload_type):
return next((x for x in self.payloads if x.type == payload_type), None)
def get_payload_notify(self, notify_id):
return next((x for x in self.payloads if x.type == enums.Payload.NOTIFY and x.notify == notify_id), None)
| import struct, io, collections, os, random, ipaddress
from . import enums, crypto
class Payload:
def __init__(self, type, critical=False):
self.type = enums.Payload(type)
self.critical = critical
self.data = None
@classmethod
def parse(cls, type, critical, stream, length):
self = cls.__new__(cls)
Payload.__init__(self, type, critical)
self.parse_data(stream, length)
return self
def parse_data(self, stream, length):
self.data = stream.read(length)
def to_bytes(self):
return self.data
def to_repr(self):
return f'data={self.data}'
def __repr__(self):
return f'{self.type.name}({"critical, " if self.critical else ""}{self.to_repr()})'
def attr_parse(stream, length, attr_type_cls):
values = collections.OrderedDict()
while length > 0:
attr_type, value = struct.unpack('>HH', stream.read(4))
length -= 4
if attr_type & 0x8000:
attr_type &= 0x7FFF
else:
length -= value
value = stream.read(value)
values[attr_type_cls(attr_type)] = value
return values
def attr_to_bytes(values):
return b''.join((struct.pack('>HH', i|0x8000, j) if isinstance(j, int) else struct.pack('>HH', i, len(j))+j) for i, j in values.items())
Transform_1 = collections.namedtuple('Transform', 'num id values')
class Proposal_1:
def __init__(self, num, protocol, spi, transforms):
self.num = num
self.protocol = enums.Protocol(protocol)
self.spi = spi
self.transforms = transforms
@classmethod
def parse(cls, stream):
num, protocol, spi_size, n_transforms = struct.unpack('>BBBB', stream.read(4))
spi = stream.read(spi_size)
transforms = []
more = True
while more:
more, length, tnum, id = struct.unpack('>BxHBB2x', stream.read(8))
if protocol == enums.Protocol.ESP:
values = attr_parse(stream, length-8, enums.ESPAttr)
for attr_type in values:
if attr_type in enums.ESPTable_1:
values[attr_type] = enums.ESPTable_1[attr_type](values[attr_type])
transforms.append(Transform_1(tnum, enums.EncrId(id), values))
else:
values = attr_parse(stream, length-8, enums.TransformAttr)
for attr_type in values:
if attr_type in enums.TransformTable_1:
values[attr_type] = enums.TransformTable_1[attr_type](values[attr_type])
transforms.append(Transform_1(tnum, enums.Protocol(id), values))
return Proposal_1(num, protocol, spi, transforms)
def to_bytes(self):
data = bytearray()
data.extend(struct.pack('>BBBB', self.num, self.protocol, len(self.spi), len(self.transforms)))
data.extend(self.spi)
for idx, transform in enumerate(self.transforms):
transform_data = attr_to_bytes(transform.values)
data.extend(struct.pack('>BxHBB2x', 0 if idx==len(self.transforms)-1 else 3,
len(transform_data)+8, transform.num, transform.id))
data.extend(transform_data)
return data
def to_repr(self):
return f'{self.protocol.name}:{self.num}(spi={self.spi.hex() or "None"}, ' + ', '.join(
f'{i.id.name}:{i.num}({", ".join(j.name+"="+str(k) for j,k in i.values.items())})' for i in self.transforms) + ')'
class PayloadSA_1(Payload):
def __init__(self, doi, situation, proposals):
Payload.__init__(self, enums.Payload.SA_1)
self.doi = doi
self.situation = situation
self.proposals = proposals
def parse_data(self, stream, length):
self.doi, self.situation = struct.unpack('>II', stream.read(8))
self.proposals = []
more = True
while more:
more, length = struct.unpack('>BxH', stream.read(4))
self.proposals.append(Proposal_1.parse(stream))
def to_bytes(self):
data = bytearray(struct.pack('>II', self.doi, self.situation))
for idx, proposal in enumerate(self.proposals):
proposal_data = proposal.to_bytes()
data.extend(struct.pack('>BxH', 0 if idx==len(self.proposals)-1 else 2, len(proposal_data)+4))
data.extend(proposal_data)
return data
def to_repr(self):
return f'doi={self.doi}, situation={self.situation}, ' + ', '.join(i.to_repr() for i in self.proposals)
class PayloadKE_1(Payload):
def __init__(self, ke_data):
Payload.__init__(self, enums.Payload.KE_1)
self.ke_data = ke_data
def parse_data(self, stream, length):
self.ke_data = stream.read(length)
def to_bytes(self):
return self.ke_data
def to_repr(self):
return f'{self.ke_data.hex()}'
class PayloadID_1(Payload):
def __init__(self, id_type, id_data, prot=0, port=0, critical=False):
Payload.__init__(self, enums.Payload.ID_1, critical)
self.id_type = enums.IDType(id_type)
self.prot = enums.IpProto(prot)
self.port = port
self.id_data = id_data
def parse_data(self, stream, length):
id_type, prot, self.port = struct.unpack('>BBH', stream.read(4))
self.id_type = enums.IDType(id_type)
self.prot = enums.IpProto(prot)
self.id_data = stream.read(length-4)
def to_bytes(self):
return struct.pack('>BBH', self.id_type, self.prot, self.port) + self.id_data
def _id_data_str(self):
if self.id_type in (enums.IDType.ID_RFC822_ADDR, enums.IDType.ID_FQDN):
return self.id_data.decode()
elif self.id_type in (enums.IDType.ID_IPV4_ADDR, enums.IDType.ID_IPV6_ADDR):
return str(ipaddress.ip_address(self.id_data))+(f':{self.port}({self.prot.name})' if self.prot!=0 else '')
else:
return self.id_data.hex()
def to_repr(self):
return f'{self.id_type.name}({self._id_data_str()})'
class PayloadHASH_1(Payload):
def __init__(self, data):
Payload.__init__(self, enums.Payload.HASH_1)
self.data = data
def parse_data(self, stream, length):
self.data = stream.read(length)
def to_bytes(self):
return self.data
def to_repr(self):
return f'{self.data.hex()}'
class PayloadNONCE_1(Payload):
def __init__(self, nonce=None, critical=False):
Payload.__init__(self, enums.Payload.NONCE_1, critical)
self.nonce = os.urandom(random.randrange(16, 256)) if nonce is None else nonce
def parse_data(self, stream, length):
self.nonce = stream.read(length)
def to_bytes(self):
return self.nonce
def to_repr(self):
return f'{self.nonce.hex()}'
class PayloadNOTIFY_1(Payload):
def __init__(self, doi, protocol, notify, spi, data):
Payload.__init__(self, enums.Payload.NOTIFY_1)
self.doi = doi
self.protocol = enums.Protocol(protocol)
self.notify = enums.Notify(notify)
self.spi = spi
self.data = data
def parse_data(self, stream, length):
self.doi, protocol, spi_size, notify = struct.unpack('>IBBH', stream.read(8))
self.protocol = enums.Protocol(protocol)
self.notify = enums.Notify(notify)
self.spi = stream.read(spi_size)
self.data = stream.read(length-8-spi_size)
def to_bytes(self):
data = bytearray(struct.pack('>IBBH', self.doi, self.protocol, len(self.spi), self.notify))
data.extend(self.spi)
data.extend(self.data)
return data
def to_repr(self):
return f'{self.notify.name}(doi={self.doi}, {"protocol="+self.protocol.name+", " if self.protocol else ""}{"spi="+self.spi.hex()+", " if self.spi else ""}{"data="+self.data.hex() if self.data else ""})'
class PayloadDELETE_1(Payload):
def __init__(self, doi, protocol, spis):
Payload.__init__(self, enums.Payload.DELETE_1)
self.doi = doi
self.protocol = enums.Protocol(protocol)
self.spis = spis
def parse_data(self, stream, length):
self.doi, protocol, spi_size, num_spis = struct.unpack('>IBBH', stream.read(8))
self.protocol = enums.Protocol(protocol)
self.spis = [stream.read(spi_size) for i in range(num_spis)]
def to_bytes(self):
data = bytearray()
data.extend(struct.pack('>IBBH', self.doi, self.protocol, len(self.spis[0]) if self.spis else 0, len(self.spis)))
for spi in self.spis:
data.extend(spi)
return data
def to_repr(self):
return f'{self.protocol.name}(doi={self.doi}, {", ".join(i.hex() for i in self.spis)})'
class PayloadVENDOR_1(Payload):
def __init__(self, vendor):
Payload.__init__(self, enums.Payload.VENDOR_1, False)
self.vendor = vendor
def parse_data(self, stream, length):
self.vendor = stream.read(length)
def to_bytes(self):
return self.vendor
def to_repr(self):
return f'{self.vendor.hex()}'
class PayloadCP_1(Payload):
def __init__(self, type, attrs, critical=False, identifier=0):
Payload.__init__(self, enums.Payload.CP_1, critical)
self.cftype = enums.CFGType(type)
self.identifier = identifier
self.attrs = attrs
def parse_data(self, stream, length):
cftype, self.identifier = struct.unpack('>BxH', stream.read(4))
self.cftype = enums.CFGType(cftype)
self.attrs = attr_parse(stream, length-4, enums.CPAttrType)
def to_bytes(self):
return struct.pack('>BxH', self.cftype, self.identifier) + attr_to_bytes(self.attrs)
def to_repr(self):
return f'{self.cftype.name}(id={self.identifier}, {", ".join(k.name+"="+(str(v) if type(v) is int else (v.hex() or "None")) for k, v in self.attrs.items())})'
class PayloadNATD_1(Payload):
def __init__(self, data):
Payload.__init__(self, enums.Payload.NATD_1, False)
self.data = data
def parse_data(self, stream, length):
self.data = stream.read(length)
def to_bytes(self):
return self.data
def to_repr(self):
return f'{self.data.hex()}'
Transform = collections.namedtuple('Transform', 'type id keylen')
class Proposal:
def __init__(self, num, protocol, spi, transforms):
self.num = num
self.protocol = enums.Protocol(protocol)
self.spi = spi
self.transforms = transforms
@classmethod
def parse(cls, stream):
num, protocol, spi_size, n_transforms = struct.unpack('>BBBB', stream.read(4))
spi = stream.read(spi_size)
transforms = []
more = True
while more:
more, length, type, id = struct.unpack('>BxHBxH', stream.read(8))
values = attr_parse(stream, length-8, enums.TransformAttr)
keylen = values.get(enums.TransformAttr.KEY_LENGTH)
transforms.append(Transform(enums.Transform(type), enums.TransformTable[type](id), keylen))
return Proposal(num, protocol, spi, transforms)
def to_bytes(self):
data = bytearray()
data.extend(struct.pack('>BBBB', self.num, self.protocol, len(self.spi), len(self.transforms)))
data.extend(self.spi)
for idx, transform in enumerate(self.transforms):
transform_data = struct.pack('>HH', 0x800e, transform.keylen) if transform.keylen else b''
data.extend(struct.pack('>BxHBxH', 0 if idx==len(self.transforms)-1 else 3,
len(transform_data)+8, transform.type, transform.id))
data.extend(transform_data)
return data
def to_repr(self):
return f'{self.protocol.name}:{self.num}(spi={self.spi.hex() or "None"}, ' + ', '.join(
f'{i.id.name}{"(keylen="+str(i.keylen)+")" if i.keylen else ""}' for i in self.transforms) + ')'
def remove_redundancy(self):
transforms = []
transformtypes = set()
for t in self.transforms:
if t.type not in transformtypes:
transformtypes.add(t.type)
if t.id == enums.PrfId.PRF_AES128_XCBC:
t = t._replace(id=enums.PrfId.PRF_HMAC_SHA2_256)
transforms.append(t)
print('++++++ transforms.id: ', t.id)
return Proposal(self.num, self.protocol, self.spi, transforms)
def get_transform(self, type):
return next((x for x in self.transforms if x.type == type), None)
class PayloadSA(Payload):
def __init__(self, proposals, critical=False):
Payload.__init__(self, enums.Payload.SA, critical)
self.proposals = proposals
def parse_data(self, stream, length):
self.proposals = []
more = True
while more:
more, length = struct.unpack('>BxH', stream.read(4))
self.proposals.append(Proposal.parse(stream))
def get_proposal(self, encr_id):
for i in self.proposals:
if i.get_transform(enums.Transform.ENCR).id == encr_id:
return i.remove_redundancy()
def to_bytes(self):
data = bytearray()
for idx, proposal in enumerate(self.proposals):
proposal_data = proposal.to_bytes()
data.extend(struct.pack('>BxH', 0 if idx==len(self.proposals)-1 else 2, len(proposal_data)+4))
data.extend(proposal_data)
return data
def to_repr(self):
return ', '.join(i.to_repr() for i in self.proposals)
class PayloadKE(Payload):
def __init__(self, dh_group, ke_data, critical=False):
Payload.__init__(self, enums.Payload.KE, critical)
self.dh_group = dh_group
self.ke_data = ke_data
def parse_data(self, stream, length):
self.dh_group, = struct.unpack('>H2x', stream.read(4))
self.ke_data = stream.read(length-4)
def to_bytes(self):
return struct.pack('>H2x', self.dh_group) + self.ke_data
def to_repr(self):
return f'{self.dh_group}, {self.ke_data.hex()}'
class PayloadIDi(PayloadID_1):
def __init__(self, id_type, id_data, prot=0, port=0, critical=False):
PayloadID_1.__init__(self, id_type, id_data, prot, port, critical)
self.type = enums.Payload.IDi
class PayloadIDr(PayloadID_1):
def __init__(self, id_type, id_data, prot=0, port=0, critical=False):
PayloadID_1.__init__(self, id_type, id_data, prot, port, critical)
self.type = enums.Payload.IDr
class PayloadAUTH(Payload):
def __init__(self, method, auth_data, critical=False):
Payload.__init__(self, enums.Payload.AUTH, critical)
self.method = enums.AuthMethod(method)
self.auth_data = auth_data
def parse_data(self, stream, length):
self.method = enums.AuthMethod(struct.unpack('>B3x', stream.read(4))[0])
self.auth_data = stream.read(length-4)
def to_bytes(self):
return struct.pack('>B3x', self.method) + self.auth_data
def to_repr(self):
return f'{self.method.name}({self.auth_data.hex()})'
class PayloadNONCE(PayloadNONCE_1):
def __init__(self, nonce=None, critical=False):
PayloadNONCE_1.__init__(self, nonce, critical)
self.type = enums.Payload.NONCE
class PayloadNOTIFY(Payload):
def __init__(self, protocol, notify, spi, data, critical=False):
Payload.__init__(self, enums.Payload.NOTIFY, critical)
self.protocol = enums.Protocol(protocol)
self.notify = enums.Notify(notify)
self.spi = spi
self.data = data
def parse_data(self, stream, length):
protocol, spi_size, notify = struct.unpack('>BBH', stream.read(4))
self.protocol = enums.Protocol(protocol)
self.notify = enums.Notify(notify)
self.spi = stream.read(spi_size)
self.data = stream.read(length-4-spi_size)
def to_bytes(self):
data = bytearray(struct.pack('>BBH', self.protocol, len(self.spi), self.notify))
data.extend(self.spi)
data.extend(self.data)
return data
def to_repr(self):
return f'{self.notify.name}({"protocol="+self.protocol.name+", " if self.protocol else ""}{"spi="+self.spi.hex()+", " if self.spi else ""}{"data="+self.data.hex() if self.data else ""})'
class PayloadDELETE(Payload):
def __init__(self, protocol, spis, critical=False):
Payload.__init__(self, enums.Payload.DELETE, critical)
self.protocol = enums.Protocol(protocol)
self.spis = spis
def parse_data(self, stream, length):
protocol, spi_size, num_spis = struct.unpack('>BBH', stream.read(4))
self.protocol = enums.Protocol(protocol)
self.spis = [stream.read(spi_size) for i in range(num_spis)]
def to_bytes(self):
data = bytearray()
data.extend(struct.pack('>BBH', self.protocol, len(self.spis[0]) if self.spis else 0, len(self.spis)))
for spi in self.spis:
data.extend(spi)
return data
def to_repr(self):
return f'{self.protocol.name}({", ".join(i.hex() for i in self.spis)})'
class PayloadVENDOR(Payload):
def __init__(self, vendor=None, critical=False):
Payload.__init__(self, enums.Payload.VENDOR, critical)
self.vendor = vendor
def parse_data(self, stream, length):
self.vendor = stream.read(length)
def to_bytes(self):
return self.vendor
def to_repr(self):
return f'{self.vendor.decode()}'
class TrafficSelector:
def __init__(self, ts_type, ip_proto, start_port, end_port, start_addr, end_addr):
self.ts_type = enums.TSType(ts_type)
self.ip_proto = enums.IpProto(ip_proto)
self.start_port = start_port
self.end_port = end_port
self.start_addr = start_addr
self.end_addr = end_addr
@classmethod
def from_network(cls, subnet, port, ip_proto):
return TrafficSelector(enums.TSType.TS_IPV4_ADDR_RANGE, ip_proto, port,
65535 if port == 0 else port, subnet[0], subnet[-1])
def get_network(self):
network = ipaddress.ip_network(self.start_addr)
while self.end_addr not in network:
network = network.supernet()
return network
def get_port(self):
return 0 if self.start_port==0 and self.end_port==65535 else self.end_port
@classmethod
def parse(cls, stream):
ts_type, ip_proto, length, start_port, end_port = struct.unpack('>BBHHH', stream.read(8))
addr_len = (length - 8) // 2
start_addr = stream.read(addr_len)
end_addr = stream.read(addr_len)
return TrafficSelector(ts_type, ip_proto, start_port, end_port, ipaddress.ip_address(start_addr),
ipaddress.ip_address(end_addr))
def to_bytes(self):
pack_addr = self.start_addr.packed + self.end_addr.packed
return struct.pack('>BBHHH', self.ts_type, self.ip_proto, 8 + len(pack_addr), self.start_port, self.end_port) + pack_addr
def __repr__(self):
return f'{self.ts_type.name}({self.ip_proto.name}, {self.start_addr} - {self.end_addr}, {self.start_port} - {self.end_port})'
class PayloadTSi(Payload):
def __init__(self, traffic_selectors, critical=False):
Payload.__init__(self, enums.Payload.TSi, critical)
self.traffic_selectors = traffic_selectors
def parse_data(self, stream, length):
n_ts, = struct.unpack_from('>B3x', stream.read(4))
self.traffic_selectors = [TrafficSelector.parse(stream) for i in range(n_ts)]
def to_bytes(self):
data = bytearray(struct.pack('>BBH', len(self.traffic_selectors), 0, 0))
for ts in self.traffic_selectors:
data.extend(ts.to_bytes())
return data
def to_repr(self):
return ', '.join(repr(i) for i in self.traffic_selectors)
class PayloadTSr(PayloadTSi):
def __init__(self, traffic_selectors, critical=False):
Payload.__init__(self, enums.Payload.TSr, critical)
self.traffic_selectors = traffic_selectors
class PayloadSK(Payload):
def __init__(self, ciphertext, critical=False):
Payload.__init__(self, enums.Payload.SK, critical)
self.ciphertext = ciphertext
def parse_data(self, stream, length):
self.ciphertext = stream.read(length)
def to_bytes(self):
return self.ciphertext
def to_repr(self):
return self.ciphertext.hex()
class PayloadCP(PayloadCP_1):
def __init__(self, type, attrs, critical=False):
PayloadCP_1.__init__(self, type, attrs, critical)
self.type = enums.Payload.CP
class PayloadEAP(Payload):
def __init__(self, code, data, critical=False):
Payload.__init__(self, enums.Payload.EAP, critical)
self.code = enums.EAPCode(code)
self.data = data
def parse_data(self, stream, length):
self.code = enums.EAPCode(stream.unpack('>B3x', stream.read(4))[0])
self.data = stream.read(length-4)
def to_bytes(self):
data = struct.pack('>BxH', self.code, len(self.data)+4)
return data+self.data
def to_repr(self):
return f'{self.code.name}({self.data.hex()})'
PayloadClass = {
enums.Payload.SA_1: PayloadSA_1,
enums.Payload.KE_1: PayloadKE_1,
enums.Payload.ID_1: PayloadID_1,
enums.Payload.HASH_1: PayloadHASH_1,
enums.Payload.NONCE_1: PayloadNONCE_1,
enums.Payload.NOTIFY_1: PayloadNOTIFY_1,
enums.Payload.DELETE_1: PayloadDELETE_1,
enums.Payload.VENDOR_1: PayloadVENDOR_1,
enums.Payload.CP_1: PayloadCP_1,
enums.Payload.NATD_1: PayloadNATD_1,
enums.Payload.SA: PayloadSA,
enums.Payload.KE: PayloadKE,
enums.Payload.IDi: PayloadIDi,
enums.Payload.IDr: PayloadIDr,
enums.Payload.AUTH: PayloadAUTH,
enums.Payload.NONCE: PayloadNONCE,
enums.Payload.NOTIFY: PayloadNOTIFY,
enums.Payload.DELETE: PayloadDELETE,
enums.Payload.VENDOR: PayloadVENDOR,
enums.Payload.TSi: PayloadTSi,
enums.Payload.TSr: PayloadTSr,
enums.Payload.SK: PayloadSK,
enums.Payload.CP: PayloadCP,
enums.Payload.EAP: PayloadEAP,
}
class Message:
def __init__(self, spi_i, spi_r, version, exchange, flag, message_id, payloads=None, *, first_payload=None):
self.spi_i = spi_i
self.spi_r = spi_r
self.version = version
self.exchange = enums.Exchange(exchange)
self.flag = enums.MsgFlag(flag)
self.message_id = message_id
self.first_payload = first_payload
self.payloads = [] if payloads is None else payloads
@classmethod
def parse(cls, stream):
header = struct.unpack('>8s8s4B2L', stream.read(28))
return Message(header[0], header[1], header[3], header[4], header[5], header[6], first_payload=header[2])
def parse_payloads(self, stream, *, crypto=None):
if self.flag & enums.MsgFlag.Encryption:
stream = io.BytesIO(crypto.decrypt_1(stream.read(), self.message_id))
next_payload = self.first_payload
while next_payload:
payload_id = next_payload
next_payload, critical, length = struct.unpack('>BBH', stream.read(4))
critical = bool(critical >> 7)
payload = PayloadClass.get(payload_id, Payload).parse(payload_id, critical, stream, length-4)
if payload_id == enums.Payload.SK:
if crypto is not None:
crypto.verify_checksum(stream.getvalue())
decrypted = crypto.decrypt(payload.ciphertext)
stream = io.BytesIO(decrypted)
continue
payload.next_payload = next_payload
next_payload = enums.Payload.NONE
self.payloads.append(payload)
@classmethod
def encode_payloads(cls, payloads):
data = bytearray()
for idx, payload in enumerate(payloads):
payload_data = payload.to_bytes()
if idx < len(payloads) - 1:
next_payload = payloads[idx+1].type
else:
next_payload = enums.Payload.NONE
data.extend(struct.pack('>BBH', next_payload, 0x80 if payload.critical else 0x00, len(payload_data) + 4))
data.extend(payload_data)
return data
def to_bytes(self, *, crypto=None):
first_payload = self.payloads[0].type if self.payloads else enums.Payload.NONE
data = self.encode_payloads(self.payloads)
if crypto and self.version == 0x10:
data = bytearray(crypto.encrypt_1(data, self.message_id))
self.flag |= enums.MsgFlag.Encryption
elif crypto and self.version == 0x20:
payload_sk = PayloadSK(crypto.encrypt(data))
payload_data = payload_sk.to_bytes()
data = bytearray(struct.pack('>BxH', first_payload, len(payload_data) + 4) + payload_data)
first_payload = enums.Payload.SK
data[0:0] = struct.pack(
'>8s8s4B2L', self.spi_i, self.spi_r, first_payload,
self.version, self.exchange, self.flag,
self.message_id, 28+len(data))
if crypto and self.version == 0x20:
crypto.add_checksum(data)
return data
def __repr__(self):
return f'{self.exchange.name}(spi_i={self.spi_i.hex()}, spi_r={self.spi_r.hex()}, version={self.version>>4}.{self.version&0xF}, flag={self.flag!s}, message_id={self.message_id}, ' + \
(', '.join(repr(i) for i in self.payloads) or 'NONE') + ')'
def get_payload(self, payload_type):
return next((x for x in self.payloads if x.type == payload_type), None)
def get_payload_notify(self, notify_id):
return next((x for x in self.payloads if x.type == enums.Payload.NOTIFY and x.notify == notify_id), None)
|
"""
Explanation of Code:
"""
# This file is a loose translation of Morgan Price's MultiCodes.pl into python.
import os
import logging
import re
import copy
import time
"""
Program Process:
"""
def RunMultiCodes(MC_d):
"""
(fp stands for filepath)
Inputs as listed in function 'CheckInputs'
MC_d: (dict):
out_prefix: (str) writes to this fp + '.codes', '.counts', '.close'
maxReads: (int) max Reads from input FASTQ file (Also known as nLimit)
[index_name]: (str) Name of index
[indexfile_fp]: (str) Not in use* fp to an index file, which has a format as
listed above XOR index_name. Rarely used*
minQuality: (int) minQuality for FASTQ base pairs
protocol_type: (str) 'custom' or 'dntag' or 'base' or 'bs3' or 'n25' or 'Unknown'
[bs3_fp]: (str) Filepath to barseq3.index2 tsv file (Nec. if protocol_type is bs3)
doOff1: (bool) - Checks whether or not we write to ".close"- performs analysis
for likelyhood of OffBy1 errors.
MC_seqs: (dict)
dnt_pre: (str) dntag pre sequence
dnt_post: (str) dntag post sequence
bs_pre: (str) base pre sequence
bs_post: (str) base post sequence
debug: (bool)
[pre_seq]: (str) Optional pre sequence (Nec. if protocol_type is custom)
[post_seq]: (str) Optional post sequence (Nec. if protocol_type is custom)
[nPreExpected]: int to which nPreExpectedMax/Min will be int +/- 2
(Nec. if protocol_type is custom)
fastq_fp: (str)
Returns:
Report_Dict: (d)
fastq_fp: s
nReads: i
nOff: d
int -> int
nUniqBC: i
nMultiplexed: i
[nWrongIndex2]: i
[nWrongI2Perc]: f (percent)
[nWrongPrePos]: i
[nWrongPrePosPerc]: f (percent)
[nOnce]: (i)
[nCases]: i
[nOff1Reads]: i
[fOff1]: f
EstimateDiversity_d: (d)
[noise]: (d)
percent_noise: (f) (prcnt)
diversity: (f)
seen_once: (f)
seen_twice: (f)
[good]: (d)
k_good_codes: (f)
percent_good_reads: (f) (prcnt)
Estimate_Bias_d: (d)
countSofar: (i)
percent_codes: (f) prcnt
k_codes: (f)
percent_reads: (f) prcnt
k_reads: (f)
Description:
*This is after removing multiplexing capabilities.
First we get the index preseq/postseq sequences
to find the barcode, and also the index name.
This part is run once per FASTQ file.
We count the number of times each barcode
found was seen. We find barcodes by looking
for the preseq and postseq indicated in
the function 'GetProtocolVariables'.
"""
# PREPARATION PHASE ---------------------------
vrs = CheckInputs(MC_d)
# We get nPreExpectedMin/Max
vrs = GetProtocolVariables(vrs)
# We get prefix (essential list for downstream analysis)
# vrs = IndexFileOrInameToPrefixInfo(vrs)
# DEBUG
#print(vrs)
#sys.exit(0)
# RUNNING ANALYSIS PHASE ----------------------------
# We parse input fastq
vrs = ParseFastqInput(vrs)
#sys.exit(0)
# WRITING TO OUTPUT -------------------
# We write out to files
# out.codes - Barcode and number of times it was seen
vrs = WriteOutCodesGetnPerCount(vrs)
# out.counts - For a given number of hits, how many barcodes match that?
vrs = WriteOutCounts(vrs)
# This writes the closest variants to barcodes and the differences
# in counts between them
if vrs['doOff1']:
vrs = WriteOutCloseGetOffBy1(vrs)
else:
vrs['offby1'] = {}
# RETURN TO USER --------------------
# We Start Report
output_d = PrepareMCOutput(vrs)
return output_d
def PrepareMCOutput(vrs):
"""
In this function we run all the estimates and preparations
Necessary keys in vrs: (d)
minQuality
codes
nPerCount
nOff
Rd
fastq_fp: s
"""
vrs['nUniq'] = len(vrs["codes"].keys())
vrs["Rd"]= InitReport(vrs)
vrs["Rd"]["EstimateDiversity_d"] = EstimateDiversity(vrs)
vrs["Rd"]["Estimate_Bias_d"] = EstimateBias(vrs)
vrs["fastq_fp"] = vrs["fastq_fp"]
return vrs["Rd"]
def EstimateDiversity(inp_d):
"""
Args:
inp_d: (d) Necessary keys:
minQuality: (i)
nOff: (d)
nPerCount: (d)
nUniq: (i)
doOff1: (b)
offby1: (d)
Barcode -> 1 if likely offby1 error
Returns:
ED_d: (d) Estimate Diversity dict. Optional keys:
[noise]: (d)
percent_noise: (f) (prcnt)
diversity: (f)
seen_once: (f)
seen_twice: (f)
[good]: (d)
good_codes: (i)
percent_good_reads: (f) (prcnt)
"""
ED_d = {}
if inp_d['minQuality'] > 0 and inp_d['nOff'][20] >= 1000 \
and inp_d['nPerCount'][2] >= 10:
ED_d["noise"] = {}
for fNoise in [0, 0.005, 0.01, 0.02]:
nNoise = int(0.5 + inp_d['nOff'][20] * fNoise)
if nNoise > inp_d['nPerCount'][1]:
continue
noise_d = {
"percent_noise": fNoise * 100,
"diversity": ((inp_d['nUniq'] - nNoise + \
(inp_d['nPerCount'][1] - nNoise)**2)/(2 * inp_d['nPerCount'][2])),
"seen_once" : (inp_d['nUniq'] - nNoise),
}
ED_d["noise"][fNoise] = noise_d
ED_d["seen_twice"] = inp_d['nPerCount'][2]
if (inp_d['minQuality']>0 and inp_d['nOff'][20]> 1000 \
and inp_d['doOff1']):
nGoodCodes = 0
nGoodReads = 0
for code in inp_d['codes'].keys():
count = inp_d['codes'][code]
if ((code not in inp_d['offby1']) and (count > 1)):
nGoodCodes += 1
nGoodReads += count
ED_d["good"] = {
"good_codes": nGoodCodes,
"percent_good_reads":100.0 * float(nGoodReads)/float(inp_d['nOff'][20])
}
return ED_d
def EstimateBias(inp_d):
"""
Args:
inp_d: d Necessary keys:
minQuality
codes
nPerCount
nOff
Returns:
countSofar: (i)
percent_codes: (f) prcnt
k_codes: (f)
percent_reads: (f) prcnt
k_reads: (f)
"""
EB_d = {"containsValues": False}
nUniq = len(inp_d["codes"].keys())
if inp_d['minQuality'] > 0 and nUniq >= 5000:
# What fraction of reads are accounted for by the top 1% of strains?
f = 0.01
nReadsSofar = 0
nCodesSofar = 0
countSofar = -1
nPerCount = inp_d['nPerCount']
sorted_npc_keys = sorted(nPerCount.keys(), reverse=True)
for count in sorted_npc_keys:
nReadsSofar += count * nPerCount[count]
nCodesSofar += nPerCount[count]
countSofar = count
if nCodesSofar >= f * nUniq:
break
#Estimate Bias dict. Note if nUniq >0 then nOff[20] > 0
EB_d = {
"containsValues": True,
"countSofar": countSofar,
'percent_codes': (100.0 * float(nCodesSofar))/float(nUniq),
'k_codes': float(nCodesSofar)/1000.0,
'percent_reads': (100.0 * float(nReadsSofar))/float(inp_d['nOff'][20]),
'k_reads': float(nReadsSofar)/1000.0
}
return EB_d
def WriteOutCloseGetOffBy1(inp_d):
"""
Args:
inp_d: (d)
out_prefix: (Str)
doOff1: (b)
nOff: (int)
codes: (d)
barcode -> num times seen
"""
offby1 = {} # barcode => 1 for likely off-by-1 errors
out_close_fp = inp_d["out_prefix"] + ".close"
OUTCLOSE = open(out_close_fp, "w")
OUTCLOSE.write("\t".join(['code1', 'count1', 'code2', 'count2']) + "\n")
nCases = 0
nOff1Reads = 0
codes = inp_d['codes']
for code in codes.keys():
count = codes[code]
variants = GetVariants(code) # variants is a list
for variant in variants:
if variant in codes:
n1 = count
n2 = codes[variant]
out_close_str = "\t".join([str(code),
str(n1), str(variant), str(n2)]) + "\n"
OUTCLOSE.write(out_close_str)
if n1 < n2:
offby1[code] = 1
nOff_val = n1
else:
offby1[variant] = 1
nOff_val = n2
nCases += 1
nOff1Reads += nOff_val
OUTCLOSE.close()
if 20 in inp_d['nOff']:
# Almost always should be the case
denominator = inp_d['nOff'][20]
if denominator == 0:
logging.warning("Warning, no barcodes length 20 found.")
denominator = 1
else:
denominator = 1
fOff1 = str(float(nOff1Reads)/float(denominator))
logging.info("Wrote .close to " + out_close_fp)
# int, int, float
inp_d['nCases'] = nCases
inp_d['nOff1Reads'] = nOff1Reads
inp_d['fOff1'] = fOff1
inp_d['offby1'] = offby1
return inp_d
def WriteOutCounts(inp_d):
"""
Args:
inp_d: (d) Must contain keys
out_prefix: (str)
nPerCount: (d)
sum of counts per index (i) - > number of codes with that sum (i)
Rd: (d) Report Dict
codes: (d) Barcode -> list of indexes and numbers of times barcode w/ index
Description:
Writes to out.counts file, which holds, for each count,
(which is a number of times a barcode was seen), how
many barcodes matched that number. Should be higher
closer to the smaller numbers.
"""
out_counts_fp = inp_d["out_prefix"] + ".counts"
OUTCOUNTS = open(out_counts_fp, "w")
nUniqBC = len(inp_d['codes'].keys())
OUTCOUNTS.write("\t".join(["Count","nCodes", "Frac"]) + "\n")
sorted_npc_keys = sorted(inp_d['nPerCount'].keys())
for count in sorted_npc_keys:
out_counts_str = "\t".join([str(count),
str(inp_d['nPerCount'][count]),
str((inp_d['nPerCount'][count]/nUniqBC))
]) + "\n"
OUTCOUNTS.write(out_counts_str)
OUTCOUNTS.close()
logging.info("Wrote out counts to " + out_counts_fp)
return inp_d
def WriteOutCodesGetnPerCount(inp_d):
"""
Args:
inp_d: (d) Necessary keys:
index_name (str): Name of index.
out_prefix: (str) Path to out file
codes: (d) barcode -> number of times seen
Rd: (d) report_dict
Returns:
nPerCount: (d)
sum of counts per index (i) - > number of codes with that sum (i)
Description:
We write 'codes' dict out to a file.
File name is defined by key 'out_prefix' + '.codes'
File looks like "barcode\tindex_name\n" Then
one row per barcode and then number of times seen.
"""
#Will add this to inp_d later
nPerCount = {} # sum of counts per index - > number of codes with that count
header_list = ["barcode", inp_d['index_name']]
out_codes_fp = inp_d['out_prefix'] + ".codes"
OUTCODES = open(out_codes_fp, "w")
#initializing codes tmp string
OUTCODES.write("\t".join(header_list) + "\n")
# nPrefix = len(inp_d['prefix']) # will equal 1 if iname given
for barcode in inp_d['codes'].keys():
count = inp_d['codes'][barcode]
current_row_list = [barcode, count]
OUTCODES.write("\t".join([str(x) for x in current_row_list]) + "\n")
if count in nPerCount:
nPerCount[count] += 1
else:
nPerCount[count] = 1
OUTCODES.close()
logging.info("Wrote Out-codes to " + out_codes_fp)
inp_d['nPerCount'] = nPerCount
return inp_d
def CheckInputs(MC_d):
"""
MC_d: (dict):
out_prefix: (str) writes to this fp + '.codes', '.counts', '.close'
fastq_fp: (str) Path to input fastq file
maxReads: (int) max Reads from input FASTQ file (Also known as nLimit)
[index_name]: (str) Name of index
[indexfile_fp]: (str) fp to an index file, which has a format as listed above XOR index_name
Rarely used*
minQuality: (int) minQuality for FASTQ base pairs
protocol_type: (str) 'custom' or 'dntag' or 'base' or 'bs3' or 'n25' or 'Unknown'
bs3_fp: (str) Filepath to barseq3.index2 tsv file
doOff1: (bool) - Checks whether or not we write to ".close"- performs analysis
for likelyhood of OffBy1 errors.
MC_seqs: (dict)
dnt_pre: (str) dntag pre sequence
dnt_post: (str) dntag post sequence
bs_pre: (str) base pre sequence
bs_post: (str) base post sequence
debug: (bool)
[pre_seq]: (str) Optional pre sequence (Nec. if protocol_type is custom)
[post_seq]: (str) Optional post sequence (Nec. if protocol_type is custom)
[nPreExpected]: int to which nPreExpectedMax/Min will be int +/- 2
(Nec. if protocol_type is custom)
"""
for x in ["out_prefix", "maxReads", "minQuality", "protocol_type", "doOff1",
"MC_seqs", "debug"]:
if x not in MC_d:
raise Exception("Input to MultiCodes must contain " + x + ".")
if not isinstance(MC_d["out_prefix"], str):
raise Exception("File prefix to write out to must be string")
if not os.path.exists(os.path.dirname(MC_d["out_prefix"])):
raise Exception("Directory for MultiCodes output does not exist: {}".format(
os.path.dirname(MC_d["out_prefix"])))
if not isinstance(MC_d["fastq_fp"], str):
raise Exception("FASTQ file path must be string")
if not os.path.exists(MC_d["fastq_fp"]):
raise Exception("FASTQ file path does not exist: {}".format(MC_d["fastq_fp"]))
if not isinstance(MC_d["maxReads"], int):
if MC_d["maxReads"] is not None:
raise Exception("max Reads must be an int or null (None)")
if not ( MC_d["maxReads"] is None or MC_d["maxReads"] > 0 ):
raise Exception("max Reads must be greater than 0")
if not "indexfile_fp" in MC_d:
if not "index_name" in MC_d:
raise Exception("indexfile_fp or index_name must be input to MultiCodes")
elif not isinstance(MC_d["index_name"], str):
raise Exception("index_name must be a string when input to MultiCodes")
elif not "index_name" in MC_d:
if not "indexfile_fp" in MC_d:
raise Exception("indexfile_fp or index_name must be input to MultiCodes")
elif not os.path.exists(MC_d["indexfile_fp"]):
raise Exception("Index file does not exist")
if not (isinstance(MC_d["minQuality"], int) and MC_d["minQuality"] >= 0):
raise Exception("minQuality must be an integer that is equal to " \
+ "or greater than 0. {}".format(MC_d["minQuality"]))
if not isinstance(MC_d["protocol_type"], str):
raise Exception("Protocol Type must be a string")
protocol_option_list = ["custom", "dntag", "base", "bs3", "n25", "Unknown"]
if not MC_d["protocol_type"] in protocol_option_list:
raise Exception("Protocol Type must be one of:\n {}".format(
" ".join(protocol_option_list)))
if not "bs3_fp" in MC_d:
raise Exception("bs3_fp must be input to MultiCodes")
elif not os.path.exists(MC_d["bs3_fp"]):
raise Exception("BS3 index file does not exist at path " + MC_d["bs3_fp"])
for x in ["doOff1", "debug"]:
if not isinstance(MC_d[x], bool):
raise Exception(x + " must be boolean.")
for x in ["dnt_pre", "dnt_post", "bs_pre", "bs_post"]:
if not x in MC_d["MC_seqs"]:
raise Exception("MC_seqs must contain key " + x)
if MC_d["protocol_type"] == "custom":
for x in ["pre_seq", "post_seq"]:
if x not in MC_d:
raise Exception(x + " must be in MultiCodes input if protocol type is custom.")
seq_b = True
for y in MC_d[x].upper():
if not y in ["A","C","T","G","N"]:
seq_b = False
if not seq_b:
raise Exception("custom " + x + " must contain only values 'ACTGN'")
if not "nPreExpected" in MC_d or not isinstance(MC_d["nPreExpected"], int):
raise Exception("nPreExpected must be int")
if not MC_d["nPreExpected"] >= 0:
raise Exception("nPreExpected must be greater than or equal to 0")
elif MC_d["protocol_type"] == "dntag":
if "index_name" in MC_d:
raise Exception("If protocol is dntag then we "
"must have indexfile_fp, not index_name")
return MC_d
def GetProtocolVariables(inp_d):
"""
Args: (Essential)
inp_d: (dict)
protocol_type: (str)
'custom' or 'dntag' or 'base' or 'bs3' or 'n25' or 'Unknown'
[index_name]: (str) Index Name, e.g. ?? or None.
iname is a necessary input IF protocol_type == "base" or "bs3"
bs3_fp: (str) Filepath to barseq3 index2 tsv file
this is a necessary input IF protocol_type == "bs3"
MC_seqs:
"dnt_pre": "GTCTCGTAG",
"dnt_post": "CGATGAATT",
"bs_pre": "CAGCGTACG",
"bs_post": "AGAGACCTC"
nPreExpectedMin (essential if protocol
nPreExpectedMax
You get the variables nPreExpectedMin(Max), and preseq and postseq
no matter what.
If bs3 is the protocol type, then you also get index2 and index 2At
"""
# str
pc = inp_d['protocol_type']
seq_dict = inp_d["MC_seqs"]
if pc == "bs3":
# This function fails if index name isn't in the bs3 file
bs3_info_d = GetBarSeq3Info(bs3_info_d)
nPreExpectedMin = bs3_info_d['nPreExpectedMin']
nPreExpectedMax = bs3_info_d['nPreExpectedMax']
preseq = seq_dict["bs_pre"]
postseq = seq_dict["bs_post"]
elif pc == "n25":
nPreExpectedMin = 11
nPreExpectedMax = 14
preseq = seq_dict["bs_pre"]
postseq = seq_dict["bs_post"]
elif pc == "dntag":
preseq = seq_dict["dnt_pre"]
postseq = seq_dict["dnt_post"]
nPreExpectedMin = 6
nPreExpectedMax = 10
elif pc == "base":
if "index_name" in inp_d:
#Usually here
nPreExpectedMin = 12
nPreExpectedMax = 16
else:
nPreExpectedMin = 7
nPreExpectedMax = 11
preseq = seq_dict["bs_pre"]
postseq = seq_dict["bs_post"]
elif pc == "custom":
# if 'preseq' and 'postseq' are empty, then what?
preseq = inp_d['preseq']
postseq = inp_d['postseq']
if inp_d['nPreExpected'] == None:
raise Exception("Missing -nPreExpected but has preseq and postseq")
nPreExpectedMin = inp_d['nPreExpected'] - 2
nPreExpectedMax = inp_d['nPreExpected'] + 2
else:
raise Exception("Could not recognize protocol type: '" + pc + "'")
#Updates
# DNA sequences:
inp_d['preseq'] = preseq
inp_d['postseq'] = postseq
# ints:
inp_d['nPreExpectedMin'] = nPreExpectedMin
inp_d['nPreExpectedMax'] = nPreExpectedMax
logging.basicConfig(level=logging.DEBUG)
logging.info("preseq, postseq, nPreExpectedMin, nPreExpectedMax:")
logging.info(f" {preseq}, {postseq}, {nPreExpectedMin}, {nPreExpectedMax}")
return inp_d
def GetBarSeq3Info(inp_d):
"""
Args:
inp_d: (dict)
bs3_fp: (str) filepath to barseq3.index2
index_name: (str) Index name
Returns:
new_d (dict):
nPreExpectedMin (int)
nPreExpectedMax (int)
[index2] (str): DNA sequence
[index2At]:
Description:
If the computed index name is not found in the
BarSeq3 index file, then the program will halt.
In the case that the second index is found,
inp_d will have the keys index2 and index2At
We will also update the variable index2len
"""
new_d = {}
#This is a special function to get the table fom file somehow
required_bs3_file_columns = ["index_name", "index2", "nN"]
#tab is a list of dicts with each line from ifile
bs3_rows = ReadTable(inp_d['bs3_fp'], required_bs3_file_columns)
#tabMatch is a subset of rows in bs3 with dicts whose index_name matches
# main index_name
tabMatch = []
for row_d in bs3_rows:
if row_d["index_name"] == inp_d["index_name"]:
tabMatch.append(row_d)
break
if len(tabMatch) == 0:
# Could not find index name in the barseq3 file.
warning_str = "Warning! Ignoring the second index -- index_name " \
+ "{} does not appear in {}\n".format(inp_d['index_name'],
inp_d['bs3_fp'])
#inp_d["report_dict"]["warnings"].append(warning_str)
logging.warning(warning_str)
error_string = f"Index name {inp_d["index_name"]} not found in barseq3 " + \
f"index file at {inp_d["bs3_fp"]}"
# Getting out of program.
raise Exception(error_string)
#new_d['nPreExpectedMin'] = 16
#new_d['nPreExpectedMax'] = 19
else:
#length of tabMatch is exactly 1
row = tabMatch[0]
inp_d['index2'] = row['index2'] #str
inp_d['index2At'] = int(row['nN']) # (Number of ns before)
nPE_preval = inp_d['index2At'] + 6 + 9
new_d['nPreExpectedMin'] = nPE_preval - 2
new_d['nPreExpectedMax'] = nPE_preval + 2
return new_d
# NOT IN USE
def MyGrep(hash_list, index_name, iname):
"""
hash_list: (list<subdict>)
subdict: (dict)
header -> value
index_name: (str) key in subdict that maps to index names
iname: (str) the index name we want.
Returns:
list<dict> minimized such that only dicts with wanted index name
are in it.
"""
new_list = []
for h in hash_list:
if h[index_name] == iname:
new_list.append(h)
return new_list
# fp is filepath, required is a list of required headers
# returns a list of hashmaps
def ReadTable(fp, required):
"""
fp: (str) Filepath to TSV file
required: (list<str>) A list of required headers in string format.
Returns:
rows: list<dicts>
each dict is a map of headers to values, which are all strings
In the case of index TSV reading- looks for index_name, index2 and nN
"""
FH = open(fp, "r")
header_line = FH.readline().rstrip()
header_list = header_line.split("\t")
# columns map
cols_map = {}
for i in range(len(header_list)):
cols_map[header_list[i]] = i
for field in required:
if field not in cols_map:
raise Exception("No field {} in {}".format(
field, fp))
rows = []
c_line = FH.readline()
while c_line != "":
line = c_line.rstrip()
new_line_list = line.split("\t")
if len(new_line_list) != len(header_list):
raise Exception("Wrong number of columns in:\n{} \
\n in {}".format(line, fp))
row_dict = {}
for i in range(len(new_line_list)):
row_dict[header_list[i]] = new_line_list[i]
rows.append(copy.deepcopy(row_dict))
c_line = FH.readline()
return rows
# Deprecated
def IndexFileOrInameToPrefixInfo(inp_d):
"""
There are two options: Either an index file path to get index information,
or an index name, in which case prefix is a list with length 1
Args:
inp_d: (dict)
[indexfile_fp] (str)
OR
index_name: (str)
"""
# Report String doesn't exist yet
if "index_name" in inp_d:
logging.info("Recognized index type as index name")
# nLeading (int), Some sequence (str), index_name (str)
prefix = [[0, "", inp_d['index_name']]]
prefixNames = [inp_d['index_name']]
else:
raise Exception("Program only works with index_names now,"
" index file deprecated.")
#updating inp_d
inp_d['prefix'] = prefix
inp_d['prefixNames'] = prefixNames
return inp_d
def InitReport(inp_d):
"""
Args:
inp_d: (dict)
fastq_fp: (str)
nOff: (dict)
ints (18-23) mapping to number of times (int) this distance
occured between preseq and postseq within the reads
codes: (dict)
barcode (str) -> prefixlist
prefixlist: list<int>
such that at the index of a DNAindex from the list 'prefix',
the number of times that barcode is found with that DNAindex
nReads: (int)
nMulti: (int)
[index2]: (str)
[nWrongIndex2]: (int)
Returns:
Rd: (d) Report Dict
fastq_fp: s
nReads: i
nOff: d
int -> int
nUniqBC: i
nMultiplexed: i
[nWrongIndex2]: i
[nWrongI2Perc]: f (percent)
[nWrongPrePos]: i
[nWrongPrePosPerc]: f (percent)
[nOnce]: (i)
[nCases]: i
[nOff1Reads]: i
[fOff1]: f
"""
# Report Dict
Rd = {}
# Total differences between preseq and postseqs found
nOffTot = sum(inp_d['nOff'].values())
# Number of unique barcodes
nUniqBC = len(inp_d['codes'].keys())
stringed_nOff = {str(x):inp_d['nOff'][x] for x in inp_d['nOff'].keys()}
Rd["fastq_fp"] = inp_d["fastq_fp"]
Rd['nReads'] = inp_d['nReads']
Rd['nOff'] = stringed_nOff
Rd['nOffTot'] = nOffTot
Rd['nUniqBC'] = nUniqBC
Rd['nMultiplexed'] = inp_d['nMulti']
offby1vals = False
if "nCases" in inp_d:
offby1vals = True
for x in ["nCases", "nOff1Reads", "fOff1"]:
if x in inp_d:
Rd[x] = inp_d[x]
Rd["offby1vals"] = offby1vals
if inp_d['nReads'] > 0 and "index2" in inp_d:
Rd['nWrongIndex2'] = inp_d['nWrongIndex2']
Rd['nWrongI2Perc'] = (100*inp_d['nWrongIndex2']/inp_d['nReads'])
if inp_d['nReads'] > inp_d['nWrongIndex2']:
Rd['nWrongPrePos'] = inp_d['nWrongPrePos']
Rd['nWrongPrePosPerc'] = 100*(inp_d['nWrongPrePos']/(inp_d['nReads'] - inp_d['nWrongIndex2'] ))
if 1 in inp_d['nPerCount']:
Rd["nOnce"] = inp_d['nPerCount'][1]
return Rd
def ParseFastqInput(inp_d):
"""
Args:
inp_d: (dict) Necessary keys: (There are others unused)
fastq_fp: (str) path to FASTQ file
maxReads: (int) A limit on number of reads from FASTQ
index_name: (str) Name of the index
[index2]: (str) A sequence of length 6 (if protocol_type == 'bs3')
[index2At]: (int) location of index2 (if protocol_type == 'bs3')
debug: (bool)
(For FindBarcode:)
nPreExpectedMin: (int)
nPreExpectedMax: (int)
minQuality: (int)
Returns:
nWrongPrePos (int):
nWrongIndex2 (int):
nPostSeqUsed (int): How many times we used the postSeq while finding
the read.
nReads (int): Total number of reads
nMulti (int): Number of reads with the prefix found (should be many).
nOff (dict): mapping from number 18-24 to number of times that offset seen.
codes (dict): barcode mapped to number of times it was found.
Description:
In this function we parse the FASTQ file.
In the case of bs3 (BarSeq3) we have a
key called 'index2' which is mapped
to a DNA sequence of length 6, and 'index2At'
which points to the expected location of index2
within a read.
If, within a read, we don't find index2 at
its expected location, then that's noted as an error,
and we add a number to the variable 'nWrongIndex2'.
"""
nWrongPrePos = 0
nWrongIndex2 = 0
nPostSeqUsed = 0
nReads = 0
nMulti = 0 # count with prefix identified
nOff = {i:0 for i in range(18,24)}
codes = {} #barcode maps to number of times seen
# FastQ File Handle
FQ_FH = open(inp_d['fastq_fp'], "r")
# current read name
c_readname = FQ_FH.readline()
line_num = 1
crnt_time = time.time()
while c_readname != '':
# We keep track of the number of reads
nReads += 1
# We extract the read info from the file handle
read_name = c_readname.rstrip()
seq = FQ_FH.readline().rstrip()
break_line = FQ_FH.readline().rstrip()
quality = FQ_FH.readline().rstrip()
CheckRead(read_name, seq, break_line, quality,
inp_d['fastq_fp'], line_num)
line_num += 4
if inp_d['maxReads'] is not None and (
nReads >= inp_d['maxReads']):
break
# Index 2 is a DNA sequence of length 6 - Only exists with bs3
# protocol under certain conditions
if "index2" in inp_d:
part = seq[inp_d['index2At']: inp_d['index2At'] + len(inp_d['index2'])]
if part != inp_d['index2']:
nWrongIndex2 += 1
c_readname = FQ_FH.readline()
continue
nMulti += 1
'''
if "index_name" in inp_d:
iPrefix = 0
else:
# Only if not multiplexed
iPrefix = FindPrefix(seq, inp_d['prefix'],
inp_d['debug']) # returns match (int) or -1
'''
#In most cases, index_name is used, so iPrefix is 0,
# so we get nLeading = 0, indexseq = "", prefixName is index_name
nLeading, indexseq, prefixName = [0, "", inp_d["index_name"]]
# Meaning that offset = nLeading + len("") = 0 + 0 = 0
#offset = nLeading + len(indexseq)
# barcode is str barcode, off is distance from start of barcode to start of postseq
# i.e. distance between end of preseq and beginning of postseq.
barcode, off, postseqIgnored = FindBarcode(seq, quality, inp_d)
if not postseqIgnored:
nPostSeqUsed += 1
if (barcode is None and off is not None and off >=0):
nWrongPrePos += 1
if nWrongPrePos >= 200 and nWrongPrePos >= (0.1 * nReads):
raise Exception("Over 10% of reads have the wrong spacing ( \
not {}:{}) to the pre-sequence ({} \
of {} so far).\n Maybe the wrong \
protocol indicated (i.e., 'n25' or 'bs3')?\n".format(
inp_d["nPreExpectedMin"],
inp_d["nPreExpectedMax"],
nWrongPrePos,
nReads))
if barcode is None:
c_readname = FQ_FH.readline()
continue
# We count the number of times a distance between preseq and postseq occurs
nOff[off] += 1
if off != 20:
# Barcode length is not 20
c_readname = FQ_FH.readline()
continue
if barcode in codes:
codes[barcode] += 1
else:
codes[barcode] = 1
if nReads % 1000000 == 0:
print("Read {} Reads so far".format(nReads))
new_time = time.time()
time_dif = int(new_time - crnt_time)
print("Time: {} seconds".format(time_dif))
crnt_time = new_time
# Prepare for next read loop
c_readname = FQ_FH.readline()
FQ_FH.close()
inp_d['nWrongPrePos'] = nWrongPrePos
inp_d['nWrongIndex2'] = nWrongIndex2
inp_d['nPostSeqUsed'] = nPostSeqUsed
inp_d['nReads'] = nReads
inp_d['nMulti'] = nMulti
inp_d['nOff'] = nOff
inp_d['codes'] = codes
#DEBUG
for x in ["nWrongPrePos", "nWrongIndex2", "nReads", "nMulti"]:
print(x + ": " + str(inp_d[x]))
return inp_d
# Deprecated!
# seq is DNA sequence (str)
# indexes is a list of lists, internal lists are [nLeading, indexseq, name],
# where nLeading is an int, indexseq is str, name is str
# debug in inp_d, True or False
# Deprecated!
def FindPrefix(seq, indexes, debug):
"""
Note this function is only run if the FASTQ file
isn't multiplexed and all are in one.
Args:
seq: (str) DNA sequence (from FASTQ)
indexes: list<list> internal lists are [nLeading, indexseq, name]
([int, str, str])
the list is the same as the variable 'prefix'
debug: (bool)
Returns:
An int, the index within the list of indexes which
matches this current index.
"""
matches = []
for i in range(len(indexes)):
nLeading, indexseq, name = indexes[i]
if (seq[nLeading:(nLeading + len(indexseq))] == indexseq):
matches.append(i)
if len(matches) == 1:
return matches[0]
elif len(matches) > 1:
logging.critical("More than one match for DNA sequence:\n {}\n with indexes".format(
seq))
if debug:
logging.info("No prefix for {}\n".format(seq))
return -1
def UpdateCodesiPrefix(codes_dict, barcode):
"""
Args:
codes_dict: (dict)
barcode (str) -> prefixlist
prefixlist: list<int>
such that at the index of a DNAindex from the list 'prefix',
the number of times that barcode is found with that DNAindex
is being updated
barcode: (str)
"""
return codes_dict
def IndexFileToPrefixInfo(index_fp):
"""
This function does not make sense given extant indexfiles
Args:
index_fp: (str) filepath to index file (TSV) with two columns
Returns:
ret_d: (dict)
"report_str": (str)
"prefixNames": list<str>,
"prefix": list<[int, str, str]>
[nLeading, indexseq, name] e.g. [
"""
IX_FH = open(index_fp, "r")
header_line = IX_FH.readline()
c_line = "placeholder"
# prefix is an important list that holds [[nLeading i, indexseq s, name s],...]
# nLeading is number of n's before index
prefix = []
line_num = 0
while c_line != "":
c_line = IX_FH.readline().rstrip()
line_num += 1
line_split = c_line.split('\t')
if len(line_split) > 2:
raise Exception("In indexfile, found a line that has more than "\
+ "2 tsvs.\n Filename: {} Line Number: {}".format(
index_fp, line_num))
#Note name & index are in form H1, ATCACGAG
name, index = line_split
# What does this account for?
if (re.search(r'name', name ,re.IGNORECASE)):
continue
nLeading = None
indexseq = None
match = re.search(r'^([nN]*)([ACGT]+)$',index)
if not match:
raise Exception("Invalid index sequence {}".format(index))
else:
nLeading = len(match[0])
indexseq = match[1]
if (nLeading == None ) or (indexseq == None) or (name == ''):
raise Exception(line)
prefix.append([nLeading, indexseq, name])
IX_FH.close()
report_str = "Read {} indices from {}\n".format(len(prefix),index_fp)
prefixNames = [x[2] for x in prefix]
return {
"report_str": report_str,
"prefixNames": prefixNames,
"prefix": prefix
}
#seq str -
#quality str
#offset int, usually 0
def FindBarcode(seq, quality, inp_d, offset=0):
"""
Args:
seq: (str) Sequence from FASTQ Read
quality: (str) Quality from FastQ Read
inp_d: (dict) Required keys:
preseq: (str) DNA Sequence
postseq: (str) DNA Sequence
nPreExpectedMin: (int)
nPreExpectedMax: (int)
minQuality: (int)
debug: (bool)
offset: (int) Represents location after nLeading and index sequence
preseq often: 'CAGCGTACG'
postseq often: 'AGAGACCTC'
How function works:
Note: We assume FASTQs are demultiplexed so that the important
part of the sequence is the sequence given, meaning that
offset = 0.
We get useful part of sequence and quality by taking original sequence and
starting from location after leading n's and index sequence.
Then we find the index of presequence defined
earlier in the program within the useful part of the sequence and assign it's value
to preseq_pos. preseq_pos must be within the nPreExpectedMin and
nPreExpectedMax index values of the true sequence, or it's not viable
and we return [None, None].
Then we assign barcode to where the presequence ends to 20 indeces
after that. If the entire sequence
is too short and we don't get a full barcode, then we return
[None, None].
Then we check for the postsequence in the true sequence. If the length
of the useful sequence is less than the sum of the barcode (20) and the
presequence and the index of the presequence and the postsequence, we
try a shorter postsequence of length 4, if that's not found we
claim it's too short, make postsequence "" and continue with function.
foundEnd: foundEnd is the distance between the end of the presequence
and the beginning of the postsequence if it's found. If the
postsequence is nothing (will this ever be the case in KBase?) then
foundEnd is automatically 20
Returns: [barcode, foundEnd, postseqIgnored]
barcode (str): String of length 20, the barcode
foundEnd (int): Difference between preseq and postseq
postseqIgnored (bool): Whether or not we actually used postseq.
True means not used.
"""
seq2 = seq[offset:]
quality2 = quality[offset:]
preseq = inp_d['preseq']
# The following gives -1 if not found, index of beginning if found
preseq_pos = seq2.find(preseq)
#Bad cases
if preseq_pos == -1 or preseq_pos < inp_d['nPreExpectedMin'] or \
preseq_pos > inp_d['nPreExpectedMax']:
if preseq_pos != -1:
if inp_d['debug']:
warning_str = "seq2 {} has invalid index-of-preseq: {}\n".format(
seq2, preseq_pos)
#inp_d["report_dict"]["warnings"].append(warning_str)
logging.warning(warning_str)
return [None, preseq_pos, True] # report that spacing was wrong
return [None, None, True]
#Note: Below line does not throw error if end index > len(seq2)
barcode = seq2[preseq_pos + len(preseq): preseq_pos + len(preseq) + 20]
if not (len(barcode) == 20 and re.search(r'^[A-Z]+$',barcode)):
# Barcode could be too short - meaning read is too short.
#note barcodes with ambiguous sequences are ignored
# we might want to allow one N in the future
if inp_d['debug']:
warning_str = "seq2 {} has invalid barcode sequence {}\n".format(
seq2, barcode)
#inp_d["report_dict"]["warnings"].append(warning_str)
logging.warning(warning_str)
return [None, None, True]
crnt_postseq = inp_d['postseq']
if len(seq2) < preseq_pos + len(preseq) + 20 + len(crnt_postseq):
crnt_postseq = crnt_postseq[:4] #first 4 characters.
if inp_d['debug']:
warning_str = "Using postseq {}\n".format(crnt_postseq)
#inp_d["report_dict"]["warnings"].append(warning_str)
logging.warning(warning_str)
#There might be redundant code here in MultiCodes.pl which checks
# above length (16 lines above) Redundant code left out of this file.
#We check again with a shorter crnt_postseq
if len(seq2) < preseq_pos + len(preseq) + 20 + len(crnt_postseq):
if inp_d['debug']:
warning_str = "Ignoring postseq, too short\n"
#inp_d["report_dict"]["warnings"].append(warning_str)
logging.warning(warning_str)
crnt_postseq = ""
foundEnd = -1
if crnt_postseq == "":
foundEnd = 20
postseqIgnored = True
else:
postseqIgnored = False
#check 20 first in case end of barcode matches post-seq (AGAG issue)
for off in [20,19,21,18,22]:
start_slice = preseq_pos + len(preseq) + off
end_slice = start_slice + len(crnt_postseq)
if (seq2[start_slice:end_slice] == crnt_postseq):
foundEnd = off
break
if foundEnd == -1:
# Could not find postseq
if inp_d['debug']:
warning_str = "seq2 \n {} \n barcode \n{}\n postseq not found\n".format(
seq2, barcode)
#inp_d["report_dict"]["warnings"].append(warning_str)
logging.warning(warning_str)
return [None,None, True]
if inp_d['minQuality'] > 0:
# the sanger code for !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJ
barqual = quality2[preseq_pos + len(preseq): preseq_pos + len(preseq) \
+ 20]
# quality score is encoded as 33+
scores = [ord(c) - 33 for c in barqual]
for score in scores:
if (score < 0 or score > 100):
raise Exception("Invalid score {} from barcode {} " \
+ "quality {}".format(score, barcode, barqual))
if score < inp_d['minQuality']:
if inp_d['debug']:
warning_str = "Low quality {} for barcode {} in " \
+ "{}\n".format(score, barcode, seq2)
#inp_d["report_dict"]["warnings"].append(warning_str)
logging.warning(warning_str)
return [None,None, True]
return [barcode, foundEnd, postseqIgnored]
def CheckRead(read_name, seq, break_line, quality, fastq_fp, line_num):
"""
Args are all fastq strings without ending linebreak
line_num refers to line number of read_name (int)
"""
if not read_name[0] == "@":
raise Exception("Read name does not start with @, line # {}\n File: {}".format(
line_num, fastq_fp))
for x in seq.upper():
if x not in ["A","C","T","G","N"]:
raise Exception("Sequence value {} not recognized. Line # {}\n File: {}".format(
x, line_num + 1, fastq_fp))
if not break_line[0] == "+":
raise Exception("Break line not '+'. Instead '{}'. Line # {}\n File: {}".format(
break_line[0],line_num + 2, fastq_fp))
if not len(quality) == len(seq):
raise Exception("Quality line wrong length. Lines # {}\n File: {}".format(
line_num + 3, fastq_fp))
#baseseq (str)
# returns all variants on sequence
def GetVariants(baseseq):
out = []
baseseq = baseseq.upper()
for i in range(len(baseseq)):
pre = baseseq[0:i]
char = baseseq[i:i+1]
post = baseseq[i+1:]
if not (char in ["A","C","G","T"]):
continue
for newchar in ["A","C","G","T"]:
if not newchar == char:
out.append(pre + newchar + post)
return out
| """
Explanation of Code:
"""
# This file is a loose translation of Morgan Price's MultiCodes.pl into python.
import os
import logging
import re
import copy
import time
"""
Program Process:
"""
def RunMultiCodes(MC_d):
"""
(fp stands for filepath)
Inputs as listed in function 'CheckInputs'
MC_d: (dict):
out_prefix: (str) writes to this fp + '.codes', '.counts', '.close'
maxReads: (int) max Reads from input FASTQ file (Also known as nLimit)
[index_name]: (str) Name of index
[indexfile_fp]: (str) Not in use* fp to an index file, which has a format as
listed above XOR index_name. Rarely used*
minQuality: (int) minQuality for FASTQ base pairs
protocol_type: (str) 'custom' or 'dntag' or 'base' or 'bs3' or 'n25' or 'Unknown'
[bs3_fp]: (str) Filepath to barseq3.index2 tsv file (Nec. if protocol_type is bs3)
doOff1: (bool) - Checks whether or not we write to ".close"- performs analysis
for likelyhood of OffBy1 errors.
MC_seqs: (dict)
dnt_pre: (str) dntag pre sequence
dnt_post: (str) dntag post sequence
bs_pre: (str) base pre sequence
bs_post: (str) base post sequence
debug: (bool)
[pre_seq]: (str) Optional pre sequence (Nec. if protocol_type is custom)
[post_seq]: (str) Optional post sequence (Nec. if protocol_type is custom)
[nPreExpected]: int to which nPreExpectedMax/Min will be int +/- 2
(Nec. if protocol_type is custom)
fastq_fp: (str)
Returns:
Report_Dict: (d)
fastq_fp: s
nReads: i
nOff: d
int -> int
nUniqBC: i
nMultiplexed: i
[nWrongIndex2]: i
[nWrongI2Perc]: f (percent)
[nWrongPrePos]: i
[nWrongPrePosPerc]: f (percent)
[nOnce]: (i)
[nCases]: i
[nOff1Reads]: i
[fOff1]: f
EstimateDiversity_d: (d)
[noise]: (d)
percent_noise: (f) (prcnt)
diversity: (f)
seen_once: (f)
seen_twice: (f)
[good]: (d)
k_good_codes: (f)
percent_good_reads: (f) (prcnt)
Estimate_Bias_d: (d)
countSofar: (i)
percent_codes: (f) prcnt
k_codes: (f)
percent_reads: (f) prcnt
k_reads: (f)
Description:
*This is after removing multiplexing capabilities.
First we get the index preseq/postseq sequences
to find the barcode, and also the index name.
This part is run once per FASTQ file.
We count the number of times each barcode
found was seen. We find barcodes by looking
for the preseq and postseq indicated in
the function 'GetProtocolVariables'.
"""
# PREPARATION PHASE ---------------------------
vrs = CheckInputs(MC_d)
# We get nPreExpectedMin/Max
vrs = GetProtocolVariables(vrs)
# We get prefix (essential list for downstream analysis)
# vrs = IndexFileOrInameToPrefixInfo(vrs)
# DEBUG
#print(vrs)
#sys.exit(0)
# RUNNING ANALYSIS PHASE ----------------------------
# We parse input fastq
vrs = ParseFastqInput(vrs)
#sys.exit(0)
# WRITING TO OUTPUT -------------------
# We write out to files
# out.codes - Barcode and number of times it was seen
vrs = WriteOutCodesGetnPerCount(vrs)
# out.counts - For a given number of hits, how many barcodes match that?
vrs = WriteOutCounts(vrs)
# This writes the closest variants to barcodes and the differences
# in counts between them
if vrs['doOff1']:
vrs = WriteOutCloseGetOffBy1(vrs)
else:
vrs['offby1'] = {}
# RETURN TO USER --------------------
# We Start Report
output_d = PrepareMCOutput(vrs)
return output_d
def PrepareMCOutput(vrs):
"""
In this function we run all the estimates and preparations
Necessary keys in vrs: (d)
minQuality
codes
nPerCount
nOff
Rd
fastq_fp: s
"""
vrs['nUniq'] = len(vrs["codes"].keys())
vrs["Rd"]= InitReport(vrs)
vrs["Rd"]["EstimateDiversity_d"] = EstimateDiversity(vrs)
vrs["Rd"]["Estimate_Bias_d"] = EstimateBias(vrs)
vrs["fastq_fp"] = vrs["fastq_fp"]
return vrs["Rd"]
def EstimateDiversity(inp_d):
"""
Args:
inp_d: (d) Necessary keys:
minQuality: (i)
nOff: (d)
nPerCount: (d)
nUniq: (i)
doOff1: (b)
offby1: (d)
Barcode -> 1 if likely offby1 error
Returns:
ED_d: (d) Estimate Diversity dict. Optional keys:
[noise]: (d)
percent_noise: (f) (prcnt)
diversity: (f)
seen_once: (f)
seen_twice: (f)
[good]: (d)
good_codes: (i)
percent_good_reads: (f) (prcnt)
"""
ED_d = {}
if inp_d['minQuality'] > 0 and inp_d['nOff'][20] >= 1000 \
and inp_d['nPerCount'][2] >= 10:
ED_d["noise"] = {}
for fNoise in [0, 0.005, 0.01, 0.02]:
nNoise = int(0.5 + inp_d['nOff'][20] * fNoise)
if nNoise > inp_d['nPerCount'][1]:
continue
noise_d = {
"percent_noise": fNoise * 100,
"diversity": ((inp_d['nUniq'] - nNoise + \
(inp_d['nPerCount'][1] - nNoise)**2)/(2 * inp_d['nPerCount'][2])),
"seen_once" : (inp_d['nUniq'] - nNoise),
}
ED_d["noise"][fNoise] = noise_d
ED_d["seen_twice"] = inp_d['nPerCount'][2]
if (inp_d['minQuality']>0 and inp_d['nOff'][20]> 1000 \
and inp_d['doOff1']):
nGoodCodes = 0
nGoodReads = 0
for code in inp_d['codes'].keys():
count = inp_d['codes'][code]
if ((code not in inp_d['offby1']) and (count > 1)):
nGoodCodes += 1
nGoodReads += count
ED_d["good"] = {
"good_codes": nGoodCodes,
"percent_good_reads":100.0 * float(nGoodReads)/float(inp_d['nOff'][20])
}
return ED_d
def EstimateBias(inp_d):
"""
Args:
inp_d: d Necessary keys:
minQuality
codes
nPerCount
nOff
Returns:
countSofar: (i)
percent_codes: (f) prcnt
k_codes: (f)
percent_reads: (f) prcnt
k_reads: (f)
"""
EB_d = {"containsValues": False}
nUniq = len(inp_d["codes"].keys())
if inp_d['minQuality'] > 0 and nUniq >= 5000:
# What fraction of reads are accounted for by the top 1% of strains?
f = 0.01
nReadsSofar = 0
nCodesSofar = 0
countSofar = -1
nPerCount = inp_d['nPerCount']
sorted_npc_keys = sorted(nPerCount.keys(), reverse=True)
for count in sorted_npc_keys:
nReadsSofar += count * nPerCount[count]
nCodesSofar += nPerCount[count]
countSofar = count
if nCodesSofar >= f * nUniq:
break
#Estimate Bias dict. Note if nUniq >0 then nOff[20] > 0
EB_d = {
"containsValues": True,
"countSofar": countSofar,
'percent_codes': (100.0 * float(nCodesSofar))/float(nUniq),
'k_codes': float(nCodesSofar)/1000.0,
'percent_reads': (100.0 * float(nReadsSofar))/float(inp_d['nOff'][20]),
'k_reads': float(nReadsSofar)/1000.0
}
return EB_d
def WriteOutCloseGetOffBy1(inp_d):
"""
Args:
inp_d: (d)
out_prefix: (Str)
doOff1: (b)
nOff: (int)
codes: (d)
barcode -> num times seen
"""
offby1 = {} # barcode => 1 for likely off-by-1 errors
out_close_fp = inp_d["out_prefix"] + ".close"
OUTCLOSE = open(out_close_fp, "w")
OUTCLOSE.write("\t".join(['code1', 'count1', 'code2', 'count2']) + "\n")
nCases = 0
nOff1Reads = 0
codes = inp_d['codes']
for code in codes.keys():
count = codes[code]
variants = GetVariants(code) # variants is a list
for variant in variants:
if variant in codes:
n1 = count
n2 = codes[variant]
out_close_str = "\t".join([str(code),
str(n1), str(variant), str(n2)]) + "\n"
OUTCLOSE.write(out_close_str)
if n1 < n2:
offby1[code] = 1
nOff_val = n1
else:
offby1[variant] = 1
nOff_val = n2
nCases += 1
nOff1Reads += nOff_val
OUTCLOSE.close()
if 20 in inp_d['nOff']:
# Almost always should be the case
denominator = inp_d['nOff'][20]
if denominator == 0:
logging.warning("Warning, no barcodes length 20 found.")
denominator = 1
else:
denominator = 1
fOff1 = str(float(nOff1Reads)/float(denominator))
logging.info("Wrote .close to " + out_close_fp)
# int, int, float
inp_d['nCases'] = nCases
inp_d['nOff1Reads'] = nOff1Reads
inp_d['fOff1'] = fOff1
inp_d['offby1'] = offby1
return inp_d
def WriteOutCounts(inp_d):
"""
Args:
inp_d: (d) Must contain keys
out_prefix: (str)
nPerCount: (d)
sum of counts per index (i) - > number of codes with that sum (i)
Rd: (d) Report Dict
codes: (d) Barcode -> list of indexes and numbers of times barcode w/ index
Description:
Writes to out.counts file, which holds, for each count,
(which is a number of times a barcode was seen), how
many barcodes matched that number. Should be higher
closer to the smaller numbers.
"""
out_counts_fp = inp_d["out_prefix"] + ".counts"
OUTCOUNTS = open(out_counts_fp, "w")
nUniqBC = len(inp_d['codes'].keys())
OUTCOUNTS.write("\t".join(["Count","nCodes", "Frac"]) + "\n")
sorted_npc_keys = sorted(inp_d['nPerCount'].keys())
for count in sorted_npc_keys:
out_counts_str = "\t".join([str(count),
str(inp_d['nPerCount'][count]),
str((inp_d['nPerCount'][count]/nUniqBC))
]) + "\n"
OUTCOUNTS.write(out_counts_str)
OUTCOUNTS.close()
logging.info("Wrote out counts to " + out_counts_fp)
return inp_d
def WriteOutCodesGetnPerCount(inp_d):
"""
Args:
inp_d: (d) Necessary keys:
index_name (str): Name of index.
out_prefix: (str) Path to out file
codes: (d) barcode -> number of times seen
Rd: (d) report_dict
Returns:
nPerCount: (d)
sum of counts per index (i) - > number of codes with that sum (i)
Description:
We write 'codes' dict out to a file.
File name is defined by key 'out_prefix' + '.codes'
File looks like "barcode\tindex_name\n" Then
one row per barcode and then number of times seen.
"""
#Will add this to inp_d later
nPerCount = {} # sum of counts per index - > number of codes with that count
header_list = ["barcode", inp_d['index_name']]
out_codes_fp = inp_d['out_prefix'] + ".codes"
OUTCODES = open(out_codes_fp, "w")
#initializing codes tmp string
OUTCODES.write("\t".join(header_list) + "\n")
# nPrefix = len(inp_d['prefix']) # will equal 1 if iname given
for barcode in inp_d['codes'].keys():
count = inp_d['codes'][barcode]
current_row_list = [barcode, count]
OUTCODES.write("\t".join([str(x) for x in current_row_list]) + "\n")
if count in nPerCount:
nPerCount[count] += 1
else:
nPerCount[count] = 1
OUTCODES.close()
logging.info("Wrote Out-codes to " + out_codes_fp)
inp_d['nPerCount'] = nPerCount
return inp_d
def CheckInputs(MC_d):
"""
MC_d: (dict):
out_prefix: (str) writes to this fp + '.codes', '.counts', '.close'
fastq_fp: (str) Path to input fastq file
maxReads: (int) max Reads from input FASTQ file (Also known as nLimit)
[index_name]: (str) Name of index
[indexfile_fp]: (str) fp to an index file, which has a format as listed above XOR index_name
Rarely used*
minQuality: (int) minQuality for FASTQ base pairs
protocol_type: (str) 'custom' or 'dntag' or 'base' or 'bs3' or 'n25' or 'Unknown'
bs3_fp: (str) Filepath to barseq3.index2 tsv file
doOff1: (bool) - Checks whether or not we write to ".close"- performs analysis
for likelyhood of OffBy1 errors.
MC_seqs: (dict)
dnt_pre: (str) dntag pre sequence
dnt_post: (str) dntag post sequence
bs_pre: (str) base pre sequence
bs_post: (str) base post sequence
debug: (bool)
[pre_seq]: (str) Optional pre sequence (Nec. if protocol_type is custom)
[post_seq]: (str) Optional post sequence (Nec. if protocol_type is custom)
[nPreExpected]: int to which nPreExpectedMax/Min will be int +/- 2
(Nec. if protocol_type is custom)
"""
for x in ["out_prefix", "maxReads", "minQuality", "protocol_type", "doOff1",
"MC_seqs", "debug"]:
if x not in MC_d:
raise Exception("Input to MultiCodes must contain " + x + ".")
if not isinstance(MC_d["out_prefix"], str):
raise Exception("File prefix to write out to must be string")
if not os.path.exists(os.path.dirname(MC_d["out_prefix"])):
raise Exception("Directory for MultiCodes output does not exist: {}".format(
os.path.dirname(MC_d["out_prefix"])))
if not isinstance(MC_d["fastq_fp"], str):
raise Exception("FASTQ file path must be string")
if not os.path.exists(MC_d["fastq_fp"]):
raise Exception("FASTQ file path does not exist: {}".format(MC_d["fastq_fp"]))
if not isinstance(MC_d["maxReads"], int):
if MC_d["maxReads"] is not None:
raise Exception("max Reads must be an int or null (None)")
if not ( MC_d["maxReads"] is None or MC_d["maxReads"] > 0 ):
raise Exception("max Reads must be greater than 0")
if not "indexfile_fp" in MC_d:
if not "index_name" in MC_d:
raise Exception("indexfile_fp or index_name must be input to MultiCodes")
elif not isinstance(MC_d["index_name"], str):
raise Exception("index_name must be a string when input to MultiCodes")
elif not "index_name" in MC_d:
if not "indexfile_fp" in MC_d:
raise Exception("indexfile_fp or index_name must be input to MultiCodes")
elif not os.path.exists(MC_d["indexfile_fp"]):
raise Exception("Index file does not exist")
if not (isinstance(MC_d["minQuality"], int) and MC_d["minQuality"] >= 0):
raise Exception("minQuality must be an integer that is equal to " \
+ "or greater than 0. {}".format(MC_d["minQuality"]))
if not isinstance(MC_d["protocol_type"], str):
raise Exception("Protocol Type must be a string")
protocol_option_list = ["custom", "dntag", "base", "bs3", "n25", "Unknown"]
if not MC_d["protocol_type"] in protocol_option_list:
raise Exception("Protocol Type must be one of:\n {}".format(
" ".join(protocol_option_list)))
if not "bs3_fp" in MC_d:
raise Exception("bs3_fp must be input to MultiCodes")
elif not os.path.exists(MC_d["bs3_fp"]):
raise Exception("BS3 index file does not exist at path " + MC_d["bs3_fp"])
for x in ["doOff1", "debug"]:
if not isinstance(MC_d[x], bool):
raise Exception(x + " must be boolean.")
for x in ["dnt_pre", "dnt_post", "bs_pre", "bs_post"]:
if not x in MC_d["MC_seqs"]:
raise Exception("MC_seqs must contain key " + x)
if MC_d["protocol_type"] == "custom":
for x in ["pre_seq", "post_seq"]:
if x not in MC_d:
raise Exception(x + " must be in MultiCodes input if protocol type is custom.")
seq_b = True
for y in MC_d[x].upper():
if not y in ["A","C","T","G","N"]:
seq_b = False
if not seq_b:
raise Exception("custom " + x + " must contain only values 'ACTGN'")
if not "nPreExpected" in MC_d or not isinstance(MC_d["nPreExpected"], int):
raise Exception("nPreExpected must be int")
if not MC_d["nPreExpected"] >= 0:
raise Exception("nPreExpected must be greater than or equal to 0")
elif MC_d["protocol_type"] == "dntag":
if "index_name" in MC_d:
raise Exception("If protocol is dntag then we "
"must have indexfile_fp, not index_name")
return MC_d
def GetProtocolVariables(inp_d):
"""
Args: (Essential)
inp_d: (dict)
protocol_type: (str)
'custom' or 'dntag' or 'base' or 'bs3' or 'n25' or 'Unknown'
[index_name]: (str) Index Name, e.g. ?? or None.
iname is a necessary input IF protocol_type == "base" or "bs3"
bs3_fp: (str) Filepath to barseq3 index2 tsv file
this is a necessary input IF protocol_type == "bs3"
MC_seqs:
"dnt_pre": "GTCTCGTAG",
"dnt_post": "CGATGAATT",
"bs_pre": "CAGCGTACG",
"bs_post": "AGAGACCTC"
nPreExpectedMin (essential if protocol
nPreExpectedMax
You get the variables nPreExpectedMin(Max), and preseq and postseq
no matter what.
If bs3 is the protocol type, then you also get index2 and index 2At
"""
# str
pc = inp_d['protocol_type']
seq_dict = inp_d["MC_seqs"]
if pc == "bs3":
# This function fails if index name isn't in the bs3 file
bs3_info_d = GetBarSeq3Info(bs3_info_d)
nPreExpectedMin = bs3_info_d['nPreExpectedMin']
nPreExpectedMax = bs3_info_d['nPreExpectedMax']
preseq = seq_dict["bs_pre"]
postseq = seq_dict["bs_post"]
elif pc == "n25":
nPreExpectedMin = 11
nPreExpectedMax = 14
preseq = seq_dict["bs_pre"]
postseq = seq_dict["bs_post"]
elif pc == "dntag":
preseq = seq_dict["dnt_pre"]
postseq = seq_dict["dnt_post"]
nPreExpectedMin = 6
nPreExpectedMax = 10
elif pc == "base":
if "index_name" in inp_d:
#Usually here
nPreExpectedMin = 12
nPreExpectedMax = 16
else:
nPreExpectedMin = 7
nPreExpectedMax = 11
preseq = seq_dict["bs_pre"]
postseq = seq_dict["bs_post"]
elif pc == "custom":
# if 'preseq' and 'postseq' are empty, then what?
preseq = inp_d['preseq']
postseq = inp_d['postseq']
if inp_d['nPreExpected'] == None:
raise Exception("Missing -nPreExpected but has preseq and postseq")
nPreExpectedMin = inp_d['nPreExpected'] - 2
nPreExpectedMax = inp_d['nPreExpected'] + 2
else:
raise Exception("Could not recognize protocol type: '" + pc + "'")
#Updates
# DNA sequences:
inp_d['preseq'] = preseq
inp_d['postseq'] = postseq
# ints:
inp_d['nPreExpectedMin'] = nPreExpectedMin
inp_d['nPreExpectedMax'] = nPreExpectedMax
logging.basicConfig(level=logging.DEBUG)
logging.info("preseq, postseq, nPreExpectedMin, nPreExpectedMax:")
logging.info(f" {preseq}, {postseq}, {nPreExpectedMin}, {nPreExpectedMax}")
return inp_d
def GetBarSeq3Info(inp_d):
"""
Args:
inp_d: (dict)
bs3_fp: (str) filepath to barseq3.index2
index_name: (str) Index name
Returns:
new_d (dict):
nPreExpectedMin (int)
nPreExpectedMax (int)
[index2] (str): DNA sequence
[index2At]:
Description:
If the computed index name is not found in the
BarSeq3 index file, then the program will halt.
In the case that the second index is found,
inp_d will have the keys index2 and index2At
We will also update the variable index2len
"""
new_d = {}
#This is a special function to get the table fom file somehow
required_bs3_file_columns = ["index_name", "index2", "nN"]
#tab is a list of dicts with each line from ifile
bs3_rows = ReadTable(inp_d['bs3_fp'], required_bs3_file_columns)
#tabMatch is a subset of rows in bs3 with dicts whose index_name matches
# main index_name
tabMatch = []
for row_d in bs3_rows:
if row_d["index_name"] == inp_d["index_name"]:
tabMatch.append(row_d)
break
if len(tabMatch) == 0:
# Could not find index name in the barseq3 file.
warning_str = "Warning! Ignoring the second index -- index_name " \
+ "{} does not appear in {}\n".format(inp_d['index_name'],
inp_d['bs3_fp'])
#inp_d["report_dict"]["warnings"].append(warning_str)
logging.warning(warning_str)
error_string = f"Index name {inp_d['index_name']} not found in barseq3 " + \
f"index file at {inp_d['bs3_fp']}"
# Getting out of program.
raise Exception(error_string)
#new_d['nPreExpectedMin'] = 16
#new_d['nPreExpectedMax'] = 19
else:
#length of tabMatch is exactly 1
row = tabMatch[0]
inp_d['index2'] = row['index2'] #str
inp_d['index2At'] = int(row['nN']) # (Number of ns before)
nPE_preval = inp_d['index2At'] + 6 + 9
new_d['nPreExpectedMin'] = nPE_preval - 2
new_d['nPreExpectedMax'] = nPE_preval + 2
return new_d
# NOT IN USE
def MyGrep(hash_list, index_name, iname):
"""
hash_list: (list<subdict>)
subdict: (dict)
header -> value
index_name: (str) key in subdict that maps to index names
iname: (str) the index name we want.
Returns:
list<dict> minimized such that only dicts with wanted index name
are in it.
"""
new_list = []
for h in hash_list:
if h[index_name] == iname:
new_list.append(h)
return new_list
# fp is filepath, required is a list of required headers
# returns a list of hashmaps
def ReadTable(fp, required):
"""
fp: (str) Filepath to TSV file
required: (list<str>) A list of required headers in string format.
Returns:
rows: list<dicts>
each dict is a map of headers to values, which are all strings
In the case of index TSV reading- looks for index_name, index2 and nN
"""
FH = open(fp, "r")
header_line = FH.readline().rstrip()
header_list = header_line.split("\t")
# columns map
cols_map = {}
for i in range(len(header_list)):
cols_map[header_list[i]] = i
for field in required:
if field not in cols_map:
raise Exception("No field {} in {}".format(
field, fp))
rows = []
c_line = FH.readline()
while c_line != "":
line = c_line.rstrip()
new_line_list = line.split("\t")
if len(new_line_list) != len(header_list):
raise Exception("Wrong number of columns in:\n{} \
\n in {}".format(line, fp))
row_dict = {}
for i in range(len(new_line_list)):
row_dict[header_list[i]] = new_line_list[i]
rows.append(copy.deepcopy(row_dict))
c_line = FH.readline()
return rows
# Deprecated
def IndexFileOrInameToPrefixInfo(inp_d):
"""
There are two options: Either an index file path to get index information,
or an index name, in which case prefix is a list with length 1
Args:
inp_d: (dict)
[indexfile_fp] (str)
OR
index_name: (str)
"""
# Report String doesn't exist yet
if "index_name" in inp_d:
logging.info("Recognized index type as index name")
# nLeading (int), Some sequence (str), index_name (str)
prefix = [[0, "", inp_d['index_name']]]
prefixNames = [inp_d['index_name']]
else:
raise Exception("Program only works with index_names now,"
" index file deprecated.")
#updating inp_d
inp_d['prefix'] = prefix
inp_d['prefixNames'] = prefixNames
return inp_d
def InitReport(inp_d):
"""
Args:
inp_d: (dict)
fastq_fp: (str)
nOff: (dict)
ints (18-23) mapping to number of times (int) this distance
occured between preseq and postseq within the reads
codes: (dict)
barcode (str) -> prefixlist
prefixlist: list<int>
such that at the index of a DNAindex from the list 'prefix',
the number of times that barcode is found with that DNAindex
nReads: (int)
nMulti: (int)
[index2]: (str)
[nWrongIndex2]: (int)
Returns:
Rd: (d) Report Dict
fastq_fp: s
nReads: i
nOff: d
int -> int
nUniqBC: i
nMultiplexed: i
[nWrongIndex2]: i
[nWrongI2Perc]: f (percent)
[nWrongPrePos]: i
[nWrongPrePosPerc]: f (percent)
[nOnce]: (i)
[nCases]: i
[nOff1Reads]: i
[fOff1]: f
"""
# Report Dict
Rd = {}
# Total differences between preseq and postseqs found
nOffTot = sum(inp_d['nOff'].values())
# Number of unique barcodes
nUniqBC = len(inp_d['codes'].keys())
stringed_nOff = {str(x):inp_d['nOff'][x] for x in inp_d['nOff'].keys()}
Rd["fastq_fp"] = inp_d["fastq_fp"]
Rd['nReads'] = inp_d['nReads']
Rd['nOff'] = stringed_nOff
Rd['nOffTot'] = nOffTot
Rd['nUniqBC'] = nUniqBC
Rd['nMultiplexed'] = inp_d['nMulti']
offby1vals = False
if "nCases" in inp_d:
offby1vals = True
for x in ["nCases", "nOff1Reads", "fOff1"]:
if x in inp_d:
Rd[x] = inp_d[x]
Rd["offby1vals"] = offby1vals
if inp_d['nReads'] > 0 and "index2" in inp_d:
Rd['nWrongIndex2'] = inp_d['nWrongIndex2']
Rd['nWrongI2Perc'] = (100*inp_d['nWrongIndex2']/inp_d['nReads'])
if inp_d['nReads'] > inp_d['nWrongIndex2']:
Rd['nWrongPrePos'] = inp_d['nWrongPrePos']
Rd['nWrongPrePosPerc'] = 100*(inp_d['nWrongPrePos']/(inp_d['nReads'] - inp_d['nWrongIndex2'] ))
if 1 in inp_d['nPerCount']:
Rd["nOnce"] = inp_d['nPerCount'][1]
return Rd
def ParseFastqInput(inp_d):
"""
Args:
inp_d: (dict) Necessary keys: (There are others unused)
fastq_fp: (str) path to FASTQ file
maxReads: (int) A limit on number of reads from FASTQ
index_name: (str) Name of the index
[index2]: (str) A sequence of length 6 (if protocol_type == 'bs3')
[index2At]: (int) location of index2 (if protocol_type == 'bs3')
debug: (bool)
(For FindBarcode:)
nPreExpectedMin: (int)
nPreExpectedMax: (int)
minQuality: (int)
Returns:
nWrongPrePos (int):
nWrongIndex2 (int):
nPostSeqUsed (int): How many times we used the postSeq while finding
the read.
nReads (int): Total number of reads
nMulti (int): Number of reads with the prefix found (should be many).
nOff (dict): mapping from number 18-24 to number of times that offset seen.
codes (dict): barcode mapped to number of times it was found.
Description:
In this function we parse the FASTQ file.
In the case of bs3 (BarSeq3) we have a
key called 'index2' which is mapped
to a DNA sequence of length 6, and 'index2At'
which points to the expected location of index2
within a read.
If, within a read, we don't find index2 at
its expected location, then that's noted as an error,
and we add a number to the variable 'nWrongIndex2'.
"""
nWrongPrePos = 0
nWrongIndex2 = 0
nPostSeqUsed = 0
nReads = 0
nMulti = 0 # count with prefix identified
nOff = {i:0 for i in range(18,24)}
codes = {} #barcode maps to number of times seen
# FastQ File Handle
FQ_FH = open(inp_d['fastq_fp'], "r")
# current read name
c_readname = FQ_FH.readline()
line_num = 1
crnt_time = time.time()
while c_readname != '':
# We keep track of the number of reads
nReads += 1
# We extract the read info from the file handle
read_name = c_readname.rstrip()
seq = FQ_FH.readline().rstrip()
break_line = FQ_FH.readline().rstrip()
quality = FQ_FH.readline().rstrip()
CheckRead(read_name, seq, break_line, quality,
inp_d['fastq_fp'], line_num)
line_num += 4
if inp_d['maxReads'] is not None and (
nReads >= inp_d['maxReads']):
break
# Index 2 is a DNA sequence of length 6 - Only exists with bs3
# protocol under certain conditions
if "index2" in inp_d:
part = seq[inp_d['index2At']: inp_d['index2At'] + len(inp_d['index2'])]
if part != inp_d['index2']:
nWrongIndex2 += 1
c_readname = FQ_FH.readline()
continue
nMulti += 1
'''
if "index_name" in inp_d:
iPrefix = 0
else:
# Only if not multiplexed
iPrefix = FindPrefix(seq, inp_d['prefix'],
inp_d['debug']) # returns match (int) or -1
'''
#In most cases, index_name is used, so iPrefix is 0,
# so we get nLeading = 0, indexseq = "", prefixName is index_name
nLeading, indexseq, prefixName = [0, "", inp_d["index_name"]]
# Meaning that offset = nLeading + len("") = 0 + 0 = 0
#offset = nLeading + len(indexseq)
# barcode is str barcode, off is distance from start of barcode to start of postseq
# i.e. distance between end of preseq and beginning of postseq.
barcode, off, postseqIgnored = FindBarcode(seq, quality, inp_d)
if not postseqIgnored:
nPostSeqUsed += 1
if (barcode is None and off is not None and off >=0):
nWrongPrePos += 1
if nWrongPrePos >= 200 and nWrongPrePos >= (0.1 * nReads):
raise Exception("Over 10% of reads have the wrong spacing ( \
not {}:{}) to the pre-sequence ({} \
of {} so far).\n Maybe the wrong \
protocol indicated (i.e., 'n25' or 'bs3')?\n".format(
inp_d["nPreExpectedMin"],
inp_d["nPreExpectedMax"],
nWrongPrePos,
nReads))
if barcode is None:
c_readname = FQ_FH.readline()
continue
# We count the number of times a distance between preseq and postseq occurs
nOff[off] += 1
if off != 20:
# Barcode length is not 20
c_readname = FQ_FH.readline()
continue
if barcode in codes:
codes[barcode] += 1
else:
codes[barcode] = 1
if nReads % 1000000 == 0:
print("Read {} Reads so far".format(nReads))
new_time = time.time()
time_dif = int(new_time - crnt_time)
print("Time: {} seconds".format(time_dif))
crnt_time = new_time
# Prepare for next read loop
c_readname = FQ_FH.readline()
FQ_FH.close()
inp_d['nWrongPrePos'] = nWrongPrePos
inp_d['nWrongIndex2'] = nWrongIndex2
inp_d['nPostSeqUsed'] = nPostSeqUsed
inp_d['nReads'] = nReads
inp_d['nMulti'] = nMulti
inp_d['nOff'] = nOff
inp_d['codes'] = codes
#DEBUG
for x in ["nWrongPrePos", "nWrongIndex2", "nReads", "nMulti"]:
print(x + ": " + str(inp_d[x]))
return inp_d
# Deprecated!
# seq is DNA sequence (str)
# indexes is a list of lists, internal lists are [nLeading, indexseq, name],
# where nLeading is an int, indexseq is str, name is str
# debug in inp_d, True or False
# Deprecated!
def FindPrefix(seq, indexes, debug):
"""
Note this function is only run if the FASTQ file
isn't multiplexed and all are in one.
Args:
seq: (str) DNA sequence (from FASTQ)
indexes: list<list> internal lists are [nLeading, indexseq, name]
([int, str, str])
the list is the same as the variable 'prefix'
debug: (bool)
Returns:
An int, the index within the list of indexes which
matches this current index.
"""
matches = []
for i in range(len(indexes)):
nLeading, indexseq, name = indexes[i]
if (seq[nLeading:(nLeading + len(indexseq))] == indexseq):
matches.append(i)
if len(matches) == 1:
return matches[0]
elif len(matches) > 1:
logging.critical("More than one match for DNA sequence:\n {}\n with indexes".format(
seq))
if debug:
logging.info("No prefix for {}\n".format(seq))
return -1
def UpdateCodesiPrefix(codes_dict, barcode):
"""
Args:
codes_dict: (dict)
barcode (str) -> prefixlist
prefixlist: list<int>
such that at the index of a DNAindex from the list 'prefix',
the number of times that barcode is found with that DNAindex
is being updated
barcode: (str)
"""
return codes_dict
def IndexFileToPrefixInfo(index_fp):
"""
This function does not make sense given extant indexfiles
Args:
index_fp: (str) filepath to index file (TSV) with two columns
Returns:
ret_d: (dict)
"report_str": (str)
"prefixNames": list<str>,
"prefix": list<[int, str, str]>
[nLeading, indexseq, name] e.g. [
"""
IX_FH = open(index_fp, "r")
header_line = IX_FH.readline()
c_line = "placeholder"
# prefix is an important list that holds [[nLeading i, indexseq s, name s],...]
# nLeading is number of n's before index
prefix = []
line_num = 0
while c_line != "":
c_line = IX_FH.readline().rstrip()
line_num += 1
line_split = c_line.split('\t')
if len(line_split) > 2:
raise Exception("In indexfile, found a line that has more than "\
+ "2 tsvs.\n Filename: {} Line Number: {}".format(
index_fp, line_num))
#Note name & index are in form H1, ATCACGAG
name, index = line_split
# What does this account for?
if (re.search(r'name', name ,re.IGNORECASE)):
continue
nLeading = None
indexseq = None
match = re.search(r'^([nN]*)([ACGT]+)$',index)
if not match:
raise Exception("Invalid index sequence {}".format(index))
else:
nLeading = len(match[0])
indexseq = match[1]
if (nLeading == None ) or (indexseq == None) or (name == ''):
raise Exception(line)
prefix.append([nLeading, indexseq, name])
IX_FH.close()
report_str = "Read {} indices from {}\n".format(len(prefix),index_fp)
prefixNames = [x[2] for x in prefix]
return {
"report_str": report_str,
"prefixNames": prefixNames,
"prefix": prefix
}
#seq str -
#quality str
#offset int, usually 0
def FindBarcode(seq, quality, inp_d, offset=0):
"""
Args:
seq: (str) Sequence from FASTQ Read
quality: (str) Quality from FastQ Read
inp_d: (dict) Required keys:
preseq: (str) DNA Sequence
postseq: (str) DNA Sequence
nPreExpectedMin: (int)
nPreExpectedMax: (int)
minQuality: (int)
debug: (bool)
offset: (int) Represents location after nLeading and index sequence
preseq often: 'CAGCGTACG'
postseq often: 'AGAGACCTC'
How function works:
Note: We assume FASTQs are demultiplexed so that the important
part of the sequence is the sequence given, meaning that
offset = 0.
We get useful part of sequence and quality by taking original sequence and
starting from location after leading n's and index sequence.
Then we find the index of presequence defined
earlier in the program within the useful part of the sequence and assign it's value
to preseq_pos. preseq_pos must be within the nPreExpectedMin and
nPreExpectedMax index values of the true sequence, or it's not viable
and we return [None, None].
Then we assign barcode to where the presequence ends to 20 indeces
after that. If the entire sequence
is too short and we don't get a full barcode, then we return
[None, None].
Then we check for the postsequence in the true sequence. If the length
of the useful sequence is less than the sum of the barcode (20) and the
presequence and the index of the presequence and the postsequence, we
try a shorter postsequence of length 4, if that's not found we
claim it's too short, make postsequence "" and continue with function.
foundEnd: foundEnd is the distance between the end of the presequence
and the beginning of the postsequence if it's found. If the
postsequence is nothing (will this ever be the case in KBase?) then
foundEnd is automatically 20
Returns: [barcode, foundEnd, postseqIgnored]
barcode (str): String of length 20, the barcode
foundEnd (int): Difference between preseq and postseq
postseqIgnored (bool): Whether or not we actually used postseq.
True means not used.
"""
seq2 = seq[offset:]
quality2 = quality[offset:]
preseq = inp_d['preseq']
# The following gives -1 if not found, index of beginning if found
preseq_pos = seq2.find(preseq)
#Bad cases
if preseq_pos == -1 or preseq_pos < inp_d['nPreExpectedMin'] or \
preseq_pos > inp_d['nPreExpectedMax']:
if preseq_pos != -1:
if inp_d['debug']:
warning_str = "seq2 {} has invalid index-of-preseq: {}\n".format(
seq2, preseq_pos)
#inp_d["report_dict"]["warnings"].append(warning_str)
logging.warning(warning_str)
return [None, preseq_pos, True] # report that spacing was wrong
return [None, None, True]
#Note: Below line does not throw error if end index > len(seq2)
barcode = seq2[preseq_pos + len(preseq): preseq_pos + len(preseq) + 20]
if not (len(barcode) == 20 and re.search(r'^[A-Z]+$',barcode)):
# Barcode could be too short - meaning read is too short.
#note barcodes with ambiguous sequences are ignored
# we might want to allow one N in the future
if inp_d['debug']:
warning_str = "seq2 {} has invalid barcode sequence {}\n".format(
seq2, barcode)
#inp_d["report_dict"]["warnings"].append(warning_str)
logging.warning(warning_str)
return [None, None, True]
crnt_postseq = inp_d['postseq']
if len(seq2) < preseq_pos + len(preseq) + 20 + len(crnt_postseq):
crnt_postseq = crnt_postseq[:4] #first 4 characters.
if inp_d['debug']:
warning_str = "Using postseq {}\n".format(crnt_postseq)
#inp_d["report_dict"]["warnings"].append(warning_str)
logging.warning(warning_str)
#There might be redundant code here in MultiCodes.pl which checks
# above length (16 lines above) Redundant code left out of this file.
#We check again with a shorter crnt_postseq
if len(seq2) < preseq_pos + len(preseq) + 20 + len(crnt_postseq):
if inp_d['debug']:
warning_str = "Ignoring postseq, too short\n"
#inp_d["report_dict"]["warnings"].append(warning_str)
logging.warning(warning_str)
crnt_postseq = ""
foundEnd = -1
if crnt_postseq == "":
foundEnd = 20
postseqIgnored = True
else:
postseqIgnored = False
#check 20 first in case end of barcode matches post-seq (AGAG issue)
for off in [20,19,21,18,22]:
start_slice = preseq_pos + len(preseq) + off
end_slice = start_slice + len(crnt_postseq)
if (seq2[start_slice:end_slice] == crnt_postseq):
foundEnd = off
break
if foundEnd == -1:
# Could not find postseq
if inp_d['debug']:
warning_str = "seq2 \n {} \n barcode \n{}\n postseq not found\n".format(
seq2, barcode)
#inp_d["report_dict"]["warnings"].append(warning_str)
logging.warning(warning_str)
return [None,None, True]
if inp_d['minQuality'] > 0:
# the sanger code for !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJ
barqual = quality2[preseq_pos + len(preseq): preseq_pos + len(preseq) \
+ 20]
# quality score is encoded as 33+
scores = [ord(c) - 33 for c in barqual]
for score in scores:
if (score < 0 or score > 100):
raise Exception("Invalid score {} from barcode {} " \
+ "quality {}".format(score, barcode, barqual))
if score < inp_d['minQuality']:
if inp_d['debug']:
warning_str = "Low quality {} for barcode {} in " \
+ "{}\n".format(score, barcode, seq2)
#inp_d["report_dict"]["warnings"].append(warning_str)
logging.warning(warning_str)
return [None,None, True]
return [barcode, foundEnd, postseqIgnored]
def CheckRead(read_name, seq, break_line, quality, fastq_fp, line_num):
"""
Args are all fastq strings without ending linebreak
line_num refers to line number of read_name (int)
"""
if not read_name[0] == "@":
raise Exception("Read name does not start with @, line # {}\n File: {}".format(
line_num, fastq_fp))
for x in seq.upper():
if x not in ["A","C","T","G","N"]:
raise Exception("Sequence value {} not recognized. Line # {}\n File: {}".format(
x, line_num + 1, fastq_fp))
if not break_line[0] == "+":
raise Exception("Break line not '+'. Instead '{}'. Line # {}\n File: {}".format(
break_line[0],line_num + 2, fastq_fp))
if not len(quality) == len(seq):
raise Exception("Quality line wrong length. Lines # {}\n File: {}".format(
line_num + 3, fastq_fp))
#baseseq (str)
# returns all variants on sequence
def GetVariants(baseseq):
out = []
baseseq = baseseq.upper()
for i in range(len(baseseq)):
pre = baseseq[0:i]
char = baseseq[i:i+1]
post = baseseq[i+1:]
if not (char in ["A","C","G","T"]):
continue
for newchar in ["A","C","G","T"]:
if not newchar == char:
out.append(pre + newchar + post)
return out
|
import random
import math
from typing import List, Dict
"""
This file can be a nice home for your move logic, and to write helper functions.
"""
def avoid_my_neck(my_head: Dict[str, int], my_body: List[dict],
possible_moves: List[str]) -> List[str]:
"""
my_head: Dictionary of x/y coordinates of the Battlesnake head.
return: The list of remaining possible_moves, with the 'neck' direction removed
"""
my_neck = my_body[
1] # The segment of body right after the head is the 'neck'
if my_neck["x"] < my_head["x"]: # my neck is left of my head
possible_moves.remove("left")
elif my_neck["x"] > my_head["x"]: # my neck is right of my head
possible_moves.remove("right")
elif my_neck["y"] < my_head["y"]: # my neck is below my head
possible_moves.remove("down")
elif my_neck["y"] > my_head["y"]: # my neck is above my head
possible_moves.remove("up")
return possible_moves
#find the bounds of the arena
def get_walls(board_height, board_width):
walls = []
y = -1
while y <= board_height:
walls.append({'x': -1, 'y': y})
walls.append({'x': board_width, 'y': y})
y += 1
x = -1
while x <= board_width:
walls.append({'x': x, 'y': -1})
walls.append({'x': x, 'y': board_height})
x += 1
return walls
#avoid impact with certain co-ordinates
def avoid_impact(my_head, positions, possible_moves):
for pos in positions:
for move in possible_moves:
if move == 'up':
if my_head['x'] == pos['x'] and my_head['y'] + 1 == pos['y']:
possible_moves.remove('up')
elif move == 'down':
if my_head['x'] == pos['x'] and my_head['y'] - 1 == pos['y']:
possible_moves.remove('down')
elif move == 'right':
if my_head['x'] + 1 == pos['x'] and my_head['y'] == pos['y']:
possible_moves.remove('right')
else:
if my_head['x'] - 1 == pos['x'] and my_head['y'] == pos['y']:
possible_moves.remove('left')
return possible_moves
#get all the moves that a snake's head can move to
def get_head_moves(head):
moves = []
#right
moves.append({'x': head['x'] + 1, 'y': head['y']})
#left
moves.append({'x': head['x'] - 1, 'y': head['y']})
#up
moves.append({'x': head['x'], 'y': head['y'] + 1})
#down
moves.append({'x': head['x'], 'y': head['y'] - 1})
return moves
#get all the moves a snake's tail can make
def get_tail_moves(tail):
moves = []
#right
moves.append({'x': tail['x'] + 1, 'y': tail['y']})
#left
moves.append({'x': tail['x'] - 1, 'y': tail['y']})
#up
moves.append({'x': tail['x'], 'y': tail['y'] + 1})
#down
moves.append({'x': tail['x'], 'y': tail['y'] - 1})
return moves
#get the distance between two points
def get_distance(point1, point2):
distance = math.sqrt((point1['x'] - point2['x'])**2 +
(point1['y'] - point2['y'])**2)
return distance
#locate the closest food- can also be used to find the closest snake head
def get_closest_food(head, foods, hazards):
closest = {}
closest_distance = 99999
for food in foods:
if food != head:
distance = get_distance(head, food)
#add to distance if food in hazard
if food in hazards:
if distance > 2:
distance += 10
if distance < closest_distance:
closest_distance = distance
closest = {'x': food['x'], 'y': food['y']}
return closest
#find the optimal move towards food, or sometimes another snake's head
def move_to_food(head, food, possible_moves):
best_dist = 9999
best_move = 'none'
for move in possible_moves:
if move == 'up':
distance = get_distance({'x': head['x'], 'y': head['y'] + 1}, food)
if distance < best_dist:
best_dist = distance
best_move = 'up'
elif move == 'down':
distance = get_distance({'x': head['x'], 'y': head['y'] - 1}, food)
if distance < best_dist:
best_dist = distance
best_move = 'down'
elif move == 'right':
distance = get_distance({'x': head['x'] + 1, 'y': head['y']}, food)
if distance < best_dist:
best_dist = distance
best_move = 'right'
elif move == 'left':
distance = get_distance({'x': head['x'] - 1, 'y': head['y']}, food)
if distance < best_dist:
best_dist = distance
best_move = 'left'
return best_move
#a recursive floodfill algorithm
#used to find how many free spaces there are if a snake makes a given move, and can be applied at various search depths
def flood_recursive(start_pos, obstacles, width, height, depth, hazards):
free_spaces = 0
checked = []
start_depth = depth
def fill(pos, obstacles, depth, hazards, start_depth):
nonlocal free_spaces
nonlocal checked
print(pos)
#stop searching if there are over 70 free spaces as this is clearly enough
if free_spaces > 70:
return
#if at max search depth then stop
if depth == 0:
#last_move = []
print("max depth reached")
return
#if the square is occupied or has been checked, return
if pos in obstacles:
#print("obstacle hit")
return
elif pos in checked:
#print("already checked")
return
else:
checked.append(pos)
#try to avoid hazards that are not instant killers by awarding less than 1 free space to these locations
if pos in hazards:
if depth == start_depth:
free_spaces = free_spaces -0.5
elif depth == start_depth - 1:
free_spaces = free_spaces +0.2
else:
free_spaces = free_spaces + 0.25
elif pos['x'] == 0 or pos['x'] == 10 or pos['y'] == 0 or pos[
'y'] == 10:
if depth == start_depth:
free_spaces = free_spaces + 0.5
else:
free_spaces = free_spaces + 0.75
elif pos['x'] >= 4 and pos ['x'] <= 6 and pos['y'] >= 4 and pos['y'] <=6 and depth == start_depth or depth == start_depth - 1:
free_spaces = free_spaces +1.8
elif depth== start_depth and pos['x'] == 0 or pos['x'] == 10 or pos['y'] == 0 or pos['y'] == 10:
free_spaces = free_spaces - 0.5
else:
free_spaces = free_spaces + 1
#print(free_spaces)
#all next possible moves
neighbours = [{
'x': pos['x'] + 1,
'y': pos['y']
}, {
'x': pos['x'] - 1,
'y': pos['y']
}, {
'x': pos['x'],
'y': pos['y'] + 1
}, {
'x': pos['x'],
'y': pos['y'] - 1
}]
#floodfill each neighbour
for n in neighbours:
#if neighbour is not out of bounds
if 0 <= n['x'] < width and 0 <= n[
'y'] < height and n not in checked:
fill(n, obstacles, depth - 1, hazards, start_depth)
fill(start_pos, obstacles, depth, hazards, start_depth)
#print(free_spaces)
return free_spaces
#choose which move to make
def choose_move(data: dict) -> str:
"""
data: Dictionary of all Game Board data as received from the Battlesnake Engine.
For a full example of 'data', see https://docs.battlesnake.com/references/api/sample-move-request
return: A String, the single move to make. One of "up", "down", "left" or "right".
Use the information in 'data' to decide your next move. The 'data' variable can be interacted
with as a Python Dictionary, and contains all of the information about the Battlesnake board
for each move of the game.
"""
my_head = data["you"][
"head"] # A dictionary of x/y coordinates like {"x": 0, "y": 0}
my_body = data["you"][
"body"] # A list of x/y coordinate dictionaries like [ {"x": 0, "y": 0}, {"x": 1, "y": 0}, {"x": 2, "y": 0} ]
print(
f"~~~ Turn: {data["turn"]} Game Mode: {data["game"]["ruleset"]["name"]} ~~~"
)
print(f"All board data this turn: {data}")
print(f"My Battlesnakes head this turn is: {my_head}")
print(f"My Battlesnakes body this turn is: {my_body}")
#the move options
original_moves = ["up", "down", "left", "right"]
possible_moves = ["up", "down", "left", "right"]
# Don't allow your Battlesnake to move back in on it's own neck
possible_moves = avoid_my_neck(my_head, my_body, possible_moves)
print('After neck check: ' + str(possible_moves))
#edges of board
board_height = data['board']['height']
board_width = data['board']['width']
walls = get_walls(board_height, board_width)
#avoid walls
possible_moves = avoid_impact(my_head, walls, possible_moves)
print('After wall check' + str(possible_moves))
#if only one move avoids a wall then play it
if len(possible_moves) == 1:
return possible_moves[0]
#avoid own head
new_possible_moves = avoid_impact(my_head, my_body[:-1], possible_moves)
if new_possible_moves != []:
possible_moves = new_possible_moves
print("After own body check: " + str(possible_moves))
#if there is only one possible move just play it
if len(possible_moves) == 1:
return possible_moves[0]
print(possible_moves)
old_possible_moves = []
for direction in possible_moves:
old_possible_moves.append(direction)
# TODO: Using information from 'data', don't let your Battlesnake pick a move that would collide with another Battlesnake
snakes = data['board']['snakes']
snakes_locations = []
enemy_pos_heads = []
enemy_pos_tails = []
for snake in snakes:
if snake['head'] != my_head:
head_moves = get_head_moves(snake['head'])
for food in data['board']['food']:
food_found = False
if food in head_moves:
food_found = True
if food_found != True:
#non-food tails will not be obstacles
enemy_pos_tails.append(snake['body'][-1])
if food_found == True:
new_possible_moves = avoid_impact(my_head, snake["body"],
possible_moves)
else:
new_possible_moves = avoid_impact(my_head, snake["body"][:-1],
possible_moves)
if len(new_possible_moves) != 0:
possible_moves = new_possible_moves
else:
return random.choice(old_possible_moves)
print("After enemy snake:" + str(possible_moves))
old_possible_moves = []
for direction in possible_moves:
old_possible_moves.append(direction)
snakes_locations.extend(snake['body'])
#remove head moves if small
if data['you']['length'] <= snake['length'] + 1:
#print("head moves: "+ str(head_moves))
new_possible_moves = avoid_impact(my_head, head_moves,
possible_moves)
snakes_locations.extend(head_moves)
enemy_pos_heads.extend(head_moves)
print(len(new_possible_moves))
if len(new_possible_moves) != 0:
possible_moves = new_possible_moves
else:
return random.choice(old_possible_moves)
#tail_moves = get_tail_moves(snake['body'][-1])
#new_possible_moves = avoid_impact(my_head,tail_moves, possible_moves)
#if new_possible_moves != []:
# possible_moves = new_possible_moves
print(possible_moves)
# TODO: Using information from 'data', make your Battlesnake move towards a piece of food on the board
#go for food at the start of the game and when low on health
hazards = data['board']['hazards']
food_move = 'none'
if data['turn'] <= 20 or data['you']['health'] < 60 or data['you'][
'length'] < 9:
closest_food = get_closest_food(my_head, data['board']['food'],
hazards)
food_move = move_to_food(my_head, closest_food, possible_moves)
# Choose a random direction from the remaining possible_moves to move in, and then return that move
print(possible_moves)
#desperation food move
if food_move != 'none' and data['you']['health'] < 20:
move = food_move
else:
#perform a dfs floodfill in each possible direction to find which move gets the most free space/if the food is safe to get
obstacles = []
is_biggest = False
for enemy in snakes:
if enemy['head']!= my_head:
#attack other snakes if bigger by at least 2
if enemy['length'] < data['you']['length'] + 1:
is_biggest = True
else:
is_biggest = False
if enemy_pos_heads != [] and is_biggest != True:
for pos in enemy_pos_heads:
neighbours = [{
'x': pos['x'] + 1,
'y': pos['y']
}, {
'x': pos['x'] - 1,
'y': pos['y']
}, {
'x': pos['x'],
'y': pos['y'] + 1
}, {
'x': pos['x'],
'y': pos['y'] - 1
}]
obstacles.extend(neighbours)
if data['turn'] < 20 or data['you']['length'] < 9:
depth = 9
food_space_val = data['you']['length'] + 5
attack_space_val = 100
else:
depth = 13
if data['you']['length'] < 15:
food_space_val = 15
attack_space_val = 10
else:
food_space_val = data['you']['length'] + 2
attack_space_val = food_space_val -7
obstacles.extend(walls)
obstacles.extend(my_body)
obstacles.extend(snakes_locations)
#if there is no food near the head then the tail is not an obstacle
my_head_moves = get_head_moves(my_head)
food_found = False
for food in data['board']['food']:
if food in my_head_moves:
food_found = True
if food_found == False:
obstacles.remove(my_body[-1])
#remove tails that will not be there in the future
for tail in enemy_pos_tails:
if tail in obstacles:
obstacles.remove(tail)
move = my_head
right_spaces = -100
left_spaces = -100
up_spaces = -100
down_spaces = -100
for direction in possible_moves:
if direction == "right":
try_move = {'x': my_head['x'] + 1, 'y': my_head['y']}
print("checking right")
right_spaces = flood_recursive(try_move, obstacles,
board_width, board_height,
depth, hazards)
elif direction == "left":
try_move = {'x': my_head['x'] - 1, 'y': my_head['y']}
print("checking left")
left_spaces = flood_recursive(try_move, obstacles, board_width,
board_height, depth, hazards)
elif direction == "up":
print("checking up")
try_move = {'x': my_head['x'], 'y': my_head['y'] + 1}
up_spaces = flood_recursive(try_move, obstacles, board_width,
board_height, depth, hazards)
elif direction == "down":
print("checking down")
try_move = {'x': my_head['x'], 'y': my_head['y'] - 1}
down_spaces = flood_recursive(try_move, obstacles, board_width,
board_height, depth, hazards)
print("Right spaces: " + str(right_spaces))
print("Left spaces: " + str(left_spaces))
print("Up spaces: " + str(up_spaces))
print("Down spaces: " + str(down_spaces))
#try and attack if health is greater than 40 and you are the biggest snake
if is_biggest == True and data['you']['health'] > 40:
bravery = 2
dist_for_interest = 8
closest_prey = get_closest_food(my_head, snakes_locations, hazards)
attack_move = move_to_food(my_head, closest_prey, possible_moves)
if attack_move == 'right':
attack_dir = {'x': my_head['x']+1, 'y': my_head['y']}
elif attack_move == 'left':
attack_dir = {'x': my_head['x']-1, 'y': my_head['y']}
elif attack_move == 'up':
attack_dir = {'x': my_head['x'], 'y': my_head['y']+1}
else:
attack_dir = {'x': my_head['x'], 'y': my_head['y']-1}
if my_head['x'] == 0 or my_head['x'] == board_width - 1 or my_head['y'] == 0 or my_head['y'] == board_height - 1 or attack_dir['x'] == 0 or attack_dir['x'] == board_width -1 or attack_dir['y'] == 0 or attack_dir['y'] == board_height -1:
if get_distance(my_head, closest_prey) < bravery:
food_space_val = attack_space_val +8
food_move = attack_move
else:
if get_distance(my_head, closest_prey) < dist_for_interest:
food_space_val = attack_space_val +8
food_move = attack_move
#if there is space surrounding food then go for it
if right_spaces >= food_space_val and food_move == 'right' and {'x': my_head['x']+ 1, 'y': my_head['y']} not in hazards:
move = 'right'
print('floodfill right food priority')
return move
elif left_spaces >= food_space_val and food_move == 'left' and {'x': my_head['x']- 1, 'y': my_head['y']} not in hazards:
move = 'left'
print('floodfill left food priority')
return move
elif up_spaces >= food_space_val and food_move == 'up' and {'x': my_head['x'], 'y': my_head['y']+1} not in hazards:
move = 'up'
print('floodfill up food priority')
return move
if down_spaces >= food_space_val and food_move == 'down' and {'x': my_head['x'], 'y': my_head['y']-1} not in hazards:
move = 'down'
print('floodfill down food priority')
return move
best_move = max(right_spaces, left_spaces, up_spaces, down_spaces)
if best_move == right_spaces and 'right' in possible_moves:
move = 'right'
print("floodfilled right")
elif best_move == left_spaces and 'left' in possible_moves:
move = 'left'
print("floodfilled left")
elif best_move == up_spaces and 'up' in possible_moves:
move = 'up'
print("floodfilled up")
elif best_move == down_spaces and 'down' in possible_moves:
move = 'down'
print("floodfilled down")
else:
if len(possible_moves) > 0:
move = random.choice(possible_moves)
print("random possible")
else:
move = random.choice(original_moves)
print("random desperation")
# TODO: Explore new strategies for picking a move that are better than random
print(
f"{data["game"]["id"]} MOVE {data["turn"]}: {move} picked from all valid options in {possible_moves}"
)
return move
| import random
import math
from typing import List, Dict
"""
This file can be a nice home for your move logic, and to write helper functions.
"""
def avoid_my_neck(my_head: Dict[str, int], my_body: List[dict],
possible_moves: List[str]) -> List[str]:
"""
my_head: Dictionary of x/y coordinates of the Battlesnake head.
return: The list of remaining possible_moves, with the 'neck' direction removed
"""
my_neck = my_body[
1] # The segment of body right after the head is the 'neck'
if my_neck["x"] < my_head["x"]: # my neck is left of my head
possible_moves.remove("left")
elif my_neck["x"] > my_head["x"]: # my neck is right of my head
possible_moves.remove("right")
elif my_neck["y"] < my_head["y"]: # my neck is below my head
possible_moves.remove("down")
elif my_neck["y"] > my_head["y"]: # my neck is above my head
possible_moves.remove("up")
return possible_moves
#find the bounds of the arena
def get_walls(board_height, board_width):
walls = []
y = -1
while y <= board_height:
walls.append({'x': -1, 'y': y})
walls.append({'x': board_width, 'y': y})
y += 1
x = -1
while x <= board_width:
walls.append({'x': x, 'y': -1})
walls.append({'x': x, 'y': board_height})
x += 1
return walls
#avoid impact with certain co-ordinates
def avoid_impact(my_head, positions, possible_moves):
for pos in positions:
for move in possible_moves:
if move == 'up':
if my_head['x'] == pos['x'] and my_head['y'] + 1 == pos['y']:
possible_moves.remove('up')
elif move == 'down':
if my_head['x'] == pos['x'] and my_head['y'] - 1 == pos['y']:
possible_moves.remove('down')
elif move == 'right':
if my_head['x'] + 1 == pos['x'] and my_head['y'] == pos['y']:
possible_moves.remove('right')
else:
if my_head['x'] - 1 == pos['x'] and my_head['y'] == pos['y']:
possible_moves.remove('left')
return possible_moves
#get all the moves that a snake's head can move to
def get_head_moves(head):
moves = []
#right
moves.append({'x': head['x'] + 1, 'y': head['y']})
#left
moves.append({'x': head['x'] - 1, 'y': head['y']})
#up
moves.append({'x': head['x'], 'y': head['y'] + 1})
#down
moves.append({'x': head['x'], 'y': head['y'] - 1})
return moves
#get all the moves a snake's tail can make
def get_tail_moves(tail):
moves = []
#right
moves.append({'x': tail['x'] + 1, 'y': tail['y']})
#left
moves.append({'x': tail['x'] - 1, 'y': tail['y']})
#up
moves.append({'x': tail['x'], 'y': tail['y'] + 1})
#down
moves.append({'x': tail['x'], 'y': tail['y'] - 1})
return moves
#get the distance between two points
def get_distance(point1, point2):
distance = math.sqrt((point1['x'] - point2['x'])**2 +
(point1['y'] - point2['y'])**2)
return distance
#locate the closest food- can also be used to find the closest snake head
def get_closest_food(head, foods, hazards):
closest = {}
closest_distance = 99999
for food in foods:
if food != head:
distance = get_distance(head, food)
#add to distance if food in hazard
if food in hazards:
if distance > 2:
distance += 10
if distance < closest_distance:
closest_distance = distance
closest = {'x': food['x'], 'y': food['y']}
return closest
#find the optimal move towards food, or sometimes another snake's head
def move_to_food(head, food, possible_moves):
best_dist = 9999
best_move = 'none'
for move in possible_moves:
if move == 'up':
distance = get_distance({'x': head['x'], 'y': head['y'] + 1}, food)
if distance < best_dist:
best_dist = distance
best_move = 'up'
elif move == 'down':
distance = get_distance({'x': head['x'], 'y': head['y'] - 1}, food)
if distance < best_dist:
best_dist = distance
best_move = 'down'
elif move == 'right':
distance = get_distance({'x': head['x'] + 1, 'y': head['y']}, food)
if distance < best_dist:
best_dist = distance
best_move = 'right'
elif move == 'left':
distance = get_distance({'x': head['x'] - 1, 'y': head['y']}, food)
if distance < best_dist:
best_dist = distance
best_move = 'left'
return best_move
#a recursive floodfill algorithm
#used to find how many free spaces there are if a snake makes a given move, and can be applied at various search depths
def flood_recursive(start_pos, obstacles, width, height, depth, hazards):
free_spaces = 0
checked = []
start_depth = depth
def fill(pos, obstacles, depth, hazards, start_depth):
nonlocal free_spaces
nonlocal checked
print(pos)
#stop searching if there are over 70 free spaces as this is clearly enough
if free_spaces > 70:
return
#if at max search depth then stop
if depth == 0:
#last_move = []
print("max depth reached")
return
#if the square is occupied or has been checked, return
if pos in obstacles:
#print("obstacle hit")
return
elif pos in checked:
#print("already checked")
return
else:
checked.append(pos)
#try to avoid hazards that are not instant killers by awarding less than 1 free space to these locations
if pos in hazards:
if depth == start_depth:
free_spaces = free_spaces -0.5
elif depth == start_depth - 1:
free_spaces = free_spaces +0.2
else:
free_spaces = free_spaces + 0.25
elif pos['x'] == 0 or pos['x'] == 10 or pos['y'] == 0 or pos[
'y'] == 10:
if depth == start_depth:
free_spaces = free_spaces + 0.5
else:
free_spaces = free_spaces + 0.75
elif pos['x'] >= 4 and pos ['x'] <= 6 and pos['y'] >= 4 and pos['y'] <=6 and depth == start_depth or depth == start_depth - 1:
free_spaces = free_spaces +1.8
elif depth== start_depth and pos['x'] == 0 or pos['x'] == 10 or pos['y'] == 0 or pos['y'] == 10:
free_spaces = free_spaces - 0.5
else:
free_spaces = free_spaces + 1
#print(free_spaces)
#all next possible moves
neighbours = [{
'x': pos['x'] + 1,
'y': pos['y']
}, {
'x': pos['x'] - 1,
'y': pos['y']
}, {
'x': pos['x'],
'y': pos['y'] + 1
}, {
'x': pos['x'],
'y': pos['y'] - 1
}]
#floodfill each neighbour
for n in neighbours:
#if neighbour is not out of bounds
if 0 <= n['x'] < width and 0 <= n[
'y'] < height and n not in checked:
fill(n, obstacles, depth - 1, hazards, start_depth)
fill(start_pos, obstacles, depth, hazards, start_depth)
#print(free_spaces)
return free_spaces
#choose which move to make
def choose_move(data: dict) -> str:
"""
data: Dictionary of all Game Board data as received from the Battlesnake Engine.
For a full example of 'data', see https://docs.battlesnake.com/references/api/sample-move-request
return: A String, the single move to make. One of "up", "down", "left" or "right".
Use the information in 'data' to decide your next move. The 'data' variable can be interacted
with as a Python Dictionary, and contains all of the information about the Battlesnake board
for each move of the game.
"""
my_head = data["you"][
"head"] # A dictionary of x/y coordinates like {"x": 0, "y": 0}
my_body = data["you"][
"body"] # A list of x/y coordinate dictionaries like [ {"x": 0, "y": 0}, {"x": 1, "y": 0}, {"x": 2, "y": 0} ]
print(
f"~~~ Turn: {data['turn']} Game Mode: {data['game']['ruleset']['name']} ~~~"
)
print(f"All board data this turn: {data}")
print(f"My Battlesnakes head this turn is: {my_head}")
print(f"My Battlesnakes body this turn is: {my_body}")
#the move options
original_moves = ["up", "down", "left", "right"]
possible_moves = ["up", "down", "left", "right"]
# Don't allow your Battlesnake to move back in on it's own neck
possible_moves = avoid_my_neck(my_head, my_body, possible_moves)
print('After neck check: ' + str(possible_moves))
#edges of board
board_height = data['board']['height']
board_width = data['board']['width']
walls = get_walls(board_height, board_width)
#avoid walls
possible_moves = avoid_impact(my_head, walls, possible_moves)
print('After wall check' + str(possible_moves))
#if only one move avoids a wall then play it
if len(possible_moves) == 1:
return possible_moves[0]
#avoid own head
new_possible_moves = avoid_impact(my_head, my_body[:-1], possible_moves)
if new_possible_moves != []:
possible_moves = new_possible_moves
print("After own body check: " + str(possible_moves))
#if there is only one possible move just play it
if len(possible_moves) == 1:
return possible_moves[0]
print(possible_moves)
old_possible_moves = []
for direction in possible_moves:
old_possible_moves.append(direction)
# TODO: Using information from 'data', don't let your Battlesnake pick a move that would collide with another Battlesnake
snakes = data['board']['snakes']
snakes_locations = []
enemy_pos_heads = []
enemy_pos_tails = []
for snake in snakes:
if snake['head'] != my_head:
head_moves = get_head_moves(snake['head'])
for food in data['board']['food']:
food_found = False
if food in head_moves:
food_found = True
if food_found != True:
#non-food tails will not be obstacles
enemy_pos_tails.append(snake['body'][-1])
if food_found == True:
new_possible_moves = avoid_impact(my_head, snake["body"],
possible_moves)
else:
new_possible_moves = avoid_impact(my_head, snake["body"][:-1],
possible_moves)
if len(new_possible_moves) != 0:
possible_moves = new_possible_moves
else:
return random.choice(old_possible_moves)
print("After enemy snake:" + str(possible_moves))
old_possible_moves = []
for direction in possible_moves:
old_possible_moves.append(direction)
snakes_locations.extend(snake['body'])
#remove head moves if small
if data['you']['length'] <= snake['length'] + 1:
#print("head moves: "+ str(head_moves))
new_possible_moves = avoid_impact(my_head, head_moves,
possible_moves)
snakes_locations.extend(head_moves)
enemy_pos_heads.extend(head_moves)
print(len(new_possible_moves))
if len(new_possible_moves) != 0:
possible_moves = new_possible_moves
else:
return random.choice(old_possible_moves)
#tail_moves = get_tail_moves(snake['body'][-1])
#new_possible_moves = avoid_impact(my_head,tail_moves, possible_moves)
#if new_possible_moves != []:
# possible_moves = new_possible_moves
print(possible_moves)
# TODO: Using information from 'data', make your Battlesnake move towards a piece of food on the board
#go for food at the start of the game and when low on health
hazards = data['board']['hazards']
food_move = 'none'
if data['turn'] <= 20 or data['you']['health'] < 60 or data['you'][
'length'] < 9:
closest_food = get_closest_food(my_head, data['board']['food'],
hazards)
food_move = move_to_food(my_head, closest_food, possible_moves)
# Choose a random direction from the remaining possible_moves to move in, and then return that move
print(possible_moves)
#desperation food move
if food_move != 'none' and data['you']['health'] < 20:
move = food_move
else:
#perform a dfs floodfill in each possible direction to find which move gets the most free space/if the food is safe to get
obstacles = []
is_biggest = False
for enemy in snakes:
if enemy['head']!= my_head:
#attack other snakes if bigger by at least 2
if enemy['length'] < data['you']['length'] + 1:
is_biggest = True
else:
is_biggest = False
if enemy_pos_heads != [] and is_biggest != True:
for pos in enemy_pos_heads:
neighbours = [{
'x': pos['x'] + 1,
'y': pos['y']
}, {
'x': pos['x'] - 1,
'y': pos['y']
}, {
'x': pos['x'],
'y': pos['y'] + 1
}, {
'x': pos['x'],
'y': pos['y'] - 1
}]
obstacles.extend(neighbours)
if data['turn'] < 20 or data['you']['length'] < 9:
depth = 9
food_space_val = data['you']['length'] + 5
attack_space_val = 100
else:
depth = 13
if data['you']['length'] < 15:
food_space_val = 15
attack_space_val = 10
else:
food_space_val = data['you']['length'] + 2
attack_space_val = food_space_val -7
obstacles.extend(walls)
obstacles.extend(my_body)
obstacles.extend(snakes_locations)
#if there is no food near the head then the tail is not an obstacle
my_head_moves = get_head_moves(my_head)
food_found = False
for food in data['board']['food']:
if food in my_head_moves:
food_found = True
if food_found == False:
obstacles.remove(my_body[-1])
#remove tails that will not be there in the future
for tail in enemy_pos_tails:
if tail in obstacles:
obstacles.remove(tail)
move = my_head
right_spaces = -100
left_spaces = -100
up_spaces = -100
down_spaces = -100
for direction in possible_moves:
if direction == "right":
try_move = {'x': my_head['x'] + 1, 'y': my_head['y']}
print("checking right")
right_spaces = flood_recursive(try_move, obstacles,
board_width, board_height,
depth, hazards)
elif direction == "left":
try_move = {'x': my_head['x'] - 1, 'y': my_head['y']}
print("checking left")
left_spaces = flood_recursive(try_move, obstacles, board_width,
board_height, depth, hazards)
elif direction == "up":
print("checking up")
try_move = {'x': my_head['x'], 'y': my_head['y'] + 1}
up_spaces = flood_recursive(try_move, obstacles, board_width,
board_height, depth, hazards)
elif direction == "down":
print("checking down")
try_move = {'x': my_head['x'], 'y': my_head['y'] - 1}
down_spaces = flood_recursive(try_move, obstacles, board_width,
board_height, depth, hazards)
print("Right spaces: " + str(right_spaces))
print("Left spaces: " + str(left_spaces))
print("Up spaces: " + str(up_spaces))
print("Down spaces: " + str(down_spaces))
#try and attack if health is greater than 40 and you are the biggest snake
if is_biggest == True and data['you']['health'] > 40:
bravery = 2
dist_for_interest = 8
closest_prey = get_closest_food(my_head, snakes_locations, hazards)
attack_move = move_to_food(my_head, closest_prey, possible_moves)
if attack_move == 'right':
attack_dir = {'x': my_head['x']+1, 'y': my_head['y']}
elif attack_move == 'left':
attack_dir = {'x': my_head['x']-1, 'y': my_head['y']}
elif attack_move == 'up':
attack_dir = {'x': my_head['x'], 'y': my_head['y']+1}
else:
attack_dir = {'x': my_head['x'], 'y': my_head['y']-1}
if my_head['x'] == 0 or my_head['x'] == board_width - 1 or my_head['y'] == 0 or my_head['y'] == board_height - 1 or attack_dir['x'] == 0 or attack_dir['x'] == board_width -1 or attack_dir['y'] == 0 or attack_dir['y'] == board_height -1:
if get_distance(my_head, closest_prey) < bravery:
food_space_val = attack_space_val +8
food_move = attack_move
else:
if get_distance(my_head, closest_prey) < dist_for_interest:
food_space_val = attack_space_val +8
food_move = attack_move
#if there is space surrounding food then go for it
if right_spaces >= food_space_val and food_move == 'right' and {'x': my_head['x']+ 1, 'y': my_head['y']} not in hazards:
move = 'right'
print('floodfill right food priority')
return move
elif left_spaces >= food_space_val and food_move == 'left' and {'x': my_head['x']- 1, 'y': my_head['y']} not in hazards:
move = 'left'
print('floodfill left food priority')
return move
elif up_spaces >= food_space_val and food_move == 'up' and {'x': my_head['x'], 'y': my_head['y']+1} not in hazards:
move = 'up'
print('floodfill up food priority')
return move
if down_spaces >= food_space_val and food_move == 'down' and {'x': my_head['x'], 'y': my_head['y']-1} not in hazards:
move = 'down'
print('floodfill down food priority')
return move
best_move = max(right_spaces, left_spaces, up_spaces, down_spaces)
if best_move == right_spaces and 'right' in possible_moves:
move = 'right'
print("floodfilled right")
elif best_move == left_spaces and 'left' in possible_moves:
move = 'left'
print("floodfilled left")
elif best_move == up_spaces and 'up' in possible_moves:
move = 'up'
print("floodfilled up")
elif best_move == down_spaces and 'down' in possible_moves:
move = 'down'
print("floodfilled down")
else:
if len(possible_moves) > 0:
move = random.choice(possible_moves)
print("random possible")
else:
move = random.choice(original_moves)
print("random desperation")
# TODO: Explore new strategies for picking a move that are better than random
print(
f"{data['game']['id']} MOVE {data['turn']}: {move} picked from all valid options in {possible_moves}"
)
return move
|
################################################################################
# ForecasterAutoregMultiOutput #
# #
# This work by Joaquin Amat Rodrigo is licensed under a Creative Commons #
# Attribution 4.0 International License. #
################################################################################
# coding=utf-8
from typing import Union, Dict, List, Tuple, Any, Optional
import warnings
import logging
import numpy as np
import skforecast
from ..ForecasterAutoregDirect import ForecasterAutoregDirect
logging.basicConfig(
format = '%(name)-10s %(levelname)-5s %(message)s',
level = logging.INFO,
)
class ForecasterAutoregMultiOutput(ForecasterAutoregDirect):
'''
This class turns any regressor compatible with the scikit-learn API into a
autoregressive multi-output forecaster. A separate model is created for each
forecast time step. See Notes for more details.
Parameters
----------
regressor : regressor or pipeline compatible with the scikit-learn API
An instance of a regressor or pipeline compatible with the scikit-learn API.
lags : int, list, 1d numpy ndarray, range
Lags used as predictors. Index starts at 1, so lag 1 is equal to t-1.
`int`: include lags from 1 to `lags` (included).
`list`, `numpy ndarray` or range: include only lags present in `lags`.
steps : int
Maximum number of future steps the forecaster will predict when using
method `predict()`. Since a different model is created for each step,
this value should be defined before training.
Attributes
----------
regressor : regressor or pipeline compatible with the scikit-learn API
An instance of a regressor or pipeline compatible with the scikit-learn API.
One instance of this regressor is trainned for each step. All
them are stored in `self.regressors_`.
regressors_ : dict
Dictionary with regressors trained for each step.
steps : int
Number of future steps the forecaster will predict when using method
`predict()`. Since a different model is created for each step, this value
should be defined before training.
lags : numpy ndarray
Lags used as predictors.
max_lag : int
Maximum value of lag included in `lags`.
last_window : pandas Series
Last window the forecaster has seen during trained. It stores the
values needed to predict the next `step` right after the training data.
window_size: int
Size of the window needed to create the predictors. It is equal to
`max_lag`.
fitted: Bool
Tag to identify if the regressor has been fitted (trained).
index_type : type
Type of index of the input used in training.
index_freq : str
Frequency of Index of the input used in training.
training_range: pandas Index
First and last index of samples used during training.
included_exog : bool
If the forecaster has been trained using exogenous variable/s.
exog_type : type
Type of exogenous variable/s used in training.
exog_col_names : tuple
Names of columns of `exog` if `exog` used in training was a pandas
DataFrame.
X_train_col_names : tuple
Names of columns of the matrix created internally for training.
creation_date: str
Date of creation.
fit_date: str
Date of last fit.
skforcast_version: str
Version of skforecast library used to create the forecaster.
Notes
-----
A separate model is created for each forecast time step. It is important to
note that all models share the same configuration of parameters and
hyperparameters.
'''
def __init__(self, regressor, steps: int,
lags: Union[int, np.ndarray, list]) -> None:
# Add warning to __init__ ForecasterAutoregDirect
ForecasterAutoregDirect.__init__(self, regressor, steps, lags)
warnings.warn(
f'ForecasterAutoregMultiOutput has been renamed to ForecasterAutoregDirect.'
f'This class will be removed in skforecast 0.6.0.'
)
def __repr__(self) -> str:
'''
Information displayed when a ForecasterAutoregMultiOutput object is printed.
'''
if isinstance(self.regressor, sklearn.pipeline.Pipeline):
name_pipe_steps = tuple(name + "__" for name in self.regressor.named_steps.keys())
params = {key : value for key, value in self.regressor.get_params().items() \
if key.startswith(name_pipe_steps)}
else:
params = self.regressor.get_params()
info = (
f"{"=" * len(str(type(forecaster)).split(".")[-1].replace("""">""", ""))} \n"
f"{str(type(forecaster)).split(".")[-1].replace("""">""", "")} \n"
f"{"=" * len(str(type(forecaster)).split(".")[-1].replace("""">""", ""))} \n"
f"Regressor: {self.regressor} \n"
f"Lags: {self.lags} \n"
f"Window size: {self.window_size} \n"
f"Maximum steps predicted: {self.steps} \n"
f"Included exogenous: {self.included_exog} \n"
f"Type of exogenous variable: {self.exog_type} \n"
f"Exogenous variables names: {self.exog_col_names} \n"
f"Training range: {self.training_range.to_list() if self.fitted else None} \n"
f"Training index type: {str(self.index_type).split(".")[-1][:-2] if self.fitted else None} \n"
f"Training index frequency: {self.index_freq if self.fitted else None} \n"
f"Regressor parameters: {params} \n"
f"Creation date: {self.creation_date} \n"
f"Last fit date: {self.fit_date} \n"
f"Skforecast version: {self.skforcast_version} \n"
)
return info | ################################################################################
# ForecasterAutoregMultiOutput #
# #
# This work by Joaquin Amat Rodrigo is licensed under a Creative Commons #
# Attribution 4.0 International License. #
################################################################################
# coding=utf-8
from typing import Union, Dict, List, Tuple, Any, Optional
import warnings
import logging
import numpy as np
import skforecast
from ..ForecasterAutoregDirect import ForecasterAutoregDirect
logging.basicConfig(
format = '%(name)-10s %(levelname)-5s %(message)s',
level = logging.INFO,
)
class ForecasterAutoregMultiOutput(ForecasterAutoregDirect):
'''
This class turns any regressor compatible with the scikit-learn API into a
autoregressive multi-output forecaster. A separate model is created for each
forecast time step. See Notes for more details.
Parameters
----------
regressor : regressor or pipeline compatible with the scikit-learn API
An instance of a regressor or pipeline compatible with the scikit-learn API.
lags : int, list, 1d numpy ndarray, range
Lags used as predictors. Index starts at 1, so lag 1 is equal to t-1.
`int`: include lags from 1 to `lags` (included).
`list`, `numpy ndarray` or range: include only lags present in `lags`.
steps : int
Maximum number of future steps the forecaster will predict when using
method `predict()`. Since a different model is created for each step,
this value should be defined before training.
Attributes
----------
regressor : regressor or pipeline compatible with the scikit-learn API
An instance of a regressor or pipeline compatible with the scikit-learn API.
One instance of this regressor is trainned for each step. All
them are stored in `self.regressors_`.
regressors_ : dict
Dictionary with regressors trained for each step.
steps : int
Number of future steps the forecaster will predict when using method
`predict()`. Since a different model is created for each step, this value
should be defined before training.
lags : numpy ndarray
Lags used as predictors.
max_lag : int
Maximum value of lag included in `lags`.
last_window : pandas Series
Last window the forecaster has seen during trained. It stores the
values needed to predict the next `step` right after the training data.
window_size: int
Size of the window needed to create the predictors. It is equal to
`max_lag`.
fitted: Bool
Tag to identify if the regressor has been fitted (trained).
index_type : type
Type of index of the input used in training.
index_freq : str
Frequency of Index of the input used in training.
training_range: pandas Index
First and last index of samples used during training.
included_exog : bool
If the forecaster has been trained using exogenous variable/s.
exog_type : type
Type of exogenous variable/s used in training.
exog_col_names : tuple
Names of columns of `exog` if `exog` used in training was a pandas
DataFrame.
X_train_col_names : tuple
Names of columns of the matrix created internally for training.
creation_date: str
Date of creation.
fit_date: str
Date of last fit.
skforcast_version: str
Version of skforecast library used to create the forecaster.
Notes
-----
A separate model is created for each forecast time step. It is important to
note that all models share the same configuration of parameters and
hyperparameters.
'''
def __init__(self, regressor, steps: int,
lags: Union[int, np.ndarray, list]) -> None:
# Add warning to __init__ ForecasterAutoregDirect
ForecasterAutoregDirect.__init__(self, regressor, steps, lags)
warnings.warn(
f'ForecasterAutoregMultiOutput has been renamed to ForecasterAutoregDirect.'
f'This class will be removed in skforecast 0.6.0.'
)
def __repr__(self) -> str:
'''
Information displayed when a ForecasterAutoregMultiOutput object is printed.
'''
if isinstance(self.regressor, sklearn.pipeline.Pipeline):
name_pipe_steps = tuple(name + "__" for name in self.regressor.named_steps.keys())
params = {key : value for key, value in self.regressor.get_params().items() \
if key.startswith(name_pipe_steps)}
else:
params = self.regressor.get_params()
info = (
f"{'=' * len(str(type(forecaster)).split('.')[-1].replace(''''>''', ''))} \n"
f"{str(type(forecaster)).split('.')[-1].replace(''''>''', '')} \n"
f"{'=' * len(str(type(forecaster)).split('.')[-1].replace(''''>''', ''))} \n"
f"Regressor: {self.regressor} \n"
f"Lags: {self.lags} \n"
f"Window size: {self.window_size} \n"
f"Maximum steps predicted: {self.steps} \n"
f"Included exogenous: {self.included_exog} \n"
f"Type of exogenous variable: {self.exog_type} \n"
f"Exogenous variables names: {self.exog_col_names} \n"
f"Training range: {self.training_range.to_list() if self.fitted else None} \n"
f"Training index type: {str(self.index_type).split('.')[-1][:-2] if self.fitted else None} \n"
f"Training index frequency: {self.index_freq if self.fitted else None} \n"
f"Regressor parameters: {params} \n"
f"Creation date: {self.creation_date} \n"
f"Last fit date: {self.fit_date} \n"
f"Skforecast version: {self.skforcast_version} \n"
)
return info |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# isort:skip_file
"""Unit tests for Superset"""
from datetime import datetime
import json
import pytz
import pytest
import prison
from sqlalchemy.sql import func
from superset import db
from superset.models.core import Database
from superset.models.slice import Slice
from superset.models.dashboard import Dashboard
from superset.models.reports import (
ReportSchedule,
ReportCreationMethodType,
ReportRecipients,
ReportExecutionLog,
ReportScheduleType,
ReportRecipientType,
ReportState,
)
from superset.utils.core import get_example_database
from tests.integration_tests.base_tests import SupersetTestCase
from tests.integration_tests.conftest import with_feature_flags
from tests.integration_tests.fixtures.birth_names_dashboard import (
load_birth_names_dashboard_with_slices,
load_birth_names_data,
)
from tests.integration_tests.fixtures.tabbed_dashboard import tabbed_dashboard
from tests.integration_tests.reports.utils import insert_report_schedule
REPORTS_COUNT = 10
class TestReportSchedulesApi(SupersetTestCase):
@pytest.fixture()
def create_working_report_schedule(self):
with self.create_app().app_context():
admin_user = self.get_user("admin")
alpha_user = self.get_user("alpha")
chart = db.session.query(Slice).first()
example_db = get_example_database()
report_schedule = insert_report_schedule(
type=ReportScheduleType.ALERT,
name="name_working",
crontab="* * * * *",
sql="SELECT value from table",
description="Report working",
chart=chart,
database=example_db,
owners=[admin_user, alpha_user],
last_state=ReportState.WORKING,
)
yield
db.session.delete(report_schedule)
db.session.commit()
@pytest.fixture()
def create_report_schedules(self):
with self.create_app().app_context():
report_schedules = []
admin_user = self.get_user("admin")
alpha_user = self.get_user("alpha")
chart = db.session.query(Slice).first()
example_db = get_example_database()
for cx in range(REPORTS_COUNT):
recipients = []
logs = []
for cy in range(cx):
config_json = {"target": f"target{cy}@email.com"}
recipients.append(
ReportRecipients(
type=ReportRecipientType.EMAIL,
recipient_config_json=json.dumps(config_json),
)
)
logs.append(
ReportExecutionLog(
scheduled_dttm=datetime(2020, 1, 1),
state=ReportState.ERROR,
error_message=f"Error {cy}",
)
)
report_schedules.append(
insert_report_schedule(
type=ReportScheduleType.ALERT,
name=f"name{cx}",
crontab=f"*/{cx} * * * *",
sql=f"SELECT value from table{cx}",
description=f"Some description {cx}",
chart=chart,
database=example_db,
owners=[admin_user, alpha_user],
recipients=recipients,
logs=logs,
)
)
yield report_schedules
report_schedules = db.session.query(ReportSchedule).all()
# rollback changes (assuming cascade delete)
for report_schedule in report_schedules:
db.session.delete(report_schedule)
db.session.commit()
@pytest.fixture()
def create_alpha_users(self):
with self.create_app().app_context():
users = [
self.create_user(
"alpha1", "password", "Alpha", email="alpha1@superset.org"
),
self.create_user(
"alpha2", "password", "Alpha", email="alpha2@superset.org"
),
]
yield users
# rollback changes (assuming cascade delete)
for user in users:
db.session.delete(user)
db.session.commit()
@with_feature_flags(ALERT_REPORTS=False)
@pytest.mark.usefixtures("create_report_schedules")
def test_get_report_schedule_disabled(self):
"""
ReportSchedule Api: Test get report schedule 404s when feature is disabled
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name1")
.first()
)
self.login(username="admin")
uri = f"api/v1/report/{report_schedule.id}"
rv = self.client.get(uri)
assert rv.status_code == 404
@pytest.mark.usefixtures("create_report_schedules")
def test_get_report_schedule(self):
"""
ReportSchedule Api: Test get report schedule
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name1")
.first()
)
self.login(username="admin")
uri = f"api/v1/report/{report_schedule.id}"
rv = self.get_assert_metric(uri, "get")
data = json.loads(rv.data.decode("utf-8"))
assert rv.status_code == 200
expected_result = {
"active": report_schedule.active,
"chart": {
"id": report_schedule.chart.id,
"slice_name": report_schedule.chart.slice_name,
"viz_type": report_schedule.chart.viz_type,
},
"context_markdown": report_schedule.context_markdown,
"crontab": report_schedule.crontab,
"dashboard": None,
"database": {
"id": report_schedule.database.id,
"database_name": report_schedule.database.database_name,
},
"description": report_schedule.description,
"grace_period": report_schedule.grace_period,
"id": report_schedule.id,
"last_eval_dttm": report_schedule.last_eval_dttm,
"last_state": report_schedule.last_state,
"last_value": report_schedule.last_value,
"last_value_row_json": report_schedule.last_value_row_json,
"log_retention": report_schedule.log_retention,
"name": report_schedule.name,
"recipients": [
{
"id": report_schedule.recipients[0].id,
"recipient_config_json": '{"target": "target0@email.com"}',
"type": "Email",
}
],
"timezone": report_schedule.timezone,
"type": report_schedule.type,
"validator_config_json": report_schedule.validator_config_json,
"validator_type": report_schedule.validator_type,
}
for key in expected_result:
assert data["result"][key] == expected_result[key]
# needed because order may vary
assert {"first_name": "admin", "id": 1, "last_name": "user"} in data["result"][
"owners"
]
assert {"first_name": "alpha", "id": 5, "last_name": "user"} in data["result"][
"owners"
]
assert len(data["result"]["owners"]) == 2
def test_info_report_schedule(self):
"""
ReportSchedule API: Test info
"""
self.login(username="admin")
uri = f"api/v1/report/_info"
rv = self.get_assert_metric(uri, "info")
assert rv.status_code == 200
def test_info_security_report(self):
"""
ReportSchedule API: Test info security
"""
self.login(username="admin")
params = {"keys": ["permissions"]}
uri = f"api/v1/report/_info?q={prison.dumps(params)}"
rv = self.get_assert_metric(uri, "info")
data = json.loads(rv.data.decode("utf-8"))
assert rv.status_code == 200
assert "can_read" in data["permissions"]
assert "can_write" in data["permissions"]
assert len(data["permissions"]) == 2
@pytest.mark.usefixtures("create_report_schedules")
def test_get_report_schedule_not_found(self):
"""
ReportSchedule Api: Test get report schedule not found
"""
max_id = db.session.query(func.max(ReportSchedule.id)).scalar()
self.login(username="admin")
uri = f"api/v1/report/{max_id + 1}"
rv = self.get_assert_metric(uri, "get")
assert rv.status_code == 404
@pytest.mark.usefixtures("create_report_schedules")
def test_get_list_report_schedule(self):
"""
ReportSchedule Api: Test get list report schedules
"""
self.login(username="admin")
uri = f"api/v1/report/"
rv = self.get_assert_metric(uri, "get_list")
expected_fields = [
"active",
"changed_by",
"changed_on",
"changed_on_delta_humanized",
"created_by",
"created_on",
"creation_method",
"crontab",
"crontab_humanized",
"description",
"id",
"last_eval_dttm",
"last_state",
"name",
"owners",
"recipients",
"timezone",
"type",
]
assert rv.status_code == 200
data = json.loads(rv.data.decode("utf-8"))
assert data["count"] == REPORTS_COUNT
data_keys = sorted(list(data["result"][0].keys()))
assert expected_fields == data_keys
# Assert nested fields
expected_owners_fields = ["first_name", "id", "last_name"]
data_keys = sorted(list(data["result"][0]["owners"][0].keys()))
assert expected_owners_fields == data_keys
expected_recipients_fields = ["id", "type"]
data_keys = sorted(list(data["result"][1]["recipients"][0].keys()))
assert expected_recipients_fields == data_keys
@pytest.mark.usefixtures("create_report_schedules")
def test_get_list_report_schedule_sorting(self):
"""
ReportSchedule Api: Test sorting on get list report schedules
"""
self.login(username="admin")
uri = "api/v1/report/"
order_columns = [
"active",
"created_by.first_name",
"changed_by.first_name",
"changed_on",
"changed_on_delta_humanized",
"created_on",
"crontab",
"description",
"last_eval_dttm",
"name",
"type",
"crontab_humanized",
]
for order_column in order_columns:
arguments = {"order_column": order_column, "order_direction": "asc"}
uri = f"api/v1/report/?q={prison.dumps(arguments)}"
rv = self.get_assert_metric(uri, "get_list")
assert rv.status_code == 200
@pytest.mark.usefixtures("create_report_schedules")
def test_get_list_report_schedule_filter_name(self):
"""
ReportSchedule Api: Test filter name on get list report schedules
"""
self.login(username="admin")
# Test normal contains filter
arguments = {
"columns": ["name"],
"filters": [{"col": "name", "opr": "ct", "value": "2"}],
}
uri = f"api/v1/report/?q={prison.dumps(arguments)}"
rv = self.get_assert_metric(uri, "get_list")
expected_result = {
"name": "name2",
}
assert rv.status_code == 200
data = json.loads(rv.data.decode("utf-8"))
assert data["count"] == 1
assert data["result"][0] == expected_result
@pytest.mark.usefixtures("create_report_schedules")
def test_get_list_report_schedule_filter_custom(self):
"""
ReportSchedule Api: Test custom filter on get list report schedules
"""
self.login(username="admin")
# Test custom all text filter
arguments = {
"columns": ["name"],
"filters": [{"col": "name", "opr": "report_all_text", "value": "table3"}],
}
uri = f"api/v1/report/?q={prison.dumps(arguments)}"
rv = self.get_assert_metric(uri, "get_list")
expected_result = {
"name": "name3",
}
assert rv.status_code == 200
data = json.loads(rv.data.decode("utf-8"))
assert data["count"] == 1
assert data["result"][0] == expected_result
@pytest.mark.usefixtures("create_report_schedules")
def test_get_list_report_schedule_filter_active(self):
"""
ReportSchedule Api: Test active filter on get list report schedules
"""
self.login(username="admin")
arguments = {
"columns": ["name"],
"filters": [{"col": "active", "opr": "eq", "value": True}],
}
uri = f"api/v1/report/?q={prison.dumps(arguments)}"
rv = self.get_assert_metric(uri, "get_list")
assert rv.status_code == 200
data = json.loads(rv.data.decode("utf-8"))
assert data["count"] == REPORTS_COUNT
@pytest.mark.usefixtures("create_report_schedules")
def test_get_list_report_schedule_filter_type(self):
"""
ReportSchedule Api: Test type filter on get list report schedules
"""
self.login(username="admin")
arguments = {
"columns": ["name"],
"filters": [
{"col": "type", "opr": "eq", "value": ReportScheduleType.ALERT}
],
}
uri = f"api/v1/report/?q={prison.dumps(arguments)}"
rv = self.get_assert_metric(uri, "get_list")
assert rv.status_code == 200
data = json.loads(rv.data.decode("utf-8"))
assert data["count"] == REPORTS_COUNT
# Test type filter
arguments = {
"columns": ["name"],
"filters": [
{"col": "type", "opr": "eq", "value": ReportScheduleType.REPORT}
],
}
uri = f"api/v1/report/?q={prison.dumps(arguments)}"
rv = self.get_assert_metric(uri, "get_list")
assert rv.status_code == 200
data = json.loads(rv.data.decode("utf-8"))
assert data["count"] == 0
@pytest.mark.usefixtures("create_report_schedules")
def test_get_related_report_schedule(self):
"""
ReportSchedule Api: Test get releated report schedule
"""
self.login(username="admin")
related_columns = ["owners", "chart", "dashboard", "database"]
for related_column in related_columns:
uri = f"api/v1/report/related/{related_column}"
rv = self.client.get(uri)
assert rv.status_code == 200
@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
def test_create_report_schedule(self):
"""
ReportSchedule Api: Test create report schedule
"""
self.login(username="admin")
chart = db.session.query(Slice).first()
example_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"crontab": "0 9 * * *",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
},
{
"type": ReportRecipientType.SLACK,
"recipient_config_json": {"target": "channel"},
},
],
"grace_period": 14400,
"working_timeout": 3600,
"chart": chart.id,
"database": example_db.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
data = json.loads(rv.data.decode("utf-8"))
assert rv.status_code == 201
created_model = db.session.query(ReportSchedule).get(data.get("id"))
assert created_model is not None
assert created_model.name == report_schedule_data["name"]
assert created_model.grace_period == report_schedule_data["grace_period"]
assert created_model.working_timeout == report_schedule_data["working_timeout"]
assert created_model.description == report_schedule_data["description"]
assert created_model.crontab == report_schedule_data["crontab"]
assert created_model.chart.id == report_schedule_data["chart"]
assert created_model.database.id == report_schedule_data["database"]
assert created_model.creation_method == report_schedule_data["creation_method"]
# Rollback changes
db.session.delete(created_model)
db.session.commit()
@pytest.mark.usefixtures("create_report_schedules")
def test_create_report_schedule_uniqueness(self):
"""
ReportSchedule Api: Test create report schedule uniqueness
"""
self.login(username="admin")
chart = db.session.query(Slice).first()
example_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "name3",
"description": "description",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"crontab": "0 9 * * *",
"chart": chart.id,
"database": example_db.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 422
data = json.loads(rv.data.decode("utf-8"))
assert data == {"message": {"name": ["Name must be unique"]}}
# Check that uniqueness is composed by name and type
report_schedule_data = {
"type": ReportScheduleType.REPORT,
"name": "name3",
"description": "description",
"crontab": "0 9 * * *",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"chart": chart.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 201
data = json.loads(rv.data.decode("utf-8"))
# Rollback changes
created_model = db.session.query(ReportSchedule).get(data.get("id"))
db.session.delete(created_model)
db.session.commit()
@pytest.mark.usefixtures(
"load_birth_names_dashboard_with_slices", "create_report_schedules"
)
def test_create_report_schedule_schema(self):
"""
ReportSchedule Api: Test create report schedule schema check
"""
self.login(username="admin")
chart = db.session.query(Slice).first()
dashboard = db.session.query(Dashboard).first()
example_db = get_example_database()
# Check that a report does not have a database reference
report_schedule_data = {
"type": ReportScheduleType.REPORT,
"name": "name3",
"description": "description",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"crontab": "0 9 * * *",
"chart": chart.id,
"database": example_db.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 400
# Test that report can be created with null grace period
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"crontab": "0 9 * * *",
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
},
{
"type": ReportRecipientType.SLACK,
"recipient_config_json": {"target": "channel"},
},
],
"working_timeout": 3600,
"chart": chart.id,
"database": example_db.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 201
# Test that grace period and working timeout cannot be < 1
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"crontab": "0 9 * * *",
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
},
{
"type": ReportRecipientType.SLACK,
"recipient_config_json": {"target": "channel"},
},
],
"working_timeout": -10,
"chart": chart.id,
"database": example_db.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 400
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"crontab": "0 9 * * *",
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
},
{
"type": ReportRecipientType.SLACK,
"recipient_config_json": {"target": "channel"},
},
],
"grace_period": -10,
"working_timeout": 3600,
"chart": chart.id,
"database": example_db.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 400
# Test that report can be created with null dashboard
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new4",
"description": "description",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"crontab": "0 9 * * *",
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
},
{
"type": ReportRecipientType.SLACK,
"recipient_config_json": {"target": "channel"},
},
],
"working_timeout": 3600,
"chart": chart.id,
"dashboard": None,
"database": example_db.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 201
# Test that report can be created with null chart
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new5",
"description": "description",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"crontab": "0 9 * * *",
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
},
{
"type": ReportRecipientType.SLACK,
"recipient_config_json": {"target": "channel"},
},
],
"working_timeout": 3600,
"chart": None,
"dashboard": dashboard.id,
"database": example_db.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 201
# Test that report cannot be created with null timezone
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new5",
"description": "description",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"crontab": "0 9 * * *",
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
},
{
"type": ReportRecipientType.SLACK,
"recipient_config_json": {"target": "channel"},
},
],
"working_timeout": 3600,
"timezone": None,
"dashboard": dashboard.id,
"database": example_db.id,
}
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 400
data = json.loads(rv.data.decode("utf-8"))
assert data == {"message": {"timezone": ["Field may not be null."]}}
# Test that report cannot be created with an invalid timezone
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new5",
"description": "description",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"crontab": "0 9 * * *",
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
},
{
"type": ReportRecipientType.SLACK,
"recipient_config_json": {"target": "channel"},
},
],
"working_timeout": 3600,
"timezone": "this is not a timezone",
"dashboard": dashboard.id,
"database": example_db.id,
}
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 400
data = json.loads(rv.data.decode("utf-8"))
assert data == {
"message": {
"timezone": [f"Must be one of: {", ".join(pytz.all_timezones)}."]
}
}
# Test that report should reflect the timezone value passed in
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new6",
"description": "description",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"crontab": "0 9 * * *",
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
},
{
"type": ReportRecipientType.SLACK,
"recipient_config_json": {"target": "channel"},
},
],
"working_timeout": 3600,
"timezone": "America/Los_Angeles",
"dashboard": dashboard.id,
"database": example_db.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
data = json.loads(rv.data.decode("utf-8"))
assert data["result"]["timezone"] == "America/Los_Angeles"
assert rv.status_code == 201
@pytest.mark.usefixtures(
"load_birth_names_dashboard_with_slices", "create_report_schedules"
)
def test_unsaved_report_schedule_schema(self):
"""
ReportSchedule Api: Test create report schedule with unsaved chart
"""
self.login(username="admin")
chart = db.session.query(Slice).first()
dashboard = db.session.query(Dashboard).first()
example_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.REPORT,
"name": "name3",
"description": "description",
"creation_method": ReportCreationMethodType.CHARTS,
"crontab": "0 9 * * *",
"chart": 0,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
data = json.loads(rv.data.decode("utf-8"))
assert rv.status_code == 422
assert (
data["message"]["chart"]
== "Please save your chart first, then try creating a new email report."
)
@pytest.mark.usefixtures(
"load_birth_names_dashboard_with_slices", "create_report_schedules"
)
def test_no_dashboard_report_schedule_schema(self):
"""
ReportSchedule Api: Test create report schedule with no dashboard id
"""
self.login(username="admin")
chart = db.session.query(Slice).first()
dashboard = db.session.query(Dashboard).first()
example_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.REPORT,
"name": "name3",
"description": "description",
"creation_method": ReportCreationMethodType.DASHBOARDS,
"crontab": "0 9 * * *",
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
data = json.loads(rv.data.decode("utf-8"))
assert rv.status_code == 422
assert (
data["message"]["dashboard"]
== "Please save your dashboard first, then try creating a new email report."
)
@pytest.mark.usefixtures(
"load_birth_names_dashboard_with_slices", "create_report_schedules"
)
def test_create_multiple_creation_method_report_schedule_charts(self):
"""
ReportSchedule Api: Test create multiple reports with the same creation method
"""
self.login(username="admin")
chart = db.session.query(Slice).first()
dashboard = db.session.query(Dashboard).first()
example_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.REPORT,
"name": "name4",
"description": "description",
"creation_method": ReportCreationMethodType.CHARTS,
"crontab": "0 9 * * *",
"working_timeout": 3600,
"chart": chart.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
data = json.loads(rv.data.decode("utf-8"))
assert rv.status_code == 201
# this second time it should receive an error because the chart has an attached report
# with the same creation method from the same user.
report_schedule_data = {
"type": ReportScheduleType.REPORT,
"name": "name5",
"description": "description",
"creation_method": ReportCreationMethodType.CHARTS,
"crontab": "0 9 * * *",
"working_timeout": 3600,
"chart": chart.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
data = json.loads(rv.data.decode("utf-8"))
assert rv.status_code == 409
assert data == {
"errors": [
{
"message": "Resource already has an attached report.",
"error_type": "GENERIC_COMMAND_ERROR",
"level": "warning",
"extra": {
"issue_codes": [
{
"code": 1010,
"message": "Issue 1010 - Superset encountered an error while running a command.",
}
]
},
}
]
}
@pytest.mark.usefixtures(
"load_birth_names_dashboard_with_slices", "create_report_schedules"
)
def test_create_multiple_creation_method_report_schedule_dashboards(self):
"""
ReportSchedule Api: Test create multiple reports with the same creation method
"""
self.login(username="admin")
chart = db.session.query(Slice).first()
dashboard = db.session.query(Dashboard).first()
example_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.REPORT,
"name": "name4",
"description": "description",
"creation_method": ReportCreationMethodType.DASHBOARDS,
"crontab": "0 9 * * *",
"working_timeout": 3600,
"dashboard": dashboard.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
data = json.loads(rv.data.decode("utf-8"))
assert rv.status_code == 201
# this second time it should receive an error because the dashboard has an attached report
# with the same creation method from the same user.
report_schedule_data = {
"type": ReportScheduleType.REPORT,
"name": "name5",
"description": "description",
"creation_method": ReportCreationMethodType.DASHBOARDS,
"crontab": "0 9 * * *",
"working_timeout": 3600,
"dashboard": dashboard.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
data = json.loads(rv.data.decode("utf-8"))
assert rv.status_code == 409
assert data == {
"errors": [
{
"message": "Resource already has an attached report.",
"error_type": "GENERIC_COMMAND_ERROR",
"level": "warning",
"extra": {
"issue_codes": [
{
"code": 1010,
"message": "Issue 1010 - Superset encountered an error while running a command.",
}
]
},
}
]
}
@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
def test_create_report_schedule_chart_dash_validation(self):
"""
ReportSchedule Api: Test create report schedule chart and dashboard validation
"""
self.login(username="admin")
# Test we can submit a chart or a dashboard not both
chart = db.session.query(Slice).first()
dashboard = db.session.query(Dashboard).first()
example_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"crontab": "0 9 * * *",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"chart": chart.id,
"dashboard": dashboard.id,
"database": example_db.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 422
data = json.loads(rv.data.decode("utf-8"))
assert data == {"message": {"chart": "Choose a chart or dashboard not both"}}
@pytest.mark.usefixtures("create_report_schedules")
def test_create_report_schedule_chart_db_validation(self):
"""
ReportSchedule Api: Test create report schedule chart and database validation
"""
self.login(username="admin")
# Test database required for alerts
chart = db.session.query(Slice).first()
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"crontab": "0 9 * * *",
"chart": chart.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 422
data = json.loads(rv.data.decode("utf-8"))
assert data == {"message": {"database": "Database is required for alerts"}}
@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
def test_create_report_schedule_relations_exist(self):
"""
ReportSchedule Api: Test create report schedule
relations (chart, dash, db) exist
"""
self.login(username="admin")
# Test chart and database do not exist
chart_max_id = db.session.query(func.max(Slice.id)).scalar()
database_max_id = db.session.query(func.max(Database.id)).scalar()
examples_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"crontab": "0 9 * * *",
"chart": chart_max_id + 1,
"database": database_max_id + 1,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 422
data = json.loads(rv.data.decode("utf-8"))
assert data == {
"message": {
"chart": "Chart does not exist",
"database": "Database does not exist",
}
}
# Test dashboard does not exist
dashboard_max_id = db.session.query(func.max(Dashboard.id)).scalar()
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"crontab": "0 9 * * *",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"dashboard": dashboard_max_id + 1,
"database": examples_db.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 422
data = json.loads(rv.data.decode("utf-8"))
assert data == {"message": {"dashboard": "Dashboard does not exist"}}
# @pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
# TODO (AAfghahi): I am going to enable this when the report schedule feature is fully finished
# def test_create_report_schedule_no_creation_method(self):
# """
# ReportSchedule Api: Test create report schedule
# """
# self.login(username="admin")
# chart = db.session.query(Slice).first()
# example_db = get_example_database()
# report_schedule_data = {
# "type": ReportScheduleType.ALERT,
# "name": "new3",
# "description": "description",
# "crontab": "0 9 * * *",
# "recipients": [
# {
# "type": ReportRecipientType.EMAIL,
# "recipient_config_json": {"target": "target@superset.org"},
# },
# {
# "type": ReportRecipientType.SLACK,
# "recipient_config_json": {"target": "channel"},
# },
# ],
# "grace_period": 14400,
# "working_timeout": 3600,
# "chart": chart.id,
# "database": example_db.id,
# }
# uri = "api/v1/report/"
# rv = self.client.post(uri, json=report_schedule_data)
# response = json.loads(rv.data.decode("utf-8"))
# assert response == {
# "message": {"creation_method": ["Missing data for required field."]}
# }
# assert rv.status_code == 400
@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
def test_create_report_schedule_invalid_creation_method(self):
"""
ReportSchedule API: Test create report schedule
"""
self.login(username="admin")
chart = db.session.query(Slice).first()
example_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"creation_method": "BAD_CREATION_METHOD",
"crontab": "0 9 * * *",
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
},
{
"type": ReportRecipientType.SLACK,
"recipient_config_json": {"target": "channel"},
},
],
"grace_period": 14400,
"working_timeout": 3600,
"chart": chart.id,
"database": example_db.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
response = json.loads(rv.data.decode("utf-8"))
assert response == {
"message": {"creation_method": ["Invalid enum value BAD_CREATION_METHOD"]}
}
assert rv.status_code == 400
@pytest.mark.usefixtures("create_report_schedules")
def test_update_report_schedule(self):
"""
ReportSchedule Api: Test update report schedule
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name2")
.one_or_none()
)
self.login(username="admin")
chart = db.session.query(Slice).first()
example_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "changed",
"description": "description",
"crontab": "0 10 * * *",
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
}
],
"chart": chart.id,
"database": example_db.id,
}
uri = f"api/v1/report/{report_schedule.id}"
rv = self.client.put(uri, json=report_schedule_data)
assert rv.status_code == 200
updated_model = db.session.query(ReportSchedule).get(report_schedule.id)
assert updated_model is not None
assert updated_model.name == report_schedule_data["name"]
assert updated_model.description == report_schedule_data["description"]
assert len(updated_model.recipients) == 1
assert updated_model.crontab == report_schedule_data["crontab"]
assert updated_model.chart_id == report_schedule_data["chart"]
assert updated_model.database_id == report_schedule_data["database"]
@pytest.mark.usefixtures("create_working_report_schedule")
def test_update_report_schedule_state_working(self):
"""
ReportSchedule Api: Test update state in a working report
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name_working")
.one_or_none()
)
self.login(username="admin")
report_schedule_data = {"active": False}
uri = f"api/v1/report/{report_schedule.id}"
rv = self.client.put(uri, json=report_schedule_data)
assert rv.status_code == 200
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name_working")
.one_or_none()
)
assert report_schedule.last_state == ReportState.NOOP
@pytest.mark.usefixtures("create_report_schedules")
def test_update_report_schedule_uniqueness(self):
"""
ReportSchedule Api: Test update report schedule uniqueness
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name2")
.one_or_none()
)
self.login(username="admin")
report_schedule_data = {"name": "name3", "description": "changed_description"}
uri = f"api/v1/report/{report_schedule.id}"
rv = self.client.put(uri, json=report_schedule_data)
data = json.loads(rv.data.decode("utf-8"))
assert rv.status_code == 422
assert data == {"message": {"name": ["Name must be unique"]}}
@pytest.mark.usefixtures("create_report_schedules")
def test_update_report_schedule_not_found(self):
"""
ReportSchedule Api: Test update report schedule not found
"""
max_id = db.session.query(func.max(ReportSchedule.id)).scalar()
self.login(username="admin")
report_schedule_data = {"name": "changed"}
uri = f"api/v1/report/{max_id + 1}"
rv = self.client.put(uri, json=report_schedule_data)
assert rv.status_code == 404
@pytest.mark.usefixtures(
"load_birth_names_dashboard_with_slices", "create_report_schedules"
)
def test_update_report_schedule_chart_dash_validation(self):
"""
ReportSchedule Api: Test update report schedule chart and dashboard validation
"""
self.login(username="admin")
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name2")
.one_or_none()
)
# Test we can submit a chart or a dashboard not both
chart = db.session.query(Slice).first()
dashboard = db.session.query(Dashboard).first()
example_db = get_example_database()
report_schedule_data = {
"chart": chart.id,
"dashboard": dashboard.id,
"database": example_db.id,
}
uri = f"api/v1/report/{report_schedule.id}"
rv = self.client.put(uri, json=report_schedule_data)
assert rv.status_code == 422
data = json.loads(rv.data.decode("utf-8"))
assert data == {"message": {"chart": "Choose a chart or dashboard not both"}}
@pytest.mark.usefixtures(
"load_birth_names_dashboard_with_slices", "create_report_schedules"
)
def test_update_report_schedule_relations_exist(self):
"""
ReportSchedule Api: Test update report schedule relations exist
relations (chart, dash, db) exist
"""
self.login(username="admin")
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name2")
.one_or_none()
)
# Test chart and database do not exist
chart_max_id = db.session.query(func.max(Slice.id)).scalar()
database_max_id = db.session.query(func.max(Database.id)).scalar()
examples_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"crontab": "0 9 * * *",
"chart": chart_max_id + 1,
"database": database_max_id + 1,
}
uri = f"api/v1/report/{report_schedule.id}"
rv = self.client.put(uri, json=report_schedule_data)
assert rv.status_code == 422
data = json.loads(rv.data.decode("utf-8"))
assert data == {
"message": {
"chart": "Chart does not exist",
"database": "Database does not exist",
}
}
# Test dashboard does not exist
dashboard_max_id = db.session.query(func.max(Dashboard.id)).scalar()
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"crontab": "0 9 * * *",
"dashboard": dashboard_max_id + 1,
"database": examples_db.id,
}
uri = f"api/v1/report/{report_schedule.id}"
rv = self.client.put(uri, json=report_schedule_data)
assert rv.status_code == 422
data = json.loads(rv.data.decode("utf-8"))
assert data == {"message": {"dashboard": "Dashboard does not exist"}}
@pytest.mark.usefixtures("create_report_schedules")
@pytest.mark.usefixtures("create_alpha_users")
def test_update_report_not_owned(self):
"""
ReportSchedule API: Test update report not owned
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name2")
.one_or_none()
)
self.login(username="alpha2", password="password")
report_schedule_data = {
"active": False,
}
uri = f"api/v1/report/{report_schedule.id}"
rv = self.put_assert_metric(uri, report_schedule_data, "put")
self.assertEqual(rv.status_code, 403)
@pytest.mark.usefixtures("create_report_schedules")
def test_delete_report_schedule(self):
"""
ReportSchedule Api: Test update report schedule
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name1")
.one_or_none()
)
self.login(username="admin")
uri = f"api/v1/report/{report_schedule.id}"
rv = self.client.delete(uri)
assert rv.status_code == 200
deleted_report_schedule = db.session.query(ReportSchedule).get(
report_schedule.id
)
assert deleted_report_schedule is None
deleted_recipients = (
db.session.query(ReportRecipients)
.filter(ReportRecipients.report_schedule_id == report_schedule.id)
.all()
)
assert deleted_recipients == []
deleted_logs = (
db.session.query(ReportExecutionLog)
.filter(ReportExecutionLog.report_schedule_id == report_schedule.id)
.all()
)
assert deleted_logs == []
@pytest.mark.usefixtures("create_report_schedules")
def test_delete_report_schedule_not_found(self):
"""
ReportSchedule Api: Test delete report schedule not found
"""
max_id = db.session.query(func.max(ReportSchedule.id)).scalar()
self.login(username="admin")
uri = f"api/v1/report/{max_id + 1}"
rv = self.client.delete(uri)
assert rv.status_code == 404
@pytest.mark.usefixtures("create_report_schedules")
@pytest.mark.usefixtures("create_alpha_users")
def test_delete_report_not_owned(self):
"""
ReportSchedule API: Test delete try not owned
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name2")
.one_or_none()
)
self.login(username="alpha2", password="password")
uri = f"api/v1/report/{report_schedule.id}"
rv = self.client.delete(uri)
self.assertEqual(rv.status_code, 403)
@pytest.mark.usefixtures("create_report_schedules")
def test_bulk_delete_report_schedule(self):
"""
ReportSchedule Api: Test bulk delete report schedules
"""
query_report_schedules = db.session.query(ReportSchedule)
report_schedules = query_report_schedules.all()
report_schedules_ids = [
report_schedule.id for report_schedule in report_schedules
]
self.login(username="admin")
uri = f"api/v1/report/?q={prison.dumps(report_schedules_ids)}"
rv = self.client.delete(uri)
assert rv.status_code == 200
deleted_report_schedules = query_report_schedules.all()
assert deleted_report_schedules == []
response = json.loads(rv.data.decode("utf-8"))
expected_response = {
"message": f"Deleted {len(report_schedules_ids)} report schedules"
}
assert response == expected_response
@pytest.mark.usefixtures("create_report_schedules")
def test_bulk_delete_report_schedule_not_found(self):
"""
ReportSchedule Api: Test bulk delete report schedule not found
"""
report_schedules = db.session.query(ReportSchedule).all()
report_schedules_ids = [
report_schedule.id for report_schedule in report_schedules
]
max_id = db.session.query(func.max(ReportSchedule.id)).scalar()
report_schedules_ids.append(max_id + 1)
self.login(username="admin")
uri = f"api/v1/report/?q={prison.dumps(report_schedules_ids)}"
rv = self.client.delete(uri)
assert rv.status_code == 404
@pytest.mark.usefixtures("create_report_schedules")
@pytest.mark.usefixtures("create_alpha_users")
def test_bulk_delete_report_not_owned(self):
"""
ReportSchedule API: Test bulk delete try not owned
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name2")
.one_or_none()
)
report_schedules_ids = [report_schedule.id]
self.login(username="alpha2", password="password")
uri = f"api/v1/report/?q={prison.dumps(report_schedules_ids)}"
rv = self.client.delete(uri)
self.assertEqual(rv.status_code, 403)
@pytest.mark.usefixtures("create_report_schedules")
def test_get_list_report_schedule_logs(self):
"""
ReportSchedule Api: Test get list report schedules logs
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name3")
.one_or_none()
)
self.login(username="admin")
uri = f"api/v1/report/{report_schedule.id}/log/"
rv = self.client.get(uri)
assert rv.status_code == 200
data = json.loads(rv.data.decode("utf-8"))
assert data["count"] == 3
@pytest.mark.usefixtures("create_report_schedules")
def test_get_list_report_schedule_logs_sorting(self):
"""
ReportSchedule Api: Test get list report schedules logs
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name3")
.one_or_none()
)
self.login(username="admin")
uri = f"api/v1/report/{report_schedule.id}/log/"
order_columns = [
"state",
"value",
"error_message",
"end_dttm",
"start_dttm",
"scheduled_dttm",
]
for order_column in order_columns:
arguments = {"order_column": order_column, "order_direction": "asc"}
uri = f"api/v1/report/{report_schedule.id}/log/?q={prison.dumps(arguments)}"
rv = self.get_assert_metric(uri, "get_list")
if rv.status_code == 400:
raise Exception(json.loads(rv.data.decode("utf-8")))
assert rv.status_code == 200
@pytest.mark.usefixtures("create_report_schedules")
def test_get_list_report_schedule_logs_filters(self):
"""
ReportSchedule Api: Test get list report schedules log filters
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name3")
.one_or_none()
)
self.login(username="admin")
arguments = {
"columns": ["name"],
"filters": [{"col": "state", "opr": "eq", "value": ReportState.SUCCESS}],
}
uri = f"api/v1/report/{report_schedule.id}/log/?q={prison.dumps(arguments)}"
rv = self.get_assert_metric(uri, "get_list")
assert rv.status_code == 200
data = json.loads(rv.data.decode("utf-8"))
assert data["count"] == 0
@pytest.mark.usefixtures("create_report_schedules")
def test_report_schedule_logs_no_mutations(self):
"""
ReportSchedule Api: Test assert there's no way to alter logs
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name3")
.one_or_none()
)
data = {"state": ReportState.ERROR, "error_message": "New error changed"}
self.login(username="admin")
uri = f"api/v1/report/{report_schedule.id}/log/"
rv = self.client.post(uri, json=data)
assert rv.status_code == 405
uri = f"api/v1/report/{report_schedule.id}/log/{report_schedule.logs[0].id}"
rv = self.client.put(uri, json=data)
assert rv.status_code == 405
rv = self.client.delete(uri)
assert rv.status_code == 405
@pytest.mark.usefixtures("create_report_schedules")
@pytest.mark.usefixtures("tabbed_dashboard")
def test_when_invalid_tab_ids_are_given_it_raises_bad_request(self):
"""
when tab ids are specified in the extra argument, make sure that the
tab ids are valid.
"""
self.login(username="admin")
dashboard = (
db.session.query(Dashboard)
.filter(Dashboard.slug == "tabbed-dash-test")
.first()
)
example_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"crontab": "0 9 * * *",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
},
],
"grace_period": 14400,
"working_timeout": 3600,
"chart": None,
"dashboard": dashboard.id,
"database": example_db.id,
"extra": {"dashboard_tab_ids": ["INVALID-TAB-ID-1", "TABS-IpViLohnyP"]},
}
response = self.client.post("api/v1/report/", json=report_schedule_data)
assert response.status_code == 422
assert response.json == {
"message": {"extra": ["Invalid tab IDs selected: ['INVALID-TAB-ID-1']"]}
}
@pytest.mark.usefixtures("create_report_schedules")
@pytest.mark.usefixtures("tabbed_dashboard")
def test_when_tab_ids_are_given_it_gets_added_to_extra(self):
self.login(username="admin")
dashboard = (
db.session.query(Dashboard)
.filter(Dashboard.slug == "tabbed-dash-test")
.first()
)
example_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"crontab": "0 9 * * *",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
},
],
"grace_period": 14400,
"working_timeout": 3600,
"chart": None,
"dashboard": dashboard.id,
"database": example_db.id,
"extra": {"dashboard_tab_ids": ["TABS-IpViLohnyP"]},
}
response = self.client.post("api/v1/report/", json=report_schedule_data)
assert response.status_code == 201
assert json.loads(
db.session.query(ReportSchedule)
.filter(ReportSchedule.id == response.json["id"])
.first()
.extra
) == {"dashboard_tab_ids": ["TABS-IpViLohnyP"]}
| # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# isort:skip_file
"""Unit tests for Superset"""
from datetime import datetime
import json
import pytz
import pytest
import prison
from sqlalchemy.sql import func
from superset import db
from superset.models.core import Database
from superset.models.slice import Slice
from superset.models.dashboard import Dashboard
from superset.models.reports import (
ReportSchedule,
ReportCreationMethodType,
ReportRecipients,
ReportExecutionLog,
ReportScheduleType,
ReportRecipientType,
ReportState,
)
from superset.utils.core import get_example_database
from tests.integration_tests.base_tests import SupersetTestCase
from tests.integration_tests.conftest import with_feature_flags
from tests.integration_tests.fixtures.birth_names_dashboard import (
load_birth_names_dashboard_with_slices,
load_birth_names_data,
)
from tests.integration_tests.fixtures.tabbed_dashboard import tabbed_dashboard
from tests.integration_tests.reports.utils import insert_report_schedule
REPORTS_COUNT = 10
class TestReportSchedulesApi(SupersetTestCase):
@pytest.fixture()
def create_working_report_schedule(self):
with self.create_app().app_context():
admin_user = self.get_user("admin")
alpha_user = self.get_user("alpha")
chart = db.session.query(Slice).first()
example_db = get_example_database()
report_schedule = insert_report_schedule(
type=ReportScheduleType.ALERT,
name="name_working",
crontab="* * * * *",
sql="SELECT value from table",
description="Report working",
chart=chart,
database=example_db,
owners=[admin_user, alpha_user],
last_state=ReportState.WORKING,
)
yield
db.session.delete(report_schedule)
db.session.commit()
@pytest.fixture()
def create_report_schedules(self):
with self.create_app().app_context():
report_schedules = []
admin_user = self.get_user("admin")
alpha_user = self.get_user("alpha")
chart = db.session.query(Slice).first()
example_db = get_example_database()
for cx in range(REPORTS_COUNT):
recipients = []
logs = []
for cy in range(cx):
config_json = {"target": f"target{cy}@email.com"}
recipients.append(
ReportRecipients(
type=ReportRecipientType.EMAIL,
recipient_config_json=json.dumps(config_json),
)
)
logs.append(
ReportExecutionLog(
scheduled_dttm=datetime(2020, 1, 1),
state=ReportState.ERROR,
error_message=f"Error {cy}",
)
)
report_schedules.append(
insert_report_schedule(
type=ReportScheduleType.ALERT,
name=f"name{cx}",
crontab=f"*/{cx} * * * *",
sql=f"SELECT value from table{cx}",
description=f"Some description {cx}",
chart=chart,
database=example_db,
owners=[admin_user, alpha_user],
recipients=recipients,
logs=logs,
)
)
yield report_schedules
report_schedules = db.session.query(ReportSchedule).all()
# rollback changes (assuming cascade delete)
for report_schedule in report_schedules:
db.session.delete(report_schedule)
db.session.commit()
@pytest.fixture()
def create_alpha_users(self):
with self.create_app().app_context():
users = [
self.create_user(
"alpha1", "password", "Alpha", email="alpha1@superset.org"
),
self.create_user(
"alpha2", "password", "Alpha", email="alpha2@superset.org"
),
]
yield users
# rollback changes (assuming cascade delete)
for user in users:
db.session.delete(user)
db.session.commit()
@with_feature_flags(ALERT_REPORTS=False)
@pytest.mark.usefixtures("create_report_schedules")
def test_get_report_schedule_disabled(self):
"""
ReportSchedule Api: Test get report schedule 404s when feature is disabled
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name1")
.first()
)
self.login(username="admin")
uri = f"api/v1/report/{report_schedule.id}"
rv = self.client.get(uri)
assert rv.status_code == 404
@pytest.mark.usefixtures("create_report_schedules")
def test_get_report_schedule(self):
"""
ReportSchedule Api: Test get report schedule
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name1")
.first()
)
self.login(username="admin")
uri = f"api/v1/report/{report_schedule.id}"
rv = self.get_assert_metric(uri, "get")
data = json.loads(rv.data.decode("utf-8"))
assert rv.status_code == 200
expected_result = {
"active": report_schedule.active,
"chart": {
"id": report_schedule.chart.id,
"slice_name": report_schedule.chart.slice_name,
"viz_type": report_schedule.chart.viz_type,
},
"context_markdown": report_schedule.context_markdown,
"crontab": report_schedule.crontab,
"dashboard": None,
"database": {
"id": report_schedule.database.id,
"database_name": report_schedule.database.database_name,
},
"description": report_schedule.description,
"grace_period": report_schedule.grace_period,
"id": report_schedule.id,
"last_eval_dttm": report_schedule.last_eval_dttm,
"last_state": report_schedule.last_state,
"last_value": report_schedule.last_value,
"last_value_row_json": report_schedule.last_value_row_json,
"log_retention": report_schedule.log_retention,
"name": report_schedule.name,
"recipients": [
{
"id": report_schedule.recipients[0].id,
"recipient_config_json": '{"target": "target0@email.com"}',
"type": "Email",
}
],
"timezone": report_schedule.timezone,
"type": report_schedule.type,
"validator_config_json": report_schedule.validator_config_json,
"validator_type": report_schedule.validator_type,
}
for key in expected_result:
assert data["result"][key] == expected_result[key]
# needed because order may vary
assert {"first_name": "admin", "id": 1, "last_name": "user"} in data["result"][
"owners"
]
assert {"first_name": "alpha", "id": 5, "last_name": "user"} in data["result"][
"owners"
]
assert len(data["result"]["owners"]) == 2
def test_info_report_schedule(self):
"""
ReportSchedule API: Test info
"""
self.login(username="admin")
uri = f"api/v1/report/_info"
rv = self.get_assert_metric(uri, "info")
assert rv.status_code == 200
def test_info_security_report(self):
"""
ReportSchedule API: Test info security
"""
self.login(username="admin")
params = {"keys": ["permissions"]}
uri = f"api/v1/report/_info?q={prison.dumps(params)}"
rv = self.get_assert_metric(uri, "info")
data = json.loads(rv.data.decode("utf-8"))
assert rv.status_code == 200
assert "can_read" in data["permissions"]
assert "can_write" in data["permissions"]
assert len(data["permissions"]) == 2
@pytest.mark.usefixtures("create_report_schedules")
def test_get_report_schedule_not_found(self):
"""
ReportSchedule Api: Test get report schedule not found
"""
max_id = db.session.query(func.max(ReportSchedule.id)).scalar()
self.login(username="admin")
uri = f"api/v1/report/{max_id + 1}"
rv = self.get_assert_metric(uri, "get")
assert rv.status_code == 404
@pytest.mark.usefixtures("create_report_schedules")
def test_get_list_report_schedule(self):
"""
ReportSchedule Api: Test get list report schedules
"""
self.login(username="admin")
uri = f"api/v1/report/"
rv = self.get_assert_metric(uri, "get_list")
expected_fields = [
"active",
"changed_by",
"changed_on",
"changed_on_delta_humanized",
"created_by",
"created_on",
"creation_method",
"crontab",
"crontab_humanized",
"description",
"id",
"last_eval_dttm",
"last_state",
"name",
"owners",
"recipients",
"timezone",
"type",
]
assert rv.status_code == 200
data = json.loads(rv.data.decode("utf-8"))
assert data["count"] == REPORTS_COUNT
data_keys = sorted(list(data["result"][0].keys()))
assert expected_fields == data_keys
# Assert nested fields
expected_owners_fields = ["first_name", "id", "last_name"]
data_keys = sorted(list(data["result"][0]["owners"][0].keys()))
assert expected_owners_fields == data_keys
expected_recipients_fields = ["id", "type"]
data_keys = sorted(list(data["result"][1]["recipients"][0].keys()))
assert expected_recipients_fields == data_keys
@pytest.mark.usefixtures("create_report_schedules")
def test_get_list_report_schedule_sorting(self):
"""
ReportSchedule Api: Test sorting on get list report schedules
"""
self.login(username="admin")
uri = "api/v1/report/"
order_columns = [
"active",
"created_by.first_name",
"changed_by.first_name",
"changed_on",
"changed_on_delta_humanized",
"created_on",
"crontab",
"description",
"last_eval_dttm",
"name",
"type",
"crontab_humanized",
]
for order_column in order_columns:
arguments = {"order_column": order_column, "order_direction": "asc"}
uri = f"api/v1/report/?q={prison.dumps(arguments)}"
rv = self.get_assert_metric(uri, "get_list")
assert rv.status_code == 200
@pytest.mark.usefixtures("create_report_schedules")
def test_get_list_report_schedule_filter_name(self):
"""
ReportSchedule Api: Test filter name on get list report schedules
"""
self.login(username="admin")
# Test normal contains filter
arguments = {
"columns": ["name"],
"filters": [{"col": "name", "opr": "ct", "value": "2"}],
}
uri = f"api/v1/report/?q={prison.dumps(arguments)}"
rv = self.get_assert_metric(uri, "get_list")
expected_result = {
"name": "name2",
}
assert rv.status_code == 200
data = json.loads(rv.data.decode("utf-8"))
assert data["count"] == 1
assert data["result"][0] == expected_result
@pytest.mark.usefixtures("create_report_schedules")
def test_get_list_report_schedule_filter_custom(self):
"""
ReportSchedule Api: Test custom filter on get list report schedules
"""
self.login(username="admin")
# Test custom all text filter
arguments = {
"columns": ["name"],
"filters": [{"col": "name", "opr": "report_all_text", "value": "table3"}],
}
uri = f"api/v1/report/?q={prison.dumps(arguments)}"
rv = self.get_assert_metric(uri, "get_list")
expected_result = {
"name": "name3",
}
assert rv.status_code == 200
data = json.loads(rv.data.decode("utf-8"))
assert data["count"] == 1
assert data["result"][0] == expected_result
@pytest.mark.usefixtures("create_report_schedules")
def test_get_list_report_schedule_filter_active(self):
"""
ReportSchedule Api: Test active filter on get list report schedules
"""
self.login(username="admin")
arguments = {
"columns": ["name"],
"filters": [{"col": "active", "opr": "eq", "value": True}],
}
uri = f"api/v1/report/?q={prison.dumps(arguments)}"
rv = self.get_assert_metric(uri, "get_list")
assert rv.status_code == 200
data = json.loads(rv.data.decode("utf-8"))
assert data["count"] == REPORTS_COUNT
@pytest.mark.usefixtures("create_report_schedules")
def test_get_list_report_schedule_filter_type(self):
"""
ReportSchedule Api: Test type filter on get list report schedules
"""
self.login(username="admin")
arguments = {
"columns": ["name"],
"filters": [
{"col": "type", "opr": "eq", "value": ReportScheduleType.ALERT}
],
}
uri = f"api/v1/report/?q={prison.dumps(arguments)}"
rv = self.get_assert_metric(uri, "get_list")
assert rv.status_code == 200
data = json.loads(rv.data.decode("utf-8"))
assert data["count"] == REPORTS_COUNT
# Test type filter
arguments = {
"columns": ["name"],
"filters": [
{"col": "type", "opr": "eq", "value": ReportScheduleType.REPORT}
],
}
uri = f"api/v1/report/?q={prison.dumps(arguments)}"
rv = self.get_assert_metric(uri, "get_list")
assert rv.status_code == 200
data = json.loads(rv.data.decode("utf-8"))
assert data["count"] == 0
@pytest.mark.usefixtures("create_report_schedules")
def test_get_related_report_schedule(self):
"""
ReportSchedule Api: Test get releated report schedule
"""
self.login(username="admin")
related_columns = ["owners", "chart", "dashboard", "database"]
for related_column in related_columns:
uri = f"api/v1/report/related/{related_column}"
rv = self.client.get(uri)
assert rv.status_code == 200
@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
def test_create_report_schedule(self):
"""
ReportSchedule Api: Test create report schedule
"""
self.login(username="admin")
chart = db.session.query(Slice).first()
example_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"crontab": "0 9 * * *",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
},
{
"type": ReportRecipientType.SLACK,
"recipient_config_json": {"target": "channel"},
},
],
"grace_period": 14400,
"working_timeout": 3600,
"chart": chart.id,
"database": example_db.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
data = json.loads(rv.data.decode("utf-8"))
assert rv.status_code == 201
created_model = db.session.query(ReportSchedule).get(data.get("id"))
assert created_model is not None
assert created_model.name == report_schedule_data["name"]
assert created_model.grace_period == report_schedule_data["grace_period"]
assert created_model.working_timeout == report_schedule_data["working_timeout"]
assert created_model.description == report_schedule_data["description"]
assert created_model.crontab == report_schedule_data["crontab"]
assert created_model.chart.id == report_schedule_data["chart"]
assert created_model.database.id == report_schedule_data["database"]
assert created_model.creation_method == report_schedule_data["creation_method"]
# Rollback changes
db.session.delete(created_model)
db.session.commit()
@pytest.mark.usefixtures("create_report_schedules")
def test_create_report_schedule_uniqueness(self):
"""
ReportSchedule Api: Test create report schedule uniqueness
"""
self.login(username="admin")
chart = db.session.query(Slice).first()
example_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "name3",
"description": "description",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"crontab": "0 9 * * *",
"chart": chart.id,
"database": example_db.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 422
data = json.loads(rv.data.decode("utf-8"))
assert data == {"message": {"name": ["Name must be unique"]}}
# Check that uniqueness is composed by name and type
report_schedule_data = {
"type": ReportScheduleType.REPORT,
"name": "name3",
"description": "description",
"crontab": "0 9 * * *",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"chart": chart.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 201
data = json.loads(rv.data.decode("utf-8"))
# Rollback changes
created_model = db.session.query(ReportSchedule).get(data.get("id"))
db.session.delete(created_model)
db.session.commit()
@pytest.mark.usefixtures(
"load_birth_names_dashboard_with_slices", "create_report_schedules"
)
def test_create_report_schedule_schema(self):
"""
ReportSchedule Api: Test create report schedule schema check
"""
self.login(username="admin")
chart = db.session.query(Slice).first()
dashboard = db.session.query(Dashboard).first()
example_db = get_example_database()
# Check that a report does not have a database reference
report_schedule_data = {
"type": ReportScheduleType.REPORT,
"name": "name3",
"description": "description",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"crontab": "0 9 * * *",
"chart": chart.id,
"database": example_db.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 400
# Test that report can be created with null grace period
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"crontab": "0 9 * * *",
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
},
{
"type": ReportRecipientType.SLACK,
"recipient_config_json": {"target": "channel"},
},
],
"working_timeout": 3600,
"chart": chart.id,
"database": example_db.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 201
# Test that grace period and working timeout cannot be < 1
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"crontab": "0 9 * * *",
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
},
{
"type": ReportRecipientType.SLACK,
"recipient_config_json": {"target": "channel"},
},
],
"working_timeout": -10,
"chart": chart.id,
"database": example_db.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 400
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"crontab": "0 9 * * *",
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
},
{
"type": ReportRecipientType.SLACK,
"recipient_config_json": {"target": "channel"},
},
],
"grace_period": -10,
"working_timeout": 3600,
"chart": chart.id,
"database": example_db.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 400
# Test that report can be created with null dashboard
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new4",
"description": "description",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"crontab": "0 9 * * *",
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
},
{
"type": ReportRecipientType.SLACK,
"recipient_config_json": {"target": "channel"},
},
],
"working_timeout": 3600,
"chart": chart.id,
"dashboard": None,
"database": example_db.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 201
# Test that report can be created with null chart
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new5",
"description": "description",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"crontab": "0 9 * * *",
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
},
{
"type": ReportRecipientType.SLACK,
"recipient_config_json": {"target": "channel"},
},
],
"working_timeout": 3600,
"chart": None,
"dashboard": dashboard.id,
"database": example_db.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 201
# Test that report cannot be created with null timezone
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new5",
"description": "description",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"crontab": "0 9 * * *",
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
},
{
"type": ReportRecipientType.SLACK,
"recipient_config_json": {"target": "channel"},
},
],
"working_timeout": 3600,
"timezone": None,
"dashboard": dashboard.id,
"database": example_db.id,
}
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 400
data = json.loads(rv.data.decode("utf-8"))
assert data == {"message": {"timezone": ["Field may not be null."]}}
# Test that report cannot be created with an invalid timezone
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new5",
"description": "description",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"crontab": "0 9 * * *",
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
},
{
"type": ReportRecipientType.SLACK,
"recipient_config_json": {"target": "channel"},
},
],
"working_timeout": 3600,
"timezone": "this is not a timezone",
"dashboard": dashboard.id,
"database": example_db.id,
}
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 400
data = json.loads(rv.data.decode("utf-8"))
assert data == {
"message": {
"timezone": [f"Must be one of: {', '.join(pytz.all_timezones)}."]
}
}
# Test that report should reflect the timezone value passed in
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new6",
"description": "description",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"crontab": "0 9 * * *",
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
},
{
"type": ReportRecipientType.SLACK,
"recipient_config_json": {"target": "channel"},
},
],
"working_timeout": 3600,
"timezone": "America/Los_Angeles",
"dashboard": dashboard.id,
"database": example_db.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
data = json.loads(rv.data.decode("utf-8"))
assert data["result"]["timezone"] == "America/Los_Angeles"
assert rv.status_code == 201
@pytest.mark.usefixtures(
"load_birth_names_dashboard_with_slices", "create_report_schedules"
)
def test_unsaved_report_schedule_schema(self):
"""
ReportSchedule Api: Test create report schedule with unsaved chart
"""
self.login(username="admin")
chart = db.session.query(Slice).first()
dashboard = db.session.query(Dashboard).first()
example_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.REPORT,
"name": "name3",
"description": "description",
"creation_method": ReportCreationMethodType.CHARTS,
"crontab": "0 9 * * *",
"chart": 0,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
data = json.loads(rv.data.decode("utf-8"))
assert rv.status_code == 422
assert (
data["message"]["chart"]
== "Please save your chart first, then try creating a new email report."
)
@pytest.mark.usefixtures(
"load_birth_names_dashboard_with_slices", "create_report_schedules"
)
def test_no_dashboard_report_schedule_schema(self):
"""
ReportSchedule Api: Test create report schedule with no dashboard id
"""
self.login(username="admin")
chart = db.session.query(Slice).first()
dashboard = db.session.query(Dashboard).first()
example_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.REPORT,
"name": "name3",
"description": "description",
"creation_method": ReportCreationMethodType.DASHBOARDS,
"crontab": "0 9 * * *",
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
data = json.loads(rv.data.decode("utf-8"))
assert rv.status_code == 422
assert (
data["message"]["dashboard"]
== "Please save your dashboard first, then try creating a new email report."
)
@pytest.mark.usefixtures(
"load_birth_names_dashboard_with_slices", "create_report_schedules"
)
def test_create_multiple_creation_method_report_schedule_charts(self):
"""
ReportSchedule Api: Test create multiple reports with the same creation method
"""
self.login(username="admin")
chart = db.session.query(Slice).first()
dashboard = db.session.query(Dashboard).first()
example_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.REPORT,
"name": "name4",
"description": "description",
"creation_method": ReportCreationMethodType.CHARTS,
"crontab": "0 9 * * *",
"working_timeout": 3600,
"chart": chart.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
data = json.loads(rv.data.decode("utf-8"))
assert rv.status_code == 201
# this second time it should receive an error because the chart has an attached report
# with the same creation method from the same user.
report_schedule_data = {
"type": ReportScheduleType.REPORT,
"name": "name5",
"description": "description",
"creation_method": ReportCreationMethodType.CHARTS,
"crontab": "0 9 * * *",
"working_timeout": 3600,
"chart": chart.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
data = json.loads(rv.data.decode("utf-8"))
assert rv.status_code == 409
assert data == {
"errors": [
{
"message": "Resource already has an attached report.",
"error_type": "GENERIC_COMMAND_ERROR",
"level": "warning",
"extra": {
"issue_codes": [
{
"code": 1010,
"message": "Issue 1010 - Superset encountered an error while running a command.",
}
]
},
}
]
}
@pytest.mark.usefixtures(
"load_birth_names_dashboard_with_slices", "create_report_schedules"
)
def test_create_multiple_creation_method_report_schedule_dashboards(self):
"""
ReportSchedule Api: Test create multiple reports with the same creation method
"""
self.login(username="admin")
chart = db.session.query(Slice).first()
dashboard = db.session.query(Dashboard).first()
example_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.REPORT,
"name": "name4",
"description": "description",
"creation_method": ReportCreationMethodType.DASHBOARDS,
"crontab": "0 9 * * *",
"working_timeout": 3600,
"dashboard": dashboard.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
data = json.loads(rv.data.decode("utf-8"))
assert rv.status_code == 201
# this second time it should receive an error because the dashboard has an attached report
# with the same creation method from the same user.
report_schedule_data = {
"type": ReportScheduleType.REPORT,
"name": "name5",
"description": "description",
"creation_method": ReportCreationMethodType.DASHBOARDS,
"crontab": "0 9 * * *",
"working_timeout": 3600,
"dashboard": dashboard.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
data = json.loads(rv.data.decode("utf-8"))
assert rv.status_code == 409
assert data == {
"errors": [
{
"message": "Resource already has an attached report.",
"error_type": "GENERIC_COMMAND_ERROR",
"level": "warning",
"extra": {
"issue_codes": [
{
"code": 1010,
"message": "Issue 1010 - Superset encountered an error while running a command.",
}
]
},
}
]
}
@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
def test_create_report_schedule_chart_dash_validation(self):
"""
ReportSchedule Api: Test create report schedule chart and dashboard validation
"""
self.login(username="admin")
# Test we can submit a chart or a dashboard not both
chart = db.session.query(Slice).first()
dashboard = db.session.query(Dashboard).first()
example_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"crontab": "0 9 * * *",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"chart": chart.id,
"dashboard": dashboard.id,
"database": example_db.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 422
data = json.loads(rv.data.decode("utf-8"))
assert data == {"message": {"chart": "Choose a chart or dashboard not both"}}
@pytest.mark.usefixtures("create_report_schedules")
def test_create_report_schedule_chart_db_validation(self):
"""
ReportSchedule Api: Test create report schedule chart and database validation
"""
self.login(username="admin")
# Test database required for alerts
chart = db.session.query(Slice).first()
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"crontab": "0 9 * * *",
"chart": chart.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 422
data = json.loads(rv.data.decode("utf-8"))
assert data == {"message": {"database": "Database is required for alerts"}}
@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
def test_create_report_schedule_relations_exist(self):
"""
ReportSchedule Api: Test create report schedule
relations (chart, dash, db) exist
"""
self.login(username="admin")
# Test chart and database do not exist
chart_max_id = db.session.query(func.max(Slice.id)).scalar()
database_max_id = db.session.query(func.max(Database.id)).scalar()
examples_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"crontab": "0 9 * * *",
"chart": chart_max_id + 1,
"database": database_max_id + 1,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 422
data = json.loads(rv.data.decode("utf-8"))
assert data == {
"message": {
"chart": "Chart does not exist",
"database": "Database does not exist",
}
}
# Test dashboard does not exist
dashboard_max_id = db.session.query(func.max(Dashboard.id)).scalar()
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"crontab": "0 9 * * *",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"dashboard": dashboard_max_id + 1,
"database": examples_db.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
assert rv.status_code == 422
data = json.loads(rv.data.decode("utf-8"))
assert data == {"message": {"dashboard": "Dashboard does not exist"}}
# @pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
# TODO (AAfghahi): I am going to enable this when the report schedule feature is fully finished
# def test_create_report_schedule_no_creation_method(self):
# """
# ReportSchedule Api: Test create report schedule
# """
# self.login(username="admin")
# chart = db.session.query(Slice).first()
# example_db = get_example_database()
# report_schedule_data = {
# "type": ReportScheduleType.ALERT,
# "name": "new3",
# "description": "description",
# "crontab": "0 9 * * *",
# "recipients": [
# {
# "type": ReportRecipientType.EMAIL,
# "recipient_config_json": {"target": "target@superset.org"},
# },
# {
# "type": ReportRecipientType.SLACK,
# "recipient_config_json": {"target": "channel"},
# },
# ],
# "grace_period": 14400,
# "working_timeout": 3600,
# "chart": chart.id,
# "database": example_db.id,
# }
# uri = "api/v1/report/"
# rv = self.client.post(uri, json=report_schedule_data)
# response = json.loads(rv.data.decode("utf-8"))
# assert response == {
# "message": {"creation_method": ["Missing data for required field."]}
# }
# assert rv.status_code == 400
@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
def test_create_report_schedule_invalid_creation_method(self):
"""
ReportSchedule API: Test create report schedule
"""
self.login(username="admin")
chart = db.session.query(Slice).first()
example_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"creation_method": "BAD_CREATION_METHOD",
"crontab": "0 9 * * *",
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
},
{
"type": ReportRecipientType.SLACK,
"recipient_config_json": {"target": "channel"},
},
],
"grace_period": 14400,
"working_timeout": 3600,
"chart": chart.id,
"database": example_db.id,
}
uri = "api/v1/report/"
rv = self.client.post(uri, json=report_schedule_data)
response = json.loads(rv.data.decode("utf-8"))
assert response == {
"message": {"creation_method": ["Invalid enum value BAD_CREATION_METHOD"]}
}
assert rv.status_code == 400
@pytest.mark.usefixtures("create_report_schedules")
def test_update_report_schedule(self):
"""
ReportSchedule Api: Test update report schedule
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name2")
.one_or_none()
)
self.login(username="admin")
chart = db.session.query(Slice).first()
example_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "changed",
"description": "description",
"crontab": "0 10 * * *",
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
}
],
"chart": chart.id,
"database": example_db.id,
}
uri = f"api/v1/report/{report_schedule.id}"
rv = self.client.put(uri, json=report_schedule_data)
assert rv.status_code == 200
updated_model = db.session.query(ReportSchedule).get(report_schedule.id)
assert updated_model is not None
assert updated_model.name == report_schedule_data["name"]
assert updated_model.description == report_schedule_data["description"]
assert len(updated_model.recipients) == 1
assert updated_model.crontab == report_schedule_data["crontab"]
assert updated_model.chart_id == report_schedule_data["chart"]
assert updated_model.database_id == report_schedule_data["database"]
@pytest.mark.usefixtures("create_working_report_schedule")
def test_update_report_schedule_state_working(self):
"""
ReportSchedule Api: Test update state in a working report
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name_working")
.one_or_none()
)
self.login(username="admin")
report_schedule_data = {"active": False}
uri = f"api/v1/report/{report_schedule.id}"
rv = self.client.put(uri, json=report_schedule_data)
assert rv.status_code == 200
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name_working")
.one_or_none()
)
assert report_schedule.last_state == ReportState.NOOP
@pytest.mark.usefixtures("create_report_schedules")
def test_update_report_schedule_uniqueness(self):
"""
ReportSchedule Api: Test update report schedule uniqueness
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name2")
.one_or_none()
)
self.login(username="admin")
report_schedule_data = {"name": "name3", "description": "changed_description"}
uri = f"api/v1/report/{report_schedule.id}"
rv = self.client.put(uri, json=report_schedule_data)
data = json.loads(rv.data.decode("utf-8"))
assert rv.status_code == 422
assert data == {"message": {"name": ["Name must be unique"]}}
@pytest.mark.usefixtures("create_report_schedules")
def test_update_report_schedule_not_found(self):
"""
ReportSchedule Api: Test update report schedule not found
"""
max_id = db.session.query(func.max(ReportSchedule.id)).scalar()
self.login(username="admin")
report_schedule_data = {"name": "changed"}
uri = f"api/v1/report/{max_id + 1}"
rv = self.client.put(uri, json=report_schedule_data)
assert rv.status_code == 404
@pytest.mark.usefixtures(
"load_birth_names_dashboard_with_slices", "create_report_schedules"
)
def test_update_report_schedule_chart_dash_validation(self):
"""
ReportSchedule Api: Test update report schedule chart and dashboard validation
"""
self.login(username="admin")
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name2")
.one_or_none()
)
# Test we can submit a chart or a dashboard not both
chart = db.session.query(Slice).first()
dashboard = db.session.query(Dashboard).first()
example_db = get_example_database()
report_schedule_data = {
"chart": chart.id,
"dashboard": dashboard.id,
"database": example_db.id,
}
uri = f"api/v1/report/{report_schedule.id}"
rv = self.client.put(uri, json=report_schedule_data)
assert rv.status_code == 422
data = json.loads(rv.data.decode("utf-8"))
assert data == {"message": {"chart": "Choose a chart or dashboard not both"}}
@pytest.mark.usefixtures(
"load_birth_names_dashboard_with_slices", "create_report_schedules"
)
def test_update_report_schedule_relations_exist(self):
"""
ReportSchedule Api: Test update report schedule relations exist
relations (chart, dash, db) exist
"""
self.login(username="admin")
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name2")
.one_or_none()
)
# Test chart and database do not exist
chart_max_id = db.session.query(func.max(Slice.id)).scalar()
database_max_id = db.session.query(func.max(Database.id)).scalar()
examples_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"crontab": "0 9 * * *",
"chart": chart_max_id + 1,
"database": database_max_id + 1,
}
uri = f"api/v1/report/{report_schedule.id}"
rv = self.client.put(uri, json=report_schedule_data)
assert rv.status_code == 422
data = json.loads(rv.data.decode("utf-8"))
assert data == {
"message": {
"chart": "Chart does not exist",
"database": "Database does not exist",
}
}
# Test dashboard does not exist
dashboard_max_id = db.session.query(func.max(Dashboard.id)).scalar()
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"crontab": "0 9 * * *",
"dashboard": dashboard_max_id + 1,
"database": examples_db.id,
}
uri = f"api/v1/report/{report_schedule.id}"
rv = self.client.put(uri, json=report_schedule_data)
assert rv.status_code == 422
data = json.loads(rv.data.decode("utf-8"))
assert data == {"message": {"dashboard": "Dashboard does not exist"}}
@pytest.mark.usefixtures("create_report_schedules")
@pytest.mark.usefixtures("create_alpha_users")
def test_update_report_not_owned(self):
"""
ReportSchedule API: Test update report not owned
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name2")
.one_or_none()
)
self.login(username="alpha2", password="password")
report_schedule_data = {
"active": False,
}
uri = f"api/v1/report/{report_schedule.id}"
rv = self.put_assert_metric(uri, report_schedule_data, "put")
self.assertEqual(rv.status_code, 403)
@pytest.mark.usefixtures("create_report_schedules")
def test_delete_report_schedule(self):
"""
ReportSchedule Api: Test update report schedule
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name1")
.one_or_none()
)
self.login(username="admin")
uri = f"api/v1/report/{report_schedule.id}"
rv = self.client.delete(uri)
assert rv.status_code == 200
deleted_report_schedule = db.session.query(ReportSchedule).get(
report_schedule.id
)
assert deleted_report_schedule is None
deleted_recipients = (
db.session.query(ReportRecipients)
.filter(ReportRecipients.report_schedule_id == report_schedule.id)
.all()
)
assert deleted_recipients == []
deleted_logs = (
db.session.query(ReportExecutionLog)
.filter(ReportExecutionLog.report_schedule_id == report_schedule.id)
.all()
)
assert deleted_logs == []
@pytest.mark.usefixtures("create_report_schedules")
def test_delete_report_schedule_not_found(self):
"""
ReportSchedule Api: Test delete report schedule not found
"""
max_id = db.session.query(func.max(ReportSchedule.id)).scalar()
self.login(username="admin")
uri = f"api/v1/report/{max_id + 1}"
rv = self.client.delete(uri)
assert rv.status_code == 404
@pytest.mark.usefixtures("create_report_schedules")
@pytest.mark.usefixtures("create_alpha_users")
def test_delete_report_not_owned(self):
"""
ReportSchedule API: Test delete try not owned
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name2")
.one_or_none()
)
self.login(username="alpha2", password="password")
uri = f"api/v1/report/{report_schedule.id}"
rv = self.client.delete(uri)
self.assertEqual(rv.status_code, 403)
@pytest.mark.usefixtures("create_report_schedules")
def test_bulk_delete_report_schedule(self):
"""
ReportSchedule Api: Test bulk delete report schedules
"""
query_report_schedules = db.session.query(ReportSchedule)
report_schedules = query_report_schedules.all()
report_schedules_ids = [
report_schedule.id for report_schedule in report_schedules
]
self.login(username="admin")
uri = f"api/v1/report/?q={prison.dumps(report_schedules_ids)}"
rv = self.client.delete(uri)
assert rv.status_code == 200
deleted_report_schedules = query_report_schedules.all()
assert deleted_report_schedules == []
response = json.loads(rv.data.decode("utf-8"))
expected_response = {
"message": f"Deleted {len(report_schedules_ids)} report schedules"
}
assert response == expected_response
@pytest.mark.usefixtures("create_report_schedules")
def test_bulk_delete_report_schedule_not_found(self):
"""
ReportSchedule Api: Test bulk delete report schedule not found
"""
report_schedules = db.session.query(ReportSchedule).all()
report_schedules_ids = [
report_schedule.id for report_schedule in report_schedules
]
max_id = db.session.query(func.max(ReportSchedule.id)).scalar()
report_schedules_ids.append(max_id + 1)
self.login(username="admin")
uri = f"api/v1/report/?q={prison.dumps(report_schedules_ids)}"
rv = self.client.delete(uri)
assert rv.status_code == 404
@pytest.mark.usefixtures("create_report_schedules")
@pytest.mark.usefixtures("create_alpha_users")
def test_bulk_delete_report_not_owned(self):
"""
ReportSchedule API: Test bulk delete try not owned
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name2")
.one_or_none()
)
report_schedules_ids = [report_schedule.id]
self.login(username="alpha2", password="password")
uri = f"api/v1/report/?q={prison.dumps(report_schedules_ids)}"
rv = self.client.delete(uri)
self.assertEqual(rv.status_code, 403)
@pytest.mark.usefixtures("create_report_schedules")
def test_get_list_report_schedule_logs(self):
"""
ReportSchedule Api: Test get list report schedules logs
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name3")
.one_or_none()
)
self.login(username="admin")
uri = f"api/v1/report/{report_schedule.id}/log/"
rv = self.client.get(uri)
assert rv.status_code == 200
data = json.loads(rv.data.decode("utf-8"))
assert data["count"] == 3
@pytest.mark.usefixtures("create_report_schedules")
def test_get_list_report_schedule_logs_sorting(self):
"""
ReportSchedule Api: Test get list report schedules logs
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name3")
.one_or_none()
)
self.login(username="admin")
uri = f"api/v1/report/{report_schedule.id}/log/"
order_columns = [
"state",
"value",
"error_message",
"end_dttm",
"start_dttm",
"scheduled_dttm",
]
for order_column in order_columns:
arguments = {"order_column": order_column, "order_direction": "asc"}
uri = f"api/v1/report/{report_schedule.id}/log/?q={prison.dumps(arguments)}"
rv = self.get_assert_metric(uri, "get_list")
if rv.status_code == 400:
raise Exception(json.loads(rv.data.decode("utf-8")))
assert rv.status_code == 200
@pytest.mark.usefixtures("create_report_schedules")
def test_get_list_report_schedule_logs_filters(self):
"""
ReportSchedule Api: Test get list report schedules log filters
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name3")
.one_or_none()
)
self.login(username="admin")
arguments = {
"columns": ["name"],
"filters": [{"col": "state", "opr": "eq", "value": ReportState.SUCCESS}],
}
uri = f"api/v1/report/{report_schedule.id}/log/?q={prison.dumps(arguments)}"
rv = self.get_assert_metric(uri, "get_list")
assert rv.status_code == 200
data = json.loads(rv.data.decode("utf-8"))
assert data["count"] == 0
@pytest.mark.usefixtures("create_report_schedules")
def test_report_schedule_logs_no_mutations(self):
"""
ReportSchedule Api: Test assert there's no way to alter logs
"""
report_schedule = (
db.session.query(ReportSchedule)
.filter(ReportSchedule.name == "name3")
.one_or_none()
)
data = {"state": ReportState.ERROR, "error_message": "New error changed"}
self.login(username="admin")
uri = f"api/v1/report/{report_schedule.id}/log/"
rv = self.client.post(uri, json=data)
assert rv.status_code == 405
uri = f"api/v1/report/{report_schedule.id}/log/{report_schedule.logs[0].id}"
rv = self.client.put(uri, json=data)
assert rv.status_code == 405
rv = self.client.delete(uri)
assert rv.status_code == 405
@pytest.mark.usefixtures("create_report_schedules")
@pytest.mark.usefixtures("tabbed_dashboard")
def test_when_invalid_tab_ids_are_given_it_raises_bad_request(self):
"""
when tab ids are specified in the extra argument, make sure that the
tab ids are valid.
"""
self.login(username="admin")
dashboard = (
db.session.query(Dashboard)
.filter(Dashboard.slug == "tabbed-dash-test")
.first()
)
example_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"crontab": "0 9 * * *",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
},
],
"grace_period": 14400,
"working_timeout": 3600,
"chart": None,
"dashboard": dashboard.id,
"database": example_db.id,
"extra": {"dashboard_tab_ids": ["INVALID-TAB-ID-1", "TABS-IpViLohnyP"]},
}
response = self.client.post("api/v1/report/", json=report_schedule_data)
assert response.status_code == 422
assert response.json == {
"message": {"extra": ["Invalid tab IDs selected: ['INVALID-TAB-ID-1']"]}
}
@pytest.mark.usefixtures("create_report_schedules")
@pytest.mark.usefixtures("tabbed_dashboard")
def test_when_tab_ids_are_given_it_gets_added_to_extra(self):
self.login(username="admin")
dashboard = (
db.session.query(Dashboard)
.filter(Dashboard.slug == "tabbed-dash-test")
.first()
)
example_db = get_example_database()
report_schedule_data = {
"type": ReportScheduleType.ALERT,
"name": "new3",
"description": "description",
"crontab": "0 9 * * *",
"creation_method": ReportCreationMethodType.ALERTS_REPORTS,
"recipients": [
{
"type": ReportRecipientType.EMAIL,
"recipient_config_json": {"target": "target@superset.org"},
},
],
"grace_period": 14400,
"working_timeout": 3600,
"chart": None,
"dashboard": dashboard.id,
"database": example_db.id,
"extra": {"dashboard_tab_ids": ["TABS-IpViLohnyP"]},
}
response = self.client.post("api/v1/report/", json=report_schedule_data)
assert response.status_code == 201
assert json.loads(
db.session.query(ReportSchedule)
.filter(ReportSchedule.id == response.json["id"])
.first()
.extra
) == {"dashboard_tab_ids": ["TABS-IpViLohnyP"]}
|
"""Smoke tests ranging across the CIDC REST API.
This file doesn't contain tests for methods that don't directly correspond
to data resources, like endpoints that handle upload-related functionality.
"""
from cidc_api.models.templates.trial_metadata import ClinicalTrial
from collections import OrderedDict
from cidc_api.models.templates.utils import insert_record_batch
from copy import deepcopy
from unittest.mock import MagicMock
from datetime import datetime
from dateutil.parser import parse as parse_date
import pytest
from werkzeug.exceptions import BadRequest
from cidc_api.models import (
Users,
DownloadableFiles,
Permissions,
TrialMetadata,
UploadJobs,
UploadJobStatus,
CIDCRole,
BaseModel,
)
from .utils import mock_current_user, mock_gcloud_client
TEST_RECORD_ID = 1
# Configuration for resource tests below. For each resource, the following keywords are supported:
# `json` (required): a JSON instance of this resource.
# `model` (required): the SQLAlchemy model for this resource.
# `allowed_methods` (required): the HTTP methods this resource supports.
# `POST_setup`: a list of other resources to add to the database before POSTing this resource.
# `PATCH_json` (required if "PATCH" in `allowed_methods`): a JSON patch update for this resource.
# `lookup_func`: given a config, return the URL suffix for an item lookup, i.e., `<resource>/<suffix>`.
# `filters`: a dictionary containing two entries representing possible filter queries:
# `empty`: a query filter that should return empty results.
# `one`: a query filter that should return exactly one result.
# `additional_records`: a list of JSON instances of this resource to insert before testing pagination.
# `mocks`: a list of functions that accept pytest's `monkeypatch` as their argument.
users = {
"json": {
"email": "test-admin@example.com",
"id": TEST_RECORD_ID,
"role": CIDCRole.ADMIN.value,
"approval_date": str(datetime.now()),
},
"model": Users,
"allowed_methods": {"POST", "PATCH", "GET"},
"PATCH_json": {"role": CIDCRole.CIMAC_USER.value},
}
users["additional_records"] = [
{**users["json"], "id": 2, "email": "foo@bar.com"},
{**users["json"], "id": 3, "email": "fizz@buzz.com"},
]
trial_metadata = {
"json": {
"id": TEST_RECORD_ID,
"trial_id": "foo",
"metadata_json": {
"protocol_identifier": "foo",
"allowed_collection_event_names": [],
"allowed_cohort_names": [],
"participants": [],
},
},
"model": TrialMetadata,
"allowed_methods": {"POST", "PATCH", "GET"},
"lookup_func": lambda cfg: cfg["trial_id"],
"PATCH_json": {
"metadata_json": {
"protocol_identifier": "foo",
"allowed_collection_event_names": ["bar"],
"allowed_cohort_names": ["buzz"],
"participants": [],
}
},
}
downloadable_files = {
"json": {
"id": TEST_RECORD_ID,
"trial_id": trial_metadata["json"]["trial_id"],
"upload_type": "rna_bam",
"object_url": f'{trial_metadata['json']['trial_id']}/rna/.../r1_123.fastq.gz',
"facet_group": "/rna/reads_.bam",
"uploaded_timestamp": datetime.now(),
"file_size_bytes": 1,
},
"model": DownloadableFiles,
"allowed_methods": {"GET"},
"POST_setup": ["trial_metadata"],
"PATCH_json": {"upload_type": "fizzbuzz"},
"filters": {
"empty": {
"trial_ids": [trial_metadata["json"]["trial_id"]],
"facets": "Clinical Type|Participants Info",
},
"one": {
"trial_ids": [trial_metadata["json"]["trial_id"]],
"facets": "Assay Type|RNA|Source",
},
},
}
downloadable_files["additional_records"] = [
{**downloadable_files["json"], "id": 2, "object_url": "foo/bar"},
{**downloadable_files["json"], "id": 3, "object_url": "fizz/buzz"},
]
permissions = {
"json": {
"id": TEST_RECORD_ID,
"granted_to_user": TEST_RECORD_ID,
"granted_by_user": TEST_RECORD_ID,
"trial_id": trial_metadata["json"]["trial_id"],
"upload_type": downloadable_files["json"]["upload_type"],
},
"model": Permissions,
"allowed_methods": {"POST", "GET", "DELETE"},
"POST_setup": ["users", "trial_metadata"],
"PATCH_json": {"upload_type": "fizzbuzz"},
"filters": {"empty": {"user_id": 2}, "one": {"user_id": TEST_RECORD_ID}},
}
upload_token = "53b455a5-d25b-428b-8c83-86a3120188da"
upload_jobs = {
"json": {
"id": TEST_RECORD_ID,
"trial_id": trial_metadata["json"]["trial_id"],
"uploader_email": users["json"]["email"],
"upload_type": downloadable_files["json"]["upload_type"],
"metadata_patch": {},
"gcs_xlsx_uri": "",
"multifile": False,
"status": UploadJobStatus.STARTED.value,
"token": upload_token,
},
"model": UploadJobs,
"lookup_func": lambda cfg: f"{cfg["id"]}?token={upload_token}",
"allowed_methods": {"PATCH", "GET"},
"POST_setup": ["users", "trial_metadata"],
"PATCH_json": {
"status": UploadJobStatus.UPLOAD_COMPLETED.value,
"token": upload_token,
},
"mocks": [
lambda monkeypatch: monkeypatch.setattr(
"cidc_api.shared.gcloud_client.revoke_upload_access", MagicMock()
),
lambda monkeypatch: monkeypatch.setattr(
"cidc_api.shared.gcloud_client.publish_upload_success", MagicMock()
),
],
}
resource_requests = {
"users": users,
"trial_metadata": trial_metadata,
"downloadable_files": downloadable_files,
"permissions": permissions,
"upload_jobs": upload_jobs,
}
def mock_admin_user(cidc_api, monkeypatch) -> int:
user = Users(**{**users["json"], "email": "other@email.com", "id": None})
mock_current_user(user, monkeypatch)
with cidc_api.app_context():
user.insert()
return user.id
ETAG = "test-etag"
def setup_db_records(cidc_api):
extra = {"_etag": ETAG}
with cidc_api.app_context():
Users(**users["json"], **extra).insert(compute_etag=False)
TrialMetadata(**trial_metadata["json"], **extra).insert(compute_etag=False)
DownloadableFiles(**downloadable_files["json"], **extra).insert(
compute_etag=False
)
Permissions(**permissions["json"], **extra).insert(compute_etag=False)
UploadJobs(**upload_jobs["json"], **extra).insert(compute_etag=False)
records = OrderedDict()
records[ClinicalTrial] = [ClinicalTrial(protocol_identifier="foo")]
errs = insert_record_batch(records)
assert len(errs) == 0, "\n".join(str(e) for e in errs)
def assert_dict_contains(base, target):
assert isinstance(target, dict) and isinstance(base, (dict, BaseModel))
def equal_dates(d1, d2):
if isinstance(d1, str):
d1 = parse_date(d1)
if isinstance(d2, str):
d2 = parse_date(d2)
return d1 == d2
for key, value in target.items():
if hasattr(base, key):
base_val = getattr(base, key)
else:
assert key in base
base_val = base[key]
assert base_val == value or equal_dates(base_val, value)
def setup_mocks(config, monkeypatch):
if "mocks" in config:
for mock in config["mocks"]:
mock(monkeypatch)
def get_lookup_value(config):
lookup_func = config.get("lookup_func")
return lookup_func(config["json"]) if lookup_func else config["json"]["id"]
def resource_requests_with_key(key):
return [rc for rc in resource_requests.items() if key in rc[1]]
@pytest.mark.parametrize("resource, config", resource_requests.items())
def test_resource_post(resource, config, cidc_api, clean_db, monkeypatch):
mock_gcloud_client(monkeypatch)
mock_admin_user(cidc_api, monkeypatch)
setup_mocks(config, monkeypatch)
client = cidc_api.test_client()
if "POST_setup" in config:
for setup_resource in config["POST_setup"]:
res = client.post(
setup_resource, json=resource_requests[setup_resource]["json"]
)
assert res.status_code == 201, "error during POST test setup"
# Try to create the item with POST
response = client.post(resource, json=config["json"])
if "POST" in config["allowed_methods"]:
assert response.status_code == 201
# Make sure it was created
with cidc_api.app_context():
item = config["model"].find_by_id(response.json["id"]).__dict__
assert_dict_contains(item, config["json"])
else:
assert response.status_code == 405
@pytest.mark.parametrize("resource, config", resource_requests.items())
def test_resource_and_item_get(resource, config, cidc_api, clean_db, monkeypatch):
mock_gcloud_client(monkeypatch)
setup_mocks(config, monkeypatch)
setup_db_records(cidc_api)
mock_admin_user(cidc_api, monkeypatch)
client = cidc_api.test_client()
# resource-level GET
response = client.get(resource)
if "GET" in config["allowed_methods"]:
assert response.status_code == 200
item = response.json["_items"][0]
# trial_metadata is an exception - it prunes metadata_json
# on resource-level GET queries
if resource == "trial_metadata":
json = deepcopy(config["json"])
json["metadata_json"].pop("participants")
assert_dict_contains(item, json)
else:
assert_dict_contains(item, config["json"])
if config.get("pagination"):
assert response.json["_meta"]["total"] == 3
elif resource == "users":
# Since the mocked admin user is also in the DB
assert response.json["_meta"]["total"] == 2
else:
assert response.json["_meta"]["total"] == 1
else:
assert response.status_code == 405
# item-level GET
lookup = get_lookup_value(config)
response = client.get(f"{resource}/{lookup}")
if "GET" in config["allowed_methods"]:
assert response.status_code == 200
assert_dict_contains(response.json, config["json"])
else:
assert response.status_code in (404, 405)
@pytest.mark.parametrize("resource, config", resource_requests.items())
def test_item_patch(resource, config, cidc_api, clean_db, monkeypatch):
mock_gcloud_client(monkeypatch)
setup_db_records(cidc_api)
mock_admin_user(cidc_api, monkeypatch)
setup_mocks(config, monkeypatch)
client = cidc_api.test_client()
# Try to update the resource
lookup = get_lookup_value(config)
response = client.patch(f"{resource}/{lookup}", json=config.get("PATCH_json"))
if "PATCH" in config["allowed_methods"]:
# Need to match etag
assert response.status_code == 428
response = client.patch(
f"{resource}/{lookup}",
json=config.get("PATCH_json"),
headers={"if-match": ETAG},
)
assert response.status_code == 200
# Check that the record was updated
with cidc_api.app_context():
item = config["model"].find_by_id(response.json["id"])
assert_dict_contains(item, config["PATCH_json"])
else:
assert response.status_code in (404, 405)
@pytest.mark.parametrize("resource, config", resource_requests.items())
def test_item_put(resource, config, cidc_api, clean_db, monkeypatch):
mock_gcloud_client(monkeypatch)
setup_db_records(cidc_api)
mock_admin_user(cidc_api, monkeypatch)
setup_mocks(config, monkeypatch)
client = cidc_api.test_client()
# Try to PUT the resource - this is disallowed for all resources.
lookup = get_lookup_value(config)
response = client.put(f"{resource}/{lookup}", json=config["json"])
if "PUT" in config["allowed_methods"]:
assert response.status_code == 200
assert response.json == config["json"]
else:
assert response.status_code in (404, 405)
@pytest.mark.parametrize("resource, config", resource_requests.items())
def test_item_delete(resource, config, cidc_api, clean_db, monkeypatch):
mock_gcloud_client(monkeypatch)
setup_db_records(cidc_api)
mock_admin_user(cidc_api, monkeypatch)
setup_mocks(config, monkeypatch)
client = cidc_api.test_client()
# Try to DELETE the resource - this is disallowed for all resources.
lookup = get_lookup_value(config)
response = client.delete(f"{resource}/{lookup}", headers={"if-match": ETAG})
if "DELETE" in config["allowed_methods"]:
assert response.status_code == 204
else:
assert response.status_code in (404, 405)
@pytest.mark.parametrize("resource, config", resource_requests_with_key("filters"))
def test_resource_filters(resource, config, cidc_api, clean_db, monkeypatch):
mock_gcloud_client(monkeypatch)
setup_db_records(cidc_api)
mock_admin_user(cidc_api, monkeypatch)
setup_mocks(config, monkeypatch)
client = cidc_api.test_client()
one_response = client.get(resource, query_string=config["filters"]["one"])
assert one_response.status_code == 200
assert len(one_response.json["_items"]) == 1
item = one_response.json["_items"][0]
assert_dict_contains(item, config["json"])
empty_response = client.get(resource, query_string=config["filters"]["empty"])
assert empty_response.status_code == 200
assert empty_response.json["_items"] == []
@pytest.mark.parametrize(
"resource, config", resource_requests_with_key("additional_records")
)
def test_resource_pagination(resource, config, cidc_api, clean_db, monkeypatch):
mock_gcloud_client(monkeypatch)
setup_db_records(cidc_api)
mock_admin_user(cidc_api, monkeypatch)
setup_mocks(config, monkeypatch)
# Insert additional records for pagination testing
with cidc_api.app_context():
for record in config["additional_records"]:
config["model"](**record).insert()
client = cidc_api.test_client()
# Check that max_results = 1 returns only one result
response = client.get(resource, query_string={"page_size": 1})
assert response.status_code == 200
assert len(response.json["_items"]) == 1
# Check that changing the sorting seems to work
response = client.get(
resource,
query_string={"page_size": 1, "sort_field": "id", "sort_direction": "desc"},
)
assert response.status_code == 200
assert response.json["_items"][0]["id"] > TEST_RECORD_ID
# Check that pagination seems to work
page_1_response = client.get(resource, query_string={"page_size": 2, "page_num": 0})
assert page_1_response.status_code == 200
assert len(page_1_response.json["_items"]) == 2
page_2_response = client.get(resource, query_string={"page_size": 2, "page_num": 1})
assert page_2_response.status_code == 200
assert len(page_2_response.json["_items"]) == (2 if resource == "users" else 1)
def test_endpoint_urls(cidc_api):
"""
Ensure that the API has exactly the endpoints we expect.
"""
expected_endpoints = {
"/",
"/admin/test_csms",
"/admin/load_from_blobs",
"/downloadable_files/",
"/downloadable_files/filelist",
"/downloadable_files/compressed_batch",
"/downloadable_files/download_url",
"/downloadable_files/filter_facets",
"/downloadable_files/<int:downloadable_file>",
"/downloadable_files/<int:downloadable_file>/related_files",
"/info/assays",
"/info/analyses",
"/info/manifests",
"/info/extra_data_types",
"/info/data_overview",
"/info/templates/<template_family>/<template_type>",
"/ingestion/validate",
"/ingestion/upload_manifest",
"/ingestion/upload_assay",
"/ingestion/upload_analysis",
"/ingestion/extra-assay-metadata",
"/ingestion/poll_upload_merge_status/<int:upload_job>",
"/ingestion/intake_bucket",
"/ingestion/intake_metadata",
"/permissions/",
"/permissions/<int:permission>",
"/trial_metadata/",
"/trial_metadata/new_manifest",
"/trial_metadata/summaries",
"/trial_metadata/<string:trial>",
"/upload_jobs/",
"/upload_jobs/<int:upload_job>",
"/users/",
"/users/self",
"/users/<int:user>",
"/users/data_access_report",
}
# Check that every endpoint included in the API is expected.
endpoints = set(
[
rule.rule
for rule in cidc_api.url_map._rules
if not "/dashboards/" in rule.rule # exclude plotly dash dashboards
]
)
assert endpoints == expected_endpoints
def test_exception_handler(clean_cidc_api):
"""
Ensure that the API handles HTTPExceptions in its routes as expected.
"""
message = "uh oh!"
@clean_cidc_api.route("/bad_request")
def raise_bad_request():
raise BadRequest(message)
@clean_cidc_api.route("/key_error")
def raise_key_error():
raise KeyError(message)
client = clean_cidc_api.test_client()
res = client.get("/bad_request")
assert res.status_code == 400
assert res.json == {"_status": "ERR", "_error": {"message": message}}
res = client.get("/key_error")
assert res.status_code == 500
assert res.json["_status"] == "ERR"
assert "internal error" in res.json["_error"]["message"]
| """Smoke tests ranging across the CIDC REST API.
This file doesn't contain tests for methods that don't directly correspond
to data resources, like endpoints that handle upload-related functionality.
"""
from cidc_api.models.templates.trial_metadata import ClinicalTrial
from collections import OrderedDict
from cidc_api.models.templates.utils import insert_record_batch
from copy import deepcopy
from unittest.mock import MagicMock
from datetime import datetime
from dateutil.parser import parse as parse_date
import pytest
from werkzeug.exceptions import BadRequest
from cidc_api.models import (
Users,
DownloadableFiles,
Permissions,
TrialMetadata,
UploadJobs,
UploadJobStatus,
CIDCRole,
BaseModel,
)
from .utils import mock_current_user, mock_gcloud_client
TEST_RECORD_ID = 1
# Configuration for resource tests below. For each resource, the following keywords are supported:
# `json` (required): a JSON instance of this resource.
# `model` (required): the SQLAlchemy model for this resource.
# `allowed_methods` (required): the HTTP methods this resource supports.
# `POST_setup`: a list of other resources to add to the database before POSTing this resource.
# `PATCH_json` (required if "PATCH" in `allowed_methods`): a JSON patch update for this resource.
# `lookup_func`: given a config, return the URL suffix for an item lookup, i.e., `<resource>/<suffix>`.
# `filters`: a dictionary containing two entries representing possible filter queries:
# `empty`: a query filter that should return empty results.
# `one`: a query filter that should return exactly one result.
# `additional_records`: a list of JSON instances of this resource to insert before testing pagination.
# `mocks`: a list of functions that accept pytest's `monkeypatch` as their argument.
users = {
"json": {
"email": "test-admin@example.com",
"id": TEST_RECORD_ID,
"role": CIDCRole.ADMIN.value,
"approval_date": str(datetime.now()),
},
"model": Users,
"allowed_methods": {"POST", "PATCH", "GET"},
"PATCH_json": {"role": CIDCRole.CIMAC_USER.value},
}
users["additional_records"] = [
{**users["json"], "id": 2, "email": "foo@bar.com"},
{**users["json"], "id": 3, "email": "fizz@buzz.com"},
]
trial_metadata = {
"json": {
"id": TEST_RECORD_ID,
"trial_id": "foo",
"metadata_json": {
"protocol_identifier": "foo",
"allowed_collection_event_names": [],
"allowed_cohort_names": [],
"participants": [],
},
},
"model": TrialMetadata,
"allowed_methods": {"POST", "PATCH", "GET"},
"lookup_func": lambda cfg: cfg["trial_id"],
"PATCH_json": {
"metadata_json": {
"protocol_identifier": "foo",
"allowed_collection_event_names": ["bar"],
"allowed_cohort_names": ["buzz"],
"participants": [],
}
},
}
downloadable_files = {
"json": {
"id": TEST_RECORD_ID,
"trial_id": trial_metadata["json"]["trial_id"],
"upload_type": "rna_bam",
"object_url": f'{trial_metadata["json"]["trial_id"]}/rna/.../r1_123.fastq.gz',
"facet_group": "/rna/reads_.bam",
"uploaded_timestamp": datetime.now(),
"file_size_bytes": 1,
},
"model": DownloadableFiles,
"allowed_methods": {"GET"},
"POST_setup": ["trial_metadata"],
"PATCH_json": {"upload_type": "fizzbuzz"},
"filters": {
"empty": {
"trial_ids": [trial_metadata["json"]["trial_id"]],
"facets": "Clinical Type|Participants Info",
},
"one": {
"trial_ids": [trial_metadata["json"]["trial_id"]],
"facets": "Assay Type|RNA|Source",
},
},
}
downloadable_files["additional_records"] = [
{**downloadable_files["json"], "id": 2, "object_url": "foo/bar"},
{**downloadable_files["json"], "id": 3, "object_url": "fizz/buzz"},
]
permissions = {
"json": {
"id": TEST_RECORD_ID,
"granted_to_user": TEST_RECORD_ID,
"granted_by_user": TEST_RECORD_ID,
"trial_id": trial_metadata["json"]["trial_id"],
"upload_type": downloadable_files["json"]["upload_type"],
},
"model": Permissions,
"allowed_methods": {"POST", "GET", "DELETE"},
"POST_setup": ["users", "trial_metadata"],
"PATCH_json": {"upload_type": "fizzbuzz"},
"filters": {"empty": {"user_id": 2}, "one": {"user_id": TEST_RECORD_ID}},
}
upload_token = "53b455a5-d25b-428b-8c83-86a3120188da"
upload_jobs = {
"json": {
"id": TEST_RECORD_ID,
"trial_id": trial_metadata["json"]["trial_id"],
"uploader_email": users["json"]["email"],
"upload_type": downloadable_files["json"]["upload_type"],
"metadata_patch": {},
"gcs_xlsx_uri": "",
"multifile": False,
"status": UploadJobStatus.STARTED.value,
"token": upload_token,
},
"model": UploadJobs,
"lookup_func": lambda cfg: f"{cfg['id']}?token={upload_token}",
"allowed_methods": {"PATCH", "GET"},
"POST_setup": ["users", "trial_metadata"],
"PATCH_json": {
"status": UploadJobStatus.UPLOAD_COMPLETED.value,
"token": upload_token,
},
"mocks": [
lambda monkeypatch: monkeypatch.setattr(
"cidc_api.shared.gcloud_client.revoke_upload_access", MagicMock()
),
lambda monkeypatch: monkeypatch.setattr(
"cidc_api.shared.gcloud_client.publish_upload_success", MagicMock()
),
],
}
resource_requests = {
"users": users,
"trial_metadata": trial_metadata,
"downloadable_files": downloadable_files,
"permissions": permissions,
"upload_jobs": upload_jobs,
}
def mock_admin_user(cidc_api, monkeypatch) -> int:
user = Users(**{**users["json"], "email": "other@email.com", "id": None})
mock_current_user(user, monkeypatch)
with cidc_api.app_context():
user.insert()
return user.id
ETAG = "test-etag"
def setup_db_records(cidc_api):
extra = {"_etag": ETAG}
with cidc_api.app_context():
Users(**users["json"], **extra).insert(compute_etag=False)
TrialMetadata(**trial_metadata["json"], **extra).insert(compute_etag=False)
DownloadableFiles(**downloadable_files["json"], **extra).insert(
compute_etag=False
)
Permissions(**permissions["json"], **extra).insert(compute_etag=False)
UploadJobs(**upload_jobs["json"], **extra).insert(compute_etag=False)
records = OrderedDict()
records[ClinicalTrial] = [ClinicalTrial(protocol_identifier="foo")]
errs = insert_record_batch(records)
assert len(errs) == 0, "\n".join(str(e) for e in errs)
def assert_dict_contains(base, target):
assert isinstance(target, dict) and isinstance(base, (dict, BaseModel))
def equal_dates(d1, d2):
if isinstance(d1, str):
d1 = parse_date(d1)
if isinstance(d2, str):
d2 = parse_date(d2)
return d1 == d2
for key, value in target.items():
if hasattr(base, key):
base_val = getattr(base, key)
else:
assert key in base
base_val = base[key]
assert base_val == value or equal_dates(base_val, value)
def setup_mocks(config, monkeypatch):
if "mocks" in config:
for mock in config["mocks"]:
mock(monkeypatch)
def get_lookup_value(config):
lookup_func = config.get("lookup_func")
return lookup_func(config["json"]) if lookup_func else config["json"]["id"]
def resource_requests_with_key(key):
return [rc for rc in resource_requests.items() if key in rc[1]]
@pytest.mark.parametrize("resource, config", resource_requests.items())
def test_resource_post(resource, config, cidc_api, clean_db, monkeypatch):
mock_gcloud_client(monkeypatch)
mock_admin_user(cidc_api, monkeypatch)
setup_mocks(config, monkeypatch)
client = cidc_api.test_client()
if "POST_setup" in config:
for setup_resource in config["POST_setup"]:
res = client.post(
setup_resource, json=resource_requests[setup_resource]["json"]
)
assert res.status_code == 201, "error during POST test setup"
# Try to create the item with POST
response = client.post(resource, json=config["json"])
if "POST" in config["allowed_methods"]:
assert response.status_code == 201
# Make sure it was created
with cidc_api.app_context():
item = config["model"].find_by_id(response.json["id"]).__dict__
assert_dict_contains(item, config["json"])
else:
assert response.status_code == 405
@pytest.mark.parametrize("resource, config", resource_requests.items())
def test_resource_and_item_get(resource, config, cidc_api, clean_db, monkeypatch):
mock_gcloud_client(monkeypatch)
setup_mocks(config, monkeypatch)
setup_db_records(cidc_api)
mock_admin_user(cidc_api, monkeypatch)
client = cidc_api.test_client()
# resource-level GET
response = client.get(resource)
if "GET" in config["allowed_methods"]:
assert response.status_code == 200
item = response.json["_items"][0]
# trial_metadata is an exception - it prunes metadata_json
# on resource-level GET queries
if resource == "trial_metadata":
json = deepcopy(config["json"])
json["metadata_json"].pop("participants")
assert_dict_contains(item, json)
else:
assert_dict_contains(item, config["json"])
if config.get("pagination"):
assert response.json["_meta"]["total"] == 3
elif resource == "users":
# Since the mocked admin user is also in the DB
assert response.json["_meta"]["total"] == 2
else:
assert response.json["_meta"]["total"] == 1
else:
assert response.status_code == 405
# item-level GET
lookup = get_lookup_value(config)
response = client.get(f"{resource}/{lookup}")
if "GET" in config["allowed_methods"]:
assert response.status_code == 200
assert_dict_contains(response.json, config["json"])
else:
assert response.status_code in (404, 405)
@pytest.mark.parametrize("resource, config", resource_requests.items())
def test_item_patch(resource, config, cidc_api, clean_db, monkeypatch):
mock_gcloud_client(monkeypatch)
setup_db_records(cidc_api)
mock_admin_user(cidc_api, monkeypatch)
setup_mocks(config, monkeypatch)
client = cidc_api.test_client()
# Try to update the resource
lookup = get_lookup_value(config)
response = client.patch(f"{resource}/{lookup}", json=config.get("PATCH_json"))
if "PATCH" in config["allowed_methods"]:
# Need to match etag
assert response.status_code == 428
response = client.patch(
f"{resource}/{lookup}",
json=config.get("PATCH_json"),
headers={"if-match": ETAG},
)
assert response.status_code == 200
# Check that the record was updated
with cidc_api.app_context():
item = config["model"].find_by_id(response.json["id"])
assert_dict_contains(item, config["PATCH_json"])
else:
assert response.status_code in (404, 405)
@pytest.mark.parametrize("resource, config", resource_requests.items())
def test_item_put(resource, config, cidc_api, clean_db, monkeypatch):
mock_gcloud_client(monkeypatch)
setup_db_records(cidc_api)
mock_admin_user(cidc_api, monkeypatch)
setup_mocks(config, monkeypatch)
client = cidc_api.test_client()
# Try to PUT the resource - this is disallowed for all resources.
lookup = get_lookup_value(config)
response = client.put(f"{resource}/{lookup}", json=config["json"])
if "PUT" in config["allowed_methods"]:
assert response.status_code == 200
assert response.json == config["json"]
else:
assert response.status_code in (404, 405)
@pytest.mark.parametrize("resource, config", resource_requests.items())
def test_item_delete(resource, config, cidc_api, clean_db, monkeypatch):
mock_gcloud_client(monkeypatch)
setup_db_records(cidc_api)
mock_admin_user(cidc_api, monkeypatch)
setup_mocks(config, monkeypatch)
client = cidc_api.test_client()
# Try to DELETE the resource - this is disallowed for all resources.
lookup = get_lookup_value(config)
response = client.delete(f"{resource}/{lookup}", headers={"if-match": ETAG})
if "DELETE" in config["allowed_methods"]:
assert response.status_code == 204
else:
assert response.status_code in (404, 405)
@pytest.mark.parametrize("resource, config", resource_requests_with_key("filters"))
def test_resource_filters(resource, config, cidc_api, clean_db, monkeypatch):
mock_gcloud_client(monkeypatch)
setup_db_records(cidc_api)
mock_admin_user(cidc_api, monkeypatch)
setup_mocks(config, monkeypatch)
client = cidc_api.test_client()
one_response = client.get(resource, query_string=config["filters"]["one"])
assert one_response.status_code == 200
assert len(one_response.json["_items"]) == 1
item = one_response.json["_items"][0]
assert_dict_contains(item, config["json"])
empty_response = client.get(resource, query_string=config["filters"]["empty"])
assert empty_response.status_code == 200
assert empty_response.json["_items"] == []
@pytest.mark.parametrize(
"resource, config", resource_requests_with_key("additional_records")
)
def test_resource_pagination(resource, config, cidc_api, clean_db, monkeypatch):
mock_gcloud_client(monkeypatch)
setup_db_records(cidc_api)
mock_admin_user(cidc_api, monkeypatch)
setup_mocks(config, monkeypatch)
# Insert additional records for pagination testing
with cidc_api.app_context():
for record in config["additional_records"]:
config["model"](**record).insert()
client = cidc_api.test_client()
# Check that max_results = 1 returns only one result
response = client.get(resource, query_string={"page_size": 1})
assert response.status_code == 200
assert len(response.json["_items"]) == 1
# Check that changing the sorting seems to work
response = client.get(
resource,
query_string={"page_size": 1, "sort_field": "id", "sort_direction": "desc"},
)
assert response.status_code == 200
assert response.json["_items"][0]["id"] > TEST_RECORD_ID
# Check that pagination seems to work
page_1_response = client.get(resource, query_string={"page_size": 2, "page_num": 0})
assert page_1_response.status_code == 200
assert len(page_1_response.json["_items"]) == 2
page_2_response = client.get(resource, query_string={"page_size": 2, "page_num": 1})
assert page_2_response.status_code == 200
assert len(page_2_response.json["_items"]) == (2 if resource == "users" else 1)
def test_endpoint_urls(cidc_api):
"""
Ensure that the API has exactly the endpoints we expect.
"""
expected_endpoints = {
"/",
"/admin/test_csms",
"/admin/load_from_blobs",
"/downloadable_files/",
"/downloadable_files/filelist",
"/downloadable_files/compressed_batch",
"/downloadable_files/download_url",
"/downloadable_files/filter_facets",
"/downloadable_files/<int:downloadable_file>",
"/downloadable_files/<int:downloadable_file>/related_files",
"/info/assays",
"/info/analyses",
"/info/manifests",
"/info/extra_data_types",
"/info/data_overview",
"/info/templates/<template_family>/<template_type>",
"/ingestion/validate",
"/ingestion/upload_manifest",
"/ingestion/upload_assay",
"/ingestion/upload_analysis",
"/ingestion/extra-assay-metadata",
"/ingestion/poll_upload_merge_status/<int:upload_job>",
"/ingestion/intake_bucket",
"/ingestion/intake_metadata",
"/permissions/",
"/permissions/<int:permission>",
"/trial_metadata/",
"/trial_metadata/new_manifest",
"/trial_metadata/summaries",
"/trial_metadata/<string:trial>",
"/upload_jobs/",
"/upload_jobs/<int:upload_job>",
"/users/",
"/users/self",
"/users/<int:user>",
"/users/data_access_report",
}
# Check that every endpoint included in the API is expected.
endpoints = set(
[
rule.rule
for rule in cidc_api.url_map._rules
if not "/dashboards/" in rule.rule # exclude plotly dash dashboards
]
)
assert endpoints == expected_endpoints
def test_exception_handler(clean_cidc_api):
"""
Ensure that the API handles HTTPExceptions in its routes as expected.
"""
message = "uh oh!"
@clean_cidc_api.route("/bad_request")
def raise_bad_request():
raise BadRequest(message)
@clean_cidc_api.route("/key_error")
def raise_key_error():
raise KeyError(message)
client = clean_cidc_api.test_client()
res = client.get("/bad_request")
assert res.status_code == 400
assert res.json == {"_status": "ERR", "_error": {"message": message}}
res = client.get("/key_error")
assert res.status_code == 500
assert res.json["_status"] == "ERR"
assert "internal error" in res.json["_error"]["message"]
|
import os
import subprocess
import sys
from invoke import task
class GoModule:
"""A Go module abstraction."""
def __init__(self, path, targets=None, condition=lambda: True, should_tag=True):
self.path = path
self.targets = targets if targets else ["."]
self.condition = condition
self.should_tag = should_tag
self._dependencies = None
def __version(self, agent_version):
"""Return the module version for a given Agent version.
>>> mods = [GoModule("."), GoModule("pkg/util/log")]
>>> [mod.__version("7.27.0") for mod in mods]
["v7.27.0", "v0.27.0"]
"""
if self.path == ".":
return "v" + agent_version
return "v0" + agent_version[1:]
def __compute_dependencies(self):
"""
Computes the list of github.com/DataDog/datadog-agent/ dependencies of the module.
"""
prefix = "github.com/DataDog/datadog-agent/"
base_path = os.getcwd()
mod_parser_path = os.path.join(base_path, "internal", "tools", "modparser")
if not os.path.isdir(mod_parser_path):
raise Exception(f"Cannot find go.mod parser in {mod_parser_path}")
try:
output = subprocess.check_output(
["go", "run", ".", "-path", os.path.join(base_path, self.path), "-prefix", prefix],
cwd=mod_parser_path,
).decode("utf-8")
except subprocess.CalledProcessError as e:
print(f"Error while calling go.mod parser: {e.output}")
raise e
# Remove github.com/DataDog/datadog-agent/ from each line
return [line[len(prefix) :] for line in output.strip().splitlines()]
# FIXME: Change when Agent 6 and Agent 7 releases are decoupled
def tag(self, agent_version):
"""Return the module tag name for a given Agent version.
>>> mods = [GoModule("."), GoModule("pkg/util/log")]
>>> [mod.tag("7.27.0") for mod in mods]
[["6.27.0", "7.27.0"], ["pkg/util/log/v0.27.0"]]
"""
if self.path == ".":
return ["6" + agent_version[1:], "7" + agent_version[1:]]
return [f"{self.path}/{self.__version(agent_version)}"]
def full_path(self):
"""Return the absolute path of the Go module."""
return os.path.abspath(self.path)
def go_mod_path(self):
"""Return the absolute path of the Go module go.mod file."""
return self.full_path() + "/go.mod"
@property
def dependencies(self):
if not self._dependencies:
self._dependencies = self.__compute_dependencies()
return self._dependencies
@property
def import_path(self):
"""Return the Go import path of the Go module
>>> mods = [GoModule("."), GoModule("pkg/util/log")]
>>> [mod.import_path for mod in mods]
["github.com/DataDog/datadog-agent", "github.com/DataDog/datadog-agent/pkg/util/log"]
"""
path = "github.com/DataDog/datadog-agent"
if self.path != ".":
path += "/" + self.path
return path
def dependency_path(self, agent_version):
"""Return the versioned dependency path of the Go module
>>> mods = [GoModule("."), GoModule("pkg/util/log")]
>>> [mod.dependency_path("7.27.0") for mod in mods]
["github.com/DataDog/datadog-agent@v7.27.0", "github.com/DataDog/datadog-agent/pkg/util/log@v0.27.0"]
"""
return f"{self.import_path}@{self.__version(agent_version)}"
DEFAULT_MODULES = {
".": GoModule(
".",
targets=["./pkg", "./cmd"],
),
"pkg/util/scrubber": GoModule("pkg/util/scrubber"),
"pkg/util/log": GoModule("pkg/util/log"),
"internal/tools": GoModule("internal/tools", condition=lambda: False, should_tag=False),
"internal/tools/proto": GoModule("internal/tools/proto", condition=lambda: False, should_tag=False),
"internal/tools/modparser": GoModule("internal/tools/modparser", condition=lambda: False, should_tag=False),
"pkg/util/winutil": GoModule(
"pkg/util/winutil",
condition=lambda: sys.platform == 'win32',
),
"pkg/quantile": GoModule("pkg/quantile"),
"pkg/obfuscate": GoModule("pkg/obfuscate"),
"pkg/trace": GoModule("pkg/trace"),
"pkg/otlp/model": GoModule("pkg/otlp/model"),
"pkg/security/secl": GoModule("pkg/security/secl"),
}
MAIN_TEMPLATE = """package main
import (
{imports}
)
func main() {{}}
"""
PACKAGE_TEMPLATE = ' _ "{}"'
@task
def generate_dummy_package(ctx, folder):
import_paths = []
for mod in DEFAULT_MODULES.values():
if mod.path != "." and mod.condition():
import_paths.append(mod.import_path)
os.mkdir(folder)
with ctx.cd(folder):
print("Creating dummy 'main.go' file... ", end="")
with open(os.path.join(ctx.cwd, 'main.go'), 'w') as main_file:
main_file.write(
MAIN_TEMPLATE.format(imports="\n".join(PACKAGE_TEMPLATE.format(path) for path in import_paths))
)
print("Done")
ctx.run("go mod init example.com/testmodule")
for mod in DEFAULT_MODULES.values():
if mod.path != ".":
ctx.run(f"go mod edit -require={mod.dependency_path("0.0.0")}")
ctx.run(f"go mod edit -replace {mod.import_path}=../{mod.path}")
| import os
import subprocess
import sys
from invoke import task
class GoModule:
"""A Go module abstraction."""
def __init__(self, path, targets=None, condition=lambda: True, should_tag=True):
self.path = path
self.targets = targets if targets else ["."]
self.condition = condition
self.should_tag = should_tag
self._dependencies = None
def __version(self, agent_version):
"""Return the module version for a given Agent version.
>>> mods = [GoModule("."), GoModule("pkg/util/log")]
>>> [mod.__version("7.27.0") for mod in mods]
["v7.27.0", "v0.27.0"]
"""
if self.path == ".":
return "v" + agent_version
return "v0" + agent_version[1:]
def __compute_dependencies(self):
"""
Computes the list of github.com/DataDog/datadog-agent/ dependencies of the module.
"""
prefix = "github.com/DataDog/datadog-agent/"
base_path = os.getcwd()
mod_parser_path = os.path.join(base_path, "internal", "tools", "modparser")
if not os.path.isdir(mod_parser_path):
raise Exception(f"Cannot find go.mod parser in {mod_parser_path}")
try:
output = subprocess.check_output(
["go", "run", ".", "-path", os.path.join(base_path, self.path), "-prefix", prefix],
cwd=mod_parser_path,
).decode("utf-8")
except subprocess.CalledProcessError as e:
print(f"Error while calling go.mod parser: {e.output}")
raise e
# Remove github.com/DataDog/datadog-agent/ from each line
return [line[len(prefix) :] for line in output.strip().splitlines()]
# FIXME: Change when Agent 6 and Agent 7 releases are decoupled
def tag(self, agent_version):
"""Return the module tag name for a given Agent version.
>>> mods = [GoModule("."), GoModule("pkg/util/log")]
>>> [mod.tag("7.27.0") for mod in mods]
[["6.27.0", "7.27.0"], ["pkg/util/log/v0.27.0"]]
"""
if self.path == ".":
return ["6" + agent_version[1:], "7" + agent_version[1:]]
return [f"{self.path}/{self.__version(agent_version)}"]
def full_path(self):
"""Return the absolute path of the Go module."""
return os.path.abspath(self.path)
def go_mod_path(self):
"""Return the absolute path of the Go module go.mod file."""
return self.full_path() + "/go.mod"
@property
def dependencies(self):
if not self._dependencies:
self._dependencies = self.__compute_dependencies()
return self._dependencies
@property
def import_path(self):
"""Return the Go import path of the Go module
>>> mods = [GoModule("."), GoModule("pkg/util/log")]
>>> [mod.import_path for mod in mods]
["github.com/DataDog/datadog-agent", "github.com/DataDog/datadog-agent/pkg/util/log"]
"""
path = "github.com/DataDog/datadog-agent"
if self.path != ".":
path += "/" + self.path
return path
def dependency_path(self, agent_version):
"""Return the versioned dependency path of the Go module
>>> mods = [GoModule("."), GoModule("pkg/util/log")]
>>> [mod.dependency_path("7.27.0") for mod in mods]
["github.com/DataDog/datadog-agent@v7.27.0", "github.com/DataDog/datadog-agent/pkg/util/log@v0.27.0"]
"""
return f"{self.import_path}@{self.__version(agent_version)}"
DEFAULT_MODULES = {
".": GoModule(
".",
targets=["./pkg", "./cmd"],
),
"pkg/util/scrubber": GoModule("pkg/util/scrubber"),
"pkg/util/log": GoModule("pkg/util/log"),
"internal/tools": GoModule("internal/tools", condition=lambda: False, should_tag=False),
"internal/tools/proto": GoModule("internal/tools/proto", condition=lambda: False, should_tag=False),
"internal/tools/modparser": GoModule("internal/tools/modparser", condition=lambda: False, should_tag=False),
"pkg/util/winutil": GoModule(
"pkg/util/winutil",
condition=lambda: sys.platform == 'win32',
),
"pkg/quantile": GoModule("pkg/quantile"),
"pkg/obfuscate": GoModule("pkg/obfuscate"),
"pkg/trace": GoModule("pkg/trace"),
"pkg/otlp/model": GoModule("pkg/otlp/model"),
"pkg/security/secl": GoModule("pkg/security/secl"),
}
MAIN_TEMPLATE = """package main
import (
{imports}
)
func main() {{}}
"""
PACKAGE_TEMPLATE = ' _ "{}"'
@task
def generate_dummy_package(ctx, folder):
import_paths = []
for mod in DEFAULT_MODULES.values():
if mod.path != "." and mod.condition():
import_paths.append(mod.import_path)
os.mkdir(folder)
with ctx.cd(folder):
print("Creating dummy 'main.go' file... ", end="")
with open(os.path.join(ctx.cwd, 'main.go'), 'w') as main_file:
main_file.write(
MAIN_TEMPLATE.format(imports="\n".join(PACKAGE_TEMPLATE.format(path) for path in import_paths))
)
print("Done")
ctx.run("go mod init example.com/testmodule")
for mod in DEFAULT_MODULES.values():
if mod.path != ".":
ctx.run(f"go mod edit -require={mod.dependency_path('0.0.0')}")
ctx.run(f"go mod edit -replace {mod.import_path}=../{mod.path}")
|
"""
Module containing a class for
calibrating multiple calibration classes at once.
"""
import os
from typing import List
import numpy as np
from aixcalibuha import CalibrationClass, data_types
from aixcalibuha.calibration import Calibrator
class MultipleClassCalibrator(Calibrator):
r"""
Class for calibration of multiple calibration classes.
When passing multiple classes of the same name, all names
are merged into one class with so called relevant time intervals.
These time intervals are used for the evaluation of the objective
function. Please have a look at the file in docs\img\typeOfContinouusCalibration.pdf
for a better understanding on how this class works.
:param str start_time_method:
Default is 'fixstart'. Method you want to use to
specify the start time of your simulation. If 'fixstart' is selected,
the keyword argument fixstart is used for all classes (Default is 0).
If 'timedelta' is used, the keyword argument timedelta specifies the
time being subtracted from each start time of each calibration class.
Please have a look at the file in docs\img\typeOfContinouusCalibration.pdf
for a better visualization.
:param str calibration_strategy:
Default is 'parallel'. Strategy you want to use for multi-class calibration.
If 'parallel' is used, parameters will be calibrated on the respective time intervals
independently. If 'sequential' is used, the order of the calibration classes matters:
The resulting parameter values of one class will be used as starting values for calibration
on the next class.
:keyword float fix_start_time:
Value for the fix start time if start_time_method="fixstart". Default is zero.
:keyword float timedelta:
Value for timedelta if start_time_method="timedelta". Default is zero.
:keyword str merge_multiple_classes:
Default True. If False, the given list of calibration-classes
is handeled as-is. This means if you pass two CalibrationClass objects
with the same name (e.g. "device on"), the calibration process will run
for both these classes stand-alone.
This will automatically yield an intersection of tuner-parameters, however may
have advantages in some cases.
"""
# Default value for the reference time is zero
fix_start_time = 0
merge_multiple_classes = True
def __init__(self,
cd: str,
sim_api,
calibration_classes: List[CalibrationClass],
start_time_method: str = 'fixstart',
calibration_strategy: str = 'parallel',
**kwargs):
# Check if input is correct
if not isinstance(calibration_classes, list):
raise TypeError("calibration_classes is of type "
"%s but should be list" % type(calibration_classes).__name__)
for cal_class in calibration_classes:
if not isinstance(cal_class, CalibrationClass):
raise TypeError(f"calibration_classes is of type {type(cal_class).__name__} "
f"but should be CalibrationClass")
# Pop kwargs of this class (pass parameters and remove from kwarg dict):
self.merge_multiple_classes = kwargs.pop("merge_multiple_classes", True)
# Apply (if given) the fix_start_time. Check for correct input as-well.
self.fix_start_time = kwargs.pop("fix_start_time", 0)
self.timedelta = kwargs.pop("timedelta", 0)
# Choose the time-method
if start_time_method.lower() not in ["fixstart", "timedelta"]:
raise ValueError(f"Given start_time_method {start_time_method} is not supported. "
"Please choose between 'fixstart' or 'timedelta'")
self.start_time_method = start_time_method
# Choose the calibration method
if calibration_strategy.lower() not in ['parallel', 'sequential']:
raise ValueError(f"Given calibration_strategy {calibration_strategy} is not supported. "
f"Please choose between 'parallel' or 'sequential'")
self.calibration_strategy = calibration_strategy.lower()
# Instantiate parent-class
super().__init__(cd, sim_api, calibration_classes[0], **kwargs)
# Merge the multiple calibration_classes
if self.merge_multiple_classes:
self.calibration_classes = data_types.merge_calibration_classes(calibration_classes)
self._cal_history = []
def calibrate(self, framework, method=None, **kwargs) -> dict:
"""
Start the calibration process.
:return dict self.res_tuner:
Dictionary of the optimized tuner parameter names and values.
:return dict self._current_best_iterate:
Dictionary of the current best results of tuner parameter,
iteration step, objective value, information
about the goals object and the penaltyfactor.
"""
# First check possible intersection of tuner-parameteres
# and warn the user about it
all_tuners = []
for cal_class in self.calibration_classes:
all_tuners.append(cal_class.tuner_paras.get_names())
intersection = set(all_tuners[0]).intersection(*all_tuners)
if intersection and len(self.calibration_classes) > 1:
self.logger.log("The following tuner-parameters intersect over multiple"
f" classes:\n{", ".join(list(intersection))}")
# Iterate over the different existing classes
for cal_class in self.calibration_classes:
#%% Working-Directory:
# Alter the working directory for saving the simulations-results
self.cd_of_class = os.path.join(self.cd,
f"{cal_class.name}_"
f"{cal_class.start_time}_"
f"{cal_class.stop_time}")
self.sim_api.set_cd(self.cd_of_class)
#%% Calibration-Setup
# Reset counter for new calibration
self._counter = 0
# Retrieve already calibrated parameters (i.e. calibrated in the previous classes)
already_calibrated_parameters = {}
for cal_run in self._cal_history:
for par_name in cal_run['res']['Parameters'].index:
already_calibrated_parameters[par_name] = cal_run['res']['Parameters'][par_name]
# Set fixed names:
self.fixed_parameters.update(already_calibrated_parameters)
# Reset best iterate for new class
self._current_best_iterate = {"Objective": np.inf}
self.calibration_class = cal_class
# Set initial values
initial_values = self.tuner_paras.get_initial_values()
for idx, par_name in enumerate(self.tuner_paras.get_names()):
if self.calibration_strategy == "sequential":
# Use already calibrated values as initial value for new calibration
# Delete it from fixed values and retreive the value
initial_values[idx] = self.fixed_parameters.pop(par_name,
initial_values[idx])
else:
try:
self.fixed_parameters.pop(par_name) # Just delete, don't use the value
except KeyError:
pass # Faster than checking if is in dict.
self.x0 = self.tuner_paras.scale(initial_values)
# Either bounds are present or not.
# If present, the obj will scale the values to 0 and 1. If not
# we have an unconstrained optimization.
if self.tuner_paras.bounds is None:
self.bounds = None
else:
self.bounds = [(0, 1) for i in range(len(self.x0))]
#%% Execution
# Run the single ModelicaCalibration
super().calibrate(framework=framework, method=method, **kwargs)
#%% Post-processing
# Append result to list for future perturbation based on older results.
self._cal_history.append({"res": self._current_best_iterate,
"cal_class": cal_class})
res_tuner = self.check_intersection_of_tuner_parameters()
# Save calibrated parameter values in JSON
parameter_values = {}
for cal_run in self._cal_history:
for p_name in cal_run['res']['Parameters'].index:
parameter_values[p_name] = cal_run['res']['Parameters'][p_name]
self.save_results(parameter_values=parameter_values,
filename='MultiClassCalibrationResult')
return parameter_values
def _apply_start_time_method(self, start_time):
"""
Method to be calculate the start_time based on the used
start-time-method (timedelta or fix-start).
:param float start_time:
Start time which was specified by the user in the TOML file.
:return float start_time - self.timedelta:
Calculated "timedelta", if specified in the TOML file.
:return float self.fix_start_time:
Fix start time which was specified by the user in the TOML file.
"""
if self.start_time_method == "timedelta":
# Check if timedelta does not fall below the
# start_time (start_time should not be lower then zero)
if start_time - self.timedelta < 0:
# pylint: disable=import-outside-toplevel
import warnings
warnings.warn(
'Simulation start time current calibration class \n'
' falls below 0, because of the chosen timedelta. '
'The start time will be set to 0 seconds.'
)
return 0
# Using timedelta, _ref_time is subtracted of the given start-time
return start_time - self.timedelta
else:
# With fixed start, the _ref_time parameter is always returned
return self.fix_start_time
def check_intersection_of_tuner_parameters(self):
"""
Checks intersections between tuner parameters.
:return dict res_tuner:
Dictionary of the optimized tuner parameter names and values.
"""
# merge all tuners (writes all values from all classes in one dictionary)
merged_tuner_parameters = {}
for cal_class in self._cal_history:
for tuner_name, best_value in cal_class["res"]["Parameters"].items():
if (tuner_name in merged_tuner_parameters and
best_value not in merged_tuner_parameters[tuner_name]):
merged_tuner_parameters[tuner_name].append(best_value)
else:
merged_tuner_parameters[tuner_name] = [best_value]
# Get tuner parameter
res_tuner = {}
for tuner_para, values in merged_tuner_parameters.items():
res_tuner[tuner_para] = values[0]
# pop single values, as of no interest
intersected_tuners = {}
for tuner_para, values in merged_tuner_parameters.items():
if len(values) >= 2:
intersected_tuners[tuner_para] = values
# Handle tuner intersections
if intersected_tuners.keys():
# Plot or log the information, depending on which logger you are using:
self.logger.log_intersection_of_tuners(intersected_tuners,
itercount=self.recalibration_count)
# Return average value of ALL tuner parameters (not only intersected).
# Reason: if there is an intersection of a tuner parameter, but
# the results of both calibration classes are exactly the same, there
# is no intersection and the affected parameter will not be
# delivered to "res_tuner" if one of the other tuners
# intersect and "intersected_tuners.keys()" is true.
average_tuner_parameter = {}
for tuner_para, values in merged_tuner_parameters.items():
average_tuner_parameter[tuner_para] = sum(values) / len(values)
self.logger.log("The tuner parameters used for evaluation "
"are averaged as follows:\n "
"{}".format(' ,'.join([f"{tuner}={value}"
for tuner, value in average_tuner_parameter.items()])))
# Create result-dictionary
res_tuner = average_tuner_parameter
return res_tuner
| """
Module containing a class for
calibrating multiple calibration classes at once.
"""
import os
from typing import List
import numpy as np
from aixcalibuha import CalibrationClass, data_types
from aixcalibuha.calibration import Calibrator
class MultipleClassCalibrator(Calibrator):
r"""
Class for calibration of multiple calibration classes.
When passing multiple classes of the same name, all names
are merged into one class with so called relevant time intervals.
These time intervals are used for the evaluation of the objective
function. Please have a look at the file in docs\img\typeOfContinouusCalibration.pdf
for a better understanding on how this class works.
:param str start_time_method:
Default is 'fixstart'. Method you want to use to
specify the start time of your simulation. If 'fixstart' is selected,
the keyword argument fixstart is used for all classes (Default is 0).
If 'timedelta' is used, the keyword argument timedelta specifies the
time being subtracted from each start time of each calibration class.
Please have a look at the file in docs\img\typeOfContinouusCalibration.pdf
for a better visualization.
:param str calibration_strategy:
Default is 'parallel'. Strategy you want to use for multi-class calibration.
If 'parallel' is used, parameters will be calibrated on the respective time intervals
independently. If 'sequential' is used, the order of the calibration classes matters:
The resulting parameter values of one class will be used as starting values for calibration
on the next class.
:keyword float fix_start_time:
Value for the fix start time if start_time_method="fixstart". Default is zero.
:keyword float timedelta:
Value for timedelta if start_time_method="timedelta". Default is zero.
:keyword str merge_multiple_classes:
Default True. If False, the given list of calibration-classes
is handeled as-is. This means if you pass two CalibrationClass objects
with the same name (e.g. "device on"), the calibration process will run
for both these classes stand-alone.
This will automatically yield an intersection of tuner-parameters, however may
have advantages in some cases.
"""
# Default value for the reference time is zero
fix_start_time = 0
merge_multiple_classes = True
def __init__(self,
cd: str,
sim_api,
calibration_classes: List[CalibrationClass],
start_time_method: str = 'fixstart',
calibration_strategy: str = 'parallel',
**kwargs):
# Check if input is correct
if not isinstance(calibration_classes, list):
raise TypeError("calibration_classes is of type "
"%s but should be list" % type(calibration_classes).__name__)
for cal_class in calibration_classes:
if not isinstance(cal_class, CalibrationClass):
raise TypeError(f"calibration_classes is of type {type(cal_class).__name__} "
f"but should be CalibrationClass")
# Pop kwargs of this class (pass parameters and remove from kwarg dict):
self.merge_multiple_classes = kwargs.pop("merge_multiple_classes", True)
# Apply (if given) the fix_start_time. Check for correct input as-well.
self.fix_start_time = kwargs.pop("fix_start_time", 0)
self.timedelta = kwargs.pop("timedelta", 0)
# Choose the time-method
if start_time_method.lower() not in ["fixstart", "timedelta"]:
raise ValueError(f"Given start_time_method {start_time_method} is not supported. "
"Please choose between 'fixstart' or 'timedelta'")
self.start_time_method = start_time_method
# Choose the calibration method
if calibration_strategy.lower() not in ['parallel', 'sequential']:
raise ValueError(f"Given calibration_strategy {calibration_strategy} is not supported. "
f"Please choose between 'parallel' or 'sequential'")
self.calibration_strategy = calibration_strategy.lower()
# Instantiate parent-class
super().__init__(cd, sim_api, calibration_classes[0], **kwargs)
# Merge the multiple calibration_classes
if self.merge_multiple_classes:
self.calibration_classes = data_types.merge_calibration_classes(calibration_classes)
self._cal_history = []
def calibrate(self, framework, method=None, **kwargs) -> dict:
"""
Start the calibration process.
:return dict self.res_tuner:
Dictionary of the optimized tuner parameter names and values.
:return dict self._current_best_iterate:
Dictionary of the current best results of tuner parameter,
iteration step, objective value, information
about the goals object and the penaltyfactor.
"""
# First check possible intersection of tuner-parameteres
# and warn the user about it
all_tuners = []
for cal_class in self.calibration_classes:
all_tuners.append(cal_class.tuner_paras.get_names())
intersection = set(all_tuners[0]).intersection(*all_tuners)
if intersection and len(self.calibration_classes) > 1:
self.logger.log("The following tuner-parameters intersect over multiple"
f" classes:\n{', '.join(list(intersection))}")
# Iterate over the different existing classes
for cal_class in self.calibration_classes:
#%% Working-Directory:
# Alter the working directory for saving the simulations-results
self.cd_of_class = os.path.join(self.cd,
f"{cal_class.name}_"
f"{cal_class.start_time}_"
f"{cal_class.stop_time}")
self.sim_api.set_cd(self.cd_of_class)
#%% Calibration-Setup
# Reset counter for new calibration
self._counter = 0
# Retrieve already calibrated parameters (i.e. calibrated in the previous classes)
already_calibrated_parameters = {}
for cal_run in self._cal_history:
for par_name in cal_run['res']['Parameters'].index:
already_calibrated_parameters[par_name] = cal_run['res']['Parameters'][par_name]
# Set fixed names:
self.fixed_parameters.update(already_calibrated_parameters)
# Reset best iterate for new class
self._current_best_iterate = {"Objective": np.inf}
self.calibration_class = cal_class
# Set initial values
initial_values = self.tuner_paras.get_initial_values()
for idx, par_name in enumerate(self.tuner_paras.get_names()):
if self.calibration_strategy == "sequential":
# Use already calibrated values as initial value for new calibration
# Delete it from fixed values and retreive the value
initial_values[idx] = self.fixed_parameters.pop(par_name,
initial_values[idx])
else:
try:
self.fixed_parameters.pop(par_name) # Just delete, don't use the value
except KeyError:
pass # Faster than checking if is in dict.
self.x0 = self.tuner_paras.scale(initial_values)
# Either bounds are present or not.
# If present, the obj will scale the values to 0 and 1. If not
# we have an unconstrained optimization.
if self.tuner_paras.bounds is None:
self.bounds = None
else:
self.bounds = [(0, 1) for i in range(len(self.x0))]
#%% Execution
# Run the single ModelicaCalibration
super().calibrate(framework=framework, method=method, **kwargs)
#%% Post-processing
# Append result to list for future perturbation based on older results.
self._cal_history.append({"res": self._current_best_iterate,
"cal_class": cal_class})
res_tuner = self.check_intersection_of_tuner_parameters()
# Save calibrated parameter values in JSON
parameter_values = {}
for cal_run in self._cal_history:
for p_name in cal_run['res']['Parameters'].index:
parameter_values[p_name] = cal_run['res']['Parameters'][p_name]
self.save_results(parameter_values=parameter_values,
filename='MultiClassCalibrationResult')
return parameter_values
def _apply_start_time_method(self, start_time):
"""
Method to be calculate the start_time based on the used
start-time-method (timedelta or fix-start).
:param float start_time:
Start time which was specified by the user in the TOML file.
:return float start_time - self.timedelta:
Calculated "timedelta", if specified in the TOML file.
:return float self.fix_start_time:
Fix start time which was specified by the user in the TOML file.
"""
if self.start_time_method == "timedelta":
# Check if timedelta does not fall below the
# start_time (start_time should not be lower then zero)
if start_time - self.timedelta < 0:
# pylint: disable=import-outside-toplevel
import warnings
warnings.warn(
'Simulation start time current calibration class \n'
' falls below 0, because of the chosen timedelta. '
'The start time will be set to 0 seconds.'
)
return 0
# Using timedelta, _ref_time is subtracted of the given start-time
return start_time - self.timedelta
else:
# With fixed start, the _ref_time parameter is always returned
return self.fix_start_time
def check_intersection_of_tuner_parameters(self):
"""
Checks intersections between tuner parameters.
:return dict res_tuner:
Dictionary of the optimized tuner parameter names and values.
"""
# merge all tuners (writes all values from all classes in one dictionary)
merged_tuner_parameters = {}
for cal_class in self._cal_history:
for tuner_name, best_value in cal_class["res"]["Parameters"].items():
if (tuner_name in merged_tuner_parameters and
best_value not in merged_tuner_parameters[tuner_name]):
merged_tuner_parameters[tuner_name].append(best_value)
else:
merged_tuner_parameters[tuner_name] = [best_value]
# Get tuner parameter
res_tuner = {}
for tuner_para, values in merged_tuner_parameters.items():
res_tuner[tuner_para] = values[0]
# pop single values, as of no interest
intersected_tuners = {}
for tuner_para, values in merged_tuner_parameters.items():
if len(values) >= 2:
intersected_tuners[tuner_para] = values
# Handle tuner intersections
if intersected_tuners.keys():
# Plot or log the information, depending on which logger you are using:
self.logger.log_intersection_of_tuners(intersected_tuners,
itercount=self.recalibration_count)
# Return average value of ALL tuner parameters (not only intersected).
# Reason: if there is an intersection of a tuner parameter, but
# the results of both calibration classes are exactly the same, there
# is no intersection and the affected parameter will not be
# delivered to "res_tuner" if one of the other tuners
# intersect and "intersected_tuners.keys()" is true.
average_tuner_parameter = {}
for tuner_para, values in merged_tuner_parameters.items():
average_tuner_parameter[tuner_para] = sum(values) / len(values)
self.logger.log("The tuner parameters used for evaluation "
"are averaged as follows:\n "
"{}".format(' ,'.join([f"{tuner}={value}"
for tuner, value in average_tuner_parameter.items()])))
# Create result-dictionary
res_tuner = average_tuner_parameter
return res_tuner
|
frase = str(input('Digite uma frase: ')).strip().upper()
print(f'A letra "A" aparece {frase.count('A')} vezes na frase.\n'
f'A primeira letra "A" aparece na posição {frase.find('A') + 1}.\n'
f'E a ultima letra "A" aparece na posição {frase.rfind('A') + 1}.')
| frase = str(input('Digite uma frase: ')).strip().upper()
print(f'A letra "A" aparece {frase.count("A")} vezes na frase.\n'
f'A primeira letra "A" aparece na posição {frase.find("A") + 1}.\n'
f'E a ultima letra "A" aparece na posição {frase.rfind("A") + 1}.')
|
import boto3
from typing import List
from botocore.exceptions import ClientError
from shelvery.aws_helper import AwsHelper
from shelvery.engine import SHELVERY_DO_BACKUP_TAGS
from shelvery.ec2_backup import ShelveryEC2Backup
from shelvery.entity_resource import EntityResource
from shelvery.backup_resource import BackupResource
class ShelveryEBSBackup(ShelveryEC2Backup):
"""Shelvery engine implementation for EBS data backups"""
def __init__(self):
ShelveryEC2Backup.__init__(self)
def delete_backup(self, backup_resource: BackupResource):
ec2client = AwsHelper.boto3_client('ec2', arn=self.role_arn, external_id=self.role_external_id)
ec2client.delete_snapshot(SnapshotId=backup_resource.backup_id)
def get_existing_backups(self, tag_prefix: str) -> List[BackupResource]:
ec2client = AwsHelper.boto3_client('ec2', arn=self.role_arn, external_id=self.role_external_id)
# lookup snapshots by tags
snapshots = ec2client.describe_snapshots(Filters=[
{'Name': f"tag:{tag_prefix}:{BackupResource.BACKUP_MARKER_TAG}", 'Values': ['true']}
])
backups = []
# create backup resource objects
for snap in snapshots['Snapshots']:
snap_tags = dict(map(lambda t: (t['Key'], t['Value']), snap['Tags']))
if f"{tag_prefix}:ami_id" in snap_tags:
self.logger.info(f"EBS snapshot {snap["SnapshotId"]} created by AMI shelvery backup, skiping...")
continue
backup = BackupResource.construct(
tag_prefix=tag_prefix,
backup_id=snap['SnapshotId'],
tags=snap_tags
)
# legacy code - entity id should be picked up from tags
if backup.entity_id is None:
self.logger.info(f"SnapshotId is None, using VolumeId {snap["VolumeId"]}")
backup.entity_id = snap['VolumeId']
backups.append(backup)
self.populate_volume_information(backups)
return backups
def get_engine_type(self) -> str:
return 'ebs'
def get_resource_type(self) -> str:
return 'ec2 volume'
def backup_resource(self, backup_resource: BackupResource) -> BackupResource:
ec2client = AwsHelper.boto3_client('ec2', arn=self.role_arn, external_id=self.role_external_id)
# create snapshot
snap = ec2client.create_snapshot(
VolumeId=backup_resource.entity_id,
Description=backup_resource.name
)
backup_resource.backup_id = snap['SnapshotId']
return backup_resource
def get_backup_resource(self, region: str, backup_id: str) -> BackupResource:
ec2 = AwsHelper.boto3_session('ec2', region_name=region, arn=self.role_arn, external_id=self.role_external_id)
snapshot = ec2.Snapshot(backup_id)
d_tags = dict(map(lambda t: (t['Key'], t['Value']), snapshot.tags))
return BackupResource.construct(d_tags['shelvery:tag_name'], backup_id, d_tags)
def get_entities_to_backup(self, tag_name: str) -> List[EntityResource]:
volumes = self.collect_volumes(tag_name)
return list(
map(
lambda vol: EntityResource(
resource_id=vol['VolumeId'],
resource_region=self.region,
date_created=vol['CreateTime'],
tags=dict(map(lambda t: (t['Key'], t['Value']), vol['Tags']))
),
volumes
)
)
def is_backup_available(self, region: str, backup_id: str) -> bool:
try:
regional_client = AwsHelper.boto3_client('ec2', region_name=region, arn=self.role_arn, external_id=self.role_external_id)
snapshot = regional_client.describe_snapshots(SnapshotIds=[backup_id])['Snapshots'][0]
complete = snapshot['State'] == 'completed'
self.logger.info(f"{backup_id} is {snapshot["Progress"]} complete")
return complete
except Exception as e:
self.logger.warn(f"Problem getting status of ec2 snapshot status for snapshot {backup_id}:{e}")
def copy_backup_to_region(self, backup_id: str, region: str):
ec2client = AwsHelper.boto3_client('ec2', arn=self.role_arn, external_id=self.role_external_id)
snapshot = ec2client.describe_snapshots(SnapshotIds=[backup_id])['Snapshots'][0]
regional_client = AwsHelper.boto3_client('ec2', region_name=region, arn=self.role_arn, external_id=self.role_external_id)
copy_snapshot_response = regional_client.copy_snapshot(SourceSnapshotId=backup_id,
SourceRegion=ec2client._client_config.region_name,
DestinationRegion=region,
Description=snapshot['Description'])
# return id of newly created snapshot in dr region
return copy_snapshot_response['SnapshotId']
def share_backup_with_account(self, backup_region: str, backup_id: str, aws_account_id: str):
ec2 = AwsHelper.boto3_session('ec2', region_name=backup_region, arn=self.role_arn, external_id=self.role_external_id)
snapshot = ec2.Snapshot(backup_id)
snapshot.modify_attribute(Attribute='createVolumePermission',
CreateVolumePermission={
'Add': [{'UserId': aws_account_id}]
},
UserIds=[aws_account_id],
OperationType='add')
def copy_shared_backup(self, source_account: str, source_backup: BackupResource):
ec2client = AwsHelper.boto3_client('ec2', arn=self.role_arn, external_id=self.role_external_id)
snap = ec2client.copy_snapshot(
SourceSnapshotId=source_backup.backup_id,
SourceRegion=source_backup.region
)
return snap['SnapshotId']
# collect all volumes tagged with given tag, in paginated manner
def collect_volumes(self, tag_name: str):
load_volumes = True
next_token = ''
all_volumes = []
ec2client = AwsHelper.boto3_client('ec2', arn=self.role_arn, external_id=self.role_external_id)
while load_volumes:
tagged_volumes = ec2client.describe_volumes(
Filters=[{'Name': f"tag:{tag_name}", 'Values': SHELVERY_DO_BACKUP_TAGS}],
NextToken=next_token
)
all_volumes = all_volumes + tagged_volumes['Volumes']
if 'NextToken' in tagged_volumes and len(tagged_volumes['NextToken']) > 0:
load_volumes = True
next_token = tagged_volumes['NextToken']
else:
load_volumes = False
return all_volumes
def populate_volume_information(self, backups):
volume_ids = []
volumes = {}
ec2client = AwsHelper.boto3_client('ec2', arn=self.role_arn, external_id=self.role_external_id)
local_region = boto3.session.Session().region_name
# create list of all volume ids
for backup in backups:
if backup.entity_id not in volume_ids:
volume_ids.append(backup.entity_id)
# populate map volumeid->volume if present
for volume_id in volume_ids:
try:
volume = ec2client.describe_volumes(VolumeIds=[volume_id])['Volumes'][0]
d_tags = dict(map(lambda t: (t['Key'], t['Value']), volume['Tags']))
volumes[volume_id] = EntityResource(volume_id, local_region, volume['CreateTime'], d_tags)
except ClientError as e:
if 'InvalidVolume.NotFound' in str(e):
volumes[volume_id] = EntityResource.empty()
volumes[volume_id].resource_id = volume_id
else:
raise e
# add info to backup resource objects
for backup in backups:
if backup.entity_id in volumes:
backup.entity_resource = volumes[backup.entity_id]
| import boto3
from typing import List
from botocore.exceptions import ClientError
from shelvery.aws_helper import AwsHelper
from shelvery.engine import SHELVERY_DO_BACKUP_TAGS
from shelvery.ec2_backup import ShelveryEC2Backup
from shelvery.entity_resource import EntityResource
from shelvery.backup_resource import BackupResource
class ShelveryEBSBackup(ShelveryEC2Backup):
"""Shelvery engine implementation for EBS data backups"""
def __init__(self):
ShelveryEC2Backup.__init__(self)
def delete_backup(self, backup_resource: BackupResource):
ec2client = AwsHelper.boto3_client('ec2', arn=self.role_arn, external_id=self.role_external_id)
ec2client.delete_snapshot(SnapshotId=backup_resource.backup_id)
def get_existing_backups(self, tag_prefix: str) -> List[BackupResource]:
ec2client = AwsHelper.boto3_client('ec2', arn=self.role_arn, external_id=self.role_external_id)
# lookup snapshots by tags
snapshots = ec2client.describe_snapshots(Filters=[
{'Name': f"tag:{tag_prefix}:{BackupResource.BACKUP_MARKER_TAG}", 'Values': ['true']}
])
backups = []
# create backup resource objects
for snap in snapshots['Snapshots']:
snap_tags = dict(map(lambda t: (t['Key'], t['Value']), snap['Tags']))
if f"{tag_prefix}:ami_id" in snap_tags:
self.logger.info(f"EBS snapshot {snap['SnapshotId']} created by AMI shelvery backup, skiping...")
continue
backup = BackupResource.construct(
tag_prefix=tag_prefix,
backup_id=snap['SnapshotId'],
tags=snap_tags
)
# legacy code - entity id should be picked up from tags
if backup.entity_id is None:
self.logger.info(f"SnapshotId is None, using VolumeId {snap['VolumeId']}")
backup.entity_id = snap['VolumeId']
backups.append(backup)
self.populate_volume_information(backups)
return backups
def get_engine_type(self) -> str:
return 'ebs'
def get_resource_type(self) -> str:
return 'ec2 volume'
def backup_resource(self, backup_resource: BackupResource) -> BackupResource:
ec2client = AwsHelper.boto3_client('ec2', arn=self.role_arn, external_id=self.role_external_id)
# create snapshot
snap = ec2client.create_snapshot(
VolumeId=backup_resource.entity_id,
Description=backup_resource.name
)
backup_resource.backup_id = snap['SnapshotId']
return backup_resource
def get_backup_resource(self, region: str, backup_id: str) -> BackupResource:
ec2 = AwsHelper.boto3_session('ec2', region_name=region, arn=self.role_arn, external_id=self.role_external_id)
snapshot = ec2.Snapshot(backup_id)
d_tags = dict(map(lambda t: (t['Key'], t['Value']), snapshot.tags))
return BackupResource.construct(d_tags['shelvery:tag_name'], backup_id, d_tags)
def get_entities_to_backup(self, tag_name: str) -> List[EntityResource]:
volumes = self.collect_volumes(tag_name)
return list(
map(
lambda vol: EntityResource(
resource_id=vol['VolumeId'],
resource_region=self.region,
date_created=vol['CreateTime'],
tags=dict(map(lambda t: (t['Key'], t['Value']), vol['Tags']))
),
volumes
)
)
def is_backup_available(self, region: str, backup_id: str) -> bool:
try:
regional_client = AwsHelper.boto3_client('ec2', region_name=region, arn=self.role_arn, external_id=self.role_external_id)
snapshot = regional_client.describe_snapshots(SnapshotIds=[backup_id])['Snapshots'][0]
complete = snapshot['State'] == 'completed'
self.logger.info(f"{backup_id} is {snapshot['Progress']} complete")
return complete
except Exception as e:
self.logger.warn(f"Problem getting status of ec2 snapshot status for snapshot {backup_id}:{e}")
def copy_backup_to_region(self, backup_id: str, region: str):
ec2client = AwsHelper.boto3_client('ec2', arn=self.role_arn, external_id=self.role_external_id)
snapshot = ec2client.describe_snapshots(SnapshotIds=[backup_id])['Snapshots'][0]
regional_client = AwsHelper.boto3_client('ec2', region_name=region, arn=self.role_arn, external_id=self.role_external_id)
copy_snapshot_response = regional_client.copy_snapshot(SourceSnapshotId=backup_id,
SourceRegion=ec2client._client_config.region_name,
DestinationRegion=region,
Description=snapshot['Description'])
# return id of newly created snapshot in dr region
return copy_snapshot_response['SnapshotId']
def share_backup_with_account(self, backup_region: str, backup_id: str, aws_account_id: str):
ec2 = AwsHelper.boto3_session('ec2', region_name=backup_region, arn=self.role_arn, external_id=self.role_external_id)
snapshot = ec2.Snapshot(backup_id)
snapshot.modify_attribute(Attribute='createVolumePermission',
CreateVolumePermission={
'Add': [{'UserId': aws_account_id}]
},
UserIds=[aws_account_id],
OperationType='add')
def copy_shared_backup(self, source_account: str, source_backup: BackupResource):
ec2client = AwsHelper.boto3_client('ec2', arn=self.role_arn, external_id=self.role_external_id)
snap = ec2client.copy_snapshot(
SourceSnapshotId=source_backup.backup_id,
SourceRegion=source_backup.region
)
return snap['SnapshotId']
# collect all volumes tagged with given tag, in paginated manner
def collect_volumes(self, tag_name: str):
load_volumes = True
next_token = ''
all_volumes = []
ec2client = AwsHelper.boto3_client('ec2', arn=self.role_arn, external_id=self.role_external_id)
while load_volumes:
tagged_volumes = ec2client.describe_volumes(
Filters=[{'Name': f"tag:{tag_name}", 'Values': SHELVERY_DO_BACKUP_TAGS}],
NextToken=next_token
)
all_volumes = all_volumes + tagged_volumes['Volumes']
if 'NextToken' in tagged_volumes and len(tagged_volumes['NextToken']) > 0:
load_volumes = True
next_token = tagged_volumes['NextToken']
else:
load_volumes = False
return all_volumes
def populate_volume_information(self, backups):
volume_ids = []
volumes = {}
ec2client = AwsHelper.boto3_client('ec2', arn=self.role_arn, external_id=self.role_external_id)
local_region = boto3.session.Session().region_name
# create list of all volume ids
for backup in backups:
if backup.entity_id not in volume_ids:
volume_ids.append(backup.entity_id)
# populate map volumeid->volume if present
for volume_id in volume_ids:
try:
volume = ec2client.describe_volumes(VolumeIds=[volume_id])['Volumes'][0]
d_tags = dict(map(lambda t: (t['Key'], t['Value']), volume['Tags']))
volumes[volume_id] = EntityResource(volume_id, local_region, volume['CreateTime'], d_tags)
except ClientError as e:
if 'InvalidVolume.NotFound' in str(e):
volumes[volume_id] = EntityResource.empty()
volumes[volume_id].resource_id = volume_id
else:
raise e
# add info to backup resource objects
for backup in backups:
if backup.entity_id in volumes:
backup.entity_resource = volumes[backup.entity_id]
|
from pyrogram import filters
from pyrogram.types.bots_and_keyboards import callback_game
from pyrogram.types.bots_and_keyboards.inline_keyboard_button import InlineKeyboardButton
from pyrogram.types.bots_and_keyboards.inline_keyboard_markup import InlineKeyboardMarkup
from nksama import bot ,help_message
from typing import List , Any
HELPP_TEXT = """Yo, [mikey](https://telegra.ph/file/52c571e44fdb38e150dca.jpg) here a telegram management bot written on pyrogram library
Check the following buttons for more info
Report bugs at - @Mano_sanjiro_support"""
@bot.on_message(filters.command('help') | filters.command('help@KomiSanRobot'))
def bothelp(_,message):
if message.chat.type == "private":
keyboard = []
for x in help_message:
keyboard.append([InlineKeyboardButton(f"{x["Module_Name"]}" , callback_data=f"help:{x["Module_Name"]}")])
bot.send_message(message.chat.id , HELPP_TEXT , reply_markup=InlineKeyboardMarkup(keyboard))
else:
bot.send_photo(message.chat.id , "https://telegra.ph/file/79d19fe1900a4946e50d4.jpg" , caption=HELPP_TEXT , reply_markup=InlineKeyboardMarkup(
[
[InlineKeyboardButton("Pm me for more details" , url="t.me/Sanjiro_probot?start=help")]
]))
| from pyrogram import filters
from pyrogram.types.bots_and_keyboards import callback_game
from pyrogram.types.bots_and_keyboards.inline_keyboard_button import InlineKeyboardButton
from pyrogram.types.bots_and_keyboards.inline_keyboard_markup import InlineKeyboardMarkup
from nksama import bot ,help_message
from typing import List , Any
HELPP_TEXT = """Yo, [mikey](https://telegra.ph/file/52c571e44fdb38e150dca.jpg) here a telegram management bot written on pyrogram library
Check the following buttons for more info
Report bugs at - @Mano_sanjiro_support"""
@bot.on_message(filters.command('help') | filters.command('help@KomiSanRobot'))
def bothelp(_,message):
if message.chat.type == "private":
keyboard = []
for x in help_message:
keyboard.append([InlineKeyboardButton(f"{x['Module_Name']}" , callback_data=f"help:{x['Module_Name']}")])
bot.send_message(message.chat.id , HELPP_TEXT , reply_markup=InlineKeyboardMarkup(keyboard))
else:
bot.send_photo(message.chat.id , "https://telegra.ph/file/79d19fe1900a4946e50d4.jpg" , caption=HELPP_TEXT , reply_markup=InlineKeyboardMarkup(
[
[InlineKeyboardButton("Pm me for more details" , url="t.me/Sanjiro_probot?start=help")]
]))
|
from toolz.itertoolz import last
from web3 import Web3
import argparse
import time
import datetime
import sys
import json
import numpy as np
import random
from decimal import Decimal
with open('config.json') as f:
config = json.load(f)
# Connect our wallet
web3 = Web3(Web3.HTTPProvider("https://bsc-dataseed.binance.org/"))
print("Web3 Connected: {}".format(web3.isConnected()))
# Set some static contract ABI variables. TODO: pull from etherscan
PancakePredictionV2ABI = '[{"inputs":[{"internalType":"address","name":"_oracleAddress","type":"address"},{"internalType":"address","name":"_adminAddress","type":"address"},{"internalType":"address","name":"_operatorAddress","type":"address"},{"internalType":"uint256","name":"_intervalSeconds","type":"uint256"},{"internalType":"uint256","name":"_bufferSeconds","type":"uint256"},{"internalType":"uint256","name":"_minBetAmount","type":"uint256"},{"internalType":"uint256","name":"_oracleUpdateAllowance","type":"uint256"},{"internalType":"uint256","name":"_treasuryFee","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"BetBear","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"BetBull","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Claim","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"roundId","type":"uint256"},{"indexed":false,"internalType":"int256","name":"price","type":"int256"}],"name":"EndRound","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"roundId","type":"uint256"},{"indexed":false,"internalType":"int256","name":"price","type":"int256"}],"name":"LockRound","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"admin","type":"address"}],"name":"NewAdminAddress","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"bufferSeconds","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"intervalSeconds","type":"uint256"}],"name":"NewBufferAndIntervalSeconds","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"minBetAmount","type":"uint256"}],"name":"NewMinBetAmount","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"operator","type":"address"}],"name":"NewOperatorAddress","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oracle","type":"address"}],"name":"NewOracle","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oracleUpdateAllowance","type":"uint256"}],"name":"NewOracleUpdateAllowance","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"treasuryFee","type":"uint256"}],"name":"NewTreasuryFee","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"}],"name":"Pause","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"rewardBaseCalAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"rewardAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"treasuryAmount","type":"uint256"}],"name":"RewardsCalculated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"}],"name":"StartRound","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"TokenRecovery","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"TreasuryClaim","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"}],"name":"Unpause","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"inputs":[],"name":"MAX_TREASURY_FEE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"adminAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"epoch","type":"uint256"}],"name":"betBear","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"epoch","type":"uint256"}],"name":"betBull","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"bufferSeconds","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"epochs","type":"uint256[]"}],"name":"claim","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"claimTreasury","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"epoch","type":"uint256"},{"internalType":"address","name":"user","type":"address"}],"name":"claimable","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"currentEpoch","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"executeRound","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"genesisLockOnce","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"genesisLockRound","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"genesisStartOnce","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"genesisStartRound","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"cursor","type":"uint256"},{"internalType":"uint256","name":"size","type":"uint256"}],"name":"getUserRounds","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"},{"components":[{"internalType":"enum PancakePredictionV2.Position","name":"position","type":"uint8"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bool","name":"claimed","type":"bool"}],"internalType":"struct PancakePredictionV2.BetInfo[]","name":"","type":"tuple[]"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"getUserRoundsLength","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"intervalSeconds","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"address","name":"","type":"address"}],"name":"ledger","outputs":[{"internalType":"enum PancakePredictionV2.Position","name":"position","type":"uint8"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bool","name":"claimed","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minBetAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"operatorAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"oracle","outputs":[{"internalType":"contract AggregatorV3Interface","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"oracleLatestRoundId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"oracleUpdateAllowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"recoverToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"epoch","type":"uint256"},{"internalType":"address","name":"user","type":"address"}],"name":"refundable","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"rounds","outputs":[{"internalType":"uint256","name":"epoch","type":"uint256"},{"internalType":"uint256","name":"startTimestamp","type":"uint256"},{"internalType":"uint256","name":"lockTimestamp","type":"uint256"},{"internalType":"uint256","name":"closeTimestamp","type":"uint256"},{"internalType":"int256","name":"lockPrice","type":"int256"},{"internalType":"int256","name":"closePrice","type":"int256"},{"internalType":"uint256","name":"lockOracleId","type":"uint256"},{"internalType":"uint256","name":"closeOracleId","type":"uint256"},{"internalType":"uint256","name":"totalAmount","type":"uint256"},{"internalType":"uint256","name":"bullAmount","type":"uint256"},{"internalType":"uint256","name":"bearAmount","type":"uint256"},{"internalType":"uint256","name":"rewardBaseCalAmount","type":"uint256"},{"internalType":"uint256","name":"rewardAmount","type":"uint256"},{"internalType":"bool","name":"oracleCalled","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_adminAddress","type":"address"}],"name":"setAdmin","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_bufferSeconds","type":"uint256"},{"internalType":"uint256","name":"_intervalSeconds","type":"uint256"}],"name":"setBufferAndIntervalSeconds","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_minBetAmount","type":"uint256"}],"name":"setMinBetAmount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_operatorAddress","type":"address"}],"name":"setOperator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_oracle","type":"address"}],"name":"setOracle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_oracleUpdateAllowance","type":"uint256"}],"name":"setOracleUpdateAllowance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_treasuryFee","type":"uint256"}],"name":"setTreasuryFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"treasuryAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"treasuryFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"userRounds","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]'
oracleABI = '[{"inputs":[{"internalType":"address","name":"_aggregator","type":"address"},{"internalType":"address","name":"_accessController","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"int256","name":"current","type":"int256"},{"indexed":true,"internalType":"uint256","name":"roundId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"updatedAt","type":"uint256"}],"name":"AnswerUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"roundId","type":"uint256"},{"indexed":true,"internalType":"address","name":"startedBy","type":"address"},{"indexed":false,"internalType":"uint256","name":"startedAt","type":"uint256"}],"name":"NewRound","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"OwnershipTransferRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"inputs":[],"name":"acceptOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"accessController","outputs":[{"internalType":"contract AccessControllerInterface","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"aggregator","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_aggregator","type":"address"}],"name":"confirmAggregator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"description","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_roundId","type":"uint256"}],"name":"getAnswer","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint80","name":"_roundId","type":"uint80"}],"name":"getRoundData","outputs":[{"internalType":"uint80","name":"roundId","type":"uint80"},{"internalType":"int256","name":"answer","type":"int256"},{"internalType":"uint256","name":"startedAt","type":"uint256"},{"internalType":"uint256","name":"updatedAt","type":"uint256"},{"internalType":"uint80","name":"answeredInRound","type":"uint80"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_roundId","type":"uint256"}],"name":"getTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"latestAnswer","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"latestRound","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"latestRoundData","outputs":[{"internalType":"uint80","name":"roundId","type":"uint80"},{"internalType":"int256","name":"answer","type":"int256"},{"internalType":"uint256","name":"startedAt","type":"uint256"},{"internalType":"uint256","name":"updatedAt","type":"uint256"},{"internalType":"uint80","name":"answeredInRound","type":"uint80"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"latestTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint16","name":"","type":"uint16"}],"name":"phaseAggregators","outputs":[{"internalType":"contract AggregatorV2V3Interface","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"phaseId","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_aggregator","type":"address"}],"name":"proposeAggregator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"proposedAggregator","outputs":[{"internalType":"contract AggregatorV2V3Interface","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint80","name":"_roundId","type":"uint80"}],"name":"proposedGetRoundData","outputs":[{"internalType":"uint80","name":"roundId","type":"uint80"},{"internalType":"int256","name":"answer","type":"int256"},{"internalType":"uint256","name":"startedAt","type":"uint256"},{"internalType":"uint256","name":"updatedAt","type":"uint256"},{"internalType":"uint80","name":"answeredInRound","type":"uint80"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"proposedLatestRoundData","outputs":[{"internalType":"uint80","name":"roundId","type":"uint80"},{"internalType":"int256","name":"answer","type":"int256"},{"internalType":"uint256","name":"startedAt","type":"uint256"},{"internalType":"uint256","name":"updatedAt","type":"uint256"},{"internalType":"uint80","name":"answeredInRound","type":"uint80"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_accessController","type":"address"}],"name":"setController","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_to","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"version","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]'
BTCBABI = '[{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"Burn","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount0In","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1In","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount0Out","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1Out","type":"uint256"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"Swap","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint112","name":"reserve0","type":"uint112"},{"indexed":false,"internalType":"uint112","name":"reserve1","type":"uint112"}],"name":"Sync","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"constant":true,"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"MINIMUM_LIQUIDITY","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"PERMIT_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"burn","outputs":[{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getReserves","outputs":[{"internalType":"uint112","name":"_reserve0","type":"uint112"},{"internalType":"uint112","name":"_reserve1","type":"uint112"},{"internalType":"uint32","name":"_blockTimestampLast","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_token0","type":"address"},{"internalType":"address","name":"_token1","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"kLast","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"mint","outputs":[{"internalType":"uint256","name":"liquidity","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"price0CumulativeLast","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"price1CumulativeLast","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"skim","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"amount0Out","type":"uint256"},{"internalType":"uint256","name":"amount1Out","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"swap","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"sync","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"token0","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"token1","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"}]'
# Function for asking the Oracle .. Neo
def askTheOracle():
addr = web3.toChecksumAddress(config["oracleContract"])
contract = web3.eth.contract(address=addr, abi=oracleABI)
latestData = contract.functions.latestRoundData().call()
price = latestData[1]
return price
def getBTCB():
btcbContract = web3.toChecksumAddress(config["BTCBBUSDContract"])
contract = web3.eth.contract(address=btcbContract, abi=BTCBABI)
reserveData = contract.functions.getReserves().call()
reserve0 = reserveData[0]
reserve1 = reserveData[1]
price = (Decimal(reserve1) / 10 ** 18) / (Decimal(reserve0) / (10 ** 18))
return price
# Function for a Bear bet
def betBear(amount):
predictionContract = web3.toChecksumAddress(config["predictionContract"])
contract = web3.eth.contract(address=predictionContract,abi=PancakePredictionV2ABI)
sender_address = web3.toChecksumAddress(config["walletAddress"])
nonce = web3.eth.get_transaction_count(sender_address)
entry_transaction = contract.functions.betBear(int(getEpoch())).buildTransaction({
'chainId': 56,
'from': sender_address,
'gas': config["gasAmount"],
'gasPrice': web3.toWei('5','gwei'),
'value': web3.toWei(amount, "ether"),
'nonce': nonce
})
signed_txn = web3.eth.account.sign_transaction(entry_transaction,config["walletPrivateKey"])
tx_token = web3.eth.send_raw_transaction(signed_txn.rawTransaction)
print("Carnac the Magnificent says it's a Bear bet. {}".format(web3.toHex(tx_token)))
# Function for a Bull bet
def betBull(amount):
predictionContract = web3.toChecksumAddress(config["predictionContract"])
contract = web3.eth.contract(address=predictionContract,abi=PancakePredictionV2ABI)
sender_address = web3.toChecksumAddress(config["walletAddress"])
nonce = web3.eth.get_transaction_count(sender_address)
entry_transaction = contract.functions.betBull(int(getEpoch())).buildTransaction({
'chainId': 56,
'from': sender_address,
'gas': config["gasAmount"],
'gasPrice': web3.toWei('5','gwei'),
'value': web3.toWei(amount, "ether"),
'nonce': nonce
})
signed_txn = web3.eth.account.sign_transaction(entry_transaction, config["walletPrivateKey"])
tx_token = web3.eth.send_raw_transaction(signed_txn.rawTransaction)
print("Carnac the Magnificent says it's a Bull bet. {}".format(web3.toHex(tx_token)))
# Function to the the current round's card info
def getRounds(e):
addr = web3.toChecksumAddress(config["predictionContract"])
contract = web3.eth.contract(address=addr, abi=PancakePredictionV2ABI)
response = contract.functions.rounds(e).call()
return response
# Function to
def getEpoch():
# We need to get the epoch of the current card
addr = web3.toChecksumAddress(config["predictionContract"])
contract = web3.eth.contract(address=addr, abi=PancakePredictionV2ABI)
epoch = contract.functions.currentEpoch().call()
return epoch
def checkClaims():
print("Checking previous round for winnings.")
sender_address = web3.toChecksumAddress(config["walletAddress"])
addr = web3.toChecksumAddress(config["predictionContract"])
contract = web3.eth.contract(address=addr, abi=PancakePredictionV2ABI)
epochs = []
lastEpoch = (int(getEpoch()) - 2)
twoEpoch = lastEpoch - 1
epochs.append(twoEpoch)
epochs.append(lastEpoch)
claims = contract.functions.claimable(lastEpoch, sender_address).call()
if claims != False:
claimWinnings()
def claimWinnings():
predictionContract = web3.toChecksumAddress(config["predictionContract"])
contract = web3.eth.contract(address=predictionContract,abi=PancakePredictionV2ABI)
sender_address = web3.toChecksumAddress(config["walletAddress"])
nonce = web3.eth.get_transaction_count(sender_address)
epochs = []
lastEpoch = (int(getEpoch()) - 2)
epochs.append(lastEpoch)
entry_transaction = contract.functions.claim(epochs).buildTransaction({
'chainId': 56,
'from': sender_address,
'gas': config["gasAmount"],
'gasPrice': web3.toWei('5','gwei'),
'nonce': nonce
})
signed_txn = web3.eth.account.sign_transaction(entry_transaction,config["walletPrivateKey"])
tx_token = web3.eth.send_raw_transaction(signed_txn.rawTransaction)
print("Claimed {}".format(web3.toHex(tx_token)))
def CarnacSays(amount,ranmin,ranmax,opposite,btcbFactor,multiplier,skip):
while True:
try:
# Check if we won the previous round
checkClaims()
if ranmin and ranmax:
amount = round(random.uniform(float(ranmin),float(ranmax)), 3)
print("Bet Amount: {}".format(amount))
# Get the current card data
rawEpoch = getEpoch()
epoch = rawEpoch - 1
print("Round {} starting..".format(int(epoch)))
currentRound = getRounds(epoch)
# Set the start time of this card
startTimestamp = datetime.datetime.fromtimestamp(currentRound[1])
print("Round Start Time: {}".format(startTimestamp))
# Set the end time of this card
closeTimestamp = datetime.datetime.fromtimestamp(currentRound[3])
print("Round End Time: {}".format(closeTimestamp))
# Get card locked-in price
lockPrice = currentRound[4]
print("Monitoring {} as the start price".format(int(lockPrice) * 0.00000001))
# Set the cutoff time for our order to process
cutOffTime = closeTimestamp - datetime.timedelta(seconds=25)
print("Cutoff time for order: {}: ".format(cutOffTime))
# Get the starting BTCB price
startingBTCBPrice = getBTCB()
print("Starting BTCB Price: {}".format(startingBTCBPrice))
while True:
currentPrice = askTheOracle()
currentTime = datetime.datetime.fromtimestamp(time.time())
if currentTime >= cutOffTime:
# Set the cutoff time for our order to process
endingBTCBPrice = getBTCB()
print("Ending BTCB Price: {}".format(endingBTCBPrice))
#else:
if currentPrice > lockPrice:
# Check if BTCB is influencing and bet accordingly
if btcbFactor:
if endingBTCBPrice > startingBTCBPrice:
print("BTCB Price ascending, adding to our Bull bet.")
amount = float(amount) * float(multiplier)
print("Total bet: {}".format(amount))
betBull(amount)
else:
betBull(amount)
else:
if opposite:
betBear(amount)
else:
betBull(amount)
print("")
print("Sleeping for next round..")
if skip:
print("Skipping a round.")
time.sleep(600)
break
else:
time.sleep(120)
break
else:
# Check if BTCB is influincing and bet accordingly
if btcbFactor:
if endingBTCBPrice < startingBTCBPrice:
amount = float(amount) * float(multiplier)
print("BTCB Price descending, adding to our Bear bet.")
print("Total bet: {}".format(amount))
betBear(amount)
else:
betBear(amount)
else:
if opposite:
betBull(amount)
else:
betBear(amount)
print("")
print("Sleeping for next round..")
if skip:
print("Skipping a round.")
time.sleep(600)
break
else:
time.sleep(120)
break
time.sleep(4)
except KeyboardInterrupt:
sys.exit()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-a","--amount",default=0.009, help="Amount to stake every round.")
parser.add_argument("--randmin", help="Minimum bet amount.")
parser.add_argument("--randmax", help="Maximum bet amount.")
parser.add_argument("--multiplier", default=1.10, help="If btcbFactor is enabled, this will multiply the bet if we follow that trend. Default is 10%, 1.10.")
parser.add_argument("--opposite",action="store_true", help="If ending price is HIGHER, bet DOWN.")
parser.add_argument("--btcbFactor",action="store_true", help="Factor in BTCB price. Adds 10% to the bet if BNB AND BTCB are going up. Otherwise, it switches the bet.")
parser.add_argument("--skipRound", action="store_true", help="Skip ever other round.")
args = parser.parse_args()
CarnacSays(args.amount,args.randmin,args.randmax,args.opposite,args.btcbFactor,args.multiplier,args.skipRound) | from toolz.itertoolz import last
from web3 import Web3
import argparse
import time
import datetime
import sys
import json
import numpy as np
import random
from decimal import Decimal
with open('config.json') as f:
config = json.load(f)
# Connect our wallet
web3 = Web3(Web3.HTTPProvider("https://bsc-dataseed.binance.org/"))
print("Web3 Connected: {}".format(web3.isConnected()))
# Set some static contract ABI variables. TODO: pull from etherscan
PancakePredictionV2ABI = '[{"inputs":[{"internalType":"address","name":"_oracleAddress","type":"address"},{"internalType":"address","name":"_adminAddress","type":"address"},{"internalType":"address","name":"_operatorAddress","type":"address"},{"internalType":"uint256","name":"_intervalSeconds","type":"uint256"},{"internalType":"uint256","name":"_bufferSeconds","type":"uint256"},{"internalType":"uint256","name":"_minBetAmount","type":"uint256"},{"internalType":"uint256","name":"_oracleUpdateAllowance","type":"uint256"},{"internalType":"uint256","name":"_treasuryFee","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"BetBear","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"BetBull","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Claim","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"roundId","type":"uint256"},{"indexed":false,"internalType":"int256","name":"price","type":"int256"}],"name":"EndRound","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"roundId","type":"uint256"},{"indexed":false,"internalType":"int256","name":"price","type":"int256"}],"name":"LockRound","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"admin","type":"address"}],"name":"NewAdminAddress","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"bufferSeconds","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"intervalSeconds","type":"uint256"}],"name":"NewBufferAndIntervalSeconds","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"minBetAmount","type":"uint256"}],"name":"NewMinBetAmount","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"operator","type":"address"}],"name":"NewOperatorAddress","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oracle","type":"address"}],"name":"NewOracle","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oracleUpdateAllowance","type":"uint256"}],"name":"NewOracleUpdateAllowance","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"treasuryFee","type":"uint256"}],"name":"NewTreasuryFee","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"}],"name":"Pause","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"rewardBaseCalAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"rewardAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"treasuryAmount","type":"uint256"}],"name":"RewardsCalculated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"}],"name":"StartRound","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"TokenRecovery","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"TreasuryClaim","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"}],"name":"Unpause","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"inputs":[],"name":"MAX_TREASURY_FEE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"adminAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"epoch","type":"uint256"}],"name":"betBear","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"epoch","type":"uint256"}],"name":"betBull","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"bufferSeconds","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"epochs","type":"uint256[]"}],"name":"claim","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"claimTreasury","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"epoch","type":"uint256"},{"internalType":"address","name":"user","type":"address"}],"name":"claimable","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"currentEpoch","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"executeRound","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"genesisLockOnce","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"genesisLockRound","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"genesisStartOnce","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"genesisStartRound","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"cursor","type":"uint256"},{"internalType":"uint256","name":"size","type":"uint256"}],"name":"getUserRounds","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"},{"components":[{"internalType":"enum PancakePredictionV2.Position","name":"position","type":"uint8"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bool","name":"claimed","type":"bool"}],"internalType":"struct PancakePredictionV2.BetInfo[]","name":"","type":"tuple[]"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"getUserRoundsLength","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"intervalSeconds","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"address","name":"","type":"address"}],"name":"ledger","outputs":[{"internalType":"enum PancakePredictionV2.Position","name":"position","type":"uint8"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bool","name":"claimed","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minBetAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"operatorAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"oracle","outputs":[{"internalType":"contract AggregatorV3Interface","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"oracleLatestRoundId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"oracleUpdateAllowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"recoverToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"epoch","type":"uint256"},{"internalType":"address","name":"user","type":"address"}],"name":"refundable","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"rounds","outputs":[{"internalType":"uint256","name":"epoch","type":"uint256"},{"internalType":"uint256","name":"startTimestamp","type":"uint256"},{"internalType":"uint256","name":"lockTimestamp","type":"uint256"},{"internalType":"uint256","name":"closeTimestamp","type":"uint256"},{"internalType":"int256","name":"lockPrice","type":"int256"},{"internalType":"int256","name":"closePrice","type":"int256"},{"internalType":"uint256","name":"lockOracleId","type":"uint256"},{"internalType":"uint256","name":"closeOracleId","type":"uint256"},{"internalType":"uint256","name":"totalAmount","type":"uint256"},{"internalType":"uint256","name":"bullAmount","type":"uint256"},{"internalType":"uint256","name":"bearAmount","type":"uint256"},{"internalType":"uint256","name":"rewardBaseCalAmount","type":"uint256"},{"internalType":"uint256","name":"rewardAmount","type":"uint256"},{"internalType":"bool","name":"oracleCalled","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_adminAddress","type":"address"}],"name":"setAdmin","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_bufferSeconds","type":"uint256"},{"internalType":"uint256","name":"_intervalSeconds","type":"uint256"}],"name":"setBufferAndIntervalSeconds","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_minBetAmount","type":"uint256"}],"name":"setMinBetAmount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_operatorAddress","type":"address"}],"name":"setOperator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_oracle","type":"address"}],"name":"setOracle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_oracleUpdateAllowance","type":"uint256"}],"name":"setOracleUpdateAllowance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_treasuryFee","type":"uint256"}],"name":"setTreasuryFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"treasuryAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"treasuryFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"userRounds","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]'
oracleABI = '[{"inputs":[{"internalType":"address","name":"_aggregator","type":"address"},{"internalType":"address","name":"_accessController","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"int256","name":"current","type":"int256"},{"indexed":true,"internalType":"uint256","name":"roundId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"updatedAt","type":"uint256"}],"name":"AnswerUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"roundId","type":"uint256"},{"indexed":true,"internalType":"address","name":"startedBy","type":"address"},{"indexed":false,"internalType":"uint256","name":"startedAt","type":"uint256"}],"name":"NewRound","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"OwnershipTransferRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"inputs":[],"name":"acceptOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"accessController","outputs":[{"internalType":"contract AccessControllerInterface","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"aggregator","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_aggregator","type":"address"}],"name":"confirmAggregator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"description","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_roundId","type":"uint256"}],"name":"getAnswer","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint80","name":"_roundId","type":"uint80"}],"name":"getRoundData","outputs":[{"internalType":"uint80","name":"roundId","type":"uint80"},{"internalType":"int256","name":"answer","type":"int256"},{"internalType":"uint256","name":"startedAt","type":"uint256"},{"internalType":"uint256","name":"updatedAt","type":"uint256"},{"internalType":"uint80","name":"answeredInRound","type":"uint80"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_roundId","type":"uint256"}],"name":"getTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"latestAnswer","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"latestRound","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"latestRoundData","outputs":[{"internalType":"uint80","name":"roundId","type":"uint80"},{"internalType":"int256","name":"answer","type":"int256"},{"internalType":"uint256","name":"startedAt","type":"uint256"},{"internalType":"uint256","name":"updatedAt","type":"uint256"},{"internalType":"uint80","name":"answeredInRound","type":"uint80"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"latestTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint16","name":"","type":"uint16"}],"name":"phaseAggregators","outputs":[{"internalType":"contract AggregatorV2V3Interface","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"phaseId","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_aggregator","type":"address"}],"name":"proposeAggregator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"proposedAggregator","outputs":[{"internalType":"contract AggregatorV2V3Interface","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint80","name":"_roundId","type":"uint80"}],"name":"proposedGetRoundData","outputs":[{"internalType":"uint80","name":"roundId","type":"uint80"},{"internalType":"int256","name":"answer","type":"int256"},{"internalType":"uint256","name":"startedAt","type":"uint256"},{"internalType":"uint256","name":"updatedAt","type":"uint256"},{"internalType":"uint80","name":"answeredInRound","type":"uint80"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"proposedLatestRoundData","outputs":[{"internalType":"uint80","name":"roundId","type":"uint80"},{"internalType":"int256","name":"answer","type":"int256"},{"internalType":"uint256","name":"startedAt","type":"uint256"},{"internalType":"uint256","name":"updatedAt","type":"uint256"},{"internalType":"uint80","name":"answeredInRound","type":"uint80"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_accessController","type":"address"}],"name":"setController","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_to","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"version","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]'
BTCBABI = '[{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"Burn","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount0In","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1In","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount0Out","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1Out","type":"uint256"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"Swap","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint112","name":"reserve0","type":"uint112"},{"indexed":false,"internalType":"uint112","name":"reserve1","type":"uint112"}],"name":"Sync","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"constant":true,"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"MINIMUM_LIQUIDITY","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"PERMIT_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"burn","outputs":[{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getReserves","outputs":[{"internalType":"uint112","name":"_reserve0","type":"uint112"},{"internalType":"uint112","name":"_reserve1","type":"uint112"},{"internalType":"uint32","name":"_blockTimestampLast","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_token0","type":"address"},{"internalType":"address","name":"_token1","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"kLast","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"mint","outputs":[{"internalType":"uint256","name":"liquidity","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"price0CumulativeLast","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"price1CumulativeLast","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"skim","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"amount0Out","type":"uint256"},{"internalType":"uint256","name":"amount1Out","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"swap","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"sync","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"token0","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"token1","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"}]'
# Function for asking the Oracle .. Neo
def askTheOracle():
addr = web3.toChecksumAddress(config["oracleContract"])
contract = web3.eth.contract(address=addr, abi=oracleABI)
latestData = contract.functions.latestRoundData().call()
price = latestData[1]
return price
def getBTCB():
btcbContract = web3.toChecksumAddress(config["BTCBBUSDContract"])
contract = web3.eth.contract(address=btcbContract, abi=BTCBABI)
reserveData = contract.functions.getReserves().call()
reserve0 = reserveData[0]
reserve1 = reserveData[1]
price = (Decimal(reserve1) / 10 ** 18) / (Decimal(reserve0) / (10 ** 18))
return price
# Function for a Bear bet
def betBear(amount):
predictionContract = web3.toChecksumAddress(config["predictionContract"])
contract = web3.eth.contract(address=predictionContract,abi=PancakePredictionV2ABI)
sender_address = web3.toChecksumAddress(config["walletAddress"])
nonce = web3.eth.get_transaction_count(sender_address)
entry_transaction = contract.functions.betBear(int(getEpoch())).buildTransaction({
'chainId': 56,
'from': sender_address,
'gas': config["gasAmount"],
'gasPrice': web3.toWei('5','gwei'),
'value': web3.toWei(amount, "ether"),
'nonce': nonce
})
signed_txn = web3.eth.account.sign_transaction(entry_transaction,config["walletPrivateKey"])
tx_token = web3.eth.send_raw_transaction(signed_txn.rawTransaction)
print("Carnac the Magnificent says it's a Bear bet. {}".format(web3.toHex(tx_token)))
# Function for a Bull bet
def betBull(amount):
predictionContract = web3.toChecksumAddress(config["predictionContract"])
contract = web3.eth.contract(address=predictionContract,abi=PancakePredictionV2ABI)
sender_address = web3.toChecksumAddress(config["walletAddress"])
nonce = web3.eth.get_transaction_count(sender_address)
entry_transaction = contract.functions.betBull(int(getEpoch())).buildTransaction({
'chainId': 56,
'from': sender_address,
'gas': config["gasAmount"],
'gasPrice': web3.toWei('5','gwei'),
'value': web3.toWei(amount, "ether"),
'nonce': nonce
})
signed_txn = web3.eth.account.sign_transaction(entry_transaction, config["walletPrivateKey"])
tx_token = web3.eth.send_raw_transaction(signed_txn.rawTransaction)
print("Carnac the Magnificent says it's a Bull bet. {}".format(web3.toHex(tx_token)))
# Function to the the current round's card info
def getRounds(e):
addr = web3.toChecksumAddress(config["predictionContract"])
contract = web3.eth.contract(address=addr, abi=PancakePredictionV2ABI)
response = contract.functions.rounds(e).call()
return response
# Function to
def getEpoch():
# We need to get the epoch of the current card
addr = web3.toChecksumAddress(config["predictionContract"])
contract = web3.eth.contract(address=addr, abi=PancakePredictionV2ABI)
epoch = contract.functions.currentEpoch().call()
return epoch
def checkClaims():
print("Checking previous round for winnings.")
sender_address = web3.toChecksumAddress(config["walletAddress"])
addr = web3.toChecksumAddress(config["predictionContract"])
contract = web3.eth.contract(address=addr, abi=PancakePredictionV2ABI)
epochs = []
lastEpoch = (int(getEpoch()) - 2)
twoEpoch = lastEpoch - 1
epochs.append(twoEpoch)
epochs.append(lastEpoch)
claims = contract.functions.claimable(lastEpoch, sender_address).call()
if claims != False:
claimWinnings()
def claimWinnings():
predictionContract = web3.toChecksumAddress(config["predictionContract"])
contract = web3.eth.contract(address=predictionContract,abi=PancakePredictionV2ABI)
sender_address = web3.toChecksumAddress(config["walletAddress"])
nonce = web3.eth.get_transaction_count(sender_address)
epochs = []
lastEpoch = (int(getEpoch()) - 2)
epochs.append(lastEpoch)
entry_transaction = contract.functions.claim(epochs).buildTransaction({
'chainId': 56,
'from': sender_address,
'gas': config["gasAmount"],
'gasPrice': web3.toWei('5','gwei'),
'nonce': nonce
})
signed_txn = web3.eth.account.sign_transaction(entry_transaction,config["walletPrivateKey"])
tx_token = web3.eth.send_raw_transaction(signed_txn.rawTransaction)
print("Claimed {}".format(web3.toHex(tx_token)))
def CarnacSays(amount,ranmin,ranmax,opposite,btcbFactor,multiplier,skip):
while True:
try:
# Check if we won the previous round
checkClaims()
if ranmin and ranmax:
amount = round(random.uniform(float(ranmin),float(ranmax)), 3)
print("Bet Amount: {}".format(amount))
# Get the current card data
rawEpoch = getEpoch()
epoch = rawEpoch - 1
print("Round {} starting..".format(int(epoch)))
currentRound = getRounds(epoch)
# Set the start time of this card
startTimestamp = datetime.datetime.fromtimestamp(currentRound[1])
print("Round Start Time: {}".format(startTimestamp))
# Set the end time of this card
closeTimestamp = datetime.datetime.fromtimestamp(currentRound[3])
print("Round End Time: {}".format(closeTimestamp))
# Get card locked-in price
lockPrice = currentRound[4]
print("Monitoring {} as the start price".format(int(lockPrice) * 0.00000001))
# Set the cutoff time for our order to process
cutOffTime = closeTimestamp - datetime.timedelta(seconds=25)
print("Cutoff time for order: {}: ".format(cutOffTime))
# Get the starting BTCB price
startingBTCBPrice = getBTCB()
print("Starting BTCB Price: {}".format(startingBTCBPrice))
while True:
currentPrice = askTheOracle()
currentTime = datetime.datetime.fromtimestamp(time.time())
if currentTime >= cutOffTime:
# Set the cutoff time for our order to process
endingBTCBPrice = getBTCB()
print("Ending BTCB Price: {}".format(endingBTCBPrice))
#else:
if currentPrice > lockPrice:
# Check if BTCB is influencing and bet accordingly
if btcbFactor:
if endingBTCBPrice > startingBTCBPrice:
print("BTCB Price ascending, adding to our Bull bet.")
amount = float(amount) * float(multiplier)
print("Total bet: {}".format(amount))
betBull(amount)
else:
betBull(amount)
else:
if opposite:
betBear(amount)
else:
betBull(amount)
print("")
print("Sleeping for next round..")
if skip:
print("Skipping a round.")
time.sleep(600)
break
else:
time.sleep(120)
break
else:
# Check if BTCB is influincing and bet accordingly
if btcbFactor:
if endingBTCBPrice < startingBTCBPrice:
amount = float(amount) * float(multiplier)
print("BTCB Price descending, adding to our Bear bet.")
print("Total bet: {}".format(amount))
betBear(amount)
else:
betBear(amount)
else:
if opposite:
betBull(amount)
else:
betBear(amount)
print("")
print("Sleeping for next round..")
if skip:
print("Skipping a round.")
time.sleep(600)
break
else:
time.sleep(120)
break
time.sleep(4)
except KeyboardInterrupt:
sys.exit()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-a","--amount",default=0.009, help="Amount to stake every round.")
parser.add_argument("--randmin", help="Minimum bet amount.")
parser.add_argument("--randmax", help="Maximum bet amount.")
parser.add_argument("--multiplier", default=1.10, help="If btcbFactor is enabled, this will multiply the bet if we follow that trend. Default is 10%, 1.10.")
parser.add_argument("--opposite",action="store_true", help="If ending price is HIGHER, bet DOWN.")
parser.add_argument("--btcbFactor",action="store_true", help="Factor in BTCB price. Adds 10% to the bet if BNB AND BTCB are going up. Otherwise, it switches the bet.")
parser.add_argument("--skipRound", action="store_true", help="Skip ever other round.")
args = parser.parse_args()
CarnacSays(args.amount,args.randmin,args.randmax,args.opposite,args.btcbFactor,args.multiplier,args.skipRound) |
# -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
'''
This module provides one useful class: NodeHandler
The NodeHandler class is designed to be subclassed. Each subclass
should support the processing that createpdf.RstToPdf needs to do
on a particular type of node that could appear in a document tree.
When the subclass is defined, it should reference NodeHandler as
the first base class, and one or more docutils node classes as
subsequent base classes.
These docutils node classes will not actually wind up in the
base classes of the subclass. Instead, they will be used as
keys in a dispatch dictionary which is used to find the correct
NodeHandler subclass to use to process an instance of a given
docutils node class.
When an instance of createpdf.RstToPdf is created, a NodeHandler
instance will be called to return dispatchers for gather_elements
and gather_pdftext, wrapped up as methods of the createpdf.RstToPdf
class.
When a dispatcher is called, it will dispatch to the correct subclass
to handle the given docutils node instance.
If no NodeHandler subclass has been created to handle that particular
type of docutils node, then default processing will occur and a warning
will be logged.
'''
from copy import copy
import inspect
import types
from smartypants import smartypants
import docutils.nodes
from .flowables import BoundByWidth, TocEntry
from .log import log, nodeid
class MetaHelper(type):
"""MetaHelper is designed to generically enable a few of the benefits of
using metaclasses by encapsulating some of the complexity of setting
them up.
If a base class uses MetaHelper (by assigning __metaclass__ = MetaHelper),
then that class (and its metaclass inheriting subclasses) can control
class creation behavior by defining a couple of helper functions.
1) A base class can define a _classpreinit function. This function
is called during __new__ processing of the class object itself,
but only during subclass creation (not when the class defining
the _classpreinit is itself created).
The subclass object does not yet exist at the time _classpreinit
is called. _classpreinit accepts all the parameters of the
__new__ function for the class itself (not the same as the __new__
function for the instantiation of class objects!) and must return
a tuple of the same objects. A typical use of this would be to
modify the class bases before class creation.
2) Either a base class or a subclass can define a _classinit() function.
This function will be called immediately after the actual class has
been created, and can do whatever setup is required for the class.
Note that every base class (but not every subclass) which uses
MetaHelper MUST define _classinit, even if that definition is None.
MetaHelper also places an attribute into each class created with it.
_baseclass is set to None if this class has no superclasses which
also use MetaHelper, or to the first such MetaHelper-using baseclass.
_baseclass can be explicitly set inside the class definition, in
which case MetaHelper will not override it.
"""
def __new__(clstype, name, bases, clsdict):
# Our base class is the first base in the class definition which
# uses MetaHelper, or None if no such base exists.
base = ([x for x in bases if type(x) is MetaHelper] + [None])[0]
# Only set our base into the class if it has not been explicitly
# set
clsdict.setdefault('_baseclass', base)
# See if the base class definied a preinit function, and call it
# if so.
preinit = getattr(base, '_classpreinit', None)
if preinit is not None:
clstype, name, bases, clsdict = preinit(clstype, name, bases, clsdict)
# Delegate the real work to type
return type.__new__(clstype, name, bases, clsdict)
def __init__(cls, name, bases, clsdict):
# Let type build the class for us
type.__init__(cls, name, bases, clsdict)
# Call the class's initialization function if defined
if cls._classinit is not None:
cls._classinit()
class NodeHandler(metaclass=MetaHelper):
"""NodeHandler classes are used to dispatch
to the correct class to handle some node class
type, via a dispatchdict in the main class.
"""
dispatchdict = {}
@classmethod
def _classpreinit(baseclass, clstype, name, bases, clsdict):
# _classpreinit is called before the actual class is built
# Perform triage on the class bases to separate actual
# inheritable bases from the target docutils node classes
# which we want to dispatch for.
new_bases = []
targets = []
for target in bases:
if target is not object:
(targets, new_bases)[issubclass(target, NodeHandler)].append(target)
clsdict['_targets'] = targets
return clstype, name, tuple(new_bases), clsdict
@classmethod
def _classinit(cls):
# _classinit() is called once the subclass has actually
# been created.
# For the base class, just add a dispatch dictionary
if cls._baseclass is None:
cls.dispatchdict = {}
return
# for subclasses, instantiate them, and then add
# the class to the dispatch dictionary for each of its targets.
self = cls()
for target in cls._targets:
if cls.dispatchdict.setdefault(target, self) is not self:
t = repr(target)
old = repr(cls.dispatchdict[target])
new = repr(self)
log.debug(
'Dispatch handler %s for node type %s overridden by %s'
% (old, t, new)
)
cls.dispatchdict[target] = self
@staticmethod
def getclassname(obj):
cln = repr(obj.__class__)
info = cln.split("'")
if len(info) == 3:
return info[1]
return cln
def log_unknown(self, node, during):
if not hasattr(self, 'unkn_node'):
self.unkn_node = set()
cln = self.getclassname(node)
if cln not in self.unkn_node:
self.unkn_node.add(cln)
log.warning("Unkn. node (self.%s): %s [%s]", during, cln, nodeid(node))
try:
log.debug(node)
except (UnicodeDecodeError, UnicodeEncodeError):
log.debug(repr(node))
def findsubclass(self, node, during):
handlerinfo = '%s.%s' % (self.getclassname(self), during)
log.debug("%s: %s", handlerinfo, self.getclassname(node))
log.debug("%s: [%s]", handlerinfo, nodeid(node))
try:
log.debug("%s: %s", handlerinfo, node)
except (UnicodeDecodeError, UnicodeEncodeError):
log.debug("%s: %r", handlerinfo, node)
log.debug("")
# Dispatch to the first matching class in the MRO
dispatchdict = self.dispatchdict
for baseclass in inspect.getmro(node.__class__):
result = dispatchdict.get(baseclass)
if result is not None:
break
else:
self.log_unknown(node, during)
result = self
return result
def __call__(self, client):
'''Get the dispatchers, wrapped up as methods for the client'''
textdispatch = types.MethodType(self.textdispatch, client)
elemdispatch = types.MethodType(self.elemdispatch, client)
return textdispatch, elemdispatch
# This overridable attribute will be set true in the instance
# if handling a sphinx document
sphinxmode = False
# Begin overridable attributes and methods for elemdispatch
def gather_elements(self, client, node, style):
return client.gather_elements(node, style=style)
def _get_non_default_values_from_style(self, style):
"""Return a dictionary of all the items in the style that are changed from their default value"""
items = style.__dict__.copy()
defaults = style.defaults
for key in defaults.keys():
if defaults[key] == items[key]:
del items[key]
return items
def getstyle(self, client, node, style):
try:
if node['classes'] and node['classes'][0]:
for n in range(len(node['classes'])):
if node['classes'][n] in client.styles.StyleSheet:
if n == 0:
style = client.styles[node['classes'][n]]
else:
# merge the non-default properties of this style into the style we currently have
style = copy(style)
items = self._get_non_default_values_from_style(
client.styles[node['classes'][n]]
)
items.pop("parent", None)
name = f"{style.__dict__["name"]}-{items["name"]}"
items['name'] = name
style.__dict__.update(items)
else:
log.info(
"Unknown class %s, ignoring. [%s]",
n,
nodeid(node),
)
except TypeError: # Happens when a docutils.node.Text reaches here
pass
if style is None or style == client.styles['bodytext']:
style = client.styles.styleForNode(node)
return style
def getelements(self, client, node, style):
style = self.getstyle(client, node, style)
elements = self.gather_elements(client, node, style)
# Make all the sidebar cruft unreachable
# if style.__dict__.get('float','None').lower() !='none':
# node.elements=[Sidebar(node.elements,style)]
# elif 'width' in style.__dict__:
if 'width' in style.__dict__:
elements = [BoundByWidth(style.width, elements, style, mode="shrink")]
return elements
# End overridable attributes and methods for elemdispatch
def elemdispatch(self, client, node, style=None):
self = self.findsubclass(node, 'elemdispatch')
# set anchors for internal references
try:
for i in node['ids']:
client.pending_targets.append(i)
except TypeError: # Happens with docutils.node.Text
pass
elements = self.getelements(client, node, style)
if node.line and client.debugLinesPdf:
elements.insert(0, TocEntry(client.depth - 1, 'LINE-%s' % node.line))
node.elements = elements
return elements
# Begin overridable attributes and methods for textdispatch
pre = ''
post = ''
def get_pre_post(self, client, node, replaceEnt):
return self.pre, self.post
def get_text(self, client, node, replaceEnt):
return client.gather_pdftext(node)
def apply_smartypants(self, text, smarty, node):
# Try to be clever about when to use smartypants
if node.__class__ in (
docutils.nodes.paragraph,
docutils.nodes.block_quote,
docutils.nodes.title,
):
return smartypants(text, smarty)
return text
# End overridable attributes and methods for textdispatch
def textdispatch(self, client, node, replaceEnt=True):
self = self.findsubclass(node, 'textdispatch')
pre, post = self.get_pre_post(client, node, replaceEnt)
text = self.get_text(client, node, replaceEnt)
text = pre + text + post
try:
log.debug("%s.textdispatch: %s" % (self.getclassname(self), text))
except UnicodeDecodeError:
pass
text = self.apply_smartypants(text, client.smartypants_attributes, node)
node.pdftext = text
return text
| # -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
'''
This module provides one useful class: NodeHandler
The NodeHandler class is designed to be subclassed. Each subclass
should support the processing that createpdf.RstToPdf needs to do
on a particular type of node that could appear in a document tree.
When the subclass is defined, it should reference NodeHandler as
the first base class, and one or more docutils node classes as
subsequent base classes.
These docutils node classes will not actually wind up in the
base classes of the subclass. Instead, they will be used as
keys in a dispatch dictionary which is used to find the correct
NodeHandler subclass to use to process an instance of a given
docutils node class.
When an instance of createpdf.RstToPdf is created, a NodeHandler
instance will be called to return dispatchers for gather_elements
and gather_pdftext, wrapped up as methods of the createpdf.RstToPdf
class.
When a dispatcher is called, it will dispatch to the correct subclass
to handle the given docutils node instance.
If no NodeHandler subclass has been created to handle that particular
type of docutils node, then default processing will occur and a warning
will be logged.
'''
from copy import copy
import inspect
import types
from smartypants import smartypants
import docutils.nodes
from .flowables import BoundByWidth, TocEntry
from .log import log, nodeid
class MetaHelper(type):
"""MetaHelper is designed to generically enable a few of the benefits of
using metaclasses by encapsulating some of the complexity of setting
them up.
If a base class uses MetaHelper (by assigning __metaclass__ = MetaHelper),
then that class (and its metaclass inheriting subclasses) can control
class creation behavior by defining a couple of helper functions.
1) A base class can define a _classpreinit function. This function
is called during __new__ processing of the class object itself,
but only during subclass creation (not when the class defining
the _classpreinit is itself created).
The subclass object does not yet exist at the time _classpreinit
is called. _classpreinit accepts all the parameters of the
__new__ function for the class itself (not the same as the __new__
function for the instantiation of class objects!) and must return
a tuple of the same objects. A typical use of this would be to
modify the class bases before class creation.
2) Either a base class or a subclass can define a _classinit() function.
This function will be called immediately after the actual class has
been created, and can do whatever setup is required for the class.
Note that every base class (but not every subclass) which uses
MetaHelper MUST define _classinit, even if that definition is None.
MetaHelper also places an attribute into each class created with it.
_baseclass is set to None if this class has no superclasses which
also use MetaHelper, or to the first such MetaHelper-using baseclass.
_baseclass can be explicitly set inside the class definition, in
which case MetaHelper will not override it.
"""
def __new__(clstype, name, bases, clsdict):
# Our base class is the first base in the class definition which
# uses MetaHelper, or None if no such base exists.
base = ([x for x in bases if type(x) is MetaHelper] + [None])[0]
# Only set our base into the class if it has not been explicitly
# set
clsdict.setdefault('_baseclass', base)
# See if the base class definied a preinit function, and call it
# if so.
preinit = getattr(base, '_classpreinit', None)
if preinit is not None:
clstype, name, bases, clsdict = preinit(clstype, name, bases, clsdict)
# Delegate the real work to type
return type.__new__(clstype, name, bases, clsdict)
def __init__(cls, name, bases, clsdict):
# Let type build the class for us
type.__init__(cls, name, bases, clsdict)
# Call the class's initialization function if defined
if cls._classinit is not None:
cls._classinit()
class NodeHandler(metaclass=MetaHelper):
"""NodeHandler classes are used to dispatch
to the correct class to handle some node class
type, via a dispatchdict in the main class.
"""
dispatchdict = {}
@classmethod
def _classpreinit(baseclass, clstype, name, bases, clsdict):
# _classpreinit is called before the actual class is built
# Perform triage on the class bases to separate actual
# inheritable bases from the target docutils node classes
# which we want to dispatch for.
new_bases = []
targets = []
for target in bases:
if target is not object:
(targets, new_bases)[issubclass(target, NodeHandler)].append(target)
clsdict['_targets'] = targets
return clstype, name, tuple(new_bases), clsdict
@classmethod
def _classinit(cls):
# _classinit() is called once the subclass has actually
# been created.
# For the base class, just add a dispatch dictionary
if cls._baseclass is None:
cls.dispatchdict = {}
return
# for subclasses, instantiate them, and then add
# the class to the dispatch dictionary for each of its targets.
self = cls()
for target in cls._targets:
if cls.dispatchdict.setdefault(target, self) is not self:
t = repr(target)
old = repr(cls.dispatchdict[target])
new = repr(self)
log.debug(
'Dispatch handler %s for node type %s overridden by %s'
% (old, t, new)
)
cls.dispatchdict[target] = self
@staticmethod
def getclassname(obj):
cln = repr(obj.__class__)
info = cln.split("'")
if len(info) == 3:
return info[1]
return cln
def log_unknown(self, node, during):
if not hasattr(self, 'unkn_node'):
self.unkn_node = set()
cln = self.getclassname(node)
if cln not in self.unkn_node:
self.unkn_node.add(cln)
log.warning("Unkn. node (self.%s): %s [%s]", during, cln, nodeid(node))
try:
log.debug(node)
except (UnicodeDecodeError, UnicodeEncodeError):
log.debug(repr(node))
def findsubclass(self, node, during):
handlerinfo = '%s.%s' % (self.getclassname(self), during)
log.debug("%s: %s", handlerinfo, self.getclassname(node))
log.debug("%s: [%s]", handlerinfo, nodeid(node))
try:
log.debug("%s: %s", handlerinfo, node)
except (UnicodeDecodeError, UnicodeEncodeError):
log.debug("%s: %r", handlerinfo, node)
log.debug("")
# Dispatch to the first matching class in the MRO
dispatchdict = self.dispatchdict
for baseclass in inspect.getmro(node.__class__):
result = dispatchdict.get(baseclass)
if result is not None:
break
else:
self.log_unknown(node, during)
result = self
return result
def __call__(self, client):
'''Get the dispatchers, wrapped up as methods for the client'''
textdispatch = types.MethodType(self.textdispatch, client)
elemdispatch = types.MethodType(self.elemdispatch, client)
return textdispatch, elemdispatch
# This overridable attribute will be set true in the instance
# if handling a sphinx document
sphinxmode = False
# Begin overridable attributes and methods for elemdispatch
def gather_elements(self, client, node, style):
return client.gather_elements(node, style=style)
def _get_non_default_values_from_style(self, style):
"""Return a dictionary of all the items in the style that are changed from their default value"""
items = style.__dict__.copy()
defaults = style.defaults
for key in defaults.keys():
if defaults[key] == items[key]:
del items[key]
return items
def getstyle(self, client, node, style):
try:
if node['classes'] and node['classes'][0]:
for n in range(len(node['classes'])):
if node['classes'][n] in client.styles.StyleSheet:
if n == 0:
style = client.styles[node['classes'][n]]
else:
# merge the non-default properties of this style into the style we currently have
style = copy(style)
items = self._get_non_default_values_from_style(
client.styles[node['classes'][n]]
)
items.pop("parent", None)
name = f"{style.__dict__['name']}-{items['name']}"
items['name'] = name
style.__dict__.update(items)
else:
log.info(
"Unknown class %s, ignoring. [%s]",
n,
nodeid(node),
)
except TypeError: # Happens when a docutils.node.Text reaches here
pass
if style is None or style == client.styles['bodytext']:
style = client.styles.styleForNode(node)
return style
def getelements(self, client, node, style):
style = self.getstyle(client, node, style)
elements = self.gather_elements(client, node, style)
# Make all the sidebar cruft unreachable
# if style.__dict__.get('float','None').lower() !='none':
# node.elements=[Sidebar(node.elements,style)]
# elif 'width' in style.__dict__:
if 'width' in style.__dict__:
elements = [BoundByWidth(style.width, elements, style, mode="shrink")]
return elements
# End overridable attributes and methods for elemdispatch
def elemdispatch(self, client, node, style=None):
self = self.findsubclass(node, 'elemdispatch')
# set anchors for internal references
try:
for i in node['ids']:
client.pending_targets.append(i)
except TypeError: # Happens with docutils.node.Text
pass
elements = self.getelements(client, node, style)
if node.line and client.debugLinesPdf:
elements.insert(0, TocEntry(client.depth - 1, 'LINE-%s' % node.line))
node.elements = elements
return elements
# Begin overridable attributes and methods for textdispatch
pre = ''
post = ''
def get_pre_post(self, client, node, replaceEnt):
return self.pre, self.post
def get_text(self, client, node, replaceEnt):
return client.gather_pdftext(node)
def apply_smartypants(self, text, smarty, node):
# Try to be clever about when to use smartypants
if node.__class__ in (
docutils.nodes.paragraph,
docutils.nodes.block_quote,
docutils.nodes.title,
):
return smartypants(text, smarty)
return text
# End overridable attributes and methods for textdispatch
def textdispatch(self, client, node, replaceEnt=True):
self = self.findsubclass(node, 'textdispatch')
pre, post = self.get_pre_post(client, node, replaceEnt)
text = self.get_text(client, node, replaceEnt)
text = pre + text + post
try:
log.debug("%s.textdispatch: %s" % (self.getclassname(self), text))
except UnicodeDecodeError:
pass
text = self.apply_smartypants(text, client.smartypants_attributes, node)
node.pdftext = text
return text
|
from collections import Counter
import aiohttp
import asyncio
import functools
import json
import time
from pprint import pprint
from typing import List, Dict, Optional, Callable
from xcha.cmds.wallet_funcs import print_balance, wallet_coin_unit
from xcha.pools.pool_wallet_info import PoolWalletInfo, PoolSingletonState
from xcha.protocols.pool_protocol import POOL_PROTOCOL_VERSION
from xcha.rpc.farmer_rpc_client import FarmerRpcClient
from xcha.rpc.wallet_rpc_client import WalletRpcClient
from xcha.types.blockchain_format.sized_bytes import bytes32
from xcha.server.server import ssl_context_for_root
from xcha.ssl.create_ssl import get_mozilla_ca_crt
from xcha.util.bech32m import encode_puzzle_hash
from xcha.util.byte_types import hexstr_to_bytes
from xcha.util.config import load_config
from xcha.util.default_root import DEFAULT_ROOT_PATH
from xcha.util.ints import uint16, uint32
from xcha.wallet.transaction_record import TransactionRecord
from xcha.wallet.util.wallet_types import WalletType
async def create_pool_args(pool_url: str) -> Dict:
try:
async with aiohttp.ClientSession() as session:
async with session.get(f"{pool_url}/pool_info", ssl=ssl_context_for_root(get_mozilla_ca_crt())) as response:
if response.ok:
json_dict = json.loads(await response.text())
else:
raise ValueError(f"Response from {pool_url} not OK: {response.status}")
except Exception as e:
raise ValueError(f"Error connecting to pool {pool_url}: {e}")
if json_dict["relative_lock_height"] > 1000:
raise ValueError("Relative lock height too high for this pool, cannot join")
if json_dict["protocol_version"] != POOL_PROTOCOL_VERSION:
raise ValueError(f"Incorrect version: {json_dict["protocol_version"]}, should be {POOL_PROTOCOL_VERSION}")
header_msg = f"\n---- Pool parameters fetched from {pool_url} ----"
print(header_msg)
pprint(json_dict)
print("-" * len(header_msg))
return json_dict
async def create(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
state = args["state"]
prompt = not args.get("yes", False)
# Could use initial_pool_state_from_dict to simplify
if state == "SELF_POOLING":
pool_url: Optional[str] = None
relative_lock_height = uint32(0)
target_puzzle_hash = None # wallet will fill this in
elif state == "FARMING_TO_POOL":
config = load_config(DEFAULT_ROOT_PATH, "config.yaml")
enforce_https = config["full_node"]["selected_network"] == "mainnet"
pool_url = str(args["pool_url"])
if enforce_https and not pool_url.startswith("https://"):
print(f"Pool URLs must be HTTPS on mainnet {pool_url}. Aborting.")
return
json_dict = await create_pool_args(pool_url)
relative_lock_height = json_dict["relative_lock_height"]
target_puzzle_hash = hexstr_to_bytes(json_dict["target_puzzle_hash"])
else:
raise ValueError("Plot NFT must be created in SELF_POOLING or FARMING_TO_POOL state.")
pool_msg = f" and join pool: {pool_url}" if pool_url else ""
print(f"Will create a plot NFT{pool_msg}.")
if prompt:
user_input: str = input("Confirm [n]/y: ")
else:
user_input = "yes"
if user_input.lower() == "y" or user_input.lower() == "yes":
try:
tx_record: TransactionRecord = await wallet_client.create_new_pool_wallet(
target_puzzle_hash,
pool_url,
relative_lock_height,
"localhost:5000",
"new",
state,
)
start = time.time()
while time.time() - start < 10:
await asyncio.sleep(0.1)
tx = await wallet_client.get_transaction(str(1), tx_record.name)
if len(tx.sent_to) > 0:
print(f"Transaction submitted to nodes: {tx.sent_to}")
print(f"Do xcha wallet get_transaction -f {fingerprint} -tx 0x{tx_record.name} to get status")
return None
except Exception as e:
print(f"Error creating plot NFT: {e}")
return
print("Aborting.")
async def pprint_pool_wallet_state(
wallet_client: WalletRpcClient,
wallet_id: int,
pool_wallet_info: PoolWalletInfo,
address_prefix: str,
pool_state_dict: Dict,
plot_counts: Counter,
):
if pool_wallet_info.current.state == PoolSingletonState.LEAVING_POOL and pool_wallet_info.target is None:
expected_leave_height = pool_wallet_info.singleton_block_height + pool_wallet_info.current.relative_lock_height
print(f"Current state: INVALID_STATE. Please leave/join again after block height {expected_leave_height}")
else:
print(f"Current state: {PoolSingletonState(pool_wallet_info.current.state).name}")
print(f"Current state from block height: {pool_wallet_info.singleton_block_height}")
print(f"Launcher ID: {pool_wallet_info.launcher_id}")
print(
"Target address (not for plotting): "
f"{encode_puzzle_hash(pool_wallet_info.current.target_puzzle_hash, address_prefix)}"
)
print(f"Number of plots: {plot_counts[pool_wallet_info.p2_singleton_puzzle_hash]}")
print(f"Owner public key: {pool_wallet_info.current.owner_pubkey}")
print(
f"Pool contract address (use ONLY for plotting - do not send money to this address): "
f"{encode_puzzle_hash(pool_wallet_info.p2_singleton_puzzle_hash, address_prefix)}"
)
if pool_wallet_info.target is not None:
print(f"Target state: {PoolSingletonState(pool_wallet_info.target.state).name}")
print(f"Target pool URL: {pool_wallet_info.target.pool_url}")
if pool_wallet_info.current.state == PoolSingletonState.SELF_POOLING.value:
balances: Dict = await wallet_client.get_wallet_balance(str(wallet_id))
balance = balances["confirmed_wallet_balance"]
typ = WalletType(int(WalletType.POOLING_WALLET))
address_prefix, scale = wallet_coin_unit(typ, address_prefix)
print(f"Claimable balance: {print_balance(balance, scale, address_prefix)}")
if pool_wallet_info.current.state == PoolSingletonState.FARMING_TO_POOL:
print(f"Current pool URL: {pool_wallet_info.current.pool_url}")
if pool_wallet_info.launcher_id in pool_state_dict:
print(f"Current difficulty: {pool_state_dict[pool_wallet_info.launcher_id]["current_difficulty"]}")
print(f"Points balance: {pool_state_dict[pool_wallet_info.launcher_id]["current_points"]}")
num_points_found_24h = len(pool_state_dict[pool_wallet_info.launcher_id]["points_found_24h"])
if num_points_found_24h > 0:
num_points_ack_24h = len(pool_state_dict[pool_wallet_info.launcher_id]["points_acknowledged_24h"])
success_pct = num_points_ack_24h / num_points_found_24h
print(f"Percent Successful Points (24h): {success_pct:.2%}")
print(f"Relative lock height: {pool_wallet_info.current.relative_lock_height} blocks")
payout_instructions: str = pool_state_dict[pool_wallet_info.launcher_id]["pool_config"]["payout_instructions"]
try:
payout_address = encode_puzzle_hash(bytes32.fromhex(payout_instructions), address_prefix)
print(f"Payout instructions (pool will pay to this address): {payout_address}")
except Exception:
print(f"Payout instructions (pool will pay you with this): {payout_instructions}")
if pool_wallet_info.current.state == PoolSingletonState.LEAVING_POOL:
expected_leave_height = pool_wallet_info.singleton_block_height + pool_wallet_info.current.relative_lock_height
if pool_wallet_info.target is not None:
print(f"Expected to leave after block height: {expected_leave_height}")
async def show(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
config = load_config(DEFAULT_ROOT_PATH, "config.yaml")
self_hostname = config["self_hostname"]
farmer_rpc_port = config["farmer"]["rpc_port"]
farmer_client = await FarmerRpcClient.create(self_hostname, uint16(farmer_rpc_port), DEFAULT_ROOT_PATH, config)
address_prefix = config["network_overrides"]["config"][config["selected_network"]]["address_prefix"]
summaries_response = await wallet_client.get_wallets()
wallet_id_passed_in = args.get("id", None)
plot_counts: Counter = Counter()
try:
pool_state_list: List = (await farmer_client.get_pool_state())["pool_state"]
harvesters = await farmer_client.get_harvesters()
for d in harvesters["harvesters"]:
for plot in d["plots"]:
if plot.get("pool_contract_puzzle_hash", None) is not None:
# Non pooled plots will have a None pool_contract_puzzle_hash
plot_counts[hexstr_to_bytes(plot["pool_contract_puzzle_hash"])] += 1
except Exception as e:
if isinstance(e, aiohttp.ClientConnectorError):
print(
f"Connection error. Check if farmer is running at {farmer_rpc_port}."
f" You can run the farmer by:\n xcha start farmer-only"
)
else:
print(f"Exception from 'wallet' {e}")
farmer_client.close()
await farmer_client.await_closed()
return
pool_state_dict: Dict[bytes32, Dict] = {
hexstr_to_bytes(pool_state_item["pool_config"]["launcher_id"]): pool_state_item
for pool_state_item in pool_state_list
}
if wallet_id_passed_in is not None:
for summary in summaries_response:
typ = WalletType(int(summary["type"]))
if summary["id"] == wallet_id_passed_in and typ != WalletType.POOLING_WALLET:
print(f"Wallet with id: {wallet_id_passed_in} is not a pooling wallet. Please provide a different id.")
return
pool_wallet_info, _ = await wallet_client.pw_status(wallet_id_passed_in)
await pprint_pool_wallet_state(
wallet_client,
wallet_id_passed_in,
pool_wallet_info,
address_prefix,
pool_state_dict,
plot_counts,
)
else:
print(f"Wallet height: {await wallet_client.get_height_info()}")
print(f"Sync status: {"Synced" if (await wallet_client.get_synced()) else "Not synced"}")
for summary in summaries_response:
wallet_id = summary["id"]
typ = WalletType(int(summary["type"]))
if typ == WalletType.POOLING_WALLET:
print(f"Wallet id {wallet_id}: ")
pool_wallet_info, _ = await wallet_client.pw_status(wallet_id)
await pprint_pool_wallet_state(
wallet_client,
wallet_id,
pool_wallet_info,
address_prefix,
pool_state_dict,
plot_counts,
)
print("")
farmer_client.close()
await farmer_client.await_closed()
async def get_login_link(launcher_id_str: str) -> None:
launcher_id: bytes32 = hexstr_to_bytes(launcher_id_str)
config = load_config(DEFAULT_ROOT_PATH, "config.yaml")
self_hostname = config["self_hostname"]
farmer_rpc_port = config["farmer"]["rpc_port"]
farmer_client = await FarmerRpcClient.create(self_hostname, uint16(farmer_rpc_port), DEFAULT_ROOT_PATH, config)
try:
login_link: Optional[str] = await farmer_client.get_pool_login_link(launcher_id)
if login_link is None:
print("Was not able to get login link.")
else:
print(login_link)
except Exception as e:
if isinstance(e, aiohttp.ClientConnectorError):
print(
f"Connection error. Check if farmer is running at {farmer_rpc_port}."
f" You can run the farmer by:\n xcha start farmer-only"
)
else:
print(f"Exception from 'farmer' {e}")
finally:
farmer_client.close()
await farmer_client.await_closed()
async def submit_tx_with_confirmation(
message: str, prompt: bool, func: Callable, wallet_client: WalletRpcClient, fingerprint: int, wallet_id: int
):
print(message)
if prompt:
user_input: str = input("Confirm [n]/y: ")
else:
user_input = "yes"
if user_input.lower() == "y" or user_input.lower() == "yes":
try:
tx_record: TransactionRecord = await func()
start = time.time()
while time.time() - start < 10:
await asyncio.sleep(0.1)
tx = await wallet_client.get_transaction(str(1), tx_record.name)
if len(tx.sent_to) > 0:
print(f"Transaction submitted to nodes: {tx.sent_to}")
print(f"Do xcha wallet get_transaction -f {fingerprint} -tx 0x{tx_record.name} to get status")
return None
except Exception as e:
print(f"Error performing operation on Plot NFT -f {fingerprint} wallet id: {wallet_id}: {e}")
return
print("Aborting.")
async def join_pool(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
config = load_config(DEFAULT_ROOT_PATH, "config.yaml")
enforce_https = config["full_node"]["selected_network"] == "mainnet"
pool_url: str = args["pool_url"]
if enforce_https and not pool_url.startswith("https://"):
print(f"Pool URLs must be HTTPS on mainnet {pool_url}. Aborting.")
return
wallet_id = args.get("id", None)
prompt = not args.get("yes", False)
try:
async with aiohttp.ClientSession() as session:
async with session.get(f"{pool_url}/pool_info", ssl=ssl_context_for_root(get_mozilla_ca_crt())) as response:
if response.ok:
json_dict = json.loads(await response.text())
else:
print(f"Response not OK: {response.status}")
return
except Exception as e:
print(f"Error connecting to pool {pool_url}: {e}")
return
if json_dict["relative_lock_height"] > 1000:
print("Relative lock height too high for this pool, cannot join")
return
if json_dict["protocol_version"] != POOL_PROTOCOL_VERSION:
print(f"Incorrect version: {json_dict["protocol_version"]}, should be {POOL_PROTOCOL_VERSION}")
return
pprint(json_dict)
msg = f"\nWill join pool: {pool_url} with Plot NFT {fingerprint}."
func = functools.partial(
wallet_client.pw_join_pool,
wallet_id,
hexstr_to_bytes(json_dict["target_puzzle_hash"]),
pool_url,
json_dict["relative_lock_height"],
)
await submit_tx_with_confirmation(msg, prompt, func, wallet_client, fingerprint, wallet_id)
async def self_pool(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
wallet_id = args.get("id", None)
prompt = not args.get("yes", False)
msg = f"Will start self-farming with Plot NFT on wallet id {wallet_id} fingerprint {fingerprint}."
func = functools.partial(wallet_client.pw_self_pool, wallet_id)
await submit_tx_with_confirmation(msg, prompt, func, wallet_client, fingerprint, wallet_id)
async def inspect_cmd(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
wallet_id = args.get("id", None)
pool_wallet_info, unconfirmed_transactions = await wallet_client.pw_status(wallet_id)
print(
{
"pool_wallet_info": pool_wallet_info,
"unconfirmed_transactions": [
{"sent_to": tx.sent_to, "transaction_id": tx.name.hex()} for tx in unconfirmed_transactions
],
}
)
async def claim_cmd(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
wallet_id = args.get("id", None)
msg = f"\nWill claim rewards for wallet ID: {wallet_id}."
func = functools.partial(
wallet_client.pw_absorb_rewards,
wallet_id,
)
await submit_tx_with_confirmation(msg, False, func, wallet_client, fingerprint, wallet_id)
| from collections import Counter
import aiohttp
import asyncio
import functools
import json
import time
from pprint import pprint
from typing import List, Dict, Optional, Callable
from xcha.cmds.wallet_funcs import print_balance, wallet_coin_unit
from xcha.pools.pool_wallet_info import PoolWalletInfo, PoolSingletonState
from xcha.protocols.pool_protocol import POOL_PROTOCOL_VERSION
from xcha.rpc.farmer_rpc_client import FarmerRpcClient
from xcha.rpc.wallet_rpc_client import WalletRpcClient
from xcha.types.blockchain_format.sized_bytes import bytes32
from xcha.server.server import ssl_context_for_root
from xcha.ssl.create_ssl import get_mozilla_ca_crt
from xcha.util.bech32m import encode_puzzle_hash
from xcha.util.byte_types import hexstr_to_bytes
from xcha.util.config import load_config
from xcha.util.default_root import DEFAULT_ROOT_PATH
from xcha.util.ints import uint16, uint32
from xcha.wallet.transaction_record import TransactionRecord
from xcha.wallet.util.wallet_types import WalletType
async def create_pool_args(pool_url: str) -> Dict:
try:
async with aiohttp.ClientSession() as session:
async with session.get(f"{pool_url}/pool_info", ssl=ssl_context_for_root(get_mozilla_ca_crt())) as response:
if response.ok:
json_dict = json.loads(await response.text())
else:
raise ValueError(f"Response from {pool_url} not OK: {response.status}")
except Exception as e:
raise ValueError(f"Error connecting to pool {pool_url}: {e}")
if json_dict["relative_lock_height"] > 1000:
raise ValueError("Relative lock height too high for this pool, cannot join")
if json_dict["protocol_version"] != POOL_PROTOCOL_VERSION:
raise ValueError(f"Incorrect version: {json_dict['protocol_version']}, should be {POOL_PROTOCOL_VERSION}")
header_msg = f"\n---- Pool parameters fetched from {pool_url} ----"
print(header_msg)
pprint(json_dict)
print("-" * len(header_msg))
return json_dict
async def create(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
state = args["state"]
prompt = not args.get("yes", False)
# Could use initial_pool_state_from_dict to simplify
if state == "SELF_POOLING":
pool_url: Optional[str] = None
relative_lock_height = uint32(0)
target_puzzle_hash = None # wallet will fill this in
elif state == "FARMING_TO_POOL":
config = load_config(DEFAULT_ROOT_PATH, "config.yaml")
enforce_https = config["full_node"]["selected_network"] == "mainnet"
pool_url = str(args["pool_url"])
if enforce_https and not pool_url.startswith("https://"):
print(f"Pool URLs must be HTTPS on mainnet {pool_url}. Aborting.")
return
json_dict = await create_pool_args(pool_url)
relative_lock_height = json_dict["relative_lock_height"]
target_puzzle_hash = hexstr_to_bytes(json_dict["target_puzzle_hash"])
else:
raise ValueError("Plot NFT must be created in SELF_POOLING or FARMING_TO_POOL state.")
pool_msg = f" and join pool: {pool_url}" if pool_url else ""
print(f"Will create a plot NFT{pool_msg}.")
if prompt:
user_input: str = input("Confirm [n]/y: ")
else:
user_input = "yes"
if user_input.lower() == "y" or user_input.lower() == "yes":
try:
tx_record: TransactionRecord = await wallet_client.create_new_pool_wallet(
target_puzzle_hash,
pool_url,
relative_lock_height,
"localhost:5000",
"new",
state,
)
start = time.time()
while time.time() - start < 10:
await asyncio.sleep(0.1)
tx = await wallet_client.get_transaction(str(1), tx_record.name)
if len(tx.sent_to) > 0:
print(f"Transaction submitted to nodes: {tx.sent_to}")
print(f"Do xcha wallet get_transaction -f {fingerprint} -tx 0x{tx_record.name} to get status")
return None
except Exception as e:
print(f"Error creating plot NFT: {e}")
return
print("Aborting.")
async def pprint_pool_wallet_state(
wallet_client: WalletRpcClient,
wallet_id: int,
pool_wallet_info: PoolWalletInfo,
address_prefix: str,
pool_state_dict: Dict,
plot_counts: Counter,
):
if pool_wallet_info.current.state == PoolSingletonState.LEAVING_POOL and pool_wallet_info.target is None:
expected_leave_height = pool_wallet_info.singleton_block_height + pool_wallet_info.current.relative_lock_height
print(f"Current state: INVALID_STATE. Please leave/join again after block height {expected_leave_height}")
else:
print(f"Current state: {PoolSingletonState(pool_wallet_info.current.state).name}")
print(f"Current state from block height: {pool_wallet_info.singleton_block_height}")
print(f"Launcher ID: {pool_wallet_info.launcher_id}")
print(
"Target address (not for plotting): "
f"{encode_puzzle_hash(pool_wallet_info.current.target_puzzle_hash, address_prefix)}"
)
print(f"Number of plots: {plot_counts[pool_wallet_info.p2_singleton_puzzle_hash]}")
print(f"Owner public key: {pool_wallet_info.current.owner_pubkey}")
print(
f"Pool contract address (use ONLY for plotting - do not send money to this address): "
f"{encode_puzzle_hash(pool_wallet_info.p2_singleton_puzzle_hash, address_prefix)}"
)
if pool_wallet_info.target is not None:
print(f"Target state: {PoolSingletonState(pool_wallet_info.target.state).name}")
print(f"Target pool URL: {pool_wallet_info.target.pool_url}")
if pool_wallet_info.current.state == PoolSingletonState.SELF_POOLING.value:
balances: Dict = await wallet_client.get_wallet_balance(str(wallet_id))
balance = balances["confirmed_wallet_balance"]
typ = WalletType(int(WalletType.POOLING_WALLET))
address_prefix, scale = wallet_coin_unit(typ, address_prefix)
print(f"Claimable balance: {print_balance(balance, scale, address_prefix)}")
if pool_wallet_info.current.state == PoolSingletonState.FARMING_TO_POOL:
print(f"Current pool URL: {pool_wallet_info.current.pool_url}")
if pool_wallet_info.launcher_id in pool_state_dict:
print(f"Current difficulty: {pool_state_dict[pool_wallet_info.launcher_id]['current_difficulty']}")
print(f"Points balance: {pool_state_dict[pool_wallet_info.launcher_id]['current_points']}")
num_points_found_24h = len(pool_state_dict[pool_wallet_info.launcher_id]["points_found_24h"])
if num_points_found_24h > 0:
num_points_ack_24h = len(pool_state_dict[pool_wallet_info.launcher_id]["points_acknowledged_24h"])
success_pct = num_points_ack_24h / num_points_found_24h
print(f"Percent Successful Points (24h): {success_pct:.2%}")
print(f"Relative lock height: {pool_wallet_info.current.relative_lock_height} blocks")
payout_instructions: str = pool_state_dict[pool_wallet_info.launcher_id]["pool_config"]["payout_instructions"]
try:
payout_address = encode_puzzle_hash(bytes32.fromhex(payout_instructions), address_prefix)
print(f"Payout instructions (pool will pay to this address): {payout_address}")
except Exception:
print(f"Payout instructions (pool will pay you with this): {payout_instructions}")
if pool_wallet_info.current.state == PoolSingletonState.LEAVING_POOL:
expected_leave_height = pool_wallet_info.singleton_block_height + pool_wallet_info.current.relative_lock_height
if pool_wallet_info.target is not None:
print(f"Expected to leave after block height: {expected_leave_height}")
async def show(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
config = load_config(DEFAULT_ROOT_PATH, "config.yaml")
self_hostname = config["self_hostname"]
farmer_rpc_port = config["farmer"]["rpc_port"]
farmer_client = await FarmerRpcClient.create(self_hostname, uint16(farmer_rpc_port), DEFAULT_ROOT_PATH, config)
address_prefix = config["network_overrides"]["config"][config["selected_network"]]["address_prefix"]
summaries_response = await wallet_client.get_wallets()
wallet_id_passed_in = args.get("id", None)
plot_counts: Counter = Counter()
try:
pool_state_list: List = (await farmer_client.get_pool_state())["pool_state"]
harvesters = await farmer_client.get_harvesters()
for d in harvesters["harvesters"]:
for plot in d["plots"]:
if plot.get("pool_contract_puzzle_hash", None) is not None:
# Non pooled plots will have a None pool_contract_puzzle_hash
plot_counts[hexstr_to_bytes(plot["pool_contract_puzzle_hash"])] += 1
except Exception as e:
if isinstance(e, aiohttp.ClientConnectorError):
print(
f"Connection error. Check if farmer is running at {farmer_rpc_port}."
f" You can run the farmer by:\n xcha start farmer-only"
)
else:
print(f"Exception from 'wallet' {e}")
farmer_client.close()
await farmer_client.await_closed()
return
pool_state_dict: Dict[bytes32, Dict] = {
hexstr_to_bytes(pool_state_item["pool_config"]["launcher_id"]): pool_state_item
for pool_state_item in pool_state_list
}
if wallet_id_passed_in is not None:
for summary in summaries_response:
typ = WalletType(int(summary["type"]))
if summary["id"] == wallet_id_passed_in and typ != WalletType.POOLING_WALLET:
print(f"Wallet with id: {wallet_id_passed_in} is not a pooling wallet. Please provide a different id.")
return
pool_wallet_info, _ = await wallet_client.pw_status(wallet_id_passed_in)
await pprint_pool_wallet_state(
wallet_client,
wallet_id_passed_in,
pool_wallet_info,
address_prefix,
pool_state_dict,
plot_counts,
)
else:
print(f"Wallet height: {await wallet_client.get_height_info()}")
print(f"Sync status: {'Synced' if (await wallet_client.get_synced()) else 'Not synced'}")
for summary in summaries_response:
wallet_id = summary["id"]
typ = WalletType(int(summary["type"]))
if typ == WalletType.POOLING_WALLET:
print(f"Wallet id {wallet_id}: ")
pool_wallet_info, _ = await wallet_client.pw_status(wallet_id)
await pprint_pool_wallet_state(
wallet_client,
wallet_id,
pool_wallet_info,
address_prefix,
pool_state_dict,
plot_counts,
)
print("")
farmer_client.close()
await farmer_client.await_closed()
async def get_login_link(launcher_id_str: str) -> None:
launcher_id: bytes32 = hexstr_to_bytes(launcher_id_str)
config = load_config(DEFAULT_ROOT_PATH, "config.yaml")
self_hostname = config["self_hostname"]
farmer_rpc_port = config["farmer"]["rpc_port"]
farmer_client = await FarmerRpcClient.create(self_hostname, uint16(farmer_rpc_port), DEFAULT_ROOT_PATH, config)
try:
login_link: Optional[str] = await farmer_client.get_pool_login_link(launcher_id)
if login_link is None:
print("Was not able to get login link.")
else:
print(login_link)
except Exception as e:
if isinstance(e, aiohttp.ClientConnectorError):
print(
f"Connection error. Check if farmer is running at {farmer_rpc_port}."
f" You can run the farmer by:\n xcha start farmer-only"
)
else:
print(f"Exception from 'farmer' {e}")
finally:
farmer_client.close()
await farmer_client.await_closed()
async def submit_tx_with_confirmation(
message: str, prompt: bool, func: Callable, wallet_client: WalletRpcClient, fingerprint: int, wallet_id: int
):
print(message)
if prompt:
user_input: str = input("Confirm [n]/y: ")
else:
user_input = "yes"
if user_input.lower() == "y" or user_input.lower() == "yes":
try:
tx_record: TransactionRecord = await func()
start = time.time()
while time.time() - start < 10:
await asyncio.sleep(0.1)
tx = await wallet_client.get_transaction(str(1), tx_record.name)
if len(tx.sent_to) > 0:
print(f"Transaction submitted to nodes: {tx.sent_to}")
print(f"Do xcha wallet get_transaction -f {fingerprint} -tx 0x{tx_record.name} to get status")
return None
except Exception as e:
print(f"Error performing operation on Plot NFT -f {fingerprint} wallet id: {wallet_id}: {e}")
return
print("Aborting.")
async def join_pool(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
config = load_config(DEFAULT_ROOT_PATH, "config.yaml")
enforce_https = config["full_node"]["selected_network"] == "mainnet"
pool_url: str = args["pool_url"]
if enforce_https and not pool_url.startswith("https://"):
print(f"Pool URLs must be HTTPS on mainnet {pool_url}. Aborting.")
return
wallet_id = args.get("id", None)
prompt = not args.get("yes", False)
try:
async with aiohttp.ClientSession() as session:
async with session.get(f"{pool_url}/pool_info", ssl=ssl_context_for_root(get_mozilla_ca_crt())) as response:
if response.ok:
json_dict = json.loads(await response.text())
else:
print(f"Response not OK: {response.status}")
return
except Exception as e:
print(f"Error connecting to pool {pool_url}: {e}")
return
if json_dict["relative_lock_height"] > 1000:
print("Relative lock height too high for this pool, cannot join")
return
if json_dict["protocol_version"] != POOL_PROTOCOL_VERSION:
print(f"Incorrect version: {json_dict['protocol_version']}, should be {POOL_PROTOCOL_VERSION}")
return
pprint(json_dict)
msg = f"\nWill join pool: {pool_url} with Plot NFT {fingerprint}."
func = functools.partial(
wallet_client.pw_join_pool,
wallet_id,
hexstr_to_bytes(json_dict["target_puzzle_hash"]),
pool_url,
json_dict["relative_lock_height"],
)
await submit_tx_with_confirmation(msg, prompt, func, wallet_client, fingerprint, wallet_id)
async def self_pool(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
wallet_id = args.get("id", None)
prompt = not args.get("yes", False)
msg = f"Will start self-farming with Plot NFT on wallet id {wallet_id} fingerprint {fingerprint}."
func = functools.partial(wallet_client.pw_self_pool, wallet_id)
await submit_tx_with_confirmation(msg, prompt, func, wallet_client, fingerprint, wallet_id)
async def inspect_cmd(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
wallet_id = args.get("id", None)
pool_wallet_info, unconfirmed_transactions = await wallet_client.pw_status(wallet_id)
print(
{
"pool_wallet_info": pool_wallet_info,
"unconfirmed_transactions": [
{"sent_to": tx.sent_to, "transaction_id": tx.name.hex()} for tx in unconfirmed_transactions
],
}
)
async def claim_cmd(args: dict, wallet_client: WalletRpcClient, fingerprint: int) -> None:
wallet_id = args.get("id", None)
msg = f"\nWill claim rewards for wallet ID: {wallet_id}."
func = functools.partial(
wallet_client.pw_absorb_rewards,
wallet_id,
)
await submit_tx_with_confirmation(msg, False, func, wallet_client, fingerprint, wallet_id)
|
"""Example showing how you can transfer a big file to the instrument and from the instrument with showing the progress.
Since the SMW is quite fast on data transfer, we slow it down by waiting for 100ms between each chunk transfer (1MB)
This way we see the transfer progress better and we do not need a file that is so big - let's take cca 20MB.
For big files, use the example without the time.sleep(0.1)"""
import time
import numpy as np
from RsSmw import *
def my_transfer_handler(args):
"""Function called each time a chunk of data is transferred"""
total_size = args.total_size if args.total_size is not None else "unknown"
print(f"Context: '{args.context}{"with opc" if args.opc_sync else ""}', "
f"chunk {args.chunk_ix}, "
f"transferred {args.transferred_size} bytes, "
f"total size {total_size}, "
f"direction {"reading" if args.reading else "writing"}, "
f"data '{args.data}'")
if args.end_of_transfer:
print('End of Transfer')
# Slow down the transfer by 200ms to see the progress better
time.sleep(0.1)
RsSmw.assert_minimum_version('4.80.2')
smw = RsSmw('TCPIP::10.112.1.179::HISLIP')
print(smw.utilities.idn_string)
smw.utilities.reset()
pc_file = r'c:\temp\bigFile.bin'
instr_file = '/var/user/bigFileInstr.bin'
pc_file_back = r'c:\temp\bigFileBack.bin'
# Generate a random file of 20MB size
x1mb = 1024 * 1024
with open(pc_file, 'wb') as file:
for x in range(20):
file.write(np.random.bytes(x1mb))
# Send the file to the instrument with events
smw.events.on_write_handler = my_transfer_handler
smw.utilities.data_chunk_size = x1mb
print(f'Sending file to the instrument...')
smw.utilities.send_file_from_pc_to_instrument(pc_file, instr_file)
smw.events.on_write_handler = None
print(f'Receiving file from the instrument...')
smw.events.on_read_handler = my_transfer_handler
smw.utilities.read_file_from_instrument_to_pc(instr_file, pc_file_back)
smw.events.on_read_handler = None
smw.close()
| """Example showing how you can transfer a big file to the instrument and from the instrument with showing the progress.
Since the SMW is quite fast on data transfer, we slow it down by waiting for 100ms between each chunk transfer (1MB)
This way we see the transfer progress better and we do not need a file that is so big - let's take cca 20MB.
For big files, use the example without the time.sleep(0.1)"""
import time
import numpy as np
from RsSmw import *
def my_transfer_handler(args):
"""Function called each time a chunk of data is transferred"""
total_size = args.total_size if args.total_size is not None else "unknown"
print(f"Context: '{args.context}{'with opc' if args.opc_sync else ''}', "
f"chunk {args.chunk_ix}, "
f"transferred {args.transferred_size} bytes, "
f"total size {total_size}, "
f"direction {'reading' if args.reading else 'writing'}, "
f"data '{args.data}'")
if args.end_of_transfer:
print('End of Transfer')
# Slow down the transfer by 200ms to see the progress better
time.sleep(0.1)
RsSmw.assert_minimum_version('4.80.2')
smw = RsSmw('TCPIP::10.112.1.179::HISLIP')
print(smw.utilities.idn_string)
smw.utilities.reset()
pc_file = r'c:\temp\bigFile.bin'
instr_file = '/var/user/bigFileInstr.bin'
pc_file_back = r'c:\temp\bigFileBack.bin'
# Generate a random file of 20MB size
x1mb = 1024 * 1024
with open(pc_file, 'wb') as file:
for x in range(20):
file.write(np.random.bytes(x1mb))
# Send the file to the instrument with events
smw.events.on_write_handler = my_transfer_handler
smw.utilities.data_chunk_size = x1mb
print(f'Sending file to the instrument...')
smw.utilities.send_file_from_pc_to_instrument(pc_file, instr_file)
smw.events.on_write_handler = None
print(f'Receiving file from the instrument...')
smw.events.on_read_handler = my_transfer_handler
smw.utilities.read_file_from_instrument_to_pc(instr_file, pc_file_back)
smw.events.on_read_handler = None
smw.close()
|
"""
Class that represents the execution level of nsight
@author: Alvaro Saiz (UC)
@date: Jul 2021
@version: 1.0
"""
import locale
from abc import ABC, abstractmethod # abstract class
import os, sys, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)
from parameters.level_execution_params import LevelExecutionParameters # parameters of program
from errors.level_execution_errors import *
from measure_levels.level_execution import LevelExecution
from measure_parts.extra_measure import ExtraMeasureNsight
class LevelExecutionNsight(LevelExecution, ABC):
"""
Class that represents the levels of the execution with nsight scan tool.
Attributes:
_extra_measure : ExtraMeasureNsight ; support measures
_collect_events : bool ; True if the execution must recolted the events used by NVIDIA scan tool
or False in other case
"""
def __init__(self, program : str, input_file : str, output_file : str, output_scan_file : str, collect_metrics : bool,
extra_measure : ExtraMeasureNsight):
locale.setlocale(locale.LC_ALL, 'es_ES.utf8')
self._extra_measure : ExtraMeasureNsight = extra_measure
super().__init__(program, input_file, output_file, output_scan_file, collect_metrics)
def extra_measure(self) -> ExtraMeasureNsight:
"""
Return ExtraMeasureNsight part of the execution.
Returns:
reference to ExtraMeasureNsight part of the execution
"""
return self._extra_measure
@abstractmethod
def run(self, lst_output : list):
"""
Makes execution.
Parameters:
lst_output : list ; list with results
"""
pass
@abstractmethod
def _generate_command(self) -> str:
"""
Generate command of execution with NVIDIA scan tool.
Returns:
String with command to be executed
"""
pass
@abstractmethod
def _get_results(self, lst_output : list):
"""
Get results of the different parts.
Parameters:
lst_output : list ; OUTPUT list with results
"""
pass
def extra_measure(self) -> ExtraMeasureNsight:
"""
Return ExtraMeasureNsight part of the execution.
Returns:
reference to ExtraMeasureNsight part of the execution
"""
return self._extra_measure
def _add_result_part_to_lst(self, dict_values : dict, dict_desc : dict,
lst_to_add):
"""
Add results of execution part (FrontEnd, BackEnd...) to list indicated by argument.
Args:
dict_values : dict ; diccionary with name_metric/event-value elements of the part to
add to 'lst_to_add'
dict_desc : dict ; diccionary with name_metric/event-description elements of the
part to add to 'lst_to_add'
lst_output : list ; list where to add all elements
Raises:
MetricNoDefined ; raised in case you have added an metric that is
not supported or does not exist in the NVIDIA analysis tool
"""
# metrics_events_not_average : list = LevelExecutionParameters.C_METRICS_AND_EVENTS_NOT_AVERAGE_COMPUTED.split(",")
name_max_length : int = len("Metric Name")
metric_unit_title : str = "Metric Unit"
unit_max_length : int = len(metric_unit_title)
metric_value_title : str = "Metric Value"
for key_value,key_unit in zip(dict_values, dict_desc):
if len(key_value) > name_max_length:
name_max_length = len(key_value)
if len(key_value[0]) > unit_max_length:
unit_max_length = key_value[0]
metric_name_length : int = name_max_length + 10
metric_unit_length : int = unit_max_length + 10
metric_value_length : int = len(metric_value_title)
description : str = ("\t\t\t%-*s" % (metric_name_length , "Metric Name"))
description += ("%-*s" % (metric_unit_length , metric_unit_title))
description += ("%-*s" % (metric_value_length, metric_value_title))
line_length : int = len(description)
metrics_events_not_average : list = LevelExecutionParameters.C_METRICS_AND_EVENTS_NOT_AVERAGE_COMPUTED.split(",")
total_value : float = 0.0
value_str : str
total_value_str : str = ""
metric_name : str
metric_unit : str
i : int = 0
for key_value, key_unit in zip(dict_values, dict_desc):
total_value = round(self._get_total_value_of_list(dict_values[key_value], False),
LevelExecutionParameters.C_MAX_NUM_RESULTS_DECIMALS)
if total_value.is_integer():
total_value = int(total_value)
value_metric_str = str(total_value)
metric_name = key_value
metric_unit = dict_desc.get(key_unit)
if not metric_unit:
metric_unit = "-"
elif metric_unit == "%":
# In NVIDIA scan tool, the percentages in each kernel are calculated on the total of
# each kernel and not on the total of the application
if key_value in metrics_events_not_average:
raise ComputedAsAverageError(key_unit)
value_str = "\t\t\t%-*s" % (metric_name_length, metric_name)
value_str += "%-*s" % (metric_unit_length, metric_unit)
value_str += "%-*s" % (len(metric_value_title), value_metric_str)
if len(value_str) > line_length:
line_length = len(value_str)
if i != len(dict_values) - 1:
value_str += "\n"
total_value_str += value_str
i += 1
spaces_length : int = len("\t\t\t")
line_str : str = "\t\t\t" + f'{'-' * (line_length - spaces_length)}'
lst_to_add.append("\n" + line_str)
lst_to_add.append(description)
lst_to_add.append(line_str)
lst_to_add.append(total_value_str)
lst_to_add.append(line_str + "\n")
def _percentage_time_kernel(self, kernel_number : int) -> float:
"""
Get time percentage in each Kernel.
Each kernel measured is an index of dictionaries used by this program.
Args:
kernel_number : int ; number of kernel
"""
value_lst : list = self._extra_measure.get_metric_value(LevelExecutionParameters.C_CYCLES_ELAPSED_METRIC_NAME_NSIGHT)
if value_lst is None:
raise ElapsedCyclesError
value_str : str
total_value : float = 0.0
for value_str in value_lst:
total_value += locale.atof(value_str)
return (locale.atof(value_lst[kernel_number])/total_value)*100.0
| """
Class that represents the execution level of nsight
@author: Alvaro Saiz (UC)
@date: Jul 2021
@version: 1.0
"""
import locale
from abc import ABC, abstractmethod # abstract class
import os, sys, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)
from parameters.level_execution_params import LevelExecutionParameters # parameters of program
from errors.level_execution_errors import *
from measure_levels.level_execution import LevelExecution
from measure_parts.extra_measure import ExtraMeasureNsight
class LevelExecutionNsight(LevelExecution, ABC):
"""
Class that represents the levels of the execution with nsight scan tool.
Attributes:
_extra_measure : ExtraMeasureNsight ; support measures
_collect_events : bool ; True if the execution must recolted the events used by NVIDIA scan tool
or False in other case
"""
def __init__(self, program : str, input_file : str, output_file : str, output_scan_file : str, collect_metrics : bool,
extra_measure : ExtraMeasureNsight):
locale.setlocale(locale.LC_ALL, 'es_ES.utf8')
self._extra_measure : ExtraMeasureNsight = extra_measure
super().__init__(program, input_file, output_file, output_scan_file, collect_metrics)
def extra_measure(self) -> ExtraMeasureNsight:
"""
Return ExtraMeasureNsight part of the execution.
Returns:
reference to ExtraMeasureNsight part of the execution
"""
return self._extra_measure
@abstractmethod
def run(self, lst_output : list):
"""
Makes execution.
Parameters:
lst_output : list ; list with results
"""
pass
@abstractmethod
def _generate_command(self) -> str:
"""
Generate command of execution with NVIDIA scan tool.
Returns:
String with command to be executed
"""
pass
@abstractmethod
def _get_results(self, lst_output : list):
"""
Get results of the different parts.
Parameters:
lst_output : list ; OUTPUT list with results
"""
pass
def extra_measure(self) -> ExtraMeasureNsight:
"""
Return ExtraMeasureNsight part of the execution.
Returns:
reference to ExtraMeasureNsight part of the execution
"""
return self._extra_measure
def _add_result_part_to_lst(self, dict_values : dict, dict_desc : dict,
lst_to_add):
"""
Add results of execution part (FrontEnd, BackEnd...) to list indicated by argument.
Args:
dict_values : dict ; diccionary with name_metric/event-value elements of the part to
add to 'lst_to_add'
dict_desc : dict ; diccionary with name_metric/event-description elements of the
part to add to 'lst_to_add'
lst_output : list ; list where to add all elements
Raises:
MetricNoDefined ; raised in case you have added an metric that is
not supported or does not exist in the NVIDIA analysis tool
"""
# metrics_events_not_average : list = LevelExecutionParameters.C_METRICS_AND_EVENTS_NOT_AVERAGE_COMPUTED.split(",")
name_max_length : int = len("Metric Name")
metric_unit_title : str = "Metric Unit"
unit_max_length : int = len(metric_unit_title)
metric_value_title : str = "Metric Value"
for key_value,key_unit in zip(dict_values, dict_desc):
if len(key_value) > name_max_length:
name_max_length = len(key_value)
if len(key_value[0]) > unit_max_length:
unit_max_length = key_value[0]
metric_name_length : int = name_max_length + 10
metric_unit_length : int = unit_max_length + 10
metric_value_length : int = len(metric_value_title)
description : str = ("\t\t\t%-*s" % (metric_name_length , "Metric Name"))
description += ("%-*s" % (metric_unit_length , metric_unit_title))
description += ("%-*s" % (metric_value_length, metric_value_title))
line_length : int = len(description)
metrics_events_not_average : list = LevelExecutionParameters.C_METRICS_AND_EVENTS_NOT_AVERAGE_COMPUTED.split(",")
total_value : float = 0.0
value_str : str
total_value_str : str = ""
metric_name : str
metric_unit : str
i : int = 0
for key_value, key_unit in zip(dict_values, dict_desc):
total_value = round(self._get_total_value_of_list(dict_values[key_value], False),
LevelExecutionParameters.C_MAX_NUM_RESULTS_DECIMALS)
if total_value.is_integer():
total_value = int(total_value)
value_metric_str = str(total_value)
metric_name = key_value
metric_unit = dict_desc.get(key_unit)
if not metric_unit:
metric_unit = "-"
elif metric_unit == "%":
# In NVIDIA scan tool, the percentages in each kernel are calculated on the total of
# each kernel and not on the total of the application
if key_value in metrics_events_not_average:
raise ComputedAsAverageError(key_unit)
value_str = "\t\t\t%-*s" % (metric_name_length, metric_name)
value_str += "%-*s" % (metric_unit_length, metric_unit)
value_str += "%-*s" % (len(metric_value_title), value_metric_str)
if len(value_str) > line_length:
line_length = len(value_str)
if i != len(dict_values) - 1:
value_str += "\n"
total_value_str += value_str
i += 1
spaces_length : int = len("\t\t\t")
line_str : str = "\t\t\t" + f'{"-" * (line_length - spaces_length)}'
lst_to_add.append("\n" + line_str)
lst_to_add.append(description)
lst_to_add.append(line_str)
lst_to_add.append(total_value_str)
lst_to_add.append(line_str + "\n")
def _percentage_time_kernel(self, kernel_number : int) -> float:
"""
Get time percentage in each Kernel.
Each kernel measured is an index of dictionaries used by this program.
Args:
kernel_number : int ; number of kernel
"""
value_lst : list = self._extra_measure.get_metric_value(LevelExecutionParameters.C_CYCLES_ELAPSED_METRIC_NAME_NSIGHT)
if value_lst is None:
raise ElapsedCyclesError
value_str : str
total_value : float = 0.0
for value_str in value_lst:
total_value += locale.atof(value_str)
return (locale.atof(value_lst[kernel_number])/total_value)*100.0
|
"""Utility for plotting test results."""
import argparse
from collections import defaultdict
import csv
import numpy as np
import os.path
import sys
import matplotlib.pyplot as plt
_TESTCASE, _DATASET, _PARAM, _CONDITION, _ROUND, _TIME = 'test', 'dataset', 'param', 'condition', 'round', 'time'
def _stats(iterable):
"""Returns mean, std for the iterable, excluding the min and max values."""
l = sorted(iterable)[1:-1] # drop min and max values
return [np.mean(l), np.std(l)]
def main():
"""Main routine."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('file', help='Test results spreadsheet to be plotted')
parser.add_argument('--save', default=False, action='store_true', help='Save plots to files named "test_case.format" in working directory')
parser.add_argument('--show', default=False, action='store_true', help='Show each plot as it is generated')
parser.add_argument('--format', default='png', help='Format to use when saving plot')
parser.add_argument('--dpi', type=int, default=300, help='DPI when saving plot')
parser.add_argument('--yunits', choices=['s', 'ms'], default='s', help='Units for time y-axis')
args = parser.parse_args()
# factor for y-units
yunits_factor = {'s': 1, 'ms': 1000}
# line format per condition
fmt = {'control': '--', 'optimized': ''}
# color palette (colors 3 and 4 never appear together in the current plots)
colors = defaultdict(lambda: 'xkcd:teal blue', {1: 'xkcd:medium purple', 2: 'xkcd:orange'})
# read results from spreadsheet
results = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
with open(os.path.expanduser(args.file)) as csvfile:
csvreader = csv.DictReader(csvfile)
for row in csvreader:
results[row[_TESTCASE]][(row[_CONDITION], int(row[_PARAM]))][int(row[_DATASET])].append(yunits_factor[args.yunits]*float(row[_TIME]))
# compute mean, std
for result in results.values():
for condition in result.values():
for key in condition:
condition[key] = _stats(condition[key])
# plot figures
for test_case in results:
fig, ax = plt.subplots()
for condition_param in results[test_case]:
datasets, stats = zip(*results[test_case][condition_param].items())
means, errs = zip(*stats)
condition, param = condition_param
ax.errorbar(datasets, means, yerr=errs, label=f'{condition}, n={param}', fmt=fmt[condition],
color=colors[param], ecolor='xkcd:red', lw=1.5, capsize=3, capthick=1.5)
ax.set_xticks(datasets)
ax.set_xscale('log')
ax.set(xlabel='# rows in dataset', ylabel=f'time ({args.yunits})', title=f'{test_case.replace('_', ' ').title()}')
ax.legend()
if args.save:
plt.savefig(f'{test_case}.{args.format}', dpi=args.dpi, format=args.format)
if args.show:
plt.show()
return 0
if __name__ == '__main__':
sys.exit(main())
| """Utility for plotting test results."""
import argparse
from collections import defaultdict
import csv
import numpy as np
import os.path
import sys
import matplotlib.pyplot as plt
_TESTCASE, _DATASET, _PARAM, _CONDITION, _ROUND, _TIME = 'test', 'dataset', 'param', 'condition', 'round', 'time'
def _stats(iterable):
"""Returns mean, std for the iterable, excluding the min and max values."""
l = sorted(iterable)[1:-1] # drop min and max values
return [np.mean(l), np.std(l)]
def main():
"""Main routine."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('file', help='Test results spreadsheet to be plotted')
parser.add_argument('--save', default=False, action='store_true', help='Save plots to files named "test_case.format" in working directory')
parser.add_argument('--show', default=False, action='store_true', help='Show each plot as it is generated')
parser.add_argument('--format', default='png', help='Format to use when saving plot')
parser.add_argument('--dpi', type=int, default=300, help='DPI when saving plot')
parser.add_argument('--yunits', choices=['s', 'ms'], default='s', help='Units for time y-axis')
args = parser.parse_args()
# factor for y-units
yunits_factor = {'s': 1, 'ms': 1000}
# line format per condition
fmt = {'control': '--', 'optimized': ''}
# color palette (colors 3 and 4 never appear together in the current plots)
colors = defaultdict(lambda: 'xkcd:teal blue', {1: 'xkcd:medium purple', 2: 'xkcd:orange'})
# read results from spreadsheet
results = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
with open(os.path.expanduser(args.file)) as csvfile:
csvreader = csv.DictReader(csvfile)
for row in csvreader:
results[row[_TESTCASE]][(row[_CONDITION], int(row[_PARAM]))][int(row[_DATASET])].append(yunits_factor[args.yunits]*float(row[_TIME]))
# compute mean, std
for result in results.values():
for condition in result.values():
for key in condition:
condition[key] = _stats(condition[key])
# plot figures
for test_case in results:
fig, ax = plt.subplots()
for condition_param in results[test_case]:
datasets, stats = zip(*results[test_case][condition_param].items())
means, errs = zip(*stats)
condition, param = condition_param
ax.errorbar(datasets, means, yerr=errs, label=f'{condition}, n={param}', fmt=fmt[condition],
color=colors[param], ecolor='xkcd:red', lw=1.5, capsize=3, capthick=1.5)
ax.set_xticks(datasets)
ax.set_xscale('log')
ax.set(xlabel='# rows in dataset', ylabel=f'time ({args.yunits})', title=f'{test_case.replace("_", " ").title()}')
ax.legend()
if args.save:
plt.savefig(f'{test_case}.{args.format}', dpi=args.dpi, format=args.format)
if args.show:
plt.show()
return 0
if __name__ == '__main__':
sys.exit(main())
|
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import numpy as np
import pytest
import habitat
from habitat.utils.test_utils import sample_non_stop_action
CFG_TEST = "configs/test/habitat_all_sensors_test.yaml"
TELEPORT_POSITION = [-3.2890449, 0.15067159, 11.124366]
TELEPORT_ROTATION = [0.92035, 0, -0.39109465, 0]
def test_task_actions():
config = habitat.get_config(config_paths=CFG_TEST)
config.defrost()
config.TASK.POSSIBLE_ACTIONS = config.TASK.POSSIBLE_ACTIONS + ["TELEPORT"]
config.freeze()
env = habitat.Env(config=config)
env.reset()
env.step(
action={
"action": "TELEPORT",
"action_args": {
"position": TELEPORT_POSITION,
"rotation": TELEPORT_ROTATION,
},
}
)
agent_state = env.sim.get_agent_state()
assert np.allclose(
np.array(TELEPORT_POSITION, dtype=np.float32), agent_state.position
), "mismatch in position after teleport"
assert np.allclose(
np.array(TELEPORT_ROTATION, dtype=np.float32),
np.array([*agent_state.rotation.imag, agent_state.rotation.real]),
), "mismatch in rotation after teleport"
env.step("TURN_RIGHT")
env.close()
def test_task_actions_sampling_for_teleport():
config = habitat.get_config(config_paths=CFG_TEST)
config.defrost()
config.TASK.POSSIBLE_ACTIONS = config.TASK.POSSIBLE_ACTIONS + ["TELEPORT"]
config.freeze()
env = habitat.Env(config=config)
env.reset()
while not env.episode_over:
action = sample_non_stop_action(env.action_space)
habitat.logger.info(
f"Action : "
f"{action["action"]}, "
f"args: {action["action_args"]}."
)
env.step(action)
agent_state = env.sim.get_agent_state()
habitat.logger.info(agent_state)
env.close()
@pytest.mark.parametrize(
"config_file",
[
CFG_TEST,
"configs/tasks/pointnav.yaml",
"configs/test/habitat_mp3d_eqa_test.yaml",
],
)
def test_task_actions_sampling(config_file):
config = habitat.get_config(config_paths=config_file)
if not os.path.exists(
config.DATASET.DATA_PATH.format(split=config.DATASET.SPLIT)
):
pytest.skip(
f"Please download dataset to data folder "
f"{config.DATASET.DATA_PATH}."
)
env = habitat.Env(config=config)
env.reset()
while not env.episode_over:
action = sample_non_stop_action(env.action_space)
habitat.logger.info(
f"Action : "
f"{action["action"]}, "
f"args: {action["action_args"]}."
)
env.step(action)
agent_state = env.sim.get_agent_state()
habitat.logger.info(agent_state)
env.close()
| #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import numpy as np
import pytest
import habitat
from habitat.utils.test_utils import sample_non_stop_action
CFG_TEST = "configs/test/habitat_all_sensors_test.yaml"
TELEPORT_POSITION = [-3.2890449, 0.15067159, 11.124366]
TELEPORT_ROTATION = [0.92035, 0, -0.39109465, 0]
def test_task_actions():
config = habitat.get_config(config_paths=CFG_TEST)
config.defrost()
config.TASK.POSSIBLE_ACTIONS = config.TASK.POSSIBLE_ACTIONS + ["TELEPORT"]
config.freeze()
env = habitat.Env(config=config)
env.reset()
env.step(
action={
"action": "TELEPORT",
"action_args": {
"position": TELEPORT_POSITION,
"rotation": TELEPORT_ROTATION,
},
}
)
agent_state = env.sim.get_agent_state()
assert np.allclose(
np.array(TELEPORT_POSITION, dtype=np.float32), agent_state.position
), "mismatch in position after teleport"
assert np.allclose(
np.array(TELEPORT_ROTATION, dtype=np.float32),
np.array([*agent_state.rotation.imag, agent_state.rotation.real]),
), "mismatch in rotation after teleport"
env.step("TURN_RIGHT")
env.close()
def test_task_actions_sampling_for_teleport():
config = habitat.get_config(config_paths=CFG_TEST)
config.defrost()
config.TASK.POSSIBLE_ACTIONS = config.TASK.POSSIBLE_ACTIONS + ["TELEPORT"]
config.freeze()
env = habitat.Env(config=config)
env.reset()
while not env.episode_over:
action = sample_non_stop_action(env.action_space)
habitat.logger.info(
f"Action : "
f"{action['action']}, "
f"args: {action['action_args']}."
)
env.step(action)
agent_state = env.sim.get_agent_state()
habitat.logger.info(agent_state)
env.close()
@pytest.mark.parametrize(
"config_file",
[
CFG_TEST,
"configs/tasks/pointnav.yaml",
"configs/test/habitat_mp3d_eqa_test.yaml",
],
)
def test_task_actions_sampling(config_file):
config = habitat.get_config(config_paths=config_file)
if not os.path.exists(
config.DATASET.DATA_PATH.format(split=config.DATASET.SPLIT)
):
pytest.skip(
f"Please download dataset to data folder "
f"{config.DATASET.DATA_PATH}."
)
env = habitat.Env(config=config)
env.reset()
while not env.episode_over:
action = sample_non_stop_action(env.action_space)
habitat.logger.info(
f"Action : "
f"{action['action']}, "
f"args: {action['action_args']}."
)
env.step(action)
agent_state = env.sim.get_agent_state()
habitat.logger.info(agent_state)
env.close()
|
#!/usr/bin/evn python3
"""
Record Section plotting tool for seismic waveforms (observed and synthetic)
This is a refactor of Pysep's Python utility `plotw_rs`, a record section
plotting script. The intent of this script is to plot multiple time series'
based on source-receiver characteristics (i.e., src-rcv distance, backazimuth).
.. note:: Code History
Written by Carl Tape (11/21/2011) and Yun Wang (11/2011) in Matlab
Translated to Python by Nealy Sims (1/2021)
Upgraded by Aakash Gupta (9/2021)
Refactored by Bryant Chow (3/2022)
.. requires::
obspy >= 1.2 (expected to bring in numpy and matplotlib)
.. rubric:: Examples
1) Print the help message to see available options and flags
$ python record_section.py -h
2) From the command line: The following example code blocks work with pysep
to download data for a southern California event.
# cd path/to/pysep
$ python rungetwaveform.py event_input_mtuq2022 2 # 20200404015318920
a) Plot a record section for the socal event with default values
$ python record_section.py --pysep_path 20200404015318920
b) Plot high-passed data with 7 km/s move out (focused on direct arrivals),
show direct arrivals through to surface waves for all traces, thin lines
to accentuate high frequencies. Overwrite previous figure and split
figure onto multiple pages
$ python record_section.py --pysep_path 20200404015318920 \
--move_out 7 --min_period_s 1 --xlim_s 100 175 \
--linewidth .25 --max_traces_per_rs 60 --overwrite
c) Plot bandpassed data with 4 km/s move out (focused on surface waves),
horizontal components only (radial, transverse),
thicken up default linewidth and increase spacing between adjacent
seismograms
$ python record_section.py --pysep_path 20200404015318920 \
--components RT --move_out 4 --min_period_s 2 --max_period_s 50 \
--xlim_s 50 200 --y_axis_spacing 3 --linewidth 1 \
--amplitude_scale_factor 4 --overwrite
d) Plot bandpassed transverse component, sort by azimuth, scale by the
maximum amplitude of ALL traces shown on the figure.
Scale amplitudes by factor 2 for better visualization
and start azimuth plotting at 180* (as opposed to default 0*).
$ python record_section.py --pysep_path 20200404015318920 \
--sort_by azimuth --scale_by global_norm --components T \
--min_period_s 2 --max_period_s 30 --move_out 4 \
--amplitude_scale_factor 2 --azimuth_start_deg 180 \
--linewidth 1 --overwrite
e) Plot bandpassed vertical components sorted by absolute distance.
Reduce amplitudes by 1/4 (0.25). Set y label fontsize smaller than
default and at the max X value of the figure (far to the right)
$ python record_section.py --pysep_path 20200404015318920 \
--sort_by abs_distance_r --components Z --min_period_s 2 \
--max_period_s 50 --amplitude_scale_factor 0.25 \
--y_label_loc x_max --y_label_fontsize 7 --overwrite \
--linewidth 1
3) From the Python interpreter: this is an example code block that can be
written into a Python script or run from inside a Python interactive
environment. Code block assumes we have downloaded event data with Pysep
>>> import os
>>> from glob import glob
>>> from obspy import read
>>> from record_section import plotw_rs
>>> st = Stream()
>>> for fid in glob(os.path.join("20200404015318920", "*.?")):
>>> st += read(fid)
>>> plotw_rs(st=st, sort_by="distance_r")
"""
import os
import sys
import argparse
import textwrap
import numpy as np
import matplotlib.pyplot as plt
from glob import glob
from datetime import datetime
from matplotlib.ticker import MultipleLocator
from obspy import read, Stream
from obspy.geodetics import (kilometers2degrees, gps2dist_azimuth)
# Unicode degree symbol for plot text
DEG = u"\N{DEGREE SIGN}"
def myround(x, base=5, choice="near"):
"""
Round value x to nearest base, round 'up','down' or to 'near'est base
:type x: float
:param x: value to be rounded
:type base: int
:param base: nearest integer to be rounded to
:type choice: str
:param choice: method of rounding, 'up', 'down' or 'near'
:rtype roundout: int
:return: rounded value
"""
if choice == "near":
roundout = int(base * round(float(x)/base))
elif choice == "down":
roundout = int(base * np.floor(float(x)/base))
elif choice == "up":
roundout = int(base * np.ceil(float(x)/base))
return roundout
class Dict(dict):
"""Simple dictionary overload for nicer get/set attribute characteristics"""
def __setattr__(self, key, value):
self[key] = value
def __getattr__(self, key):
return self[key]
class RecordSection:
"""
Record section plotting tool which takes ObsPy streams and
1) preprocesses and filters waveforms,
2) sorts source-receiver pairs based on User input,
3) produces record section waveform figures.
"""
def __init__(self, pysep_path=None, st=None, st_syn=None, sort_by="default",
scale_by=None, time_shift_s=None, move_out=None,
min_period_s=None, max_period_s=None,
preprocess="st", max_traces_per_rs=None, integrate=0,
xlim_s=None, components="ZRTNE12", y_label_loc="default",
y_axis_spacing=1, amplitude_scale_factor=1,
azimuth_start_deg=0., distance_units="km",
geometric_spreading_factor=0.5, geometric_spreading_k_val=None,
figsize=(9, 11), show=True, save="./record_section.png",
overwrite=False, **kwargs):
"""
Set the default record section plotting parameters and enforce types.
Run some internal parameter derivation functions by manipulating input
data and parameters.
:type pysep_path: str
:param pysep_path: path to Pysep output, which is expected to contain
trace-wise SAC waveform files which will be read
:type st: obspy.core.stream.Stream
:param st: Stream objects containing observed time series to be plotted
on the record section. Can contain any number of traces
:type st_syn: obspy.core.stream.Stream
:param st_syn: Stream objects containing synthetic time series to be
plotted on the record section. Must be same length as `st`
:type sort_by: str
:param sort_by: How to sort the Y-axis of the record section, available:
- 'default': Don't sort, just iterate directly through Stream
- 'alphabetical': sort alphabetically A->Z. Components sorted
separately with parameter `components`
- 'azimuth': sort by source-receiver azimuth (deg) with constant
vertical spacing on the y-axis. Requires `azimuth_start_deg`
- 'backazimuth': sort by source-receiver backazimuth (deg) with
constant vertical spacing. Requires `azimuth_start_deg`
- 'distance': sort by source-receiver distance (km) with constant
vertical spacing. Requires `distance_units`
- 'abs_distance': absolute vertical spacing of waveforms defined by
source-receiver distance. Requires `distance_units`
- 'abs_azimuth': absolute vertical spacing of waveforms defined
by source-receiver azimuth (deg).
- 'abs_backazimuth': absolute vertical spacing of waveforms by
source-receiver backazimuth (deg).
- '*_r': Add a '_r' to any of the values about to REVERSE the sort,
e.g., 'alphabetical_r' sort will go Z->A
:type scale_by: list
:param scale_by: scale amplitude of waveforms by available:
- None: Not set, no amplitude scaling, waveforms shown raw
- 'normalize': scale each trace by the maximum amplitude,
i.e., > a /= max(abs(a)) # where 'a' is time series amplitudes
- 'global_norm': scale by the largest amplitude to be displayed on
the screen. Will not consider waveforms which have been
excluded on other basis (e.g., wrong component)
i.e., > st[i].max /= max([max(abs(tr.data)) for tr in st])
- 'geometric_spreading': TODO this is not implemented yet.
scale amplitudes globally by predicting the
expected geometric spreading amplitude reduction and correcting
for this factor. Requires `geometric_spreading_factor`, and
optional `geometric_spreading_k_val`
:type time_shift_s: float OR list of float
:param time_shift_s: apply static time shift to waveforms, two options:
1. float (e.g., -10.2), will shift ALL waveforms by
that number (i.e., -10.2 second time shift applied)
2. list (e.g., [5., -2., ... 11.2]), will apply individual time
shifts to EACH trace in the stream. The length of this list MUST
match the number of traces in your input stream.
:type amplitude_scale_factor: float OR list of float
:param amplitude_scale_factor: apply scale factor to all amplitudes.
Used as a dial to adjust amplitudes manually. Defaults to 1.
Two options:
1. float (e.g., 1.2), will multiply ALL waveforms by that number
2. list (e.g., [5., -2., ... 11.2]), will apply individual amplitude
scale to EACH trace in the stream. The length of this list MUST
match the number of traces in your input stream.
:type move_out: float
:param move_out: Optional. A velocity value that will be used to
calculate move out, which will time shift seismograms based on
their source receiver distance. This parameter will be ADDED
to time_shift_s (both float and list), if it is provided.
Should be in units of `distance_units`/s
:type min_period_s: float
:param min_period_s: minimum filter period in seconds
:type max_period_s: float
:param max_period_s: maximum filter period in seconds
:type preprocess: str
:param preprocess: choose which data to preprocess, options are:
- 'st': process waveforms in st (default)
- 'st_syn': process waveforms in st_syn. st still must be given
- 'both': process waveforms in both st and st_syn
- None: do not run preprocessing step (including filter)
:type max_traces_per_rs: int
:param max_traces_per_rs: maximum number of traces to show on a single
record section plot. Defaults to all traces in the Stream
:type xlim_s: list of float
:param xlim_s: [start, stop] in units of time, seconds, to set the
xlimits of the figure
:type components: str
:param components: a sequence of strings representing acceptable
components from the data. Also determines the order these are shown
EVEN when sorted by other variables. For example, components=='ZR'
would only display Z and R components, and Z components would be
should BEFORE R components for the SAME station.
:type integrate: int
:param integrate: apply integration `integrate` times on all traces.
acceptable values [-inf, inf], where positive values are integration
and negative values are differentiation
e.g., if integrate == 2, will integrate each trace twice.
or if integrate == -1, will differentiate once
or if integrate == 0, do nothing (default)
:type y_axis_spacing: float
:param y_axis_spacing: spacing between adjacent seismograms applied to
Y-axis on relative (not absolute) scales. Defaults to 1.
:type y_label_loc: str
:param y_label_loc: Location to place waveform labels on the y-axis
- 'default': auto choose the best location based on `sort_by`
- 'y_axis': Replace tick labels on the y-axis (left side of figure),
This won't work if using absolute sorting and will be over-
written by 'default'
- 'y_axis_right': Replace tick labels on the right side of the
y-axis. This option won't work with absolute sorting
- 'x_min': Place labels on top of the waveforms at the global min
x-value on the figure
- 'x_min': Place labels on top of the waveforms at the global max
x-value on the figure
- None: Don't plot any text labels
:type azimuth_start_deg: float
:param azimuth_start_deg: If sorting by azimuth, this defines the
azimuthal angle for the waveform at the top of the figure.
Set to 0 for default behavior
:type distance_units: str
:param distance_units: Y-axis units when sorting by epicentral distance
'km': kilometers on the sphere
'deg': degrees on the sphere
'km_utm': kilometers on flat plane, UTM coordinate system
:type geometric_spreading_factor: float
:param geometric_spreading_factor: geometrical spreading factor when
using the `scale_by` parameter. Defaults to 0.5 for surface waves.
Use values of 0.5 to 1.0 for regional surface waves
:type geometric_spreading_k_val: float
:param geometric_spreading_k_val: K value used to scale the geometric
spreading factor (TODO figure out what this actually is)
:type figsize: tuple of float
:param figsize: size the of the figure, passed into plt.subplots()
:type show: bool
:param show: show the figure as a graphical output
:type save: str
:param save: path to save output figure, will create the parent
directory if it doesn't exist. If None, will not save.
:type overwrite: bool
:param overwrite: if the path defined by `save` exists, will overwrite
the existing figure
:raises AssertionError: if any parameters are set incorrectly
"""
# Read files from path if provided
if pysep_path is not None and os.path.exists(pysep_path):
# Expected file format: 20200404015318920.CI.LRL..BH.r
fids = glob(os.path.join(pysep_path, "*.*.*.*.*.?"))
print(f"Reading {len(fids)} files from: {pysep_path}")
if fids:
# Overwrite stream, so reading takes precedence
st = Stream()
for fid in fids:
st += read(fid)
assert(st), \
"Stream object not found, please check inputs `st` and `pysep_path"
# User defined parameters, do some type-setting
self.st = st.copy()
try:
self.st_syn = st_syn.copy()
except AttributeError:
self.st_syn = None
# Y-Axis sorting parameters
self.sort_by = sort_by.lower()
self.y_axis_spacing = float(y_axis_spacing)
self.azimuth_start_deg = float(azimuth_start_deg)
self.components = str(components)
# Amplitude scaling parameters
self.scale_by = scale_by
self.amplitude_scale_factor = amplitude_scale_factor
self.geometric_spreading_factor = float(geometric_spreading_factor)
self.geometric_spreading_k_val = geometric_spreading_k_val
# Time shift parameters
self.move_out = move_out
self.time_shift_s = time_shift_s
# Filtering parameters
self.min_period_s = min_period_s
self.max_period_s = max_period_s
self.preprocess = preprocess
self.max_traces_per_rs = max_traces_per_rs
self.integrate = int(integrate)
# Plotting parameters
self.xlim_s = xlim_s
self.distance_units = distance_units.lower()
self.y_label_loc = y_label_loc
self.figsize = figsize
self.show = bool(show)
self.save = save
self.overwrite = bool(overwrite)
self.kwargs = Dict(kwargs)
# Run checks to ensure that all the parameters are set properly
# And get some new, initial parameters that are required for other
# 'get' functions
self.check_parameters()
self.stats = self.get_srcrcv_stats()
self.distances, self.azimuths, self.backazimuths = \
self.get_srcrcv_dist_az_baz()
# Internally used parameters that will be filled out by other functions
self.f = None
self.ax = None
self.idx = []
self.station_ids = []
self.max_amplitudes = []
self.amplitude_scaling = []
self.y_axis = []
self.xlim = [] # unit: samples
self.sorted_idx = []
def check_parameters(self):
"""
Check that parameters are set properly and in line with how they
are expected by the program
.. note::
Not using assertions here because we want all incorrect parameters
to be evaluated together and displayed at once, that way the user
doesn't have to run this function multiple times to figure out how
to set their parameters correctly
:raises AssertionError: If any parameters are not set as expected by
plotw_rs functionality
"""
print("checking parameter acceptability")
# Used to keep track of which parameters failed and in what way
err = Dict()
# Check to make sure there is data
if not bool(self.st):
err.st = f"stream has {len(self.st)} traces, no data"
# Check that stream has SAC headers if we want to sort by dist or (b)az.
# Pysep should have created these
if self.sort_by != "default" and \
any(_ in self.sort_by for _ in ["azimuth", "distance"]):
_idx = []
for i, tr in enumerate(self.st):
if not hasattr(tr.stats, "sac"):
_idx.append(i)
if _idx:
err.st = (f"{len(_idx)} traces have no SAC header, plotw_rs "
f"expects SAC headers for sorting. Trace indexes "
f"are: {_idx}")
if self.st_syn is not None:
if len(self.st) != len(self.st_syn):
err.st_syn = f"length must match `st` (which is {len(self.st)})"
# Check the `sort_by` sorting parameter options
acceptable_sort_by = ["default", "azimuth", "backazimuth",
"distance", "alphabetical", "abs_azimuth",
"abs_distance"]
# Allow reverse sorts
acceptable_sort_by += [f"{_}_r" for _ in acceptable_sort_by]
if self.sort_by not in acceptable_sort_by:
err.sort_by = f"must be in {acceptable_sort_by}"
if "azimuth" in self.sort_by:
if not (0 <= self.azimuth_start_deg <= 360):
err.azimuth_start_deg = f"0 < azi < 360"
acceptable_distance_units = ["km", "km_utm", "deg"]
if ("distance" in self.sort_by) and \
(self.distance_units not in acceptable_distance_units):
err.azimuth_start_deg = \
f"must be in {acceptable_distance_units}"
if self.scale_by is not None:
acceptable_scale_by = ["normalize", "global_norm",
"geometric_spreading"]
if self.scale_by not in acceptable_scale_by:
err.scale_by = f"must be in {acceptable_scale_by}"
if self.time_shift_s is not None:
acceptable_time_shift_s = [int, float, list]
if type(self.time_shift_s) not in acceptable_time_shift_s:
err.time_shift_s = f"must be in {acceptable_time_shift_s}"
if isinstance(self.time_shift_s, list) and \
len(self.time_shift_s) != len(self.st):
err.time_shift_s = f"must be list of length {len(self.st)}"
# Defaults to float value of 1
acceptable_scale_factor = [int, float, list]
if type(self.amplitude_scale_factor) not in acceptable_scale_factor:
err.amplitude_scale_factor = f"must be in {acceptable_scale_factor}"
if isinstance(self.amplitude_scale_factor, list) and \
len(self.amplitude_scale_factor) != len(self.st):
err.amplitude_scale_factor = f"must be list length {len(self.st)}"
if self.min_period_s is not None and self.max_period_s is not None:
if self.min_period_s >= self.max_period_s:
err.min_period_s = "must be less than `max_period_s`"
if self.preprocess is not None:
acceptable_preprocess = ["both", "st"]
if self.preprocess not in acceptable_preprocess:
err.preprocess = f"must be in {acceptable_preprocess}"
# Overwrite the max traces per record section, enforce type int
if self.max_traces_per_rs is None:
self.max_traces_per_rs = int(len(self.st))
else:
self.max_traces_per_rs = int(self.max_traces_per_rs)
if self.xlim_s is not None:
if len(self.xlim_s) != 2:
err.xlim_s = f"must be of length 2, [start, stop]"
elif self.xlim_s[0] > self.xlim_s[1]:
err.xlim_s = f"start time must be less than stop time"
acceptable_y_label_loc = ["default", "y_axis", "y_axis_right", "x_min",
"x_max", None]
if self.y_label_loc not in acceptable_y_label_loc:
err.y_label_loc = f"must be in {acceptable_y_label_loc}"
if "abs" in self.sort_by and "y_axis" in self.sort_by:
err.y_label_loc = (f"absolute sorting means 'y_axis' label loc is"
f"not available")
if len(self.figsize) != 2:
err.figsize = "must be tuple defining (horizontal, vertical) extent"
if os.path.exists(self.save) and not self.overwrite:
err.save = (f"path {self.save} already exists. Use '--overwrite' "
f"flag to save over existing figures.")
_dirname = os.path.abspath(os.path.dirname(self.save))
if not os.path.exists(_dirname):
print(f"creating output directory {_dirname}")
os.makedirs(_dirname)
if err:
out = "ERROR - Parameter errors, please make following changes:\n"
out += "\n".join([f"\t{key}: {val}" for key, val in err.items()])
print(out)
sys.exit(-1)
def get_skip_idx(self):
"""
Get a list of any traces that don't adhere to user-defined boundaries
such as dist, az, baz, id, or component matches. Don't actually remove
the traces from the stream but rather just collect indices we can use
to skip when plotting.
TODO add distance, azi and backazi skip criteria
:rtype: np.array
:return: returns an indexing list which can be used to skip over
traces that don't adhere to certain criteria
"""
skip_idx = []
for idx in self.idx:
tr = self.st[idx]
# Component-wise removal
if tr.stats.component not in self.components:
skip_idx.append(idx)
# !!! Add more here
print(f"criteria check will remove "
f"{len(skip_idx)}/{len(self.st)} traces")
return np.array(skip_idx)
def get_parameters(self):
"""
Calculate parameters in a specific order and based on the user-defined
information.
.. note::
The order of function calls here is important! Some of the 'get'
functions require the results of other 'get' functions.
Calculated Parameters
::
np.array idx:
a linear indexing of all the traces in the stream
np.array station_ids:
an ordered list of station ids, used to get station names
that match the index defined in `idx`
np.array max_amplitudes:
abs max amplitudes of each trace, used for normalization
np.array amplitude_scaling:
An array to scale amplitudes based on user choices
np.array time_shift_s:
An array to time shift time series based on user choices
np.array y_axis:
Y-Axis values based on sorting algorithm, used for plotting
np.array distances:
source-receiver distances in `distance_units` units
np.array azimuths:
source-receiver azimuths in degrees
np.array backazimuths:
source-receiver backazimuths in degrees
np.array sorted_idx:
sorted indexing on all the traces of the stream based on the
chosen sorting algorithm
"""
# Extract basic information from the Stream
self.idx = np.arange(0, len(self.st), 1)
self.station_ids = np.array([tr.get_id() for tr in self.st])
self.time_shift_s = self.get_time_shifts() # !!! OVERWRITES user input
self.xlim = self.get_xlims()
# Max amplitudes should be RELATIVE to what were showing (e.g., if
# zoomed in on the P-wave, max amplitude should NOT be the surface wave)
for tr, xlim in zip(self.st, self.xlim):
start, stop = xlim
self.max_amplitudes.append(max(abs(tr.data[start:stop])))
self.max_amplitudes = np.array(self.max_amplitudes)
# Figure out which indices we'll be plotting
sorted_idx = self.get_sorted_idx()
skip_idx = self.get_skip_idx()
# Remove skip indexes from sorted index to get the final ordered list
self.sorted_idx = np.array([_ for _ in sorted_idx if _ not in skip_idx])
# Figure out how to manipulate each of the traces in the Stream
self.y_axis = self.get_y_axis_positions()
self.amplitude_scaling = self.get_amplitude_scaling()
def get_xlims(self):
"""
The x-limits of each trace depend on the overall time shift (either
static or applied through move out), as well as the sampling rate of
each trace (which can vary). Retrieve an index-dependent list of
x-limits which can be used to truncate the time series during plotting.
.. note::
Requires that get_time_shifts() has already been run
:rtype: np.array
:return: an array of tuples defining the start and stop indices for EACH
trace to be used during plotting. Already includes time shift
information so xlim can be applied DIRECTLY to the time shifted data
"""
xlim = []
if self.xlim_s is None:
# None's will index the entire trace
xlim = np.array([(None, None) for _ in range(len(self.st))])
else:
# Looping to allow for delta varying among traces,
# AND apply the time shift so that indices can be used directly in
# the plotting function
for tr, tshift in zip(self.st, self.time_shift_s):
start, stop = [int(_/tr.stats.delta) for _ in self.xlim_s]
sshift = int(tshift / tr.stats.delta) # unit: samples
xlim.append((start-sshift, stop-sshift))
xlim = np.array(xlim)
return xlim
def get_srcrcv_stats(self):
"""
Get source receiver information such as min max values, and
count-related numbers (e.g., num stations) to be used mainly for print
statements and text information
Stats Arguments
::
np.array event_names:
unique event names taken from the SAC header
int nevents:
number of unique events in the stream
np.array unique_sta_ids:
unique station codes taken from trace stats
int nstation_ids:
number of unique station codes
np.array network_codes:
unique network codes taken from station ids
int nnetwork:
number of unique network codes
np.array station_codes:
unique station codes taken from station ids
int nstation:
number of unique station codes
np.array location_codes:
unique location codes taken from station ids
int nlocation:
number of unique location codes
np.array channel_codes:
unique channel codes taken from station ids
int nchannel:
number of unique channel codes
bool reverse_sort:
determine if the user wants to reverse their sort, they do this
by appending '_r' to the end of the `sort_by` argument
"""
print("getting source-receiver stats")
def _unique(list_):
"""return a unique numpy array derived from a list"""
return np.unique(np.array(list_, dtype=str))
stats = Dict()
stats.event_names = _unique([tr.stats.sac.kevnm for tr in self.st])
stats.nevents = len(stats.event_names)
stats.unique_sta_ids = _unique([tr.get_id() for tr in self.st])
stats.longest_id = max([len(_) for _ in stats.unique_sta_ids])
stats.nstation_ids = len(stats.unique_sta_ids)
# Get unique network, station, location and channel codes. Also numbers
for name in ["network", "station", "location", "channel", "component"]:
stats[f"{name}_codes"] = _unique(
[getattr(tr.stats, name) for tr in self.st]
)
stats[f"n{name}"] = len(stats[f"{name}_codes"])
# We use `not` in `reverse_sort` to make the top of the y-axis the
# starting point, which seems more intuitive for record sections, but
# is opposite the behavior when you increment from 0
stats.reverse_sort = not bool("_r" in self.sort_by)
# Initiate empty lists for _plot_trace() to fill with min and max data
# values which can be used for global plotting parameters like xlims
stats.xmin, stats.xmax, stats.ymin, stats.ymax = [], [], [], []
return stats
def get_time_shifts(self):
"""
Very simple function which allows float inputs for time shifts and
ensures that time shifts are always per-trace arrays
Applies the move out by calculating a time shift using src-rcv distance
:rtype: np.array
:return: a stream-lengthed array of time shifts that can be applied
per trace
"""
# No user input means time shifts will be 0, so nothing happens
time_shift_arr = np.zeros(len(self.st))
if self.time_shift_s is not None:
# User inputs a static time shift
if isinstance(self.time_shift_s, (int, float)):
time_shift_arr += self.time_shift_s
# User input an array which should have already been checked for len
else:
time_shift_arr = self.time_shift_s
time_shift_arr = np.array(time_shift_arr)
# Further change the time shift if we have move out input
if self.move_out:
print(f"apply {self.move_out} {self.distance_units}/s move out")
move_out_arr = self.distances / self.move_out
time_shift_arr -= move_out_arr
return time_shift_arr
def get_srcrcv_dist_az_baz(self):
"""
Convenience function to wrap _get_srcrcv_dist_az_baz_trace into a loop
over the whole stream and return lists of distances, azimuths, and
backazimuths
:rtype distances: np.array
:return distances: source-receiver distances in user-defined units in
the original order of Stream
:rtype azimuths: np.array
:return azimuths: source-receiver azimuths (deg) in the original
order of Stream
:rtype backazimuths: np.array
:return backazimuths: source-receiver azimuths (deg) in the original
order of Stream
"""
print("calculating source-receiver distance and (back)azimuths")
distances, azimuths, backazimuths = [], [], []
for tr in self.st:
gcd, az, baz = self._get_srcrcv_dist_az_baz_trace(tr=tr)
distances.append(gcd)
azimuths.append(az)
backazimuths.append(baz)
distances = np.array(distances)
azimuths = np.array(azimuths)
backazimuths = np.array(backazimuths)
return distances, azimuths, backazimuths
def _get_srcrcv_dist_az_baz_trace(self, tr=None, idx=0):
"""
Check the source-receiver characteristics such as src-rcv distance,
azimuth, backazimuth for a given trace.
.. note::
This function ASSUMES that SAC headers have been written to the
traces. Otherwise we will need more complicated ways to get
event lat and lon
:type tr: obspy.core.trace.Trace
:param tr: trace to get srcrcv information for. If None, will use `idx`
:type idx: int
:param idx: if `tr`==None, user can provide index of self.st (Stream)
defaults to index 0
:rtype gcdist: float
:return gcdist: great circle distance in units specified by
`distance_units`, can be 'km' or 'deg'
:rtype az: float
:return az: azimuth (degrees) between source and receiver
:rtype baz: float
:return baz: azimuth (degrees) between source and receiver
"""
# Default to the first trace in the Stream
if tr is None:
tr = self.st[int(idx)]
try:
dist = tr.stats.sac.dist # units: km
az = tr.stats.sac.az # units: deg
baz = tr.stats.sac.baz # units: deg
except AttributeError:
# If for whatever reason SAC headers dont contain this info already
# Use ObsPy to get great circle distance, azimuth and backazimuth
dist, az, baz = gps2dist_azimuth(lat1=tr.stats.sac.evla,
lon1=tr.stats.sac.evlo,
lat2=tr.stats.sac.stla,
lon2=tr.stats.sac.stlo)
dist *= 1E-3 # units: m -> km
# Ensure that 0 <= (b)az <= 360
az = az % 360
baz = baz % 360
# Make sure distance is in the correct units, default units 'km'
if self.distance_units == "deg":
dist = kilometers2degrees(dist) # units: km -> deg
elif self.distance_units == "km_utm":
# Overwrite `dist`, could probably skip that calc above but
# leaving for now as I don't think this option will be used heavily.
dist_deg = np.sqrt(
((tr.stats.sac.stlo - tr.stats.sac.evlo) ** 2) /
((tr.stats.sac.stla - tr.stats.sac.evla) ** 2)
)
dist = kilometers2degrees(dist_deg) # units: km
return dist, az, baz
def get_amplitude_scaling(self):
"""
Scale the amplitudes of all the waveforms by producing a Stream
dependent scale factor based on user choice. It is expected that the
output array will be DIVIDED by the data arrays:
i.e., st[i].data /= self.amplitude_scaling[i]
.. note::
Needs to be run AFTER preprocessing because filtering etc. will
affect the final amplitudes of the waveforms
:rtype: np.array
:return: an array corresponding to the Stream indexes which provides
a per-trace scaling coefficient
"""
print(f"determining amplitude scaling with: {self.scale_by}")
# Don't scale by anything
if self.scale_by is None:
amp_scaling = np.ones(len(self.st))
# Scale by the max amplitude of each trace
elif self.scale_by == "normalize":
amp_scaling = self.max_amplitudes
# When using absolute distance scale, scale waveforms to minmax dist
if "abs" in self.sort_by:
if "distance" in self.sort_by:
print("scaling amplitudes for absolute distance")
scale = np.mean(self.distances) / 10
elif "backazimuth" in self.sort_by:
print("scaling amplitudes for absolute backazimuth")
scale = self.backazimuths.max() - self.backazimuths.min()
scale /= 100
elif "azimuth" in self.sort_by:
print("scaling amplitudes for absolute azimuth")
scale = self.azimuths.max() - self.azimuths.min()
scale /= 50
# Divide to make waveforms larger
amp_scaling /= scale
# Scale by the largest amplitude shown
elif self.scale_by == "global_norm":
global_max = self.max_amplitudes[self.sorted_idx].max()
amp_scaling = np.ones(len(self.st)) * global_max
# Scale by the theoretical geometrical spreading factor
elif self.scale_by == "geometric_spreading":
amp_scaling = self._calculate_geometric_spreading()
# Apply manual scale factor if provided, default value is 1 so nothing
# Divide because the amplitude scale divides the data array, which means
# `amplitude_scale_factor` will be MULTIPLIED by the data array
amp_scaling /= self.amplitude_scale_factor
return amp_scaling
def _calculate_geometric_spreading(self):
"""
Stations with larger source-receiver distances will have their amplitude
scaled by a larger value.
For information on geometric spreading, see Stein and Wysession,
Section 4.3.4, Eq 20 (for Rayleigh waves, geometrical spreading
factor = 0.5). For our purposes, this will fold the attenuation factor
into the same single factor that accounts for geometric spreading.
.. note::
This does not take into account the variation in amplitude.
TODO Plot geometric spreading with best-fitting curve
:type max_amplitudes: list
:param max_amplitudes: list of maximum amplitudes for each trace in the
stream. IF not given, will be calculated on the fly. Optional incase
this has been calculated already and you want to save time
:rtype: list
:return: scale factor per trace in the stream based on theoretical
geometrical spreading factor. This is meant to be MULTIPLIED by the
data arrays
"""
raise NotImplementedError("This function is currently work in progress")
print("calculating geometrical spreading for amplitude normalization")
# Create a sinusoidal function based on distances in degrees
sin_del = np.sin(np.array(self.dist) / (180 / np.pi))
# !!! TODO Stein and Wysession and figure out vector names
if self.geometric_spreading_k_val is not None:
k_vector = self.max_amplitudes * \
(sin_del ** self.geometric_spreading_factor)
k_val = np.median(k_vector)
else:
k_val = self.geometric_spreading_k_val
w_vector = k_val / (sin_del ** self.geometric_spreading_factor)
return w_vector
def get_sorted_idx(self):
"""
Sort the source-receiver pairs by the chosen parameters. Except for in
`default` sorting, always maintains component ordering defined by the
user, i.e., for the same station, components will be ordered by the
`component` parameter.
:rtype: np.array
:return: returns an indexing list which is sorted based on the user
defined `sort_by` argument.
"""
print(f"determining sort order with parameter: {self.sort_by}")
# Retain input ordering but run sorting to allow reversing
if "default" in self.sort_by:
sorted_idx = sorted(self.idx, reverse=self.stats.reverse_sort)
# Sort alphabetically BUT allow component sorting
elif "alphabetical" in self.sort_by:
sorted_idx = self._sort_by_alphabetical()
# Sort by dist, az or baz
else:
components = self._get_component_order()
# Azimuthal sorts are allowed to start at a value other than 0
# Backazimuth needs to come first because 'azimuth' can return both
if "backazimuth" in self.sort_by:
sort_list = (self.backazimuths - self.azimuth_start_deg) % 360
elif "azimuth" in self.sort_by:
sort_list = (self.azimuths - self.azimuth_start_deg) % 360
elif "distance" in self.sort_by:
sort_list = self.distances
# Sort by the values, AND the components (e.g., Z->R->T or whatever)
_, _, sorted_idx = \
zip(*sorted(zip(sort_list, components, self.idx),
reverse=self.stats.reverse_sort)
)
sorted_idx = np.array(list(sorted_idx))
return sorted_idx
def _sort_by_alphabetical(self):
"""
Sort by full station name in order. That is, network is sorted, then
within network, station is sorted, and so on. Components are sorted
last and NOT in alphabetical order. They are ordered based on the
user-input `components` parameter.
:rtype: np.array
:return: indexing of networks and stations sorted alphabetically
"""
networks = [_.split(".")[0] for _ in self.station_ids]
stations = [_.split(".")[1] for _ in self.station_ids]
locations = [_.split(".")[2] for _ in self.station_ids]
components = self._get_component_order()
zipped = zip(networks, stations, locations, components, self.idx)
arr_out = np.array(
list(zip(*sorted(zipped, reverse=self.stats.reverse_sort)))
)
return arr_out[-1].astype(int)
def _get_component_order(self):
"""
When we are sorting, we want components to be sorted by the
preferred order (i.e, ZRT, Z index is 0, T is 2), which means the
components have to be reordered to adhere to the sorting algorithm.
ALSO we need to ensure that we honor component order even if
everything else is being sorted reverse alphabetically so the
components entry needs to be the opposite of stats.reverse_sort
:rtype: list
:return: components converted to integer values which can be used for
sorting algorithms.
"""
channels = [_.split(".")[3] for _ in self.station_ids]
# ASSUMING component is the last entry in the channel, SEED convention
components = [_[-1] for _ in channels]
if self.stats.reverse_sort:
comp_list = self.components
else:
comp_list = self.components[::-1]
# Can't list comp here incase `comp_list` does NOT contain one of the
# available components, which will throw a ValueError. Use a random
# number to catch these.
numbered_components = []
for comp in components:
try:
numbered_components.append(comp_list.index(comp))
except ValueError:
numbered_components.append(-999)
return numbered_components
def get_y_axis_positions(self):
"""
Determine how seismograms are vertically separated on the Y-Axis when
plotting. Allows for constant separation, or absolute separation based
on distance or (back)azimuth separation.
:rtype: np.array
:return: an array of actual y-axis positions that can be passed directly
to plt.plot() (or similar)
"""
print(f"determining y-axis positioning for sort: {self.sort_by}")
# Default weights provides constant `y_axis_spacing` between seismos
if self.sort_by == "default" or "abs_" not in self.sort_by:
y_range = np.arange(0, len(self.sorted_idx), 1)
y_axis = self.y_axis_spacing * y_range
# Absolute y-axis (i.e., absolute distance or (back)azimuth) will just
# plot the actual distance or azimuth value
else:
if "backazimuth" in self.sort_by:
y_axis = self.backazimuths
elif "azimuth" in self.sort_by:
y_axis = self.azimuths
elif "distance" in self.sort_by:
y_axis = self.distances
return y_axis
def process_st(self):
"""
Preprocess the Stream with optional filtering in place.
.. note::
Data in memory will be irretrievably altered by running preprocess.
TODO Add feature to allow list-like periods to individually filter
seismograms. At the moment we just apply a blanket filter.
"""
if self.preprocess is None:
print("no preprocessing applied")
return
elif self.preprocess == "st":
print(f"preprocessing {len(self.st)} `st` waveforms")
preprocess_list = [self.st]
elif self.preprocess == "st_syn":
print(f"preprocessing {len(self.st_syn)} `st_syn` waveforms")
preprocess_list = [self.st_syn]
elif self.preprocess == "both":
print(f"preprocessing {len(self.st) + len(self.st_syn)} "
f"`st` and `st_syn` waveforms")
preprocess_list = [self.st, self.st_syn]
for st in preprocess_list:
# Fill any data gaps with mean of the data, do it on a trace by
# trace basis to get individual mean values
for tr in st:
tr.trim(starttime=tr.stats.starttime, endtime=tr.stats.endtime,
pad=True, fill_value=tr.data.mean())
st.detrend("demean")
st.taper(max_percentage=0.05, type="cosine")
# Allow multiple filter options based on user input
# Min period but no max period == low-pass
if self.max_period_s is not None and self.min_period_s is None:
print(f"apply lowpass filter w/ cutoff {1/self.max_period_s}")
st.filter("lowpass", freq=1/self.max_period_s, zerophase=True)
# Max period but no min period == high-pass
elif self.min_period_s is not None and self.max_period_s is None:
print(f"apply highpass filter w/ cutoff {1/self.min_period_s}")
st.filter("highpass", freq=1/self.min_period_s, zerophase=True)
# Both min and max period == band-pass
elif self.min_period_s is not None and \
self.max_period_s is not None:
print(f"applying bandpass filter w/ "
f"[{1/self.max_period_s}, {self.min_period_s}]")
st.filter("bandpass", freqmin=1/self.max_period_s,
freqmax=1/self.min_period_s, zerophase=True)
else:
print("no filtering applied")
# Integrate and differentiate N number of times specified by user
st.detrend("simple")
if self.integrate != 0:
if self.integrate < 0:
func = "differentiate"
elif self.integrate > 0:
func = "integrate"
for i in range(np.abs(self.integrate)):
print("{func} all waveform data")
getattr(st, func)()
def plot(self, subset=None, page_num=None, **kwargs):
"""
Plot record sections based on all the available information
:type subset: list of int
:param subset: subset of `sorted_idx` if there are too many waveforms to
plot on one page (set by `max_traces_per_rs`). e.g., to get the
first 10 entries, subset=[0,10]
:type page_num: int
:param page_num: If multiple pages are required due to exceeding
`max_traces_per_rs`, page_num will make adjustments to the figure
name and title to differentiate different pages of the same record
section
"""
if subset is None:
start, stop = 0, None # None will allow full list traversal
nwav = len(self.sorted_idx)
else:
start, stop = subset
nwav = stop - start
print(f"plotting record section for {nwav} waveforms")
# Do a text output of station information so the user can check
# that the plot is doing things correctly
print("PLOTTING LINE CHECK STARTING FROM BOTTOM")
print("\nIDX\tY\t\tID\tDIST\tAZ\tBAZ\tTSHIFT\tYABSMAX")
self.f, self.ax = plt.subplots(figsize=self.figsize)
# Allow choosing observed or synthetic data, defaults to observed
# Allow different waveform looks based on observed vs. synthetic
for choice in ["st", "st_syn"]:
if getattr(self, choice) is None:
continue
# Main plotting call. Indexes should already be sorted
for y_idx, idx in enumerate(self.sorted_idx[start:stop]):
# Absolute scaling requires plotting actual dist or az values
# Relative scaling just requires a linear index to stack seismos
if "abs_" in self.sort_by:
y_index = idx
else:
y_index = y_idx + start
self._plot_trace(idx=idx, y_index=y_index, choice=choice,
**kwargs)
# Change the aesthetic look of the figure, should be run before other
# set functions as they may overwrite what is done here
self._set_plot_aesthetic()
# Partition the figure by user-specified azimuth bins
if self.sort_by and "azimuth" in self.sort_by:
self._plot_azimuth_bins()
# Finalize the figure accoutrements
self._plot_title(nwav=nwav, page_num=page_num)
self._plot_axes(start=start, stop=stop)
if self.save:
# Allow appending page numbers to figure names,
# e.g., default.png -> default_01.png
if page_num:
fid, ext = os.path.splitext(self.save)
save_fid = f"{fid}_{page_num:0>2}{ext}"
else:
save_fid = self.save
print(f"\nsaving figure to {save_fid}")
plt.savefig(save_fid)
if self.show:
plt.show()
def _plot_trace(self, idx, y_index, choice="st"):
"""
Plot a single trace on the record section, with amplitude scaling,
time shifts, etc. Observed waveforms are black, synthetics are red.
:type idx: int
:param idx: index of the trace to plot and all trace-ordered values like
amplitude scaling and time shifts
:type y_index: int
:param y_index: numerical order which this trace was plotted, as each
trace is plotted on top of the previous one. y_index should be
iterated linearly in the loop that calls this function.
:type choice: str
:param choice: choice of 'st' or 'st_syn' depending on whether you want
to plot the observed or synthetic waveforms
"""
linewidth = self.kwargs.get("linewidth", .25)
# Used to differentiate the two types of streams for plotting diffs
choices = ["st", "st_syn"]
assert (choice in choices)
c = choices.index(choice)
tr = getattr(self, choice)[idx] # i.e., tr = self.st[idx]
# Plot actual data on with amplitude scaling, time shift, and y-offset
tshift = self.time_shift_s[idx]
# These are still the entire waveform
x = tr.times() + tshift
y = tr.data / self.amplitude_scaling[idx] + self.y_axis[y_index]
# Truncate waveforms to get figure scaling correct.
start, stop = self.xlim[idx]
x = x[start:stop]
y = y[start:stop]
self.ax.plot(x, y, c=["k", "r"][c], linewidth=linewidth, zorder=10)
# Sanity check print station information to check against plot
print(f"{idx}"
f"\t{int(self.y_axis[y_index])}"
f"\t{tr.get_id():<6}"
f"\t{self.distances[idx]:6.2f}"
f"\t{self.azimuths[idx]:6.2f}"
f"\t{self.backazimuths[idx]:6.2f}"
f"\t{self.time_shift_s[idx]:4.2f}"
f"\t{self.max_amplitudes[idx]:.2E}")
# Retain some stats for global plot args
self.stats.xmin.append(x.min())
self.stats.xmax.append(x.max())
self.stats.ymin.append(y.min())
self.stats.ymax.append(y.max())
def _plot_azimuth_bins(self):
"""
If plotting by azimuth, create visual bin separators so the user has
a visual understanding of radiation patterns etc.
"""
azimuth_binsize = self.kwargs.get("azimuth_binsize", 45)
# Look of the azimuth bin lines
c = self.kwargs.get("azimuth_bin_c", "r")
lw = self.kwargs.get("azimuth_bin_lw", .75)
ls = self.kwargs.get("azimuth_bin_ls", "-")
z = self.kwargs.get("azimuth_bin_zorder", 5)
azimuth_bins = np.arange(self.azimuth_start_deg,
self.azimuth_start_deg + 360,
azimuth_binsize)
# Make sure that the bins go from 0 <= azimuth_bins <= 360
azimuth_bins = azimuth_bins % 360
# In an absolute plot, the y values are simply the azimuth bins
if "abs" in self.sort_by:
y_vals = azimuth_bins
s_vals = [f"{azbin}{DEG}" for azbin in azimuth_bins]
# In a relative plot, the y values need to be found between seismograms
else:
s_vals, y_vals = [], []
# Brute force determine where these azimuth bins would fit into the
# actual plotted azimuths, draw a line between adjacent seismograms
# i.e., iterating and looking if the bin value fits between
# two adjacent azimuth values
for azbin in azimuth_bins:
# Edge case for 0 deg azimuth bin since azimuth wraps on 0
# Look for the top minimum azimuth value, place line above that
if azbin == 0:
dy = abs(self.y_axis[1] - self.y_axis[0])
azis = self.azimuths[self.sorted_idx]
i = max(np.where(azis == azis.min())[0])
y_vals.append(self.y_axis[i] + dy/2)
else:
for i, idx in enumerate(self.sorted_idx[1:]):
j = i + 1
idx_minus_one = self.sorted_idx[i]
azi_low = self.azimuths[idx]
azi_high = self.azimuths[idx_minus_one]
# Break if bin is in between azi values for two seismos
if azi_low <= azbin <= azi_high:
break
else:
continue
# Mean gives the space in between two adjacent seismograms
y_vals.append(np.mean([self.y_axis[i], self.y_axis[j]]))
s_vals.append(f"{azbin}{DEG}")
for y, (s_val, y_val) in enumerate(zip(s_vals, y_vals)):
# Dealing with the case where two bins occupy the same space,
# only plot the first one that occurs
if y_val == y_vals[y-1]:
continue
plt.axhline(y=y_val, c=c, linewidth=lw, linestyle=ls, zorder=z)
plt.text(x=max(self.stats.xmax), y=y_val, s=s_val, c=c, ha="right")
def _plot_axes(self, start=0, stop=None):
"""
Contains the logic in how to handle the x- and y-axis labels, ticks etc.
Logic options for how to plot the y-axis:
- Relative: Relative plotting means the yticklabels will get replaced
by station information. This can either be on the right or left
side but will be attached to the actual axis
- Absolute: Absolute plotting means the y-axis actual represents
something (e.g., distance, azimuth). That means labels can not
replace the y-ticks and they have to be placed within the figure
.. note::
Relative plotting can also place labels OFF the y-axis, at which
point the y-axis is turned off because it contains no usable
information
:type start: int
:param start: optional starting index for creating text labels
:type stop: int
:param stop: optional stop index for creating text labels
"""
# Sort out how the y-axis will be labeled with station information and
# dist/azimuth if we're doing absolute sorting
if "abs_" in self.sort_by:
self._set_y_axis_absolute()
if self.y_label_loc is not None:
# By default, place absolute sorted labels at xmin
if self.y_label_loc == "default":
loc = "x_min"
else:
loc = self.y_label_loc
self._set_y_axis_text_labels(start=start, stop=stop, loc=loc)
elif self.y_label_loc is not None:
# By default, relative plotting shows labels on the right side
if self.y_label_loc == "default":
loc = "y_axis"
else:
loc = self.y_label_loc
self._set_y_axis_text_labels(start=start, stop=stop, loc=loc)
print(f"placing station labels on y-axis at: {loc}")
# User requests that we turn off y-axis
if self.y_label_loc is None:
print(f"user requests turning off y-axis w/ `y_label_loc`== None")
self.ax.get_yaxis().set_visible(False)
# OR EDGE CASE: Relative plotting but labels are not placed on the
# y-axis, turn off the y-axis cause it doesn't mean anything anymore
elif self.y_label_loc not in ["default", "y_axis", "y_axis_right"] and \
"abs" not in self.sort_by:
print("turning off y-axis as it contains no information")
self.ax.get_yaxis().set_visible(False)
# Reverse the y-axis if we are doing absolute y-axis and reversing
if "abs_" in self.sort_by and "_r" in self.sort_by:
print("user requests inverting y-axis with absolute reverse sort")
self.ax.invert_yaxis()
# X-axis label is different if we time shift
if self.time_shift_s.sum() == 0:
plt.xlabel("Time [s]")
else:
plt.xlabel("Relative Time [s]")
# Allow user defined x-axis limits
if self.xlim_s is None:
self.ax.set_xlim([min(self.stats.xmin), max(self.stats.xmax)])
else:
self.ax.set_xlim(self.xlim_s)
plt.tight_layout()
def _set_y_axis_absolute(self):
"""
If 'abs_' in sort_by, then the Y-axis should be shown in absolute scale.
That means we need to format the text labels, add some labelling etc.
"""
# Reset tick label size to be larger to match absolute x-axis size
ytick_fontsize = self.kwargs.get("ytick_fontsize", 12)
self.ax.tick_params(axis="y", labelsize=ytick_fontsize)
if "distance" in self.sort_by:
if "km" in self.distance_units:
ytick_minor = self.kwargs.get("ytick_minor", 25)
ytick_major = self.kwargs.get("ytick_major", 100)
elif "deg" in self.distance_units:
ytick_minor = self.kwargs.get("ytick_minor", 0.25)
ytick_major = self.kwargs.get("ytick_major", 1.0)
ylabel = f"Distance [{self.distance_units}]"
elif "azimuth" in self.sort_by:
ytick_minor = self.kwargs.get("ytick_minor", 45)
ytick_major = self.kwargs.get("ytick_major", 90)
ylabel = f"Azimuth [{DEG}]"
# Set ytick label major and minor which is either dist or az
self.ax.yaxis.set_major_locator(MultipleLocator(ytick_major))
self.ax.yaxis.set_minor_locator(MultipleLocator(ytick_minor))
self.ax.set_ylabel(ylabel)
def _set_y_axis_text_labels(self, start=0, stop=-1, loc="y_axis"):
"""
Plot a text label next to each trace describing the station,
azimuth and source-receiver distance. We need to do this all at once
because we have to replace all ticks and tick labels at once.
.. note::
if using the 'subset' option in plot, need to also tell the y-axis
plotter that we are only plotting a subset of data by using the
`start` and `stop` parameters
:type start: int
:param start: starting index for plotting, default to start 0
:type stop: int
:param stop: stop index for plotting, default to end -1
:type loc: str
:param loc: location to place the y_axis text labels, available:
- y_axis: Place labels along the y-axis (left side of the figure)
Will replace the actual y-tick labels so not applicable for
absolute sorting which requries the y-axis labels
- y_axis_right: same as `y_axis` but set on the right side of figure
- x_min: Place labels on the waveforms at the minimum x value
- x_max: Place labels on the waveforms at the maximum x value
"""
c = self.kwargs.get("y_label_c", "k")
fontsize = self.kwargs.get("y_label_fontsize", 10)
y_tick_labels = []
for idx in self.sorted_idx[start:stop]:
str_id = self.station_ids[idx]
if self.sort_by is not None and "backazimuth" in self.sort_by:
# This is named `str_az` but it's actually backazimuths
str_az = f"{self.backazimuths[idx]:6.2f}{DEG}"
else:
str_az = f"{self.azimuths[idx]:6.2f}{DEG}"
# Allow degree distance to use the unicode * symbol
if self.distance_units == "deg":
du = DEG
else:
du = self.distance_units
str_dist = f"{self.distances[idx]:5.2f}{du}"
# Looks something like: NN.SSS.LL.CC|30*|250.03km
label = \
f"{str_id:>{self.stats.longest_id}}|{str_az:>8}|{str_dist:>8}"
# Add time shift if we have shifted at all
if self.time_shift_s[idx] != 0:
label += f"|{self.time_shift_s[idx]:.2f}s"
y_tick_labels.append(label)
if "y_axis" in loc:
# For relative plotting (not abs_), replace y_tick labels with
# station information
self.ax.set_yticks(self.y_axis[start:stop])
self.ax.set_yticklabels(y_tick_labels)
else:
# Trying to figure out where the min or max X value is on the plot
if loc == "x_min":
ha = "left"
func = min
x_val = func(self.stats.xmin)
elif loc == "x_max":
ha = "right"
func = max
x_val = func(self.stats.xmax)
if self.xlim_s is not None:
x_val = func([func(self.xlim_s), x_val])
# Plotting y-axis labels for absolute scales
if len(self.y_axis) == len(self.st):
for idx, s in zip(self.sorted_idx[start:stop], y_tick_labels):
plt.text(x=x_val, y=self.y_axis[idx], s=s, ha=ha, c=c,
fontsize=fontsize)
# Plotting y-axis labels for relative scales
elif len(self.y_axis) == len(y_tick_labels):
for y, s in zip(self.y_axis, y_tick_labels):
plt.text(x=x_val, y=y, s=s, ha=ha, c=c, fontsize=fontsize)
if loc == "y_axis_right":
self.ax.yaxis.tick_right()
self.ax.yaxis.set_label_position("right")
def _plot_title(self, nwav=None, page_num=None):
"""
Create the title of the plot based on event and station information
Allow dynamic creation of title based on user input parameters
TODO Can we make this two-column to save space?
:type nwav: int
:param nwav: if using subset, the title needs to know how many waveforms
it's showing on the page. self.plot() should tell it
:type page_num: int
:param page_num: same as nwav, we need to know what page number were on
"""
# Defines the number of waveforms plotted on a single page, allowing
# for subsets per page
if nwav is None:
nwav = len(self.sorted_idx)
# Allow appending page numbers to title
title_top = "RECORD SECTION"
if page_num:
title_top += f" PAGE {page_num:0>2}"
# The y-label will show baz or az depending on user choice, distinguish
if self.sort_by is not None and "backazimuth" in self.sort_by:
az_str = "BAZ"
else:
az_str = "AZ"
# Get the unique components that have been plotted, only
cmp = "".join(np.unique([self.st[i].stats.component
for i in self.sorted_idx]))
# Y_FMT will include time shift IF there are time shifts
y_fmt = f"Y_FMT: NET.STA.LOC.CHA|{az_str}|DIST"
if self.time_shift_s.sum() != 0:
y_fmt += "|TSHIFT"
title = "\n".join([
title_top,
f"{"/" * len(title_top*2)}",
f"ORIGINTIME: {min([tr.stats.starttime for tr in self.st])}",
f"{y_fmt}",
f"NWAV: {nwav}; NEVT: {self.stats.nevents}; "
f"NSTA: {self.stats.nstation}; COMP: {cmp}",
f"SORT_BY: {self.sort_by}; "
f"SCALE_BY: {self.scale_by} * {self.amplitude_scale_factor}",
f"FILT: [{self.min_period_s}, {self.max_period_s}]s; "
f"MOVE_OUT: {self.move_out or 0}{self.distance_units}/s",
])
self.ax.set_title(title)
def _set_plot_aesthetic(self):
"""
Give a nice look to the output figure by creating thick borders on the
axis, adjusting fontsize etc. All plot aesthetics should be placed here
so it's easiest to find.
.. note::
This was copy-pasted from Pyatoa.visuals.insp_plot.default_axes()
"""
ytick_fontsize = self.kwargs.get("ytick_fontsize", 8)
xtick_fontsize = self.kwargs.get("xtick_fontsize", 12)
tick_linewidth = self.kwargs.get("tick_linewidth", 1.5)
tick_length = self.kwargs.get("tick_length", 5)
tick_direction = self.kwargs.get("tick_direction", "in")
label_fontsize = self.kwargs.get("label_fontsize", 10)
axis_linewidth = self.kwargs.get("axis_linewidth", 2.)
title_fontsize = self.kwargs.get("title_fontsize", 10)
xtick_minor = self.kwargs.get("xtick_minor", 25)
xtick_major = self.kwargs.get("xtick_major", 100)
spine_zorder = self.kwargs.get("spine_zorder", 8)
# Re-set font sizes for labels already created
self.ax.title.set_fontsize(title_fontsize)
self.ax.tick_params(axis="both", which="both", width=tick_linewidth,
direction=tick_direction, length=tick_length)
self.ax.tick_params(axis="x", labelsize=xtick_fontsize)
self.ax.tick_params(axis="y", labelsize=ytick_fontsize)
self.ax.xaxis.label.set_size(label_fontsize)
# Thicken up the bounding axis lines
for axis in ["top", "bottom", "left", "right"]:
self.ax.spines[axis].set_linewidth(axis_linewidth)
# Set spines above azimuth bins
for spine in self.ax.spines.values():
spine.set_zorder(spine_zorder)
# Set xtick label major and minor which is assumed to be a time series
self.ax.xaxis.set_major_locator(MultipleLocator(xtick_major))
self.ax.xaxis.set_minor_locator(MultipleLocator(xtick_minor))
plt.grid(visible=True, which="major", axis="x", alpha=0.5, linewidth=1)
plt.grid(visible=True, which="minor", axis="x", alpha=0.2, linewidth=.5)
def plotw_rs(*args, **kwargs):
"""
Main call function. Run the record section plotting functions in order.
Contains the logic for breaking up figure into multiple pages.
"""
_start = datetime.now()
print(f"STARTING RECORD SECTION PLOTTER")
rs = RecordSection(*args, **kwargs)
rs.process_st()
rs.get_parameters()
# Simple case where all waveforms will fit on one page
if len(rs.sorted_idx) <= rs.max_traces_per_rs:
rs.plot()
# More complicated case where we need to split onto multiple pages
else:
for i, start in enumerate(np.arange(0, len(rs.st),
rs.max_traces_per_rs)):
stop = start + rs.max_traces_per_rs
# Case where the num waveforms is less than max_traces_per_rs
if stop < rs.max_traces_per_rs:
stop = len(rs.st)
rs.plot(subset=[start, stop], page_num=i+1)
_end = datetime.now()
print(f"FINISHED RECORD SECTION (t={_end - _start}s)")
def parse_args():
"""
Parse command line arguments to set record section parameters dynamically
This arg parser provides a simplified interface for working with plotw_rs
BUT it limits the flexibility of the code because things like long lists
are prohibitively verbose and not included in the arguments.
Kwargs can be passed in in the same format thanks to:
https://stackoverflow.com/questions/37367331/is-it-possible-to-use-\
argparse-to-capture-an-arbitrary-set-of-optional-arguments
.. note::
Not all parameters are set here, some are left as default values
Also some parameters are set different than the class defaults, so that
when the user runs record_section.py without arguments, they get a
reasonable result
.. note::
Do NOT use the command line if you want to exploit the expanded
capabilities of the record section plotter, rather script it or call
from an interactive environment.
"""
parser = argparse.ArgumentParser(
description="Input basic plotw_rs params",
formatter_class=argparse.RawTextHelpFormatter,
)
parser.add_argument("--pysep_path", default="./", type=str, nargs="?",
help="path to Pysep output, which is expected to "
"contain trace-wise SAC waveform files which will "
"be read")
parser.add_argument("--sort_by", default="distance", type=str, nargs="?",
help=textwrap.dedent("""
How to sort the Y-axis of the record section
- None: Not set, don't sort, just iterate directly through Stream
- 'alphabetical': sort alphabetically
- 'azimuth': sort by source-receiver azimuth (deg) with constant
vertical spacing
- 'backazimuth': sort by source-receiver backazimuth (deg) with
constant vertical spacing. Requires `azimuth_start_deg`
- 'distance': sort by source-receiver distance (km) with constant
vertical spacing. Requires `azimuth_start_deg` AND
`distance_units`
- 'abs_distance': absolute vertical spacing of waveforms defined by
source-receiver distance (km). Requires `distance_units`
- 'abs_azimuth': absolute vertical spacing of waveforms defined
by source-receiver azimuth (deg). Requires
`azimuth_start_deg`
- 'abs_backazimuth': absolute vertical spacing of waveforms by
source-receiver backazimuth (deg).
- '*_r': Add a '_r' to any of the values about to REVERSE the sort,
e.g., alphabetical_r sort will go Z->A"
""")
)
parser.add_argument("--scale_by", default="normalize", type=str, nargs="?",
help=textwrap.dedent("""
How to sort the Y-axis of the record section
- None: Not set, no amplitude scaling, waveforms shown raw
- 'normalize': scale each trace by the maximum amplitude,
i.e., > a /= max(abs(a)) # where 'a' is time series amplitudes
- 'global_norm': scale by the largest amplitude to be displayed on
the screen. Will not consider waveforms which have been
excluded on other basis (e.g., wrong component)
- 'geometric_spreading': scale amplitudes globally by predicting the
expected geometric spreading amplitude reduction and correcting
for this factor. Requires `geometric_spreading_factor`, optional
`geometric_spreading_k_val`
""")
)
parser.add_argument("--time_shift_s", default=None, type=float, nargs="?",
help="Set a constant time shift in unit: seconds")
parser.add_argument("--move_out", default=None, type=float, nargs="?",
help="Set a constant velocity-based move out in units:"
"`distance_units`/s")
parser.add_argument("--min_period_s", default=None, type=float, nargs="?",
help="Minimum filter period in unit seconds.")
parser.add_argument("--max_period_s", default=None, type=float, nargs="?",
help="Maximum filter period in unit seconds.")
parser.add_argument("--max_traces_per_rs", default=None, nargs="?",
help="Max waveforms to show on one page. If the number "
"of waveforms to show exceeds this value, "
"multiple pages will be saved")
parser.add_argument("--integrate", default=0, type=int, nargs="?",
help="Integrate (positive values) or differentiate "
"(negative values) `integrate` times. e.g., -2 "
"will differentiate all waveforms twice.")
parser.add_argument("--xlim_s", default=None, type=int, nargs="+",
help="Min and max x limits in units seconds. Input as "
"a list, e.g., --xlim_s 10 200 ...")
parser.add_argument("--components", default="ZRTNE12", type=str, nargs="?",
help="Ordered component list specifying 1) which "
"components will be shown, and in what order. "
"e.g., 'ZR' will show only Z and R components "
"with Z sorted above R.")
parser.add_argument("--y_label_loc", default="default", type=str, nargs="?",
help="Station information label location on the y-axis")
parser.add_argument("--y_axis_spacing", default=1, type=float, nargs="?",
help="For relative sorting, the y-axis spacing between "
"adjacent seismograms. If waveforms are "
"normalized then a default value of 1 is usually "
"normalized then a default value of 1 is usually "
"fine")
parser.add_argument("--amplitude_scale_factor", default=1, type=float,
nargs="?",
help="A user dial allowing waveform amplitudes to be"
"scaled by an arbitrary float value")
parser.add_argument("--azimuth_start_deg", default=0, type=float,
nargs="?",
help="When sorting by azimuth, choose the default "
"starting value, with azimuth 0 <= az <= 360")
parser.add_argument("--distance_units", default="km", type=str,
nargs="?", help="Set units when sorting by distance")
parser.add_argument("--save", default="./record_section.png", type=str,
nargs="?",
help="Path to save the resulting record section fig")
parser.add_argument("--overwrite", default=False, action="store_true",
help="overwrite existing figure if path exists")
# Keyword arguments can be passed directly to the argparser in the same
# format as the above kwargs (e.g., --linewidth 2), but they will not have
# help messages or type checking
parsed, unknown = parser.parse_known_args()
for arg in unknown:
if arg.startswith(("-", "--")):
parser.add_argument(arg.split("=")[0])
return parser.parse_args()
if __name__ == "__main__":
plotw_rs(**vars(parse_args()))
| #!/usr/bin/evn python3
"""
Record Section plotting tool for seismic waveforms (observed and synthetic)
This is a refactor of Pysep's Python utility `plotw_rs`, a record section
plotting script. The intent of this script is to plot multiple time series'
based on source-receiver characteristics (i.e., src-rcv distance, backazimuth).
.. note:: Code History
Written by Carl Tape (11/21/2011) and Yun Wang (11/2011) in Matlab
Translated to Python by Nealy Sims (1/2021)
Upgraded by Aakash Gupta (9/2021)
Refactored by Bryant Chow (3/2022)
.. requires::
obspy >= 1.2 (expected to bring in numpy and matplotlib)
.. rubric:: Examples
1) Print the help message to see available options and flags
$ python record_section.py -h
2) From the command line: The following example code blocks work with pysep
to download data for a southern California event.
# cd path/to/pysep
$ python rungetwaveform.py event_input_mtuq2022 2 # 20200404015318920
a) Plot a record section for the socal event with default values
$ python record_section.py --pysep_path 20200404015318920
b) Plot high-passed data with 7 km/s move out (focused on direct arrivals),
show direct arrivals through to surface waves for all traces, thin lines
to accentuate high frequencies. Overwrite previous figure and split
figure onto multiple pages
$ python record_section.py --pysep_path 20200404015318920 \
--move_out 7 --min_period_s 1 --xlim_s 100 175 \
--linewidth .25 --max_traces_per_rs 60 --overwrite
c) Plot bandpassed data with 4 km/s move out (focused on surface waves),
horizontal components only (radial, transverse),
thicken up default linewidth and increase spacing between adjacent
seismograms
$ python record_section.py --pysep_path 20200404015318920 \
--components RT --move_out 4 --min_period_s 2 --max_period_s 50 \
--xlim_s 50 200 --y_axis_spacing 3 --linewidth 1 \
--amplitude_scale_factor 4 --overwrite
d) Plot bandpassed transverse component, sort by azimuth, scale by the
maximum amplitude of ALL traces shown on the figure.
Scale amplitudes by factor 2 for better visualization
and start azimuth plotting at 180* (as opposed to default 0*).
$ python record_section.py --pysep_path 20200404015318920 \
--sort_by azimuth --scale_by global_norm --components T \
--min_period_s 2 --max_period_s 30 --move_out 4 \
--amplitude_scale_factor 2 --azimuth_start_deg 180 \
--linewidth 1 --overwrite
e) Plot bandpassed vertical components sorted by absolute distance.
Reduce amplitudes by 1/4 (0.25). Set y label fontsize smaller than
default and at the max X value of the figure (far to the right)
$ python record_section.py --pysep_path 20200404015318920 \
--sort_by abs_distance_r --components Z --min_period_s 2 \
--max_period_s 50 --amplitude_scale_factor 0.25 \
--y_label_loc x_max --y_label_fontsize 7 --overwrite \
--linewidth 1
3) From the Python interpreter: this is an example code block that can be
written into a Python script or run from inside a Python interactive
environment. Code block assumes we have downloaded event data with Pysep
>>> import os
>>> from glob import glob
>>> from obspy import read
>>> from record_section import plotw_rs
>>> st = Stream()
>>> for fid in glob(os.path.join("20200404015318920", "*.?")):
>>> st += read(fid)
>>> plotw_rs(st=st, sort_by="distance_r")
"""
import os
import sys
import argparse
import textwrap
import numpy as np
import matplotlib.pyplot as plt
from glob import glob
from datetime import datetime
from matplotlib.ticker import MultipleLocator
from obspy import read, Stream
from obspy.geodetics import (kilometers2degrees, gps2dist_azimuth)
# Unicode degree symbol for plot text
DEG = u"\N{DEGREE SIGN}"
def myround(x, base=5, choice="near"):
"""
Round value x to nearest base, round 'up','down' or to 'near'est base
:type x: float
:param x: value to be rounded
:type base: int
:param base: nearest integer to be rounded to
:type choice: str
:param choice: method of rounding, 'up', 'down' or 'near'
:rtype roundout: int
:return: rounded value
"""
if choice == "near":
roundout = int(base * round(float(x)/base))
elif choice == "down":
roundout = int(base * np.floor(float(x)/base))
elif choice == "up":
roundout = int(base * np.ceil(float(x)/base))
return roundout
class Dict(dict):
"""Simple dictionary overload for nicer get/set attribute characteristics"""
def __setattr__(self, key, value):
self[key] = value
def __getattr__(self, key):
return self[key]
class RecordSection:
"""
Record section plotting tool which takes ObsPy streams and
1) preprocesses and filters waveforms,
2) sorts source-receiver pairs based on User input,
3) produces record section waveform figures.
"""
def __init__(self, pysep_path=None, st=None, st_syn=None, sort_by="default",
scale_by=None, time_shift_s=None, move_out=None,
min_period_s=None, max_period_s=None,
preprocess="st", max_traces_per_rs=None, integrate=0,
xlim_s=None, components="ZRTNE12", y_label_loc="default",
y_axis_spacing=1, amplitude_scale_factor=1,
azimuth_start_deg=0., distance_units="km",
geometric_spreading_factor=0.5, geometric_spreading_k_val=None,
figsize=(9, 11), show=True, save="./record_section.png",
overwrite=False, **kwargs):
"""
Set the default record section plotting parameters and enforce types.
Run some internal parameter derivation functions by manipulating input
data and parameters.
:type pysep_path: str
:param pysep_path: path to Pysep output, which is expected to contain
trace-wise SAC waveform files which will be read
:type st: obspy.core.stream.Stream
:param st: Stream objects containing observed time series to be plotted
on the record section. Can contain any number of traces
:type st_syn: obspy.core.stream.Stream
:param st_syn: Stream objects containing synthetic time series to be
plotted on the record section. Must be same length as `st`
:type sort_by: str
:param sort_by: How to sort the Y-axis of the record section, available:
- 'default': Don't sort, just iterate directly through Stream
- 'alphabetical': sort alphabetically A->Z. Components sorted
separately with parameter `components`
- 'azimuth': sort by source-receiver azimuth (deg) with constant
vertical spacing on the y-axis. Requires `azimuth_start_deg`
- 'backazimuth': sort by source-receiver backazimuth (deg) with
constant vertical spacing. Requires `azimuth_start_deg`
- 'distance': sort by source-receiver distance (km) with constant
vertical spacing. Requires `distance_units`
- 'abs_distance': absolute vertical spacing of waveforms defined by
source-receiver distance. Requires `distance_units`
- 'abs_azimuth': absolute vertical spacing of waveforms defined
by source-receiver azimuth (deg).
- 'abs_backazimuth': absolute vertical spacing of waveforms by
source-receiver backazimuth (deg).
- '*_r': Add a '_r' to any of the values about to REVERSE the sort,
e.g., 'alphabetical_r' sort will go Z->A
:type scale_by: list
:param scale_by: scale amplitude of waveforms by available:
- None: Not set, no amplitude scaling, waveforms shown raw
- 'normalize': scale each trace by the maximum amplitude,
i.e., > a /= max(abs(a)) # where 'a' is time series amplitudes
- 'global_norm': scale by the largest amplitude to be displayed on
the screen. Will not consider waveforms which have been
excluded on other basis (e.g., wrong component)
i.e., > st[i].max /= max([max(abs(tr.data)) for tr in st])
- 'geometric_spreading': TODO this is not implemented yet.
scale amplitudes globally by predicting the
expected geometric spreading amplitude reduction and correcting
for this factor. Requires `geometric_spreading_factor`, and
optional `geometric_spreading_k_val`
:type time_shift_s: float OR list of float
:param time_shift_s: apply static time shift to waveforms, two options:
1. float (e.g., -10.2), will shift ALL waveforms by
that number (i.e., -10.2 second time shift applied)
2. list (e.g., [5., -2., ... 11.2]), will apply individual time
shifts to EACH trace in the stream. The length of this list MUST
match the number of traces in your input stream.
:type amplitude_scale_factor: float OR list of float
:param amplitude_scale_factor: apply scale factor to all amplitudes.
Used as a dial to adjust amplitudes manually. Defaults to 1.
Two options:
1. float (e.g., 1.2), will multiply ALL waveforms by that number
2. list (e.g., [5., -2., ... 11.2]), will apply individual amplitude
scale to EACH trace in the stream. The length of this list MUST
match the number of traces in your input stream.
:type move_out: float
:param move_out: Optional. A velocity value that will be used to
calculate move out, which will time shift seismograms based on
their source receiver distance. This parameter will be ADDED
to time_shift_s (both float and list), if it is provided.
Should be in units of `distance_units`/s
:type min_period_s: float
:param min_period_s: minimum filter period in seconds
:type max_period_s: float
:param max_period_s: maximum filter period in seconds
:type preprocess: str
:param preprocess: choose which data to preprocess, options are:
- 'st': process waveforms in st (default)
- 'st_syn': process waveforms in st_syn. st still must be given
- 'both': process waveforms in both st and st_syn
- None: do not run preprocessing step (including filter)
:type max_traces_per_rs: int
:param max_traces_per_rs: maximum number of traces to show on a single
record section plot. Defaults to all traces in the Stream
:type xlim_s: list of float
:param xlim_s: [start, stop] in units of time, seconds, to set the
xlimits of the figure
:type components: str
:param components: a sequence of strings representing acceptable
components from the data. Also determines the order these are shown
EVEN when sorted by other variables. For example, components=='ZR'
would only display Z and R components, and Z components would be
should BEFORE R components for the SAME station.
:type integrate: int
:param integrate: apply integration `integrate` times on all traces.
acceptable values [-inf, inf], where positive values are integration
and negative values are differentiation
e.g., if integrate == 2, will integrate each trace twice.
or if integrate == -1, will differentiate once
or if integrate == 0, do nothing (default)
:type y_axis_spacing: float
:param y_axis_spacing: spacing between adjacent seismograms applied to
Y-axis on relative (not absolute) scales. Defaults to 1.
:type y_label_loc: str
:param y_label_loc: Location to place waveform labels on the y-axis
- 'default': auto choose the best location based on `sort_by`
- 'y_axis': Replace tick labels on the y-axis (left side of figure),
This won't work if using absolute sorting and will be over-
written by 'default'
- 'y_axis_right': Replace tick labels on the right side of the
y-axis. This option won't work with absolute sorting
- 'x_min': Place labels on top of the waveforms at the global min
x-value on the figure
- 'x_min': Place labels on top of the waveforms at the global max
x-value on the figure
- None: Don't plot any text labels
:type azimuth_start_deg: float
:param azimuth_start_deg: If sorting by azimuth, this defines the
azimuthal angle for the waveform at the top of the figure.
Set to 0 for default behavior
:type distance_units: str
:param distance_units: Y-axis units when sorting by epicentral distance
'km': kilometers on the sphere
'deg': degrees on the sphere
'km_utm': kilometers on flat plane, UTM coordinate system
:type geometric_spreading_factor: float
:param geometric_spreading_factor: geometrical spreading factor when
using the `scale_by` parameter. Defaults to 0.5 for surface waves.
Use values of 0.5 to 1.0 for regional surface waves
:type geometric_spreading_k_val: float
:param geometric_spreading_k_val: K value used to scale the geometric
spreading factor (TODO figure out what this actually is)
:type figsize: tuple of float
:param figsize: size the of the figure, passed into plt.subplots()
:type show: bool
:param show: show the figure as a graphical output
:type save: str
:param save: path to save output figure, will create the parent
directory if it doesn't exist. If None, will not save.
:type overwrite: bool
:param overwrite: if the path defined by `save` exists, will overwrite
the existing figure
:raises AssertionError: if any parameters are set incorrectly
"""
# Read files from path if provided
if pysep_path is not None and os.path.exists(pysep_path):
# Expected file format: 20200404015318920.CI.LRL..BH.r
fids = glob(os.path.join(pysep_path, "*.*.*.*.*.?"))
print(f"Reading {len(fids)} files from: {pysep_path}")
if fids:
# Overwrite stream, so reading takes precedence
st = Stream()
for fid in fids:
st += read(fid)
assert(st), \
"Stream object not found, please check inputs `st` and `pysep_path"
# User defined parameters, do some type-setting
self.st = st.copy()
try:
self.st_syn = st_syn.copy()
except AttributeError:
self.st_syn = None
# Y-Axis sorting parameters
self.sort_by = sort_by.lower()
self.y_axis_spacing = float(y_axis_spacing)
self.azimuth_start_deg = float(azimuth_start_deg)
self.components = str(components)
# Amplitude scaling parameters
self.scale_by = scale_by
self.amplitude_scale_factor = amplitude_scale_factor
self.geometric_spreading_factor = float(geometric_spreading_factor)
self.geometric_spreading_k_val = geometric_spreading_k_val
# Time shift parameters
self.move_out = move_out
self.time_shift_s = time_shift_s
# Filtering parameters
self.min_period_s = min_period_s
self.max_period_s = max_period_s
self.preprocess = preprocess
self.max_traces_per_rs = max_traces_per_rs
self.integrate = int(integrate)
# Plotting parameters
self.xlim_s = xlim_s
self.distance_units = distance_units.lower()
self.y_label_loc = y_label_loc
self.figsize = figsize
self.show = bool(show)
self.save = save
self.overwrite = bool(overwrite)
self.kwargs = Dict(kwargs)
# Run checks to ensure that all the parameters are set properly
# And get some new, initial parameters that are required for other
# 'get' functions
self.check_parameters()
self.stats = self.get_srcrcv_stats()
self.distances, self.azimuths, self.backazimuths = \
self.get_srcrcv_dist_az_baz()
# Internally used parameters that will be filled out by other functions
self.f = None
self.ax = None
self.idx = []
self.station_ids = []
self.max_amplitudes = []
self.amplitude_scaling = []
self.y_axis = []
self.xlim = [] # unit: samples
self.sorted_idx = []
def check_parameters(self):
"""
Check that parameters are set properly and in line with how they
are expected by the program
.. note::
Not using assertions here because we want all incorrect parameters
to be evaluated together and displayed at once, that way the user
doesn't have to run this function multiple times to figure out how
to set their parameters correctly
:raises AssertionError: If any parameters are not set as expected by
plotw_rs functionality
"""
print("checking parameter acceptability")
# Used to keep track of which parameters failed and in what way
err = Dict()
# Check to make sure there is data
if not bool(self.st):
err.st = f"stream has {len(self.st)} traces, no data"
# Check that stream has SAC headers if we want to sort by dist or (b)az.
# Pysep should have created these
if self.sort_by != "default" and \
any(_ in self.sort_by for _ in ["azimuth", "distance"]):
_idx = []
for i, tr in enumerate(self.st):
if not hasattr(tr.stats, "sac"):
_idx.append(i)
if _idx:
err.st = (f"{len(_idx)} traces have no SAC header, plotw_rs "
f"expects SAC headers for sorting. Trace indexes "
f"are: {_idx}")
if self.st_syn is not None:
if len(self.st) != len(self.st_syn):
err.st_syn = f"length must match `st` (which is {len(self.st)})"
# Check the `sort_by` sorting parameter options
acceptable_sort_by = ["default", "azimuth", "backazimuth",
"distance", "alphabetical", "abs_azimuth",
"abs_distance"]
# Allow reverse sorts
acceptable_sort_by += [f"{_}_r" for _ in acceptable_sort_by]
if self.sort_by not in acceptable_sort_by:
err.sort_by = f"must be in {acceptable_sort_by}"
if "azimuth" in self.sort_by:
if not (0 <= self.azimuth_start_deg <= 360):
err.azimuth_start_deg = f"0 < azi < 360"
acceptable_distance_units = ["km", "km_utm", "deg"]
if ("distance" in self.sort_by) and \
(self.distance_units not in acceptable_distance_units):
err.azimuth_start_deg = \
f"must be in {acceptable_distance_units}"
if self.scale_by is not None:
acceptable_scale_by = ["normalize", "global_norm",
"geometric_spreading"]
if self.scale_by not in acceptable_scale_by:
err.scale_by = f"must be in {acceptable_scale_by}"
if self.time_shift_s is not None:
acceptable_time_shift_s = [int, float, list]
if type(self.time_shift_s) not in acceptable_time_shift_s:
err.time_shift_s = f"must be in {acceptable_time_shift_s}"
if isinstance(self.time_shift_s, list) and \
len(self.time_shift_s) != len(self.st):
err.time_shift_s = f"must be list of length {len(self.st)}"
# Defaults to float value of 1
acceptable_scale_factor = [int, float, list]
if type(self.amplitude_scale_factor) not in acceptable_scale_factor:
err.amplitude_scale_factor = f"must be in {acceptable_scale_factor}"
if isinstance(self.amplitude_scale_factor, list) and \
len(self.amplitude_scale_factor) != len(self.st):
err.amplitude_scale_factor = f"must be list length {len(self.st)}"
if self.min_period_s is not None and self.max_period_s is not None:
if self.min_period_s >= self.max_period_s:
err.min_period_s = "must be less than `max_period_s`"
if self.preprocess is not None:
acceptable_preprocess = ["both", "st"]
if self.preprocess not in acceptable_preprocess:
err.preprocess = f"must be in {acceptable_preprocess}"
# Overwrite the max traces per record section, enforce type int
if self.max_traces_per_rs is None:
self.max_traces_per_rs = int(len(self.st))
else:
self.max_traces_per_rs = int(self.max_traces_per_rs)
if self.xlim_s is not None:
if len(self.xlim_s) != 2:
err.xlim_s = f"must be of length 2, [start, stop]"
elif self.xlim_s[0] > self.xlim_s[1]:
err.xlim_s = f"start time must be less than stop time"
acceptable_y_label_loc = ["default", "y_axis", "y_axis_right", "x_min",
"x_max", None]
if self.y_label_loc not in acceptable_y_label_loc:
err.y_label_loc = f"must be in {acceptable_y_label_loc}"
if "abs" in self.sort_by and "y_axis" in self.sort_by:
err.y_label_loc = (f"absolute sorting means 'y_axis' label loc is"
f"not available")
if len(self.figsize) != 2:
err.figsize = "must be tuple defining (horizontal, vertical) extent"
if os.path.exists(self.save) and not self.overwrite:
err.save = (f"path {self.save} already exists. Use '--overwrite' "
f"flag to save over existing figures.")
_dirname = os.path.abspath(os.path.dirname(self.save))
if not os.path.exists(_dirname):
print(f"creating output directory {_dirname}")
os.makedirs(_dirname)
if err:
out = "ERROR - Parameter errors, please make following changes:\n"
out += "\n".join([f"\t{key}: {val}" for key, val in err.items()])
print(out)
sys.exit(-1)
def get_skip_idx(self):
"""
Get a list of any traces that don't adhere to user-defined boundaries
such as dist, az, baz, id, or component matches. Don't actually remove
the traces from the stream but rather just collect indices we can use
to skip when plotting.
TODO add distance, azi and backazi skip criteria
:rtype: np.array
:return: returns an indexing list which can be used to skip over
traces that don't adhere to certain criteria
"""
skip_idx = []
for idx in self.idx:
tr = self.st[idx]
# Component-wise removal
if tr.stats.component not in self.components:
skip_idx.append(idx)
# !!! Add more here
print(f"criteria check will remove "
f"{len(skip_idx)}/{len(self.st)} traces")
return np.array(skip_idx)
def get_parameters(self):
"""
Calculate parameters in a specific order and based on the user-defined
information.
.. note::
The order of function calls here is important! Some of the 'get'
functions require the results of other 'get' functions.
Calculated Parameters
::
np.array idx:
a linear indexing of all the traces in the stream
np.array station_ids:
an ordered list of station ids, used to get station names
that match the index defined in `idx`
np.array max_amplitudes:
abs max amplitudes of each trace, used for normalization
np.array amplitude_scaling:
An array to scale amplitudes based on user choices
np.array time_shift_s:
An array to time shift time series based on user choices
np.array y_axis:
Y-Axis values based on sorting algorithm, used for plotting
np.array distances:
source-receiver distances in `distance_units` units
np.array azimuths:
source-receiver azimuths in degrees
np.array backazimuths:
source-receiver backazimuths in degrees
np.array sorted_idx:
sorted indexing on all the traces of the stream based on the
chosen sorting algorithm
"""
# Extract basic information from the Stream
self.idx = np.arange(0, len(self.st), 1)
self.station_ids = np.array([tr.get_id() for tr in self.st])
self.time_shift_s = self.get_time_shifts() # !!! OVERWRITES user input
self.xlim = self.get_xlims()
# Max amplitudes should be RELATIVE to what were showing (e.g., if
# zoomed in on the P-wave, max amplitude should NOT be the surface wave)
for tr, xlim in zip(self.st, self.xlim):
start, stop = xlim
self.max_amplitudes.append(max(abs(tr.data[start:stop])))
self.max_amplitudes = np.array(self.max_amplitudes)
# Figure out which indices we'll be plotting
sorted_idx = self.get_sorted_idx()
skip_idx = self.get_skip_idx()
# Remove skip indexes from sorted index to get the final ordered list
self.sorted_idx = np.array([_ for _ in sorted_idx if _ not in skip_idx])
# Figure out how to manipulate each of the traces in the Stream
self.y_axis = self.get_y_axis_positions()
self.amplitude_scaling = self.get_amplitude_scaling()
def get_xlims(self):
"""
The x-limits of each trace depend on the overall time shift (either
static or applied through move out), as well as the sampling rate of
each trace (which can vary). Retrieve an index-dependent list of
x-limits which can be used to truncate the time series during plotting.
.. note::
Requires that get_time_shifts() has already been run
:rtype: np.array
:return: an array of tuples defining the start and stop indices for EACH
trace to be used during plotting. Already includes time shift
information so xlim can be applied DIRECTLY to the time shifted data
"""
xlim = []
if self.xlim_s is None:
# None's will index the entire trace
xlim = np.array([(None, None) for _ in range(len(self.st))])
else:
# Looping to allow for delta varying among traces,
# AND apply the time shift so that indices can be used directly in
# the plotting function
for tr, tshift in zip(self.st, self.time_shift_s):
start, stop = [int(_/tr.stats.delta) for _ in self.xlim_s]
sshift = int(tshift / tr.stats.delta) # unit: samples
xlim.append((start-sshift, stop-sshift))
xlim = np.array(xlim)
return xlim
def get_srcrcv_stats(self):
"""
Get source receiver information such as min max values, and
count-related numbers (e.g., num stations) to be used mainly for print
statements and text information
Stats Arguments
::
np.array event_names:
unique event names taken from the SAC header
int nevents:
number of unique events in the stream
np.array unique_sta_ids:
unique station codes taken from trace stats
int nstation_ids:
number of unique station codes
np.array network_codes:
unique network codes taken from station ids
int nnetwork:
number of unique network codes
np.array station_codes:
unique station codes taken from station ids
int nstation:
number of unique station codes
np.array location_codes:
unique location codes taken from station ids
int nlocation:
number of unique location codes
np.array channel_codes:
unique channel codes taken from station ids
int nchannel:
number of unique channel codes
bool reverse_sort:
determine if the user wants to reverse their sort, they do this
by appending '_r' to the end of the `sort_by` argument
"""
print("getting source-receiver stats")
def _unique(list_):
"""return a unique numpy array derived from a list"""
return np.unique(np.array(list_, dtype=str))
stats = Dict()
stats.event_names = _unique([tr.stats.sac.kevnm for tr in self.st])
stats.nevents = len(stats.event_names)
stats.unique_sta_ids = _unique([tr.get_id() for tr in self.st])
stats.longest_id = max([len(_) for _ in stats.unique_sta_ids])
stats.nstation_ids = len(stats.unique_sta_ids)
# Get unique network, station, location and channel codes. Also numbers
for name in ["network", "station", "location", "channel", "component"]:
stats[f"{name}_codes"] = _unique(
[getattr(tr.stats, name) for tr in self.st]
)
stats[f"n{name}"] = len(stats[f"{name}_codes"])
# We use `not` in `reverse_sort` to make the top of the y-axis the
# starting point, which seems more intuitive for record sections, but
# is opposite the behavior when you increment from 0
stats.reverse_sort = not bool("_r" in self.sort_by)
# Initiate empty lists for _plot_trace() to fill with min and max data
# values which can be used for global plotting parameters like xlims
stats.xmin, stats.xmax, stats.ymin, stats.ymax = [], [], [], []
return stats
def get_time_shifts(self):
"""
Very simple function which allows float inputs for time shifts and
ensures that time shifts are always per-trace arrays
Applies the move out by calculating a time shift using src-rcv distance
:rtype: np.array
:return: a stream-lengthed array of time shifts that can be applied
per trace
"""
# No user input means time shifts will be 0, so nothing happens
time_shift_arr = np.zeros(len(self.st))
if self.time_shift_s is not None:
# User inputs a static time shift
if isinstance(self.time_shift_s, (int, float)):
time_shift_arr += self.time_shift_s
# User input an array which should have already been checked for len
else:
time_shift_arr = self.time_shift_s
time_shift_arr = np.array(time_shift_arr)
# Further change the time shift if we have move out input
if self.move_out:
print(f"apply {self.move_out} {self.distance_units}/s move out")
move_out_arr = self.distances / self.move_out
time_shift_arr -= move_out_arr
return time_shift_arr
def get_srcrcv_dist_az_baz(self):
"""
Convenience function to wrap _get_srcrcv_dist_az_baz_trace into a loop
over the whole stream and return lists of distances, azimuths, and
backazimuths
:rtype distances: np.array
:return distances: source-receiver distances in user-defined units in
the original order of Stream
:rtype azimuths: np.array
:return azimuths: source-receiver azimuths (deg) in the original
order of Stream
:rtype backazimuths: np.array
:return backazimuths: source-receiver azimuths (deg) in the original
order of Stream
"""
print("calculating source-receiver distance and (back)azimuths")
distances, azimuths, backazimuths = [], [], []
for tr in self.st:
gcd, az, baz = self._get_srcrcv_dist_az_baz_trace(tr=tr)
distances.append(gcd)
azimuths.append(az)
backazimuths.append(baz)
distances = np.array(distances)
azimuths = np.array(azimuths)
backazimuths = np.array(backazimuths)
return distances, azimuths, backazimuths
def _get_srcrcv_dist_az_baz_trace(self, tr=None, idx=0):
"""
Check the source-receiver characteristics such as src-rcv distance,
azimuth, backazimuth for a given trace.
.. note::
This function ASSUMES that SAC headers have been written to the
traces. Otherwise we will need more complicated ways to get
event lat and lon
:type tr: obspy.core.trace.Trace
:param tr: trace to get srcrcv information for. If None, will use `idx`
:type idx: int
:param idx: if `tr`==None, user can provide index of self.st (Stream)
defaults to index 0
:rtype gcdist: float
:return gcdist: great circle distance in units specified by
`distance_units`, can be 'km' or 'deg'
:rtype az: float
:return az: azimuth (degrees) between source and receiver
:rtype baz: float
:return baz: azimuth (degrees) between source and receiver
"""
# Default to the first trace in the Stream
if tr is None:
tr = self.st[int(idx)]
try:
dist = tr.stats.sac.dist # units: km
az = tr.stats.sac.az # units: deg
baz = tr.stats.sac.baz # units: deg
except AttributeError:
# If for whatever reason SAC headers dont contain this info already
# Use ObsPy to get great circle distance, azimuth and backazimuth
dist, az, baz = gps2dist_azimuth(lat1=tr.stats.sac.evla,
lon1=tr.stats.sac.evlo,
lat2=tr.stats.sac.stla,
lon2=tr.stats.sac.stlo)
dist *= 1E-3 # units: m -> km
# Ensure that 0 <= (b)az <= 360
az = az % 360
baz = baz % 360
# Make sure distance is in the correct units, default units 'km'
if self.distance_units == "deg":
dist = kilometers2degrees(dist) # units: km -> deg
elif self.distance_units == "km_utm":
# Overwrite `dist`, could probably skip that calc above but
# leaving for now as I don't think this option will be used heavily.
dist_deg = np.sqrt(
((tr.stats.sac.stlo - tr.stats.sac.evlo) ** 2) /
((tr.stats.sac.stla - tr.stats.sac.evla) ** 2)
)
dist = kilometers2degrees(dist_deg) # units: km
return dist, az, baz
def get_amplitude_scaling(self):
"""
Scale the amplitudes of all the waveforms by producing a Stream
dependent scale factor based on user choice. It is expected that the
output array will be DIVIDED by the data arrays:
i.e., st[i].data /= self.amplitude_scaling[i]
.. note::
Needs to be run AFTER preprocessing because filtering etc. will
affect the final amplitudes of the waveforms
:rtype: np.array
:return: an array corresponding to the Stream indexes which provides
a per-trace scaling coefficient
"""
print(f"determining amplitude scaling with: {self.scale_by}")
# Don't scale by anything
if self.scale_by is None:
amp_scaling = np.ones(len(self.st))
# Scale by the max amplitude of each trace
elif self.scale_by == "normalize":
amp_scaling = self.max_amplitudes
# When using absolute distance scale, scale waveforms to minmax dist
if "abs" in self.sort_by:
if "distance" in self.sort_by:
print("scaling amplitudes for absolute distance")
scale = np.mean(self.distances) / 10
elif "backazimuth" in self.sort_by:
print("scaling amplitudes for absolute backazimuth")
scale = self.backazimuths.max() - self.backazimuths.min()
scale /= 100
elif "azimuth" in self.sort_by:
print("scaling amplitudes for absolute azimuth")
scale = self.azimuths.max() - self.azimuths.min()
scale /= 50
# Divide to make waveforms larger
amp_scaling /= scale
# Scale by the largest amplitude shown
elif self.scale_by == "global_norm":
global_max = self.max_amplitudes[self.sorted_idx].max()
amp_scaling = np.ones(len(self.st)) * global_max
# Scale by the theoretical geometrical spreading factor
elif self.scale_by == "geometric_spreading":
amp_scaling = self._calculate_geometric_spreading()
# Apply manual scale factor if provided, default value is 1 so nothing
# Divide because the amplitude scale divides the data array, which means
# `amplitude_scale_factor` will be MULTIPLIED by the data array
amp_scaling /= self.amplitude_scale_factor
return amp_scaling
def _calculate_geometric_spreading(self):
"""
Stations with larger source-receiver distances will have their amplitude
scaled by a larger value.
For information on geometric spreading, see Stein and Wysession,
Section 4.3.4, Eq 20 (for Rayleigh waves, geometrical spreading
factor = 0.5). For our purposes, this will fold the attenuation factor
into the same single factor that accounts for geometric spreading.
.. note::
This does not take into account the variation in amplitude.
TODO Plot geometric spreading with best-fitting curve
:type max_amplitudes: list
:param max_amplitudes: list of maximum amplitudes for each trace in the
stream. IF not given, will be calculated on the fly. Optional incase
this has been calculated already and you want to save time
:rtype: list
:return: scale factor per trace in the stream based on theoretical
geometrical spreading factor. This is meant to be MULTIPLIED by the
data arrays
"""
raise NotImplementedError("This function is currently work in progress")
print("calculating geometrical spreading for amplitude normalization")
# Create a sinusoidal function based on distances in degrees
sin_del = np.sin(np.array(self.dist) / (180 / np.pi))
# !!! TODO Stein and Wysession and figure out vector names
if self.geometric_spreading_k_val is not None:
k_vector = self.max_amplitudes * \
(sin_del ** self.geometric_spreading_factor)
k_val = np.median(k_vector)
else:
k_val = self.geometric_spreading_k_val
w_vector = k_val / (sin_del ** self.geometric_spreading_factor)
return w_vector
def get_sorted_idx(self):
"""
Sort the source-receiver pairs by the chosen parameters. Except for in
`default` sorting, always maintains component ordering defined by the
user, i.e., for the same station, components will be ordered by the
`component` parameter.
:rtype: np.array
:return: returns an indexing list which is sorted based on the user
defined `sort_by` argument.
"""
print(f"determining sort order with parameter: {self.sort_by}")
# Retain input ordering but run sorting to allow reversing
if "default" in self.sort_by:
sorted_idx = sorted(self.idx, reverse=self.stats.reverse_sort)
# Sort alphabetically BUT allow component sorting
elif "alphabetical" in self.sort_by:
sorted_idx = self._sort_by_alphabetical()
# Sort by dist, az or baz
else:
components = self._get_component_order()
# Azimuthal sorts are allowed to start at a value other than 0
# Backazimuth needs to come first because 'azimuth' can return both
if "backazimuth" in self.sort_by:
sort_list = (self.backazimuths - self.azimuth_start_deg) % 360
elif "azimuth" in self.sort_by:
sort_list = (self.azimuths - self.azimuth_start_deg) % 360
elif "distance" in self.sort_by:
sort_list = self.distances
# Sort by the values, AND the components (e.g., Z->R->T or whatever)
_, _, sorted_idx = \
zip(*sorted(zip(sort_list, components, self.idx),
reverse=self.stats.reverse_sort)
)
sorted_idx = np.array(list(sorted_idx))
return sorted_idx
def _sort_by_alphabetical(self):
"""
Sort by full station name in order. That is, network is sorted, then
within network, station is sorted, and so on. Components are sorted
last and NOT in alphabetical order. They are ordered based on the
user-input `components` parameter.
:rtype: np.array
:return: indexing of networks and stations sorted alphabetically
"""
networks = [_.split(".")[0] for _ in self.station_ids]
stations = [_.split(".")[1] for _ in self.station_ids]
locations = [_.split(".")[2] for _ in self.station_ids]
components = self._get_component_order()
zipped = zip(networks, stations, locations, components, self.idx)
arr_out = np.array(
list(zip(*sorted(zipped, reverse=self.stats.reverse_sort)))
)
return arr_out[-1].astype(int)
def _get_component_order(self):
"""
When we are sorting, we want components to be sorted by the
preferred order (i.e, ZRT, Z index is 0, T is 2), which means the
components have to be reordered to adhere to the sorting algorithm.
ALSO we need to ensure that we honor component order even if
everything else is being sorted reverse alphabetically so the
components entry needs to be the opposite of stats.reverse_sort
:rtype: list
:return: components converted to integer values which can be used for
sorting algorithms.
"""
channels = [_.split(".")[3] for _ in self.station_ids]
# ASSUMING component is the last entry in the channel, SEED convention
components = [_[-1] for _ in channels]
if self.stats.reverse_sort:
comp_list = self.components
else:
comp_list = self.components[::-1]
# Can't list comp here incase `comp_list` does NOT contain one of the
# available components, which will throw a ValueError. Use a random
# number to catch these.
numbered_components = []
for comp in components:
try:
numbered_components.append(comp_list.index(comp))
except ValueError:
numbered_components.append(-999)
return numbered_components
def get_y_axis_positions(self):
"""
Determine how seismograms are vertically separated on the Y-Axis when
plotting. Allows for constant separation, or absolute separation based
on distance or (back)azimuth separation.
:rtype: np.array
:return: an array of actual y-axis positions that can be passed directly
to plt.plot() (or similar)
"""
print(f"determining y-axis positioning for sort: {self.sort_by}")
# Default weights provides constant `y_axis_spacing` between seismos
if self.sort_by == "default" or "abs_" not in self.sort_by:
y_range = np.arange(0, len(self.sorted_idx), 1)
y_axis = self.y_axis_spacing * y_range
# Absolute y-axis (i.e., absolute distance or (back)azimuth) will just
# plot the actual distance or azimuth value
else:
if "backazimuth" in self.sort_by:
y_axis = self.backazimuths
elif "azimuth" in self.sort_by:
y_axis = self.azimuths
elif "distance" in self.sort_by:
y_axis = self.distances
return y_axis
def process_st(self):
"""
Preprocess the Stream with optional filtering in place.
.. note::
Data in memory will be irretrievably altered by running preprocess.
TODO Add feature to allow list-like periods to individually filter
seismograms. At the moment we just apply a blanket filter.
"""
if self.preprocess is None:
print("no preprocessing applied")
return
elif self.preprocess == "st":
print(f"preprocessing {len(self.st)} `st` waveforms")
preprocess_list = [self.st]
elif self.preprocess == "st_syn":
print(f"preprocessing {len(self.st_syn)} `st_syn` waveforms")
preprocess_list = [self.st_syn]
elif self.preprocess == "both":
print(f"preprocessing {len(self.st) + len(self.st_syn)} "
f"`st` and `st_syn` waveforms")
preprocess_list = [self.st, self.st_syn]
for st in preprocess_list:
# Fill any data gaps with mean of the data, do it on a trace by
# trace basis to get individual mean values
for tr in st:
tr.trim(starttime=tr.stats.starttime, endtime=tr.stats.endtime,
pad=True, fill_value=tr.data.mean())
st.detrend("demean")
st.taper(max_percentage=0.05, type="cosine")
# Allow multiple filter options based on user input
# Min period but no max period == low-pass
if self.max_period_s is not None and self.min_period_s is None:
print(f"apply lowpass filter w/ cutoff {1/self.max_period_s}")
st.filter("lowpass", freq=1/self.max_period_s, zerophase=True)
# Max period but no min period == high-pass
elif self.min_period_s is not None and self.max_period_s is None:
print(f"apply highpass filter w/ cutoff {1/self.min_period_s}")
st.filter("highpass", freq=1/self.min_period_s, zerophase=True)
# Both min and max period == band-pass
elif self.min_period_s is not None and \
self.max_period_s is not None:
print(f"applying bandpass filter w/ "
f"[{1/self.max_period_s}, {self.min_period_s}]")
st.filter("bandpass", freqmin=1/self.max_period_s,
freqmax=1/self.min_period_s, zerophase=True)
else:
print("no filtering applied")
# Integrate and differentiate N number of times specified by user
st.detrend("simple")
if self.integrate != 0:
if self.integrate < 0:
func = "differentiate"
elif self.integrate > 0:
func = "integrate"
for i in range(np.abs(self.integrate)):
print("{func} all waveform data")
getattr(st, func)()
def plot(self, subset=None, page_num=None, **kwargs):
"""
Plot record sections based on all the available information
:type subset: list of int
:param subset: subset of `sorted_idx` if there are too many waveforms to
plot on one page (set by `max_traces_per_rs`). e.g., to get the
first 10 entries, subset=[0,10]
:type page_num: int
:param page_num: If multiple pages are required due to exceeding
`max_traces_per_rs`, page_num will make adjustments to the figure
name and title to differentiate different pages of the same record
section
"""
if subset is None:
start, stop = 0, None # None will allow full list traversal
nwav = len(self.sorted_idx)
else:
start, stop = subset
nwav = stop - start
print(f"plotting record section for {nwav} waveforms")
# Do a text output of station information so the user can check
# that the plot is doing things correctly
print("PLOTTING LINE CHECK STARTING FROM BOTTOM")
print("\nIDX\tY\t\tID\tDIST\tAZ\tBAZ\tTSHIFT\tYABSMAX")
self.f, self.ax = plt.subplots(figsize=self.figsize)
# Allow choosing observed or synthetic data, defaults to observed
# Allow different waveform looks based on observed vs. synthetic
for choice in ["st", "st_syn"]:
if getattr(self, choice) is None:
continue
# Main plotting call. Indexes should already be sorted
for y_idx, idx in enumerate(self.sorted_idx[start:stop]):
# Absolute scaling requires plotting actual dist or az values
# Relative scaling just requires a linear index to stack seismos
if "abs_" in self.sort_by:
y_index = idx
else:
y_index = y_idx + start
self._plot_trace(idx=idx, y_index=y_index, choice=choice,
**kwargs)
# Change the aesthetic look of the figure, should be run before other
# set functions as they may overwrite what is done here
self._set_plot_aesthetic()
# Partition the figure by user-specified azimuth bins
if self.sort_by and "azimuth" in self.sort_by:
self._plot_azimuth_bins()
# Finalize the figure accoutrements
self._plot_title(nwav=nwav, page_num=page_num)
self._plot_axes(start=start, stop=stop)
if self.save:
# Allow appending page numbers to figure names,
# e.g., default.png -> default_01.png
if page_num:
fid, ext = os.path.splitext(self.save)
save_fid = f"{fid}_{page_num:0>2}{ext}"
else:
save_fid = self.save
print(f"\nsaving figure to {save_fid}")
plt.savefig(save_fid)
if self.show:
plt.show()
def _plot_trace(self, idx, y_index, choice="st"):
"""
Plot a single trace on the record section, with amplitude scaling,
time shifts, etc. Observed waveforms are black, synthetics are red.
:type idx: int
:param idx: index of the trace to plot and all trace-ordered values like
amplitude scaling and time shifts
:type y_index: int
:param y_index: numerical order which this trace was plotted, as each
trace is plotted on top of the previous one. y_index should be
iterated linearly in the loop that calls this function.
:type choice: str
:param choice: choice of 'st' or 'st_syn' depending on whether you want
to plot the observed or synthetic waveforms
"""
linewidth = self.kwargs.get("linewidth", .25)
# Used to differentiate the two types of streams for plotting diffs
choices = ["st", "st_syn"]
assert (choice in choices)
c = choices.index(choice)
tr = getattr(self, choice)[idx] # i.e., tr = self.st[idx]
# Plot actual data on with amplitude scaling, time shift, and y-offset
tshift = self.time_shift_s[idx]
# These are still the entire waveform
x = tr.times() + tshift
y = tr.data / self.amplitude_scaling[idx] + self.y_axis[y_index]
# Truncate waveforms to get figure scaling correct.
start, stop = self.xlim[idx]
x = x[start:stop]
y = y[start:stop]
self.ax.plot(x, y, c=["k", "r"][c], linewidth=linewidth, zorder=10)
# Sanity check print station information to check against plot
print(f"{idx}"
f"\t{int(self.y_axis[y_index])}"
f"\t{tr.get_id():<6}"
f"\t{self.distances[idx]:6.2f}"
f"\t{self.azimuths[idx]:6.2f}"
f"\t{self.backazimuths[idx]:6.2f}"
f"\t{self.time_shift_s[idx]:4.2f}"
f"\t{self.max_amplitudes[idx]:.2E}")
# Retain some stats for global plot args
self.stats.xmin.append(x.min())
self.stats.xmax.append(x.max())
self.stats.ymin.append(y.min())
self.stats.ymax.append(y.max())
def _plot_azimuth_bins(self):
"""
If plotting by azimuth, create visual bin separators so the user has
a visual understanding of radiation patterns etc.
"""
azimuth_binsize = self.kwargs.get("azimuth_binsize", 45)
# Look of the azimuth bin lines
c = self.kwargs.get("azimuth_bin_c", "r")
lw = self.kwargs.get("azimuth_bin_lw", .75)
ls = self.kwargs.get("azimuth_bin_ls", "-")
z = self.kwargs.get("azimuth_bin_zorder", 5)
azimuth_bins = np.arange(self.azimuth_start_deg,
self.azimuth_start_deg + 360,
azimuth_binsize)
# Make sure that the bins go from 0 <= azimuth_bins <= 360
azimuth_bins = azimuth_bins % 360
# In an absolute plot, the y values are simply the azimuth bins
if "abs" in self.sort_by:
y_vals = azimuth_bins
s_vals = [f"{azbin}{DEG}" for azbin in azimuth_bins]
# In a relative plot, the y values need to be found between seismograms
else:
s_vals, y_vals = [], []
# Brute force determine where these azimuth bins would fit into the
# actual plotted azimuths, draw a line between adjacent seismograms
# i.e., iterating and looking if the bin value fits between
# two adjacent azimuth values
for azbin in azimuth_bins:
# Edge case for 0 deg azimuth bin since azimuth wraps on 0
# Look for the top minimum azimuth value, place line above that
if azbin == 0:
dy = abs(self.y_axis[1] - self.y_axis[0])
azis = self.azimuths[self.sorted_idx]
i = max(np.where(azis == azis.min())[0])
y_vals.append(self.y_axis[i] + dy/2)
else:
for i, idx in enumerate(self.sorted_idx[1:]):
j = i + 1
idx_minus_one = self.sorted_idx[i]
azi_low = self.azimuths[idx]
azi_high = self.azimuths[idx_minus_one]
# Break if bin is in between azi values for two seismos
if azi_low <= azbin <= azi_high:
break
else:
continue
# Mean gives the space in between two adjacent seismograms
y_vals.append(np.mean([self.y_axis[i], self.y_axis[j]]))
s_vals.append(f"{azbin}{DEG}")
for y, (s_val, y_val) in enumerate(zip(s_vals, y_vals)):
# Dealing with the case where two bins occupy the same space,
# only plot the first one that occurs
if y_val == y_vals[y-1]:
continue
plt.axhline(y=y_val, c=c, linewidth=lw, linestyle=ls, zorder=z)
plt.text(x=max(self.stats.xmax), y=y_val, s=s_val, c=c, ha="right")
def _plot_axes(self, start=0, stop=None):
"""
Contains the logic in how to handle the x- and y-axis labels, ticks etc.
Logic options for how to plot the y-axis:
- Relative: Relative plotting means the yticklabels will get replaced
by station information. This can either be on the right or left
side but will be attached to the actual axis
- Absolute: Absolute plotting means the y-axis actual represents
something (e.g., distance, azimuth). That means labels can not
replace the y-ticks and they have to be placed within the figure
.. note::
Relative plotting can also place labels OFF the y-axis, at which
point the y-axis is turned off because it contains no usable
information
:type start: int
:param start: optional starting index for creating text labels
:type stop: int
:param stop: optional stop index for creating text labels
"""
# Sort out how the y-axis will be labeled with station information and
# dist/azimuth if we're doing absolute sorting
if "abs_" in self.sort_by:
self._set_y_axis_absolute()
if self.y_label_loc is not None:
# By default, place absolute sorted labels at xmin
if self.y_label_loc == "default":
loc = "x_min"
else:
loc = self.y_label_loc
self._set_y_axis_text_labels(start=start, stop=stop, loc=loc)
elif self.y_label_loc is not None:
# By default, relative plotting shows labels on the right side
if self.y_label_loc == "default":
loc = "y_axis"
else:
loc = self.y_label_loc
self._set_y_axis_text_labels(start=start, stop=stop, loc=loc)
print(f"placing station labels on y-axis at: {loc}")
# User requests that we turn off y-axis
if self.y_label_loc is None:
print(f"user requests turning off y-axis w/ `y_label_loc`== None")
self.ax.get_yaxis().set_visible(False)
# OR EDGE CASE: Relative plotting but labels are not placed on the
# y-axis, turn off the y-axis cause it doesn't mean anything anymore
elif self.y_label_loc not in ["default", "y_axis", "y_axis_right"] and \
"abs" not in self.sort_by:
print("turning off y-axis as it contains no information")
self.ax.get_yaxis().set_visible(False)
# Reverse the y-axis if we are doing absolute y-axis and reversing
if "abs_" in self.sort_by and "_r" in self.sort_by:
print("user requests inverting y-axis with absolute reverse sort")
self.ax.invert_yaxis()
# X-axis label is different if we time shift
if self.time_shift_s.sum() == 0:
plt.xlabel("Time [s]")
else:
plt.xlabel("Relative Time [s]")
# Allow user defined x-axis limits
if self.xlim_s is None:
self.ax.set_xlim([min(self.stats.xmin), max(self.stats.xmax)])
else:
self.ax.set_xlim(self.xlim_s)
plt.tight_layout()
def _set_y_axis_absolute(self):
"""
If 'abs_' in sort_by, then the Y-axis should be shown in absolute scale.
That means we need to format the text labels, add some labelling etc.
"""
# Reset tick label size to be larger to match absolute x-axis size
ytick_fontsize = self.kwargs.get("ytick_fontsize", 12)
self.ax.tick_params(axis="y", labelsize=ytick_fontsize)
if "distance" in self.sort_by:
if "km" in self.distance_units:
ytick_minor = self.kwargs.get("ytick_minor", 25)
ytick_major = self.kwargs.get("ytick_major", 100)
elif "deg" in self.distance_units:
ytick_minor = self.kwargs.get("ytick_minor", 0.25)
ytick_major = self.kwargs.get("ytick_major", 1.0)
ylabel = f"Distance [{self.distance_units}]"
elif "azimuth" in self.sort_by:
ytick_minor = self.kwargs.get("ytick_minor", 45)
ytick_major = self.kwargs.get("ytick_major", 90)
ylabel = f"Azimuth [{DEG}]"
# Set ytick label major and minor which is either dist or az
self.ax.yaxis.set_major_locator(MultipleLocator(ytick_major))
self.ax.yaxis.set_minor_locator(MultipleLocator(ytick_minor))
self.ax.set_ylabel(ylabel)
def _set_y_axis_text_labels(self, start=0, stop=-1, loc="y_axis"):
"""
Plot a text label next to each trace describing the station,
azimuth and source-receiver distance. We need to do this all at once
because we have to replace all ticks and tick labels at once.
.. note::
if using the 'subset' option in plot, need to also tell the y-axis
plotter that we are only plotting a subset of data by using the
`start` and `stop` parameters
:type start: int
:param start: starting index for plotting, default to start 0
:type stop: int
:param stop: stop index for plotting, default to end -1
:type loc: str
:param loc: location to place the y_axis text labels, available:
- y_axis: Place labels along the y-axis (left side of the figure)
Will replace the actual y-tick labels so not applicable for
absolute sorting which requries the y-axis labels
- y_axis_right: same as `y_axis` but set on the right side of figure
- x_min: Place labels on the waveforms at the minimum x value
- x_max: Place labels on the waveforms at the maximum x value
"""
c = self.kwargs.get("y_label_c", "k")
fontsize = self.kwargs.get("y_label_fontsize", 10)
y_tick_labels = []
for idx in self.sorted_idx[start:stop]:
str_id = self.station_ids[idx]
if self.sort_by is not None and "backazimuth" in self.sort_by:
# This is named `str_az` but it's actually backazimuths
str_az = f"{self.backazimuths[idx]:6.2f}{DEG}"
else:
str_az = f"{self.azimuths[idx]:6.2f}{DEG}"
# Allow degree distance to use the unicode * symbol
if self.distance_units == "deg":
du = DEG
else:
du = self.distance_units
str_dist = f"{self.distances[idx]:5.2f}{du}"
# Looks something like: NN.SSS.LL.CC|30*|250.03km
label = \
f"{str_id:>{self.stats.longest_id}}|{str_az:>8}|{str_dist:>8}"
# Add time shift if we have shifted at all
if self.time_shift_s[idx] != 0:
label += f"|{self.time_shift_s[idx]:.2f}s"
y_tick_labels.append(label)
if "y_axis" in loc:
# For relative plotting (not abs_), replace y_tick labels with
# station information
self.ax.set_yticks(self.y_axis[start:stop])
self.ax.set_yticklabels(y_tick_labels)
else:
# Trying to figure out where the min or max X value is on the plot
if loc == "x_min":
ha = "left"
func = min
x_val = func(self.stats.xmin)
elif loc == "x_max":
ha = "right"
func = max
x_val = func(self.stats.xmax)
if self.xlim_s is not None:
x_val = func([func(self.xlim_s), x_val])
# Plotting y-axis labels for absolute scales
if len(self.y_axis) == len(self.st):
for idx, s in zip(self.sorted_idx[start:stop], y_tick_labels):
plt.text(x=x_val, y=self.y_axis[idx], s=s, ha=ha, c=c,
fontsize=fontsize)
# Plotting y-axis labels for relative scales
elif len(self.y_axis) == len(y_tick_labels):
for y, s in zip(self.y_axis, y_tick_labels):
plt.text(x=x_val, y=y, s=s, ha=ha, c=c, fontsize=fontsize)
if loc == "y_axis_right":
self.ax.yaxis.tick_right()
self.ax.yaxis.set_label_position("right")
def _plot_title(self, nwav=None, page_num=None):
"""
Create the title of the plot based on event and station information
Allow dynamic creation of title based on user input parameters
TODO Can we make this two-column to save space?
:type nwav: int
:param nwav: if using subset, the title needs to know how many waveforms
it's showing on the page. self.plot() should tell it
:type page_num: int
:param page_num: same as nwav, we need to know what page number were on
"""
# Defines the number of waveforms plotted on a single page, allowing
# for subsets per page
if nwav is None:
nwav = len(self.sorted_idx)
# Allow appending page numbers to title
title_top = "RECORD SECTION"
if page_num:
title_top += f" PAGE {page_num:0>2}"
# The y-label will show baz or az depending on user choice, distinguish
if self.sort_by is not None and "backazimuth" in self.sort_by:
az_str = "BAZ"
else:
az_str = "AZ"
# Get the unique components that have been plotted, only
cmp = "".join(np.unique([self.st[i].stats.component
for i in self.sorted_idx]))
# Y_FMT will include time shift IF there are time shifts
y_fmt = f"Y_FMT: NET.STA.LOC.CHA|{az_str}|DIST"
if self.time_shift_s.sum() != 0:
y_fmt += "|TSHIFT"
title = "\n".join([
title_top,
f"{'/' * len(title_top*2)}",
f"ORIGINTIME: {min([tr.stats.starttime for tr in self.st])}",
f"{y_fmt}",
f"NWAV: {nwav}; NEVT: {self.stats.nevents}; "
f"NSTA: {self.stats.nstation}; COMP: {cmp}",
f"SORT_BY: {self.sort_by}; "
f"SCALE_BY: {self.scale_by} * {self.amplitude_scale_factor}",
f"FILT: [{self.min_period_s}, {self.max_period_s}]s; "
f"MOVE_OUT: {self.move_out or 0}{self.distance_units}/s",
])
self.ax.set_title(title)
def _set_plot_aesthetic(self):
"""
Give a nice look to the output figure by creating thick borders on the
axis, adjusting fontsize etc. All plot aesthetics should be placed here
so it's easiest to find.
.. note::
This was copy-pasted from Pyatoa.visuals.insp_plot.default_axes()
"""
ytick_fontsize = self.kwargs.get("ytick_fontsize", 8)
xtick_fontsize = self.kwargs.get("xtick_fontsize", 12)
tick_linewidth = self.kwargs.get("tick_linewidth", 1.5)
tick_length = self.kwargs.get("tick_length", 5)
tick_direction = self.kwargs.get("tick_direction", "in")
label_fontsize = self.kwargs.get("label_fontsize", 10)
axis_linewidth = self.kwargs.get("axis_linewidth", 2.)
title_fontsize = self.kwargs.get("title_fontsize", 10)
xtick_minor = self.kwargs.get("xtick_minor", 25)
xtick_major = self.kwargs.get("xtick_major", 100)
spine_zorder = self.kwargs.get("spine_zorder", 8)
# Re-set font sizes for labels already created
self.ax.title.set_fontsize(title_fontsize)
self.ax.tick_params(axis="both", which="both", width=tick_linewidth,
direction=tick_direction, length=tick_length)
self.ax.tick_params(axis="x", labelsize=xtick_fontsize)
self.ax.tick_params(axis="y", labelsize=ytick_fontsize)
self.ax.xaxis.label.set_size(label_fontsize)
# Thicken up the bounding axis lines
for axis in ["top", "bottom", "left", "right"]:
self.ax.spines[axis].set_linewidth(axis_linewidth)
# Set spines above azimuth bins
for spine in self.ax.spines.values():
spine.set_zorder(spine_zorder)
# Set xtick label major and minor which is assumed to be a time series
self.ax.xaxis.set_major_locator(MultipleLocator(xtick_major))
self.ax.xaxis.set_minor_locator(MultipleLocator(xtick_minor))
plt.grid(visible=True, which="major", axis="x", alpha=0.5, linewidth=1)
plt.grid(visible=True, which="minor", axis="x", alpha=0.2, linewidth=.5)
def plotw_rs(*args, **kwargs):
"""
Main call function. Run the record section plotting functions in order.
Contains the logic for breaking up figure into multiple pages.
"""
_start = datetime.now()
print(f"STARTING RECORD SECTION PLOTTER")
rs = RecordSection(*args, **kwargs)
rs.process_st()
rs.get_parameters()
# Simple case where all waveforms will fit on one page
if len(rs.sorted_idx) <= rs.max_traces_per_rs:
rs.plot()
# More complicated case where we need to split onto multiple pages
else:
for i, start in enumerate(np.arange(0, len(rs.st),
rs.max_traces_per_rs)):
stop = start + rs.max_traces_per_rs
# Case where the num waveforms is less than max_traces_per_rs
if stop < rs.max_traces_per_rs:
stop = len(rs.st)
rs.plot(subset=[start, stop], page_num=i+1)
_end = datetime.now()
print(f"FINISHED RECORD SECTION (t={_end - _start}s)")
def parse_args():
"""
Parse command line arguments to set record section parameters dynamically
This arg parser provides a simplified interface for working with plotw_rs
BUT it limits the flexibility of the code because things like long lists
are prohibitively verbose and not included in the arguments.
Kwargs can be passed in in the same format thanks to:
https://stackoverflow.com/questions/37367331/is-it-possible-to-use-\
argparse-to-capture-an-arbitrary-set-of-optional-arguments
.. note::
Not all parameters are set here, some are left as default values
Also some parameters are set different than the class defaults, so that
when the user runs record_section.py without arguments, they get a
reasonable result
.. note::
Do NOT use the command line if you want to exploit the expanded
capabilities of the record section plotter, rather script it or call
from an interactive environment.
"""
parser = argparse.ArgumentParser(
description="Input basic plotw_rs params",
formatter_class=argparse.RawTextHelpFormatter,
)
parser.add_argument("--pysep_path", default="./", type=str, nargs="?",
help="path to Pysep output, which is expected to "
"contain trace-wise SAC waveform files which will "
"be read")
parser.add_argument("--sort_by", default="distance", type=str, nargs="?",
help=textwrap.dedent("""
How to sort the Y-axis of the record section
- None: Not set, don't sort, just iterate directly through Stream
- 'alphabetical': sort alphabetically
- 'azimuth': sort by source-receiver azimuth (deg) with constant
vertical spacing
- 'backazimuth': sort by source-receiver backazimuth (deg) with
constant vertical spacing. Requires `azimuth_start_deg`
- 'distance': sort by source-receiver distance (km) with constant
vertical spacing. Requires `azimuth_start_deg` AND
`distance_units`
- 'abs_distance': absolute vertical spacing of waveforms defined by
source-receiver distance (km). Requires `distance_units`
- 'abs_azimuth': absolute vertical spacing of waveforms defined
by source-receiver azimuth (deg). Requires
`azimuth_start_deg`
- 'abs_backazimuth': absolute vertical spacing of waveforms by
source-receiver backazimuth (deg).
- '*_r': Add a '_r' to any of the values about to REVERSE the sort,
e.g., alphabetical_r sort will go Z->A"
""")
)
parser.add_argument("--scale_by", default="normalize", type=str, nargs="?",
help=textwrap.dedent("""
How to sort the Y-axis of the record section
- None: Not set, no amplitude scaling, waveforms shown raw
- 'normalize': scale each trace by the maximum amplitude,
i.e., > a /= max(abs(a)) # where 'a' is time series amplitudes
- 'global_norm': scale by the largest amplitude to be displayed on
the screen. Will not consider waveforms which have been
excluded on other basis (e.g., wrong component)
- 'geometric_spreading': scale amplitudes globally by predicting the
expected geometric spreading amplitude reduction and correcting
for this factor. Requires `geometric_spreading_factor`, optional
`geometric_spreading_k_val`
""")
)
parser.add_argument("--time_shift_s", default=None, type=float, nargs="?",
help="Set a constant time shift in unit: seconds")
parser.add_argument("--move_out", default=None, type=float, nargs="?",
help="Set a constant velocity-based move out in units:"
"`distance_units`/s")
parser.add_argument("--min_period_s", default=None, type=float, nargs="?",
help="Minimum filter period in unit seconds.")
parser.add_argument("--max_period_s", default=None, type=float, nargs="?",
help="Maximum filter period in unit seconds.")
parser.add_argument("--max_traces_per_rs", default=None, nargs="?",
help="Max waveforms to show on one page. If the number "
"of waveforms to show exceeds this value, "
"multiple pages will be saved")
parser.add_argument("--integrate", default=0, type=int, nargs="?",
help="Integrate (positive values) or differentiate "
"(negative values) `integrate` times. e.g., -2 "
"will differentiate all waveforms twice.")
parser.add_argument("--xlim_s", default=None, type=int, nargs="+",
help="Min and max x limits in units seconds. Input as "
"a list, e.g., --xlim_s 10 200 ...")
parser.add_argument("--components", default="ZRTNE12", type=str, nargs="?",
help="Ordered component list specifying 1) which "
"components will be shown, and in what order. "
"e.g., 'ZR' will show only Z and R components "
"with Z sorted above R.")
parser.add_argument("--y_label_loc", default="default", type=str, nargs="?",
help="Station information label location on the y-axis")
parser.add_argument("--y_axis_spacing", default=1, type=float, nargs="?",
help="For relative sorting, the y-axis spacing between "
"adjacent seismograms. If waveforms are "
"normalized then a default value of 1 is usually "
"normalized then a default value of 1 is usually "
"fine")
parser.add_argument("--amplitude_scale_factor", default=1, type=float,
nargs="?",
help="A user dial allowing waveform amplitudes to be"
"scaled by an arbitrary float value")
parser.add_argument("--azimuth_start_deg", default=0, type=float,
nargs="?",
help="When sorting by azimuth, choose the default "
"starting value, with azimuth 0 <= az <= 360")
parser.add_argument("--distance_units", default="km", type=str,
nargs="?", help="Set units when sorting by distance")
parser.add_argument("--save", default="./record_section.png", type=str,
nargs="?",
help="Path to save the resulting record section fig")
parser.add_argument("--overwrite", default=False, action="store_true",
help="overwrite existing figure if path exists")
# Keyword arguments can be passed directly to the argparser in the same
# format as the above kwargs (e.g., --linewidth 2), but they will not have
# help messages or type checking
parsed, unknown = parser.parse_known_args()
for arg in unknown:
if arg.startswith(("-", "--")):
parser.add_argument(arg.split("=")[0])
return parser.parse_args()
if __name__ == "__main__":
plotw_rs(**vars(parse_args()))
|
import os
import sys
import time
import random
import string
import argparse
import torch
import torch.backends.cudnn as cudnn
import torch.nn.init as init
import torch.optim as optim
import torch.utils.data
import numpy as np
from utils import CTCLabelConverter, AttnLabelConverter, Averager
from dataset import hierarchical_dataset, AlignCollate, Batch_Balanced_Dataset
from model import Model
from test import validation
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def train(opt):
""" dataset preparation """
if not opt.data_filtering_off:
print('Filtering the images containing characters which are not in opt.character')
print('Filtering the images whose label is longer than opt.batch_max_length')
# see https://github.com/clovaai/deep-text-recognition-benchmark/blob/master/dataset.py#L130
opt.select_data = opt.select_data.split('-')
opt.batch_ratio = opt.batch_ratio.split('-')
train_dataset = Batch_Balanced_Dataset(opt)
AlignCollate_valid = AlignCollate(imgH=opt.imgH, imgW=opt.imgW, keep_ratio_with_pad=opt.PAD)
valid_dataset = hierarchical_dataset(root=opt.valid_data, opt=opt)
valid_loader = torch.utils.data.DataLoader(
valid_dataset, batch_size=opt.batch_size,
shuffle=True, # 'True' to check training progress with validation function.
num_workers=int(opt.workers),
collate_fn=AlignCollate_valid, pin_memory=True)
print('-' * 80)
""" model configuration """
if 'CTC' in opt.Prediction:
converter = CTCLabelConverter(opt.character)
else:
converter = AttnLabelConverter(opt.character)
opt.num_class = len(converter.character)
if opt.rgb:
opt.input_channel = 3
model = Model(opt)
print('model input parameters', opt.imgH, opt.imgW, opt.num_fiducial, opt.input_channel, opt.output_channel,
opt.hidden_size, opt.num_class, opt.batch_max_length, opt.Transformation, opt.FeatureExtraction,
opt.SequenceModeling, opt.Prediction)
# weight initialization
for name, param in model.named_parameters():
if 'localization_fc2' in name:
print(f'Skip {name} as it is already initialized')
continue
try:
if 'bias' in name:
init.constant_(param, 0.0)
elif 'weight' in name:
init.kaiming_normal_(param)
except Exception as e: # for batchnorm.
if 'weight' in name:
param.data.fill_(1)
continue
# data parallel for multi-GPU
model = torch.nn.DataParallel(model).to(device)
model.train()
if opt.saved_model != '':
print(f'loading pretrained model from {opt.saved_model}')
if opt.FT:
model_state_dict = torch.load(opt.saved_model)
if opt.imgW != 100: # disable GridGenerator
for old_key in list(model_state_dict.keys()):
if old_key.startswith('module.Transformation.GridGenerator'):
new_key = '_' + old_key
model_state_dict[new_key] = model_state_dict.pop(old_key)
if opt.character != '0123456789abcdefghijklmnopqrstuvwxyz': # disable GridGenerator
for old_key in list(model_state_dict.keys()):
if old_key.startswith('module.Prediction.attention_cell.rnn') or old_key.startswith('module.Prediction.generator'):
new_key = '_' + old_key
model_state_dict[new_key] = model_state_dict.pop(old_key)
model.load_state_dict(model_state_dict, strict=False)
else:
model.load_state_dict(torch.load(opt.saved_model))
print("Model:")
print(model)
""" setup loss """
if 'CTC' in opt.Prediction:
criterion = torch.nn.CTCLoss(zero_infinity=True).to(device)
else:
criterion = torch.nn.CrossEntropyLoss(ignore_index=0).to(device) # ignore [GO] token = ignore index 0
# loss averager
loss_avg = Averager()
# filter that only require gradient decent
filtered_parameters = []
params_num = []
for p in filter(lambda p: p.requires_grad, model.parameters()):
filtered_parameters.append(p)
params_num.append(np.prod(p.size()))
print('Trainable params num : ', sum(params_num))
# [print(name, p.numel()) for name, p in filter(lambda p: p[1].requires_grad, model.named_parameters())]
# setup optimizer
if opt.adam:
optimizer = optim.Adam(filtered_parameters, lr=opt.lr, betas=(opt.beta1, 0.999))
else:
optimizer = optim.Adadelta(filtered_parameters, lr=opt.lr, rho=opt.rho, eps=opt.eps)
print("Optimizer:")
print(optimizer)
""" final options """
# print(opt)
with open(f'./saved_models/{opt.experiment_name}/opt.txt', 'a') as opt_file:
opt_log = '------------ Options -------------\n'
args = vars(opt)
for k, v in args.items():
opt_log += f'{str(k)}: {str(v)}\n'
opt_log += '---------------------------------------\n'
print(opt_log)
opt_file.write(opt_log)
""" start training """
start_iter = 0
if opt.saved_model != '':
start_iter = int(opt.saved_model.split('_')[-1].split('.')[0])
print(f'continue to train, start_iter: {start_iter}')
start_time = time.time()
best_accuracy = -1
best_norm_ED = 1e+6
i = start_iter
while(True):
# train part
image_tensors, labels, _ = train_dataset.get_batch()
image = image_tensors.to(device)
text, length = converter.encode(labels, batch_max_length=opt.batch_max_length)
text = text.to(device)
length = length.to(device)
batch_size = image.size(0)
if 'CTC' in opt.Prediction:
preds = model(image, text).log_softmax(2)
preds_size = torch.IntTensor([preds.size(1)] * batch_size)
preds = preds.permute(1, 0, 2)
# (ctc_a) For PyTorch 1.2.0 and 1.3.0. To avoid ctc_loss issue, disabled cudnn for the computation of the ctc_loss
# https://github.com/jpuigcerver/PyLaia/issues/16
torch.backends.cudnn.enabled = False
cost = criterion(preds, text.to(device), preds_size.to(device), length.to(device))
torch.backends.cudnn.enabled = True
# # (ctc_b) To reproduce our pretrained model / paper, use our previous code (below code) instead of (ctc_a).
# # With PyTorch 1.2.0, the below code occurs NAN, so you may use PyTorch 1.1.0.
# # Thus, the result of CTCLoss is different in PyTorch 1.1.0 and PyTorch 1.2.0.
# # See https://github.com/clovaai/deep-text-recognition-benchmark/issues/56#issuecomment-526490707
# cost = criterion(preds, text, preds_size, length)
else:
preds = model(image, text[:, :-1]) # align with Attention.forward
target = text[:, 1:] # without [GO] Symbol
cost = criterion(preds.view(-1, preds.shape[-1]), target.contiguous().view(-1))
model.zero_grad()
cost.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), opt.grad_clip) # gradient clipping with 5 (Default)
optimizer.step()
loss_avg.add(cost)
# validation part
if i % opt.valInterval == 0:
elapsed_time = time.time() - start_time
# for log
with open(f'./saved_models/{opt.experiment_name}/log_train.txt', 'a') as log:
model.eval()
with torch.no_grad():
valid_loss, current_accuracy, current_norm_ED, preds, confidence_score, labels, infer_time, length_of_data = validation(
model, criterion, valid_loader, converter, opt)
model.train()
# training loss and validation loss
loss_log = f'[{i}/{opt.num_iter}] Train loss: {loss_avg.val():0.5f}, Valid loss: {valid_loss:0.5f}, Elapsed_time: {elapsed_time:0.5f}'
print(loss_log)
log.write(loss_log + '\n')
loss_avg.reset()
current_model_log = f'{'Current_accuracy':17s}: {current_accuracy:0.3f}, {'Current_norm_ED':17s}: {current_norm_ED:0.2f}'
print(current_model_log)
log.write(current_model_log + '\n')
# keep best accuracy model (on valid dataset)
if current_accuracy > best_accuracy:
best_accuracy = current_accuracy
torch.save(model.state_dict(), f'./saved_models/{opt.experiment_name}/best_accuracy.pth')
if current_norm_ED < best_norm_ED:
best_norm_ED = current_norm_ED
torch.save(model.state_dict(), f'./saved_models/{opt.experiment_name}/best_norm_ED.pth')
best_model_log = f'{'Best_accuracy':17s}: {best_accuracy:0.3f}, {'Best_norm_ED':17s}: {best_norm_ED:0.2f}'
print(best_model_log)
log.write(best_model_log + '\n')
# show some predicted results
print('-' * 80)
print(f'{'Ground Truth':25s} | {'Prediction':25s} | Confidence Score & T/F')
log.write(f'{'Ground Truth':25s} | {'Prediction':25s} | {'Confidence Score'}\n')
print('-' * 80)
for gt, pred, confidence in zip(labels[:5], preds[:5], confidence_score[:5]):
if 'Attn' in opt.Prediction:
gt = gt[:gt.find('[s]')]
pred = pred[:pred.find('[s]')]
print(f'{gt:25s} | {pred:25s} | {confidence:0.4f}\t{str(pred == gt)}')
log.write(f'{gt:25s} | {pred:25s} | {confidence:0.4f}\t{str(pred == gt)}\n')
print('-' * 80)
# save model per 1e+5 iter.
if (i + 1) % 1e+5 == 0:
torch.save(
model.state_dict(), f'./saved_models/{opt.experiment_name}/iter_{i+1}.pth')
if i == opt.num_iter:
print('end the training')
sys.exit()
i += 1
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--experiment_name', help='Where to store logs and models')
parser.add_argument('--train_data', required=True, help='path to training dataset')
parser.add_argument('--valid_data', required=True, help='path to validation dataset')
parser.add_argument('--manualSeed', type=int, default=1111, help='for random seed setting')
parser.add_argument('--workers', type=int, help='number of data loading workers', default=4)
parser.add_argument('--batch_size', type=int, default=192, help='input batch size')
parser.add_argument('--num_iter', type=int, default=300000, help='number of iterations to train for')
parser.add_argument('--valInterval', type=int, default=2000, help='Interval between each validation')
parser.add_argument('--saved_model', default='', help="path to model to continue training")
parser.add_argument('--FT', action='store_true', help='whether to do fine-tuning')
parser.add_argument('--adam', action='store_true', help='Whether to use adam (default is Adadelta)')
parser.add_argument('--lr', type=float, default=1, help='learning rate, default=1.0 for Adadelta')
parser.add_argument('--beta1', type=float, default=0.9, help='beta1 for adam. default=0.9')
parser.add_argument('--rho', type=float, default=0.95, help='decay rate rho for Adadelta. default=0.95')
parser.add_argument('--eps', type=float, default=1e-8, help='eps for Adadelta. default=1e-8')
parser.add_argument('--grad_clip', type=float, default=5, help='gradient clipping value. default=5')
""" Data processing """
parser.add_argument('--select_data', type=str, default='MJ-ST',
help='select training data (default is MJ-ST, which means MJ and ST used as training data)')
parser.add_argument('--batch_ratio', type=str, default='0.5-0.5',
help='assign ratio for each selected data in the batch')
parser.add_argument('--total_data_usage_ratio', type=str, default='1.0',
help='total data usage ratio, this ratio is multiplied to total number of data.')
parser.add_argument('--batch_max_length', type=int, default=25, help='maximum-label-length')
parser.add_argument('--imgH', type=int, default=32, help='the height of the input image')
parser.add_argument('--imgW', type=int, default=100, help='the width of the input image')
parser.add_argument('--rgb', action='store_true', help='use rgb input')
parser.add_argument('--character', type=str, default='0123456789abcdefghijklmnopqrstuvwxyz', help='character label')
parser.add_argument('--sensitive', action='store_true', help='for sensitive character mode')
parser.add_argument('--PAD', action='store_true', help='whether to keep ratio then pad for image resize')
parser.add_argument('--data_filtering_off', action='store_true', help='for data_filtering_off mode')
""" Model Architecture """
parser.add_argument('--Transformation', type=str, required=True, help='Transformation stage. None|TPS')
parser.add_argument('--FeatureExtraction', type=str, required=True, help='FeatureExtraction stage. VGG|RCNN|ResNet')
parser.add_argument('--SequenceModeling', type=str, required=True, help='SequenceModeling stage. None|BiLSTM')
parser.add_argument('--Prediction', type=str, required=True, help='Prediction stage. CTC|Attn')
parser.add_argument('--num_fiducial', type=int, default=20, help='number of fiducial points of TPS-STN')
parser.add_argument('--input_channel', type=int, default=1, help='the number of input channel of Feature extractor')
parser.add_argument('--output_channel', type=int, default=512,
help='the number of output channel of Feature extractor')
parser.add_argument('--hidden_size', type=int, default=256, help='the size of the LSTM hidden state')
parser.add_argument('--results_path', required=True, help="path to save results")
opt = parser.parse_args()
if not opt.experiment_name:
opt.experiment_name = f'{opt.Transformation}-{opt.FeatureExtraction}-{opt.SequenceModeling}-{opt.Prediction}'
opt.experiment_name += f'-Seed{opt.manualSeed}'
# print(opt.experiment_name)
os.makedirs(f'./saved_models/{opt.experiment_name}', exist_ok=True)
""" vocab / character number configuration """
if opt.sensitive:
# opt.character += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
opt.character = string.printable[:-6] # same with ASTER setting (use 94 char).
""" Seed and GPU setting """
# print("Random Seed: ", opt.manualSeed)
random.seed(opt.manualSeed)
np.random.seed(opt.manualSeed)
torch.manual_seed(opt.manualSeed)
torch.cuda.manual_seed(opt.manualSeed)
cudnn.benchmark = True
cudnn.deterministic = True
opt.num_gpu = torch.cuda.device_count()
# print('device count', opt.num_gpu)
if opt.num_gpu > 1:
print('------ Use multi-GPU setting ------')
print('if you stuck too long time with multi-GPU setting, try to set --workers 0')
# check multi-GPU issue https://github.com/clovaai/deep-text-recognition-benchmark/issues/1
opt.workers = opt.workers * opt.num_gpu
opt.batch_size = opt.batch_size * opt.num_gpu
""" previous version
print('To equlize batch stats to 1-GPU setting, the batch_size is multiplied with num_gpu and multiplied batch_size is ', opt.batch_size)
opt.batch_size = opt.batch_size * opt.num_gpu
print('To equalize the number of epochs to 1-GPU setting, num_iter is divided with num_gpu by default.')
If you dont care about it, just commnet out these line.)
opt.num_iter = int(opt.num_iter / opt.num_gpu)
"""
train(opt)
| import os
import sys
import time
import random
import string
import argparse
import torch
import torch.backends.cudnn as cudnn
import torch.nn.init as init
import torch.optim as optim
import torch.utils.data
import numpy as np
from utils import CTCLabelConverter, AttnLabelConverter, Averager
from dataset import hierarchical_dataset, AlignCollate, Batch_Balanced_Dataset
from model import Model
from test import validation
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def train(opt):
""" dataset preparation """
if not opt.data_filtering_off:
print('Filtering the images containing characters which are not in opt.character')
print('Filtering the images whose label is longer than opt.batch_max_length')
# see https://github.com/clovaai/deep-text-recognition-benchmark/blob/master/dataset.py#L130
opt.select_data = opt.select_data.split('-')
opt.batch_ratio = opt.batch_ratio.split('-')
train_dataset = Batch_Balanced_Dataset(opt)
AlignCollate_valid = AlignCollate(imgH=opt.imgH, imgW=opt.imgW, keep_ratio_with_pad=opt.PAD)
valid_dataset = hierarchical_dataset(root=opt.valid_data, opt=opt)
valid_loader = torch.utils.data.DataLoader(
valid_dataset, batch_size=opt.batch_size,
shuffle=True, # 'True' to check training progress with validation function.
num_workers=int(opt.workers),
collate_fn=AlignCollate_valid, pin_memory=True)
print('-' * 80)
""" model configuration """
if 'CTC' in opt.Prediction:
converter = CTCLabelConverter(opt.character)
else:
converter = AttnLabelConverter(opt.character)
opt.num_class = len(converter.character)
if opt.rgb:
opt.input_channel = 3
model = Model(opt)
print('model input parameters', opt.imgH, opt.imgW, opt.num_fiducial, opt.input_channel, opt.output_channel,
opt.hidden_size, opt.num_class, opt.batch_max_length, opt.Transformation, opt.FeatureExtraction,
opt.SequenceModeling, opt.Prediction)
# weight initialization
for name, param in model.named_parameters():
if 'localization_fc2' in name:
print(f'Skip {name} as it is already initialized')
continue
try:
if 'bias' in name:
init.constant_(param, 0.0)
elif 'weight' in name:
init.kaiming_normal_(param)
except Exception as e: # for batchnorm.
if 'weight' in name:
param.data.fill_(1)
continue
# data parallel for multi-GPU
model = torch.nn.DataParallel(model).to(device)
model.train()
if opt.saved_model != '':
print(f'loading pretrained model from {opt.saved_model}')
if opt.FT:
model_state_dict = torch.load(opt.saved_model)
if opt.imgW != 100: # disable GridGenerator
for old_key in list(model_state_dict.keys()):
if old_key.startswith('module.Transformation.GridGenerator'):
new_key = '_' + old_key
model_state_dict[new_key] = model_state_dict.pop(old_key)
if opt.character != '0123456789abcdefghijklmnopqrstuvwxyz': # disable GridGenerator
for old_key in list(model_state_dict.keys()):
if old_key.startswith('module.Prediction.attention_cell.rnn') or old_key.startswith('module.Prediction.generator'):
new_key = '_' + old_key
model_state_dict[new_key] = model_state_dict.pop(old_key)
model.load_state_dict(model_state_dict, strict=False)
else:
model.load_state_dict(torch.load(opt.saved_model))
print("Model:")
print(model)
""" setup loss """
if 'CTC' in opt.Prediction:
criterion = torch.nn.CTCLoss(zero_infinity=True).to(device)
else:
criterion = torch.nn.CrossEntropyLoss(ignore_index=0).to(device) # ignore [GO] token = ignore index 0
# loss averager
loss_avg = Averager()
# filter that only require gradient decent
filtered_parameters = []
params_num = []
for p in filter(lambda p: p.requires_grad, model.parameters()):
filtered_parameters.append(p)
params_num.append(np.prod(p.size()))
print('Trainable params num : ', sum(params_num))
# [print(name, p.numel()) for name, p in filter(lambda p: p[1].requires_grad, model.named_parameters())]
# setup optimizer
if opt.adam:
optimizer = optim.Adam(filtered_parameters, lr=opt.lr, betas=(opt.beta1, 0.999))
else:
optimizer = optim.Adadelta(filtered_parameters, lr=opt.lr, rho=opt.rho, eps=opt.eps)
print("Optimizer:")
print(optimizer)
""" final options """
# print(opt)
with open(f'./saved_models/{opt.experiment_name}/opt.txt', 'a') as opt_file:
opt_log = '------------ Options -------------\n'
args = vars(opt)
for k, v in args.items():
opt_log += f'{str(k)}: {str(v)}\n'
opt_log += '---------------------------------------\n'
print(opt_log)
opt_file.write(opt_log)
""" start training """
start_iter = 0
if opt.saved_model != '':
start_iter = int(opt.saved_model.split('_')[-1].split('.')[0])
print(f'continue to train, start_iter: {start_iter}')
start_time = time.time()
best_accuracy = -1
best_norm_ED = 1e+6
i = start_iter
while(True):
# train part
image_tensors, labels, _ = train_dataset.get_batch()
image = image_tensors.to(device)
text, length = converter.encode(labels, batch_max_length=opt.batch_max_length)
text = text.to(device)
length = length.to(device)
batch_size = image.size(0)
if 'CTC' in opt.Prediction:
preds = model(image, text).log_softmax(2)
preds_size = torch.IntTensor([preds.size(1)] * batch_size)
preds = preds.permute(1, 0, 2)
# (ctc_a) For PyTorch 1.2.0 and 1.3.0. To avoid ctc_loss issue, disabled cudnn for the computation of the ctc_loss
# https://github.com/jpuigcerver/PyLaia/issues/16
torch.backends.cudnn.enabled = False
cost = criterion(preds, text.to(device), preds_size.to(device), length.to(device))
torch.backends.cudnn.enabled = True
# # (ctc_b) To reproduce our pretrained model / paper, use our previous code (below code) instead of (ctc_a).
# # With PyTorch 1.2.0, the below code occurs NAN, so you may use PyTorch 1.1.0.
# # Thus, the result of CTCLoss is different in PyTorch 1.1.0 and PyTorch 1.2.0.
# # See https://github.com/clovaai/deep-text-recognition-benchmark/issues/56#issuecomment-526490707
# cost = criterion(preds, text, preds_size, length)
else:
preds = model(image, text[:, :-1]) # align with Attention.forward
target = text[:, 1:] # without [GO] Symbol
cost = criterion(preds.view(-1, preds.shape[-1]), target.contiguous().view(-1))
model.zero_grad()
cost.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), opt.grad_clip) # gradient clipping with 5 (Default)
optimizer.step()
loss_avg.add(cost)
# validation part
if i % opt.valInterval == 0:
elapsed_time = time.time() - start_time
# for log
with open(f'./saved_models/{opt.experiment_name}/log_train.txt', 'a') as log:
model.eval()
with torch.no_grad():
valid_loss, current_accuracy, current_norm_ED, preds, confidence_score, labels, infer_time, length_of_data = validation(
model, criterion, valid_loader, converter, opt)
model.train()
# training loss and validation loss
loss_log = f'[{i}/{opt.num_iter}] Train loss: {loss_avg.val():0.5f}, Valid loss: {valid_loss:0.5f}, Elapsed_time: {elapsed_time:0.5f}'
print(loss_log)
log.write(loss_log + '\n')
loss_avg.reset()
current_model_log = f'{"Current_accuracy":17s}: {current_accuracy:0.3f}, {"Current_norm_ED":17s}: {current_norm_ED:0.2f}'
print(current_model_log)
log.write(current_model_log + '\n')
# keep best accuracy model (on valid dataset)
if current_accuracy > best_accuracy:
best_accuracy = current_accuracy
torch.save(model.state_dict(), f'./saved_models/{opt.experiment_name}/best_accuracy.pth')
if current_norm_ED < best_norm_ED:
best_norm_ED = current_norm_ED
torch.save(model.state_dict(), f'./saved_models/{opt.experiment_name}/best_norm_ED.pth')
best_model_log = f'{"Best_accuracy":17s}: {best_accuracy:0.3f}, {"Best_norm_ED":17s}: {best_norm_ED:0.2f}'
print(best_model_log)
log.write(best_model_log + '\n')
# show some predicted results
print('-' * 80)
print(f'{"Ground Truth":25s} | {"Prediction":25s} | Confidence Score & T/F')
log.write(f'{"Ground Truth":25s} | {"Prediction":25s} | {"Confidence Score"}\n')
print('-' * 80)
for gt, pred, confidence in zip(labels[:5], preds[:5], confidence_score[:5]):
if 'Attn' in opt.Prediction:
gt = gt[:gt.find('[s]')]
pred = pred[:pred.find('[s]')]
print(f'{gt:25s} | {pred:25s} | {confidence:0.4f}\t{str(pred == gt)}')
log.write(f'{gt:25s} | {pred:25s} | {confidence:0.4f}\t{str(pred == gt)}\n')
print('-' * 80)
# save model per 1e+5 iter.
if (i + 1) % 1e+5 == 0:
torch.save(
model.state_dict(), f'./saved_models/{opt.experiment_name}/iter_{i+1}.pth')
if i == opt.num_iter:
print('end the training')
sys.exit()
i += 1
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--experiment_name', help='Where to store logs and models')
parser.add_argument('--train_data', required=True, help='path to training dataset')
parser.add_argument('--valid_data', required=True, help='path to validation dataset')
parser.add_argument('--manualSeed', type=int, default=1111, help='for random seed setting')
parser.add_argument('--workers', type=int, help='number of data loading workers', default=4)
parser.add_argument('--batch_size', type=int, default=192, help='input batch size')
parser.add_argument('--num_iter', type=int, default=300000, help='number of iterations to train for')
parser.add_argument('--valInterval', type=int, default=2000, help='Interval between each validation')
parser.add_argument('--saved_model', default='', help="path to model to continue training")
parser.add_argument('--FT', action='store_true', help='whether to do fine-tuning')
parser.add_argument('--adam', action='store_true', help='Whether to use adam (default is Adadelta)')
parser.add_argument('--lr', type=float, default=1, help='learning rate, default=1.0 for Adadelta')
parser.add_argument('--beta1', type=float, default=0.9, help='beta1 for adam. default=0.9')
parser.add_argument('--rho', type=float, default=0.95, help='decay rate rho for Adadelta. default=0.95')
parser.add_argument('--eps', type=float, default=1e-8, help='eps for Adadelta. default=1e-8')
parser.add_argument('--grad_clip', type=float, default=5, help='gradient clipping value. default=5')
""" Data processing """
parser.add_argument('--select_data', type=str, default='MJ-ST',
help='select training data (default is MJ-ST, which means MJ and ST used as training data)')
parser.add_argument('--batch_ratio', type=str, default='0.5-0.5',
help='assign ratio for each selected data in the batch')
parser.add_argument('--total_data_usage_ratio', type=str, default='1.0',
help='total data usage ratio, this ratio is multiplied to total number of data.')
parser.add_argument('--batch_max_length', type=int, default=25, help='maximum-label-length')
parser.add_argument('--imgH', type=int, default=32, help='the height of the input image')
parser.add_argument('--imgW', type=int, default=100, help='the width of the input image')
parser.add_argument('--rgb', action='store_true', help='use rgb input')
parser.add_argument('--character', type=str, default='0123456789abcdefghijklmnopqrstuvwxyz', help='character label')
parser.add_argument('--sensitive', action='store_true', help='for sensitive character mode')
parser.add_argument('--PAD', action='store_true', help='whether to keep ratio then pad for image resize')
parser.add_argument('--data_filtering_off', action='store_true', help='for data_filtering_off mode')
""" Model Architecture """
parser.add_argument('--Transformation', type=str, required=True, help='Transformation stage. None|TPS')
parser.add_argument('--FeatureExtraction', type=str, required=True, help='FeatureExtraction stage. VGG|RCNN|ResNet')
parser.add_argument('--SequenceModeling', type=str, required=True, help='SequenceModeling stage. None|BiLSTM')
parser.add_argument('--Prediction', type=str, required=True, help='Prediction stage. CTC|Attn')
parser.add_argument('--num_fiducial', type=int, default=20, help='number of fiducial points of TPS-STN')
parser.add_argument('--input_channel', type=int, default=1, help='the number of input channel of Feature extractor')
parser.add_argument('--output_channel', type=int, default=512,
help='the number of output channel of Feature extractor')
parser.add_argument('--hidden_size', type=int, default=256, help='the size of the LSTM hidden state')
parser.add_argument('--results_path', required=True, help="path to save results")
opt = parser.parse_args()
if not opt.experiment_name:
opt.experiment_name = f'{opt.Transformation}-{opt.FeatureExtraction}-{opt.SequenceModeling}-{opt.Prediction}'
opt.experiment_name += f'-Seed{opt.manualSeed}'
# print(opt.experiment_name)
os.makedirs(f'./saved_models/{opt.experiment_name}', exist_ok=True)
""" vocab / character number configuration """
if opt.sensitive:
# opt.character += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
opt.character = string.printable[:-6] # same with ASTER setting (use 94 char).
""" Seed and GPU setting """
# print("Random Seed: ", opt.manualSeed)
random.seed(opt.manualSeed)
np.random.seed(opt.manualSeed)
torch.manual_seed(opt.manualSeed)
torch.cuda.manual_seed(opt.manualSeed)
cudnn.benchmark = True
cudnn.deterministic = True
opt.num_gpu = torch.cuda.device_count()
# print('device count', opt.num_gpu)
if opt.num_gpu > 1:
print('------ Use multi-GPU setting ------')
print('if you stuck too long time with multi-GPU setting, try to set --workers 0')
# check multi-GPU issue https://github.com/clovaai/deep-text-recognition-benchmark/issues/1
opt.workers = opt.workers * opt.num_gpu
opt.batch_size = opt.batch_size * opt.num_gpu
""" previous version
print('To equlize batch stats to 1-GPU setting, the batch_size is multiplied with num_gpu and multiplied batch_size is ', opt.batch_size)
opt.batch_size = opt.batch_size * opt.num_gpu
print('To equalize the number of epochs to 1-GPU setting, num_iter is divided with num_gpu by default.')
If you dont care about it, just commnet out these line.)
opt.num_iter = int(opt.num_iter / opt.num_gpu)
"""
train(opt)
|
import pandas as pd
from matplotlib import pyplot as plt
import os
import sys
import seaborn as sns
import json
import argparse
from dotmap import DotMap
import numpy as np
# ================================================================
# SETTINGS
# ================================================================
settings = DotMap()
# PLOT
# ----------------------------------------
settings.plot.colors = {
'frank_crossentropy' : '#F00',
'frank_cka' : '#F60',
'ps_inv_crossentropy' : '#00F',
'ps_inv_cka' : '#06F'
}
settings.plot.rename_dict = {
'frank_crossentropy' : 'With Task Loss - Cross-entropy',
'ps_inv_crossentropy' : 'Linear Least Squares - Cross-entropy',
'frank_cka' : 'With Task Loss - CKA',
'ps_inv_cka' : 'Linear Least Squares - CKA'
}
settings.plot.linewidth = 5
settings.plot.ce_linestyle = '-'
settings.plot.cka_linestyle = '--'
settings.plot.x_label = 'Layer'
settings.plot.y_label_left = 'CKA between stiched layers'
settings.plot.y_label_right = 'Cross-entropy'
# MEAN & STD TABLE
# ----------------------------------------
settings.mean_std_table.caption = 'Mean metrics with standard deviations in parentheses.'
settings.mean_std_table.column_names = ['Cross-entropy', 'CKA'] # Order cannot be changed this way
settings.mean_std_table.row_names = ['Ps. Inv', 'Frank'] # Order cannot be changed this way
# LAYERWISE TABLE
settings.layerwise_table.caption = 'Effect on logits, layerwise split on Frank stitches.'
settings.layerwise_table.column_names = {'crossentropy' : 'Cross-entropy', 'cka' : 'CKA'}
# ================================================================
# PROCESSING
# ================================================================
def parse_args(args):
parser = argparse.ArgumentParser(description='Simple settings.')
parser.add_argument('--csv', default="results/official/resnet20_w1_bn/summary.csv")
parser.add_argument('--out-dir', default='results/official/plots/resnet20_w1_bn_cka_vs_ce/')
return parser.parse_args(args)
def filter_df(df):
filters = [
df.l1 == 0.,
df.target_type=='soft_2',
df.init =='ps_inv',
(df.front_layer.str.contains('add'))|(df.front_layer=='bn1'),
(df.end_layer.str.contains('add'))|(df.end_layer=='bn1'),
df.front_model != df.end_model,
df.temperature == 1.0,
]
return df[np.logical_and.reduce(filters)]
def get_df(csv, out_dir):
# Filter csv to relevant parts
filtered_df = filter_df(pd.read_csv(csv))
filtered_df['front_layer'] = filtered_df['front_layer'].str.capitalize()
filtered_df = filtered_df.sort_values(['front_layer']).copy()
# Calculate accuracies
df = filtered_df.copy()
df['frank_cka'] = df['cka_frank']
df['ps_inv_cka'] = df['cka_ps_inv']
df['frank_crossentropy'] = df['after_crossentropy']
df['ps_inv_crossentropy'] = df['ps_inv_crossentropy']
# Rename columns in local dataframe
# df = df.rename(columns={
# 'after_cka' : 'frank_cka'
# })
# Group values into one column with a category column
def make_one_col(column):
new_df = df[['front_layer', column]].copy()
new_df['matrix'] = column
new_df['style'] = 'crossentropy' if 'crossentropy' in column else 'cka'
new_df = new_df.rename(columns={column : 'value'})
return new_df
dfs = [
make_one_col('frank_crossentropy'),
make_one_col('frank_cka'),
make_one_col('ps_inv_crossentropy'),
make_one_col('ps_inv_cka'),
]
sum_df = pd.concat(dfs, ignore_index=True).reset_index(drop=True)
# Save
filtered_df.to_csv(os.path.join(out_dir, 'filtered_df.csv'), index=False)
sum_df.to_csv(os.path.join(out_dir, 'sum_df.csv'), index=False)
return filtered_df, sum_df
def save_table_mean_std(df, out_dir):
global settings
conf = settings.mean_std_table
out_file = os.path.join(out_dir, 'overall_mean_std.tex')
# Generatre mean and std
df = df.copy()
df = df.groupby(['matrix'])['value'].describe()[['mean', 'std']].copy()
# Create table in desired format
_mean = lambda x: f"{df.loc[x, "mean"]:0.3f}"
_std = lambda x: f"(\pm{df.loc[x, "std"]:0.3f})"
_cell = lambda x: f"{_mean(x)} {_std(x)}"
_row = lambda x: [_cell(x+'_crossentropy'), _cell(x+'_cka')]
new_df = pd.DataFrame({
conf.row_names[0] : _row('ps_inv'),
conf.row_names[1] : _row('frank')
}, index=conf.column_names)
# Convert table to latex
table_latex = new_df.to_latex(escape=False, column_format='l c c')
# Place the latex table in a figure and add captopn
latex = "\\begin{table}\n\\centering\n" + table_latex + \
" \\caption{" + conf.caption + "}\n" + \
" \\label{fig:my_label}\n" + \
"\\end{table}"
# Save
with open(out_file, "w") as text_file:
print(latex, file=text_file)
def save_table_layerwise(df, out_dir):
global settings
conf = settings.layerwise_table
out_file = os.path.join(out_dir, 'layerwise_mean_std.tex')
df = df.copy()
# Create CKA/Acc and PsInv/Frank categories
df['mode'] = df.matrix.apply(lambda x: x.split('_')[-1])
df['method'] = df.matrix.apply(lambda x: '_'.join(x.split('_')[:-1]))
# Available layers in order
layers = df['front_layer'].drop_duplicates().sort_values()
# Create dataframe
new_df = pd.DataFrame(index=layers)
for layer in layers:
for mode in df['mode'].drop_duplicates():
# Filter ps_inv and frank
subdf = df[(df.front_layer==layer)&(df['mode']==mode)]
ps_inv = subdf[subdf.method == 'ps_inv']['value'].reset_index(drop=True)
frank = subdf[subdf.method == 'frank']['value'].reset_index(drop=True)
# Get mode spcific changes (e.g. % mark)
mark = '\%' if mode=='cka' else ''
multiplier = 100 if mode=='cka' else 1
# Caulculate mean and std
mean = (frank-ps_inv).mean() * multiplier
std = (frank-ps_inv).std() * multiplier
# Insert variable in table
val = f"{mean:1.3f}{mark} (\pm{std:1.3f}{mark})"
new_df.loc[layer, mode] = val
# Final decoration on table
new_df.index.name = None
new_df = new_df.rename(columns=conf.column_names)
# Convert table to latex
table_latex = new_df.to_latex(escape=False, column_format='l c c')
# Place the latex table in a figure and add captopn
latex = "\\begin{table}\n\\centering\n" + table_latex + \
" \\caption{" + conf.caption + "}\n" + \
" \\label{fig:my_label}\n" + \
"\\end{table}"
# Save
with open(out_file, "w") as text_file:
print(latex, file=text_file)
def save_diagram(df, out_dir):
global settings
conf = settings.plot
out_file = os.path.join(out_dir,'crossentropy_vs_cka.pdf')
fig = plt.figure(figsize=(16,9));
subdf = df[df['style']=='cka']
cka_ax = sns.lineplot(
data=subdf, #kind="line",
x="front_layer", y="value",
hue="matrix", style='style',
palette=conf.colors,
linewidth=conf.linewidth);
ce_ax = plt.twinx()
subdf = df[df['style']!='cka']
ce_ax = sns.lineplot(
data=subdf, #kind="line",
x="front_layer", y="value",
hue="matrix", style='style',
palette=conf.colors,
linewidth=conf.linewidth, ax=ce_ax);
xlabels = df['front_layer'].drop_duplicates().str.replace('.add', '').tolist()
xlabels.sort()
def set_linestyle(ax, linesetyle):
# Remove columns from legend
h,l = ax.get_legend_handles_labels()
cols_to_remove = ['matrix', 'style', 'crossentropy', 'cka']
h = [x for (x,y) in zip(h,l) if y not in cols_to_remove]
l = [x for x in l if x not in cols_to_remove]
# Set linewidth in legend
for x in h:
x.set_linewidth(conf.linewidth)
# Set linestyles of CKA
h[0].set_linestyle(linesetyle)
h[1].set_linestyle(linesetyle)
ax.lines[0].set_linestyle(linesetyle)
ax.lines[1].set_linestyle(linesetyle)
return h, l
h1, l1 = set_linestyle(cka_ax, conf.cka_linestyle)
h2, l2 = set_linestyle(ce_ax, conf.ce_linestyle)
h, l = h1+h2, l1+l2
cka_ax.get_legend().remove()
ce_ax.get_legend().remove()
# Remove sns default legend and set custom
# g._legend.remove()
legends = plt.legend(h,l,loc='center', fontsize=20)
for i in range(4):
legend = legends.get_texts()[i]
title = legend.get_text()
new_title = conf.rename_dict[title]
legend.set_text(new_title)
cka_ax.set_ylabel(conf.y_label_left, size = 24)
cka_ax.set_xlabel(conf.x_label, size = 24)
cka_ax.set_xticklabels(xlabels, size=24, rotation=-45)
cka_ax.tick_params(axis='y', labelsize=24)
cka_ax.set_ylim([0.6 ,1])
cka_ax.xaxis.grid()
# Set grids
# plt.grid()
ce_ax.set_ylabel(conf.y_label_right, size = 24)
ce_ax.set_xlabel(conf.x_label, size = 24)
ce_ax.set_ylim([0,0.5])
ce_ax.xaxis.grid()
plt.tick_params(axis='x', labelsize=24, rotation=-45)
plt.tick_params(axis='y', labelsize=24, labelright=True)
# Save
plt.savefig(out_file, bbox_inches='tight')
#plt.show()
def save_report(filtered_df, out_dir):
data = DotMap()
data.no_experiments = len(filtered_df)
data.unique_networks = list(set(filtered_df.front_model).union(set(filtered_df.end_model)))
data.unique_networks = [x.split('/')[-2] for x in data.unique_networks]
data.same_networks_compared = str((filtered_df.front_model == filtered_df.end_model).any())
extra_cols = ['l1', 'target_type', 'weight_decay', 'init', 'temperature']
for col in extra_cols:
data[col] = filtered_df[col].drop_duplicates().tolist()
data.layers = filtered_df.front_layer.drop_duplicates().tolist()
data.layers.sort()
with open(os.path.join(out_dir, 'run_settings.json'), 'w') as fp:
json.dump(data, fp)
return data
def main(args=None):
if args is None:
args = sys.argv[1:]
conf = parse_args(args)
# Create directory if not exist
os.makedirs(conf.out_dir, exist_ok=True)
# Read in original csv
filtered_df, df = get_df(conf.csv, conf.out_dir)
# Run and save measurements
save_table_layerwise(df, conf.out_dir)
save_report(filtered_df, conf.out_dir)
save_table_mean_std(df, conf.out_dir)
save_diagram(df, conf.out_dir)
print(f'Results saved at {conf.out_dir}')
if __name__ == '__main__':
main() | import pandas as pd
from matplotlib import pyplot as plt
import os
import sys
import seaborn as sns
import json
import argparse
from dotmap import DotMap
import numpy as np
# ================================================================
# SETTINGS
# ================================================================
settings = DotMap()
# PLOT
# ----------------------------------------
settings.plot.colors = {
'frank_crossentropy' : '#F00',
'frank_cka' : '#F60',
'ps_inv_crossentropy' : '#00F',
'ps_inv_cka' : '#06F'
}
settings.plot.rename_dict = {
'frank_crossentropy' : 'With Task Loss - Cross-entropy',
'ps_inv_crossentropy' : 'Linear Least Squares - Cross-entropy',
'frank_cka' : 'With Task Loss - CKA',
'ps_inv_cka' : 'Linear Least Squares - CKA'
}
settings.plot.linewidth = 5
settings.plot.ce_linestyle = '-'
settings.plot.cka_linestyle = '--'
settings.plot.x_label = 'Layer'
settings.plot.y_label_left = 'CKA between stiched layers'
settings.plot.y_label_right = 'Cross-entropy'
# MEAN & STD TABLE
# ----------------------------------------
settings.mean_std_table.caption = 'Mean metrics with standard deviations in parentheses.'
settings.mean_std_table.column_names = ['Cross-entropy', 'CKA'] # Order cannot be changed this way
settings.mean_std_table.row_names = ['Ps. Inv', 'Frank'] # Order cannot be changed this way
# LAYERWISE TABLE
settings.layerwise_table.caption = 'Effect on logits, layerwise split on Frank stitches.'
settings.layerwise_table.column_names = {'crossentropy' : 'Cross-entropy', 'cka' : 'CKA'}
# ================================================================
# PROCESSING
# ================================================================
def parse_args(args):
parser = argparse.ArgumentParser(description='Simple settings.')
parser.add_argument('--csv', default="results/official/resnet20_w1_bn/summary.csv")
parser.add_argument('--out-dir', default='results/official/plots/resnet20_w1_bn_cka_vs_ce/')
return parser.parse_args(args)
def filter_df(df):
filters = [
df.l1 == 0.,
df.target_type=='soft_2',
df.init =='ps_inv',
(df.front_layer.str.contains('add'))|(df.front_layer=='bn1'),
(df.end_layer.str.contains('add'))|(df.end_layer=='bn1'),
df.front_model != df.end_model,
df.temperature == 1.0,
]
return df[np.logical_and.reduce(filters)]
def get_df(csv, out_dir):
# Filter csv to relevant parts
filtered_df = filter_df(pd.read_csv(csv))
filtered_df['front_layer'] = filtered_df['front_layer'].str.capitalize()
filtered_df = filtered_df.sort_values(['front_layer']).copy()
# Calculate accuracies
df = filtered_df.copy()
df['frank_cka'] = df['cka_frank']
df['ps_inv_cka'] = df['cka_ps_inv']
df['frank_crossentropy'] = df['after_crossentropy']
df['ps_inv_crossentropy'] = df['ps_inv_crossentropy']
# Rename columns in local dataframe
# df = df.rename(columns={
# 'after_cka' : 'frank_cka'
# })
# Group values into one column with a category column
def make_one_col(column):
new_df = df[['front_layer', column]].copy()
new_df['matrix'] = column
new_df['style'] = 'crossentropy' if 'crossentropy' in column else 'cka'
new_df = new_df.rename(columns={column : 'value'})
return new_df
dfs = [
make_one_col('frank_crossentropy'),
make_one_col('frank_cka'),
make_one_col('ps_inv_crossentropy'),
make_one_col('ps_inv_cka'),
]
sum_df = pd.concat(dfs, ignore_index=True).reset_index(drop=True)
# Save
filtered_df.to_csv(os.path.join(out_dir, 'filtered_df.csv'), index=False)
sum_df.to_csv(os.path.join(out_dir, 'sum_df.csv'), index=False)
return filtered_df, sum_df
def save_table_mean_std(df, out_dir):
global settings
conf = settings.mean_std_table
out_file = os.path.join(out_dir, 'overall_mean_std.tex')
# Generatre mean and std
df = df.copy()
df = df.groupby(['matrix'])['value'].describe()[['mean', 'std']].copy()
# Create table in desired format
_mean = lambda x: f"{df.loc[x, 'mean']:0.3f}"
_std = lambda x: f"(\pm{df.loc[x, 'std']:0.3f})"
_cell = lambda x: f"{_mean(x)} {_std(x)}"
_row = lambda x: [_cell(x+'_crossentropy'), _cell(x+'_cka')]
new_df = pd.DataFrame({
conf.row_names[0] : _row('ps_inv'),
conf.row_names[1] : _row('frank')
}, index=conf.column_names)
# Convert table to latex
table_latex = new_df.to_latex(escape=False, column_format='l c c')
# Place the latex table in a figure and add captopn
latex = "\\begin{table}\n\\centering\n" + table_latex + \
" \\caption{" + conf.caption + "}\n" + \
" \\label{fig:my_label}\n" + \
"\\end{table}"
# Save
with open(out_file, "w") as text_file:
print(latex, file=text_file)
def save_table_layerwise(df, out_dir):
global settings
conf = settings.layerwise_table
out_file = os.path.join(out_dir, 'layerwise_mean_std.tex')
df = df.copy()
# Create CKA/Acc and PsInv/Frank categories
df['mode'] = df.matrix.apply(lambda x: x.split('_')[-1])
df['method'] = df.matrix.apply(lambda x: '_'.join(x.split('_')[:-1]))
# Available layers in order
layers = df['front_layer'].drop_duplicates().sort_values()
# Create dataframe
new_df = pd.DataFrame(index=layers)
for layer in layers:
for mode in df['mode'].drop_duplicates():
# Filter ps_inv and frank
subdf = df[(df.front_layer==layer)&(df['mode']==mode)]
ps_inv = subdf[subdf.method == 'ps_inv']['value'].reset_index(drop=True)
frank = subdf[subdf.method == 'frank']['value'].reset_index(drop=True)
# Get mode spcific changes (e.g. % mark)
mark = '\%' if mode=='cka' else ''
multiplier = 100 if mode=='cka' else 1
# Caulculate mean and std
mean = (frank-ps_inv).mean() * multiplier
std = (frank-ps_inv).std() * multiplier
# Insert variable in table
val = f"{mean:1.3f}{mark} (\pm{std:1.3f}{mark})"
new_df.loc[layer, mode] = val
# Final decoration on table
new_df.index.name = None
new_df = new_df.rename(columns=conf.column_names)
# Convert table to latex
table_latex = new_df.to_latex(escape=False, column_format='l c c')
# Place the latex table in a figure and add captopn
latex = "\\begin{table}\n\\centering\n" + table_latex + \
" \\caption{" + conf.caption + "}\n" + \
" \\label{fig:my_label}\n" + \
"\\end{table}"
# Save
with open(out_file, "w") as text_file:
print(latex, file=text_file)
def save_diagram(df, out_dir):
global settings
conf = settings.plot
out_file = os.path.join(out_dir,'crossentropy_vs_cka.pdf')
fig = plt.figure(figsize=(16,9));
subdf = df[df['style']=='cka']
cka_ax = sns.lineplot(
data=subdf, #kind="line",
x="front_layer", y="value",
hue="matrix", style='style',
palette=conf.colors,
linewidth=conf.linewidth);
ce_ax = plt.twinx()
subdf = df[df['style']!='cka']
ce_ax = sns.lineplot(
data=subdf, #kind="line",
x="front_layer", y="value",
hue="matrix", style='style',
palette=conf.colors,
linewidth=conf.linewidth, ax=ce_ax);
xlabels = df['front_layer'].drop_duplicates().str.replace('.add', '').tolist()
xlabels.sort()
def set_linestyle(ax, linesetyle):
# Remove columns from legend
h,l = ax.get_legend_handles_labels()
cols_to_remove = ['matrix', 'style', 'crossentropy', 'cka']
h = [x for (x,y) in zip(h,l) if y not in cols_to_remove]
l = [x for x in l if x not in cols_to_remove]
# Set linewidth in legend
for x in h:
x.set_linewidth(conf.linewidth)
# Set linestyles of CKA
h[0].set_linestyle(linesetyle)
h[1].set_linestyle(linesetyle)
ax.lines[0].set_linestyle(linesetyle)
ax.lines[1].set_linestyle(linesetyle)
return h, l
h1, l1 = set_linestyle(cka_ax, conf.cka_linestyle)
h2, l2 = set_linestyle(ce_ax, conf.ce_linestyle)
h, l = h1+h2, l1+l2
cka_ax.get_legend().remove()
ce_ax.get_legend().remove()
# Remove sns default legend and set custom
# g._legend.remove()
legends = plt.legend(h,l,loc='center', fontsize=20)
for i in range(4):
legend = legends.get_texts()[i]
title = legend.get_text()
new_title = conf.rename_dict[title]
legend.set_text(new_title)
cka_ax.set_ylabel(conf.y_label_left, size = 24)
cka_ax.set_xlabel(conf.x_label, size = 24)
cka_ax.set_xticklabels(xlabels, size=24, rotation=-45)
cka_ax.tick_params(axis='y', labelsize=24)
cka_ax.set_ylim([0.6 ,1])
cka_ax.xaxis.grid()
# Set grids
# plt.grid()
ce_ax.set_ylabel(conf.y_label_right, size = 24)
ce_ax.set_xlabel(conf.x_label, size = 24)
ce_ax.set_ylim([0,0.5])
ce_ax.xaxis.grid()
plt.tick_params(axis='x', labelsize=24, rotation=-45)
plt.tick_params(axis='y', labelsize=24, labelright=True)
# Save
plt.savefig(out_file, bbox_inches='tight')
#plt.show()
def save_report(filtered_df, out_dir):
data = DotMap()
data.no_experiments = len(filtered_df)
data.unique_networks = list(set(filtered_df.front_model).union(set(filtered_df.end_model)))
data.unique_networks = [x.split('/')[-2] for x in data.unique_networks]
data.same_networks_compared = str((filtered_df.front_model == filtered_df.end_model).any())
extra_cols = ['l1', 'target_type', 'weight_decay', 'init', 'temperature']
for col in extra_cols:
data[col] = filtered_df[col].drop_duplicates().tolist()
data.layers = filtered_df.front_layer.drop_duplicates().tolist()
data.layers.sort()
with open(os.path.join(out_dir, 'run_settings.json'), 'w') as fp:
json.dump(data, fp)
return data
def main(args=None):
if args is None:
args = sys.argv[1:]
conf = parse_args(args)
# Create directory if not exist
os.makedirs(conf.out_dir, exist_ok=True)
# Read in original csv
filtered_df, df = get_df(conf.csv, conf.out_dir)
# Run and save measurements
save_table_layerwise(df, conf.out_dir)
save_report(filtered_df, conf.out_dir)
save_table_mean_std(df, conf.out_dir)
save_diagram(df, conf.out_dir)
print(f'Results saved at {conf.out_dir}')
if __name__ == '__main__':
main() |
import os
import dotenv
import logging
import time
import textwrap
import argparse
import stat
import glob
import pathlib
import datetime
import shutil
import subprocess
from irods.session import iRODSSession
from irods.meta import iRODSMeta
RESOURCE_ID_GLOB = "????????????????????????????????"
EXCLUDED = ["bags", "temp", "zips"]
IS_PUBLIC_KEY = "isPublic"
IS_PUBLIC_VALUE = "true"
NETCDF_EXTENSIONS = [".nc", ".nc4"]
FILE_MODE = stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH
logger = logging.getLogger(__name__)
class NetCDFPublicationError(Exception):
"""
An Exception class for NetCDF publication.
"""
pass
def rchmod(path, mode):
"""
Recursively change filesystem permissions of path and all of its children.'
rchmod(path, mode) -> None
Where:
path: <str> Absolute path to change filesystems permissions
mode: <int> numeric mode for all changes consistent with constants in the stats library
"""
os.chmod(path, mode)
for root, dirs, files in os.walk(path):
for d in dirs:
os.chmod(os.path.join(root, d), mode)
for f in files:
os.chmod(os.path.join(root, f), mode)
return None
def replace_spaces_in_names(path):
"""
Recursively replace spaces in names of all of the children underneath a path.'
replace_spaces_in_names(path) -> None
Where:
path: <str> Absolute path to traverse with name fixes
This is a fix for a bug in TDS 5 which was already fixed in TDS 4 but has regressed.
When a fix is available in TDS 5 and then deployed, this function may be deprecated.
Spaces are replaced with dunders as cases have been encountered where replacing
with a single underscore resulted in a name collision.
"""
replaced = 0
walk = list(os.walk(path))
walk.reverse()
for root, dirs, files in walk:
for f in files:
if " " in f:
replacement = os.path.join(root, f.replace(" ", "__"))
if pathlib.Path(replacement).exists():
os.remove(replacement)
os.rename(os.path.join(root, f), replacement)
replaced += 1
for d in dirs:
if " " in d:
replacement = os.path.join(root, d.replace(" ", "__"))
if pathlib.Path(replacement).exists():
shutil.rmtree(replacement)
os.rename(os.path.join(root, d), replacement)
replaced += 1
if replaced:
logger.warning(f"Replaced {replaced} name{"s" if replaced != 1 else ""} " \
f"of {"a " if replaced == 1 else ""}child{"ren" if replaced != 1 else ""} " \
f"in destination path {path}")
return None
def get_latest_resource_timestamp(irods_env, collection_path):
"""
Return the latest modifcation time among the collection's data objects.
get_latest_resource_timestamp(collection_path) -> <datetime.datetime>
Where:
irods_env: <str> Absolute path to the iRODS environment file
collection_path: <str> Absolute iRODS path to the collection
Returns: <datetime.datetime> The latest modification time
This function should become deprecated with iRODS 4.2.9 which updates collection modification times
whenever a contained data object is modified.
"""
with iRODSSession(irods_env_file=irods_env) as session:
collection = session.collections.get(collection_path)
tree = [leaf for leaf in collection.walk()]
data_objects = []
for leaf in tree:
data_objects.extend(leaf[2])
timestamps = [data_object.modify_time for data_object in data_objects]
timestamp = max(timestamps)
return timestamp
def publish_resource(irods_env, proxy_path, catalog_path, resource_id):
"""
Copy the resource with its timestamp.
publish_resource(proxy_path, catalog_path, resource_id) -> None
Where:
irods_env: <str> Absolute path to the iRODS environment file
proxy_path: <str> Absolute iRODS proxy path to Hydroshare resources
catalog_path: <str> Absolute THREDDS catalog path to publish resources
resource_id: <str> Resource ID to publish
Raises:
NetCDFPublicationError
"""
logger.info(f"Publishing resource ID: {resource_id} from {proxy_path} to {catalog_path}")
source = os.path.join(proxy_path, resource_id)
destination = os.path.join(catalog_path, resource_id)
timestamp = get_latest_resource_timestamp(irods_env, source)
# The iget destination is the catalog path in light of https://github.com/irods/irods/issues/5527
proc = subprocess.Popen(["env", f"IRODS_ENVIRONMENT_FILE={irods_env}", "iget", "-rf", source, catalog_path],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
if proc.returncode:
logger.error(f"Publishing resource ID: {resource_id} from {proxy_path} to {catalog_path} failed:" \
f"return code: {proc.returncode} ::: " \
f'stdout: {stdout} ::: ' \
f"stderr: {stderr}")
raise NetCDFPublicationError(f"iget {source} to {destination} failed",
proc.returncode,
stdout,
stderr)
rchmod(destination, FILE_MODE)
# Fix for TDS 5. Hope to see a fix for this in TDS 5 itself.
replace_spaces_in_names(destination)
os.utime(destination, (timestamp.timestamp(), timestamp.timestamp()))
logger.info(f"Published resource ID: {resource_id} from {proxy_path} to {catalog_path} with timestamp: {timestamp}")
return None
def scan_source(irods_env, proxy_path):
"""
Scan the iRODS proxy path for all public Hydroshare resources containing NetCDF and their timestamps.
scan_source(irods_env, proxy_path) -> [(resource_id, timestamp), ...]
Where:
irods_env: <str> Absolute path to the iRODS environment file
proxy_path: <str> Absolute iRODS proxy path to Hydroshare resources
Returns: <list> of two-<tuple>s where:
a) first element is a <str> resource id, and
b) second element is a <datetime.datetime> modification time.
"""
with iRODSSession(irods_env_file=irods_env) as session:
subcollections = session.collections.get(proxy_path).subcollections
subcollections = [subcollection for subcollection in subcollections if subcollection.name not in EXCLUDED]
logger.info(f"Number of included subcollections: {len(subcollections)}")
public = [subcollection for subcollection in subcollections
if "isPublic" in subcollection.metadata.keys()
and subcollection.metadata[IS_PUBLIC_KEY].value.lower() == IS_PUBLIC_VALUE]
logger.info(f"Number of public included subcollections: {len(public)}")
public_netcdf = []
for subcollection in public:
public_objects = [objs for col, subcol, objs in list(subcollection.walk())]
# flatten the list of lists of data objects
data_objects = []
for objs in public_objects:
data_objects.extend(objs)
netcdf_objects = [obj for obj in data_objects if pathlib.Path(obj.name).suffix.lower() in NETCDF_EXTENSIONS]
if netcdf_objects:
public_netcdf.append(subcollection.name)
logger.info(f"Subcollection name: {subcollection.name}; Number of NetCDF data objects in subcollection: {len(netcdf_objects)}")
logger.info(f"Number of public subcollections containing NetCDF: {len(public_netcdf)}")
source_netcdf = [(resource_id, get_latest_resource_timestamp(irods_env, os.path.join(proxy_path, resource_id)))
for resource_id in public_netcdf]
return source_netcdf
def scan_destination(catalog_path):
"""
Scan the THREDDS catalog path for all resources and their timestamps.
scan_destination(catalog_path) -> [(resource_id, timestamp), ...]
Where:
catalog_path: <str> Absolute THREDDS catalog path to publish resources
Returns: <list> of two-<tuple>s where:
a) first element is a <str> resource id, and
b) second element is a <datetime.datetime> modification time.
"""
resources = glob.glob(os.path.join(catalog_path, RESOURCE_ID_GLOB))
logger.info(f"Number of destination resources: {len(resources)}")
destination_netcdf = [(pathlib.PurePath(resource).name, datetime.datetime.fromtimestamp(os.path.getmtime(resource)))
for resource in resources]
return destination_netcdf
def remove_resource(catalog_path, resource_id):
"""
Remove a resource from the published destination.
remove_resource(catalog_path, resource_id) -> None
Where:
catalog_path: <str> Absolute THREDDS catalog path to publish resources
resource_id: <str> The resource ID to remove from publication
"""
shutil.rmtree(os.path.join(catalog_path, resource_id))
logger.info(f"Removed resource ID: {resource_id}")
return None
def sync_resources(irods_env, proxy_path, catalog_path):
"""
Sync public netcdf resources between iRODS proxy and THREDDS catalog.
sync_resource(irods_env, proxy_path, catalog_path) -> None
Where:
irods_env: <str> Absolute path to the iRODS environment file
proxy_path: <str> Absolute iRODS proxy path to Hydroshare resources
catalog_path: <str> Absolute THREDDS catalog path to publish resources
a) Scan all resources in the source path and publish the public resources containing NetCDF which:
i) do not exist in the destination path, or
ii) are out of date in the destination path, and
b) Scan all resources in the destination path and remove the resources which:
i) no longer exist in the source path, or
ii) are no longer public in the source path.
"""
logger.info(f"Syncing resources from {proxy_path} to {catalog_path}")
start_time = time.perf_counter()
source_netcdf = scan_source(irods_env, proxy_path)
destination_netcdf = scan_destination(catalog_path)
destination_ids = [destination[0] for destination in destination_netcdf]
destination_timestamps = [destination[1] for destination in destination_netcdf]
for source_id, source_timestamp in source_netcdf:
try:
if source_id not in destination_ids:
logger.info(f"Resource ID: {source_id} not in destination")
publish_resource(irods_env, proxy_path, catalog_path, source_id)
else:
index = destination_ids.index(source_id)
destination_timestamp = destination_timestamps[index]
if source_timestamp > destination_timestamp:
logger.info(f"Resource ID: {source_id} source timestamp: {source_timestamp} > destination timestamp: {destination_timestamp}")
publish_resource(irods_env, proxy_path, catalog_path, source_id)
except NetCDFPublicationError as e:
logger.warning(f"Syncing resources from {proxy_path} to {catalog_path} incomplete")
destination_netcdf = scan_destination(catalog_path)
source_ids = [source[0] for source in source_netcdf]
for destination_id, destination_timestamp in destination_netcdf:
if destination_id not in source_ids:
logger.info(f"Resource ID: {destination_id} no longer in source")
remove_resource(catalog_path, destination_id)
end_time = time.perf_counter()
run_time = end_time - start_time
logger.info(f"Resources synced from {proxy_path} to {catalog_path} in {run_time:0.4f} seconds")
return None
if __name__ == "__main__":
epilog = """\
If invoked with a resource ID argument, publish the resource to the destination path, assumed to be referenced in a THREDDS catalog.
Otherwise,
a) scan all resources in the source path and publish the public resources containing NetCDF which:
i) do not exist in the destination path, or
ii) are out of date in the destination path, and
b) scan all resources in the destination path and remove the resources which:
i) no longer exist in the source path, or
ii) are no longer public in the source path."""
parser = argparse.ArgumentParser(description="Publish public Hydroshare resources containing NetCDF.",
epilog=textwrap.dedent(epilog),
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("dotenv_path",
help="Absolute path to the .env file.")
parser.add_argument("resource_id",
nargs="?",
default="",
help=textwrap.dedent("""\
Optional resource ID to publish.
If not specified, publish all public Hydroshare resources containing NetCDF."""))
args = parser.parse_args()
dotenv.load_dotenv(dotenv.find_dotenv(args.dotenv_path))
log_file = os.environ["PUBLIC_NETCDF_LOG_FILE"]
irods_env = os.environ["PUBLIC_NETCDF_IRODS_ENVIRONMENT_FILE"]
proxy_path = os.environ["PUBLIC_NETCDF_IRODS_PROXY_PATH"]
catalog_path = os.environ['PUBLIC_NETCDF_THREDDS_CATALOG_PATH']
logging.basicConfig(filename=log_file,
# Available in Python 3.9+
# encoding="utf-8",
level=logging.INFO,
format="[%(asctime)s] [%(levelname)s] %(message)s",
datefmt="%m/%d/%Y %I:%M:%S %p")
logger = logging.getLogger(__name__)
if args.resource_id:
try:
publish_resource(irods_env,
proxy_path,
catalog_path,
args.resource_id)
except NetCDFPublicationError as e:
logger.warning(f"Publishing resource {args.resource_id} from {args.src_path} to {args.dest_path} incomplete")
else:
sync_resources(irods_env,
proxy_path,
catalog_path)
| import os
import dotenv
import logging
import time
import textwrap
import argparse
import stat
import glob
import pathlib
import datetime
import shutil
import subprocess
from irods.session import iRODSSession
from irods.meta import iRODSMeta
RESOURCE_ID_GLOB = "????????????????????????????????"
EXCLUDED = ["bags", "temp", "zips"]
IS_PUBLIC_KEY = "isPublic"
IS_PUBLIC_VALUE = "true"
NETCDF_EXTENSIONS = [".nc", ".nc4"]
FILE_MODE = stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH
logger = logging.getLogger(__name__)
class NetCDFPublicationError(Exception):
"""
An Exception class for NetCDF publication.
"""
pass
def rchmod(path, mode):
"""
Recursively change filesystem permissions of path and all of its children.'
rchmod(path, mode) -> None
Where:
path: <str> Absolute path to change filesystems permissions
mode: <int> numeric mode for all changes consistent with constants in the stats library
"""
os.chmod(path, mode)
for root, dirs, files in os.walk(path):
for d in dirs:
os.chmod(os.path.join(root, d), mode)
for f in files:
os.chmod(os.path.join(root, f), mode)
return None
def replace_spaces_in_names(path):
"""
Recursively replace spaces in names of all of the children underneath a path.'
replace_spaces_in_names(path) -> None
Where:
path: <str> Absolute path to traverse with name fixes
This is a fix for a bug in TDS 5 which was already fixed in TDS 4 but has regressed.
When a fix is available in TDS 5 and then deployed, this function may be deprecated.
Spaces are replaced with dunders as cases have been encountered where replacing
with a single underscore resulted in a name collision.
"""
replaced = 0
walk = list(os.walk(path))
walk.reverse()
for root, dirs, files in walk:
for f in files:
if " " in f:
replacement = os.path.join(root, f.replace(" ", "__"))
if pathlib.Path(replacement).exists():
os.remove(replacement)
os.rename(os.path.join(root, f), replacement)
replaced += 1
for d in dirs:
if " " in d:
replacement = os.path.join(root, d.replace(" ", "__"))
if pathlib.Path(replacement).exists():
shutil.rmtree(replacement)
os.rename(os.path.join(root, d), replacement)
replaced += 1
if replaced:
logger.warning(f"Replaced {replaced} name{'s' if replaced != 1 else ''} " \
f"of {'a ' if replaced == 1 else ''}child{'ren' if replaced != 1 else ''} " \
f"in destination path {path}")
return None
def get_latest_resource_timestamp(irods_env, collection_path):
"""
Return the latest modifcation time among the collection's data objects.
get_latest_resource_timestamp(collection_path) -> <datetime.datetime>
Where:
irods_env: <str> Absolute path to the iRODS environment file
collection_path: <str> Absolute iRODS path to the collection
Returns: <datetime.datetime> The latest modification time
This function should become deprecated with iRODS 4.2.9 which updates collection modification times
whenever a contained data object is modified.
"""
with iRODSSession(irods_env_file=irods_env) as session:
collection = session.collections.get(collection_path)
tree = [leaf for leaf in collection.walk()]
data_objects = []
for leaf in tree:
data_objects.extend(leaf[2])
timestamps = [data_object.modify_time for data_object in data_objects]
timestamp = max(timestamps)
return timestamp
def publish_resource(irods_env, proxy_path, catalog_path, resource_id):
"""
Copy the resource with its timestamp.
publish_resource(proxy_path, catalog_path, resource_id) -> None
Where:
irods_env: <str> Absolute path to the iRODS environment file
proxy_path: <str> Absolute iRODS proxy path to Hydroshare resources
catalog_path: <str> Absolute THREDDS catalog path to publish resources
resource_id: <str> Resource ID to publish
Raises:
NetCDFPublicationError
"""
logger.info(f"Publishing resource ID: {resource_id} from {proxy_path} to {catalog_path}")
source = os.path.join(proxy_path, resource_id)
destination = os.path.join(catalog_path, resource_id)
timestamp = get_latest_resource_timestamp(irods_env, source)
# The iget destination is the catalog path in light of https://github.com/irods/irods/issues/5527
proc = subprocess.Popen(["env", f"IRODS_ENVIRONMENT_FILE={irods_env}", "iget", "-rf", source, catalog_path],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
if proc.returncode:
logger.error(f"Publishing resource ID: {resource_id} from {proxy_path} to {catalog_path} failed:" \
f"return code: {proc.returncode} ::: " \
f'stdout: {stdout} ::: ' \
f"stderr: {stderr}")
raise NetCDFPublicationError(f"iget {source} to {destination} failed",
proc.returncode,
stdout,
stderr)
rchmod(destination, FILE_MODE)
# Fix for TDS 5. Hope to see a fix for this in TDS 5 itself.
replace_spaces_in_names(destination)
os.utime(destination, (timestamp.timestamp(), timestamp.timestamp()))
logger.info(f"Published resource ID: {resource_id} from {proxy_path} to {catalog_path} with timestamp: {timestamp}")
return None
def scan_source(irods_env, proxy_path):
"""
Scan the iRODS proxy path for all public Hydroshare resources containing NetCDF and their timestamps.
scan_source(irods_env, proxy_path) -> [(resource_id, timestamp), ...]
Where:
irods_env: <str> Absolute path to the iRODS environment file
proxy_path: <str> Absolute iRODS proxy path to Hydroshare resources
Returns: <list> of two-<tuple>s where:
a) first element is a <str> resource id, and
b) second element is a <datetime.datetime> modification time.
"""
with iRODSSession(irods_env_file=irods_env) as session:
subcollections = session.collections.get(proxy_path).subcollections
subcollections = [subcollection for subcollection in subcollections if subcollection.name not in EXCLUDED]
logger.info(f"Number of included subcollections: {len(subcollections)}")
public = [subcollection for subcollection in subcollections
if "isPublic" in subcollection.metadata.keys()
and subcollection.metadata[IS_PUBLIC_KEY].value.lower() == IS_PUBLIC_VALUE]
logger.info(f"Number of public included subcollections: {len(public)}")
public_netcdf = []
for subcollection in public:
public_objects = [objs for col, subcol, objs in list(subcollection.walk())]
# flatten the list of lists of data objects
data_objects = []
for objs in public_objects:
data_objects.extend(objs)
netcdf_objects = [obj for obj in data_objects if pathlib.Path(obj.name).suffix.lower() in NETCDF_EXTENSIONS]
if netcdf_objects:
public_netcdf.append(subcollection.name)
logger.info(f"Subcollection name: {subcollection.name}; Number of NetCDF data objects in subcollection: {len(netcdf_objects)}")
logger.info(f"Number of public subcollections containing NetCDF: {len(public_netcdf)}")
source_netcdf = [(resource_id, get_latest_resource_timestamp(irods_env, os.path.join(proxy_path, resource_id)))
for resource_id in public_netcdf]
return source_netcdf
def scan_destination(catalog_path):
"""
Scan the THREDDS catalog path for all resources and their timestamps.
scan_destination(catalog_path) -> [(resource_id, timestamp), ...]
Where:
catalog_path: <str> Absolute THREDDS catalog path to publish resources
Returns: <list> of two-<tuple>s where:
a) first element is a <str> resource id, and
b) second element is a <datetime.datetime> modification time.
"""
resources = glob.glob(os.path.join(catalog_path, RESOURCE_ID_GLOB))
logger.info(f"Number of destination resources: {len(resources)}")
destination_netcdf = [(pathlib.PurePath(resource).name, datetime.datetime.fromtimestamp(os.path.getmtime(resource)))
for resource in resources]
return destination_netcdf
def remove_resource(catalog_path, resource_id):
"""
Remove a resource from the published destination.
remove_resource(catalog_path, resource_id) -> None
Where:
catalog_path: <str> Absolute THREDDS catalog path to publish resources
resource_id: <str> The resource ID to remove from publication
"""
shutil.rmtree(os.path.join(catalog_path, resource_id))
logger.info(f"Removed resource ID: {resource_id}")
return None
def sync_resources(irods_env, proxy_path, catalog_path):
"""
Sync public netcdf resources between iRODS proxy and THREDDS catalog.
sync_resource(irods_env, proxy_path, catalog_path) -> None
Where:
irods_env: <str> Absolute path to the iRODS environment file
proxy_path: <str> Absolute iRODS proxy path to Hydroshare resources
catalog_path: <str> Absolute THREDDS catalog path to publish resources
a) Scan all resources in the source path and publish the public resources containing NetCDF which:
i) do not exist in the destination path, or
ii) are out of date in the destination path, and
b) Scan all resources in the destination path and remove the resources which:
i) no longer exist in the source path, or
ii) are no longer public in the source path.
"""
logger.info(f"Syncing resources from {proxy_path} to {catalog_path}")
start_time = time.perf_counter()
source_netcdf = scan_source(irods_env, proxy_path)
destination_netcdf = scan_destination(catalog_path)
destination_ids = [destination[0] for destination in destination_netcdf]
destination_timestamps = [destination[1] for destination in destination_netcdf]
for source_id, source_timestamp in source_netcdf:
try:
if source_id not in destination_ids:
logger.info(f"Resource ID: {source_id} not in destination")
publish_resource(irods_env, proxy_path, catalog_path, source_id)
else:
index = destination_ids.index(source_id)
destination_timestamp = destination_timestamps[index]
if source_timestamp > destination_timestamp:
logger.info(f"Resource ID: {source_id} source timestamp: {source_timestamp} > destination timestamp: {destination_timestamp}")
publish_resource(irods_env, proxy_path, catalog_path, source_id)
except NetCDFPublicationError as e:
logger.warning(f"Syncing resources from {proxy_path} to {catalog_path} incomplete")
destination_netcdf = scan_destination(catalog_path)
source_ids = [source[0] for source in source_netcdf]
for destination_id, destination_timestamp in destination_netcdf:
if destination_id not in source_ids:
logger.info(f"Resource ID: {destination_id} no longer in source")
remove_resource(catalog_path, destination_id)
end_time = time.perf_counter()
run_time = end_time - start_time
logger.info(f"Resources synced from {proxy_path} to {catalog_path} in {run_time:0.4f} seconds")
return None
if __name__ == "__main__":
epilog = """\
If invoked with a resource ID argument, publish the resource to the destination path, assumed to be referenced in a THREDDS catalog.
Otherwise,
a) scan all resources in the source path and publish the public resources containing NetCDF which:
i) do not exist in the destination path, or
ii) are out of date in the destination path, and
b) scan all resources in the destination path and remove the resources which:
i) no longer exist in the source path, or
ii) are no longer public in the source path."""
parser = argparse.ArgumentParser(description="Publish public Hydroshare resources containing NetCDF.",
epilog=textwrap.dedent(epilog),
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("dotenv_path",
help="Absolute path to the .env file.")
parser.add_argument("resource_id",
nargs="?",
default="",
help=textwrap.dedent("""\
Optional resource ID to publish.
If not specified, publish all public Hydroshare resources containing NetCDF."""))
args = parser.parse_args()
dotenv.load_dotenv(dotenv.find_dotenv(args.dotenv_path))
log_file = os.environ["PUBLIC_NETCDF_LOG_FILE"]
irods_env = os.environ["PUBLIC_NETCDF_IRODS_ENVIRONMENT_FILE"]
proxy_path = os.environ["PUBLIC_NETCDF_IRODS_PROXY_PATH"]
catalog_path = os.environ['PUBLIC_NETCDF_THREDDS_CATALOG_PATH']
logging.basicConfig(filename=log_file,
# Available in Python 3.9+
# encoding="utf-8",
level=logging.INFO,
format="[%(asctime)s] [%(levelname)s] %(message)s",
datefmt="%m/%d/%Y %I:%M:%S %p")
logger = logging.getLogger(__name__)
if args.resource_id:
try:
publish_resource(irods_env,
proxy_path,
catalog_path,
args.resource_id)
except NetCDFPublicationError as e:
logger.warning(f"Publishing resource {args.resource_id} from {args.src_path} to {args.dest_path} incomplete")
else:
sync_resources(irods_env,
proxy_path,
catalog_path)
|
"""Generic step implementations for reports, subjects, metrics, and sources."""
import json
from asserts import assert_equal, assert_false, assert_true
from behave import given, when, then
@given("an existing {item}")
@given('an existing {item} with {attribute} "{value}"')
@given('an existing {item} with {attribute} "{value}" and parameter {parameter} "{parameter_value}"')
@when("the client creates a {item}")
@when('the client creates a {item} with {attribute} "{value}"')
@when("the client tries to create a {item}")
def add_item(context, item, attribute=None, value=None, parameter=None, parameter_value=None):
"""Add an item with and optionally set attribute to value."""
api = f"{item}/new"
container = dict(source="metric", metric="subject", subject="report").get(item)
if container:
api += f"/{context.uuid[container]}"
if "tries to" in context.step.name:
context.post(api)
return
context.uuid[item] = context.post(api)[f"new_{item}_uuid"]
if attribute and value:
context.execute_steps(f'when the client changes the {item} {attribute} to "{value}"')
if parameter and parameter_value:
context.execute_steps(f'when the client sets the source parameter {parameter} to "{parameter_value}"')
@when("the client copies the {item}")
def copy_item(context, item):
"""Copy the item."""
api = f"{item}/{context.uuid[item]}/copy"
container = dict(source="metric", metric="subject", subject="report").get(item)
if container:
api += f"/{context.uuid[container]}"
context.uuid[item] = context.post(api)[f"new_{item}_uuid"]
@when("the client moves the {item} to the {container}")
def move_item(context, item, container):
"""Move the item."""
context.post(f"{item}/{context.uuid[item]}/move/{context.uuid[container]}")
@when("the client deletes the {item}")
def delete_item(context, item):
"""Delete the item."""
if item == "notification_destination":
context.delete(f"report/{context.uuid["report"]}/{item}/{context.uuid[item]}")
else:
context.delete(f"{item}/{context.uuid[item]}")
@when('the client changes the {item} {attribute} to "{value}"')
def change_item_attribute(context, item, attribute, value):
"""Change the item attribute to value."""
item_fragment = "reports_overview" if item == "reports_overview" else f"{item}/{context.uuid[item]}"
if attribute in ("tags",): # convert comma separated values to lists
value = value.split(", ")
elif attribute in ("permissions",): # convert comma separated values to lists
if value == "None":
value = "{}"
value = json.loads(value)
else:
value = dict(true=True, false=False, none=None).get(value.lower(), value)
if item == "notification_destination":
context.post(f"report/{context.uuid["report"]}/{item_fragment}/attributes", {attribute: value})
else:
context.post(f"{item_fragment}/attribute/{attribute}", json={attribute: value})
def get_item(context, item):
"""Return the item instance of type item."""
item_instance = (
context.get("reports_overview")
if item == "reports_overview"
else context.get(f"report/{context.uuid["report"]}")
)
if item != "reports_overview":
item_instance = [
report for report in item_instance["reports"] if report["report_uuid"] == context.uuid["report"]
][0]
if item == "notification_destination":
return item_instance["notification_destinations"][context.uuid["notification_destination"]]
if item != "report":
item_instance = item_instance["subjects"][context.uuid["subject"]]
if item != "subject":
item_instance = item_instance["metrics"][context.uuid["metric"]]
if item != "metric":
item_instance = item_instance["sources"][context.uuid["source"]]
return item_instance
@then('the {item} {attribute} is "{value}"')
def check_item_attribute(context, item, attribute, value):
"""Check that the item attribute equals value."""
if item == "reports_overview" and attribute == "permissions": # parse json data
value = {} if value == "None" else json.loads(value)
else:
value = None if value == "None" else value
assert_equal(value, get_item(context, item)[attribute])
@then("the {item} does not exist")
def check_item_does_not_exist(context, item):
"""Check that the item does not exist."""
uuids = []
reports = context.get(f"report/{context.uuid[item]}") if item == "report" else context.get("report/")
for report in reports["reports"]:
uuids.append(report["report_uuid"])
uuids.extend(report["subjects"].keys())
for subject in report["subjects"].values():
uuids.extend(subject["metrics"].keys())
for metric in subject["metrics"].values():
uuids.extend(metric["sources"].keys())
assert_false(context.uuid[item] in uuids)
def get_container(context, container):
"""Return the container."""
reports = context.get("report/")
container_instance = [report for report in reports["reports"] if report["report_uuid"] == context.uuid["report"]][0]
if container != "report":
container_instance = container_instance["subjects"][context.uuid["subject"]]
if container != "subject":
container_instance = container_instance["metrics"][context.uuid["metric"]]
return container_instance
@then("the {container} contains the {item}")
def check_container_contains_item(context, container, item):
"""Check that the container contains the item."""
assert_true(context.uuid[item] in get_container(context, container)[f"{item}s"])
@then('''the {container}'s {position} {item} has {attribute} "{value}"''')
def check_item_order(context, container, position, item, attribute, value):
"""Check that the container item at position has an attribute with the specified value."""
index = dict(first=0, last=-1)[position]
assert_equal(value, list(get_container(context, container)[f"{item}s"].values())[index][attribute])
@then("the {container} contains {number} {children}")
def check_nr_children(context, container, number, children):
"""Check that the container has the expected number of child items."""
container_instance = get_container(context, container)
children = children if children.endswith("s") else children + "s"
assert_equal(number, str(len(container_instance[children])))
| """Generic step implementations for reports, subjects, metrics, and sources."""
import json
from asserts import assert_equal, assert_false, assert_true
from behave import given, when, then
@given("an existing {item}")
@given('an existing {item} with {attribute} "{value}"')
@given('an existing {item} with {attribute} "{value}" and parameter {parameter} "{parameter_value}"')
@when("the client creates a {item}")
@when('the client creates a {item} with {attribute} "{value}"')
@when("the client tries to create a {item}")
def add_item(context, item, attribute=None, value=None, parameter=None, parameter_value=None):
"""Add an item with and optionally set attribute to value."""
api = f"{item}/new"
container = dict(source="metric", metric="subject", subject="report").get(item)
if container:
api += f"/{context.uuid[container]}"
if "tries to" in context.step.name:
context.post(api)
return
context.uuid[item] = context.post(api)[f"new_{item}_uuid"]
if attribute and value:
context.execute_steps(f'when the client changes the {item} {attribute} to "{value}"')
if parameter and parameter_value:
context.execute_steps(f'when the client sets the source parameter {parameter} to "{parameter_value}"')
@when("the client copies the {item}")
def copy_item(context, item):
"""Copy the item."""
api = f"{item}/{context.uuid[item]}/copy"
container = dict(source="metric", metric="subject", subject="report").get(item)
if container:
api += f"/{context.uuid[container]}"
context.uuid[item] = context.post(api)[f"new_{item}_uuid"]
@when("the client moves the {item} to the {container}")
def move_item(context, item, container):
"""Move the item."""
context.post(f"{item}/{context.uuid[item]}/move/{context.uuid[container]}")
@when("the client deletes the {item}")
def delete_item(context, item):
"""Delete the item."""
if item == "notification_destination":
context.delete(f"report/{context.uuid['report']}/{item}/{context.uuid[item]}")
else:
context.delete(f"{item}/{context.uuid[item]}")
@when('the client changes the {item} {attribute} to "{value}"')
def change_item_attribute(context, item, attribute, value):
"""Change the item attribute to value."""
item_fragment = "reports_overview" if item == "reports_overview" else f"{item}/{context.uuid[item]}"
if attribute in ("tags",): # convert comma separated values to lists
value = value.split(", ")
elif attribute in ("permissions",): # convert comma separated values to lists
if value == "None":
value = "{}"
value = json.loads(value)
else:
value = dict(true=True, false=False, none=None).get(value.lower(), value)
if item == "notification_destination":
context.post(f"report/{context.uuid['report']}/{item_fragment}/attributes", {attribute: value})
else:
context.post(f"{item_fragment}/attribute/{attribute}", json={attribute: value})
def get_item(context, item):
"""Return the item instance of type item."""
item_instance = (
context.get("reports_overview")
if item == "reports_overview"
else context.get(f"report/{context.uuid['report']}")
)
if item != "reports_overview":
item_instance = [
report for report in item_instance["reports"] if report["report_uuid"] == context.uuid["report"]
][0]
if item == "notification_destination":
return item_instance["notification_destinations"][context.uuid["notification_destination"]]
if item != "report":
item_instance = item_instance["subjects"][context.uuid["subject"]]
if item != "subject":
item_instance = item_instance["metrics"][context.uuid["metric"]]
if item != "metric":
item_instance = item_instance["sources"][context.uuid["source"]]
return item_instance
@then('the {item} {attribute} is "{value}"')
def check_item_attribute(context, item, attribute, value):
"""Check that the item attribute equals value."""
if item == "reports_overview" and attribute == "permissions": # parse json data
value = {} if value == "None" else json.loads(value)
else:
value = None if value == "None" else value
assert_equal(value, get_item(context, item)[attribute])
@then("the {item} does not exist")
def check_item_does_not_exist(context, item):
"""Check that the item does not exist."""
uuids = []
reports = context.get(f"report/{context.uuid[item]}") if item == "report" else context.get("report/")
for report in reports["reports"]:
uuids.append(report["report_uuid"])
uuids.extend(report["subjects"].keys())
for subject in report["subjects"].values():
uuids.extend(subject["metrics"].keys())
for metric in subject["metrics"].values():
uuids.extend(metric["sources"].keys())
assert_false(context.uuid[item] in uuids)
def get_container(context, container):
"""Return the container."""
reports = context.get("report/")
container_instance = [report for report in reports["reports"] if report["report_uuid"] == context.uuid["report"]][0]
if container != "report":
container_instance = container_instance["subjects"][context.uuid["subject"]]
if container != "subject":
container_instance = container_instance["metrics"][context.uuid["metric"]]
return container_instance
@then("the {container} contains the {item}")
def check_container_contains_item(context, container, item):
"""Check that the container contains the item."""
assert_true(context.uuid[item] in get_container(context, container)[f"{item}s"])
@then('''the {container}'s {position} {item} has {attribute} "{value}"''')
def check_item_order(context, container, position, item, attribute, value):
"""Check that the container item at position has an attribute with the specified value."""
index = dict(first=0, last=-1)[position]
assert_equal(value, list(get_container(context, container)[f"{item}s"].values())[index][attribute])
@then("the {container} contains {number} {children}")
def check_nr_children(context, container, number, children):
"""Check that the container has the expected number of child items."""
container_instance = get_container(context, container)
children = children if children.endswith("s") else children + "s"
assert_equal(number, str(len(container_instance[children])))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.